A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
feat(api): read pass, dispute, refund, email and branding config
Hampus6e2ce8ba4242
diff --git a/fluxer_api/src/api/Config.test.ts b/fluxer_api/src/api/Config.test.tsindex d7b768f79..ba6bfd77e 100644--- a/fluxer_api/src/api/Config.test.ts+++ b/fluxer_api/src/api/Config.test.ts@@ -1,33 +1,11 @@// SPDX-License-Identifier: AGPL-3.0-or-later-import {buildAPIConfigFromMaster, buildAPIServerOptions} from '@app/api/Config';+import {buildAPIConfigFromMaster} from '@app/api/Config';import {loadConfig, resetConfig} from '@fluxer/config/src/ConfigLoader';import type {MasterConfig} from '@fluxer/config/src/MasterConfig';-import {createServer} from '@fluxer/hono/src/Server';-import {Hono} from 'hono';import {afterAll, afterEach, beforeAll, describe, expect, it, test, vi} from 'vitest';-interface ListeningServer {- close: (callback: () => void) => void;- headersTimeout: number;- requestTimeout: number;-}--const servers: Array<ListeningServer> = [];--async function listenWithEnv(env: Record<string, string> = {}): Promise<ListeningServer> {- for (const [key, value] of Object.entries({FLUXER_API_PORT: '0', ...env})) {- vi.stubEnv(key, value);- }- resetConfig();- const config = buildAPIConfigFromMaster(await loadConfig());- const server = createServer(new Hono(), buildAPIServerOptions(config)) as unknown as ListeningServer;- servers.push(server);- return server;-}--afterEach(async () => {- await Promise.all(servers.splice(0).map((server) => new Promise<void>((resolve) => server.close(() => resolve()))));+afterEach(() => {vi.unstubAllEnvs();resetConfig();});@@ -36,17 +14,6 @@ afterAll(async () => {await loadConfig();});-describe('buildAPIServerOptions', () => {- test('clamps a header timeout set above the request timeout', async () => {- const server = await listenWithEnv({- FLUXER_API_HEADERS_TIMEOUT_MS: '90000',- FLUXER_API_REQUEST_TIMEOUT_MS: '45000',- });- expect(server.requestTimeout).toBe(45_000);- expect(server.headersTimeout).toBe(45_000);- });-});-function withUploadRelaySecret(master: MasterConfig, secretBase64: string): MasterConfig {return {...master,@@ -143,20 +110,16 @@ describe('buildAPIConfigFromMaster stripe legacy prices', () => {});});-function withOptionalOutboundLookups(- master: MasterConfig,- selfHosted: boolean,- overrides: {breachedPasswordCheck?: boolean} = {},-): MasterConfig {+function withSelfHostedInstance(master: MasterConfig): MasterConfig {return {...master,integrations: {...master.integrations,- breached_password_check: {enabled: overrides.breachedPasswordCheck},+ breached_password_check: {enabled: undefined},},instance: {...master.instance,- self_hosted: selfHosted,+ self_hosted: true,},};}@@ -167,23 +130,8 @@ describe('buildAPIConfigFromMaster optional outbound lookups', () => {master = await loadConfig();});- it('keeps the lookup on when the instance is not self-hosted', () => {- const config = buildAPIConfigFromMaster(withOptionalOutboundLookups(master, false));- expect(config.breachedPasswordCheck.enabled).toBe(true);- });-it('leaves the lookup off on a self-hosted instance', () => {- const config = buildAPIConfigFromMaster(withOptionalOutboundLookups(master, true));- expect(config.breachedPasswordCheck.enabled).toBe(false);- });-- it('lets a self-hosted operator switch the lookup on', () => {- const config = buildAPIConfigFromMaster(withOptionalOutboundLookups(master, true, {breachedPasswordCheck: true}));- expect(config.breachedPasswordCheck.enabled).toBe(true);- });-- it('lets an operator switch the lookup off when the instance is not self-hosted', () => {- const config = buildAPIConfigFromMaster(withOptionalOutboundLookups(master, false, {breachedPasswordCheck: false}));+ const config = buildAPIConfigFromMaster(withSelfHostedInstance(master));expect(config.breachedPasswordCheck.enabled).toBe(false);});});@@ -209,13 +157,22 @@ describe('buildAPIConfigFromMaster trusted callers', () => {expect(callers).toEqual([{name: 'bugs', key: bugsKey, buckets: ['oauth:token', 'oauth:revoke']}]);});- test('turns FLUXER_API_DONATION_PROXY_KEY into a caller scoped to the donation buckets', async () => {+ test('turns FLUXER_API_DONATION_PROXY_KEY into a caller scoped to the donation and Operator Pass buckets', async () => {const callers = await trustedCallersFromEnv({FLUXER_API_DONATION_PROXY_KEY: donationKey});expect(callers).toEqual([{name: 'donation',key: donationKey,- buckets: ['donation:request_link', 'donation:manage', 'donation:checkout'],+ buckets: [+ 'donation:request_link',+ 'donation:manage',+ 'donation:checkout',+ 'operator_pass:waitlist_challenge',+ 'operator_pass:waitlist',+ 'operator_pass:waitlist_confirm',+ 'operator_pass:waitlist_followup',+ 'operator_pass:waitlist_unsubscribe',+ ],},]);});diff --git a/fluxer_api/src/api/Config.ts b/fluxer_api/src/api/Config.tsindex e7256a11d..ddff4a3d5 100644--- a/fluxer_api/src/api/Config.ts+++ b/fluxer_api/src/api/Config.ts@@ -1,11 +1,23 @@// SPDX-License-Identifier: AGPL-3.0-or-later-import type {APIConfig, BlueskyOAuthConfig, TrustedCallerConfig} from '@app/api/config/APIConfig';+import type {APIConfig, BlueskyOAuthConfig, OperatorPassConfig, TrustedCallerConfig} from '@app/api/config/APIConfig';+import {+ parseOperatorPassMaxQuantity,+ parseOperatorPassReleaseLists,+ parseOperatorPassStandardPrices,+ parseOperatorPassStoppedCountries,+ parseOperatorPassTransferLockHours,+ parseOperatorPassWallTiers,+ parseOperatorPassWithdrawalCountries,+ resolveOperatorPassDisabledCurrencies,+} from '@app/api/operator_pass/OperatorPassPrices';import {DonationRateLimitConfigs} from '@app/api/rate_limit_configs/DonationRateLimitConfig';+import {OperatorPassRateLimitConfigs} from '@app/api/rate_limit_configs/OperatorPassRateLimitConfig';import {parseIpBanEntry} from '@app/api/utils/IpRangeUtils';import {trimTrailingSlash} from '@app/api/utils/UrlUtils';import type {WorkerTaskName} from '@app/api/worker/WorkerLaneConfig';import type {MasterConfig} from '@fluxer/config/src/MasterConfig';+import {EmailDeliveryModes} from '@fluxer/constants/src/AccountConfigConstants';import {smtpTlsModeFromSecure} from '@fluxer/constants/src/SmtpConstants';import {parseIpAddress} from '@fluxer/ip_utils/src/IpAddress';import {normalizeString} from '@fluxer/schema/src/primitives/SchemaPrimitives';@@ -47,10 +59,23 @@ function toSmtpConfig(port: smtp.port,username: smtp.username,password: smtp.password,- tlsMode: smtp.tls_mode ?? smtpTlsModeFromSecure(smtp.secure),+ tlsMode: smtp.tls_mode ?? smtpTlsModeFromSecure(smtp.secure, smtp.port),};}+function resolveEnvEmailSwitch(+ email: MasterConfig['integrations']['email'],+): Pick<APIConfig['email'], 'enabled' | 'provider'> {+ switch (email.delivery) {+ case undefined:+ return {enabled: email.enabled, provider: email.provider};+ case EmailDeliveryModes.SMTP:+ return {enabled: true, provider: 'smtp'};+ case EmailDeliveryModes.OFF:+ return {enabled: false, provider: email.provider};+ }+}+function isBoolean(value: unknown): value is boolean {return typeof value === 'boolean';}@@ -130,7 +155,12 @@ function buildTrustedCallers(master: MasterConfig): Array<TrustedCallerConfig> {trustedCallers.push({name: 'donation',key: donationProxyKey,- buckets: Object.values(DonationRateLimitConfigs).map((routeConfig) => routeConfig.bucket),+ buckets: [+ ...Object.values(DonationRateLimitConfigs).map((routeConfig) => routeConfig.bucket),+ ...Object.values(OperatorPassRateLimitConfigs)+ .filter((routeConfig) => routeConfig.trustForwardedClientIp === true)+ .map((routeConfig) => routeConfig.bucket),+ ],});}return trustedCallers;@@ -154,6 +184,104 @@ function resolveSetupToken(master: MasterConfig): string | null {return token;}+const ISO_INSTANT_PATTERN = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?(?:Z|[+-]\d{2}:\d{2})$/u;+const OPERATOR_PASS_MAX_GRACE_MINUTES = 24 * 60;++function parseIsoInstant(value: string | undefined, envName: string): Date {+ const trimmed = (value ?? '').trim();+ const parsed = ISO_INSTANT_PATTERN.test(trimmed) ? Date.parse(trimmed) : Number.NaN;+ if (!Number.isFinite(parsed)) {+ throw new Error(`${envName} must be an ISO-8601 instant such as 2026-11-01T16:00:00Z`);+ }+ return new Date(parsed);+}++function parseOptionalIsoInstant(value: string | undefined, envName: string): Date | null {+ return (value ?? '').trim().length === 0 ? null : parseIsoInstant(value, envName);+}++function parseOptionalSnowflake(value: string | undefined, envName: string): bigint | null {+ const trimmed = (value ?? '').trim();+ if (trimmed.length === 0) {+ return null;+ }+ if (!/^[1-9]\d{0,19}$/u.test(trimmed)) {+ throw new Error(`${envName} must be a snowflake ID`);+ }+ return BigInt(trimmed);+}++function resolveOperatorPassClockOffsetMs(master: MasterConfig): number {+ const override = (master.operator_pass.now_override ?? '').trim();+ if (override.length === 0) {+ return 0;+ }+ const overrideAt = parseIsoInstant(override, 'FLUXER_OPERATOR_PASS_NOW');+ if (master.env === 'production' && !master.dev.test_mode_enabled) {+ console.warn('FLUXER_OPERATOR_PASS_NOW is ignored in production');+ return 0;+ }+ return overrideAt.getTime() - Date.now();+}++function buildOperatorPassConfig(master: MasterConfig): OperatorPassConfig {+ const source = master.operator_pass;+ const saleOpensAt = parseOptionalIsoInstant(source.sale_opens_at, 'FLUXER_OPERATOR_PASS_SALE_OPENS_AT');+ const priceRisesAt = parseOptionalIsoInstant(source.price_rises_at, 'FLUXER_OPERATOR_PASS_PRICE_RISES_AT');+ if ((saleOpensAt === null) !== (priceRisesAt === null)) {+ throw new Error('FLUXER_OPERATOR_PASS_SALE_OPENS_AT and FLUXER_OPERATOR_PASS_PRICE_RISES_AT must be set together');+ }+ if (saleOpensAt && priceRisesAt && priceRisesAt.getTime() <= saleOpensAt.getTime()) {+ throw new Error('FLUXER_OPERATOR_PASS_PRICE_RISES_AT must be later than FLUXER_OPERATOR_PASS_SALE_OPENS_AT');+ }+ if (saleOpensAt === null && master.env === 'production' && !master.instance.self_hosted) {+ console.warn(+ 'FLUXER_OPERATOR_PASS_SALE_OPENS_AT and FLUXER_OPERATOR_PASS_PRICE_RISES_AT are not set, the Operator Pass sale stays closed',+ );+ }+ const graceMinutes = source.grace_minutes;+ if (+ typeof graceMinutes !== 'number' ||+ !Number.isInteger(graceMinutes) ||+ graceMinutes < 0 ||+ graceMinutes > OPERATOR_PASS_MAX_GRACE_MINUTES+ ) {+ throw new Error(+ `FLUXER_OPERATOR_PASS_GRACE_MINUTES must be an integer between 0 and ${OPERATOR_PASS_MAX_GRACE_MINUTES}`,+ );+ }+ const labsGuildId = parseOptionalSnowflake(source.labs_guild_id, 'FLUXER_LABS_GUILD_ID');+ const labsOperatorRoleId = parseOptionalSnowflake(source.labs_operator_role_id, 'FLUXER_LABS_OPERATOR_ROLE_ID');+ if ((labsGuildId === null) !== (labsOperatorRoleId === null)) {+ throw new Error('FLUXER_LABS_GUILD_ID and FLUXER_LABS_OPERATOR_ROLE_ID must be set together');+ }+ const standardPricesMinor = parseOperatorPassStandardPrices(source.standard_prices_minor);+ if (standardPricesMinor === null && master.env === 'production' && !master.instance.self_hosted) {+ console.warn(+ 'FLUXER_OPERATOR_PASS_STANDARD_PRICE_* is not set, Operator Pass checkout keeps the early bird price after the price rise',+ );+ }+ return {+ saleOpensAt,+ priceRisesAt,+ graceMs: graceMinutes * 60 * 1000,+ clockOffsetMs: resolveOperatorPassClockOffsetMs(master),+ labsGuildId,+ labsOperatorRoleId,+ standardPricesMinor,+ releaseLists: parseOperatorPassReleaseLists(source.release_lists),+ transferLockMs: parseOperatorPassTransferLockHours(source.transfer_lock_hours) * 60 * 60 * 1000,+ withdrawalCountries: parseOperatorPassWithdrawalCountries(source.withdrawal_countries),+ stoppedCountries: parseOperatorPassStoppedCountries(source.stopped_countries),+ wallTierMinimums: parseOperatorPassWallTiers(source.wall_tiers),+ maxQuantity: parseOperatorPassMaxQuantity(source.max_quantity),+ disabledCurrencies: resolveOperatorPassDisabledCurrencies(+ source.localized_prices_enabled,+ parseOperatorPassStoppedCountries(source.stopped_countries),+ ),+ };+}+export function buildAPIConfigFromMaster(master: MasterConfig): APIConfig {if (!master.internal) {throw new Error('internal configuration is required for the API');@@ -296,8 +424,7 @@ export function buildAPIConfigFromMaster(master: MasterConfig): APIConfig {buckets: s3Buckets,},email: {- enabled: master.integrations.email.enabled,- provider: master.integrations.email.provider,+ ...resolveEnvEmailSwitch(master.integrations.email),webhookSecret: master.integrations.email.webhook_secret ?? undefined,fromEmail: master.integrations.email.from_email,fromName: master.integrations.email.from_name,@@ -432,6 +559,8 @@ export function buildAPIConfigFromMaster(master: MasterConfig): APIConfig {logoUrl: master.instance.branding.logo_url,wordmarkUrl: master.instance.branding.wordmark_url,faviconUrl: master.instance.branding.favicon_url,+ faviconDarkUrl: master.instance.branding.favicon_dark_url,+ signInBackdropUrl: master.instance.branding.sign_in_backdrop_url,themeColor: master.instance.branding.theme_color,statusPageUrl: master.instance.branding.status_page_url,statusPageIncidentHistoryUrl: master.instance.branding.status_page_incident_history_url,@@ -447,6 +576,13 @@ export function buildAPIConfigFromMaster(master: MasterConfig): APIConfig {enabled: master.discovery.enabled,minMemberCount: master.discovery.min_member_count,},+ operatorPass: buildOperatorPassConfig(master),+ paymentDisputes: {+ closureEffectiveAt: parseOptionalIsoInstant(+ master.payment_disputes.closure_effective_at,+ 'FLUXER_PAYMENT_DISPUTE_CLOSURE_EFFECTIVE_AT',+ ),+ },dev: {relaxRegistrationRateLimits: master.dev.relax_registration_rate_limits,disableRateLimits: master.dev.disable_rate_limits,@@ -489,6 +625,7 @@ export function buildAPIConfigFromMaster(master: MasterConfig): APIConfig {products: master.integrations.google_play.products ?? {},pushAudience: master.integrations.google_play.push_audience,pushServiceAccountEmail: master.integrations.google_play.push_service_account_email,+ selfServiceRefunds: master.integrations.google_play.self_service_refunds,},storeBilling: {sandboxUserIds: master.integrations.store_billing.sandbox_user_ids ?? [],diff --git a/fluxer_api/src/api/config/APIConfig.ts b/fluxer_api/src/api/config/APIConfig.tsindex 829bc3769..e0442116b 100644--- a/fluxer_api/src/api/config/APIConfig.ts+++ b/fluxer_api/src/api/config/APIConfig.ts@@ -1,9 +1,15 @@// SPDX-License-Identifier: AGPL-3.0-or-later+import type {+ OperatorPassPriceTable,+ OperatorPassReleaseListTable,+ OperatorPassWithdrawalCountryTable,+} from '@app/api/operator_pass/OperatorPassPrices';import type {WorkerTaskName} from '@app/api/worker/WorkerLaneConfig';import type {CachePurgeAdapterName, StoreProductSlotName} from '@fluxer/config/src/MasterConfig';import type {AccountIdentityMode, TagStyle} from '@fluxer/constants/src/AccountIdentityConstants';import type {SmtpTlsMode} from '@fluxer/constants/src/SmtpConstants';+import type {OperatorPassCurrency} from '@fluxer/schema/src/domains/operator_pass/OperatorPassSchemas';export type APIWorkerMode = 'all_lanes' | 'single_lane' | 'single_task';export type APIWorkerLaneName = 'realtime' | 'unfurl' | 'lifecycle' | 'batch' | 'crosspost';@@ -33,6 +39,23 @@ interface APICachePurgeTarget {timeoutMs: number;}+export interface OperatorPassConfig {+ saleOpensAt: Date | null;+ priceRisesAt: Date | null;+ graceMs: number;+ clockOffsetMs: number;+ labsGuildId: bigint | null;+ labsOperatorRoleId: bigint | null;+ standardPricesMinor: OperatorPassPriceTable | null;+ releaseLists: OperatorPassReleaseListTable;+ transferLockMs: number;+ withdrawalCountries: OperatorPassWithdrawalCountryTable;+ stoppedCountries: ReadonlySet<string>;+ disabledCurrencies: ReadonlySet<OperatorPassCurrency>;+ wallTierMinimums: ReadonlyArray<number>;+ maxQuantity: number;+}+export interface APICachePurgeConfig {adapter: CachePurgeAdapterName;http: APICachePurgeTarget;@@ -100,7 +123,7 @@ export interface APIConfig {skipBuckets: Array<string>;};search: {- engine: 'elasticsearch' | 'meilisearch';+ engine: 'elasticsearch' | 'meilisearch' | 'none';url: string;apiKey: string;username: string;@@ -286,6 +309,8 @@ export interface APIConfig {logoUrl?: string;wordmarkUrl?: string;faviconUrl?: string;+ faviconDarkUrl?: string;+ signInBackdropUrl?: string;themeColor?: string;statusPageUrl?: string;statusPageIncidentHistoryUrl?: string;@@ -301,6 +326,10 @@ export interface APIConfig {enabled: boolean;minMemberCount: number;};+ operatorPass: OperatorPassConfig;+ paymentDisputes: {+ closureEffectiveAt: Date | null;+ };dev: {relaxRegistrationRateLimits: boolean;disableRateLimits: boolean;@@ -340,6 +369,7 @@ export interface APIConfig {products: Record<string, StoreProductSlotName>;pushAudience?: string;pushServiceAccountEmail?: string;+ selfServiceRefunds: boolean;};storeBilling: {sandboxUserIds: Array<string>;