A free and open source instant messaging and VoIP chat app built for friends, groups, and communities.
refactor(api): tidy the api and shared packages (#2733)
Hampus5afbf67a70a4
diff --git a/fluxer_api/package.json b/fluxer_api/package.jsonindex 9dddd91b0..313726b8a 100644--- a/fluxer_api/package.json+++ b/fluxer_api/package.json@@ -41,7 +41,6 @@"@pkgs/email": "workspace:*","@pkgs/geoip": "workspace:*","@pkgs/http_client": "workspace:*",- "@pkgs/initialization": "workspace:*","@pkgs/kv_client": "workspace:*","@pkgs/locale": "workspace:*","@pkgs/media_proxy_utils": "workspace:*",diff --git a/fluxer_api/pkgs/cache/src/CacheSerialization.ts b/fluxer_api/pkgs/cache/src/CacheSerialization.tsindex a8102df42..14897d3fb 100644--- a/fluxer_api/pkgs/cache/src/CacheSerialization.ts+++ b/fluxer_api/pkgs/cache/src/CacheSerialization.ts@@ -6,12 +6,8 @@ import type {CacheLookupResult} from '@pkgs/cache/src/ICacheService';export function parseCachedValue<T>(value: string, logger?: CacheLogger): CacheLookupResult<T> {try {return {hit: true, value: JSON.parse(value)};- } catch (error) {- if (logger) {- const truncatedValue = value.length > 200 ? `${value.substring(0, 200)}...` : value;- const errorMessage = error instanceof Error ? error.message : String(error);- logger.error({errorMessage, value: truncatedValue}, '[CacheProvider] JSON parse error');- }+ } catch {+ logger?.error({valueLength: value.length}, '[CacheProvider] JSON parse error');return {hit: false};}}diff --git a/fluxer_api/pkgs/cache/src/providers/InMemoryProvider.ts b/fluxer_api/pkgs/cache/src/providers/InMemoryProvider.tsindex 6514dd594..715ba83ac 100644--- a/fluxer_api/pkgs/cache/src/providers/InMemoryProvider.ts+++ b/fluxer_api/pkgs/cache/src/providers/InMemoryProvider.ts@@ -8,27 +8,34 @@ import {} from '@pkgs/cache/src/CacheLockValidation';import {type CacheLookupResult, ICacheService} from '@pkgs/cache/src/ICacheService';-interface CacheEntry<T> {- value: T;+interface CacheEntry {expiresAt?: number;}+interface CacheValueEntry extends CacheEntry {+ kind: 'value';+ value: unknown;+}++interface CacheSetEntry extends CacheEntry {+ kind: 'set';+ value: Set<string>;+}++interface CacheLockEntry extends CacheEntry {+ token: string;+ expiresAt: number;+}+interface InMemoryProviderConfig {maxSize?: number;cleanupIntervalMs?: number;}export class InMemoryProvider extends ICacheService {- private cache = new Map<string, CacheEntry<unknown>>();- private sets = new Map<string, Set<string>>();- private locks = new Map<- string,- {- token: string;- expiresAt: number;- }- >();- private maxSize: number;+ private readonly cache = new Map<string, CacheValueEntry | CacheSetEntry>();+ private readonly locks = new Map<string, CacheLockEntry>();+ private readonly maxSize: number;private cleanupInterval?: NodeJS.Timeout;constructor(config: InMemoryProviderConfig = {}) {@@ -42,20 +49,53 @@ export class InMemoryProvider extends ICacheService {private cleanup(): void {const now = Date.now();for (const [key, entry] of this.cache.entries()) {- if (entry.expiresAt && entry.expiresAt <= now) {+ if (this.isExpired(entry, now)) {this.cache.delete(key);}}for (const [key, lock] of this.locks.entries()) {- if (lock.expiresAt <= now) {+ if (this.isExpired(lock, now)) {this.locks.delete(key);}}}- private isExpired(entry: CacheEntry<unknown>): boolean {- if (!entry.expiresAt) return false;- return Date.now() >= entry.expiresAt;+ private isExpired(entry: CacheEntry, now = Date.now()): boolean {+ return entry.expiresAt !== undefined && now >= entry.expiresAt;+ }++ private getLiveEntry(key: string): CacheValueEntry | CacheSetEntry | undefined {+ const entry = this.cache.get(key);+ if (entry && this.isExpired(entry)) {+ this.cache.delete(key);+ return undefined;+ }+ return entry;+ }++ private getValueEntry(key: string): CacheValueEntry | undefined {+ const entry = this.getLiveEntry(key);+ if (entry && entry.kind !== 'value') {+ throw new Error('Cache key contains a set, not a value.');+ }+ return entry;+ }++ private getSetEntry(key: string): CacheSetEntry | undefined {+ const entry = this.getLiveEntry(key);+ if (entry && entry.kind !== 'set') {+ throw new Error('Cache key contains a value, not a set.');+ }+ return entry;+ }++ private getLiveLock(key: string): CacheLockEntry | undefined {+ const lock = this.locks.get(key);+ if (lock && this.isExpired(lock)) {+ this.locks.delete(key);+ return undefined;+ }+ return lock;}private evictIfNeeded(): void {@@ -68,18 +108,16 @@ export class InMemoryProvider extends ICacheService {}async getEntry<T>(key: string): Promise<CacheLookupResult<T>> {- const entry = this.cache.get(key) as CacheEntry<T> | undefined;- if (!entry) return {hit: false};- if (this.isExpired(entry)) {- this.cache.delete(key);- return {hit: false};- }- return {hit: true, value: entry.value};+ const entry = this.getValueEntry(key);+ return entry ? {hit: true, value: entry.value as T} : {hit: false};}async set<T>(key: string, value: T, ttlSeconds?: number): Promise<void> {- this.evictIfNeeded();- const entry: CacheEntry<T> = {+ if (!this.cache.has(key)) {+ this.evictIfNeeded();+ }+ const entry: CacheValueEntry = {+ kind: 'value',value,expiresAt: ttlSeconds ? Date.now() + ttlSeconds * 1000 : undefined,};@@ -91,36 +129,28 @@ export class InMemoryProvider extends ICacheService {}async getAndDelete<T>(key: string): Promise<T | null> {- const value = await this.get<T>(key);- if (value !== null) {- this.cache.delete(key);- }- return value;+ const entry = this.getValueEntry(key);+ this.cache.delete(key);+ return entry ? (entry.value as T) : null;}async exists(key: string): Promise<boolean> {- const entry = this.cache.get(key);- if (!entry) return false;- if (this.isExpired(entry)) {- this.cache.delete(key);- return false;- }- return true;+ return this.getLiveEntry(key) !== undefined;}async expire(key: string, ttlSeconds: number): Promise<void> {- const entry = this.cache.get(key);- if (entry && !this.isExpired(entry)) {+ const entry = this.getLiveEntry(key);+ if (entry) {entry.expiresAt = Date.now() + ttlSeconds * 1000;}}async ttl(key: string): Promise<number> {- const entry = this.cache.get(key);- if (!entry || this.isExpired(entry)) {+ const entry = this.getLiveEntry(key);+ if (!entry) {return -2;}- if (!entry.expiresAt) {+ if (entry.expiresAt === undefined) {return -1;}const ttlMs = entry.expiresAt - Date.now();@@ -128,11 +158,10 @@ export class InMemoryProvider extends ICacheService {}async mget<T>(keys: Array<string>): Promise<Array<T | null>> {- const results: Array<T | null> = [];- for (const key of keys) {- results.push(await this.get<T>(key));- }- return results;+ return keys.map((key) => {+ const entry = this.getLiveEntry(key);+ return entry?.kind === 'value' ? (entry.value as T) : null;+ });}async mset<T>(@@ -162,8 +191,7 @@ export class InMemoryProvider extends ICacheService {async acquireLock(key: string, ttlSeconds: number): Promise<string | null> {validateLockKey(key);const lockKey = formatLockKey(key);- const existingLock = this.locks.get(lockKey);- if (existingLock && existingLock.expiresAt > Date.now()) {+ if (this.getLiveLock(lockKey)) {return null;}const token = generateLockToken();@@ -178,7 +206,7 @@ export class InMemoryProvider extends ICacheService {validateLockKey(key);validateLockToken(token);const lockKey = formatLockKey(key);- const lock = this.locks.get(lockKey);+ const lock = this.getLiveLock(lockKey);if (!lock || lock.token !== token) {return false;}@@ -190,23 +218,21 @@ export class InMemoryProvider extends ICacheService {validateLockKey(key);validateLockToken(token);const lockKey = formatLockKey(key);- const lock = this.locks.get(lockKey);- if (!lock || lock.token !== token || lock.expiresAt <= Date.now()) {+ const lock = this.getLiveLock(lockKey);+ if (!lock || lock.token !== token) {return false;}- this.locks.set(lockKey, {- token,- expiresAt: Date.now() + ttlSeconds * 1000,- });+ lock.expiresAt = Date.now() + ttlSeconds * 1000;return true;}async getAndRenewTtl<T>(key: string, newTtlSeconds: number): Promise<T | null> {- const value = await this.get<T>(key);- if (value !== null) {- await this.expire(key, newTtlSeconds);+ const entry = this.getValueEntry(key);+ if (!entry) {+ return null;}- return value;+ entry.expiresAt = Date.now() + newTtlSeconds * 1000;+ return entry.value as T;}async publish(_channel: string, _message: string): Promise<void> {@@ -214,43 +240,35 @@ export class InMemoryProvider extends ICacheService {}async sadd(key: string, member: string, ttlSeconds?: number): Promise<void> {- let set = this.sets.get(key);- if (!set) {- set = new Set<string>();- this.sets.set(key, set);+ let entry = this.getSetEntry(key);+ if (!entry) {+ this.evictIfNeeded();+ entry = {kind: 'set', value: new Set<string>()};+ this.cache.set(key, entry);}- set.add(member);+ entry.value.add(member);if (ttlSeconds) {- await this.set(`${key}:expiry`, {}, ttlSeconds);+ entry.expiresAt = Date.now() + ttlSeconds * 1000;}}async srem(key: string, member: string): Promise<void> {- const set = this.sets.get(key);- if (set) {- set.delete(member);- if (set.size === 0) {- this.sets.delete(key);- }+ const entry = this.getSetEntry(key);+ if (!entry) {+ return;+ }+ entry.value.delete(member);+ if (entry.value.size === 0) {+ this.cache.delete(key);}}async smembers(key: string): Promise<Set<string>> {- const expiryExists = await this.exists(`${key}:expiry`);- if (!expiryExists && this.sets.has(key)) {- return new Set();- }- return this.sets.get(key) ?? new Set<string>();+ return new Set(this.getSetEntry(key)?.value);}async sismember(key: string, member: string): Promise<boolean> {- const set = this.sets.get(key);- if (!set) return false;- const expiryExists = await this.exists(`${key}:expiry`);- if (!expiryExists) {- return false;- }- return set.has(member);+ return this.getSetEntry(key)?.value.has(member) ?? false;}destroy(): void {@@ -259,7 +277,6 @@ export class InMemoryProvider extends ICacheService {this.cleanupInterval = undefined;}this.cache.clear();- this.sets.clear();this.locks.clear();}}diff --git a/fluxer_api/pkgs/cache/src/providers/KVCacheProvider.ts b/fluxer_api/pkgs/cache/src/providers/KVCacheProvider.tsindex 60316a064..7409be392 100644--- a/fluxer_api/pkgs/cache/src/providers/KVCacheProvider.ts+++ b/fluxer_api/pkgs/cache/src/providers/KVCacheProvider.ts@@ -10,7 +10,7 @@ import {import type {CacheLogger, CacheTelemetry} from '@pkgs/cache/src/CacheProviderTypes';import {parseCachedValue, safeJsonParse, serializeValue} from '@pkgs/cache/src/CacheSerialization';import {type CacheLookupResult, ICacheService} from '@pkgs/cache/src/ICacheService';-import type {IKVProvider} from '@pkgs/kv_client/src/IKVProvider';+import type {IKVPipeline, IKVProvider} from '@pkgs/kv_client/src/IKVProvider';import {runSlotBatches, splitIntoSlotBatches} from '@pkgs/kv_client/src/KVHashSlots';interface KVCacheProviderConfig {@@ -70,6 +70,14 @@ export class KVCacheProvider extends ICacheService {}}+ private async executePipeline(pipeline: IKVPipeline): Promise<void> {+ for (const [error] of await pipeline.exec()) {+ if (error) {+ throw error;+ }+ }+ }+async getEntry<T>(key: string): Promise<CacheLookupResult<T>> {return this.instrumented('get',@@ -153,11 +161,7 @@ export class KVCacheProvider extends ICacheService {pipeline.set(entry.key, entry.value);}}- for (const [error] of await pipeline.exec()) {- if (error) {- throw error;- }- }+ await this.executePipeline(pipeline);});}@@ -204,7 +208,7 @@ export class KVCacheProvider extends ICacheService {if (ttlSeconds) {pipeline.expire(key, ttlSeconds);}- await pipeline.exec();+ await this.executePipeline(pipeline);}async srem(key: string, member: string): Promise<void> {diff --git a/fluxer_api/pkgs/captcha/src/providers/HttpCaptchaProvider.ts b/fluxer_api/pkgs/captcha/src/providers/HttpCaptchaProvider.tsindex c3129fecf..12d62c374 100644--- a/fluxer_api/pkgs/captcha/src/providers/HttpCaptchaProvider.ts+++ b/fluxer_api/pkgs/captcha/src/providers/HttpCaptchaProvider.ts@@ -20,6 +20,21 @@ interface CaptchaVerifyResponse {'error-codes'?: Array<string>;hostname?: string;challenge_ts?: string;+ score?: number;+}++function isCaptchaVerifyResponse(value: unknown): value is CaptchaVerifyResponse {+ if (typeof value !== 'object' || value === null || Array.isArray(value)) return false;+ const data = value as Record<string, unknown>;+ const errorCodes = data['error-codes'];+ return (+ typeof data.success === 'boolean' &&+ (errorCodes === undefined || (Array.isArray(errorCodes) && errorCodes.every((code) => typeof code === 'string'))) &&+ (data.hostname === undefined || typeof data.hostname === 'string') &&+ (data.challenge_ts === undefined || typeof data.challenge_ts === 'string') &&+ (data.score === undefined ||+ (typeof data.score === 'number' && Number.isFinite(data.score) && data.score >= 0 && data.score <= 1))+ );}export abstract class HttpCaptchaProvider implements ICaptchaProvider {@@ -58,10 +73,17 @@ export abstract class HttpCaptchaProvider implements ICaptchaProvider {signal: AbortSignal.timeout(this.timeoutMs),});if (!response.ok) {+ await response.body?.cancel().catch(() => {+ this.logger?.warn({status: response.status}, `${this.providerName} failed to cancel discarded response body`);+ });this.logger?.error({status: response.status}, `${this.providerName} verify request failed`);return false;}- const data = (await response.json()) as CaptchaVerifyResponse;+ const data: unknown = await response.json();+ if (!isCaptchaVerifyResponse(data)) {+ this.logger?.error({}, `${this.providerName} returned an invalid verification response`);+ return false;+ }if (!data.success) {this.logger?.warn({errorCodes: data['error-codes']}, `${this.providerName} verification failed`);return false;diff --git a/fluxer_api/pkgs/elasticsearch_search/src/adapters/ElasticsearchIndexAdapter.ts b/fluxer_api/pkgs/elasticsearch_search/src/adapters/ElasticsearchIndexAdapter.tsindex 79bae42d9..5401d7caf 100644--- a/fluxer_api/pkgs/elasticsearch_search/src/adapters/ElasticsearchIndexAdapter.ts+++ b/fluxer_api/pkgs/elasticsearch_search/src/adapters/ElasticsearchIndexAdapter.ts@@ -1,7 +1,15 @@// SPDX-License-Identifier: AGPL-3.0-or-laterimport type {Client} from '@elastic/elasticsearch';-import type {SearchRequest, SortCombinations, SortResults} from '@elastic/elasticsearch/lib/api/types';+import type {+ BulkOperationType,+ BulkResponse,+ DeleteByQueryResponse,+ ErrorCause,+ SearchRequest,+ SortCombinations,+ SortResults,+} from '@elastic/elasticsearch/lib/api/types';import type {ISearchAdapter, SearchOptions, SearchResult} from '@fluxer/schema/src/contracts/search/SearchAdapterTypes';import type {ElasticsearchFilter} from '../ElasticsearchFilterUtils';import {compactFilters} from '../ElasticsearchFilterUtils';@@ -11,6 +19,7 @@ const ELASTICSEARCH_MAX_RESULT_WINDOW = 10000;const DEEP_PAGINATION_BATCH_SIZE = 1000;const MAX_SEARCH_LIMIT = 1000;const FACET_TERM_LIMIT = 200;+const ERROR_TYPE_MAX_LENGTH = 128;interface ElasticsearchSearchHit<TResult> {_source?: TResult;@@ -191,7 +200,8 @@ export class ElasticsearchIndexAdapter<}this.assertInitialised();const operations = docs.flatMap((doc) => [{index: {_index: this.indexDefinition.indexName, _id: doc.id}}, doc]);- await this.client.bulk({operations, refresh: false});+ const response = await this.client.bulk({operations, refresh: false});+ this.assertBulkSucceeded(response, 'index');}async updateDocument(doc: TResult): Promise<void> {@@ -205,12 +215,7 @@ export class ElasticsearchIndexAdapter<}async bulkIndexDocuments(docs: Array<TResult>): Promise<void> {- if (docs.length === 0) {- return;- }- this.assertInitialised();- const operations = docs.flatMap((doc) => [{index: {_index: this.indexDefinition.indexName, _id: doc.id}}, doc]);- await this.client.bulk({operations, refresh: false});+ await this.indexDocuments(docs);}async refreshIndex(): Promise<void> {@@ -228,25 +233,28 @@ export class ElasticsearchIndexAdapter<}this.assertInitialised();const operations = ids.map((id) => ({delete: {_index: this.indexDefinition.indexName, _id: id}}));- await this.client.bulk({operations, refresh: false});+ const response = await this.client.bulk({operations, refresh: false});+ this.assertBulkSucceeded(response, 'delete');}async deleteByQuery(query: Record<string, unknown>): Promise<void> {this.assertInitialised();- await this.client.deleteByQuery({+ const response = await this.client.deleteByQuery({index: this.indexDefinition.indexName,query,refresh: false,});+ this.assertDeleteByQuerySucceeded(response);}async deleteAllDocuments(): Promise<void> {this.assertInitialised();- await this.client.deleteByQuery({+ const response = await this.client.deleteByQuery({index: this.indexDefinition.indexName,query: {match_all: {}},refresh: true,});+ this.assertDeleteByQuerySucceeded(response);}async search(query: string, filters: TFilters, options?: SearchOptions): Promise<SearchResult<TResult>> {@@ -307,6 +315,29 @@ export class ElasticsearchIndexAdapter<}}+ private assertBulkSucceeded(response: BulkResponse, operation: BulkOperationType): void {+ if (!response.errors) return;+ const context = `Elasticsearch bulk ${operation} failed for index ${this.indexDefinition.indexName}`;+ for (const item of response.items ?? []) {+ const failure = item[operation];+ if (failure?.error) {+ throw new Error(`${context}: ${summarizeOperationFailure(failure.status, failure.error)}`);+ }+ }+ throw new Error(`${context}: response reported errors without ${operation} item error details`);+ }++ private assertDeleteByQuerySucceeded(response: DeleteByQueryResponse): void {+ const context = `Elasticsearch delete by query failed for index ${this.indexDefinition.indexName}`;+ if (response.timed_out) {+ throw new Error(`${context}: timed out`);+ }+ const failure = response.failures?.[0];+ if (failure) {+ throw new Error(`${context}: ${summarizeOperationFailure(failure.status, failure.cause)}`);+ }+ }+private async executeDeepPaginationSearch(searchParams: ElasticsearchBaseSearchRequest,offset: number,@@ -403,6 +434,12 @@ export class ElasticsearchIndexAdapter<}}+function summarizeOperationFailure(status: number, error: ErrorCause): string {+ const errorType =+ typeof error.type === 'string' ? JSON.stringify(error.type.slice(0, ERROR_TYPE_MAX_LENGTH)) : 'missing error type';+ return `HTTP ${status}, ${errorType}`;+}+function isResourceAlreadyExistsError(error: unknown): boolean {if (error == null || typeof error !== 'object') {return false;diff --git a/fluxer_api/pkgs/geoip/src/IpInfoService.ts b/fluxer_api/pkgs/geoip/src/IpInfoService.tsindex b70df4132..ae16d8ac7 100644--- a/fluxer_api/pkgs/geoip/src/IpInfoService.ts+++ b/fluxer_api/pkgs/geoip/src/IpInfoService.ts@@ -291,10 +291,15 @@ export function createIpInfoService(ctx: IpInfoServiceContext): IpInfoService {.catch(() => {});return finalize(params);};+ const controller = new AbortController();+ const timer = setTimeout(() => {+ controller.abort(new DOMException('The operation was aborted due to timeout', 'TimeoutError'));+ }, FETCH_TIMEOUT_MS);+ timer.unref();let payload: unknown;try {const res = await fetch(fetchUrl, {- signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),+ signal: controller.signal,headers: {Accept: 'application/json'},});if (!res.ok) {@@ -312,6 +317,9 @@ export function createIpInfoService(ctx: IpInfoServiceContext): IpInfoService {outcome: 'request_failed',httpStatus: null,});+ } finally {+ clearTimeout(timer);+ controller.abort();}const parsedResponse = RawIpInfoResponseSchema.safeParse(payload);if (!parsedResponse.success) {diff --git a/fluxer_api/pkgs/http_client/package.json b/fluxer_api/pkgs/http_client/package.jsonindex fcf538405..07769a4a3 100644--- a/fluxer_api/pkgs/http_client/package.json+++ b/fluxer_api/pkgs/http_client/package.json@@ -18,6 +18,7 @@"devDependencies": {"@types/node": "catalog:","@typescript/native-preview": "catalog:",+ "undici-types": "catalog:","vitest": "catalog:"}}diff --git a/fluxer_api/pkgs/http_client/src/HttpClient.ts b/fluxer_api/pkgs/http_client/src/HttpClient.tsindex 9ae503b1a..6bf25e7ed 100644--- a/fluxer_api/pkgs/http_client/src/HttpClient.ts+++ b/fluxer_api/pkgs/http_client/src/HttpClient.ts@@ -1,10 +1,16 @@// SPDX-License-Identifier: AGPL-3.0-or-later+import {addAbortListener} from 'node:events';+import {finished} from 'node:stream';import {HttpStatus, REDIRECT_STATUS_CODES} from '@fluxer/constants/src/HttpConstants';import {buildRequestHeaders,classifyRequestError,createRequestSignal,+ DEFAULT_MAX_REDIRECTS,+ DEFAULT_TIMEOUT_MS,+ normalizeMaxRedirects,+ normalizeTimeoutMs,resolveRequestBody,statusToMetricLabel,} from '@pkgs/http_client/src/HttpClientRequestInternals';@@ -20,32 +26,28 @@ import type {StreamResponse,} from '@pkgs/http_client/src/HttpClientTypes';import {HttpError} from '@pkgs/http_client/src/HttpError';+import type {Dispatcher} from 'undici-types';-const DEFAULT_TIMEOUT_MS = 30000;-const DEFAULT_MAX_REDIRECTS = 5;const DEFAULT_SERVICE_NAME = 'unknown';interface ResolvedClientConfig {- defaultHeaders: Record<string, string>;+ defaultHeaders: Headers;defaultTimeoutMs: number;maxRedirects: number;requestUrlPolicy?: RequestUrlPolicy;telemetry?: HttpClientTelemetry;}-function createDefaultHeaders(userAgent: string, defaultHeaders?: Record<string, string>): Record<string, string> {- const headers: Record<string, string> = {- Accept: '*/*',- 'User-Agent': userAgent,- 'Cache-Control': 'no-cache, no-store, must-revalidate',- Pragma: 'no-cache',- };- if (defaultHeaders) {- for (const [key, value] of Object.entries(defaultHeaders)) {- headers[key] = value;- }- }- return headers;+function createDefaultHeaders(userAgent: string, defaultHeaders?: Record<string, string>): Headers {+ return buildRequestHeaders(+ {+ Accept: '*/*',+ 'User-Agent': userAgent,+ 'Cache-Control': 'no-cache, no-store, must-revalidate',+ Pragma: 'no-cache',+ },+ defaultHeaders,+ );}function resolveClientConfig(@@ -61,14 +63,8 @@ function resolveClientConfig(telemetry,};}- const maxRedirects =- typeof userAgentOrOptions.maxRedirects === 'number' && userAgentOrOptions.maxRedirects >= 0- ? userAgentOrOptions.maxRedirects- : DEFAULT_MAX_REDIRECTS;- const defaultTimeoutMs =- typeof userAgentOrOptions.defaultTimeoutMs === 'number' && userAgentOrOptions.defaultTimeoutMs > 0- ? userAgentOrOptions.defaultTimeoutMs- : DEFAULT_TIMEOUT_MS;+ const maxRedirects = normalizeMaxRedirects(userAgentOrOptions.maxRedirects);+ const defaultTimeoutMs = normalizeTimeoutMs(userAgentOrOptions.defaultTimeoutMs, 'defaultTimeoutMs');return {defaultHeaders: createDefaultHeaders(userAgentOrOptions.userAgent, userAgentOrOptions.defaultHeaders),defaultTimeoutMs,@@ -80,10 +76,10 @@ function resolveClientConfig(function createFetchInit(method: HttpMethod,- headers: Record<string, string>,+ headers: Headers,body: string | undefined,signal: AbortSignal,- dispatcher: NonNullable<RequestInit['dispatcher']> | undefined,+ dispatcher: Dispatcher | undefined,): RequestInit {return {method,@@ -95,10 +91,15 @@ function createFetchInit(};}-function resolveRequestUrlPolicyDispatcher(- requestUrlPolicy: RequestUrlPolicy | undefined,-): NonNullable<RequestInit['dispatcher']> | undefined {- return (requestUrlPolicy as {dispatcher?: NonNullable<RequestInit['dispatcher']>} | undefined)?.dispatcher;+function parseRequestUrl(value: string, base?: string): URL {+ const url = URL.parse(value, base);+ if (!url) {+ throw new TypeError('Invalid URL');+ }+ if (url.username || url.password) {+ throw new TypeError('Request URL must not include credentials');+ }+ return url;}function isRedirectStatus(status: number): boolean {@@ -106,33 +107,36 @@ function isRedirectStatus(status: number): boolean {}const SENSITIVE_REDIRECT_HEADERS = new Set(['authorization', 'cookie', 'proxy-authorization']);-const BODY_RELATED_HEADERS = new Set(['content-type', 'content-length', 'transfer-encoding']);+const BODY_RELATED_HEADERS = new Set([+ 'content-encoding',+ 'content-language',+ 'content-length',+ 'content-location',+ 'content-type',+ 'transfer-encoding',+]);function shouldSwitchToGet(status: number, method: HttpMethod): boolean {if (status === HttpStatus.SEE_OTHER) {- return true;+ return method !== 'GET' && method !== 'HEAD';}if (status === HttpStatus.MOVED_PERMANENTLY || status === HttpStatus.FOUND) {- return method !== 'GET' && method !== 'HEAD';+ return method === 'POST';}return false;}-function buildRedirectHeaders(- headers: Record<string, string>,- stripSensitive: boolean,- dropBodyHeaders: boolean,-): Record<string, string> {- const nextHeaders: Record<string, string> = {};- for (const [key, value] of Object.entries(headers)) {- const lowerKey = key.toLowerCase();- if (stripSensitive && SENSITIVE_REDIRECT_HEADERS.has(lowerKey)) {- continue;+function buildRedirectHeaders(headers: Headers, stripSensitive: boolean, dropBodyHeaders: boolean): Headers {+ const nextHeaders = new Headers(headers);+ if (stripSensitive) {+ for (const name of SENSITIVE_REDIRECT_HEADERS) {+ nextHeaders.delete(name);}- if (dropBodyHeaders && BODY_RELATED_HEADERS.has(lowerKey)) {- continue;+ }+ if (dropBodyHeaders) {+ for (const name of BODY_RELATED_HEADERS) {+ nextHeaders.delete(name);}- nextHeaders[key] = value;}return nextHeaders;}@@ -140,27 +144,33 @@ function buildRedirectHeaders(async function fetchWithRedirects(url: string,method: HttpMethod,- headers: Record<string, string>,+ headers: Headers,body: string | undefined,signal: AbortSignal,maxRedirects: number,requestUrlPolicy?: RequestUrlPolicy,): Promise<Response> {- let currentUrl = new URL(url);+ let currentUrl = parseRequestUrl(url);let currentMethod: HttpMethod = method;let currentBody = body;- let currentHeaders = {...headers};- const dispatcher = resolveRequestUrlPolicyDispatcher(requestUrlPolicy);- await validateRequestUrlPolicy(requestUrlPolicy, currentUrl, {- phase: 'initial',- redirectCount: 0,- });+ let currentHeaders = headers;+ const dispatcher = requestUrlPolicy?.dispatcher;+ await validateRequestUrlPolicy(+ requestUrlPolicy,+ currentUrl,+ {+ phase: 'initial',+ redirectCount: 0,+ },+ signal,+ );let response = await fetch(currentUrl.href,createFetchInit(currentMethod, currentHeaders, currentBody, signal, dispatcher),);let redirectCount = 0;while (isRedirectStatus(response.status)) {+ await response.body?.cancel();if (redirectCount >= maxRedirects) {throw new HttpError(`Maximum number of redirects (${maxRedirects}) exceeded`);}@@ -169,7 +179,7 @@ async function fetchWithRedirects(throw new HttpError('Received redirect response without Location header', response.status);}const previousUrl = currentUrl;- const nextUrl = new URL(location, response.url || currentUrl.href);+ const nextUrl = parseRequestUrl(location, response.url || currentUrl.href);const switchToGet = shouldSwitchToGet(response.status, currentMethod);if (switchToGet) {currentMethod = 'GET';@@ -180,11 +190,16 @@ async function fetchWithRedirects(const stripSensitive = previousOrigin !== nextOrigin;currentHeaders = buildRedirectHeaders(currentHeaders, stripSensitive, switchToGet);const nextRedirectCount = redirectCount + 1;- await validateRequestUrlPolicy(requestUrlPolicy, nextUrl, {- phase: 'redirect',- redirectCount: nextRedirectCount,- previousUrl: previousUrl.href,- });+ await validateRequestUrlPolicy(+ requestUrlPolicy,+ nextUrl,+ {+ phase: 'redirect',+ redirectCount: nextRedirectCount,+ previousUrl: previousUrl.href,+ },+ signal,+ );currentUrl = nextUrl;response = await fetch(currentUrl.href,@@ -199,11 +214,21 @@ async function validateRequestUrlPolicy(requestUrlPolicy: RequestUrlPolicy | undefined,url: URL,context: RequestUrlValidationContext,+ signal: AbortSignal,): Promise<void> {+ signal.throwIfAborted();if (!requestUrlPolicy) {return;}- await requestUrlPolicy.validate(url, context);+ let abortSubscription: Disposable | undefined;+ try {+ await new Promise<void>((resolve, reject) => {+ abortSubscription = addAbortListener(signal, () => reject(signal.reason));+ void requestUrlPolicy.validate(url, context).then(resolve, reject);+ });+ } finally {+ abortSubscription?.[Symbol.dispose]();+ }}function recordSuccessfulRequestMetrics(@@ -287,10 +312,11 @@ export function createHttpClient(const startTime = Date.now();const method: HttpMethod = opts.method ?? 'GET';const serviceName = opts.serviceName ?? DEFAULT_SERVICE_NAME;- const timeoutMs = typeof opts.timeout === 'number' && opts.timeout > 0 ? opts.timeout : config.defaultTimeoutMs;- const requestSignal = createRequestSignal(timeoutMs, opts.signal);+ const timeoutMs = normalizeTimeoutMs(opts.timeout, 'timeout', config.defaultTimeoutMs);const headers = buildRequestHeaders(config.defaultHeaders, opts.headers);const body = resolveRequestBody(opts.body, headers);+ const requestSignal = createRequestSignal(timeoutMs, opts.signal);+ let responseOwnsSignal = false;try {const response = await fetchWithRedirects(opts.url,@@ -309,8 +335,16 @@ export function createHttpClient(};const durationMs = Date.now() - startTime;recordSuccessfulRequestMetrics(metrics, serviceName, method, result.status, durationMs);+ if (result.stream) {+ const stopObserving = finished(result.stream, () => {+ stopObserving();+ requestSignal.cleanup();+ });+ responseOwnsSignal = true;+ }return result;} catch (error) {+ requestSignal.abort(error);const durationMs = Date.now() - startTime;if (error instanceof HttpError) {recordHttpErrorMetrics(metrics, serviceName, method, error.status?.toString() ?? 'error', durationMs);@@ -327,12 +361,11 @@ export function createHttpClient(classifiedError.errorType,);} finally {- requestSignal.cleanup();+ if (!responseOwnsSignal) {+ requestSignal.cleanup();+ }}}- async function sendRequest(opts: RequestOptions): Promise<StreamResponse> {- return request(opts);- }async function streamToString(stream: ResponseStream): Promise<string> {if (!stream) {return '';@@ -341,7 +374,7 @@ export function createHttpClient(}return {request,- sendRequest,+ sendRequest: request,streamToString,};}diff --git a/fluxer_api/pkgs/http_client/src/HttpClientDiagnostics.ts b/fluxer_api/pkgs/http_client/src/HttpClientDiagnostics.tsnew file mode 100644index 000000000..caf676cc6--- /dev/null+++ b/fluxer_api/pkgs/http_client/src/HttpClientDiagnostics.ts@@ -0,0 +1,10 @@+export function formatUrlForDiagnostics(value: string | URL): string {+ const url = typeof value === 'string' ? URL.parse(value) : value;+ if (!url) {+ return '[invalid URL]';+ }+ if (url.protocol !== 'http:' && url.protocol !== 'https:') {+ return '[non-HTTP URL]';+ }+ return url.origin;+}diff --git a/fluxer_api/pkgs/http_client/src/HttpClientRequestInternals.ts b/fluxer_api/pkgs/http_client/src/HttpClientRequestInternals.tsindex 5bc73abd4..a1e40ed52 100644--- a/fluxer_api/pkgs/http_client/src/HttpClientRequestInternals.ts+++ b/fluxer_api/pkgs/http_client/src/HttpClientRequestInternals.ts@@ -1,7 +1,12 @@// SPDX-License-Identifier: AGPL-3.0-or-later+import {addAbortListener} from 'node:events';import type {HttpErrorType} from '@pkgs/http_client/src/HttpError';+export const DEFAULT_TIMEOUT_MS = 30000;+export const DEFAULT_MAX_REDIRECTS = 5;+const MAX_TIMEOUT_MS = 2 ** 31 - 1;+const NETWORK_ERROR_CODES = new Set(['ENOTFOUND','ECONNREFUSED',@@ -11,26 +16,13 @@ const NETWORK_ERROR_CODES = new Set(['EHOSTUNREACH','ENETUNREACH',]);-const NETWORK_ERROR_MESSAGE_FRAGMENTS = [- 'ENOTFOUND',- 'ECONNREFUSED',- 'ECONNRESET',- 'ETIMEDOUT',- 'EAI_AGAIN',- 'EHOSTUNREACH',- 'ENETUNREACH',- 'fetch failed',-] as const;+const NETWORK_ERROR_MESSAGE_FRAGMENTS = [...NETWORK_ERROR_CODES, 'fetch failed'];interface NodeErrorLike {code?: unknown;cause?: unknown;}-interface NodeCauseLike {- code?: unknown;-}-interface ClassifiedRequestError {message: string;isNetworkError: boolean;@@ -39,9 +31,30 @@ interface ClassifiedRequestError {interface RequestSignalContext {signal: AbortSignal;+ abort(reason: unknown): void;cleanup(): void;}+export function normalizeMaxRedirects(value: number | undefined): number {+ const maxRedirects = value === undefined ? DEFAULT_MAX_REDIRECTS : value;+ if (!Number.isSafeInteger(maxRedirects) || maxRedirects < 0) {+ throw new RangeError('maxRedirects must be a nonnegative safe integer');+ }+ return maxRedirects;+}++export function normalizeTimeoutMs(+ value: number | undefined,+ setting: 'defaultTimeoutMs' | 'timeout',+ defaultTimeoutMs = DEFAULT_TIMEOUT_MS,+): number {+ const timeoutMs = value === undefined ? defaultTimeoutMs : value;+ if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > MAX_TIMEOUT_MS) {+ throw new RangeError(`${setting} must be an integer between 1 and 2147483647`);+ }+ return timeoutMs;+}+function isNodeErrorLike(error: unknown): error is NodeErrorLike {return typeof error === 'object' && error !== null;}@@ -53,84 +66,61 @@ function resolveErrorCode(error: unknown): string | undefined {if (typeof error.code === 'string') {return error.code;}- if (!isNodeErrorLike(error.cause)) {- return undefined;- }- const cause: NodeCauseLike = error.cause;- if (typeof cause.code === 'string') {- return cause.code;+ if (isNodeErrorLike(error.cause) && typeof error.cause.code === 'string') {+ return error.cause.code;}return undefined;}export function buildRequestHeaders(- defaultHeaders: Record<string, string>,+ defaultHeaders: Headers | Record<string, string>,requestHeaders?: Record<string, string>,-): Record<string, string> {- if (!requestHeaders) {- return {...defaultHeaders};+): Headers {+ const headers = new Headers(defaultHeaders);+ for (const [name, value] of Object.entries(requestHeaders ?? {})) {+ headers.set(name, value);}- return {...defaultHeaders, ...requestHeaders};+ return headers;}-export function resolveRequestBody(body: unknown, headers: Record<string, string>): string | undefined {+export function resolveRequestBody(body: unknown, headers: Headers): string | undefined {if (body === null || body === undefined) {return undefined;}if (body instanceof URLSearchParams) {- if (!headers['Content-Type'] && !headers['content-type']) {- headers['Content-Type'] = 'application/x-www-form-urlencoded;charset=UTF-8';+ if (!headers.get('content-type')) {+ headers.set('content-type', 'application/x-www-form-urlencoded;charset=UTF-8');}return body.toString();}if (typeof body === 'string') {return body;}- if (!headers['Content-Type'] && !headers['content-type']) {- headers['Content-Type'] = 'application/json';+ if (!headers.get('content-type')) {+ headers.set('content-type', 'application/json');}return JSON.stringify(body);}export function createRequestSignal(timeoutMs: number, inputSignal?: AbortSignal): RequestSignalContext {- const timeoutController = new AbortController();- const combinedController = new AbortController();- const attachedListeners: Array<{- signal: AbortSignal;- listener: () => void;- }> = [];+ const controller = new AbortController();const timeoutId = setTimeout(() => {- timeoutController.abort('Request timed out');+ controller.abort('Request timed out');}, timeoutMs);- function abortWithReason(reason: unknown): void {- if (!combinedController.signal.aborted) {- combinedController.abort(reason);- }- }- function attachSignal(signal: AbortSignal): void {- if (signal.aborted) {- abortWithReason(signal.reason);- return;- }- const listener = () => {- abortWithReason(signal.reason);- };- signal.addEventListener('abort', listener, {once: true});- attachedListeners.push({signal, listener});- }- if (inputSignal) {- attachSignal(inputSignal);- }- attachSignal(timeoutController.signal);- function cleanup(): void {- clearTimeout(timeoutId);- for (const attachedListener of attachedListeners) {- attachedListener.signal.removeEventListener('abort', attachedListener.listener);- }+ timeoutId.unref();+ let inputSubscription: Disposable | undefined;+ if (inputSignal?.aborted) {+ controller.abort(inputSignal.reason);+ } else if (inputSignal) {+ inputSubscription = addAbortListener(inputSignal, () => controller.abort(inputSignal.reason));}return {- signal: combinedController.signal,- cleanup,+ signal: controller.signal,+ abort: (reason) => controller.abort(reason),+ cleanup: () => {+ clearTimeout(timeoutId);+ inputSubscription?.[Symbol.dispose]();+ },};}diff --git a/fluxer_api/pkgs/http_client/src/HttpClientTypes.ts b/fluxer_api/pkgs/http_client/src/HttpClientTypes.tsindex f11f40ce3..139d32487 100644--- a/fluxer_api/pkgs/http_client/src/HttpClientTypes.ts+++ b/fluxer_api/pkgs/http_client/src/HttpClientTypes.ts@@ -1,6 +1,7 @@// SPDX-License-Identifier: AGPL-3.0-or-laterimport type {HttpClientTelemetry} from '@pkgs/http_client/src/HttpClientTelemetryTypes';+import type {Dispatcher} from 'undici-types';export type ResponseStream = ReadableStream<Uint8Array> | null;export type HttpMethod = 'GET' | 'POST' | 'HEAD' | 'PUT' | 'PATCH' | 'DELETE' | 'OPTIONS';@@ -13,6 +14,7 @@ export interface RequestUrlValidationContext {}export interface RequestUrlPolicy {+ readonly dispatcher?: Dispatcher;validate(url: URL, context: RequestUrlValidationContext): Promise<void>;}diff --git a/fluxer_api/pkgs/http_client/src/PublicInternetRequestUrlPolicy.ts b/fluxer_api/pkgs/http_client/src/PublicInternetRequestUrlPolicy.tsindex b4a615cc4..7481e9a7c 100644--- a/fluxer_api/pkgs/http_client/src/PublicInternetRequestUrlPolicy.ts+++ b/fluxer_api/pkgs/http_client/src/PublicInternetRequestUrlPolicy.ts@@ -1,13 +1,17 @@// SPDX-License-Identifier: AGPL-3.0-or-later+import assert from 'node:assert/strict';import dns from 'node:dns';import type {LookupFunction} from 'node:net';import {BlockList, isIP} from 'node:net';+import {formatUrlForDiagnostics} from '@pkgs/http_client/src/HttpClientDiagnostics';import type {RequestUrlPolicy, RequestUrlValidationContext} from '@pkgs/http_client/src/HttpClientTypes';import {HttpError} from '@pkgs/http_client/src/HttpError';import {Agent} from 'undici';+import type {Dispatcher} from 'undici-types';const DEFAULT_DNS_CACHE_TTL_MS = 60000;+const DNS_CACHE_MAX_ENTRIES = 10000;const ALLOWED_PROTOCOLS = new Set(['http:', 'https:']);const HOSTNAME_LABEL_REGEX = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;@@ -203,14 +207,14 @@ export function isPubliclyRoutableUrlShape(url: URL): boolean {function getPolicyErrorContext(context: RequestUrlValidationContext): string {if (context.phase === 'redirect') {- const previous = context.previousUrl ?? 'unknown';+ const previous = context.previousUrl === undefined ? 'unknown' : formatUrlForDiagnostics(context.previousUrl);return `redirect #${context.redirectCount} from ${previous}`;}return 'initial request';}function createBlockedRequestError(url: URL, context: RequestUrlValidationContext, reason: string): HttpError {- const message = `Blocked outbound ${getPolicyErrorContext(context)} to ${url.href}: ${reason}`;+ const message = `Blocked outbound ${getPolicyErrorContext(context)} to ${formatUrlForDiagnostics(url)}: ${reason}`;return new HttpError(message, undefined, undefined, true, 'network_error');}@@ -219,20 +223,7 @@ async function defaultLookupHost(hostname: string): Promise<Array<string>> {return addresses.map((addressEntry) => addressEntry.address);}-function deduplicateAddresses(addresses: Array<string>): Array<string> {- const seen = new Set<string>();- const deduplicated: Array<string> = [];- for (const address of addresses) {- if (seen.has(address)) {- continue;- }- seen.add(address);- deduplicated.push(address);- }- return deduplicated;-}--function createBlocklistDispatcher(allowPrivateAddresses: boolean): NonNullable<RequestInit['dispatcher']> {+function createBlocklistDispatcher(allowPrivateAddresses: boolean): Dispatcher {const lookup: LookupFunction = (hostname, options, callback) => {dns.lookup(hostname, {...options, all: true, order: options.order ?? 'verbatim'}, (error, addresses) => {if (error) {@@ -259,33 +250,46 @@ function createBlocklistDispatcher(allowPrivateAddresses: boolean): NonNullable<connect: {lookup,},- }) as unknown as NonNullable<RequestInit['dispatcher']>;+ }) as unknown as Dispatcher;}interface PublicInternetRequestUrlPolicy extends RequestUrlPolicy {- dispatcher: NonNullable<RequestInit['dispatcher']>;+ readonly dispatcher: Dispatcher;}export function createPublicInternetRequestUrlPolicy(options?: PublicInternetRequestUrlPolicyOptions,): PublicInternetRequestUrlPolicy {- const dnsCacheTtlMs =- typeof options?.dnsCacheTtlMs === 'number' && options.dnsCacheTtlMs > 0- ? options.dnsCacheTtlMs- : DEFAULT_DNS_CACHE_TTL_MS;+ const dnsCacheTtlMs = options?.dnsCacheTtlMs ?? DEFAULT_DNS_CACHE_TTL_MS;+ if (!Number.isFinite(dnsCacheTtlMs) || dnsCacheTtlMs <= 0) {+ throw new RangeError('DNS cache TTL must be a positive finite number');+ }const lookupHost = options?.lookupHost ?? defaultLookupHost;const allowPrivateAddresses = options?.allowPrivateAddresses === true;const dnsCache = new Map<string, CachedLookupResult>();async function resolveHostname(hostname: string): Promise<Array<string>> {- const now = Date.now();+ const now = performance.now();const cached = dnsCache.get(hostname);+ dnsCache.delete(hostname);if (cached && cached.expiresAt > now) {+ dnsCache.set(hostname, cached);return cached.addresses;}- const resolvedAddresses = deduplicateAddresses(await lookupHost(hostname));+ const expiresAt = now + dnsCacheTtlMs;+ const resolvedAddresses = [...new Set(await lookupHost(hostname))];+ const current = dnsCache.get(hostname);+ if (expiresAt <= performance.now() || (current && current.expiresAt > expiresAt)) {+ return resolvedAddresses;+ }+ dnsCache.delete(hostname);+ if (dnsCache.size >= DNS_CACHE_MAX_ENTRIES) {+ const oldest = dnsCache.keys().next();+ assert(!oldest.done, 'A full DNS cache must contain an eviction candidate');+ dnsCache.delete(oldest.value);+ }dnsCache.set(hostname, {addresses: resolvedAddresses,- expiresAt: now + dnsCacheTtlMs,+ expiresAt,});return resolvedAddresses;}diff --git a/fluxer_api/pkgs/http_client/src/__tests__/HttpClient.test.ts b/fluxer_api/pkgs/http_client/src/__tests__/HttpClient.test.tsindex 8aca97371..edb7f9aea 100644--- a/fluxer_api/pkgs/http_client/src/__tests__/HttpClient.test.ts+++ b/fluxer_api/pkgs/http_client/src/__tests__/HttpClient.test.ts@@ -225,7 +225,7 @@ describe('HttpClient', () => {expect(response.url).toBe(`${redirectServer.url}/target`);expect(json.path).toBe('/target');});- it('follows 301 redirect and changes method to GET for non-GET requests', async () => {+ it('follows 301 redirect and changes POST to GET', async () => {const client = createHttpClient(TEST_USER_AGENT);testServer.setHandler((_req, res) => {res.writeHead(301, {Location: `${redirectServer.url}/moved`});@@ -260,7 +260,7 @@ describe('HttpClient', () => {expect(response.status).toBe(200);expect(body).toBe('/found');});- it('follows 302 redirect and changes method to GET for non-GET requests', async () => {+ it('follows 302 redirect preserving PATCH', async () => {const client = createHttpClient(TEST_USER_AGENT);testServer.setHandler((_req, res) => {res.writeHead(302, {Location: `${redirectServer.url}/found`});@@ -278,7 +278,7 @@ describe('HttpClient', () => {const body = await client.streamToString(response.stream);const json = JSON.parse(body);expect(response.status).toBe(200);- expect(json.method).toBe('GET');+ expect(json.method).toBe('PATCH');});it('follows 303 redirect and changes method to GET', async () => {const client = createHttpClient(TEST_USER_AGENT);diff --git a/fluxer_api/pkgs/initialization/package.json b/fluxer_api/pkgs/initialization/package.jsondeleted file mode 100644index ba5fa8576..000000000--- a/fluxer_api/pkgs/initialization/package.json+++ /dev/null@@ -1,20 +0,0 @@-{- "name": "@pkgs/initialization",- "version": "0.0.0",- "private": true,- "type": "module",- "exports": {- ".": "./src/Init.ts",- "./src/*": "./src/*.ts",- "./*": "./*"- },- "main": "./src/Init.ts",- "types": "./src/Init.ts",- "scripts": {- "typecheck": "tsgo --noEmit"- },- "devDependencies": {- "@types/node": "catalog:",- "@typescript/native-preview": "catalog:"- }-}diff --git a/fluxer_api/pkgs/initialization/src/CreateServiceInstrumentation.ts b/fluxer_api/pkgs/initialization/src/CreateServiceInstrumentation.tsdeleted file mode 100644index c7ff5f7b9..000000000--- a/fluxer_api/pkgs/initialization/src/CreateServiceInstrumentation.ts+++ /dev/null@@ -1,19 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {startServiceInitialization} from '@pkgs/initialization/src/Init';-import type {ShutdownFn} from '@pkgs/initialization/src/ServiceInitializationTypes';--interface CreateServiceInstrumentationOptions {- serviceName: string;- config: {- env: string;- };-}--export function createServiceInstrumentation(options: CreateServiceInstrumentationOptions): ShutdownFn {- const {serviceName, config} = options;- return startServiceInitialization({- serviceName,- environment: config.env,- });-}diff --git a/fluxer_api/pkgs/initialization/src/Init.ts b/fluxer_api/pkgs/initialization/src/Init.tsdeleted file mode 100644index 55371bb94..000000000--- a/fluxer_api/pkgs/initialization/src/Init.ts+++ /dev/null@@ -1,30 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import type {ServiceInitConfig, ShutdownFn} from '@pkgs/initialization/src/ServiceInitializationTypes';--let initialized = false;--export async function initializeService(_config: ServiceInitConfig): Promise<void> {- if (initialized) {- return;- }- initialized = true;-}--export async function shutdownService(): Promise<void> {- if (!initialized) {- return;- }- initialized = false;-}--export function isServiceInitialized(): boolean {- return initialized;-}--export function startServiceInitialization(config: ServiceInitConfig): ShutdownFn {- initializeService(config).catch((err: unknown) => {- process.stderr.write(`[instrument] Failed to initialize instrumentation: ${err}\n`);- });- return shutdownService;-}diff --git a/fluxer_api/pkgs/initialization/src/ServiceInitializationTypes.ts b/fluxer_api/pkgs/initialization/src/ServiceInitializationTypes.tsdeleted file mode 100644index 06e297bf8..000000000--- a/fluxer_api/pkgs/initialization/src/ServiceInitializationTypes.ts+++ /dev/null@@ -1,9 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--export interface ServiceInitConfig {- serviceName: string;- serviceVersion?: string;- environment?: string;-}--export type ShutdownFn = () => Promise<void>;diff --git a/fluxer_api/pkgs/initialization/tsconfig.json b/fluxer_api/pkgs/initialization/tsconfig.jsondeleted file mode 100644index 97f2c7f13..000000000--- a/fluxer_api/pkgs/initialization/tsconfig.json+++ /dev/null@@ -1,10 +0,0 @@-{- "extends": "../../../tsconfigs/package.json",- "compilerOptions": {- "paths": {- "@fluxer/*": ["../../../packages/*", "../../../packages/*/src/index.ts"],- "@pkgs/*": ["../*"]- }- },- "include": ["src/**/*"]-}diff --git a/fluxer_api/pkgs/kv_client/src/IKVProvider.ts b/fluxer_api/pkgs/kv_client/src/IKVProvider.tsindex 988e235a4..d54946c14 100644--- a/fluxer_api/pkgs/kv_client/src/IKVProvider.ts+++ b/fluxer_api/pkgs/kv_client/src/IKVProvider.ts@@ -28,6 +28,11 @@ export interface IKVSubscription {removeAllListeners(event?: 'message' | 'error'): void;}+export interface KVPurgeBatchResult {+ urls: Array<string>;+ tokensConsumed: number;+}+export interface KVRateLimitResult {allowed: boolean;limit: number;@@ -98,10 +103,7 @@ export interface IKVProvider {maxTokens: number,refillRate: number,refillIntervalMs: number,- ): Promise<{- urls: Array<string>;- tokensConsumed: number;- }>;+ ): Promise<KVPurgeBatchResult>;pipeline(): IKVPipeline;multi(): IKVPipeline;isClustered(): boolean;diff --git a/fluxer_api/pkgs/kv_client/src/KVClient.ts b/fluxer_api/pkgs/kv_client/src/KVClient.tsindex 8110aafaa..4e3b3ad96 100644--- a/fluxer_api/pkgs/kv_client/src/KVClient.ts+++ b/fluxer_api/pkgs/kv_client/src/KVClient.ts@@ -1,14 +1,21 @@// SPDX-License-Identifier: AGPL-3.0-or-laterimport {createHash} from 'node:crypto';-import type {IKVPipeline, IKVProvider, IKVSubscription, KVRateLimitResult} from '@pkgs/kv_client/src/IKVProvider';+import type {+ IKVPipeline,+ IKVProvider,+ IKVSubscription,+ KVPurgeBatchResult,+ KVRateLimitResult,+} from '@pkgs/kv_client/src/IKVProvider';import {type IKVLogger,type KVClientConfig,type ResolvedKVClientConfig,resolveKVClientConfig,} from '@pkgs/kv_client/src/KVClientConfig';-import {KVClientError, KVClientErrorCode} from '@pkgs/kv_client/src/KVClientError';+import {createInvalidResponseError, KVClientError, KVClientErrorCode} from '@pkgs/kv_client/src/KVClientError';+import {resolveKVClusterConnection} from '@pkgs/kv_client/src/KVClusterConnection';import {createStringEntriesFromPairs,createZSetMembersFromScorePairs,@@ -21,6 +28,30 @@ import {KVPipeline} from '@pkgs/kv_client/src/KVPipeline';import {KVSubscription} from '@pkgs/kv_client/src/KVSubscription';import Redis, {Cluster} from 'ioredis';+const MAX_DATE_TIMESTAMP = 8640000000000000;++const DECODE_BUCKET_STATE_SCRIPT = `+local function decodeBucketState(rawState, amountField, timestampField)+ local ok, state = pcall(cjson.decode, rawState)+ if not ok or type(state) ~= 'table' then+ error('invalid stored bucket state')+ end+ local amount = state[amountField]+ if type(amount) ~= 'number' or amount ~= amount or amount < 0 or amount == math.huge then+ error('invalid stored bucket amount: ' .. amountField)+ end+ local timestamp = state[timestampField]+ if type(timestamp) ~= 'number'+ or timestamp ~= timestamp+ or math.abs(timestamp) > ${MAX_DATE_TIMESTAMP}+ or timestamp ~= math.floor(timestamp)+ then+ error('invalid stored bucket timestamp: ' .. timestampField)+ end+ return amount, timestamp+end+`;+const RELEASE_LOCK_SCRIPT = `if redis.call('GET', KEYS[1]) == ARGV[1] thenreturn redis.call('DEL', KEYS[1])@@ -42,6 +73,7 @@ endreturn 0`;const TRY_CONSUME_TOKENS_SCRIPT = `+${DECODE_BUCKET_STATE_SCRIPT}local key = KEYS[1]local now = tonumber(ARGV[1])local requested = tonumber(ARGV[2])@@ -54,11 +86,7 @@ local tokens = maxTokenslocal lastRefill = nowif data then- local ok, bucket = pcall(cjson.decode, data)- if ok and bucket then- tokens = tonumber(bucket.tokens) or maxTokens- lastRefill = tonumber(bucket.lastRefill) or now- end+ tokens, lastRefill = decodeBucketState(data, 'tokens', 'lastRefill')endlocal elapsed = now - lastRefill@@ -84,6 +112,7 @@ redis.call('SET', key, cjson.encode({tokens = tokens, lastRefill = lastRefill}),return consumed`;const CHECK_LEAKY_BUCKET_LIMIT_SCRIPT = `+${DECODE_BUCKET_STATE_SCRIPT}local key = KEYS[1]local nowMs = tonumber(ARGV[1])local limit = tonumber(ARGV[2])@@ -107,11 +136,7 @@ local updatedAt = nowMslocal rawState = redis.call('GET', key)if rawState then- local ok, state = pcall(cjson.decode, rawState)- if ok and state then- level = tonumber(state.level) or 0- updatedAt = tonumber(state.updatedAt) or nowMs- end+ level, updatedAt = decodeBucketState(rawState, 'level', 'updatedAt')endlocal elapsed = nowMs - updatedAt@@ -181,6 +206,7 @@ redis.call('SET', KEYS[2], ARGV[2])return 1`;const DEQUEUE_PURGE_BATCH_SCRIPT = `+${DECODE_BUCKET_STATE_SCRIPT}local queueKey = KEYS[1]local bucketKey = KEYS[2]local maxItems = tonumber(ARGV[1])@@ -191,18 +217,14 @@ local refillIntervalMs = tonumber(ARGV[5])local queueSize = redis.call('SCARD', queueKey)if queueSize == 0 then- return cjson.encode({urls = {}, tokens = 0})+ return '{"urls":[],"tokens":0}'endlocal tokens = maxTokenslocal lastRefill = nowlocal data = redis.call('GET', bucketKey)if data then- local ok, bucket = pcall(cjson.decode, data)- if ok and bucket then- tokens = tonumber(bucket.tokens) or maxTokens- lastRefill = tonumber(bucket.lastRefill) or now- end+ tokens, lastRefill = decodeBucketState(data, 'tokens', 'lastRefill')endlocal elapsed = now - lastRefill@@ -215,7 +237,7 @@ endlocal toPop = math.min(maxItems, math.floor(tokens), queueSize)if toPop <= 0 thenredis.call('SET', bucketKey, cjson.encode({tokens = tokens, lastRefill = lastRefill}), 'EX', 3600)- return cjson.encode({urls = {}, tokens = 0})+ return '{"urls":[],"tokens":0}'endlocal urls = redis.call('SPOP', queueKey, toPop)@@ -252,17 +274,13 @@ return 1const SCRIPT_SHA_CACHE = new Map<string, string>();-interface ScriptPurgeBatchResult {- urls: Array<string>;- tokens: number;-}-export class KVClient implements IKVProvider {private readonly client: Redis | Cluster;private readonly config: ResolvedKVClientConfig;private readonly logger: IKVLogger;private readonly url: string;private readonly timeoutMs: number;+ private closed = false;constructor(config: KVClientConfig | string) {const resolvedConfig = resolveKVClientConfig(config);@@ -283,13 +301,13 @@ export class KVClient implements IKVProvider {}private createClusterClient(clusterConfig: ResolvedKVClientConfig): Cluster {- const nodes =- clusterConfig.clusterNodes.length > 0 ? clusterConfig.clusterNodes : parseClusterNodesFromUrl(clusterConfig.url);+ const {nodes, redisOptions} = resolveKVClusterConnection(clusterConfig.url, clusterConfig.clusterNodes);const natMap = clusterConfig.clusterNatMap;const hasNatMap = Object.keys(natMap).length > 0;return new Cluster(nodes, {clusterRetryStrategy: createRetryStrategy(),redisOptions: {+ ...redisOptions,connectTimeout: clusterConfig.timeoutMs,commandTimeout: clusterConfig.timeoutMs,maxRetriesPerRequest: 1,@@ -299,11 +317,19 @@ export class KVClient implements IKVProvider {});}+ close(): void {+ if (this.closed) {+ return;+ }+ this.closed = true;+ this.client.disconnect(false);+ }+async health(): Promise<boolean> {try {return (await this.execute('health', async () => this.client.ping())) === 'PONG';} catch (error) {- this.logger.debug({url: this.url, error}, 'KV health check failed');+ this.logger.debug({error}, 'KV health check failed');return false;}}@@ -314,45 +340,38 @@ export class KVClient implements IKVProvider {async set(key: string, value: string, ...args: Array<string | number>): Promise<string | null> {const options = parseSetArguments(args);- if (options.useNx) {- if (options.ttlSeconds !== undefined) {- const ttlSeconds = options.ttlSeconds;- return await this.execute('set', async () => {- const result = await this.client.call('SET', key, value, 'EX', ttlSeconds, 'NX');- return normalizeStringOrNull(result);- });- }- return await this.execute('set', async () => {- const result = await this.client.call('SET', key, value, 'NX');- return normalizeStringOrNull(result);- });- }+ const modifiers: Array<string | number> = [];if (options.ttlSeconds !== undefined) {- const ttlSeconds = options.ttlSeconds;- return await this.execute('set', async () => {- const result = await this.client.call('SET', key, value, 'EX', ttlSeconds);- return normalizeStringOrNull(result);- });+ modifiers.push('EX', options.ttlSeconds);}- return await this.execute('set', async () => this.client.set(key, value));+ if (options.useNx) {+ modifiers.push('NX');+ }+ return await this.execute('set', async () => {+ const result =+ modifiers.length === 0+ ? await this.client.set(key, value)+ : await this.client.call('SET', key, value, ...modifiers);+ return parseSetReply(result, 'set', options.useNx);+ });}async setex(key: string, ttlSeconds: number, value: string): Promise<void> {await this.execute('setex', async () => {- await this.client.setex(key, ttlSeconds, value);+ parseSetReply(await this.client.setex(key, ttlSeconds, value), 'setex');});}async setnx(key: string, value: string, ttlSeconds?: number): Promise<boolean> {if (ttlSeconds !== undefined) {- const ttlSecondsValue = ttlSeconds;const result = await this.execute('setnx', async () => {- const commandResult = await this.client.call('SET', key, value, 'EX', ttlSecondsValue, 'NX');- return normalizeStringOrNull(commandResult);+ const commandResult = await this.client.call('SET', key, value, 'EX', ttlSeconds, 'NX');+ return parseSetReply(commandResult, 'setnx', true);});return result === 'OK';}- return (await this.execute('setnx', async () => this.client.setnx(key, value))) === 1;+ const result = await this.execute('setnx', async () => this.client.setnx(key, value));+ return parseIntegerDecision(result, 'setnx');}async mget(...keys: Array<string>): Promise<Array<string | null>> {@@ -360,15 +379,18 @@ export class KVClient implements IKVProvider {return [];}return await this.execute('mget', async () => {- const values = new Array<string | null>(keys.length).fill(null);+ const values = new Array<string | null>(keys.length);const batches = this.splitBySlot(keys.map((key, index) => ({key, index})),(entry) => entry.key,);await runSlotBatches(batches, async (batch) => {const batchValues = await this.client.mget(...batch.map((entry) => entry.key));+ if (!Array.isArray(batchValues) || batchValues.length !== batch.length) {+ throw createInvalidResponseError('mget', `${batch.length} values`);+ }for (const [position, entry] of batch.entries()) {- values[entry.index] = batchValues[position] ?? null;+ values[entry.index] = parseNullableStringReply(batchValues[position], 'mget');}});return values;@@ -383,7 +405,8 @@ export class KVClient implements IKVProvider {await this.execute('mset', async () => {const batches = this.splitBySlot(entries, (entry) => entry.key);await runSlotBatches(batches, async (batch) => {- await this.client.mset(...batch.flatMap((entry) => [entry.key, entry.value]));+ const result = await this.client.mset(...batch.flatMap((entry) => [entry.key, entry.value]));+ parseSetReply(result, 'mset');});});}@@ -421,14 +444,14 @@ export class KVClient implements IKVProvider {async getex(key: string, ttlSeconds: number): Promise<string | null> {return await this.execute('getex', async () => {const result = await this.client.call('GETEX', key, 'EX', ttlSeconds);- return normalizeStringOrNull(result);+ return parseNullableStringReply(result, 'getex');});}async getdel(key: string): Promise<string | null> {return await this.execute('getdel', async () => {const result = await this.client.call('GETDEL', key);- return normalizeStringOrNull(result);+ return parseNullableStringReply(result, 'getdel');});}@@ -464,10 +487,7 @@ export class KVClient implements IKVProvider {}return await this.execute('spop', async () => {const result = await this.client.spop(key, count);- if (result === null) {- return [];- }- return Array.isArray(result) ? result : [result];+ return parsePoppedValues(result, 'spop', count);});}@@ -522,16 +542,9 @@ export class KVClient implements IKVProvider {}return await this.execute('lpop', async () => {if (count !== undefined) {- const result = await this.client.call('LPOP', key, count);- if (result === null) {- return [];- }- if (Array.isArray(result)) {- return result.map((entry) => String(entry));- }- return [String(result)];+ return parsePoppedValues(await this.client.lpop(key, count), 'lpop', count);}- const single = await this.client.lpop(key);+ const single = parseNullableStringReply(await this.client.lpop(key), 'lpop');return single === null ? [] : [single];});}@@ -564,6 +577,7 @@ export class KVClient implements IKVProvider {}duplicate(): IKVSubscription {+ this.assertOpen();return new KVSubscription({url: this.url,mode: this.config.mode,@@ -576,19 +590,19 @@ export class KVClient implements IKVProvider {async acquireLock(key: string, token: string, ttlSeconds: number): Promise<boolean> {const result = await this.execute('acquireLock', async () => {const commandResult = await this.client.call('SET', key, token, 'EX', ttlSeconds, 'NX');- return normalizeStringOrNull(commandResult);+ return parseSetReply(commandResult, 'acquireLock', true);});return result === 'OK';}async releaseLock(key: string, token: string): Promise<boolean> {const result = await this.executeScript('releaseLock', RELEASE_LOCK_SCRIPT, 1, key, token);- return Number(result) === 1;+ return parseIntegerDecision(result, 'releaseLock');}async extendLock(key: string, token: string, ttlSeconds: number): Promise<boolean> {const result = await this.executeScript('extendLock', EXTEND_LOCK_SCRIPT, 1, key, token, ttlSeconds);- return Number(result) === 1;+ return parseIntegerDecision(result, 'extendLock');}async renewSnowflakeNode(key: string, instanceId: string, ttlSeconds: number): Promise<boolean> {@@ -600,20 +614,21 @@ export class KVClient implements IKVProvider {instanceId,ttlSeconds,);- return Number(result) === 1;+ return parseIntegerDecision(result, 'renewSnowflakeNode');}async checkLeakyBucketLimit(key: string, limit: number, windowMs: number, cost: number): Promise<KVRateLimitResult> {- const now = Date.now();- return await this.executeRateLimitScript(+ const result = await this.executeJsonScript('checkLeakyBucketLimit',CHECK_LEAKY_BUCKET_LIMIT_SCRIPT,+ 1,key,- now,+ Date.now(),limit,windowMs,cost,);+ return parseRateLimitResult(result);}async tryConsumeTokens(@@ -635,11 +650,14 @@ export class KVClient implements IKVProvider {refillRate,refillIntervalMs,);- return Number(result);+ if (!isNonNegativeSafeInteger(result) || result > requested) {+ throw createInvalidResponseError('tryConsumeTokens', 'an integer token count within the requested amount');+ }+ return result;}async scheduleBulkDeletion(queueKey: string, secondaryKey: string, score: number, value: string): Promise<void> {- await this.executeScript(+ const result = await this.executeScript('scheduleBulkDeletion',SCHEDULE_BULK_DELETION_SCRIPT,2,@@ -648,6 +666,7 @@ export class KVClient implements IKVProvider {score,value,);+ if (result !== 1) throw createInvalidResponseError('scheduleBulkDeletion', 'the acknowledgement 1');}async claimBulkDeletion(queueKey: string, member: string, maxScore: number, leaseScore: number): Promise<boolean> {@@ -660,7 +679,7 @@ export class KVClient implements IKVProvider {maxScore,leaseScore,);- return Number(result) === 1;+ return parseIntegerDecision(result, 'claimBulkDeletion');}async removeBulkDeletion(queueKey: string, secondaryKey: string, member = ''): Promise<boolean> {@@ -672,7 +691,7 @@ export class KVClient implements IKVProvider {secondaryKey,member,);- return Number(result) === 1;+ return parseIntegerDecision(result, 'removeBulkDeletion');}async dequeuePurgeBatch(@@ -682,12 +701,9 @@ export class KVClient implements IKVProvider {maxTokens: number,refillRate: number,refillIntervalMs: number,- ): Promise<{- urls: Array<string>;- tokensConsumed: number;- }> {+ ): Promise<KVPurgeBatchResult> {const now = Date.now();- const parsed = await this.executeJsonScript<ScriptPurgeBatchResult>(+ const result = await this.executeJsonScript('dequeuePurgeBatch',DEQUEUE_PURGE_BATCH_SCRIPT,2,@@ -699,7 +715,7 @@ export class KVClient implements IKVProvider {refillRate,refillIntervalMs,);- return {urls: parsed.urls, tokensConsumed: parsed.tokens};+ return parsePurgeBatchResult(result, maxItems);}async evalScript(@@ -738,7 +754,10 @@ export class KVClient implements IKVProvider {pipeline(): IKVPipeline {return new KVPipeline({- createCommander: () => this.client.pipeline(),+ createCommander: () => {+ this.assertOpen();+ return this.client.pipeline();+ },normalizeError: (command, error) => this.normalizeError(command, error),mode: 'pipeline',});@@ -746,7 +765,10 @@ export class KVClient implements IKVProvider {multi(): IKVPipeline {return new KVPipeline({- createCommander: () => this.client.multi(),+ createCommander: () => {+ this.assertOpen();+ return this.client.multi();+ },normalizeError: (command, error) => this.normalizeError(command, error),mode: 'multi',});@@ -754,12 +776,19 @@ export class KVClient implements IKVProvider {private async execute<T>(command: string, fn: () => Promise<T>): Promise<T> {try {+ this.assertOpen();return await fn();} catch (error) {throw this.normalizeError(command, error);}}+ private assertOpen(): void {+ if (this.closed) {+ throw new Error('KV client is closed');+ }+ }+private async executeScript(command: string,script: string,@@ -780,45 +809,23 @@ export class KVClient implements IKVProvider {}}- private async executeJsonScript<T>(+ private async executeJsonScript(command: string,script: string,keyCount: number,...args: Array<string | number>- ): Promise<T> {+ ): Promise<unknown> {const result = await this.executeScript(command, script, keyCount, ...args);+ if (typeof result !== 'string') {+ throw createInvalidResponseError(command, 'a JSON string');+ }try {- return JSON.parse(String(result)) as T;- } catch (error) {- throw new KVClientError({- code: KVClientErrorCode.INVALID_RESPONSE,- message: `KV request returned invalid JSON (${command}): ${getErrorMessage(error)}`,- });+ return JSON.parse(result);+ } catch {+ throw createInvalidResponseError(command, 'valid JSON');}}- private async executeRateLimitScript(- command: string,- script: string,- key: string,- nowMs: number,- limit: number,- windowMs: number,- cost: number,- ): Promise<KVRateLimitResult> {- const parsed = await this.executeJsonScript<KVRateLimitResult>(- command,- script,- 1,- key,- nowMs,- limit,- windowMs,- cost,- );- return normalizeRateLimitResult(parsed);- }-private normalizeError(command: string, error: unknown): KVClientError {if (error instanceof KVClientError) {return error;@@ -836,18 +843,6 @@ export class KVClient implements IKVProvider {}}-function parseClusterNodesFromUrl(url: string): Array<{- host: string;- port: number;-}> {- try {- const parsed = new URL(url);- return [{host: parsed.hostname, port: Number.parseInt(parsed.port || '6379', 10)}];- } catch {- return [{host: '127.0.0.1', port: 6379}];- }-}-function createRetryStrategy(): (times: number) => number {return (times: number) => {const backoffMs = Math.min(times * 100, 2000);@@ -855,22 +850,77 @@ function createRetryStrategy(): (times: number) => number {};}-function normalizeStringOrNull(value: unknown): string | null {- if (value === null || value === undefined) {- return null;+function parseNullableStringReply(value: unknown, command: string): string | null {+ if (value === null || typeof value === 'string') return value;+ throw createInvalidResponseError(command, 'a string or null');+}++function parseSetReply(value: unknown, command: string, conditional = false): 'OK' | null {+ if (value === 'OK' || (conditional && value === null)) return value;+ throw createInvalidResponseError(command, conditional ? 'OK or null' : 'OK');+}++function parsePoppedValues(value: unknown, command: string, count: number): Array<string> {+ if (value === null) return [];+ if (!Array.isArray(value) || value.length > count) {+ throw createInvalidResponseError(command, 'a string array within the requested count or null');+ }+ for (const entry of value) {+ if (typeof entry !== 'string') throw createInvalidResponseError(command, 'string array entries');}- return String(value);+ return value;}-function normalizeRateLimitResult(result: KVRateLimitResult): KVRateLimitResult {- return {- allowed: Boolean(result.allowed),- limit: Number(result.limit),- remaining: Number(result.remaining),- resetAfterMs: Number(result.resetAfterMs),- resetAtMs: Number(result.resetAtMs),- retryAfterMs: Number(result.retryAfterMs),- };+function parseIntegerDecision(value: unknown, command: string): boolean {+ if (value === 0 || value === 1) return value === 1;+ throw createInvalidResponseError(command, 'the integer 0 or 1');+}++function parseRateLimitResult(value: unknown): KVRateLimitResult {+ const command = 'checkLeakyBucketLimit';+ if (!isJsonObject(value)) throw createInvalidResponseError(command, 'a rate-limit result object');+ const {allowed, limit, remaining, resetAfterMs, resetAtMs, retryAfterMs} = value;+ if (+ typeof allowed !== 'boolean' ||+ !isNonNegativeSafeInteger(limit) ||+ limit === 0 ||+ !isNonNegativeSafeInteger(remaining) ||+ remaining > limit ||+ !isNonNegativeSafeInteger(resetAfterMs) ||+ typeof resetAtMs !== 'number' ||+ !Number.isSafeInteger(resetAtMs) ||+ Math.abs(resetAtMs) > MAX_DATE_TIMESTAMP ||+ !isNonNegativeSafeInteger(retryAfterMs) ||+ retryAfterMs > resetAfterMs ||+ (allowed ? retryAfterMs !== 0 : remaining !== 0 || retryAfterMs === 0)+ ) {+ throw createInvalidResponseError(command, 'a boolean decision and valid integer rate-limit counts and times');+ }+ return {allowed, limit, remaining, resetAfterMs, resetAtMs, retryAfterMs};+}++function parsePurgeBatchResult(value: unknown, maxItems: number): KVPurgeBatchResult {+ const command = 'dequeuePurgeBatch';+ if (!isJsonObject(value)) throw createInvalidResponseError(command, 'a purge batch object');+ const {urls, tokens} = value;+ if (+ !Array.isArray(urls) ||+ !urls.every((url): url is string => typeof url === 'string') ||+ !isNonNegativeSafeInteger(tokens) ||+ tokens !== urls.length ||+ urls.length > maxItems+ ) {+ throw createInvalidResponseError(command, 'a bounded string array and matching token count');+ }+ return {urls, tokensConsumed: tokens};+}++function isJsonObject(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null && !Array.isArray(value);+}++function isNonNegativeSafeInteger(value: unknown): value is number {+ return typeof value === 'number' && Number.isSafeInteger(value) && value >= 0;}function getScriptSha(script: string): string {diff --git a/fluxer_api/pkgs/kv_client/src/KVClientConfig.ts b/fluxer_api/pkgs/kv_client/src/KVClientConfig.tsindex 0d243fe9d..b1a6a3bd9 100644--- a/fluxer_api/pkgs/kv_client/src/KVClientConfig.ts+++ b/fluxer_api/pkgs/kv_client/src/KVClientConfig.ts@@ -38,23 +38,14 @@ const noopLogger: IKVLogger = {};export function resolveKVClientConfig(config: KVClientConfig | string): ResolvedKVClientConfig {- if (typeof config === 'string') {- return {- url: normalizeUrl(config),- mode: 'standalone' as const,- clusterNodes: [],- clusterNatMap: {},- timeoutMs: DEFAULT_KV_TIMEOUT_MS,- logger: noopLogger,- };- }+ const options: KVClientConfig = typeof config === 'string' ? {url: config} : config;return {- url: normalizeUrl(config.url),- mode: config.mode ?? 'standalone',- clusterNodes: config.clusterNodes ?? [],- clusterNatMap: config.clusterNatMap ?? {},- timeoutMs: config.timeoutMs ?? DEFAULT_KV_TIMEOUT_MS,- logger: config.logger ?? noopLogger,+ url: normalizeUrl(options.url),+ mode: options.mode ?? 'standalone',+ clusterNodes: options.clusterNodes ?? [],+ clusterNatMap: options.clusterNatMap ?? {},+ timeoutMs: options.timeoutMs ?? DEFAULT_KV_TIMEOUT_MS,+ logger: options.logger ?? noopLogger,};}@@ -63,5 +54,9 @@ function normalizeUrl(url: string): string {if (trimmed.length === 0) {throw new Error('KV client URL must not be empty');}+ const query = new URLSearchParams(trimmed.match(/^[^?#]*(\?[^#]*)/)?.[1]);+ if (query.has('stringNumbers')) {+ throw new Error('KV client URLs do not support stringNumbers; numeric replies are required');+ }return trimmed;}diff --git a/fluxer_api/pkgs/kv_client/src/KVClientError.ts b/fluxer_api/pkgs/kv_client/src/KVClientError.tsindex ddd84e7d5..e7dc63e46 100644--- a/fluxer_api/pkgs/kv_client/src/KVClientError.ts+++ b/fluxer_api/pkgs/kv_client/src/KVClientError.ts@@ -26,3 +26,10 @@ export class KVClientError extends FluxerError {this.name = 'KVClientError';}}++export function createInvalidResponseError(command: string, expected: string): KVClientError {+ return new KVClientError({+ code: KVClientErrorCode.INVALID_RESPONSE,+ message: `KV request returned an invalid response (${command}): expected ${expected}`,+ });+}diff --git a/fluxer_api/pkgs/kv_client/src/KVClusterConnection.ts b/fluxer_api/pkgs/kv_client/src/KVClusterConnection.tsnew file mode 100644index 000000000..49c3cba3f--- /dev/null+++ b/fluxer_api/pkgs/kv_client/src/KVClusterConnection.ts@@ -0,0 +1,130 @@+import {domainToASCII} from 'node:url';+import type {KVClusterNode} from '@pkgs/kv_client/src/KVClientConfig';+import type {RedisOptions} from 'ioredis';++interface KVClusterConnection {+ nodes: Array<KVClusterNode>;+ redisOptions: RedisOptions;+}++export function resolveKVClusterConnection(url: string, nodes: ReadonlyArray<KVClusterNode>): KVClusterConnection {+ const normalizedUrl = url.trim();+ for (let index = 0; index < normalizedUrl.length; index++) {+ const code = normalizedUrl.charCodeAt(index);+ if (code <= 0x1f || code === 0x7f) {+ throw new Error('KV cluster URL must not contain control characters');+ }+ }+ const parsed = parseClusterUrl(normalizedUrl);+ const authorityStart = normalizedUrl.indexOf('://');+ if (authorityStart === -1) {+ throw new Error('Invalid KV cluster URL');+ }+ const authorityAndPath = normalizedUrl.slice(authorityStart + 3).split(/[?#]/, 1)[0];+ const pathStart = authorityAndPath.indexOf('/');+ const authority = pathStart === -1 ? authorityAndPath : authorityAndPath.slice(0, pathStart);+ const path = pathStart === -1 ? '' : authorityAndPath.slice(pathStart + 1);+ const queryNames = new Set<string>();+ for (const name of parsed.searchParams.keys()) {+ if (name !== 'username' && name !== 'password' && name !== 'db') {+ throw new Error('Unsupported KV cluster URL option');+ }+ if (queryNames.has(name)) {+ throw new Error('Duplicate KV cluster URL option');+ }+ queryNames.add(name);+ }+ if (path.length > 0) {+ validateClusterDatabase(path);+ }+ const database = parsed.searchParams.get('db');+ if (database !== null) {+ validateClusterDatabase(database);+ }+ const redisOptions = resolveClusterAuthentication(authority, parsed.searchParams);+ if (parsed.protocol === 'rediss:') {+ redisOptions.tls = {};+ }+ const host = resolveClusterHost(authority, parsed);+ const resolvedNodes = nodes.length > 0 ? [...nodes] : [{host, port: Number(parsed.port || '6379')}];+ for (const node of resolvedNodes) {+ if (node.host.trim().length === 0) {+ throw new Error('KV cluster node must include a host');+ }+ if (!Number.isInteger(node.port) || node.port < 1 || node.port > 65535) {+ throw new Error('KV cluster node port must be an integer between 1 and 65535');+ }+ }+ return {+ nodes: resolvedNodes,+ redisOptions,+ };+}++function parseClusterUrl(url: string): URL {+ let parsed: URL;+ try {+ parsed = new URL(url);+ } catch {+ throw new Error('Invalid KV cluster URL');+ }+ if (parsed.protocol !== 'redis:' && parsed.protocol !== 'rediss:') {+ throw new Error('KV cluster URL must use redis:// or rediss://');+ }+ if (!parsed.hostname) {+ throw new Error('KV cluster URL must include a host');+ }+ return parsed;+}++function resolveClusterHost(authority: string, parsed: URL): string {+ if (parsed.hostname.startsWith('[')) {+ return parsed.hostname.slice(1, -1);+ }+ const hostAndPort = authority.slice(authority.lastIndexOf('@') + 1);+ const portStart = hostAndPort.lastIndexOf(':');+ const hostname = portStart === -1 ? hostAndPort : hostAndPort.slice(0, portStart);+ if (hostname.includes('%')) {+ throw new Error('KV cluster URL must not contain a percent-encoded hostname');+ }+ const host = domainToASCII(hostname.toLowerCase());+ if (!host) {+ throw new Error('Invalid KV cluster URL hostname');+ }+ return host;+}++function validateClusterDatabase(database: string): void {+ if (!/^0+$/.test(database)) {+ throw new Error('KV cluster URL must select database 0');+ }+}++function resolveClusterAuthentication(authority: string, query: URLSearchParams): RedisOptions {+ const authEnd = authority.lastIndexOf('@');+ let auth = '';+ if (authEnd !== -1) {+ try {+ auth = decodeURIComponent(authority.slice(0, authEnd));+ } catch {+ throw new Error('Invalid KV cluster URL credentials');+ }+ }+ if (auth) {+ const separator = auth.indexOf(':');+ return {+ username: separator === -1 ? auth : auth.slice(0, separator),+ password: separator === -1 ? '' : auth.slice(separator + 1),+ };+ }+ const options: RedisOptions = {};+ const username = query.get('username');+ const password = query.get('password');+ if (username !== null) {+ options.username = username;+ }+ if (password !== null) {+ options.password = password;+ }+ return options;+}diff --git a/fluxer_api/pkgs/kv_client/src/KVCommandArguments.ts b/fluxer_api/pkgs/kv_client/src/KVCommandArguments.tsindex 0f0c0e7ac..1d891462f 100644--- a/fluxer_api/pkgs/kv_client/src/KVCommandArguments.ts+++ b/fluxer_api/pkgs/kv_client/src/KVCommandArguments.ts@@ -83,7 +83,7 @@ export function createZSetMembersFromScorePairs(scoreMembers: Array<number | strthrow createInvalidArgumentError('zadd member must be a string');}members.push({- score: parseFiniteNumber(rawScore, 'zadd score'),+ score: parseNumberArgument(rawScore, 'zadd score'),value: rawMember,});}@@ -136,14 +136,6 @@ function parseNumberArgument(value: string | number | undefined, label: string):throw createInvalidArgumentError(`${label} must be a finite number`);}-function parseFiniteNumber(value: string | number, label: string): number {- const parsed = parseNumberArgument(value, label);- if (!Number.isFinite(parsed)) {- throw createInvalidArgumentError(`${label} must be finite`);- }- return parsed;-}-function parseNonNegativeInteger(value: string | number | undefined, label: string): number {const parsed = parseNumberArgument(value, label);if (!Number.isInteger(parsed) || parsed < 0) {diff --git a/fluxer_api/pkgs/kv_client/src/KVHashSlots.ts b/fluxer_api/pkgs/kv_client/src/KVHashSlots.tsindex bfcf6be3b..48cbf76c9 100644--- a/fluxer_api/pkgs/kv_client/src/KVHashSlots.ts+++ b/fluxer_api/pkgs/kv_client/src/KVHashSlots.ts@@ -16,10 +16,10 @@ function extractHashTag(key: string): string {}export function computeHashSlot(key: string): number {- const hashed = extractHashTag(key);+ const hashed = Buffer.from(extractHashTag(key));let crc = 0;- for (let index = 0; index < hashed.length; index += 1) {- crc ^= (hashed.charCodeAt(index) & 0xff) << 8;+ for (const byte of hashed) {+ crc ^= byte << 8;for (let bit = 0; bit < 8; bit += 1) {crc = (crc & 0x8000) === 0 ? (crc << 1) & 0xffff : ((crc << 1) ^ 0x1021) & 0xffff;}@@ -52,17 +52,17 @@ export function splitIntoSlotBatches<T>(}export async function runSlotBatches<T>(batches: ReadonlyArray<T>, run: (batch: T) => Promise<void>): Promise<void> {- if (batches.length <= MAX_CONCURRENT_SLOT_BATCHES) {- await Promise.all(batches.map(async (batch) => await run(batch)));- return;- }let nextIndex = 0;- const workers = Array.from({length: MAX_CONCURRENT_SLOT_BATCHES}, async () => {+ const workers = Array.from({length: Math.min(batches.length, MAX_CONCURRENT_SLOT_BATCHES)}, async () => {while (nextIndex < batches.length) {const batch = batches[nextIndex];nextIndex += 1;await run(batch);}});- await Promise.all(workers);+ for (const result of await Promise.allSettled(workers)) {+ if (result.status === 'rejected') {+ throw result.reason;+ }+ }}diff --git a/fluxer_api/pkgs/kv_client/src/KVPipeline.ts b/fluxer_api/pkgs/kv_client/src/KVPipeline.tsindex 515922afd..b36511cc4 100644--- a/fluxer_api/pkgs/kv_client/src/KVPipeline.ts+++ b/fluxer_api/pkgs/kv_client/src/KVPipeline.ts@@ -1,10 +1,12 @@// SPDX-License-Identifier: AGPL-3.0-or-laterimport type {IKVPipeline} from '@pkgs/kv_client/src/IKVProvider';+import {createInvalidResponseError} from '@pkgs/kv_client/src/KVClientError';import {createStringEntriesFromPairs} from '@pkgs/kv_client/src/KVCommandArguments';import type {ChainableCommander} from 'ioredis';type PipelineExecResult = [Error | null, unknown];+type PipelineCommandReply = [Error] | PipelineExecResult;interface KVPipelineOptions {createCommander: () => ChainableCommander;@@ -88,25 +90,27 @@ export class KVPipeline implements IKVPipeline {async exec(): Promise<Array<PipelineExecResult>> {const command = `${this.mode}.exec`;try {- const rawResults = (await this.commander.exec()) as Array<PipelineExecResult> | null;+ const commander = this.commander;+ const expectedResults = commander.length - (this.mode === 'multi' ? 1 : 0);this.commander = this.createCommander();- if (rawResults === null) {- return [];+ const rawResults = await commander.exec();+ if (!Array.isArray(rawResults) || rawResults.length !== expectedResults) {+ throw createInvalidResponseError(command, `${expectedResults} command results`);}- return rawResults.map((result: PipelineExecResult) => {- const [error, value] = result;- return [error ? normalizePipelineError(error) : null, value] as PipelineExecResult;+ return Array.from(rawResults, (result: unknown): PipelineExecResult => {+ if (!isPipelineCommandReply(result)) {+ throw createInvalidResponseError(command, 'an error/value pair for every command');+ }+ return [result[0], result[1]];});} catch (error) {- this.commander = this.createCommander();throw this.normalizeError(command, error);}}}-function normalizePipelineError(error: unknown): Error {- if (error instanceof Error) {- return error;- }- return new Error(String(error));+function isPipelineCommandReply(value: unknown): value is PipelineCommandReply {+ if (!Array.isArray(value)) return false;+ if (value[0] instanceof Error) return value.length === 1 || value.length === 2;+ return value.length === 2 && value[0] === null && value[1] !== undefined;}diff --git a/fluxer_api/pkgs/kv_client/src/KVSubscription.ts b/fluxer_api/pkgs/kv_client/src/KVSubscription.tsindex 32b96d048..8237e08d6 100644--- a/fluxer_api/pkgs/kv_client/src/KVSubscription.ts+++ b/fluxer_api/pkgs/kv_client/src/KVSubscription.ts@@ -2,7 +2,8 @@import type {IKVSubscription} from '@pkgs/kv_client/src/IKVProvider';import type {IKVLogger, KVClientMode, KVClusterNode} from '@pkgs/kv_client/src/KVClientConfig';-import Redis from 'ioredis';+import {resolveKVClusterConnection} from '@pkgs/kv_client/src/KVClusterConnection';+import Redis, {type RedisOptions} from 'ioredis';interface KVSubscriptionConfig {url: string;@@ -12,16 +13,23 @@ interface KVSubscriptionConfig {logger: IKVLogger;}+interface KVSubscriptionConnect {+ completion: Promise<void>;+ controller: AbortController;+}+export class KVSubscription implements IKVSubscription {private readonly url: string;private readonly mode: KVClientMode;private readonly clusterNodes: Array<KVClusterNode>;private readonly timeoutMs: number;private readonly logger: IKVLogger;- private readonly channels: Set<string> = new Set();+ private readonly desiredChannels = new Set<string>();private readonly messageCallbacks: Set<(channel: string, message: string) => void> = new Set();private readonly errorCallbacks: Set<(error: Error) => void> = new Set();private client: Redis | null = null;+ private connecting: KVSubscriptionConnect | null = null;+ private closing: Promise<void> | null = null;constructor(config: KVSubscriptionConfig) {this.url = config.url;@@ -32,31 +40,125 @@ export class KVSubscription implements IKVSubscription {}async connect(): Promise<void> {- if (this.client !== null) {+ this.assertNotClosing();+ if (this.connecting !== null) {+ return await this.connecting.completion;+ }+ if (this.client?.status === 'ready') {return;}- const connectionUrl = this.resolveSubscriptionUrl();- const client = new Redis(connectionUrl, {+ if (this.client === null || this.client.status === 'end') {+ this.client = this.createClient();+ }+ const controller = new AbortController();+ const connecting: KVSubscriptionConnect = {+ completion: this.connectClient(this.client, controller.signal),+ controller,+ };+ this.connecting = connecting;+ try {+ await connecting.completion;+ } finally {+ controller.abort();+ if (this.connecting === connecting) {+ this.connecting = null;+ }+ }+ }++ private createClient(): Redis {+ const options: RedisOptions = {autoResubscribe: true,connectTimeout: this.timeoutMs,commandTimeout: this.timeoutMs,maxRetriesPerRequest: 1,retryStrategy: createRetryStrategy(),- });+ };+ const connection = this.mode === 'cluster' ? resolveKVClusterConnection(this.url, this.clusterNodes) : null;+ const client = connection+ ? new Redis({...connection.redisOptions, ...connection.nodes[0], db: 0, ...options})+ : new Redis(this.url, options);client.on('message', (channel: string, message: string) => {+ if (this.client !== client || this.closing !== null) {+ return;+ }for (const callback of this.messageCallbacks) {callback(channel, message);}});client.on('error', (error: Error) => {+ if (this.client !== client || this.closing !== null) {+ return;+ }this.logger.error({error}, 'KV subscription error');for (const callback of this.errorCallbacks) {callback(error);}});- this.client = client;- if (this.channels.size > 0) {- await this.client.subscribe(...Array.from(this.channels));+ return client;+ }++ private async connectClient(client: Redis, signal: AbortSignal): Promise<void> {+ try {+ const ready = this.waitForReady(client, signal);+ if (client.status === 'wait') {+ await Promise.all([ready, client.connect()]);+ } else {+ await ready;+ }+ this.assertCurrentClient(client);+ if (this.desiredChannels.size > 0) {+ await client.subscribe(...this.desiredChannels);+ this.assertCurrentClient(client);+ }+ } catch (error) {+ if (this.client === client && this.closing === null) {+ this.client = null;+ client.disconnect(false);+ }+ throw error;+ }+ }++ private waitForReady(client: Redis, signal: AbortSignal): Promise<void> {+ if (signal.aborted) {+ return Promise.reject(signal.reason);+ }+ if (client.status === 'ready') {+ return Promise.resolve();+ }+ return new Promise((resolve, reject) => {+ const finish = (error?: unknown): void => {+ clearTimeout(timer);+ client.off('ready', ready);+ client.off('end', ended);+ signal.removeEventListener('abort', aborted);+ if (error === undefined) {+ resolve();+ } else {+ reject(error);+ }+ };+ const ready = (): void => finish();+ const ended = (): void => finish(new Error('KV subscription connection was closed'));+ const aborted = (): void => finish(signal.reason);+ const timer = setTimeout(() => finish(new Error('KV subscription connection timed out')), this.timeoutMs);+ timer.unref();+ client.once('ready', ready);+ client.once('end', ended);+ signal.addEventListener('abort', aborted, {once: true});+ });+ }++ private assertNotClosing(): void {+ if (this.closing !== null) {+ throw new Error('KV subscription is closing');+ }+ }++ private assertCurrentClient(client: Redis): void {+ if (this.client !== client || this.closing !== null) {+ throw new Error('KV subscription connection was closed');}}@@ -87,39 +189,72 @@ export class KVSubscription implements IKVSubscription {}async subscribe(...channels: Array<string>): Promise<void> {- const newChannels = channels.filter((channel) => {- if (this.channels.has(channel)) {- return false;- }- this.channels.add(channel);- return true;- });- if (newChannels.length === 0 || this.client === null) {+ this.assertNotClosing();+ const requestedChannels = [...new Set(channels)];+ for (const channel of requestedChannels) {+ this.desiredChannels.add(channel);+ }+ const client = this.client;+ if (requestedChannels.length === 0 || client === null) {return;}- await this.client.subscribe(...newChannels);+ await client.subscribe(...requestedChannels);+ this.assertCurrentClient(client);}async unsubscribe(...channels: Array<string>): Promise<void> {- const removedChannels = channels.filter((channel) => this.channels.delete(channel));- if (removedChannels.length === 0 || this.client === null) {+ this.assertNotClosing();+ const requestedChannels = [...new Set(channels)];+ for (const channel of requestedChannels) {+ this.desiredChannels.delete(channel);+ }+ const client = this.client;+ if (requestedChannels.length === 0 || client === null) {return;}- await this.client.unsubscribe(...removedChannels);+ await client.unsubscribe(...requestedChannels);+ this.assertCurrentClient(client);}async quit(): Promise<void> {+ if (this.closing !== null) {+ return await this.closing;+ }const client = this.client;- this.client = null;if (client === null) {return;}- await client.quit();+ const closing = Promise.resolve().then(() => this.closeClient(client));+ this.closing = closing;+ this.connecting?.controller.abort(new Error('KV subscription connection was closed'));+ try {+ await closing;+ } finally {+ if (this.client === client) {+ this.client = null;+ }+ this.connecting = null;+ if (this.closing === closing) {+ this.closing = null;+ }+ }+ }++ private async closeClient(client: Redis): Promise<void> {+ try {+ if (this.client === client && client.status !== 'end') {+ await client.quit();+ }+ } finally {+ client.disconnect(false);+ }}async disconnect(): Promise<void> {const client = this.client;this.client = null;+ this.connecting?.controller.abort(new Error('KV subscription connection was closed'));+ this.connecting = null;if (client === null) {return;}@@ -134,19 +269,8 @@ export class KVSubscription implements IKVSubscription {this.errorCallbacks.clear();}}-- private resolveSubscriptionUrl(): string {- if (this.mode !== 'cluster' || this.clusterNodes.length === 0) {- return this.url;- }- const node = this.clusterNodes[0];- return `redis://${node.host}:${node.port}`;- }}function createRetryStrategy(): (times: number) => number {- return (times: number) => {- const backoffMs = Math.min(times * 100, 2000);- return backoffMs;- };+ return (times) => Math.min(times * 100, 2000);}diff --git a/fluxer_api/pkgs/nats/src/NatsConnectionManager.ts b/fluxer_api/pkgs/nats/src/NatsConnectionManager.tsindex f18db18ba..3f47fb8c6 100644--- a/fluxer_api/pkgs/nats/src/NatsConnectionManager.ts+++ b/fluxer_api/pkgs/nats/src/NatsConnectionManager.ts@@ -2,30 +2,56 @@import type {INatsConnectionManager} from '@pkgs/nats/src/INatsConnectionManager';import type {NatsConnectionOptions} from '@pkgs/nats/src/NatsConnectionOptions';-import {connect, type NatsConnection} from 'nats';+import {connect, ErrorCode, type NatsConnection, NatsError} from 'nats';const DEFAULT_MAX_RECONNECT_ATTEMPTS = -1;const DEFAULT_RECONNECT_TIME_WAIT_MS = 500;const DEFAULT_CONNECT_TIMEOUT_MS = 5000;+const DEFAULT_DRAIN_TIMEOUT_MS = 5000;+const MAX_TIMER_DELAY_MS = 2_147_483_647;++interface NatsDrainDeadline {+ expired: boolean;+ promise: Promise<never>;+}export class NatsConnectionManager implements INatsConnectionManager {private connection: NatsConnection | null = null;- private connectPromise: Promise<NatsConnection> | null = null;+ private connectPromise: Promise<void> | null = null;+ private drainPromise: Promise<void> | null = null;+ private drainGeneration = 0;private readonly options: NatsConnectionOptions;+ private readonly drainTimeoutMs: number;constructor(options: NatsConnectionOptions) {this.options = options;+ this.drainTimeoutMs = options.drainTimeoutMs ?? DEFAULT_DRAIN_TIMEOUT_MS;+ if (+ !Number.isSafeInteger(this.drainTimeoutMs) ||+ this.drainTimeoutMs < 1 ||+ this.drainTimeoutMs > MAX_TIMER_DELAY_MS+ ) {+ throw new RangeError(`NATS drainTimeoutMs must be an integer between 1 and ${MAX_TIMER_DELAY_MS}`);+ }}async connect(): Promise<void> {+ this.assertNotDraining();if (this.connection !== null && !this.connection.isClosed()) {return;}- if (this.connectPromise !== null) {- this.connection = await this.connectPromise;- return;+ const generation = this.drainGeneration;+ this.connectPromise ??= this.openConnection().finally(() => {+ this.connectPromise = null;+ });+ await this.connectPromise;+ if (generation !== this.drainGeneration) {+ throw NatsError.errorForCode(ErrorCode.ConnectionDraining);}- const connectPromise = connect({+ }++ private async openConnection(): Promise<void> {+ this.connection = await connect({servers: this.options.url,token: this.options.token || undefined,name: this.options.name,@@ -33,39 +59,88 @@ export class NatsConnectionManager implements INatsConnectionManager {reconnectTimeWait: this.options.reconnectTimeWaitMs ?? DEFAULT_RECONNECT_TIME_WAIT_MS,timeout: this.options.connectTimeoutMs ?? DEFAULT_CONNECT_TIMEOUT_MS,});- this.connectPromise = connectPromise;- try {- this.connection = await connectPromise;- } finally {- if (this.connectPromise === connectPromise) {- this.connectPromise = null;- }- }}getConnection(): NatsConnection {+ this.assertNotDraining();if (this.connection === null || this.connection.isClosed()) {throw new Error('NATS connection is not established. Call connect() first.');}return this.connection;}- async drain(): Promise<void> {- if (this.connectPromise !== null) {+ drain(): Promise<void> {+ if (this.drainPromise !== null) {+ return this.drainPromise;+ }+ if (this.connection === null && this.connectPromise === null) {+ return Promise.resolve();+ }+ this.drainGeneration++;+ const connectPromise = this.connectPromise;+ const timeout = Promise.withResolvers<never>();+ const deadline: NatsDrainDeadline = {expired: false, promise: timeout.promise};+ const timeoutError = new Error(`NATS connection drain exceeded ${this.drainTimeoutMs}ms`);+ const timer = setTimeout(() => {+ deadline.expired = true;+ timeout.reject(timeoutError);+ }, this.drainTimeoutMs);+ const cleanup = Promise.resolve()+ .then(() => this.drainConnection(connectPromise, deadline))+ .catch((error: unknown) => {+ if (deadline.expired && error !== timeoutError) {+ process.emitWarning(new Error('NATS connection cleanup failed after its drain deadline', {cause: error}));+ }+ throw error;+ })+ .finally(() => {+ clearTimeout(timer);+ this.drainPromise = null;+ });+ this.drainPromise = Promise.race([cleanup, deadline.promise]);+ return this.drainPromise;+ }++ private async drainConnection(connectPromise: Promise<void> | null, deadline: NatsDrainDeadline): Promise<void> {+ if (connectPromise !== null) {try {- this.connection = await this.connectPromise;+ await connectPromise;} catch {- this.connectPromise = null;return;}}- if (this.connection === null) {+ const connection = this.connection;+ if (connection === null) {return;}- if (!this.connection.isClosed()) {- await this.connection.drain();+ const errors: Array<unknown> = [];+ try {+ if (!deadline.expired && !connection.isClosed()) {+ await Promise.race([connection.drain(), deadline.promise]);+ if (!connection.isClosed()) {+ throw new Error('NATS connection remained open after draining.');+ }+ }+ } catch (error) {+ errors.push(error);+ }+ try {+ await connection.close();+ } catch (error) {+ errors.push(error);+ } finally {+ if (this.connection === connection) {+ this.connection = null;+ }+ }+ if (errors.length === 1) throw errors[0];+ if (errors.length > 1) throw new AggregateError(errors, 'NATS connection drain and close failed');+ }++ private assertNotDraining(): void {+ if (this.drainPromise !== null) {+ throw NatsError.errorForCode(ErrorCode.ConnectionDraining);}- this.connection = null;}isClosed(): boolean {diff --git a/fluxer_api/pkgs/nats/src/NatsConnectionOptions.ts b/fluxer_api/pkgs/nats/src/NatsConnectionOptions.tsindex 00be738e4..73c66771b 100644--- a/fluxer_api/pkgs/nats/src/NatsConnectionOptions.ts+++ b/fluxer_api/pkgs/nats/src/NatsConnectionOptions.ts@@ -7,4 +7,5 @@ export interface NatsConnectionOptions {maxReconnectAttempts?: number;reconnectTimeWaitMs?: number;connectTimeoutMs?: number;+ drainTimeoutMs?: number;}diff --git a/fluxer_api/pkgs/postgres/src/Client.ts b/fluxer_api/pkgs/postgres/src/Client.tsindex fabdbd511..486db3e7f 100644--- a/fluxer_api/pkgs/postgres/src/Client.ts+++ b/fluxer_api/pkgs/postgres/src/Client.ts@@ -1,8 +1,26 @@// SPDX-License-Identifier: AGPL-3.0-or-later+import assert from 'node:assert/strict';import type {Pool, PoolClient, QueryResult, QueryResultRow} from 'pg';import pg from 'pg';+const MAX_DIAGNOSTIC_FIELD_LENGTH = 128;++interface PostgresConnectionDiagnostic {+ phase: 'idle' | 'checked_out';+ errorName: string;+ code?: string;+ severity?: string;+ routine?: string;+}++type PostgresConnectionErrorReporter = (diagnostic: PostgresConnectionDiagnostic) => void;++interface AcquiredPostgresConnection {+ error: Error | null;+ onError: (error: Error) => void;+}+interface PostgresConfig {url?: string;host?: string;@@ -35,10 +53,14 @@ export interface IPostgresClient extends PostgresQueryable {interface DefaultClientState {client: PostgresClient | null;+ initialization: Promise<void> | null;+ shutdown: Promise<void> | null;}const defaultClientState: DefaultClientState = {client: null,+ initialization: null,+ shutdown: null,};function assertIdentifier(identifier: string): string {@@ -53,6 +75,29 @@ function normalizePem(pem: string | undefined): string | undefined {return pem.replaceAll('\\n', '\n');}+function connectionDiagnostic(+ error: Error,+ phase: PostgresConnectionDiagnostic['phase'],+): PostgresConnectionDiagnostic {+ return {+ phase,+ errorName: error.name.slice(0, MAX_DIAGNOSTIC_FIELD_LENGTH),+ ...('code' in error && typeof error.code === 'string'+ ? {code: error.code.slice(0, MAX_DIAGNOSTIC_FIELD_LENGTH)}+ : {}),+ ...('severity' in error && typeof error.severity === 'string'+ ? {severity: error.severity.slice(0, MAX_DIAGNOSTIC_FIELD_LENGTH)}+ : {}),+ ...('routine' in error && typeof error.routine === 'string'+ ? {routine: error.routine.slice(0, MAX_DIAGNOSTIC_FIELD_LENGTH)}+ : {}),+ };+}++function reportConnectionError(diagnostic: PostgresConnectionDiagnostic): void {+ console.error('Postgres connection error', diagnostic);+}+export function quoteIdentifier(identifier: string): string {return `"${assertIdentifier(identifier)}"`;}@@ -60,14 +105,32 @@ export function quoteIdentifier(identifier: string): string {class PostgresClient implements IPostgresClient {private readonly config: PostgresConfig;private pool: Pool | null;+ private connection: Promise<void> | null = null;+ private disconnection: Promise<void> | null = null;+ private activeOperations = 0;+ private resolveOperationsDrained: (() => void) | null = null;+ private readonly acquiredConnections = new WeakMap<PoolClient, AcquiredPostgresConnection>();- constructor(config: PostgresConfig) {+ constructor(+ config: PostgresConfig,+ private readonly onConnectionError: PostgresConnectionErrorReporter,+ ) {this.config = {...config};this.pool = null;}async connect(): Promise<void> {+ if (this.disconnection !== null) {+ throw new Error('Cannot connect Postgres while it is shutting down');+ }if (this.pool !== null) return;+ this.connection ??= this.openPool().finally(() => {+ this.connection = null;+ });+ await this.connection;+ }++ private async openPool(): Promise<void> {const pool = new pg.Pool({connectionString: this.config.url || undefined,host: this.config.url ? undefined : (this.config.host ?? '127.0.0.1'),@@ -78,12 +141,72 @@ class PostgresClient implements IPostgresClient {ssl: this.config.ssl ? {rejectUnauthorized: true, ca: normalizePem(this.config.sslCa)} : undefined,max: this.config.maxConnections ?? 20,});- const client = await pool.connect();- client.release();+ this.observePoolConnections(pool);+ try {+ const client = await pool.connect();+ let discardClient = true;+ try {+ const acquired = this.getAcquiredConnection(client);+ if (acquired.error) throw acquired.error;+ discardClient = false;+ } finally {+ client.release(discardClient);+ }+ } catch (error) {+ try {+ await pool.end();+ } catch (cleanupError) {+ throw new AggregateError([error, cleanupError], 'Postgres connection and pool cleanup failed');+ }+ throw error;+ }this.pool = pool;}+ private observePoolConnections(pool: Pool): void {+ pool.on('error', (error) => this.onConnectionError(connectionDiagnostic(error, 'idle')));+ pool.on('acquire', (client) => {+ assert(!this.acquiredConnections.has(client), 'Postgres connection was acquired twice without release');+ const acquired: AcquiredPostgresConnection = {+ error: null,+ onError: (error) => {+ if (acquired.error !== null) return;+ acquired.error = error;+ this.onConnectionError(connectionDiagnostic(error, 'checked_out'));+ },+ };+ this.acquiredConnections.set(client, acquired);+ client.on('error', acquired.onError);+ });+ pool.on('release', (_error, client) => {+ const acquired = this.acquiredConnections.get(client);+ if (acquired) client.removeListener('error', acquired.onError);+ this.acquiredConnections.delete(client);+ });+ }++ private getAcquiredConnection(client: PoolClient): AcquiredPostgresConnection {+ const acquired = this.acquiredConnections.get(client);+ assert(acquired, 'Postgres connection has no active acquisition');+ return acquired;+ }+async shutdown(): Promise<void> {+ if (this.disconnection !== null) return this.disconnection;+ if (this.pool === null && this.connection === null) return;+ this.disconnection = this.closePool().finally(() => {+ this.disconnection = null;+ });+ await this.disconnection;+ }++ private async closePool(): Promise<void> {+ await this.connection;+ if (this.activeOperations > 0) {+ await new Promise<void>((resolve) => {+ this.resolveOperationsDrained = resolve;+ });+ }const pool = this.pool;if (pool === null) return;this.pool = null;@@ -91,7 +214,7 @@ class PostgresClient implements IPostgresClient {}isConnected(): boolean {- return this.pool !== null;+ return this.pool !== null && this.disconnection === null;}async query<T extends QueryResultRow = QueryResultRow>(@@ -99,7 +222,7 @@ class PostgresClient implements IPostgresClient {values: Array<unknown> = [],name?: string,): Promise<QueryResult<T>> {- return this.getPool().query<T>({text, values, name: this.statementName(name)});+ return this.withPool((pool) => pool.query<T>({text, values, name: this.statementName(name)}));}private statementName(name: string | undefined): string | undefined {@@ -107,17 +230,38 @@ class PostgresClient implements IPostgresClient {}async transaction<T>(fn: (client: PostgresQueryable) => Promise<T>): Promise<T> {- const client = await this.getPool().connect();+ return this.withPool((pool) => this.runTransaction(pool, fn));+ }++ private async runTransaction<T>(pool: Pool, fn: (client: PostgresQueryable) => Promise<T>): Promise<T> {+ const client = await pool.connect();+ let acquired: AcquiredPostgresConnection | null = null;+ let discardClient = false;try {+ acquired = this.getAcquiredConnection(client);+ if (acquired.error) throw acquired.error;await client.query('BEGIN');- const result = await fn(poolClientQueryable(client, this.config.preparedStatements !== false));+ if (acquired.error) throw acquired.error;+ const result = await runTransactionCallback(client, acquired, this.config.preparedStatements !== false, fn);+ if (acquired.error) throw acquired.error;await client.query('COMMIT');return result;} catch (error) {- await rollback(client);+ if (acquired === null) throw error;+ if (!acquired.error) {+ try {+ await client.query('ROLLBACK');+ } catch (rollbackError) {+ discardClient = true;+ throw new AggregateError([error, rollbackError], 'Postgres transaction and rollback failed');+ }+ }+ if (acquired.error && acquired.error !== error) {+ throw new AggregateError([error, acquired.error], 'Postgres transaction and connection failed');+ }throw error;} finally {- client.release();+ client.release(discardClient || acquired === null || acquired.error !== null);}}@@ -125,7 +269,24 @@ class PostgresClient implements IPostgresClient {return this.config.kvTable ?? 'fluxer_kv';}+ private async withPool<T>(operation: (pool: Pool) => Promise<T>): Promise<T> {+ const pool = this.getPool();+ this.activeOperations += 1;+ try {+ return await operation(pool);+ } finally {+ this.activeOperations -= 1;+ if (this.activeOperations === 0) {+ this.resolveOperationsDrained?.();+ this.resolveOperationsDrained = null;+ }+ }+ }+private getPool(): Pool {+ if (this.disconnection !== null) {+ throw new Error('Postgres client is shutting down');+ }if (this.pool === null) {throw new Error('Postgres client is not connected. Call connect() first.');}@@ -133,35 +294,76 @@ class PostgresClient implements IPostgresClient {}}-function poolClientQueryable(client: PoolClient, preparedStatements: boolean): PostgresQueryable {- return {- query: <T extends QueryResultRow = QueryResultRow>(text: string, values: Array<unknown> = [], name?: string) =>- client.query<T>({text, values, name: preparedStatements ? name : undefined}),+async function runTransactionCallback<T>(+ client: PoolClient,+ acquired: AcquiredPostgresConnection,+ preparedStatements: boolean,+ fn: (client: PostgresQueryable) => Promise<T>,+): Promise<T> {+ let active = true;+ const queryable: PostgresQueryable = {+ query: async <TRow extends QueryResultRow = QueryResultRow>(+ text: string,+ values: Array<unknown> = [],+ name?: string,+ ) => {+ if (!active) throw new Error('Postgres transaction callback has already completed');+ if (acquired.error) throw acquired.error;+ return client.query<TRow>({text, values, name: preparedStatements ? name : undefined});+ },};-}--async function rollback(client: PoolClient): Promise<void> {try {- await client.query('ROLLBACK');- } catch {}+ return await fn(queryable);+ } finally {+ active = false;+ }}-export async function initPostgres(config: PostgresConfig): Promise<void> {- if (defaultClientState.client !== null) {- await defaultClientState.client.shutdown();+export async function initPostgres(+ config: PostgresConfig,+ onConnectionError: PostgresConnectionErrorReporter = reportConnectionError,+): Promise<void> {+ if (defaultClientState.initialization !== null) {+ throw new Error('Postgres initialization is already in progress');+ }+ if (defaultClientState.shutdown !== null) {+ throw new Error('Cannot initialize Postgres while it is shutting down');}- const client = new PostgresClient(config);+ const client = new PostgresClient(config, onConnectionError);+ defaultClientState.initialization = replaceDefaultClient(client).finally(() => {+ defaultClientState.initialization = null;+ });+ await defaultClientState.initialization;+}++async function replaceDefaultClient(client: PostgresClient): Promise<void> {+ const previousClient = defaultClientState.client;+ defaultClientState.client = null;+ await previousClient?.shutdown();await client.connect();defaultClientState.client = client;}export async function shutdownPostgres(): Promise<void> {- if (defaultClientState.client === null) return;- await defaultClientState.client.shutdown();+ if (defaultClientState.shutdown !== null) return defaultClientState.shutdown;+ if (defaultClientState.client === null && defaultClientState.initialization === null) return;+ defaultClientState.shutdown = closeDefaultClient().finally(() => {+ defaultClientState.shutdown = null;+ });+ await defaultClientState.shutdown;+}++async function closeDefaultClient(): Promise<void> {+ await defaultClientState.initialization;+ const client = defaultClientState.client;defaultClientState.client = null;+ await client?.shutdown();}export function getDefaultPostgresClient(): IPostgresClient {+ if (defaultClientState.shutdown !== null) {+ throw new Error('Default Postgres client is shutting down');+ }if (defaultClientState.client === null) {throw new Error('Postgres client is not initialized. Call initPostgres() first.');}diff --git a/fluxer_api/pkgs/rate_limit/src/RateLimitService.ts b/fluxer_api/pkgs/rate_limit/src/RateLimitService.tsindex 0c3cfb61b..ecc275cd9 100644--- a/fluxer_api/pkgs/rate_limit/src/RateLimitService.ts+++ b/fluxer_api/pkgs/rate_limit/src/RateLimitService.ts@@ -88,9 +88,8 @@ export class RateLimitService implements IRateLimitService {if (identifierPrefix.length === 0) {throw new Error('identifierPrefix must be non-empty');}- const sentinelKey = this.keyFactory.getIdentifierKey(`${identifierPrefix}\x00`);- const keyPrefix = sentinelKey.slice(0, -1);- const pattern = `${keyPrefix}*`;+ const keyPrefix = this.keyFactory.getIdentifierKey(identifierPrefix);+ const pattern = `${keyPrefix.replace(/[\\*?[\]]/g, '\\$&')}*`;let totalDeleted = 0;const batchSize = 256;while (true) {diff --git a/fluxer_api/pkgs/sms/src/providers/TwilioSmsProvider.ts b/fluxer_api/pkgs/sms/src/providers/TwilioSmsProvider.tsindex f57a7c45e..dd4536e63 100644--- a/fluxer_api/pkgs/sms/src/providers/TwilioSmsProvider.ts+++ b/fluxer_api/pkgs/sms/src/providers/TwilioSmsProvider.ts@@ -31,12 +31,10 @@ interface TwilioErrorResponse {message?: string;}-interface TwilioVerificationCheckResponse {- status?: string;-}--interface TwilioVerificationStartResponse {- channel?: string;+interface TwilioResponse {+ ok: boolean;+ status: number;+ body: unknown;}type TwilioCooldownScope = 'account' | 'phone' | 'account_and_phone';@@ -53,17 +51,17 @@ interface StartVerificationSentryContext extends Record<string, unknown> {}interface TwilioLookupV2Response {- valid?: boolean;- country_code?: string;+ valid: boolean;+ country_code?: string | null;line_type_intelligence?: {- type?: string;- carrier_name?: string;- error_code?: number;- };+ type?: string | null;+ carrier_name?: string | null;+ error_code?: number | null;+ } | null;sms_pumping_risk?: {- sms_pumping_risk_score?: number;- error_code?: number;- };+ sms_pumping_risk_score?: number | null;+ error_code?: number | null;+ } | null;}export interface TwilioSmsProviderConfig {@@ -82,6 +80,7 @@ interface TwilioSmsProviderDependencies {}const DEFAULT_LOOKUP_TIMEOUT_MS = 3000;+const VERIFY_TIMEOUT_MS = 10000;const KNOWN_LINE_TYPES: ReadonlySet<PhoneLineType> = new Set<PhoneLineType>(['mobile','landline',@@ -97,7 +96,45 @@ const KNOWN_LINE_TYPES: ReadonlySet<PhoneLineType> = new Set<PhoneLineType>(['unknown',]);-function normalizeLineType(raw: string | undefined): PhoneLineType | null {+function isRecord(value: unknown): value is Record<string, unknown> {+ return typeof value === 'object' && value !== null && !Array.isArray(value);+}++function isNullishString(value: unknown): value is string | null | undefined {+ return value == null || typeof value === 'string';+}++function isNullishInteger(value: unknown): value is number | null | undefined {+ return value == null || (typeof value === 'number' && Number.isSafeInteger(value));+}++function isTwilioLookupResponse(value: unknown): value is TwilioLookupV2Response {+ if (!isRecord(value) || typeof value.valid !== 'boolean' || !isNullishString(value.country_code)) return false;+ const line = value.line_type_intelligence;+ if (+ line != null &&+ (!isRecord(line) ||+ !isNullishString(line.type) ||+ !isNullishString(line.carrier_name) ||+ !isNullishInteger(line.error_code))+ ) {+ return false;+ }+ const risk = value.sms_pumping_risk;+ if (risk == null) return true;+ if (!isRecord(risk) || !isNullishInteger(risk.error_code)) return false;+ const score = risk.sms_pumping_risk_score;+ return isNullishInteger(score) && (score == null || (score >= 0 && score <= 100));+}++function parseTwilioError(value: unknown): TwilioErrorResponse | null {+ if (!isRecord(value)) return null;+ if (value.code !== undefined && (typeof value.code !== 'number' || !Number.isSafeInteger(value.code))) return null;+ if (value.message !== undefined && typeof value.message !== 'string') return null;+ return {code: value.code, message: value.message};+}++function normalizeLineType(raw: string | null | undefined): PhoneLineType | null {if (!raw) return null;return KNOWN_LINE_TYPES.has(raw as PhoneLineType) ? (raw as PhoneLineType) : 'unknown';}@@ -185,7 +222,7 @@ export class TwilioSmsProvider implements ISmsProvider {requestBody[`RateLimits[${key}]`] = value;}}- let response: Response;+ let response: TwilioResponse;try {response = await this.requestTwilio('Verifications', requestBody);} catch (error) {@@ -196,24 +233,23 @@ export class TwilioSmsProvider implements ISmsProvider {throw new SmsVerificationUnavailableError();}if (response.ok) {- let parsed: TwilioVerificationStartResponse | null = null;- try {- parsed = (await response.json()) as TwilioVerificationStartResponse;- } catch (error) {- this.logger.warn(- {- error: error instanceof Error ? error.message : String(error),- phone: maskPhoneNumber(phone),- channel: requestedChannel,- },- '[TwilioSmsProvider] Verification start response JSON parse failed',+ const parsed = response.body;+ if (+ !isRecord(parsed) ||+ !isNullishString(parsed.channel) ||+ (parsed.status !== undefined && parsed.status !== 'pending' && parsed.status !== 'approved')+ ) {+ this.logger.error(+ {phone: maskPhoneNumber(phone), status: response.status},+ '[TwilioSmsProvider] Invalid verification start response',);+ throw new SmsVerificationUnavailableError();}return {- channel: parsed?.channel ?? requestedChannel,+ channel: parsed.channel ?? requestedChannel,};}- const body = await this.parseErrorBody(response);+ const body = parseTwilioError(response.body);if (body?.code === TWILIO_INVALID_PHONE_ERROR_CODE) {throw new InvalidPhoneNumberError();}@@ -230,7 +266,7 @@ export class TwilioSmsProvider implements ISmsProvider {}async checkVerification(phone: string, code: string): Promise<boolean> {- let response: Response;+ let response: TwilioResponse;try {response = await this.requestTwilio('VerificationCheck', {To: phone,@@ -244,7 +280,7 @@ export class TwilioSmsProvider implements ISmsProvider {throw new SmsVerificationUnavailableError();}if (!response.ok) {- const body = await this.parseErrorBody(response);+ const body = parseTwilioError(response.body);const rateLimitError = this.createRateLimitError(response, body, 'VerificationCheck');if (rateLimitError) {throw rateLimitError;@@ -263,21 +299,26 @@ export class TwilioSmsProvider implements ISmsProvider {}return false;}- const body = (await response.json()) as TwilioVerificationCheckResponse;+ const body = response.body;+ if (!isRecord(body) || typeof body.status !== 'string') {+ this.logger.error(+ {phone: maskPhoneNumber(phone), status: response.status},+ '[TwilioSmsProvider] Invalid verification check response',+ );+ throw new SmsVerificationUnavailableError();+ }return body.status === 'approved';}async lookupPhone(phone: string): Promise<PhoneLookupResult | null> {const url = `${this.lookupApiUrl}/PhoneNumbers/${encodeURIComponent(phone)}?Fields=line_type_intelligence,sms_pumping_risk`;const auth = Buffer.from(`${this.config.accountSid}:${this.config.authToken}`).toString('base64');- const abort = new AbortController();- const timer = setTimeout(() => abort.abort(), this.lookupTimeoutMs);let response: Response;try {response = await this.fetchFn(url, {method: 'GET',headers: {Authorization: `Basic ${auth}`},- signal: abort.signal,+ signal: AbortSignal.timeout(this.lookupTimeoutMs),});} catch (error) {this.logger.warn(@@ -285,10 +326,14 @@ export class TwilioSmsProvider implements ISmsProvider {'[TwilioSmsProvider] Lookup request failed (fail-open)',);return null;- } finally {- clearTimeout(timer);}if (response.status === 404) {+ await response.body?.cancel().catch(() => {+ this.logger.warn(+ {status: response.status},+ '[TwilioSmsProvider] Failed to cancel discarded lookup response body',+ );+ });return {valid: false,lineType: null,@@ -310,9 +355,9 @@ export class TwilioSmsProvider implements ISmsProvider {);return null;}- let parsed: TwilioLookupV2Response;+ let parsed: unknown;try {- parsed = (await response.json()) as TwilioLookupV2Response;+ parsed = await response.json();} catch (error) {this.logger.warn({error: error instanceof Error ? error.message : String(error), phone: maskPhoneNumber(phone)},@@ -320,6 +365,10 @@ export class TwilioSmsProvider implements ISmsProvider {);return null;}+ if (!isTwilioLookupResponse(parsed)) {+ this.logger.warn({phone: maskPhoneNumber(phone)}, '[TwilioSmsProvider] Invalid lookup response (fail-open)');+ return null;+ }const countryCode = parsed.country_code ?? null;const carrierName = parsed.line_type_intelligence?.carrier_name ?? null;const ltiErrorCode = parsed.line_type_intelligence?.error_code ?? null;@@ -336,36 +385,40 @@ export class TwilioSmsProvider implements ISmsProvider {'[TwilioSmsProvider] Lookup sms_pumping_risk reported error_code',);}- const rawScore = parsed.sms_pumping_risk?.sms_pumping_risk_score;- const smsPumpingRiskScore = typeof rawScore === 'number' && Number.isFinite(rawScore) ? rawScore : null;return {- valid: parsed.valid !== false,+ valid: parsed.valid,lineType: normalizeLineType(parsed.line_type_intelligence?.type),countryCode,carrierName,- smsPumpingRiskScore,+ smsPumpingRiskScore: parsed.sms_pumping_risk?.sms_pumping_risk_score ?? null,};}private async requestTwilio(endpoint: 'Verifications' | 'VerificationCheck',body: Record<string, string>,- ): Promise<Response> {+ ): Promise<TwilioResponse> {const url = `${this.verifyApiUrl}/Services/${this.config.verifyServiceSid}/${endpoint}`;const auth = Buffer.from(`${this.config.accountSid}:${this.config.authToken}`).toString('base64');- return this.fetchFn(url, {+ const response = await this.fetchFn(url, {method: 'POST',headers: {Authorization: `Basic ${auth}`,'Content-Type': 'application/x-www-form-urlencoded',},body: new URLSearchParams(body).toString(),+ signal: AbortSignal.timeout(VERIFY_TIMEOUT_MS),+ });+ const parsed: unknown = await response.json().catch((error: unknown) => {+ if (response.ok) throw error;+ return null;});+ return {ok: response.ok, status: response.status, body: parsed};}private async parseErrorBody(response: Response): Promise<TwilioErrorResponse | null> {try {- return (await response.json()) as TwilioErrorResponse;+ return parseTwilioError(await response.json());} catch {return null;}diff --git a/fluxer_api/pkgs/worker/src/contracts/WorkerTask.ts b/fluxer_api/pkgs/worker/src/contracts/WorkerTask.tsindex 4ae2ae1cc..5f93c5e1f 100644--- a/fluxer_api/pkgs/worker/src/contracts/WorkerTask.ts+++ b/fluxer_api/pkgs/worker/src/contracts/WorkerTask.ts@@ -3,9 +3,14 @@import type {LoggerInterface} from '@fluxer/logger/src/LoggerInterface';import type {WorkerJobOptions, WorkerJobPayload} from '@pkgs/worker/src/contracts/WorkerTypes';+export interface WorkerTaskAttempt {+ readonly isLastAttempt: boolean;+}+export interface WorkerTaskHelpers {logger: LoggerInterface;jobId: bigint;+ attempt?: WorkerTaskAttempt;addJob: <TPayload extends WorkerJobPayload = WorkerJobPayload>(taskType: string,payload: TPayload,diff --git a/fluxer_api/pkgs/worker/src/providers/HttpWorkerQueue.ts b/fluxer_api/pkgs/worker/src/providers/HttpWorkerQueue.tsindex e8a64484c..d8e078f74 100644--- a/fluxer_api/pkgs/worker/src/providers/HttpWorkerQueue.ts+++ b/fluxer_api/pkgs/worker/src/providers/HttpWorkerQueue.ts@@ -24,35 +24,31 @@ export class HttpWorkerQueue implements IQueueProvider {this.tracing = options.tracing;}- private createTimeoutController(): AbortController {+ private async withResponse<T>(+ input: string | URL,+ init: RequestInit,+ consume: (response: Response) => Promise<T>,+ ): Promise<T> {const controller = new AbortController();const timeoutId = setTimeout(() => controller.abort(), this.timeoutMs);- (- controller as {- timeoutId?: NodeJS.Timeout;- }- ).timeoutId = timeoutId;- return controller;- }-- private async fetchWithTimeout(input: string | URL, init?: RequestInit): Promise<Response> {- const controller = this.createTimeoutController();try {const response = await fetch(input, {...init,signal: controller.signal,});- return response;+ return await consume(response);} finally {- const timeoutId = (- controller as {- timeoutId?: NodeJS.Timeout;- }- ).timeoutId;- if (timeoutId !== undefined) {- clearTimeout(timeoutId);- }+ clearTimeout(timeoutId);+ controller.abort();+ }+ }++ private async requireSuccess(response: Response, action: string): Promise<void> {+ if (response.ok) {+ return;}+ const text = await response.text();+ throw new Error(`Failed to ${action}: ${response.status} ${text}`);}private async withOptionalSpan<T>(@@ -100,20 +96,22 @@ export class HttpWorkerQueue implements IQueueProvider {run_at: options?.runAt?.toISOString(),max_attempts: options?.maxAttempts ?? 5,};- const response = await this.fetchWithTimeout(`${this.baseUrl}/enqueue`, {- method: 'POST',- headers: {'Content-Type': 'application/json'},- body: JSON.stringify(body),- });- if (!response.ok) {- const text = await response.text();- throw new Error(`Failed to enqueue job: ${response.status} ${text}`);- }- const jobIdResult = (await response.json()) as {- job_id: string;- };- this.setSpanAttributes({'queue.job_id': jobIdResult.job_id});- return jobIdResult.job_id;+ return this.withResponse(+ `${this.baseUrl}/enqueue`,+ {+ method: 'POST',+ headers: {'Content-Type': 'application/json'},+ body: JSON.stringify(body),+ },+ async (response) => {+ await this.requireSuccess(response, 'enqueue job');+ const jobIdResult = (await response.json()) as {+ job_id: string;+ };+ this.setSpanAttributes({'queue.job_id': jobIdResult.job_id});+ return jobIdResult.job_id;+ },+ );},);}@@ -134,34 +132,32 @@ export class HttpWorkerQueue implements IQueueProvider {url.searchParams.set('task_types', taskTypes.join(','));url.searchParams.set('limit', limit.toString());url.searchParams.set('wait_time_ms', '0');- const response = await this.fetchWithTimeout(url.toString(), {method: 'GET'});- if (!response.ok) {- const text = await response.text();- throw new Error(`Failed to dequeue job: ${response.status} ${text}`);- }- this.addSpanEvent('dequeue.parse_response');- const jobs = (await response.json()) as Array<LeasedQueueJob>;- const jobCount = jobs?.length ?? 0;- this.setSpanAttributes({- 'queue.jobs_returned': jobCount,- 'queue.empty': jobCount === 0,+ return this.withResponse(url, {method: 'GET'}, async (response) => {+ await this.requireSuccess(response, 'dequeue job');+ this.addSpanEvent('dequeue.parse_response');+ const jobs = (await response.json()) as Array<LeasedQueueJob>;+ const jobCount = jobs?.length ?? 0;+ this.setSpanAttributes({+ 'queue.jobs_returned': jobCount,+ 'queue.empty': jobCount === 0,+ });+ this.addSpanEvent('dequeue.complete');+ return jobs ?? [];});- this.addSpanEvent('dequeue.complete');- return jobs ?? [];},);}async upsertCron(id: string, taskType: string, payload: WorkerJobPayload, cronExpression: string): Promise<void> {- const response = await this.fetchWithTimeout(`${this.baseUrl}/cron`, {- method: 'POST',- headers: {'Content-Type': 'application/json'},- body: JSON.stringify({id, task_type: taskType, payload, cron_expression: cronExpression}),- });- if (!response.ok) {- const text = await response.text();- throw new Error(`Failed to upsert cron job: ${response.status} ${text}`);- }+ await this.withResponse(+ `${this.baseUrl}/cron`,+ {+ method: 'POST',+ headers: {'Content-Type': 'application/json'},+ body: JSON.stringify({id, task_type: taskType, payload, cron_expression: cronExpression}),+ },+ (response) => this.requireSuccess(response, 'upsert cron job'),+ );}async complete(receipt: string): Promise<void> {@@ -172,17 +168,16 @@ export class HttpWorkerQueue implements IQueueProvider {'queue.receipt': receipt,},},- async () => {- const response = await this.fetchWithTimeout(`${this.baseUrl}/ack`, {- method: 'POST',- headers: {'Content-Type': 'application/json'},- body: JSON.stringify({receipt}),- });- if (!response.ok) {- const text = await response.text();- throw new Error(`Failed to complete job: ${response.status} ${text}`);- }- },+ async () =>+ this.withResponse(+ `${this.baseUrl}/ack`,+ {+ method: 'POST',+ headers: {'Content-Type': 'application/json'},+ body: JSON.stringify({receipt}),+ },+ (response) => this.requireSuccess(response, 'complete job'),+ ),);}@@ -195,48 +190,45 @@ export class HttpWorkerQueue implements IQueueProvider {'queue.error_message': error,},},- async () => {- const response = await this.fetchWithTimeout(`${this.baseUrl}/nack`, {- method: 'POST',- headers: {'Content-Type': 'application/json'},- body: JSON.stringify({receipt, error}),- });- if (!response.ok) {- const text = await response.text();- throw new Error(`Failed to fail job: ${response.status} ${text}`);- }- },+ async () =>+ this.withResponse(+ `${this.baseUrl}/nack`,+ {+ method: 'POST',+ headers: {'Content-Type': 'application/json'},+ body: JSON.stringify({receipt, error}),+ },+ (response) => this.requireSuccess(response, 'fail job'),+ ),);}async cancelJob(jobId: string): Promise<boolean> {- const response = await this.fetchWithTimeout(`${this.baseUrl}/job/${jobId}`, {- method: 'DELETE',- });- if (!response.ok) {- const text = await response.text();- if (response.status === 404) {- return false;+ return this.withResponse(`${this.baseUrl}/job/${jobId}`, {method: 'DELETE'}, async (response) => {+ if (!response.ok) {+ const text = await response.text();+ if (response.status === 404) {+ return false;+ }+ throw new Error(`Failed to cancel job: ${response.status} ${text}`);}- throw new Error(`Failed to cancel job: ${response.status} ${text}`);- }- const result = (await response.json()) as {- success: boolean;- };- return result.success ?? true;+ const result = (await response.json()) as {+ success: boolean;+ };+ return result.success ?? true;+ });}async retryDeadLetterJob(jobId: string): Promise<boolean> {- const response = await this.fetchWithTimeout(`${this.baseUrl}/retry/${jobId}`, {- method: 'POST',- });- if (!response.ok) {- const text = await response.text();- if (response.status === 404) {- return false;+ return this.withResponse(`${this.baseUrl}/retry/${jobId}`, {method: 'POST'}, async (response) => {+ if (!response.ok) {+ const text = await response.text();+ if (response.status === 404) {+ return false;+ }+ throw new Error(`Failed to retry job: ${response.status} ${text}`);}- throw new Error(`Failed to retry job: ${response.status} ${text}`);- }- return true;+ return true;+ });}}diff --git a/fluxer_api/src/App.ts b/fluxer_api/src/App.tsindex 22c8ff44a..c297bcf83 100644--- a/fluxer_api/src/App.ts+++ b/fluxer_api/src/App.ts@@ -4,7 +4,6 @@ import {createAPIApp} from '@app/api/App';import {buildAPIServerOptions, initializeConfig} from '@app/api/Config';import {initializeLogger} from '@app/api/Logger';import {Config} from '@app/Config';-import {shutdownInstrumentation} from '@app/Instrument';import {Logger} from '@app/Logger';import {createServer, setupGracefulShutdown} from '@fluxer/hono/src/Server';@@ -40,7 +39,6 @@ async function main(): Promise<void> {async () => {await closeHttpServer(server);await shutdown();- await shutdownInstrumentation();},{logger: Logger, timeoutMs: 30000},);diff --git a/fluxer_api/src/AppEntrypoint.ts b/fluxer_api/src/AppEntrypoint.tsindex 1f565e624..c32f75f70 100644--- a/fluxer_api/src/AppEntrypoint.ts+++ b/fluxer_api/src/AppEntrypoint.ts@@ -1,4 +1,3 @@// SPDX-License-Identifier: AGPL-3.0-or-later-import '@app/Instrument';import '@app/App';diff --git a/fluxer_api/src/Instrument.ts b/fluxer_api/src/Instrument.tsdeleted file mode 100644index 616e9bcc0..000000000--- a/fluxer_api/src/Instrument.ts+++ /dev/null@@ -1,9 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {Config} from '@app/Config';-import {createServiceInstrumentation} from '@pkgs/initialization/src/CreateServiceInstrumentation';--export const shutdownInstrumentation = createServiceInstrumentation({- serviceName: 'fluxer-api',- config: Config,-});diff --git a/fluxer_api/src/WorkerEntrypoint.ts b/fluxer_api/src/WorkerEntrypoint.tsindex d66e65b40..6d249b9c3 100644--- a/fluxer_api/src/WorkerEntrypoint.ts+++ b/fluxer_api/src/WorkerEntrypoint.ts@@ -1,6 +1,5 @@// SPDX-License-Identifier: AGPL-3.0-or-later-import '@app/Instrument';import {initializeConfig} from '@app/api/Config';import {initializeLogger} from '@app/api/Logger';import {startWorkerMain} from '@app/api/worker/WorkerMain';diff --git a/fluxer_api/src/api/Tables.ts b/fluxer_api/src/api/Tables.tsindex 0a99d6e8e..122c76a1f 100644--- a/fluxer_api/src/api/Tables.ts+++ b/fluxer_api/src/api/Tables.ts@@ -4,7 +4,9 @@ import type {AttachmentID, ChannelID, GuildID, MemeID, PasswordResetToken, UserIimport {defineTable} from './database/CassandraTableDsl';import {ADMIN_ARCHIVE_COLUMNS,+ ADMIN_ARCHIVE_INDEX_COLUMNS,ADMIN_AUDIT_LOG_COLUMNS,+ type AdminArchiveIndexRow,type AdminArchiveRow,type AdminAuditLogRow,BANNED_AVATAR_HASH_COLUMNS,@@ -146,7 +148,7 @@ import {WEBHOOK_COLUMNS,type WebhookRow,} from './database/types/ChannelTypes';-import {USER_CONNECTION_COLUMNS, type UserConnectionRow} from './database/types/ConnectionTypes';+import {USER_CONNECTION_STORAGE_COLUMNS, type UserConnectionStorageRow} from './database/types/ConnectionTypes';import {NCMEC_ATTACHMENT_SUBMISSION_COLUMNS,NCMEC_USER_WORKFLOW_COLUMNS,@@ -427,9 +429,9 @@ export const UserContactChangeLogs = defineTable<UserContactChangeLogRow, 'user_columns: USER_CONTACT_CHANGE_LOG_COLUMNS,primaryKey: ['user_id', 'event_id'],});-export const UserConnections = defineTable<UserConnectionRow, 'user_id' | 'connection_type' | 'connection_id'>({+export const UserConnections = defineTable<UserConnectionStorageRow, 'user_id' | 'connection_type' | 'connection_id'>({name: 'user_connections',- columns: USER_CONNECTION_COLUMNS,+ columns: USER_CONNECTION_STORAGE_COLUMNS,primaryKey: ['user_id', 'connection_type', 'connection_id'],partitionKey: ['user_id'],});@@ -739,14 +741,14 @@ export const AdminArchivesBySubject = defineTable<AdminArchiveRow, 'subject_typecolumns: ADMIN_ARCHIVE_COLUMNS,primaryKey: ['subject_type', 'subject_id', 'archive_id'],});-export const AdminArchivesByRequester = defineTable<AdminArchiveRow, 'requested_by' | 'archive_id'>({+export const AdminArchivesByRequester = defineTable<AdminArchiveIndexRow, 'requested_by' | 'archive_id'>({name: 'admin_archives_by_requester',- columns: ADMIN_ARCHIVE_COLUMNS,+ columns: ADMIN_ARCHIVE_INDEX_COLUMNS,primaryKey: ['requested_by', 'archive_id'],});-export const AdminArchivesByType = defineTable<AdminArchiveRow, 'subject_type' | 'archive_id'>({+export const AdminArchivesByType = defineTable<AdminArchiveIndexRow, 'subject_type' | 'archive_id'>({name: 'admin_archives_by_type',- columns: ADMIN_ARCHIVE_COLUMNS,+ columns: ADMIN_ARCHIVE_INDEX_COLUMNS,primaryKey: ['subject_type', 'archive_id'],});export const AdminAuditLogs = defineTable<AdminAuditLogRow, 'log_id'>({diff --git a/fluxer_api/src/api/admin/controllers/InstanceConfigAdminController.ts b/fluxer_api/src/api/admin/controllers/InstanceConfigAdminController.tsindex 7bb28bbbc..d795239a8 100644--- a/fluxer_api/src/api/admin/controllers/InstanceConfigAdminController.ts+++ b/fluxer_api/src/api/admin/controllers/InstanceConfigAdminController.ts@@ -548,6 +548,7 @@ export function InstanceConfigAdminController(app: HonoApp) {async (ctx) => {const userId = ctx.req.valid('param').user_id.toString();const decision = ctx.req.valid('json').status === 'approved' ? 'approve' : 'reject';+ await instanceConfigRepository.getPendingRegistrations();await updatePendingRegistrationUser(ctx, userId, decision);await instanceConfigRepository.removePendingRegistration(userId);return ctx.json(await buildInstanceConfigResponse());@@ -626,12 +627,11 @@ async function applyInstancePolicyUpdate(patch.deferred_phone_gate_member_threshold = policy.deferred_phone_gate.member_threshold;}}- if (Object.keys(patch).length > 0) {+ if (patch.premium_mode !== undefined) {+ await ctx.get('limitConfigService').updatePolicyConfig(patch);+ } else if (Object.keys(patch).length > 0) {await instanceConfigRepository.setInstancePolicyConfig(patch);}- if (policy.premium_mode !== undefined && policy.premium_mode !== current.premium_mode) {- await ctx.get('limitConfigService').reloadForPolicyChange();- }}async function updatePendingRegistrationUser(diff --git a/fluxer_api/src/api/admin/controllers/LimitConfigAdminController.ts b/fluxer_api/src/api/admin/controllers/LimitConfigAdminController.tsindex a611e9bda..eead8d7f0 100644--- a/fluxer_api/src/api/admin/controllers/LimitConfigAdminController.ts+++ b/fluxer_api/src/api/admin/controllers/LimitConfigAdminController.ts@@ -1,16 +1,10 @@// SPDX-License-Identifier: AGPL-3.0-or-laterimport {AdminACLs} from '@fluxer/constants/src/AdminACLs';-import {- LIMIT_CATEGORY_LABELS,- LIMIT_KEY_METADATA,- LIMIT_KEYS,- type LimitKey,-} from '@fluxer/constants/src/LimitConfigMetadata';-import type {LimitConfigSnapshot, LimitRule} from '@fluxer/limits/src/LimitTypes';+import {LIMIT_CATEGORY_LABELS, LIMIT_KEY_METADATA, LIMIT_KEYS} from '@fluxer/constants/src/LimitConfigMetadata';+import type {LimitConfigSnapshot} from '@fluxer/limits/src/LimitTypes';import {LimitConfigGetResponse, LimitConfigUpdateRequest} from '@fluxer/schema/src/domains/admin/AdminSchemas';import {Config} from '../../Config';-import {createDefaultLimitConfig} from '../../constants/LimitConfig';import type {LimitConfigService} from '../../limits/LimitConfigService';import {requireAdminACL} from '../../middleware/AdminMiddleware';import {RateLimitMiddleware} from '../../middleware/RateLimitMiddleware';@@ -19,77 +13,20 @@ import {RateLimitConfigs} from '../../RateLimitConfig';import type {HonoApp} from '../../types/HonoEnv';import {Validator} from '../../Validator';-function formatConfig(config: LimitConfigSnapshot) {- const defaults = createDefaultLimitConfig({selfHosted: Config.instance.selfHosted});- const defaultLimitsMap: Record<string, Record<LimitKey, number>> = {};- for (const rule of defaults.rules) {- defaultLimitsMap[rule.id] = rule.limits as Record<LimitKey, number>;- }+function formatConfig(service: LimitConfigService) {+ const config = service.getConfigSnapshot();+ const defaults = service.getDefaultConfigSnapshot();return {limit_config: config,limit_config_json: JSON.stringify(config, null, 2),self_hosted: Config.instance.selfHosted,- defaults: defaultLimitsMap,+ defaults: Object.fromEntries(defaults.rules.map((rule) => [rule.id, rule.limits])),metadata: LIMIT_KEY_METADATA,categories: LIMIT_CATEGORY_LABELS,limit_keys: LIMIT_KEYS,};}-function trackModifiedFields(config: LimitConfigSnapshot): LimitConfigSnapshot {- const defaults = createDefaultLimitConfig({selfHosted: Config.instance.selfHosted});- const defaultRulesMap = buildRulesMap(defaults.rules);- const rulesWithTracking = config.rules.map((rule) => trackRuleModifiedFields(rule, defaultRulesMap));- return {- ...config,- rules: rulesWithTracking,- };-}--function buildRulesMap(rules: Array<LimitRule>): Map<string, LimitRule> {- const map = new Map<string, LimitRule>();- for (const rule of rules) {- map.set(rule.id, rule);- }- return map;-}--function trackRuleModifiedFields(- rule: LimitRule,- defaultRulesMap: Map<string, LimitRule>,-): LimitRule & {- modifiedFields?: Array<LimitKey>;-} {- const defaultRule = defaultRulesMap.get(rule.id);- const fallbackDefault = defaultRule ?? defaultRulesMap.get('default');- if (!fallbackDefault) {- return {- ...rule,- modifiedFields: Object.keys(rule.limits) as Array<LimitKey>,- };- }- const modifiedFields = findModifiedLimits(rule.limits, fallbackDefault.limits);- return {- ...rule,- modifiedFields: modifiedFields.length > 0 ? modifiedFields : undefined,- };-}--function findModifiedLimits(- currentLimits: Partial<Record<LimitKey, number>>,- defaultLimits: Partial<Record<LimitKey, number>>,-): Array<LimitKey> {- const modified: Array<LimitKey> = [];- for (const key of LIMIT_KEYS) {- const currentValue = currentLimits[key];- const defaultValue = defaultLimits[key];- if (currentValue !== undefined && currentValue !== defaultValue) {- modified.push(key);- }- }- return modified;-}-export function LimitConfigAdminController(app: HonoApp) {app.get('/admin/limit-config',@@ -107,8 +44,7 @@ export function LimitConfigAdminController(app: HonoApp) {}),async (ctx) => {const limitConfigService = ctx.get('limitConfigService') as LimitConfigService;- const snapshot = limitConfigService.getConfigSnapshot();- return ctx.json(formatConfig(snapshot));+ return ctx.json(formatConfig(limitConfigService));},);app.put(@@ -133,9 +69,8 @@ export function LimitConfigAdminController(app: HonoApp) {...data.limit_config,traitDefinitions: data.limit_config.traitDefinitions ?? [],};- const withTracking = trackModifiedFields(normalized);- await limitConfigService.updateConfig(withTracking);- return ctx.json(formatConfig(limitConfigService.getConfigSnapshot()));+ await limitConfigService.updateConfig(normalized);+ return ctx.json(formatConfig(limitConfigService));},);}diff --git a/fluxer_api/src/api/admin/models/AdminArchiveModel.ts b/fluxer_api/src/api/admin/models/AdminArchiveModel.tsindex 8325b46fd..0dc0d6583 100644--- a/fluxer_api/src/api/admin/models/AdminArchiveModel.ts+++ b/fluxer_api/src/api/admin/models/AdminArchiveModel.ts@@ -9,9 +9,11 @@ export class AdminArchive {archiveId: bigint;requestedBy: bigint;requestedAt: Date;+ attemptId: string | null;startedAt: Date | null;completedAt: Date | null;failedAt: Date | null;+ terminalFailedAt: Date | null;storageKey: string | null;fileSize: bigint | null;progressPercent: number;@@ -26,9 +28,11 @@ export class AdminArchive {this.archiveId = row.archive_id;this.requestedBy = row.requested_by;this.requestedAt = row.requested_at;+ this.attemptId = row.attempt_id ?? null;this.startedAt = row.started_at ?? null;this.completedAt = row.completed_at ?? null;this.failedAt = row.failed_at ?? null;+ this.terminalFailedAt = row.terminal_failed_at ?? null;this.storageKey = row.storage_key ?? null;this.fileSize = row.file_size ?? null;this.progressPercent = row.progress_percent;@@ -45,9 +49,11 @@ export class AdminArchive {archive_id: this.archiveId,requested_by: this.requestedBy,requested_at: this.requestedAt,+ attempt_id: this.attemptId,started_at: this.startedAt,completed_at: this.completedAt,failed_at: this.failedAt,+ terminal_failed_at: this.terminalFailedAt,storage_key: this.storageKey,file_size: this.fileSize,progress_percent: this.progressPercent,diff --git a/fluxer_api/src/api/admin/models/UserTypes.ts b/fluxer_api/src/api/admin/models/UserTypes.tsindex bd0679974..109bf2588 100644--- a/fluxer_api/src/api/admin/models/UserTypes.ts+++ b/fluxer_api/src/api/admin/models/UserTypes.ts@@ -1,37 +1,12 @@// SPDX-License-Identifier: AGPL-3.0-or-later-import dns from 'node:dns';import {AdminACLs} from '@fluxer/constants/src/AdminACLs';import {DEFERRED_PHONE_ON_COMMUNITY_JOIN} from '@fluxer/constants/src/UserConstants';import type {UserAdminResponse} from '@fluxer/schema/src/domains/admin/AdminUserSchemas';import type {ICacheService} from '@pkgs/cache/src/ICacheService';import {formatGeoipLocation} from '@pkgs/geoip/src/GeoipLookup';-import {seconds} from 'itty-time';import type {User} from '../../models/User';-import {lookupGeoip} from '../../utils/IpUtils';--const REVERSE_DNS_CACHE_TTL_SECONDS = seconds('1 day');--async function reverseDnsLookup(ip: string, cacheService?: ICacheService): Promise<string | null> {- const cacheKey = `reverse-dns:${ip}`;- if (cacheService) {- const cached = await cacheService.get<string | null>(cacheKey);- if (cached !== null) {- return cached === '' ? null : cached;- }- }- let result: string | null = null;- try {- const hostnames = await dns.promises.reverse(ip);- result = hostnames[0] ?? null;- } catch {- result = null;- }- if (cacheService) {- await cacheService.set(cacheKey, result ?? '', REVERSE_DNS_CACHE_TTL_SECONDS);- }- return result;-}+import {getIpAddressReverse, lookupGeoip} from '../../utils/IpUtils';function hasAcl(acls: ReadonlySet<string>, acl: string): boolean {return acls.has(acl) || acls.has(AdminACLs.WILDCARD);@@ -46,7 +21,7 @@ export async function mapUserToAdminResponse(const canViewDob = !acls || hasAcl(acls, AdminACLs.USER_VIEW_DOB);const canViewIp = !acls || hasAcl(acls, AdminACLs.USER_VIEW_IP);const lastActiveIpReverse =- canViewIp && user.lastActiveIp ? await reverseDnsLookup(user.lastActiveIp, cacheService) : null;+ canViewIp && user.lastActiveIp ? await getIpAddressReverse(user.lastActiveIp, cacheService) : null;let lastActiveLocation: string | null = null;if (canViewIp && user.lastActiveIp) {try {diff --git a/fluxer_api/src/api/admin/repositories/AdminApiKeyRepository.ts b/fluxer_api/src/api/admin/repositories/AdminApiKeyRepository.tsindex bdab0e892..5be34f743 100644--- a/fluxer_api/src/api/admin/repositories/AdminApiKeyRepository.ts+++ b/fluxer_api/src/api/admin/repositories/AdminApiKeyRepository.ts@@ -3,7 +3,7 @@import type {UserID} from '../../BrandedTypes';import {BatchBuilder, fetchMany, fetchManyInChunks, fetchOne, upsertOne} from '../../database/CassandraQueryExecution';import {Db} from '../../database/CassandraTypes';-import type {AdminApiKeyRow} from '../../database/types/AdminAuthTypes';+import type {AdminApiKeyByCreatorRow, AdminApiKeyRow} from '../../database/types/AdminAuthTypes';import {AdminApiKey} from '../../models/AdminApiKey';import {AdminApiKeys, AdminApiKeysByCreator} from '../../Tables';import {hashPassword} from '../../utils/PasswordUtils';@@ -29,39 +29,24 @@ export class AdminApiKeyRepository implements IAdminApiKeyRepository {version: 1,acls: data.acls,};+ const creatorRow: AdminApiKeyByCreatorRow = {+ created_by_user_id: row.created_by_user_id,+ key_id: row.key_id,+ created_at: row.created_at,+ name: row.name,+ expires_at: row.expires_at,+ last_used_at: row.last_used_at,+ version: row.version,+ acls: row.acls,+ };const batch = new BatchBuilder();if (data.expiresAt) {const ttlSeconds = computeTtlSeconds(data.expiresAt);batch.addPrepared(AdminApiKeys.insertWithTtl(row, ttlSeconds));- batch.addPrepared(- AdminApiKeysByCreator.insertWithTtl(- {- created_by_user_id: row.created_by_user_id,- key_id: row.key_id,- created_at: row.created_at,- name: row.name,- expires_at: row.expires_at,- last_used_at: row.last_used_at,- version: row.version,- acls: row.acls,- },- ttlSeconds,- ),- );+ batch.addPrepared(AdminApiKeysByCreator.insertWithTtl(creatorRow, ttlSeconds));} else {batch.addPrepared(AdminApiKeys.upsertAll(row));- batch.addPrepared(- AdminApiKeysByCreator.upsertAll({- created_by_user_id: row.created_by_user_id,- key_id: row.key_id,- created_at: row.created_at,- name: row.name,- expires_at: row.expires_at,- last_used_at: row.last_used_at,- version: row.version,- acls: row.acls,- }),- );+ batch.addPrepared(AdminApiKeysByCreator.upsertAll(creatorRow));}await batch.execute();return new AdminApiKey(row);@@ -133,7 +118,7 @@ export class AdminApiKeyRepository implements IAdminApiKeyRepository {async updateLastUsed(keyId: bigint, expiresAt: Date | null): Promise<void> {if (expiresAt) {- const remainingTtl = Math.max(Math.floor((expiresAt.getTime() - Date.now()) / 1000), 1);+ const remainingTtl = computeTtlSeconds(expiresAt);await upsertOne(AdminApiKeys.patchByPkWithTtl({key_id: keyId}, {last_used_at: Db.set(new Date())}, remainingTtl));} else {await upsertOne(AdminApiKeys.patchByPk({key_id: keyId}, {last_used_at: Db.set(new Date())}));diff --git a/fluxer_api/src/api/admin/repositories/AdminArchiveRepository.ts b/fluxer_api/src/api/admin/repositories/AdminArchiveRepository.tsindex e28a48244..fd0b7fbcb 100644--- a/fluxer_api/src/api/admin/repositories/AdminArchiveRepository.ts+++ b/fluxer_api/src/api/admin/repositories/AdminArchiveRepository.ts@@ -1,20 +1,45 @@// SPDX-License-Identifier: AGPL-3.0-or-later+import assert from 'node:assert/strict';+import {randomUUID} from 'node:crypto';import type {ArchiveSubjectType} from '@fluxer/schema/src/domains/admin/AdminArchiveSchemas';import {ms} from 'itty-time';-import {BatchBuilder, fetchMany, fetchOne} from '../../database/CassandraQueryExecution';-import {Db} from '../../database/CassandraTypes';-import type {AdminArchiveRow} from '../../database/types/AdminArchiveTypes';+import {ArchiveAttemptSupersededError} from '../../archive/ArchiveAttemptSupersededError';+import {BatchBuilder, executeConditional, fetchMany, fetchOne} from '../../database/CassandraQueryExecution';+import {Db, type DbOp} from '../../database/CassandraTypes';+import {+ ADMIN_ARCHIVE_INDEX_COLUMNS,+ type AdminArchiveIndexRow,+ type AdminArchiveRow,+} from '../../database/types/AdminArchiveTypes';import {Logger} from '../../Logger';import {AdminArchivesByRequester, AdminArchivesBySubject, AdminArchivesByType} from '../../Tables';+import {mapWithConcurrency} from '../../utils/ConcurrencyUtils';import {AdminArchive} from '../models/AdminArchiveModel';const RETENTION_DAYS = 365;const DEFAULT_RETENTION_MS = ms(`${RETENTION_DAYS} days`);+const ARCHIVE_READ_CONCURRENCY = 10;-function computeTtlSeconds(expiresAt: Date): number {- const diffSeconds = Math.floor((expiresAt.getTime() - Date.now()) / 1000);- return Math.max(diffSeconds, 1);+interface AdminArchivePatch {+ completed_at?: DbOp<Date>;+ failed_at?: DbOp<Date>;+ terminal_failed_at?: DbOp<Date>;+ storage_key?: DbOp<string>;+ file_size?: DbOp<bigint>;+ progress_percent?: DbOp<number>;+ progress_step?: DbOp<string>;+ error_message?: DbOp<string>;+ download_url_expires_at?: DbOp<Date>;+}++function computeTtlSeconds(expiresAt: Date | null): number {+ if (expiresAt === null || !Number.isFinite(expiresAt.getTime())) {+ throw new Error('Admin archive has no valid expiry');+ }+ const ttlSeconds = Math.floor((expiresAt.getTime() - Date.now()) / 1000);+ if (ttlSeconds < 1) throw new Error('Admin archive has expired');+ return ttlSeconds;}function filterExpired(rows: Array<AdminArchiveRow>, includeExpired: boolean): Array<AdminArchiveRow> {@@ -24,163 +49,113 @@ function filterExpired(rows: Array<AdminArchiveRow>, includeExpired: boolean): A}export class AdminArchiveRepository {- private ensureExpiry(archive: AdminArchive): AdminArchive {- if (!archive.expiresAt) {- archive.expiresAt = new Date(Date.now() + DEFAULT_RETENTION_MS);- }- return archive;- }-async create(archive: AdminArchive): Promise<void> {- const withExpiry = this.ensureExpiry(archive);- const row = withExpiry.toRow();- const ttlSeconds = computeTtlSeconds(withExpiry.expiresAt!);- const batch = new BatchBuilder();- batch.addPrepared(- AdminArchivesBySubject.insertWithTtlParam({...row, ttl_seconds: ttlSeconds} as AdminArchiveRow, 'ttl_seconds'),- );- batch.addPrepared(- AdminArchivesByRequester.insertWithTtlParam({...row, ttl_seconds: ttlSeconds} as AdminArchiveRow, 'ttl_seconds'),+ archive.expiresAt ??= new Date(archive.requestedAt.getTime() + DEFAULT_RETENTION_MS);+ const row = archive.toRow();+ const applied = await executeConditional(+ AdminArchivesBySubject.insertIfNotExistsWithTtl(row, computeTtlSeconds(row.expires_at)),);- batch.addPrepared(- AdminArchivesByType.insertWithTtlParam({...row, ttl_seconds: ttlSeconds} as AdminArchiveRow, 'ttl_seconds'),- );- await batch.execute();- Logger.debug(- {subjectType: withExpiry.subjectType, subjectId: withExpiry.subjectId, archiveId: withExpiry.archiveId},- 'Created admin archive record',- );- }-- async update(archive: AdminArchive): Promise<void> {- const withExpiry = this.ensureExpiry(archive);- const row = withExpiry.toRow();- const ttlSeconds = computeTtlSeconds(withExpiry.expiresAt!);+ if (!applied) {+ throw new Error(`Admin archive ${row.archive_id} for ${row.subject_type} ${row.subject_id} already exists`);+ }+ const indexRow: AdminArchiveIndexRow = {+ subject_type: row.subject_type,+ subject_id: row.subject_id,+ archive_id: row.archive_id,+ requested_by: row.requested_by,+ };+ const ttlSeconds = computeTtlSeconds(row.expires_at);const batch = new BatchBuilder();- batch.addPrepared(- AdminArchivesBySubject.insertWithTtlParam({...row, ttl_seconds: ttlSeconds} as AdminArchiveRow, 'ttl_seconds'),- );- batch.addPrepared(- AdminArchivesByRequester.insertWithTtlParam({...row, ttl_seconds: ttlSeconds} as AdminArchiveRow, 'ttl_seconds'),- );- batch.addPrepared(- AdminArchivesByType.insertWithTtlParam({...row, ttl_seconds: ttlSeconds} as AdminArchiveRow, 'ttl_seconds'),- );+ batch.addPrepared(AdminArchivesByRequester.insertWithTtl(indexRow, ttlSeconds));+ batch.addPrepared(AdminArchivesByType.insertWithTtl(indexRow, ttlSeconds));await batch.execute();Logger.debug(- {subjectType: withExpiry.subjectType, subjectId: withExpiry.subjectId, archiveId: withExpiry.archiveId},- 'Updated admin archive record',+ {subjectType: archive.subjectType, subjectId: archive.subjectId, archiveId: archive.archiveId},+ 'Created admin archive record',);}- async markAsStarted(archive: AdminArchive, progressStep = 'Starting archive'): Promise<void> {- const withExpiry = this.ensureExpiry(archive);- const ttlSeconds = computeTtlSeconds(withExpiry.expiresAt!);- const batch = new BatchBuilder();- batch.addPrepared(- AdminArchivesBySubject.patchByPkWithTtlParam(+ private async patchOwned(archive: AdminArchive, patch: AdminArchivePatch): Promise<void> {+ assert(archive.attemptId !== null, 'Admin archive mutation requires a claimed attempt');+ const applied = await executeConditional(+ AdminArchivesBySubject.conditionalPatchByPkWithTtl({- subject_type: withExpiry.subjectType,- subject_id: withExpiry.subjectId,- archive_id: withExpiry.archiveId,+ subject_type: archive.subjectType,+ subject_id: archive.subjectId,+ archive_id: archive.archiveId,},+ patch,{- started_at: Db.set(new Date()),- failed_at: Db.clear(),- error_message: Db.clear(),- progress_percent: Db.set(0),- progress_step: Db.set(progressStep),+ requested_at: archive.requestedAt,+ attempt_id: archive.attemptId,+ completed_at: null,+ failed_at: null,+ terminal_failed_at: null,},- 'ttl_seconds',- ttlSeconds,+ computeTtlSeconds(archive.expiresAt),),);- batch.addPrepared(- AdminArchivesByRequester.patchByPkWithTtlParam(+ if (!applied) throw new ArchiveAttemptSupersededError();+ }++ private async hydrateIndexRows(+ rows: ReadonlyArray<AdminArchiveIndexRow>,+ includeExpired: boolean,+ ): Promise<Array<AdminArchive>> {+ const archives = await mapWithConcurrency(rows, ARCHIVE_READ_CONCURRENCY, (row) =>+ this.findBySubjectAndArchiveId(row.subject_type, row.subject_id, row.archive_id),+ );+ const now = Date.now();+ return archives.filter(+ (archive): archive is AdminArchive =>+ archive !== null && (includeExpired || archive.expiresAt === null || archive.expiresAt.getTime() > now),+ );+ }++ async markAsStarted(archive: AdminArchive, progressStep = 'Starting archive'): Promise<AdminArchive> {+ const attempt = new AdminArchive({+ ...archive.toRow(),+ attempt_id: randomUUID(),+ started_at: new Date(),+ failed_at: null,+ error_message: null,+ progress_percent: 0,+ progress_step: progressStep,+ });+ const applied = await executeConditional(+ AdminArchivesBySubject.conditionalPatchByPkWithTtl({- requested_by: withExpiry.requestedBy,- archive_id: withExpiry.archiveId,+ subject_type: archive.subjectType,+ subject_id: archive.subjectId,+ archive_id: archive.archiveId,},{- started_at: Db.set(new Date()),+ attempt_id: Db.set(attempt.attemptId),+ started_at: Db.set(attempt.startedAt),failed_at: Db.clear(),error_message: Db.clear(),progress_percent: Db.set(0),progress_step: Db.set(progressStep),},- 'ttl_seconds',- ttlSeconds,- ),- );- batch.addPrepared(- AdminArchivesByType.patchByPkWithTtlParam({- subject_type: withExpiry.subjectType,- archive_id: withExpiry.archiveId,+ requested_at: archive.requestedAt,+ attempt_id: archive.attemptId,+ completed_at: null,+ terminal_failed_at: null,},- {- started_at: Db.set(new Date()),- failed_at: Db.clear(),- error_message: Db.clear(),- progress_percent: Db.set(0),- progress_step: Db.set(progressStep),- },- 'ttl_seconds',- ttlSeconds,+ computeTtlSeconds(archive.expiresAt),),);- await batch.execute();+ if (!applied) throw new ArchiveAttemptSupersededError();+ return attempt;}async updateProgress(archive: AdminArchive, progressPercent: number, progressStep: string): Promise<void> {- const withExpiry = this.ensureExpiry(archive);- const ttlSeconds = computeTtlSeconds(withExpiry.expiresAt!);- const batch = new BatchBuilder();- batch.addPrepared(- AdminArchivesBySubject.patchByPkWithTtlParam(- {- subject_type: withExpiry.subjectType,- subject_id: withExpiry.subjectId,- archive_id: withExpiry.archiveId,- },- {- progress_percent: Db.set(progressPercent),- progress_step: Db.set(progressStep),- },- 'ttl_seconds',- ttlSeconds,- ),- );- batch.addPrepared(- AdminArchivesByRequester.patchByPkWithTtlParam(- {- requested_by: withExpiry.requestedBy,- archive_id: withExpiry.archiveId,- },- {- progress_percent: Db.set(progressPercent),- progress_step: Db.set(progressStep),- },- 'ttl_seconds',- ttlSeconds,- ),- );- batch.addPrepared(- AdminArchivesByType.patchByPkWithTtlParam(- {- subject_type: withExpiry.subjectType,- archive_id: withExpiry.archiveId,- },- {- progress_percent: Db.set(progressPercent),- progress_step: Db.set(progressStep),- },- 'ttl_seconds',- ttlSeconds,- ),- );- await batch.execute();- Logger.debug({archiveId: withExpiry.archiveId, progressPercent, progressStep}, 'Updated admin archive progress');+ await this.patchOwned(archive, {+ progress_percent: Db.set(progressPercent),+ progress_step: Db.set(progressStep),+ });+ Logger.debug({archiveId: archive.archiveId, progressPercent, progressStep}, 'Updated admin archive progress');}async markAsCompleted(@@ -189,118 +164,34 @@ export class AdminArchiveRepository {fileSize: bigint,downloadUrlExpiresAt: Date,): Promise<void> {- const withExpiry = this.ensureExpiry(archive);- const ttlSeconds = computeTtlSeconds(withExpiry.expiresAt!);- const batch = new BatchBuilder();- batch.addPrepared(- AdminArchivesBySubject.patchByPkWithTtlParam(- {- subject_type: withExpiry.subjectType,- subject_id: withExpiry.subjectId,- archive_id: withExpiry.archiveId,- },- {- completed_at: Db.set(new Date()),- storage_key: Db.set(storageKey),- file_size: Db.set(fileSize),- download_url_expires_at: Db.set(downloadUrlExpiresAt),- progress_percent: Db.set(100),- progress_step: Db.set('Completed'),- },- 'ttl_seconds',- ttlSeconds,- ),- );- batch.addPrepared(- AdminArchivesByRequester.patchByPkWithTtlParam(- {- requested_by: withExpiry.requestedBy,- archive_id: withExpiry.archiveId,- },- {- completed_at: Db.set(new Date()),- storage_key: Db.set(storageKey),- file_size: Db.set(fileSize),- download_url_expires_at: Db.set(downloadUrlExpiresAt),- progress_percent: Db.set(100),- progress_step: Db.set('Completed'),- },- 'ttl_seconds',- ttlSeconds,- ),- );- batch.addPrepared(- AdminArchivesByType.patchByPkWithTtlParam(- {- subject_type: withExpiry.subjectType,- archive_id: withExpiry.archiveId,- },- {- completed_at: Db.set(new Date()),- storage_key: Db.set(storageKey),- file_size: Db.set(fileSize),- download_url_expires_at: Db.set(downloadUrlExpiresAt),- progress_percent: Db.set(100),- progress_step: Db.set('Completed'),- },- 'ttl_seconds',- ttlSeconds,- ),- );- await batch.execute();+ await this.patchOwned(archive, {+ completed_at: Db.set(new Date()),+ failed_at: Db.clear(),+ error_message: Db.clear(),+ storage_key: Db.set(storageKey),+ file_size: Db.set(fileSize),+ download_url_expires_at: Db.set(downloadUrlExpiresAt),+ progress_percent: Db.set(100),+ progress_step: Db.set('Completed'),+ });}async markAsFailed(archive: AdminArchive, errorMessage: string): Promise<void> {- const withExpiry = this.ensureExpiry(archive);- const ttlSeconds = computeTtlSeconds(withExpiry.expiresAt!);- const batch = new BatchBuilder();- batch.addPrepared(- AdminArchivesBySubject.patchByPkWithTtlParam(- {- subject_type: withExpiry.subjectType,- subject_id: withExpiry.subjectId,- archive_id: withExpiry.archiveId,- },- {- failed_at: Db.set(new Date()),- error_message: Db.set(errorMessage),- progress_step: Db.set('Failed'),- },- 'ttl_seconds',- ttlSeconds,- ),- );- batch.addPrepared(- AdminArchivesByRequester.patchByPkWithTtlParam(- {- requested_by: withExpiry.requestedBy,- archive_id: withExpiry.archiveId,- },- {- failed_at: Db.set(new Date()),- error_message: Db.set(errorMessage),- progress_step: Db.set('Failed'),- },- 'ttl_seconds',- ttlSeconds,- ),- );- batch.addPrepared(- AdminArchivesByType.patchByPkWithTtlParam(- {- subject_type: withExpiry.subjectType,- archive_id: withExpiry.archiveId,- },- {- failed_at: Db.set(new Date()),- error_message: Db.set(errorMessage),- progress_step: Db.set('Failed'),- },- 'ttl_seconds',- ttlSeconds,- ),- );- await batch.execute();+ await this.patchOwned(archive, {+ failed_at: Db.set(new Date()),+ error_message: Db.set(errorMessage),+ progress_step: Db.set('Failed'),+ });+ }++ async markAsTerminallyFailed(archive: AdminArchive, errorMessage: string): Promise<void> {+ const failedAt = new Date();+ await this.patchOwned(archive, {+ failed_at: Db.set(failedAt),+ terminal_failed_at: Db.set(failedAt),+ error_message: Db.set(errorMessage),+ progress_step: Db.set('Failed'),+ });}async findBySubjectAndArchiveId(@@ -347,27 +238,29 @@ export class AdminArchiveRepository {async listByType(subjectType: ArchiveSubjectType, limit = 50, includeExpired = false): Promise<Array<AdminArchive>> {const query = AdminArchivesByType.select({+ columns: ADMIN_ARCHIVE_INDEX_COLUMNS,where: AdminArchivesByType.where.eq('subject_type'),limit,});- const rows = await fetchMany<AdminArchiveRow>(+ const rows = await fetchMany<AdminArchiveIndexRow>(query.bind({subject_type: subjectType,}),);- return filterExpired(rows, includeExpired).map((row) => new AdminArchive(row));+ return this.hydrateIndexRows(rows, includeExpired);}async listByRequester(requestedBy: bigint, limit = 50, includeExpired = false): Promise<Array<AdminArchive>> {const query = AdminArchivesByRequester.select({+ columns: ADMIN_ARCHIVE_INDEX_COLUMNS,where: AdminArchivesByRequester.where.eq('requested_by'),limit,});- const rows = await fetchMany<AdminArchiveRow>(+ const rows = await fetchMany<AdminArchiveIndexRow>(query.bind({requested_by: requestedBy,}),);- return filterExpired(rows, includeExpired).map((row) => new AdminArchive(row));+ return this.hydrateIndexRows(rows, includeExpired);}}diff --git a/fluxer_api/src/api/admin/services/AdminAuditService.ts b/fluxer_api/src/api/admin/services/AdminAuditService.tsindex 41fb5ef13..1f0ed4a73 100644--- a/fluxer_api/src/api/admin/services/AdminAuditService.ts+++ b/fluxer_api/src/api/admin/services/AdminAuditService.ts@@ -55,7 +55,7 @@ export class AdminAuditService {created_at: new Date(),});const auditLogSearchService = getAuditLogSearchService();- if (auditLogSearchService && 'indexAuditLog' in auditLogSearchService) {+ if (auditLogSearchService) {auditLogSearchService.indexAuditLog(log).catch((error) => {Logger.error({error, logId: log.logId}, 'Failed to index audit log to search');});diff --git a/fluxer_api/src/api/admin/services/AdminUserDeletionService.ts b/fluxer_api/src/api/admin/services/AdminUserDeletionService.tsindex 284789874..875fddcc6 100644--- a/fluxer_api/src/api/admin/services/AdminUserDeletionService.ts+++ b/fluxer_api/src/api/admin/services/AdminUserDeletionService.ts@@ -61,17 +61,13 @@ export class AdminUserDeletionService {const daysUntilDeletion = Math.max(data.days_until_deletion, minDays);const pendingDeletionAt = new Date();pendingDeletionAt.setDate(pendingDeletionAt.getDate() + daysUntilDeletion);- const updatedUser = await userRepository.patchUpsert(- userId,- {- flags: user.flags | UserFlags.DELETED,- pending_deletion_at: pendingDeletionAt,- deletion_reason_code: data.reason_code,- deletion_public_reason: data.public_reason ?? null,- deletion_audit_log_reason: auditLogReason,- },- user.toRow(),- );+ const updatedUser = await userRepository.updateDeletionSchedule(user, {+ flags: user.flags | UserFlags.DELETED,+ pending_deletion_at: pendingDeletionAt,+ deletion_reason_code: data.reason_code,+ deletion_public_reason: data.public_reason ?? null,+ deletion_audit_log_reason: auditLogReason,+ });await reschedulePendingDeletion({userId,currentPendingDeletionAt: user.pendingDeletionAt,@@ -191,23 +187,19 @@ export class AdminUserDeletionService {if (!user) {throw new UnknownUserError();}+ const updatedUser = await userRepository.updateDeletionSchedule(user, {+ flags: user.flags & ~UserFlags.DELETED & ~UserFlags.SELF_DELETED,+ pending_deletion_at: null,+ deletion_reason_code: null,+ deletion_public_reason: null,+ deletion_audit_log_reason: null,+ });await clearPendingDeletion({userId,pendingDeletionAt: user.pendingDeletionAt,userRepository,deletionQueue: this.deps.kvDeletionQueue,});- const updatedUser = await userRepository.patchUpsert(- userId,- {- flags: user.flags & ~UserFlags.DELETED & ~UserFlags.SELF_DELETED,- pending_deletion_at: null,- deletion_reason_code: null,- deletion_public_reason: null,- deletion_audit_log_reason: null,- },- user.toRow(),- );await updatePropagator.propagateUserUpdate({userId, oldUser: user, updatedUser: updatedUser});if (user.email) {await emailService.sendUnbanNotification(diff --git a/fluxer_api/src/api/admin/services/AdminUserProfileService.ts b/fluxer_api/src/api/admin/services/AdminUserProfileService.tsindex 6cd516aca..e439a6e6a 100644--- a/fluxer_api/src/api/admin/services/AdminUserProfileService.ts+++ b/fluxer_api/src/api/admin/services/AdminUserProfileService.ts@@ -90,14 +90,8 @@ export class AdminUserProfileService {updates['global_name'] = null;}}- let updatedUser: User;- try {- updatedUser = await userRepository.patchUpsert(userId, updates, user.toRow());- } catch (error) {- await Promise.all(preparedAssets.map((p) => entityAssetService.rollbackAssetUpload(p)));- throw error;- }- await Promise.all(preparedAssets.map((p) => entityAssetService.commitAssetChange({prepared: p})));+ const updatedUser = await userRepository.patchUpsert(userId, updates, user.toRow());+ await entityAssetService.commitAssetChanges(preparedAssets);await updatePropagator.propagateUserUpdate({userId, oldUser: user, updatedUser: updatedUser});await auditService.createAuditLog({adminUserId,@@ -334,21 +328,7 @@ export class AdminUserProfileService {const {users: userRepository} = this.deps.apiContext.services;const {guildRepository} = this.deps;const guildIds = await userRepository.getUserGuildIds(updatedUser.id);- if (guildIds.length === 0) return;- const guilds = await guildRepository.listGuilds(guildIds);- const indexedGuilds = guilds.filter((guild) => guild.membersIndexedAt != null);- if (indexedGuilds.length === 0) return;- const members = await Promise.all(- indexedGuilds.map((guild) => guildRepository.getMember(guild.id, updatedUser.id)),- );- for (let i = 0; i < members.length; i++) {- const member = members[i];- if (member) {- const guild = indexedGuilds[i]!;- const includeDefault = guild.membersIndexedAt != null;- void this.searchIndexService.updateMember(member, updatedUser, {includeDefault});- }- }+ await this.searchIndexService.updateUserMembers(updatedUser, guildIds, guildRepository);} catch (error) {Logger.error({userId: updatedUser.id.toString(), error},diff --git a/fluxer_api/src/api/admin/services/guild/AdminGuildUpdateService.ts b/fluxer_api/src/api/admin/services/guild/AdminGuildUpdateService.tsindex 427e884d9..c213accef 100644--- a/fluxer_api/src/api/admin/services/guild/AdminGuildUpdateService.ts+++ b/fluxer_api/src/api/admin/services/guild/AdminGuildUpdateService.ts@@ -11,7 +11,7 @@ import {createGuildID, createUserID, type GuildID, type UserID} from '../../../Bimport type {GuildRow} from '../../../database/types/GuildTypes';import type {IGuildRepositoryAggregate} from '../../../guild/repositories/IGuildRepositoryAggregate';import type {EntityAssetService, PreparedAssetUpload} from '../../../infrastructure/EntityAssetService';-import type {Guild} from '../../../models/Guild';+import {Logger} from '../../../Logger';import {mapGuildToAdminResponse} from '../../models/GuildTypes';import type {AdminAuditService} from '../AdminAuditService';import type {AdminGuildUpdatePropagator} from './AdminGuildUpdatePropagator';@@ -82,62 +82,37 @@ export class AdminGuildUpdateService {}const patch: Partial<GuildRow> = {};const preparedAssets: Array<PreparedAssetUpload> = [];+ const imageFields = {+ icon: {previousHash: guild.iconHash, patchField: 'icon_hash'},+ banner: {previousHash: guild.bannerHash, patchField: 'banner_hash'},+ splash: {previousHash: guild.splashHash, patchField: 'splash_hash'},+ embed_splash: {previousHash: guild.embedSplashHash, patchField: 'embed_splash_hash'},+ } as const;for (const field of data.fields) {- if (field === 'icon') {- const prepared = await entityAssetService.prepareAssetUpload({- assetType: 'icon',- entityType: 'guild',- entityId: guildId,- previousHash: guild.iconHash,- base64Image: null,- errorPath: 'icon',- });- preparedAssets.push(prepared);- patch.icon_hash = prepared.newHash;- } else if (field === 'banner') {- const prepared = await entityAssetService.prepareAssetUpload({- assetType: 'banner',- entityType: 'guild',- entityId: guildId,- previousHash: guild.bannerHash,- base64Image: null,- errorPath: 'banner',- });- preparedAssets.push(prepared);- patch.banner_hash = prepared.newHash;- } else if (field === 'splash') {- const prepared = await entityAssetService.prepareAssetUpload({- assetType: 'splash',- entityType: 'guild',- entityId: guildId,- previousHash: guild.splashHash,- base64Image: null,- errorPath: 'splash',- });- preparedAssets.push(prepared);- patch.splash_hash = prepared.newHash;- } else if (field === 'embed_splash') {- const prepared = await entityAssetService.prepareAssetUpload({- assetType: 'embed_splash',- entityType: 'guild',- entityId: guildId,- previousHash: guild.embedSplashHash,- base64Image: null,- errorPath: 'embed_splash',- });- preparedAssets.push(prepared);- patch.embed_splash_hash = prepared.newHash;- }+ const {previousHash, patchField} = imageFields[field];+ const prepared = await entityAssetService.prepareAssetUpload({+ assetType: field,+ entityType: 'guild',+ entityId: guildId,+ previousHash,+ base64Image: null,+ errorPath: field,+ });+ preparedAssets.push(prepared);+ patch[patchField] = prepared.newHash;}- let updatedGuild: Guild;- try {- updatedGuild =- Object.keys(patch).length === 0 ? guild : await guildRepository.upsertPartial(guildId, patch, guild.toRow());- } catch (error) {- await Promise.allSettled(preparedAssets.map((p) => entityAssetService.rollbackAssetUpload(p)));- throw error;+ const updatedGuild =+ Object.keys(patch).length === 0 ? guild : await guildRepository.upsertPartial(guildId, patch, guild.toRow());+ const commitResults = await Promise.allSettled(+ preparedAssets.map((prepared) => entityAssetService.commitAssetChange(prepared)),+ );+ for (const [index, result] of commitResults.entries()) {+ if (result.status === 'fulfilled') continue;+ Logger.error(+ {error: result.reason, guildId, previousS3Key: preparedAssets[index].previousS3Key},+ 'Failed to queue cleared guild asset for deletion after successful DB update',+ );}- await Promise.allSettled(preparedAssets.map((p) => entityAssetService.commitAssetChange({prepared: p})));await updatePropagator.dispatchGuildUpdate(guildId, updatedGuild);await auditService.createAuditLog({adminUserId,diff --git a/fluxer_api/src/api/admin/tests/AdminArchiveRetryClearsFailure.test.ts b/fluxer_api/src/api/admin/tests/AdminArchiveRetryClearsFailure.test.tsindex a12d94099..e63922df7 100644--- a/fluxer_api/src/api/admin/tests/AdminArchiveRetryClearsFailure.test.ts+++ b/fluxer_api/src/api/admin/tests/AdminArchiveRetryClearsFailure.test.ts@@ -28,11 +28,13 @@ async function triggerGuildArchive(adminToken: string,guildId: string,): Promise<ArchiveResponse> {- return await createBuilder<ArchiveResponse>(harness, `${adminToken}`)+ const archive = await createBuilder<ArchiveResponse>(harness, `${adminToken}`).post(`/admin/guilds/${guildId}/archives`).body({}).expect(HTTP_STATUS.OK).execute();+ await new AdminArchiveRepository().markAsStarted(await loadArchive(guildId, archive.archive_id));+ return archive;}async function loadArchive(guildId: string, archiveId: string): Promise<AdminArchive> {diff --git a/fluxer_api/src/api/app/APILifecycle.ts b/fluxer_api/src/api/app/APILifecycle.tsindex 06ac13532..54b5142d5 100644--- a/fluxer_api/src/api/app/APILifecycle.ts+++ b/fluxer_api/src/api/app/APILifecycle.ts@@ -15,10 +15,12 @@ import {startAbuseReplicationSubscriber, stopAbuseReplicationSubscriber} from '.import {ipBanCache} from '../middleware/IpBanMiddleware';import {initializeServiceSingletons, shutdownReportService} from '../middleware/ServiceMiddleware';import {+ closeOwnedKVClient,ensureVoiceResourcesInitialized,getKVClient,getSnowflakeService,setInjectedWorkerService,+ shutdownVoiceResources,} from '../middleware/ServiceRegistry';import {getCacheService,@@ -26,6 +28,8 @@ import {getKVAccountDeletionQueue,getReportRepository,getUserRepository,+ shutdownInstanceConfigRepository,+ shutdownServiceSingletons,} from '../middleware/ServiceSingletons';import {torExitListCache} from '../middleware/TorExitListCache';import {ensureApnsSigningKey} from '../push/ApnsPushService';@@ -39,6 +43,42 @@ import {ensureDeletionQueueState} from './DeletionQueueStartup';let jsConnectionManager: JetStreamConnectionManager | null = null;+interface RefreshCacheLifecycle {+ initialize(): Promise<void>;+ shutdown(): Promise<void>;+}++const refreshCaches = new Map<RefreshCacheLifecycle, string>();+let refreshCacheShutdownPromise: Promise<void> | null = null;++async function initializeRefreshCache(cache: RefreshCacheLifecycle, name: string, logger: ILogger): Promise<void> {+ refreshCaches.set(cache, name);+ await cache.initialize();+ logger.info(`${name} initialized`);+}++async function shutdownRefreshCaches(logger: ILogger): Promise<void> {+ if (refreshCacheShutdownPromise) return await refreshCacheShutdownPromise;+ const caches = [...refreshCaches];+ refreshCaches.clear();+ const shutdown = Promise.all(+ caches.map(async ([cache, name]) => {+ try {+ await cache.shutdown();+ logger.info(`${name} shut down`);+ } catch (error) {+ logger.error({error}, `Error shutting down ${name}`);+ }+ }),+ ).then(() => undefined);+ refreshCacheShutdownPromise = shutdown;+ try {+ await shutdown;+ } finally {+ if (refreshCacheShutdownPromise === shutdown) refreshCacheShutdownPromise = null;+ }+}+function unsupportedDatabaseBackend(backend: never): never {throw new Error(`Unsupported database backend during shutdown: ${String(backend)}`);}@@ -70,7 +110,7 @@ export function createInitializer(config: APIConfig, logger: ILogger): () => Pro);}if (config.database.backend === 'postgres' && !hasDatabaseQueryExecutor()) {- await initPostgres(config.postgres);+ await initPostgres(config.postgres, (diagnostic) => logger.error(diagnostic, 'Postgres connection error'));const postgres = getDefaultPostgresClient();await ensurePostgresKvSchema(postgres);setDatabaseQueryExecutor(new PostgresKvQueryExecutor(postgres));@@ -93,8 +133,7 @@ export function createInitializer(config: APIConfig, logger: ILogger): () => Pro}const kvClient = getKVClient();ipBanCache.setRefreshSubscriber(kvClient);- await ipBanCache.initialize();- logger.info('IP ban cache initialized');+ await initializeRefreshCache(ipBanCache, 'IP ban cache', logger);await startAbuseReplicationSubscriber(kvClient);logger.info('Abusive-IP auto-banner replication started');torExitListCache.setKvClient(kvClient);@@ -104,24 +143,19 @@ export function createInitializer(config: APIConfig, logger: ILogger): () => ProurlBlocklistCache.setRefreshSubscriber(kvClient);const {getStorageService} = await import('../middleware/ServiceSingletons');urlBlocklistCache.setStorageService(getStorageService());- await urlBlocklistCache.initialize();- logger.info('URL blocklist cache initialized');+ await initializeRefreshCache(urlBlocklistCache, 'URL blocklist cache', logger);const {fileShaCache} = await import('../middleware/FileShaCache');fileShaCache.setRefreshSubscriber(kvClient);- await fileShaCache.initialize();- logger.info('File SHA blocklist cache initialized');+ await initializeRefreshCache(fileShaCache, 'File SHA blocklist cache', logger);const {phraseBlocklistCache} = await import('../middleware/PhraseBlocklistCache');phraseBlocklistCache.setRefreshSubscriber(kvClient);- await phraseBlocklistCache.initialize();- logger.info('Phrase blocklist cache initialized');+ await initializeRefreshCache(phraseBlocklistCache, 'Phrase blocklist cache', logger);const {bannedAvatarHashCache} = await import('../middleware/BannedAvatarHashCache');bannedAvatarHashCache.setRefreshSubscriber(kvClient);- await bannedAvatarHashCache.initialize();- logger.info('Banned avatar hash cache initialized');+ await initializeRefreshCache(bannedAvatarHashCache, 'Banned avatar hash cache', logger);const {profileSubstringBlocklistCache} = await import('../middleware/ProfileSubstringBlocklistCache');profileSubstringBlocklistCache.setRefreshSubscriber(kvClient);- await profileSubstringBlocklistCache.initialize();- logger.info('Profile substring blocklist cache initialized');+ await initializeRefreshCache(profileSubstringBlocklistCache, 'Profile substring blocklist cache', logger);await initializeServiceSingletons();logger.info('Service singletons initialized');if (!config.dev.testModeEnabled) {@@ -210,6 +244,12 @@ export function createInitializer(config: APIConfig, logger: ILogger): () => Proexport function createShutdown(config: APIConfig, logger: ILogger): () => Promise<void> {return async (): Promise<void> => {logger.info('Shutting down API service...');+ try {+ await shutdownVoiceResources();+ logger.info('Voice resources shut down');+ } catch (error) {+ logger.error({error}, 'Error shutting down voice resources');+ }if (jsConnectionManager) {try {await jsConnectionManager.drain();@@ -225,26 +265,30 @@ export function createShutdown(config: APIConfig, logger: ILogger): () => Promis} catch (error) {logger.error({error}, 'Error shutting down search service');}- try {- ipBanCache.shutdown();- logger.info('IP ban cache shut down');- } catch (error) {- logger.error({error}, 'Error shutting down IP ban cache');- }try {await stopAbuseReplicationSubscriber();logger.info('Abusive-IP auto-banner replication stopped');} catch (error) {logger.error({error}, 'Error stopping abusive-IP auto-banner replication');}+ await Promise.all([+ shutdownRefreshCaches(logger),+ shutdownServiceSingletons()+ .then(() => {+ logger.info('Service singletons shut down');+ })+ .catch((error) => {+ logger.error({error}, 'Error shutting down service singletons');+ }),+ ]);try {- torExitListCache.shutdown();+ await torExitListCache.shutdown();logger.info('Tor exit list cache shut down');} catch (error) {logger.error({error}, 'Error shutting down Tor exit list cache');}try {- getInstanceConfigRepository().shutdown();+ await shutdownInstanceConfigRepository();logger.info('Instance config repository shut down');} catch (error) {logger.error({error}, 'Error shutting down instance config repository');@@ -276,6 +320,12 @@ export function createShutdown(config: APIConfig, logger: ILogger): () => Promisdefault:unsupportedDatabaseBackend(config.database.backend);}+ try {+ closeOwnedKVClient();+ logger.info('Key-value client closed');+ } catch (error) {+ logger.error({error}, 'Error closing key-value client');+ }logger.info('API service shutdown complete');};}diff --git a/fluxer_api/src/api/app/tests/DeletionQueueStartup.test.ts b/fluxer_api/src/api/app/tests/DeletionQueueStartup.test.tsindex 699eca0be..0f0a5993f 100644--- a/fluxer_api/src/api/app/tests/DeletionQueueStartup.test.ts+++ b/fluxer_api/src/api/app/tests/DeletionQueueStartup.test.ts@@ -32,7 +32,7 @@ class RecordingLogger implements ILogger {}class UnreadableStateKVProvider extends MockKVProvider {- override async exists(): Promise<number> {+ override async get(): Promise<string | null> {throw new Error('kv unavailable');}}diff --git a/fluxer_api/src/api/archive/ArchiveAttemptSupersededError.ts b/fluxer_api/src/api/archive/ArchiveAttemptSupersededError.tsnew file mode 100644index 000000000..797a50b21--- /dev/null+++ b/fluxer_api/src/api/archive/ArchiveAttemptSupersededError.ts@@ -0,0 +1,6 @@+export class ArchiveAttemptSupersededError extends Error {+ constructor() {+ super('Archive attempt no longer owns this archive');+ this.name = 'ArchiveAttemptSupersededError';+ }+}diff --git a/fluxer_api/src/api/archive/ArchiveTask.ts b/fluxer_api/src/api/archive/ArchiveTask.tsnew file mode 100644index 000000000..59c03d8ee--- /dev/null+++ b/fluxer_api/src/api/archive/ArchiveTask.ts@@ -0,0 +1,56 @@+import type {WorkerTaskAttempt, WorkerTaskHandler, WorkerTaskHelpers} from '@pkgs/worker/src/contracts/WorkerTask';+import type {AdminArchive} from '../admin/models/AdminArchiveModel';+import type {UserHarvest} from '../user/UserHarvestModel';+import {ArchiveAttemptSupersededError} from './ArchiveAttemptSupersededError';++export class ArchiveTaskDeferredError extends Error {+ constructor(cause: unknown) {+ super('Archive execution could not confirm a terminal result', {cause});+ this.name = 'ArchiveTaskDeferredError';+ }+}++export class ArchiveTerminalFailureError extends Error {+ constructor(message: string) {+ super(message);+ this.name = 'ArchiveTerminalFailureError';+ }+}++interface ArchiveTask extends WorkerTaskHandler {+ readonly failurePolicy: 'archive';+}++export type ArchiveTaskHandler = (+ payload: Record<string, unknown>,+ helpers: WorkerTaskHelpers,+ attempt: WorkerTaskAttempt,+) => Promise<void>;++export function isArchiveTask(task: WorkerTaskHandler | undefined): task is ArchiveTask {+ return task !== undefined && 'failurePolicy' in task && task.failurePolicy === 'archive';+}++export function throwIfArchiveTerminallyFailed(archive: UserHarvest | AdminArchive): void {+ if (archive.terminalFailedAt === null) return;+ if (archive.errorMessage === null) throw new Error('Terminal archive failure has no recorded reason');+ throw new ArchiveTerminalFailureError(archive.errorMessage);+}++export function createArchiveTask(handler: ArchiveTaskHandler): ArchiveTask {+ const task: WorkerTaskHandler = async (payload, helpers) => {+ try {+ const attempt = helpers.attempt;+ if (attempt === undefined || typeof attempt.isLastAttempt !== 'boolean') {+ throw new Error('Archive execution requires queue attempt metadata');+ }+ await handler(payload, helpers, attempt);+ } catch (error) {+ if (error instanceof ArchiveAttemptSupersededError || error instanceof ArchiveTerminalFailureError) {+ throw error;+ }+ throw new ArchiveTaskDeferredError(error);+ }+ };+ return Object.assign(task, {failurePolicy: 'archive' as const});+}diff --git a/fluxer_api/src/api/auth/AuthController.ts b/fluxer_api/src/api/auth/AuthController.tsindex 58e3622ca..2ffb01a57 100644--- a/fluxer_api/src/api/auth/AuthController.ts+++ b/fluxer_api/src/api/auth/AuthController.ts@@ -343,7 +343,8 @@ export function AuthController(app: HonoApp) {}),async (ctx) => {const userId = ctx.get('user').id;- return ctx.json(await ctx.get('authRequestService').getAuthSessions(userId));+ const currentSessionIdHash = ctx.get('authSession')?.sessionIdHash;+ return ctx.json(await ctx.get('authRequestService').getAuthSessions(userId, currentSessionIdHash));},);app.post(diff --git a/fluxer_api/src/api/auth/AuthEmail.ts b/fluxer_api/src/api/auth/AuthEmail.tsindex 3bc20c507..eb7996109 100644--- a/fluxer_api/src/api/auth/AuthEmail.ts+++ b/fluxer_api/src/api/auth/AuthEmail.ts@@ -7,9 +7,7 @@ import type {VerifyEmailRequest} from '@fluxer/schema/src/domains/auth/AuthSchemimport {ms} from 'itty-time';import type {ApiContext} from '../ApiContext';import {createEmailVerificationToken} from '../BrandedTypes';-import {Logger} from '../Logger';import type {User} from '../models/User';-import {getUserSearchService} from '../SearchFactory';import {mapUserToPrivateResponse} from '../user/UserMappers';import * as RandomUtils from '../utils/RandomUtils';@@ -38,7 +36,11 @@ export async function verifyEmail(ctx: ApiContext, data: VerifyEmailRequest): Prreturn false;}assertNonBotUser(user);- if (user.flags & UserFlags.DELETED) {+ if (+ user.flags & UserFlags.DELETED ||+ !user.email ||+ user.email.trim().toLowerCase() !== tokenData.email.trim().toLowerCase()+ ) {return false;}const updates: {@@ -57,12 +59,6 @@ export async function verifyEmail(ctx: ApiContext, data: VerifyEmailRequest): Pr}const updatedUser = await users.patchUpsert(user.id, updates, user.toRow());await users.deleteEmailVerificationToken(data.token);- const userSearchService = getUserSearchService();- if (userSearchService && 'updateUser' in userSearchService) {- await userSearchService.updateUser(updatedUser).catch((error) => {- Logger.error({userId: user.id, error}, 'Failed to update user in search');- });- }await gateway.dispatchPresence({userId: user.id,event: 'USER_UPDATE',diff --git a/fluxer_api/src/api/auth/AuthEmailRevert.ts b/fluxer_api/src/api/auth/AuthEmailRevert.tsindex 9db018413..d081f3ae7 100644--- a/fluxer_api/src/api/auth/AuthEmailRevert.ts+++ b/fluxer_api/src/api/auth/AuthEmailRevert.ts@@ -5,9 +5,7 @@ import {InputValidationError} from '@fluxer/errors/src/domains/core/InputValidatimport {requireClientIp} from '@fluxer/ip_utils/src/ClientIp';import type {ApiContext} from '../ApiContext';import {createEmailRevertToken} from '../BrandedTypes';-import {Logger} from '../Logger';import type {User} from '../models/User';-import {getUserSearchService} from '../SearchFactory';import {mapUserToPrivateResponse} from '../user/UserMappers';import * as AuthPassword from './AuthPassword';import * as AuthSession from './AuthSession';@@ -75,6 +73,7 @@ export async function revertEmailChange(},user.toRow(),);+ await users.deleteAllPasswordResetTokens(user.id);await users.deleteEmailRevertToken(token);await users.deleteAllMfaBackupCodes(user.id);await users.deleteAllWebAuthnCredentials(user.id);@@ -87,14 +86,6 @@ export async function revertEmailChange(clientIpHeaderName: config.proxy.client_ip_header,}),);- const userSearchService = getUserSearchService();- if (userSearchService && updatedUser && 'updateUser' in userSearchService) {- await userSearchService- .updateUser(updatedUser)- .catch((error) =>- Logger.debug({error, userId: updatedUser.id}, 'Failed to update search index after email revert'),- );- }await gateway.dispatchPresence({userId: updatedUser.id,event: 'USER_UPDATE',diff --git a/fluxer_api/src/api/auth/AuthLogin.ts b/fluxer_api/src/api/auth/AuthLogin.tsindex 9f862083c..9a9090880 100644--- a/fluxer_api/src/api/auth/AuthLogin.ts+++ b/fluxer_api/src/api/auth/AuthLogin.ts@@ -8,13 +8,11 @@ import {IpAuthorizationResendLimitExceededError} from '@fluxer/errors/src/domainimport {RegistrationPendingApprovalError} from '@fluxer/errors/src/domains/auth/RegistrationPendingApprovalError';import {RegistrationRejectedError} from '@fluxer/errors/src/domains/auth/RegistrationRejectedError';import {InputValidationError} from '@fluxer/errors/src/domains/core/InputValidationError';-import {RateLimitError} from '@fluxer/errors/src/domains/core/RateLimitError';import {UnknownUserError} from '@fluxer/errors/src/domains/user/UnknownUserError';import {requireClientIp} from '@fluxer/ip_utils/src/ClientIp';import {getSameIpDecisionKey} from '@fluxer/ip_utils/src/IpAddress';import type {LoginRequest} from '@fluxer/schema/src/domains/auth/AuthSchemas';import {formatGeoipLocation, UNKNOWN_LOCATION} from '@pkgs/geoip/src/GeoipLookup';-import type {RateLimitResult} from '@pkgs/rate_limit/src/IRateLimitService';import type {AuthenticationResponseJSON} from '@simplewebauthn/server';import {ms, seconds} from 'itty-time';import type {ApiContext} from '../ApiContext';@@ -33,6 +31,7 @@ import {createRequestCache} from '../middleware/RequestCacheMiddleware';import {getInstanceConfigRepository} from '../middleware/ServiceSingletons';import type {User} from '../models/User';import {lookupGeoip} from '../utils/IpUtils';+import {createRateLimitError} from '../utils/RateLimitUtils';import * as AuthMfa from './AuthMfa';import * as AuthPassword from './AuthPassword';import * as AuthSession from './AuthSession';@@ -79,18 +78,6 @@ interface LoginMfaResult {type LoginResult = LoginTokenResult | LoginMfaResult;-function getRetryAfterSeconds(result: RateLimitResult): number {- return result.retryAfter ?? Math.max(0, Math.ceil((result.resetTime.getTime() - Date.now()) / 1000));-}--function throwLoginRateLimit(result: RateLimitResult): never {- throw new RateLimitError({- retryAfter: getRetryAfterSeconds(result),- limit: result.limit,- resetTime: result.resetTime,- });-}-export interface IpAuthorizationTicketCache {userId: string;email: string;@@ -202,7 +189,7 @@ export async function login(windowMs: ms('15 minutes'),});if (!emailRateLimit.allowed && !skipRateLimits) {- throwLoginRateLimit(emailRateLimit);+ throw createRateLimitError(emailRateLimit);}const clientIp = requireClientIp(request, {trustClientIpHeader: config.proxy.trust_client_ip_header,@@ -214,7 +201,7 @@ export async function login(windowMs: ms('30 minutes'),});if (!ipRateLimit.allowed && !skipRateLimits) {- throwLoginRateLimit(ipRateLimit);+ throw createRateLimitError(ipRateLimit);}const user = await users.findByEmail(data.email);if (!user) {@@ -254,22 +241,19 @@ export async function login(Logger.info({userId: currentUser.id}, 'Auto-undisabled user on login');}if ((currentUser.flags & UserFlags.SELF_DELETED) !== 0n) {- if (currentUser.pendingDeletionAt) {- await users.removePendingDeletion(currentUser.id, currentUser.pendingDeletionAt);+ const pendingDeletionAt = currentUser.pendingDeletionAt;+ const updatedFlags = currentUser.flags & ~UserFlags.SELF_DELETED;+ currentUser = await users.updateDeletionSchedule(currentUser, {+ flags: updatedFlags,+ pending_deletion_at: null,+ deletion_reason_code: null,+ deletion_public_reason: null,+ deletion_audit_log_reason: null,+ });+ if (pendingDeletionAt) {+ await users.removePendingDeletion(currentUser.id, pendingDeletionAt);}await kvDeletionQueue.removeFromQueue(currentUser.id);- const updatedFlags = currentUser.flags & ~UserFlags.SELF_DELETED;- currentUser = await users.patchUpsert(- currentUser.id,- {- flags: updatedFlags,- pending_deletion_at: null,- deletion_reason_code: null,- deletion_public_reason: null,- deletion_audit_log_reason: null,- },- currentUser.toRow(),- );Logger.info({userId: currentUser.id}, 'Auto-cancelled deletion on login');}if (currentUser.traits.has(REGISTRATION_PENDING_APPROVAL_TRAIT)) {diff --git a/fluxer_api/src/api/auth/AuthMfa.ts b/fluxer_api/src/api/auth/AuthMfa.tsindex 0cf07db7d..0c29d9437 100644--- a/fluxer_api/src/api/auth/AuthMfa.ts+++ b/fluxer_api/src/api/auth/AuthMfa.ts@@ -27,7 +27,6 @@ import {createUserID, type UserID} from '../BrandedTypes';import {Logger} from '../Logger';import type {User} from '../models/User';import type {WebAuthnCredential} from '../models/WebAuthnCredential';-import {getUserSearchService} from '../SearchFactory';import {mapUserToPrivateResponse} from '../user/UserMappers';import {TotpGenerator} from '../utils/TotpGenerator';import {deriveSudoMethods, userHasMfa} from './services/SudoMethods';@@ -217,12 +216,6 @@ export async function verifyWebAuthnRegistration(if (!authenticatorTypes.has(UserAuthenticatorTypes.WEBAUTHN)) {authenticatorTypes.add(UserAuthenticatorTypes.WEBAUTHN);const updatedUser = await users.patchUpsert(userId, {authenticator_types: authenticatorTypes}, user.toRow());- const userSearchService = getUserSearchService();- if (userSearchService && 'updateUser' in userSearchService) {- await userSearchService.updateUser(updatedUser).catch((error) => {- Logger.error({userId, error}, 'Failed to update user in search');- });- }await gateway.dispatchPresence({userId, event: 'USER_UPDATE', data: mapUserToPrivateResponse(updatedUser)});await botMfaMirror.syncAuthenticatorTypesForOwner(updatedUser);}@@ -242,12 +235,6 @@ export async function deleteWebAuthnCredential(ctx: ApiContext, userId: UserID,const authenticatorTypes = user.authenticatorTypes || new Set<number>();authenticatorTypes.delete(UserAuthenticatorTypes.WEBAUTHN);const updatedUser = await users.patchUpsert(userId, {authenticator_types: authenticatorTypes}, user.toRow());- const userSearchService = getUserSearchService();- if (userSearchService && 'updateUser' in userSearchService) {- await userSearchService.updateUser(updatedUser).catch((error) => {- Logger.error({userId, error}, 'Failed to update user in search');- });- }await gateway.dispatchPresence({userId, event: 'USER_UPDATE', data: mapUserToPrivateResponse(updatedUser)});await botMfaMirror.syncAuthenticatorTypesForOwner(updatedUser);}diff --git a/fluxer_api/src/api/auth/AuthModel.ts b/fluxer_api/src/api/auth/AuthModel.tsindex bf6b9458c..dd1976d33 100644--- a/fluxer_api/src/api/auth/AuthModel.ts+++ b/fluxer_api/src/api/auth/AuthModel.ts@@ -28,10 +28,10 @@ async function resolveAuthSessionLocation(session: AuthSession): Promise<stringexport async function mapAuthSessionsToResponse({authSessions,- currentSessionId,+ currentSessionIdHash,}: {authSessions: Array<AuthSession>;- currentSessionId?: Uint8Array;+ currentSessionIdHash?: Uint8Array;}): Promise<Array<AuthSessionResponse>> {const sortedSessions = authSessions.toSorted((a, b) => {const aTime = a.approximateLastUsedAt?.getTime() || 0;@@ -51,7 +51,7 @@ export async function mapAuthSessionsToResponse({productName: branding.product_name,});const idHash = uint8ArrayToBase64(authSession.sessionIdHash, {urlSafe: true});- const isCurrent = currentSessionId ? Buffer.compare(authSession.sessionIdHash, currentSessionId) === 0 : false;+ const isCurrent = currentSessionIdHash ? authSession.sessionIdHash.equals(currentSessionIdHash) : false;return {id_hash: idHash,client_info: {diff --git a/fluxer_api/src/api/auth/AuthPassword.ts b/fluxer_api/src/api/auth/AuthPassword.tsindex 64fba36c2..48bfc1a62 100644--- a/fluxer_api/src/api/auth/AuthPassword.ts+++ b/fluxer_api/src/api/auth/AuthPassword.ts@@ -5,7 +5,6 @@ import {FLUXER_USER_AGENT} from '@fluxer/constants/src/Core';import {UserAuthenticatorTypes, UserFlags} from '@fluxer/constants/src/UserConstants';import {ValidationErrorCodes} from '@fluxer/constants/src/ValidationErrorCodes';import {InputValidationError} from '@fluxer/errors/src/domains/core/InputValidationError';-import {RateLimitError} from '@fluxer/errors/src/domains/core/RateLimitError';import {requireClientIp} from '@fluxer/ip_utils/src/ClientIp';import {getSameIpDecisionKey} from '@fluxer/ip_utils/src/IpAddress';import type {ForgotPasswordRequest, ResetPasswordRequest} from '@fluxer/schema/src/domains/auth/AuthSchemas';@@ -17,6 +16,7 @@ import type {User} from '../models/User';import {EXTERNAL_RESPONSE_LIMITS} from '../utils/ExternalResponseLimits';import * as FetchUtils from '../utils/FetchUtils';import {hashPassword as hashPasswordUtil, verifyPassword as verifyPasswordUtil} from '../utils/PasswordUtils';+import {createRateLimitError} from '../utils/RateLimitUtils';import * as AuthSession from './AuthSession';import * as AuthUtility from './AuthUtility';@@ -132,6 +132,7 @@ export async function isPasswordPwned(_ctx: ApiContext, password: string): Promisignal: AbortSignal.timeout(PWNED_PASSWORDS_TIMEOUT_MS),});if (!response.ok) {+ FetchUtils.discardResponseBody(response.body, response.status);Logger.warn({status: response.status,@@ -183,29 +184,21 @@ export async function forgotPassword(ctx: ApiContext, {data, request}: ForgotPastrustClientIpHeader: config.proxy.trust_client_ip_header,clientIpHeaderName: config.proxy.client_ip_header,});- const ipLimitConfig = {maxAttempts: 20, windowMs: ms('30 minutes')};- const emailLimitConfig = {maxAttempts: 5, windowMs: ms('30 minutes')};const ipRateLimit = await rateLimit.checkLimit({identifier: `password_reset:ip:${getSameIpDecisionKey(clientIp) ?? clientIp}`,- ...ipLimitConfig,+ maxAttempts: 20,+ windowMs: ms('30 minutes'),});const emailRateLimit = await rateLimit.checkLimit({identifier: `password_reset:email:${data.email.toLowerCase()}`,- ...emailLimitConfig,+ maxAttempts: 5,+ windowMs: ms('30 minutes'),});- const exceeded = !ipRateLimit.allowed- ? {result: ipRateLimit, config: ipLimitConfig}- : !emailRateLimit.allowed- ? {result: emailRateLimit, config: emailLimitConfig}- : null;- if (exceeded) {- const retryAfter =- exceeded.result.retryAfter ?? Math.max(0, Math.ceil((exceeded.result.resetTime.getTime() - Date.now()) / 1000));- throw new RateLimitError({- retryAfter,- limit: exceeded.result.limit,- resetTime: exceeded.result.resetTime,- });+ if (!ipRateLimit.allowed) {+ throw createRateLimitError(ipRateLimit);+ }+ if (!emailRateLimit.allowed) {+ throw createRateLimitError(emailRateLimit);}const hasValidDns = await emailDnsValidation.hasValidDnsRecords(data.email);if (!hasValidDns) {@@ -235,7 +228,11 @@ export async function validateResetToken(ctx: ApiContext, token: string): Promisif (!user) {return false;}- if (user.flags & UserFlags.DELETED) {+ if (+ user.flags & UserFlags.DELETED ||+ !user.email ||+ user.email.trim().toLowerCase() !== tokenData.email.trim().toLowerCase()+ ) {return false;}return true;@@ -255,7 +252,11 @@ export async function resetPassword(throw InputValidationError.fromCode('token', ValidationErrorCodes.INVALID_OR_EXPIRED_RESET_TOKEN);}AuthUtility.assertNonBotUser(ctx, user);- if (user.flags & UserFlags.DELETED) {+ if (+ user.flags & UserFlags.DELETED ||+ !user.email ||+ user.email.trim().toLowerCase() !== tokenData.email.trim().toLowerCase()+ ) {throw InputValidationError.fromCode('token', ValidationErrorCodes.INVALID_OR_EXPIRED_RESET_TOKEN);}await AuthUtility.handleBanStatus(ctx, user);diff --git a/fluxer_api/src/api/auth/AuthPhone.ts b/fluxer_api/src/api/auth/AuthPhone.tsindex c5dc3c936..71c4ddf58 100644--- a/fluxer_api/src/api/auth/AuthPhone.ts+++ b/fluxer_api/src/api/auth/AuthPhone.ts@@ -33,7 +33,6 @@ import type {ApiContext} from '../ApiContext';import type {UserID} from '../BrandedTypes';import {Logger} from '../Logger';import type {User} from '../models/User';-import {getUserSearchService} from '../SearchFactory';import {mapUserToPartialResponse, mapUserToPrivateResponse} from '../user/UserMappers';import {phonePrefixBanCache} from './PhonePrefixBanCache';import {requiresInboundPhoneVerification} from './PhoneVerificationPrefixPolicy';@@ -367,12 +366,6 @@ async function attachVerifiedPhoneToAccount(ctx: ApiContext, userId: UserID, phoreason: 'user_requested',actorUserId: userId,});- const userSearchService = getUserSearchService();- if (userSearchService && 'updateUser' in userSearchService) {- await userSearchService.updateUser(updatedUser).catch((error) => {- Logger.error({userId, error}, 'Failed to update user in search index');- });- }await gateway.dispatchPresence({userId,event: 'USER_UPDATE',diff --git a/fluxer_api/src/api/auth/AuthRegistration.ts b/fluxer_api/src/api/auth/AuthRegistration.tsindex 86247b5f3..a59ce1b21 100644--- a/fluxer_api/src/api/auth/AuthRegistration.ts+++ b/fluxer_api/src/api/auth/AuthRegistration.ts@@ -7,12 +7,10 @@ import {RegistrationClosedError} from '@fluxer/errors/src/domains/auth/Registratimport {RegistrationUrlInvalidError} from '@fluxer/errors/src/domains/auth/RegistrationUrlInvalidError';import {ContentBlockedError} from '@fluxer/errors/src/domains/content/ContentBlockedError';import {InputValidationError} from '@fluxer/errors/src/domains/core/InputValidationError';-import {RateLimitError} from '@fluxer/errors/src/domains/core/RateLimitError';import {requireClientIp} from '@fluxer/ip_utils/src/ClientIp';import {getSameIpDecisionKey, getSubnet} from '@fluxer/ip_utils/src/IpAddress';import type {RegisterRequest} from '@fluxer/schema/src/domains/auth/AuthSchemas';import {parseAcceptLanguage} from '@pkgs/locale/src/LocaleService';-import type {RateLimitResult} from '@pkgs/rate_limit/src/IRateLimitService';import {types} from 'cassandra-driver';import {ms} from 'itty-time';import type {ApiContext} from '../ApiContext';@@ -43,10 +41,10 @@ import {deferPhoneFlagsUntilCommunityJoin} from '../risk/DeferredPhoneGate';import type {IRiskHistoryRepository} from '../risk/HistoricalOutcomeRepository';import type {IRiskAssessmentRepository} from '../risk/RiskAssessmentRepository';import {deriveLatestRiskContext} from '../risk/RiskHistoryContext';-import {getUserSearchService} from '../SearchFactory';import * as AgeUtils from '../utils/AgeUtils';import {extractEmailDomain} from '../utils/EmailDomainUtils';import {lookupGeoip} from '../utils/IpUtils';+import {createRateLimitError} from '../utils/RateLimitUtils';import {generateRandomUsername} from '../utils/UsernameGenerator';import {deriveUsernameFromDisplayName} from '../utils/UsernameSuggestionUtils';import * as AuthPassword from './AuthPassword';@@ -56,18 +54,6 @@ import type {IRegistrationRiskEvaluator} from './services/IRegistrationRiskEvaluconst DEFAULT_MINIMUM_AGE = 13;-function getRetryAfterSeconds(result: RateLimitResult): number {- return result.retryAfter ?? Math.max(0, Math.ceil((result.resetTime.getTime() - Date.now()) / 1000));-}--function throwRegistrationRateLimit(result: RateLimitResult): never {- throw new RateLimitError({- retryAfter: getRetryAfterSeconds(result),- limit: result.limit,- resetTime: result.resetTime,- });-}-function parseDobLocalDate(dateOfBirth: string): types.LocalDate {const match = /^(\d{4})-(\d{2})-(\d{2})$/.exec(dateOfBirth);if (!match) {@@ -149,6 +135,9 @@ export async function register(}const now = new Date();const registrationAccess = await resolveRegistrationAccess(instanceConfigRepository, data.registration_url_code);+ if (registrationAccess.pendingApproval) {+ await instanceConfigRepository.getPendingRegistrations();+ }const clientIp = requireClientIp(request, {trustClientIpHeader: config.proxy.trust_client_ip_header,clientIpHeaderName: config.proxy.client_ip_header,@@ -410,7 +399,6 @@ export async function register();}}- await maybeIndexUser(user);if (rawEmail && emailEnabled) await maybeSendVerificationEmail(ctx, {user, email: rawEmail});await users.createAuthorizedIp(userId, clientIp);if (registrationAccess.registrationUrl) {@@ -506,18 +494,6 @@ async function resolveRegistrationAccess(};}-async function maybeIndexUser(user: User): Promise<void> {- const userSearchService = getUserSearchService();- if (!userSearchService) return;- if ('indexUser' in userSearchService) {- try {- await userSearchService.indexUser(user);- } catch (error) {- Logger.error({userId: user.id, error}, 'Failed to index user in search');- }- }-}-async function maybeSendVerificationEmail(ctx: ApiContext, params: {user: User; email: string}): Promise<void> {const {users, email: emailService} = ctx.services;const {user, email} = params;@@ -570,14 +546,14 @@ async function enforceRegistrationRateLimits(maxAttempts: 3,windowMs: ms('15 minutes'),});- if (!emailRateLimit.allowed) throwRegistrationRateLimit(emailRateLimit);+ if (!emailRateLimit.allowed) throw createRateLimitError(emailRateLimit);}const ipRateLimit = await rateLimit.checkLimit({identifier: `registration:ip:${getSameIpDecisionKey(clientIp) ?? clientIp}`,maxAttempts: 3,windowMs: ms('1 hour'),});- if (!ipRateLimit.allowed) throwRegistrationRateLimit(ipRateLimit);+ if (!ipRateLimit.allowed) throw createRateLimitError(ipRateLimit);const subnet = getSubnet(clientIp);if (subnet) {const subnetRateLimit = await rateLimit.checkLimit({@@ -585,7 +561,7 @@ async function enforceRegistrationRateLimits(maxAttempts: 15,windowMs: ms('1 hour'),});- if (!subnetRateLimit.allowed) throwRegistrationRateLimit(subnetRateLimit);+ if (!subnetRateLimit.allowed) throw createRateLimitError(subnetRateLimit);}}diff --git a/fluxer_api/src/api/auth/AuthRequestService.ts b/fluxer_api/src/api/auth/AuthRequestService.tsindex 34f2446d3..7572ad1f0 100644--- a/fluxer_api/src/api/auth/AuthRequestService.ts+++ b/fluxer_api/src/api/auth/AuthRequestService.ts@@ -228,8 +228,8 @@ export class AuthRequestService {return await this.toAuthLoginResponse(result);}- getAuthSessions(userId: UserID): Promise<AuthSessionsResponse> {- return AuthSession.getAuthSessions(this.apiContext, userId);+ getAuthSessions(userId: UserID, currentSessionIdHash?: Uint8Array): Promise<AuthSessionsResponse> {+ return AuthSession.getAuthSessions(this.apiContext, userId, currentSessionIdHash);}async logoutAuthSessions({user, data}: AuthLogoutAuthSessionsRequest): Promise<void> {diff --git a/fluxer_api/src/api/auth/AuthSession.ts b/fluxer_api/src/api/auth/AuthSession.tsindex f519992a6..794327909 100644--- a/fluxer_api/src/api/auth/AuthSession.ts+++ b/fluxer_api/src/api/auth/AuthSession.ts@@ -17,6 +17,7 @@ import type {User} from '../models/User';import {lookupGeoip} from '../utils/IpUtils';import {isFluxerNativeUserAgent, parseReportedClientOs} from '../utils/SessionClientIdentity';import {mapAuthSessionsToResponse} from './AuthModel';+import {revokeAllAuthSessions, revokeAuthSessions} from './AuthSessionRevocation';import * as AuthUtility from './AuthUtility';export interface SessionOrigin {@@ -134,10 +135,14 @@ export async function getAuthSessionByToken(ctx: ApiContext, token: string): Proreturn users.getAuthSessionByToken(Buffer.from(AuthUtility.getTokenIdHash(ctx, token)));}-export async function getAuthSessions(ctx: ApiContext, userId: UserID): Promise<Array<AuthSessionResponse>> {+export async function getAuthSessions(+ ctx: ApiContext,+ userId: UserID,+ currentSessionIdHash?: Uint8Array,+): Promise<Array<AuthSessionResponse>> {const {users} = ctx.services;const authSessions = await users.listAuthSessions(userId);- return await mapAuthSessionsToResponse({authSessions});+ return await mapAuthSessionsToResponse({authSessions, currentSessionIdHash});}export async function updateAuthSessionLastUsed(ctx: ApiContext, tokenHash: Uint8Array): Promise<void> {@@ -145,52 +150,28 @@ export async function updateAuthSessionLastUsed(ctx: ApiContext, tokenHash: Uint}export async function revokeToken(ctx: ApiContext, token: string): Promise<void> {- const {users, gateway} = ctx.services;+ const {users} = ctx.services;const tokenHash = Buffer.from(AuthUtility.getTokenIdHash(ctx, token));const authSession = await users.getAuthSessionByToken(tokenHash);if (!authSession) return;- const sessionIdHash = Buffer.from(authSession.sessionIdHash).toString('base64url');- await users.deletePushSubscriptionsForAuthSessions(authSession.userId, [sessionIdHash], {- deleteUnboundSubscriptions: true,- });- await gateway.invalidatePushSubscriptions({userId: authSession.userId});- await users.revokeAuthSession(tokenHash);- await gateway.terminateSession({- userId: authSession.userId,- sessionIdHashes: [sessionIdHash],- });+ await revokeAuthSessions(ctx.services, authSession.userId, [+ {sessionIdHash: tokenHash, encodedIdHash: encodeSessionIdHash(authSession.sessionIdHash)},+ ]);}export async function logoutAuthSessions(ctx: ApiContext,{user, sessionIdHashes}: LogoutAuthSessionsParams,): Promise<void> {- const {users, gateway} = ctx.services;- const hashes = sessionIdHashes.map((hash) => Buffer.from(hash, 'base64url'));- await users.deletePushSubscriptionsForAuthSessions(user.id, sessionIdHashes, {- deleteUnboundSubscriptions: true,- });- await gateway.invalidatePushSubscriptions({userId: user.id});- await users.deleteAuthSessions(user.id, hashes);- await gateway.terminateSession({- userId: user.id,- sessionIdHashes,- });+ await revokeAuthSessions(+ ctx.services,+ user.id,+ sessionIdHashes.map((encodedIdHash) => ({sessionIdHash: Buffer.from(encodedIdHash, 'base64url'), encodedIdHash})),+ );}export async function terminateAllUserSessions(ctx: ApiContext, userId: UserID): Promise<number> {- const {users, gateway} = ctx.services;- const authSessions = await users.listAuthSessions(userId);- await users.deleteAllPushSubscriptions(userId);- await gateway.invalidatePushSubscriptions({userId});- if (authSessions.length === 0) return 0;- const hashes = authSessions.map((s) => s.sessionIdHash);- await users.deleteAuthSessions(userId, hashes);- await gateway.terminateSession({- userId,- sessionIdHashes: authSessions.map((s) => Buffer.from(s.sessionIdHash).toString('base64url')),- });- return authSessions.length;+ return await revokeAllAuthSessions(ctx.services, userId);}export async function replaceCurrentAuthSession(@@ -229,20 +210,14 @@ async function deleteAndTerminateAuthSessions(if (authSessions.length === 0) {return;}- const {users, gateway} = ctx.services;- const sessionIdHashes = authSessions.map((authSession) => encodeSessionIdHash(authSession.sessionIdHash));- await users.deletePushSubscriptionsForAuthSessions(userId, sessionIdHashes, {- deleteUnboundSubscriptions: true,- });- await gateway.invalidatePushSubscriptions({userId});- await users.deleteAuthSessions(+ await revokeAuthSessions(+ ctx.services,userId,- authSessions.map((authSession) => authSession.sessionIdHash),+ authSessions.map((authSession) => ({+ sessionIdHash: authSession.sessionIdHash,+ encodedIdHash: encodeSessionIdHash(authSession.sessionIdHash),+ })),);- await gateway.terminateSession({- userId,- sessionIdHashes,- });}function encodeSessionIdHash(sessionIdHash: Uint8Array): string {diff --git a/fluxer_api/src/api/auth/AuthSessionRevocation.ts b/fluxer_api/src/api/auth/AuthSessionRevocation.tsnew file mode 100644index 000000000..5dcc0de49--- /dev/null+++ b/fluxer_api/src/api/auth/AuthSessionRevocation.ts@@ -0,0 +1,59 @@+import type {UserID} from '../BrandedTypes';+import type {IGatewayService} from '../infrastructure/IGatewayService';+import type {IUserRepositoryAggregate} from '../user/repositories/IUserRepositoryAggregate';+import {runAllInOrder} from '../utils/ConcurrencyUtils';++interface SessionRevocationDependencies {+ users: IUserRepositoryAggregate;+ gateway: IGatewayService;+}++interface SessionRevocationTarget {+ sessionIdHash: Buffer;+ encodedIdHash: string;+}++export async function revokeAuthSessions(+ deps: SessionRevocationDependencies,+ userId: UserID,+ targets: ReadonlyArray<SessionRevocationTarget>,+): Promise<void> {+ await revokeSessionTargets(deps, userId, targets, 'selected');+}++export async function revokeAllAuthSessions(deps: SessionRevocationDependencies, userId: UserID): Promise<number> {+ const sessions = await deps.users.listAuthSessions(userId);+ const targets = sessions.map((session) => ({+ sessionIdHash: session.sessionIdHash,+ encodedIdHash: session.sessionIdHash.toString('base64url'),+ }));+ await revokeSessionTargets(deps, userId, targets, 'all');+ return sessions.length;+}++async function revokeSessionTargets(+ {users, gateway}: SessionRevocationDependencies,+ userId: UserID,+ targets: ReadonlyArray<SessionRevocationTarget>,+ scope: 'selected' | 'all',+): Promise<void> {+ const sessionIdHashes = targets.map((target) => target.encodedIdHash);+ const steps: Array<() => Promise<unknown>> = [+ () =>+ scope === 'all'+ ? users.deleteAllPushSubscriptions(userId)+ : users.deletePushSubscriptionsForAuthSessions(userId, sessionIdHashes, {deleteUnboundSubscriptions: true}),+ () => gateway.invalidatePushSubscriptions({userId}),+ ];+ if (scope === 'selected' || targets.length > 0) {+ steps.push(+ () =>+ users.deleteAuthSessions(+ userId,+ targets.map((target) => target.sessionIdHash),+ ),+ () => gateway.terminateSession({userId, sessionIdHashes}),+ );+ }+ await runAllInOrder(steps, 'Failed to revoke auth sessions');+}diff --git a/fluxer_api/src/api/auth/AuthUtility.ts b/fluxer_api/src/api/auth/AuthUtility.tsindex 15b899a2c..930565fab 100644--- a/fluxer_api/src/api/auth/AuthUtility.ts+++ b/fluxer_api/src/api/auth/AuthUtility.ts@@ -104,6 +104,7 @@ function checkAccountBanStatus(_ctx: ApiContext, user: User): AccountBanStatus {export async function handleBanStatus(ctx: ApiContext, user: User): Promise<User> {const {users} = ctx.services;+ if (user.deletionStartedAt) throw new AccountPermanentlySuspendedError();const banStatus = checkAccountBanStatus(ctx, user);if (banStatus.isPermanentlyBanned) {throw new AccountPermanentlySuspendedError();diff --git a/fluxer_api/src/api/auth/PhonePrefixBanCache.ts b/fluxer_api/src/api/auth/PhonePrefixBanCache.tsindex 3d889ba24..cdb65cbc2 100644--- a/fluxer_api/src/api/auth/PhonePrefixBanCache.ts+++ b/fluxer_api/src/api/auth/PhonePrefixBanCache.ts@@ -1,9 +1,10 @@// SPDX-License-Identifier: AGPL-3.0-or-later-import type {IKVProvider, IKVSubscription} from '@pkgs/kv_client/src/IKVProvider';+import type {IKVProvider} from '@pkgs/kv_client/src/IKVProvider';import {AdminRepository} from '../admin/AdminRepository';import {PHONE_PREFIX_BAN_REFRESH_CHANNEL} from '../constants/PhonePrefixBan';import {Logger} from '../Logger';+import {RefreshSubscription} from '../utils/RefreshSubscription';const BUILT_IN_BANNED_PHONE_PREFIXES: ReadonlyArray<string> = ['+93',@@ -29,55 +30,31 @@ const BUILT_IN_BANNED_PHONE_PREFIXES: ReadonlyArray<string> = [export class PhonePrefixBanCache {private prefixes: Set<string> = new Set();private prefixLengths: ReadonlyArray<number> = [];- private isInitialized = false;private adminRepository = new AdminRepository();private kvClient: IKVProvider | null = null;- private kvSubscription: IKVSubscription | null = null;- private subscriberInitialized = false;- private messageHandler: ((channel: string) => void) | null = null;private consecutiveFailures = 0;private readonly maxConsecutiveFailures = 5;+ private readonly refreshSubscription = new RefreshSubscription({+ name: 'phone-prefix ban cache',+ channels: [PHONE_PREFIX_BAN_REFRESH_CHANNEL],+ refresh: () => this.refresh(),+ onRefreshError: (err) => {+ this.consecutiveFailures++;+ const message = err instanceof Error ? err.message : String(err);+ if (this.consecutiveFailures >= this.maxConsecutiveFailures) {+ Logger.error({error: message}, 'Failed to refresh phone-prefix ban cache after notification');+ } else {+ Logger.warn({error: message}, 'Failed to refresh phone-prefix ban cache after notification');+ }+ },+ });setRefreshSubscriber(kvClient: IKVProvider | null): void {this.kvClient = kvClient;}- async initialize(): Promise<void> {- if (this.isInitialized) return;- await this.refresh();- this.isInitialized = true;- this.setupSubscriber();- }-- private setupSubscriber(): void {- if (this.subscriberInitialized || !this.kvClient) return;- const subscription = this.kvClient.duplicate();- this.kvSubscription = subscription;- this.messageHandler = (channel: string) => {- if (channel === PHONE_PREFIX_BAN_REFRESH_CHANNEL) {- this.refresh().catch((err) => {- this.consecutiveFailures++;- const message = err instanceof Error ? err.message : String(err);- if (this.consecutiveFailures >= this.maxConsecutiveFailures) {- Logger.error({error: message}, 'Failed to refresh phone-prefix ban cache after notification');- } else {- Logger.warn({error: message}, 'Failed to refresh phone-prefix ban cache after notification');- }- });- }- };- subscription- .connect()- .then(() => subscription.subscribe(PHONE_PREFIX_BAN_REFRESH_CHANNEL))- .then(() => {- if (this.messageHandler) {- subscription.on('message', this.messageHandler);- }- })- .catch((error) => {- Logger.error({error}, 'Failed to subscribe to phone-prefix ban refresh channel');- });- this.subscriberInitialized = true;+ initialize(): Promise<void> {+ return this.refreshSubscription.start(this.kvClient);}async refresh(): Promise<void> {@@ -132,9 +109,11 @@ export class PhonePrefixBanCache {}resetForTests(): void {+ void this.shutdown().catch((error) => {+ Logger.error({error}, 'Failed to shut down phone-prefix ban cache');+ });this.prefixes = new Set();this.prefixLengths = [];- this.isInitialized = false;}private computeSortedLengths(): ReadonlyArray<number> {@@ -143,15 +122,8 @@ export class PhonePrefixBanCache {return [...seen].sort((a, b) => a - b);}- shutdown(): void {- if (this.kvSubscription && this.messageHandler) {- this.kvSubscription.off('message', this.messageHandler);- }- if (this.kvSubscription) {- this.kvSubscription.disconnect();- this.kvSubscription = null;- }- this.messageHandler = null;+ shutdown(): Promise<void> {+ return this.refreshSubscription.stop();}}diff --git a/fluxer_api/src/api/auth/services/SsoService.ts b/fluxer_api/src/api/auth/services/SsoService.tsindex 6305ce86d..86330b3ac 100644--- a/fluxer_api/src/api/auth/services/SsoService.ts+++ b/fluxer_api/src/api/auth/services/SsoService.ts@@ -10,6 +10,7 @@ import {ContentBlockedError} from '@fluxer/errors/src/domains/content/ContentBloimport {FeatureTemporarilyDisabledError} from '@fluxer/errors/src/domains/core/FeatureTemporarilyDisabledError';import {InputValidationError} from '@fluxer/errors/src/domains/core/InputValidationError';import {EmailType} from '@fluxer/schema/src/primitives/UserValidators';+import {formatUrlForDiagnostics} from '@pkgs/http_client/src/HttpClientDiagnostics';import {ms, seconds} from 'itty-time';import {type CryptoKey,@@ -377,6 +378,9 @@ export class SsoService {throw new RegistrationClosedError();}const pendingApproval = registrationConfig.mode === 'approval';+ if (pendingApproval) {+ await this.instanceConfigRepository.getPendingRegistrations();+ }const user = await this.provisionUserFromClaims(claims, config, {pendingApproval});if (pendingApproval) {await this.instanceConfigRepository.addPendingRegistration({@@ -675,6 +679,7 @@ export class SsoService {{requestUrlPolicy: getSsoRequestUrlPolicy()},);if (response.status < 200 || response.status >= 300) {+ FetchUtils.discardResponseBody(response.stream, response.status);throw new Error(`Failed to fetch JWKS: HTTP ${response.status}`);}const rawBody = await FetchUtils.streamToStringWithLimit(response.stream, {@@ -774,6 +779,7 @@ export class SsoService {{requestUrlPolicy: getSsoRequestUrlPolicy()},);if (resp.status < 200 || resp.status >= 300) {+ FetchUtils.discardResponseBody(resp.stream, resp.status);throw InputValidationError.fromCode('access_token', ValidationErrorCodes.FAILED_TO_FETCH_SSO_USER_INFO);}try {@@ -836,6 +842,7 @@ export class SsoService {{requestUrlPolicy: getSsoRequestUrlPolicy()},);if (resp.status < 200 || resp.status >= 300) {+ FetchUtils.discardResponseBody(resp.stream, resp.status);throw InputValidationError.fromCode('code', ValidationErrorCodes.INVALID_SSO_AUTHORIZATION_CODE);}const rawBody = await FetchUtils.streamToStringWithLimit(resp.stream, {@@ -926,7 +933,10 @@ export class SsoService {try {return await this.assertPublicOutboundUrl(rawUrl, fieldName);} catch (error) {- getLogger().warn({fieldName, rawUrl, error}, 'Ignoring SSO URL that failed outbound policy validation');+ getLogger().warn(+ {fieldName, rawUrl: formatUrlForDiagnostics(rawUrl), error},+ 'Ignoring SSO URL that failed outbound policy validation',+ );return null;}}diff --git a/fluxer_api/src/api/auth/services/SsoUtils.ts b/fluxer_api/src/api/auth/services/SsoUtils.tsindex c003241f0..9358d18c3 100644--- a/fluxer_api/src/api/auth/services/SsoUtils.ts+++ b/fluxer_api/src/api/auth/services/SsoUtils.ts@@ -1,5 +1,6 @@// SPDX-License-Identifier: AGPL-3.0-or-later+import {formatUrlForDiagnostics} from '@pkgs/http_client/src/HttpClientDiagnostics';import {ms} from 'itty-time';import {Logger} from '../../Logger';import {EXTERNAL_RESPONSE_LIMITS} from '../../utils/ExternalResponseLimits';@@ -52,7 +53,10 @@ export function parseTokenEndpointResponse(}function buildDiscoveryUrl(issuer: string): URL {- const issuerUrl = new URL(issuer);+ const issuerUrl = URL.parse(issuer);+ if (!issuerUrl) {+ throw new Error('Invalid OIDC issuer URL');+ }const normalized = issuerUrl.toString().replace(/\/$/, '');return new URL(`${normalized}/.well-known/openid-configuration`);}@@ -71,7 +75,10 @@ export async function tryDiscoverOidcProviderMetadata(issuer: string): Promise<Dtimeout: ms('10 seconds'),serviceName: 'sso_oidc_discovery',});- if (resp.status < 200 || resp.status >= 300) return null;+ if (resp.status < 200 || resp.status >= 300) {+ FetchUtils.discardResponseBody(resp.stream, resp.status);+ return null;+ }const rawBody = await FetchUtils.streamToStringWithLimit(resp.stream, {maxBytes: EXTERNAL_RESPONSE_LIMITS.ssoDiscoveryBytes,headers: resp.headers,@@ -94,7 +101,7 @@ export async function tryDiscoverOidcProviderMetadata(issuer: string): Promise<Djwks_uri: typeof json['jwks_uri'] === 'string' ? json['jwks_uri'] : undefined,};} catch (error) {- Logger.debug({issuer, error}, 'Failed to discover OIDC provider metadata');+ Logger.debug({issuer: formatUrlForDiagnostics(issuer), error}, 'Failed to discover OIDC provider metadata');return null;}}diff --git a/fluxer_api/src/api/bluesky/BlueskyOAuthController.ts b/fluxer_api/src/api/bluesky/BlueskyOAuthController.tsindex 107cdb94b..28c752686 100644--- a/fluxer_api/src/api/bluesky/BlueskyOAuthController.ts+++ b/fluxer_api/src/api/bluesky/BlueskyOAuthController.ts@@ -1,16 +1,12 @@// SPDX-License-Identifier: AGPL-3.0-or-later-import {ConnectionTypes} from '@fluxer/constants/src/ConnectionConstants';import {BlueskyAuthorizeRequest,BlueskyAuthorizeResponse,} from '@fluxer/schema/src/domains/connection/BlueskyOAuthSchemas';import {Config} from '../Config';import {BlueskyOAuthAuthorizationFailedError} from '../connection/errors/BlueskyOAuthAuthorizationFailedError';-import {BlueskyOAuthCallbackFailedError} from '../connection/errors/BlueskyOAuthCallbackFailedError';import {BlueskyOAuthNotEnabledError} from '../connection/errors/BlueskyOAuthNotEnabledError';-import {BlueskyOAuthStateInvalidError} from '../connection/errors/BlueskyOAuthStateInvalidError';-import {ConnectionAlreadyExistsError} from '../connection/errors/ConnectionAlreadyExistsError';import {Logger} from '../Logger';import {DefaultUserOnly, LoginRequired} from '../middleware/AuthMiddleware';import {RateLimitMiddleware} from '../middleware/RateLimitMiddleware';@@ -18,20 +14,31 @@ import {OpenAPI} from '../middleware/ResponseTypeMiddleware';import {ConnectionRateLimitConfigs} from '../rate_limit_configs/ConnectionRateLimitConfig';import type {HonoApp} from '../types/HonoEnv';import {Validator} from '../Validator';+import {BlueskyOAuthStateInvalidError, BlueskyOAuthStoreError} from './BlueskyOAuthStores';import {DisabledBlueskyOAuthService} from './DisabledBlueskyOAuthService';-import type {BlueskyAuthorizeResult, BlueskyCallbackResult} from './IBlueskyOAuthService';+import type {BlueskyAuthorizeResult, IBlueskyOAuthService} from './IBlueskyOAuthService';const BLUESKY_PROFILE_URL_RE = /^https?:\/\/bsky\.app\/profile\//i;+type BlueskyCallbackPhase = 'callback' | 'connection';+type BlueskyCallbackFailureReason = 'not_enabled' | 'state_invalid' | 'callback_failed' | 'unknown';function normalizeBlueskyHandle(input: string): string {- let handle = input.trim();- handle = handle.replace(BLUESKY_PROFILE_URL_RE, '');- handle = handle.replace(/^@/, '');- return handle;+ return input.trim().replace(BLUESKY_PROFILE_URL_RE, '').replace(/^@/, '');}-function isBlueskyOAuthEnabled(service: unknown): boolean {- return service != null && !(service instanceof DisabledBlueskyOAuthService);+function isBlueskyOAuthEnabled(service: IBlueskyOAuthService): boolean {+ return !(service instanceof DisabledBlueskyOAuthService);+}++function getCallbackFailureReason(error: unknown, phase: BlueskyCallbackPhase): BlueskyCallbackFailureReason {+ if (error instanceof BlueskyOAuthNotEnabledError) return 'not_enabled';+ if (+ error instanceof BlueskyOAuthStateInvalidError ||+ (error instanceof BlueskyOAuthStoreError && error.kind === 'state')+ ) {+ return 'state_invalid';+ }+ return phase === 'callback' ? 'callback_failed' : 'unknown';}export function BlueskyOAuthController(app: HonoApp) {@@ -84,15 +91,6 @@ export function BlueskyOAuthController(app: HonoApp) {const {handle: rawHandle} = ctx.req.valid('json');const userId = ctx.get('user').id;const handle = normalizeBlueskyHandle(rawHandle);- const connectionService = ctx.get('connectionService');- const connections = await connectionService.getConnectionsForUser(userId);- const lowerHandle = handle.toLowerCase();- const existing = connections.find(- (c) => c.connection_type === ConnectionTypes.BLUESKY && c.name.toLowerCase() === lowerHandle,- );- if (existing) {- throw new ConnectionAlreadyExistsError();- }let result: BlueskyAuthorizeResult;try {result = await service.authorize(handle, userId);@@ -100,7 +98,7 @@ export function BlueskyOAuthController(app: HonoApp) {if (error instanceof BlueskyOAuthNotEnabledError) {throw error;}- Logger.error({error, handle}, 'Bluesky OAuth authorize failed');+ Logger.error({error}, 'Bluesky OAuth authorize failed');throw new BlueskyOAuthAuthorizationFailedError();}return ctx.json({authorize_url: result.authorizeUrl});@@ -110,46 +108,26 @@ export function BlueskyOAuthController(app: HonoApp) {'/connections/bluesky/callback',RateLimitMiddleware(ConnectionRateLimitConfigs.BLUESKY_CALLBACK),async (ctx) => {- const appUrl = Config.endpoints.webApp;- const callbackUrl = `${appUrl}/connection-callback`;+ const callbackUrl = `${Config.endpoints.webApp}/connection-callback`;const service = ctx.get('blueskyOAuthService');if (!isBlueskyOAuthEnabled(service)) {return ctx.redirect(`${callbackUrl}?status=error&reason=not_enabled`);}+ let phase: BlueskyCallbackPhase = 'callback';try {- const params = new URLSearchParams(ctx.req.url.split('?')[1] ?? '');- let result: BlueskyCallbackResult;- try {- result = await service.callback(params);- } catch (callbackError) {- if (callbackError instanceof BlueskyOAuthNotEnabledError) {- throw callbackError;- }- Logger.error({error: callbackError}, 'Bluesky OAuth callback error from upstream');- if (- callbackError instanceof Error &&- (callbackError.message.toLowerCase().includes('state') ||- callbackError.message.toLowerCase().includes('expired'))- ) {- throw new BlueskyOAuthStateInvalidError();- }- throw new BlueskyOAuthCallbackFailedError();- }+ const params = new URL(ctx.req.url).searchParams;+ const result = await service.callback(params);+ phase = 'connection';const connectionService = ctx.get('connectionService');- await connectionService.createOrUpdateBlueskyConnection(result.userId, result.did, result.handle);+ await connectionService.createOrUpdateBlueskyConnection(result);return ctx.redirect(`${callbackUrl}?status=connected`);} catch (error) {- Logger.error({error}, 'Bluesky OAuth callback failed');- if (error instanceof BlueskyOAuthStateInvalidError) {- return ctx.redirect(`${callbackUrl}?status=error&reason=state_invalid`);- }- if (error instanceof BlueskyOAuthCallbackFailedError) {- return ctx.redirect(`${callbackUrl}?status=error&reason=callback_failed`);- }- if (error instanceof BlueskyOAuthNotEnabledError) {- return ctx.redirect(`${callbackUrl}?status=error&reason=not_enabled`);- }- return ctx.redirect(`${callbackUrl}?status=error&reason=unknown`);+ const reason = getCallbackFailureReason(error, phase);+ Logger.error(+ {phase, reason, storeError: error instanceof BlueskyOAuthStoreError ? error.message : undefined},+ 'Bluesky OAuth callback failed',+ );+ return ctx.redirect(`${callbackUrl}?status=error&reason=${reason}`);}},);diff --git a/fluxer_api/src/api/bluesky/BlueskyOAuthService.ts b/fluxer_api/src/api/bluesky/BlueskyOAuthService.tsindex 21bf95191..9659c6fc7 100644--- a/fluxer_api/src/api/bluesky/BlueskyOAuthService.ts+++ b/fluxer_api/src/api/bluesky/BlueskyOAuthService.ts@@ -1,23 +1,98 @@// SPDX-License-Identifier: AGPL-3.0-or-later+import {randomUUID} from 'node:crypto';import {readFile} from 'node:fs/promises';import {isAbsolute} from 'node:path';import {Agent} from '@atproto/api';import {JoseKey} from '@bluesky-social/jwk-jose';-import {NodeOAuthClient, requestLocalLock} from '@bluesky-social/oauth-client-node';+import {+ FetchError,+ NodeOAuthClient,+ type NodeSavedSessionStore,+ type OAuthClientMetadataInput,+ OAuthResponseError,+ requestLocalLock,+} from '@bluesky-social/oauth-client-node';import type {IKVProvider} from '@pkgs/kv_client/src/IKVProvider';-import {createUserID, type UserID} from '../BrandedTypes';-import type {BlueskyOAuthConfig} from '../config/APIConfig';-import {Logger} from '../Logger';-import {parseJsonRecord} from '../utils/JsonBoundaryUtils';-import {createKVSessionStore, createKVStateStore} from './BlueskyOAuthStores';-import type {BlueskyAuthorizeResult, BlueskyCallbackResult, IBlueskyOAuthService} from './IBlueskyOAuthService';+import type {UserID} from '../BrandedTypes';+import type {BlueskyOAuthConfig, BlueskyOAuthKeyConfig} from '../config/APIConfig';+import {ConnectionCredentialRepository} from '../connection/ConnectionCredentialRepository';+import {+ BlueskyOAuthStateInvalidError,+ BlueskyOAuthStoreError,+ createSessionStore,+ createStateStore,+ validateBlueskyGrantOwner,+} from './BlueskyOAuthStores';+import type {+ BlueskyAuthorizeResult,+ BlueskyCallbackResult,+ BlueskyOAuthGrantOwner,+ IBlueskyOAuthService,+} from './IBlueskyOAuthService';++interface BlueskyClientConfiguration {+ clientMetadata: OAuthClientMetadataInput;+ keyset: Array<JoseKey>;+}++interface BlueskyClientSession {+ client: NodeOAuthClient;+ sessionStore: NodeSavedSessionStore;+}++async function loadSigningKey(config: BlueskyOAuthKeyConfig, index: number): Promise<JoseKey> {+ const field = `Bluesky OAuth keys[${index}]`;+ let keyData = config.private_key;+ if (keyData == null) {+ const keyPath = config.private_key_path;+ if (!keyPath) {+ throw new Error(`${field} requires private_key or private_key_path`);+ }+ if (typeof keyPath !== 'string' || !isAbsolute(keyPath)) {+ throw new Error(`${field}.private_key_path must be absolute`);+ }+ try {+ keyData = await readFile(keyPath, 'utf-8');+ } catch {+ throw new Error(`${field}.private_key_path could not be read`);+ }+ }+ let key: JoseKey;+ try {+ key = await JoseKey.fromImportable(keyData, config.kid);+ } catch {+ throw new Error(`${field} must contain valid PEM or JWK key material`);+ }+ try {+ if (!key.matches({usage: 'sign', alg: 'ES256'})) return key;+ const publicJwk = key.publicJwk;+ if (!publicJwk) {+ throw new Error(`${field} has no advertised public key`);+ }+ const publicKey = await JoseKey.fromJWK(publicJwk);+ const jwt = await key.createJwt({alg: 'ES256'}, {});+ await publicKey.verifyJwt(jwt);+ } catch {+ throw new Error(`${field} must support ES256 signing with its advertised public key`);+ }+ return key;+}export class BlueskyOAuthService implements IBlueskyOAuthService {- private client: NodeOAuthClient;+ readonly clientMetadata: Record<string, unknown>;+ readonly jwks: Record<string, unknown>;+ private readonly credentials = new ConnectionCredentialRepository();- private constructor(client: NodeOAuthClient) {- this.client = client;+ private constructor(+ private readonly configuration: BlueskyClientConfiguration,+ private readonly kvClient: IKVProvider,+ ) {+ const {client} = this.createClient(() => {+ throw new Error('Bluesky public client documents have no grant owner');+ });+ this.clientMetadata = client.clientMetadata as Record<string, unknown>;+ this.jwks = client.jwks as Record<string, unknown>;}static async create(@@ -26,111 +101,107 @@ export class BlueskyOAuthService implements IBlueskyOAuthService {apiPublicEndpoint: string,): Promise<BlueskyOAuthService> {const baseUrl = apiPublicEndpoint.replace(/\/$/, '');- const keyset = await Promise.all(- config.keys.map(async (key) => {- const keyPath = key.private_key_path;- if (!key.private_key && keyPath && !isAbsolute(keyPath)) {- throw new Error(`Bluesky OAuth key path must be absolute, got: ${keyPath}`);- }- const keyData = key.private_key ?? (await readFile(keyPath!, 'utf-8'));- return JoseKey.fromImportable(keyData, key.kid);- }),- );- const stateStore = createKVStateStore(kvClient, 3600);- const sessionStore = createKVSessionStore(kvClient, 86400);- const client = new NodeOAuthClient({- clientMetadata: {- client_id: `${baseUrl}/connections/bluesky/client-metadata.json`,- client_name: config.client_name,- client_uri: baseUrl,- logo_uri: config.logo_uri || undefined,- tos_uri: config.tos_uri || undefined,- policy_uri: config.policy_uri || undefined,- redirect_uris: [`${baseUrl}/connections/bluesky/callback`],- grant_types: ['authorization_code', 'refresh_token'],- scope: 'atproto',- response_types: ['code'],- application_type: 'web',- token_endpoint_auth_method: 'private_key_jwt',- token_endpoint_auth_signing_alg: 'ES256',- dpop_bound_access_tokens: true,- jwks_uri: `${baseUrl}/connections/bluesky/jwks.json`,+ const keyset: Array<JoseKey> = [];+ for (const [index, key] of config.keys.entries()) {+ keyset.push(await loadSigningKey(key, index));+ }+ return new BlueskyOAuthService(+ {+ clientMetadata: {+ client_id: `${baseUrl}/connections/bluesky/client-metadata.json`,+ client_name: config.client_name,+ client_uri: baseUrl,+ logo_uri: config.logo_uri || undefined,+ tos_uri: config.tos_uri || undefined,+ policy_uri: config.policy_uri || undefined,+ redirect_uris: [`${baseUrl}/connections/bluesky/callback`],+ grant_types: ['authorization_code', 'refresh_token'],+ scope: 'atproto',+ response_types: ['code'],+ application_type: 'web',+ token_endpoint_auth_method: 'private_key_jwt',+ token_endpoint_auth_signing_alg: 'ES256',+ dpop_bound_access_tokens: true,+ jwks_uri: `${baseUrl}/connections/bluesky/jwks.json`,+ },+ keyset,},- keyset,- requestLock: requestLocalLock,- stateStore,- sessionStore,- });- return new BlueskyOAuthService(client);- }-- get clientMetadata(): Record<string, unknown> {- return this.client.clientMetadata as Record<string, unknown>;- }-- get jwks(): Record<string, unknown> {- return this.client.jwks as Record<string, unknown>;+ kvClient,+ );}async authorize(handle: string, userId: UserID): Promise<BlueskyAuthorizeResult> {- const statePayload = JSON.stringify({userId: String(userId)});- const url = await this.client.authorize(handle, {state: statePayload});- return {authorizeUrl: url.toString()};+ try {+ const owner = validateBlueskyGrantOwner({userId, grantId: randomUUID()});+ const {client} = this.createClient(() => owner);+ const state = JSON.stringify({userId: String(owner.userId), grantId: owner.grantId});+ const url = await client.authorize(handle, {state});+ return {authorizeUrl: url.toString()};+ } catch (error) {+ throw createOAuthOperationError('authorize account', error);+ }}async callback(params: URLSearchParams): Promise<BlueskyCallbackResult> {- const {session, state} = await this.client.callback(params);- const parsed = state ? parseJsonRecord(state) : null;- const parsedUserId = typeof parsed?.userId === 'string' ? parsed.userId : null;- if (!parsedUserId) {- throw new Error('Bluesky OAuth callback state is missing userId');+ if (!params.has('response') && !params.get('state')) {+ throw new BlueskyOAuthStateInvalidError();}- const userId = createUserID(BigInt(parsedUserId));+ let owner: BlueskyOAuthGrantOwner | undefined;+ const requireOwner = (): BlueskyOAuthGrantOwner => {+ if (!owner) throw new BlueskyOAuthStateInvalidError();+ return owner;+ };+ const {client} = this.createClient(requireOwner, (consumedOwner) => {+ if (owner) throw new BlueskyOAuthStateInvalidError();+ owner = consumedOwner;+ });+ const {session} = await client.callback(params);+ const grantOwner = requireOwner();const handle = await this.resolveHandle(session.did);return {- userId,+ ...grantOwner,did: session.did,handle,};}- async restoreAndVerify(did: string): Promise<{- handle: string;- } | null> {- try {- await this.client.restore(did);- const handle = await this.resolveHandle(did);- return {handle};- } catch (error) {- Logger.error(- {- did,- error: error instanceof Error ? error.message : String(error),- },- 'Failed to restore and verify Bluesky session',- );- return null;- }+ private createClient(+ resolveOwner: () => BlueskyOAuthGrantOwner,+ onConsume?: (owner: BlueskyOAuthGrantOwner) => void,+ ): BlueskyClientSession {+ const sessionStore = createSessionStore(this.credentials, 86400, resolveOwner);+ const client = new NodeOAuthClient({+ ...this.configuration,+ stateStore: createStateStore(this.kvClient, this.credentials, 3600, resolveOwner, onConsume),+ sessionStore,+ requestLock: (name, operation) => {+ const owner = resolveOwner();+ return requestLocalLock(`bsky:${owner.userId}:${owner.grantId}:${name}`, operation);+ },+ });+ return {client, sessionStore};}private async resolveHandle(did: string): Promise<string> {const agent = new Agent('https://public.api.bsky.app');- const profile = await agent.getProfile({actor: did});- return profile.data.handle;- }-- async revoke(did: string): Promise<void> {try {- const session = await this.client.restore(did);- await session.signOut();+ const profile = await agent.getProfile({actor: did});+ return profile.data.handle;} catch (error) {- Logger.debug(- {- did,- error: error instanceof Error ? error.message : String(error),- },- 'Failed to revoke Bluesky session (session may be expired or already revoked)',- );+ throw createOAuthOperationError('resolve profile', error);}}}++function createOAuthOperationError(+ operation: 'authorize account' | 'restore session' | 'resolve profile',+ error: unknown,+): Error {+ if (error instanceof BlueskyOAuthStoreError) return error;+ let status: number | undefined;+ if (error instanceof OAuthResponseError) status = error.status;+ else if (error instanceof FetchError) status = error.statusCode;+ const detail =+ status !== undefined && Number.isInteger(status) && status >= 100 && status <= 599 ? ` (HTTP ${status})` : '';+ return new Error(`Bluesky OAuth could not ${operation}${detail}`);+}diff --git a/fluxer_api/src/api/bluesky/BlueskyOAuthStores.ts b/fluxer_api/src/api/bluesky/BlueskyOAuthStores.tsindex e27af5000..ebbbe0a01 100644--- a/fluxer_api/src/api/bluesky/BlueskyOAuthStores.ts+++ b/fluxer_api/src/api/bluesky/BlueskyOAuthStores.ts@@ -1,48 +1,207 @@// SPDX-License-Identifier: AGPL-3.0-or-later-import type {NodeSavedSession, NodeSavedState} from '@bluesky-social/oauth-client-node';+import {+ type AtprotoDid,+ type AtprotoOAuthScope,+ isAtprotoDid,+ isAtprotoOAuthScope,+ type Jwk,+ jwkPrivateSchema,+ type NodeSavedSession,+ type NodeSavedSessionStore,+ type NodeSavedState,+ type NodeSavedStateStore,+} from '@bluesky-social/oauth-client-node';+import {SnowflakeType} from '@fluxer/schema/src/primitives/SchemaPrimitives';import type {IKVProvider} from '@pkgs/kv_client/src/IKVProvider';-import {isJsonRecord, parseJsonWithGuard} from '../utils/JsonBoundaryUtils';+import {z} from 'zod';+import {createUserID} from '../BrandedTypes';+import type {ConnectionCredentialRepository} from '../connection/ConnectionCredentialRepository';+import type {BlueskyOAuthGrantOwner} from './IBlueskyOAuthService';-const STATE_PREFIX = 'bsky:oauth:state:';-const SESSION_PREFIX = 'bsky:oauth:session:';+const STATE_LOCATOR_PREFIX = 'bsky:oauth:state_locator:';-function isNodeSavedState(value: unknown): value is NodeSavedState {- return isJsonRecord(value);+const GrantOwnerSchema: z.ZodType<BlueskyOAuthGrantOwner> = z.strictObject({+ userId: z+ .string()+ .max(19)+ .regex(/^(0|[1-9]\d*)$/)+ .transform((value, ctx) => {+ const parsed = SnowflakeType.safeParse(value);+ if (!parsed.success) {+ ctx.addIssue({code: 'custom', message: 'Invalid user ID'});+ return z.NEVER;+ }+ return createUserID(parsed.data);+ }),+ grantId: z.uuid(),+});+const SavedAuthMethodSchema = z.strictObject({method: z.literal('private_key_jwt'), kid: z.string().min(1)});+const SavedKeySchema = z.custom<Jwk>((value) => jwkPrivateSchema.safeParse(value).success);+const SavedStateSchema: z.ZodType<NodeSavedState> = z.strictObject({+ iss: z.string(),+ dpopJwk: SavedKeySchema,+ authMethod: SavedAuthMethodSchema,+ verifier: z.string().min(1),+ appState: z.string(),+});+const SavedSessionSchema: z.ZodType<NodeSavedSession> = z.strictObject({+ dpopJwk: SavedKeySchema,+ authMethod: SavedAuthMethodSchema,+ tokenSet: z.strictObject({+ iss: z.string(),+ sub: z.custom<AtprotoDid>(isAtprotoDid),+ aud: z.string(),+ scope: z.custom<AtprotoOAuthScope>((value) => typeof value === 'string' && isAtprotoOAuthScope(value)),+ refresh_token: z.string().optional(),+ access_token: z.string(),+ token_type: z.literal('DPoP'),+ expires_at: z.iso.datetime().optional(),+ }),+});++type BlueskyOAuthStoreKind = 'state' | 'session';++export class BlueskyOAuthStateInvalidError extends Error {+ constructor() {+ super('Bluesky OAuth state is invalid');+ }}-function isNodeSavedSession(value: unknown): value is NodeSavedSession {- return isJsonRecord(value);+export class BlueskyOAuthStoreError extends Error {+ constructor(+ readonly kind: BlueskyOAuthStoreKind,+ message: string,+ ) {+ super(message);+ }}-export function createKVStateStore(kvClient: IKVProvider, ttlSeconds: number) {+function parseBlueskyGrantOwner(state: string | null | undefined): BlueskyOAuthGrantOwner {+ if (typeof state !== 'string' || state.length > 128) throw new BlueskyOAuthStateInvalidError();+ let value: unknown;+ try {+ value = JSON.parse(state);+ } catch {+ throw new BlueskyOAuthStateInvalidError();+ }+ const parsed = GrantOwnerSchema.safeParse(value);+ if (!parsed.success) throw new BlueskyOAuthStateInvalidError();+ return parsed.data;+}++export function validateBlueskyGrantOwner(owner: BlueskyOAuthGrantOwner): BlueskyOAuthGrantOwner {+ if (owner === null || typeof owner !== 'object' || typeof owner.userId !== 'bigint') {+ throw new BlueskyOAuthStoreError('session', 'Bluesky OAuth session owner is invalid');+ }+ const parsed = GrantOwnerSchema.safeParse({userId: String(owner.userId), grantId: owner.grantId});+ if (!parsed.success) {+ throw new BlueskyOAuthStoreError('session', 'Bluesky OAuth session owner is invalid');+ }+ return parsed.data;+}++function parseSavedValue<T>(+ data: string | undefined,+ schema: z.ZodType<T>,+ kind: BlueskyOAuthStoreKind,+): T | undefined {+ if (data === undefined) return undefined;+ let value: unknown;+ try {+ value = JSON.parse(data);+ } catch {+ throw new BlueskyOAuthStoreError(kind, `Stored Bluesky OAuth ${kind} is not valid JSON`);+ }+ const parsed = schema.safeParse(value);+ if (!parsed.success) {+ const path = parsed.error.issues[0]?.path.join('.') || 'root';+ throw new BlueskyOAuthStoreError(kind, `Stored Bluesky OAuth ${kind} has an invalid ${path}`);+ }+ return parsed.data;+}++export function createStateStore(+ kvClient: IKVProvider,+ credentials: ConnectionCredentialRepository,+ ttlSeconds: number,+ resolveOwner: () => BlueskyOAuthGrantOwner,+ onConsume?: (owner: BlueskyOAuthGrantOwner) => void,+): NodeSavedStateStore {return {async set(key: string, internalState: NodeSavedState): Promise<void> {- await kvClient.setex(`${STATE_PREFIX}${key}`, ttlSeconds, JSON.stringify(internalState));+ const owner = validateBlueskyGrantOwner(resolveOwner());+ const stateOwner = parseBlueskyGrantOwner(internalState.appState);+ if (stateOwner.userId !== owner.userId || stateOwner.grantId !== owner.grantId) {+ throw new BlueskyOAuthStateInvalidError();+ }+ await credentials.createState(owner, key, JSON.stringify(internalState), ttlSeconds);+ await kvClient.setex(+ `${STATE_LOCATOR_PREFIX}${key}`,+ ttlSeconds,+ JSON.stringify({userId: String(owner.userId), grantId: owner.grantId}),+ );},async get(key: string): Promise<NodeSavedState | undefined> {- const data = await kvClient.getdel(`${STATE_PREFIX}${key}`);- if (!data) return undefined;- return parseJsonWithGuard(data, isNodeSavedState) ?? undefined;+ const locator = await kvClient.getdel(`${STATE_LOCATOR_PREFIX}${key}`);+ if (locator === null) return undefined;+ const owner = parseBlueskyGrantOwner(locator);+ const state = parseSavedValue(await credentials.consumeState(owner, key), SavedStateSchema, 'state');+ if (state !== undefined) {+ const stateOwner = parseBlueskyGrantOwner(state.appState);+ if (stateOwner.userId !== owner.userId || stateOwner.grantId !== owner.grantId) {+ throw new BlueskyOAuthStateInvalidError();+ }+ onConsume?.(owner);+ }+ return state;},async del(key: string): Promise<void> {- await kvClient.del(`${STATE_PREFIX}${key}`);+ const locator = await kvClient.getdel(`${STATE_LOCATOR_PREFIX}${key}`);+ if (locator !== null) await credentials.discardPendingState(parseBlueskyGrantOwner(locator), key);},};}-export function createKVSessionStore(kvClient: IKVProvider, ttlSeconds: number) {+export function createSessionStore(+ credentials: ConnectionCredentialRepository,+ ttlSeconds: number,+ resolveOwner: () => BlueskyOAuthGrantOwner,+): NodeSavedSessionStore {+ function sessionOwner(sub: string): BlueskyOAuthGrantOwner {+ const owner = validateBlueskyGrantOwner(resolveOwner());+ if (!isAtprotoDid(sub)) {+ throw new BlueskyOAuthStoreError('session', 'Bluesky OAuth session identity is invalid');+ }+ return owner;+ }+return {async set(sub: string, session: NodeSavedSession): Promise<void> {- await kvClient.setex(`${SESSION_PREFIX}${sub}`, ttlSeconds, JSON.stringify(session));+ if (session.tokenSet.sub !== sub) {+ throw new BlueskyOAuthStoreError('session', 'Bluesky OAuth session does not match the requested identity');+ }+ await credentials.setSession(sessionOwner(sub), sub, JSON.stringify(session), ttlSeconds);},async get(sub: string): Promise<NodeSavedSession | undefined> {- const data = await kvClient.get(`${SESSION_PREFIX}${sub}`);- if (!data) return undefined;- return parseJsonWithGuard(data, isNodeSavedSession) ?? undefined;+ const owner = sessionOwner(sub);+ let data: string | undefined;+ try {+ data = await credentials.getSession(owner, sub);+ } catch {+ throw new BlueskyOAuthStoreError('session', 'Could not read stored Bluesky OAuth session');+ }+ const session = parseSavedValue(data, SavedSessionSchema, 'session');+ if (session !== undefined && session.tokenSet.sub !== sub) {+ throw new BlueskyOAuthStoreError(+ 'session',+ 'Stored Bluesky OAuth session does not match the requested identity',+ );+ }+ return session;},async del(sub: string): Promise<void> {- await kvClient.del(`${SESSION_PREFIX}${sub}`);+ await credentials.deleteSession(sessionOwner(sub), sub);},};}diff --git a/fluxer_api/src/api/bluesky/DisabledBlueskyOAuthService.ts b/fluxer_api/src/api/bluesky/DisabledBlueskyOAuthService.tsindex efacbc986..7ff62df8f 100644--- a/fluxer_api/src/api/bluesky/DisabledBlueskyOAuthService.ts+++ b/fluxer_api/src/api/bluesky/DisabledBlueskyOAuthService.ts@@ -15,14 +15,4 @@ export class DisabledBlueskyOAuthService implements IBlueskyOAuthService {async callback(_params: URLSearchParams): Promise<BlueskyCallbackResult> {throw new BlueskyOAuthNotEnabledError();}-- async restoreAndVerify(_did: string): Promise<{- handle: string;- } | null> {- throw new BlueskyOAuthNotEnabledError();- }-- async revoke(_did: string): Promise<void> {- throw new BlueskyOAuthNotEnabledError();- }}diff --git a/fluxer_api/src/api/bluesky/IBlueskyOAuthService.ts b/fluxer_api/src/api/bluesky/IBlueskyOAuthService.tsindex a34128e24..e05042fcc 100644--- a/fluxer_api/src/api/bluesky/IBlueskyOAuthService.ts+++ b/fluxer_api/src/api/bluesky/IBlueskyOAuthService.ts@@ -6,9 +6,16 @@ export interface BlueskyAuthorizeResult {authorizeUrl: string;}-export interface BlueskyCallbackResult {+export interface BlueskyOAuthGrantOwner {userId: UserID;+ grantId: string;+}++interface BlueskyOAuthGrant extends BlueskyOAuthGrantOwner {did: string;+}++export interface BlueskyCallbackResult extends BlueskyOAuthGrant {handle: string;}@@ -17,8 +24,4 @@ export interface IBlueskyOAuthService {readonly jwks: Record<string, unknown>;authorize(handle: string, userId: UserID): Promise<BlueskyAuthorizeResult>;callback(params: URLSearchParams): Promise<BlueskyCallbackResult>;- restoreAndVerify(did: string): Promise<{- handle: string;- } | null>;- revoke(did: string): Promise<void>;}diff --git a/fluxer_api/src/api/channel/services/message/AttachmentProcessingService.ts b/fluxer_api/src/api/channel/services/message/AttachmentProcessingService.tsindex 588c24a5c..c72f70cea 100644--- a/fluxer_api/src/api/channel/services/message/AttachmentProcessingService.ts+++ b/fluxer_api/src/api/channel/services/message/AttachmentProcessingService.ts@@ -16,9 +16,13 @@ import {createAttachmentID, type UserID} from '../../../BrandedTypes';import {Config} from '../../../Config';import type {MessageAttachment} from '../../../database/types/MessageTypes';import {contentModerationService, type ModerationContext} from '../../../infrastructure/ContentModerationService';-import type {IMediaService, MediaProxyNsfwMode} from '../../../infrastructure/IMediaService';+import type {+ IMediaService,+ MediaProxyMetadataResponse,+ MediaProxyNsfwMode,+} from '../../../infrastructure/IMediaService';import type {ISnowflakeService} from '../../../infrastructure/ISnowflakeService';-import type {IStorageService} from '../../../infrastructure/IStorageService';+import type {IStorageService, ProcessedStorageObjectMetadata} from '../../../infrastructure/IStorageService';import {hashFileSha256} from '../../../infrastructure/StorageObjectHelpers';import {Logger} from '../../../Logger';import type {Channel} from '../../../models/Channel';@@ -80,52 +84,51 @@ export class AttachmentProcessingService {hasVirusDetected: boolean;}> {validateAttachmentIds(params.attachments.map((a) => ({id: BigInt(a.id)})));- const results = await mapWithConcurrency(- params.attachments,- ATTACHMENT_PROCESSING_CONCURRENCY,- (attachment, index) =>- this.processAttachment({- message: params.message,- attachment,- index,- uploadUserId: params.uploadUserId,- channel: params.channel,- guild: params.guild,- member: params.member,- nsfwMode: params.nsfwMode,- }),- );- const hasVirusDetected = results.some((result) => result.hasVirusDetected);- if (hasVirusDetected) {- await Promise.all(- results.map(async (result) => {- if (result.sourceLocalPath) {- await fs.promises.unlink(result.sourceLocalPath).catch(() => undefined);- }- }),+ const retainedLocalPaths: Array<string> = [];+ let results: Array<ProcessedAttachment>;+ let copyResults: Array<ProcessedStorageObjectMetadata | null>;+ let hasVirusDetected: boolean;+ try {+ results = await mapWithConcurrency(+ params.attachments,+ ATTACHMENT_PROCESSING_CONCURRENCY,+ async (attachment, index) => {+ const result = await this.processAttachment({+ message: params.message,+ attachment,+ index,+ uploadUserId: params.uploadUserId,+ channel: params.channel,+ guild: params.guild,+ member: params.member,+ nsfwMode: params.nsfwMode,+ });+ if (result.sourceLocalPath !== null) retainedLocalPaths.push(result.sourceLocalPath);+ return result;+ },);+ hasVirusDetected = results.some((result) => result.hasVirusDetected);+ copyResults = hasVirusDetected+ ? []+ : await mapWithConcurrency(results, ATTACHMENT_PROCESSING_CONCURRENCY, (result) =>+ this.storageService.copyObjectWithMetadataStripping({+ sourceBucket: result.copyOperation.sourceBucket,+ sourceKey: result.copyOperation.sourceKey,+ destinationBucket: result.copyOperation.destinationBucket,+ destinationKey: result.copyOperation.destinationKey,+ contentType: result.copyOperation.newContentType,+ ...(result.sourceLocalPath ? {sourceLocalPath: result.sourceLocalPath} : {}),+ }),+ );+ } finally {+ await Promise.all(retainedLocalPaths.map((localPath) => fs.promises.unlink(localPath).catch(() => undefined)));+ }+ if (hasVirusDetected) {for (const result of results) {this.deleteUploadObject(result.copyOperation.sourceBucket, result.copyOperation.sourceKey);}return {attachments: [], hasVirusDetected: true};}- const copyResults = await mapWithConcurrency(results, ATTACHMENT_PROCESSING_CONCURRENCY, (result) =>- this.storageService.copyObjectWithMetadataStripping({- sourceBucket: result.copyOperation.sourceBucket,- sourceKey: result.copyOperation.sourceKey,- destinationBucket: result.copyOperation.destinationBucket,- destinationKey: result.copyOperation.destinationKey,- contentType: result.copyOperation.newContentType,- ...(result.sourceLocalPath ? {sourceLocalPath: result.sourceLocalPath} : {}),- }),- );- await Promise.all(- results.map(async (result) => {- if (result.sourceLocalPath) {- await fs.promises.unlink(result.sourceLocalPath).catch(() => undefined);- }- }),- );const bindingResults = await Promise.all(results.map(async (result, index) => ({index,@@ -206,7 +209,7 @@ export class AttachmentProcessingService {const clientDuration: number | null = attachment.duration ?? null;const waveform: string | null = attachment.waveform ?? null;const isMedia = isMediaFile(contentType);- let metadata: Awaited<ReturnType<AttachmentProcessingService['getAttachmentMediaMetadata']>> = null;+ let metadata: MediaProxyMetadataResponse | null = null;if (isMedia) {metadata = await this.getAttachmentMediaMetadata({index,@@ -347,7 +350,7 @@ export class AttachmentProcessingService {uploadFilename: string;filename: string;nsfwMode: MediaProxyNsfwMode;- }) {+ }): Promise<MediaProxyMetadataResponse | null> {try {const metadata = await this.mediaService.getMetadata({type: 'upload',diff --git a/fluxer_api/src/api/connection/ConnectionController.ts b/fluxer_api/src/api/connection/ConnectionController.tsindex 7b53aa21d..2deba931d 100644--- a/fluxer_api/src/api/connection/ConnectionController.ts+++ b/fluxer_api/src/api/connection/ConnectionController.ts@@ -130,29 +130,6 @@ export function ConnectionController(app: HonoApp) {return ctx.body(null, 204);},);- app.post(- '/users/@me/connections/:type/:connection_id/verify',- RateLimitMiddleware(ConnectionRateLimitConfigs.CONNECTION_VERIFY),- LoginRequired,- DefaultUserOnly,- Validator('param', ConnectionTypeParam),- OpenAPI({- operationId: 'verify_connection',- summary: 'Verify connection',- responseSchema: ConnectionResponse,- statusCode: 200,- security: ['bearerToken', 'sessionToken'],- tags: ['Connections'],- description: 'Triggers verification for an external service connection.',- }),- async (ctx) => {- const {type, connection_id} = ctx.req.valid('param');- const connection = await ctx- .get('connectionRequestService')- .verifyConnection(ctx.get('user').id, type, connection_id);- return ctx.json(connection);- },- );app.patch('/users/@me/connections/reorder',RateLimitMiddleware(ConnectionRateLimitConfigs.CONNECTION_UPDATE),diff --git a/fluxer_api/src/api/connection/ConnectionCredentialRepository.ts b/fluxer_api/src/api/connection/ConnectionCredentialRepository.tsnew file mode 100644index 000000000..4aaa0adc9--- /dev/null+++ b/fluxer_api/src/api/connection/ConnectionCredentialRepository.ts@@ -0,0 +1,247 @@+import {randomUUID} from 'node:crypto';+import {isAtprotoDid} from '@bluesky-social/oauth-client-node';+import {z} from 'zod';+import type {UserID} from '../BrandedTypes';+import type {BlueskyOAuthGrantOwner} from '../bluesky/IBlueskyOAuthService';+import {executeConditional, fetchMany} from '../database/CassandraQueryExecution';+import {type ConditionalWriteEntry, Db, validateTtlSeconds} from '../database/CassandraTypes';+import {USER_CONNECTION_CREDENTIAL_TYPE, type UserConnectionStorageRow} from '../database/types/ConnectionTypes';+import {UserConnections} from '../Tables';+import {+ CONNECTION_WRITE_ATTEMPTS,+ ConnectionOwnerClosedError,+ ConnectionWriteConflictError,+ connectionMembershipPatch,+ createPrivateConnectionRow,+ loadConnectionMembership,+} from './ConnectionMembership';++type CredentialWrite = ConditionalWriteEntry<UserConnectionStorageRow, 'user_id' | 'connection_type' | 'connection_id'>;++const CredentialPayload = z.discriminatedUnion('phase', [+ z.strictObject({phase: z.literal('pending'), stateKey: z.string().min(1), payload: z.string().min(1)}),+ z.strictObject({phase: z.literal('consumed'), stateKey: z.string().min(1)}),+ z.strictObject({+ phase: z.literal('active'),+ did: z.string().refine(isAtprotoDid),+ payload: z.string().min(1),+ }),+]);+type CredentialPayload = z.infer<typeof CredentialPayload>;++interface CredentialSnapshot {+ revision: string;+ expiresAt: Date;+ value: CredentialPayload;+}++interface CredentialOperation<T> {+ result: T;+ write?: CredentialWrite;+}++const FETCH_CREDENTIAL_CQL = UserConnections.selectCql({+ where: [+ UserConnections.where.eq('user_id'),+ UserConnections.where.eq('connection_type'),+ UserConnections.where.eq('connection_id'),+ ],+ limit: 1,+});++class ConnectionCredentialUnavailableError extends Error {+ constructor() {+ super('Connection credentials are no longer available');+ }+}++export function connectionCredentialKey(owner: BlueskyOAuthGrantOwner): {+ user_id: UserID;+ connection_type: string;+ connection_id: string;+} {+ if (typeof owner.userId !== 'bigint' || !z.uuid().safeParse(owner.grantId).success) {+ throw new Error('Connection credentials have an invalid owner');+ }+ return {+ user_id: owner.userId,+ connection_type: USER_CONNECTION_CREDENTIAL_TYPE,+ connection_id: owner.grantId,+ };+}++export async function readConnectionCredential(+ owner: BlueskyOAuthGrantOwner,+): Promise<UserConnectionStorageRow | null> {+ const key = connectionCredentialKey(owner);+ const [row] = await fetchMany<UserConnectionStorageRow>(FETCH_CREDENTIAL_CQL, key, {consistency: 'serial'});+ return row ?? null;+}++function credentialExpiry(ttlSeconds: number): Date {+ validateTtlSeconds(ttlSeconds);+ if (ttlSeconds === 0) throw new Error('Connection credentials require a positive expiry');+ return new Date(Date.now() + ttlSeconds * 1000);+}++function credentialPatch(+ owner: BlueskyOAuthGrantOwner,+ snapshot: CredentialSnapshot,+ value: CredentialPayload,+ expiresAt: Date,+): CredentialWrite {+ const ttlSeconds = Math.ceil((expiresAt.getTime() - Date.now()) / 1000);+ if (ttlSeconds <= 0) throw new ConnectionCredentialUnavailableError();+ return {+ action: 'patch',+ pk: connectionCredentialKey(owner),+ patch: {+ revision: Db.set(randomUUID()),+ credential_payload: Db.set(JSON.stringify(value)),+ credential_expires_at: Db.set(expiresAt),+ },+ expected: {revision: snapshot.revision},+ ttlSeconds,+ };+}++export class ConnectionCredentialRepository {+ async createState(+ owner: BlueskyOAuthGrantOwner,+ stateKey: string,+ payload: string,+ ttlSeconds: number,+ ): Promise<void> {+ const expiresAt = credentialExpiry(ttlSeconds);+ const value = CredentialPayload.parse({phase: 'pending', stateKey, payload});+ await this.withOwner(owner, (snapshot) => {+ if (snapshot) throw new ConnectionWriteConflictError();+ const remainingTtl = Math.ceil((expiresAt.getTime() - Date.now()) / 1000);+ if (remainingTtl <= 0) throw new ConnectionCredentialUnavailableError();+ return {+ result: undefined,+ write: {+ action: 'insert',+ row: {+ ...createPrivateConnectionRow(owner.userId, USER_CONNECTION_CREDENTIAL_TYPE, owner.grantId),+ credential_payload: JSON.stringify(value),+ credential_expires_at: expiresAt,+ },+ ttlSeconds: remainingTtl,+ },+ };+ });+ }++ async consumeState(owner: BlueskyOAuthGrantOwner, stateKey: string): Promise<string | undefined> {+ const state = await this.withOwner<{payload: string; expiresAt: Date} | undefined>(owner, (snapshot) => {+ if (snapshot?.value.phase !== 'pending' || snapshot.value.stateKey !== stateKey) {+ return {result: undefined};+ }+ return {+ result: {payload: snapshot.value.payload, expiresAt: snapshot.expiresAt},+ write: credentialPatch(owner, snapshot, {phase: 'consumed', stateKey}, snapshot.expiresAt),+ };+ });+ return state && state.expiresAt.getTime() > Date.now() ? state.payload : undefined;+ }++ async discardPendingState(owner: BlueskyOAuthGrantOwner, stateKey: string): Promise<void> {+ await this.cleanup(owner, (snapshot) => ({+ result: undefined,+ write:+ snapshot?.value.phase === 'pending' && snapshot.value.stateKey === stateKey+ ? {action: 'delete', pk: connectionCredentialKey(owner), expected: {revision: snapshot.revision}}+ : undefined,+ }));+ }++ async getSession(owner: BlueskyOAuthGrantOwner, did: string): Promise<string | undefined> {+ const session = await this.withOwner(owner, (snapshot) => ({+ result:+ snapshot?.value.phase === 'active' && snapshot.value.did === did+ ? {payload: snapshot.value.payload, expiresAt: snapshot.expiresAt}+ : undefined,+ }));+ return session && session.expiresAt.getTime() > Date.now() ? session.payload : undefined;+ }++ async setSession(owner: BlueskyOAuthGrantOwner, did: string, payload: string, ttlSeconds: number): Promise<void> {+ const expiresAt = credentialExpiry(ttlSeconds);+ const value = CredentialPayload.parse({phase: 'active', did, payload});+ await this.withOwner(owner, (snapshot) => {+ if (+ !snapshot ||+ snapshot.value.phase === 'pending' ||+ (snapshot.value.phase === 'active' && snapshot.value.did !== did)+ ) {+ throw new ConnectionCredentialUnavailableError();+ }+ return {result: undefined, write: credentialPatch(owner, snapshot, value, expiresAt)};+ });+ }++ async deleteSession(owner: BlueskyOAuthGrantOwner, did: string): Promise<void> {+ await this.cleanup(owner, (snapshot) => ({+ result: undefined,+ write:+ snapshot?.value.phase === 'active' && snapshot.value.did === did+ ? {action: 'delete', pk: connectionCredentialKey(owner), expected: {revision: snapshot.revision}}+ : undefined,+ }));+ }++ private async cleanup(+ owner: BlueskyOAuthGrantOwner,+ operation: (snapshot: CredentialSnapshot | null) => CredentialOperation<void>,+ ): Promise<void> {+ try {+ await this.withOwner(owner, operation);+ } catch (error) {+ if (!(error instanceof ConnectionOwnerClosedError)) throw error;+ }+ }++ private async withOwner<T>(+ owner: BlueskyOAuthGrantOwner,+ operation: (snapshot: CredentialSnapshot | null) => CredentialOperation<T>,+ ): Promise<T> {+ connectionCredentialKey(owner);+ let initialRevision: string | null | undefined;+ for (let attempt = 0; attempt < CONNECTION_WRITE_ATTEMPTS; attempt++) {+ const membership = await loadConnectionMembership(owner.userId);+ if (!membership) continue;+ if (membership.state === 'closed') throw new ConnectionOwnerClosedError();+ const row = await readConnectionCredential(owner);+ const snapshot = row ? this.parseCredential(row) : null;+ const revision = snapshot?.revision ?? null;+ if (initialRevision !== undefined && initialRevision !== revision) throw new ConnectionWriteConflictError();+ initialRevision = revision;+ const {result, write} = operation(snapshot);+ if (write === undefined) return result;+ const writes: Array<CredentialWrite> = [connectionMembershipPatch(membership, membership.entries), write];+ if (await executeConditional(UserConnections.conditionalBatch(writes))) return result;+ }+ throw new ConnectionWriteConflictError();+ }++ private parseCredential(row: UserConnectionStorageRow): CredentialSnapshot | null {+ if (!(row.credential_expires_at instanceof Date) || !Number.isFinite(row.credential_expires_at.getTime())) {+ throw new Error('Connection credentials have an invalid expiry');+ }+ if (row.credential_expires_at.getTime() <= Date.now()) return null;+ const revision = z.uuid().safeParse(row.revision);+ if (!revision.success || typeof row.credential_payload !== 'string') {+ throw new Error('Connection credentials have an invalid stored revision or payload');+ }+ let payload: unknown;+ try {+ payload = JSON.parse(row.credential_payload);+ } catch {+ throw new Error('Connection credentials contain invalid JSON');+ }+ const value = CredentialPayload.safeParse(payload);+ if (!value.success) throw new Error('Connection credentials have an invalid stored phase');+ return {revision: revision.data, expiresAt: row.credential_expires_at, value: value.data};+ }+}diff --git a/fluxer_api/src/api/connection/ConnectionMembership.ts b/fluxer_api/src/api/connection/ConnectionMembership.tsnew file mode 100644index 000000000..3b42b1f2d--- /dev/null+++ b/fluxer_api/src/api/connection/ConnectionMembership.ts@@ -0,0 +1,234 @@+import {randomUUID} from 'node:crypto';+import {+ type ConnectionType,+ ConnectionTypes,+ MAX_CONNECTIONS_PER_USER,+} from '@fluxer/constants/src/ConnectionConstants';+import {z} from 'zod';+import type {UserID} from '../BrandedTypes';+import {executeConditional, fetchMany, fetchOne} from '../database/CassandraQueryExecution';+import {type ConditionalWriteEntry, Db} from '../database/CassandraTypes';+import {USER_CONNECTION_CREDENTIAL_TYPE, type UserConnectionStorageRow} from '../database/types/ConnectionTypes';+import {UserConnections} from '../Tables';++const MEMBERSHIP_TYPE = '_membership';+const MEMBERSHIP_ID = '_membership';+export const CONNECTION_WRITE_ATTEMPTS = 3;++export class ConnectionOwnerClosedError extends Error {+ constructor() {+ super('Connection ownership is closed for this account');+ }+}++export class ConnectionWriteConflictError extends Error {+ constructor() {+ super('Connection ownership changed during the operation');+ }+}++interface ConnectionMembershipEntry {+ connection_type: ConnectionType;+ identifier: string;+ connection_id: string;+}++interface ConnectionMembershipOwner {+ userId: UserID;+ revision: string;+}++interface ActiveConnectionMembership extends ConnectionMembershipOwner {+ state: 'active';+ entries: ReadonlyArray<ConnectionMembershipEntry>;+}++interface ClosedConnectionMembership extends ConnectionMembershipOwner {+ state: 'closed';+}++type ConnectionMembershipSnapshot = ActiveConnectionMembership | ClosedConnectionMembership;++const MembershipRevision = z.uuid();+const MembershipState = z.discriminatedUnion('state', [+ z.strictObject({state: z.literal('closed')}),+ z.strictObject({state: z.literal('active'), entries: z.unknown()}),+]);+const MembershipEntries = z+ .array(+ z.strictObject({+ connection_type: z.enum(ConnectionTypes),+ identifier: z+ .string()+ .min(1)+ .refine((identifier) => identifier === identifier.toLowerCase()),+ connection_id: z.string().min(1),+ }),+ )+ .max(MAX_CONNECTIONS_PER_USER);++const FETCH_MEMBERSHIP_CQL = UserConnections.selectCql({+ where: [+ UserConnections.where.eq('user_id'),+ UserConnections.where.eq('connection_type'),+ UserConnections.where.eq('connection_id'),+ ],+ limit: 1,+});+const FETCH_BOOTSTRAP_CONNECTIONS_CQL = UserConnections.selectCql({+ where: UserConnections.where.eq('user_id'),+ limit: MAX_CONNECTIONS_PER_USER + 2,+});++function validateEntries(value: unknown): Array<ConnectionMembershipEntry> {+ const result = MembershipEntries.safeParse(value);+ if (!result.success) throw new Error('Connection membership catalogue contains invalid entries');+ const identities = new Set<string>();+ const connectionIds = new Set<string>();+ for (const entry of result.data) {+ const identity = JSON.stringify([entry.connection_type, entry.identifier]);+ if (identities.has(identity) || connectionIds.has(entry.connection_id)) {+ throw new Error('Connection membership catalogue contains duplicate connections');+ }+ identities.add(identity);+ connectionIds.add(entry.connection_id);+ }+ return result.data;+}++function parseMembership(row: UserConnectionStorageRow, userId: UserID): ConnectionMembershipSnapshot {+ if (row.user_id !== userId || row.connection_type !== MEMBERSHIP_TYPE || row.connection_id !== MEMBERSHIP_ID) {+ throw new Error('Connection membership catalogue has an invalid owner or key');+ }+ const revision = MembershipRevision.safeParse(row.revision);+ if (!revision.success) throw new Error('Connection membership catalogue has an invalid revision');+ if (typeof row.membership !== 'string') throw new Error('Connection membership catalogue has no entries');+ let value: unknown;+ try {+ value = JSON.parse(row.membership);+ } catch {+ throw new Error('Connection membership catalogue contains invalid JSON');+ }+ const state = MembershipState.safeParse(value);+ if (!state.success) throw new Error('Connection membership catalogue has an invalid state');+ if (state.data.state === 'closed') return {userId, revision: revision.data, state: 'closed'};+ return {userId, revision: revision.data, state: 'active', entries: validateEntries(state.data.entries)};+}++export function isConnectionMembershipRow(row: UserConnectionStorageRow): boolean {+ return row.connection_type === MEMBERSHIP_TYPE && row.connection_id === MEMBERSHIP_ID;+}++export function createPrivateConnectionRow(+ userId: UserID,+ connectionType: string,+ connectionId: string,+): UserConnectionStorageRow {+ return {+ user_id: userId,+ connection_type: connectionType,+ connection_id: connectionId,+ identifier: null,+ name: null,+ verified: null,+ visibility_flags: null,+ sort_order: null,+ verification_token: null,+ oauth_grant_id: null,+ verified_at: null,+ last_verified_at: null,+ created_at: null,+ revision: randomUUID(),+ version: null,+ membership: null,+ credential_payload: null,+ credential_expires_at: null,+ };+}++export async function loadConnectionMembership(userId: UserID): Promise<ConnectionMembershipSnapshot | null> {+ const stored = await fetchOne<UserConnectionStorageRow>(FETCH_MEMBERSHIP_CQL, {+ user_id: userId,+ connection_type: MEMBERSHIP_TYPE,+ connection_id: MEMBERSHIP_ID,+ });+ if (stored) return parseMembership(stored, userId);+ await fetchMany(FETCH_BOOTSTRAP_CONNECTIONS_CQL, {user_id: userId}, {consistency: 'serial'});+ const rows = await fetchMany<UserConnectionStorageRow>(+ FETCH_BOOTSTRAP_CONNECTIONS_CQL,+ {user_id: userId},+ {consistency: 'all'},+ );+ const catalogue = rows.find(isConnectionMembershipRow);+ if (catalogue) return parseMembership(catalogue, userId);+ if (rows.some((row) => row.connection_type === USER_CONNECTION_CREDENTIAL_TYPE)) {+ throw new Error('Connection credentials exist without their membership owner');+ }+ const entries = validateEntries(+ rows.map((row) => {+ if (row.user_id !== userId || typeof row.identifier !== 'string') {+ throw new Error('Connection membership bootstrap encountered an invalid connection');+ }+ return {+ connection_type: row.connection_type,+ identifier: row.identifier.toLowerCase(),+ connection_id: row.connection_id,+ };+ }),+ );+ const row: UserConnectionStorageRow = {+ ...createPrivateConnectionRow(userId, MEMBERSHIP_TYPE, MEMBERSHIP_ID),+ membership: JSON.stringify({state: 'active', entries}),+ };+ const applied = await executeConditional(UserConnections.insertIfNotExists(row));+ return applied ? parseMembership(row, userId) : null;+}++export async function sealConnectionMembership(userId: UserID): Promise<void> {+ for (let attempt = 0; attempt < CONNECTION_WRITE_ATTEMPTS; attempt++) {+ const stored = await fetchOne<UserConnectionStorageRow>(FETCH_MEMBERSHIP_CQL, {+ user_id: userId,+ connection_type: MEMBERSHIP_TYPE,+ connection_id: MEMBERSHIP_ID,+ });+ if (!stored) {+ const applied = await executeConditional(+ UserConnections.insertIfNotExists({+ ...createPrivateConnectionRow(userId, MEMBERSHIP_TYPE, MEMBERSHIP_ID),+ membership: JSON.stringify({state: 'closed'}),+ }),+ );+ if (applied) return;+ continue;+ }+ const membership = parseMembership(stored, userId);+ if (membership.state === 'closed') return;+ const applied = await executeConditional(+ UserConnections.conditionalPatchByPk(+ {user_id: userId, connection_type: MEMBERSHIP_TYPE, connection_id: MEMBERSHIP_ID},+ {revision: Db.set(randomUUID()), membership: Db.set(JSON.stringify({state: 'closed'}))},+ {revision: membership.revision},+ ),+ );+ if (applied) return;+ }+ throw new ConnectionWriteConflictError();+}++export function connectionMembershipPatch(+ snapshot: ActiveConnectionMembership,+ entries: ReadonlyArray<ConnectionMembershipEntry>,+): ConditionalWriteEntry<UserConnectionStorageRow, 'user_id' | 'connection_type' | 'connection_id'> {+ if (!MembershipRevision.safeParse(snapshot.revision).success) {+ throw new Error('Connection membership snapshot has an invalid revision');+ }+ return {+ action: 'patch',+ pk: {user_id: snapshot.userId, connection_type: MEMBERSHIP_TYPE, connection_id: MEMBERSHIP_ID},+ patch: {+ revision: Db.set(randomUUID()),+ membership: Db.set(JSON.stringify({state: 'active', entries: validateEntries(entries)})),+ },+ expected: {revision: snapshot.revision},+ };+}diff --git a/fluxer_api/src/api/connection/ConnectionRepository.ts b/fluxer_api/src/api/connection/ConnectionRepository.tsindex c5a88c3a7..ccf5ecde0 100644--- a/fluxer_api/src/api/connection/ConnectionRepository.ts+++ b/fluxer_api/src/api/connection/ConnectionRepository.ts@@ -1,15 +1,41 @@// SPDX-License-Identifier: AGPL-3.0-or-later-import type {ConnectionType} from '@fluxer/constants/src/ConnectionConstants';+import {randomUUID} from 'node:crypto';+import {+ type ConnectionType,+ ConnectionTypes,+ MAX_CONNECTIONS_PER_USER,+} from '@fluxer/constants/src/ConnectionConstants';import type {UserID} from '../BrandedTypes';-import {BatchBuilder, deleteOneOrMany, fetchMany, fetchOne, upsertOne} from '../database/CassandraQueryExecution';-import {Db, type DbOp} from '../database/CassandraTypes';-import type {UserConnectionRow} from '../database/types/ConnectionTypes';+import {BatchBuilder, executeConditional, fetchMany, fetchOne} from '../database/CassandraQueryExecution';+import {type ConditionalWriteEntry, Db, type DbOp} from '../database/CassandraTypes';+import {+ type RevisionedUserConnectionRow,+ USER_CONNECTION_COLUMNS,+ type UserConnectionRow,+ type UserConnectionStorageRow,+} from '../database/types/ConnectionTypes';import {UserConnections} from '../Tables';-import {type CreateConnectionParams, IConnectionRepository, type UpdateConnectionParams} from './IConnectionRepository';+import {connectionCredentialKey, readConnectionCredential} from './ConnectionCredentialRepository';+import {+ CONNECTION_WRITE_ATTEMPTS,+ ConnectionOwnerClosedError,+ connectionMembershipPatch,+ isConnectionMembershipRow,+ loadConnectionMembership,+ sealConnectionMembership,+} from './ConnectionMembership';+import {+ type ConnectionCreationResult,+ type ConnectionSortOrderUpdate,+ type CreateConnectionParams,+ IConnectionRepository,+ type UpdateConnectionParams,+} from './IConnectionRepository';const FETCH_CONNECTIONS_BY_USER_CQL = UserConnections.selectCql({- where: UserConnections.where.eq('user_id'),+ columns: USER_CONNECTION_COLUMNS,+ where: [UserConnections.where.eq('user_id'), UserConnections.where.in('connection_type', 'connection_types')],});const FETCH_CONNECTION_BY_ID_CQL = UserConnections.selectCql({where: [@@ -20,12 +46,25 @@ const FETCH_CONNECTION_BY_ID_CQL = UserConnections.selectCql({limit: 1,});const COUNT_CONNECTIONS_CQL = UserConnections.selectCountCql({+ where: [UserConnections.where.eq('user_id'), UserConnections.where.in('connection_type', 'connection_types')],+});+const FETCH_DELETION_CONNECTIONS_CQL = UserConnections.selectCql({where: UserConnections.where.eq('user_id'),+ limit: 101,});+type ConnectionWrite = ConditionalWriteEntry<UserConnectionStorageRow, 'user_id' | 'connection_type' | 'connection_id'>;++function hasConnectionRevision(connection: UserConnectionRow): connection is RevisionedUserConnectionRow {+ return typeof connection.revision === 'string';+}+export class ConnectionRepository extends IConnectionRepository {async findByUserId(userId: UserID): Promise<Array<UserConnectionRow>> {- return fetchMany<UserConnectionRow>(FETCH_CONNECTIONS_BY_USER_CQL, {user_id: userId});+ return fetchMany<UserConnectionRow>(FETCH_CONNECTIONS_BY_USER_CQL, {+ user_id: userId,+ connection_types: Object.values(ConnectionTypes),+ });}async findById(@@ -53,9 +92,22 @@ export class ConnectionRepository extends IConnectionRepository {);}- async create(params: CreateConnectionParams): Promise<UserConnectionRow> {+ async create(params: CreateConnectionParams): Promise<ConnectionCreationResult> {+ const membership = await loadConnectionMembership(params.user_id);+ if (!membership) return {status: 'conflict'};+ if (membership.state === 'closed') throw new ConnectionOwnerClosedError();+ const identifier = params.identifier.toLowerCase();+ if (+ membership.entries.some(+ (entry) => entry.connection_type === params.connection_type && entry.identifier === identifier,+ )+ ) {+ return {status: 'duplicate'};+ }+ if (membership.entries.length >= MAX_CONNECTIONS_PER_USER) return {status: 'limit_reached'};+ if (membership.entries.some((entry) => entry.connection_id === params.connection_id)) return {status: 'conflict'};const now = new Date();- const row: UserConnectionRow = {+ const row: RevisionedUserConnectionRow = {user_id: params.user_id,connection_id: params.connection_id,connection_type: params.connection_type,@@ -63,78 +115,192 @@ export class ConnectionRepository extends IConnectionRepository {name: params.name,verified: params.verified ?? false,visibility_flags: params.visibility_flags,- sort_order: params.sort_order,+ sort_order: params.sort_order ?? membership.entries.length,verification_token: params.verification_token,+ oauth_grant_id: params.oauth_grant_id ?? null,verified_at: params.verified_at ?? null,last_verified_at: params.last_verified_at ?? null,created_at: now,+ revision: randomUUID(),version: 1,+ membership: null,+ credential_payload: null,+ credential_expires_at: null,};- await upsertOne(UserConnections.upsertAll(row));- return row;+ const applied = await executeConditional(+ UserConnections.conditionalBatch([+ connectionMembershipPatch(membership, [+ ...membership.entries,+ {+ connection_type: params.connection_type,+ identifier,+ connection_id: params.connection_id,+ },+ ]),+ {action: 'insert', row},+ ]),+ );+ return applied ? {status: 'created', connection: row} : {status: 'conflict'};+ }++ async ensureRevision(snapshot: UserConnectionRow): Promise<RevisionedUserConnectionRow | null> {+ if (hasConnectionRevision(snapshot)) return snapshot;+ const revised = {...snapshot, revision: randomUUID()};+ const applied = await this.writeWithOwner(snapshot.user_id, [+ {+ action: 'patch',+ pk: {+ user_id: snapshot.user_id,+ connection_type: snapshot.connection_type,+ connection_id: snapshot.connection_id,+ },+ patch: {revision: Db.set(revised.revision)},+ expected: {revision: null, created_at: snapshot.created_at},+ },+ ]);+ return applied ? revised : null;}async update(- userId: UserID,- connectionType: ConnectionType,- connectionId: string,+ snapshot: RevisionedUserConnectionRow,params: UpdateConnectionParams,- ): Promise<void> {- const patch: Record<string, DbOp<unknown>> = {};+ ): Promise<RevisionedUserConnectionRow | null> {+ const updated = {...snapshot, revision: randomUUID()};+ const patch: Record<string, DbOp<unknown>> = {revision: Db.set(updated.revision)};if (params.name !== undefined) {patch['name'] = Db.set(params.name);+ updated.name = params.name;}if (params.visibility_flags !== undefined) {patch['visibility_flags'] = Db.set(params.visibility_flags);+ updated.visibility_flags = params.visibility_flags;}if (params.sort_order !== undefined) {patch['sort_order'] = Db.set(params.sort_order);+ updated.sort_order = params.sort_order;+ }+ if (params.oauth_grant_id !== undefined) {+ patch['oauth_grant_id'] = Db.set(params.oauth_grant_id);+ updated.oauth_grant_id = params.oauth_grant_id;}if (params.verified !== undefined) {patch['verified'] = Db.set(params.verified);+ updated.verified = params.verified;}if (params.verified_at !== undefined) {patch['verified_at'] = Db.set(params.verified_at);+ updated.verified_at = params.verified_at;}if (params.last_verified_at !== undefined) {patch['last_verified_at'] = Db.set(params.last_verified_at);+ updated.last_verified_at = params.last_verified_at;}- if (Object.keys(patch).length > 0) {- await upsertOne(- UserConnections.patchByPk(- {user_id: userId, connection_type: connectionType, connection_id: connectionId},- patch,+ const applied = await this.writeWithOwner(snapshot.user_id, [+ {+ action: 'patch',+ pk: {+ user_id: snapshot.user_id,+ connection_type: snapshot.connection_type,+ connection_id: snapshot.connection_id,+ },+ patch,+ expected: {revision: snapshot.revision},+ },+ ]);+ return applied ? updated : null;+ }++ async updateSortOrders(entries: ReadonlyArray<ConnectionSortOrderUpdate>): Promise<boolean> {+ if (entries.length === 0) return true;+ return this.writeWithOwner(+ entries[0].snapshot.user_id,+ entries.map(({snapshot, sortOrder}) => ({+ action: 'patch',+ pk: {+ user_id: snapshot.user_id,+ connection_type: snapshot.connection_type,+ connection_id: snapshot.connection_id,+ },+ patch: {sort_order: Db.set(sortOrder), revision: Db.set(randomUUID())},+ expected: {revision: snapshot.revision},+ })),+ );+ }++ async delete(snapshot: RevisionedUserConnectionRow): Promise<boolean> {+ const membership = await loadConnectionMembership(snapshot.user_id);+ if (!membership) return false;+ if (membership.state === 'closed') throw new ConnectionOwnerClosedError();+ const entries = membership.entries.filter(+ (entry) =>+ !(+ entry.connection_type === snapshot.connection_type &&+ entry.identifier === snapshot.identifier.toLowerCase() &&+ entry.connection_id === snapshot.connection_id),- );+ );+ if (entries.length === membership.entries.length) return false;+ const writes: Array<ConnectionWrite> = [+ connectionMembershipPatch(membership, entries),+ {+ action: 'delete',+ pk: {+ user_id: snapshot.user_id,+ connection_type: snapshot.connection_type,+ connection_id: snapshot.connection_id,+ },+ expected: {revision: snapshot.revision},+ },+ ];+ if (snapshot.oauth_grant_id) {+ const owner = {userId: snapshot.user_id, grantId: snapshot.oauth_grant_id};+ const key = connectionCredentialKey(owner);+ const grant = await readConnectionCredential(owner);+ if (grant) {+ if (typeof grant.revision !== 'string') throw new Error('Connection credentials have no stored revision');+ writes.push({action: 'delete', pk: key, expected: {revision: grant.revision}});+ }}+ return executeConditional(UserConnections.conditionalBatch(writes));}- async updateSortOrders(- userId: UserID,- entries: Array<{connectionType: ConnectionType; connectionId: string; sortOrder: number}>,- ): Promise<void> {- const batch = new BatchBuilder();- for (const entry of entries) {- batch.addPrepared(- UserConnections.patchByPk(- {user_id: userId, connection_type: entry.connectionType, connection_id: entry.connectionId},- {sort_order: Db.set(entry.sortOrder)},- ),- );+ async sealAndDeleteForUser(userId: UserID): Promise<void> {+ await sealConnectionMembership(userId);+ for (;;) {+ const rows = await fetchMany<UserConnectionStorageRow>(FETCH_DELETION_CONNECTIONS_CQL, {user_id: userId});+ const remaining = rows.filter((row) => !isConnectionMembershipRow(row));+ if (remaining.length === 0) return;+ const batch = new BatchBuilder();+ for (const row of remaining) {+ batch.addPrepared(+ UserConnections.deleteByPk({+ user_id: userId,+ connection_type: row.connection_type,+ connection_id: row.connection_id,+ }),+ );+ }+ await batch.execute();}- await batch.execute();}- async delete(userId: UserID, connectionType: ConnectionType, connectionId: string): Promise<void> {- await deleteOneOrMany(- UserConnections.deleteByPk({user_id: userId, connection_type: connectionType, connection_id: connectionId}),- );+ private async writeWithOwner(userId: UserID, writes: ReadonlyArray<ConnectionWrite>): Promise<boolean> {+ for (let attempt = 0; attempt < CONNECTION_WRITE_ATTEMPTS; attempt++) {+ const membership = await loadConnectionMembership(userId);+ if (!membership) continue;+ if (membership.state === 'closed') throw new ConnectionOwnerClosedError();+ const applied = await executeConditional(+ UserConnections.conditionalBatch([connectionMembershipPatch(membership, membership.entries), ...writes]),+ );+ if (applied) return true;+ }+ return false;}async count(userId: UserID): Promise<number> {const result = await fetchOne<{count: bigint;- }>(COUNT_CONNECTIONS_CQL, {user_id: userId});+ }>(COUNT_CONNECTIONS_CQL, {user_id: userId, connection_types: Object.values(ConnectionTypes)});return result ? Number(result.count) : 0;}}diff --git a/fluxer_api/src/api/connection/ConnectionRequestService.ts b/fluxer_api/src/api/connection/ConnectionRequestService.tsindex 629a0288b..a92530244 100644--- a/fluxer_api/src/api/connection/ConnectionRequestService.ts+++ b/fluxer_api/src/api/connection/ConnectionRequestService.ts@@ -82,15 +82,6 @@ export class ConnectionRequestService {await this.connectionService.deleteConnection(userId, connectionType, connectionId);}- async verifyConnection(- userId: UserID,- connectionType: ConnectionType,- connectionId: string,- ): Promise<ConnectionResponse> {- const row = await this.connectionService.verifyConnection(userId, connectionType, connectionId);- return mapConnectionToResponse(row);- }-async reorderConnections(userId: UserID, connectionIds: Array<string>): Promise<void> {await this.connectionService.reorderConnections(userId, connectionIds);}diff --git a/fluxer_api/src/api/connection/ConnectionService.ts b/fluxer_api/src/api/connection/ConnectionService.tsindex 54c212fde..870f66c9a 100644--- a/fluxer_api/src/api/connection/ConnectionService.ts+++ b/fluxer_api/src/api/connection/ConnectionService.ts@@ -1,15 +1,17 @@// SPDX-License-Identifier: AGPL-3.0-or-laterimport {randomUUID} from 'node:crypto';+import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';import {type ConnectionType,ConnectionTypes,ConnectionVisibilityFlags,MAX_CONNECTIONS_PER_USER,} from '@fluxer/constants/src/ConnectionConstants';+import {ConflictError} from '@fluxer/errors/src/domains/core/ConflictError';import type {UserID} from '../BrandedTypes';-import type {IBlueskyOAuthService} from '../bluesky/IBlueskyOAuthService';-import type {UserConnectionRow} from '../database/types/ConnectionTypes';+import type {BlueskyCallbackResult} from '../bluesky/IBlueskyOAuthService';+import type {RevisionedUserConnectionRow, UserConnectionRow} from '../database/types/ConnectionTypes';import type {IGatewayService} from '../infrastructure/IGatewayService';import {mapConnectionToResponse} from './ConnectionMappers';import {createDomainConnectionId} from './DomainConnectionId';@@ -19,17 +21,19 @@ import {ConnectionInvalidTypeError} from './errors/ConnectionInvalidTypeError';import {ConnectionLimitReachedError} from './errors/ConnectionLimitReachedError';import {ConnectionNotFoundError} from './errors/ConnectionNotFoundError';import {ConnectionVerificationFailedError} from './errors/ConnectionVerificationFailedError';-import type {IConnectionRepository, UpdateConnectionParams} from './IConnectionRepository';+import type {+ ConnectionSortOrderUpdate,+ CreateConnectionParams,+ IConnectionRepository,+ UpdateConnectionParams,+} from './IConnectionRepository';import {IConnectionService, type InitiateConnectionResult} from './IConnectionService';-import {BlueskyOAuthVerifier} from './verification/BlueskyOAuthVerifier';import {DomainConnectionVerifier} from './verification/DomainConnectionVerifier';-import type {IConnectionVerifier} from './verification/IConnectionVerifier';export class ConnectionService extends IConnectionService {constructor(private readonly repository: IConnectionRepository,private readonly gateway: IGatewayService,- private readonly blueskyOAuthService: IBlueskyOAuthService,) {super();}@@ -56,12 +60,11 @@ export class ConnectionService extends IConnectionService {}}- private async requireAvailableConnectionSlot(userId: UserID): Promise<number> {+ private async requireAvailableConnectionSlot(userId: UserID): Promise<void> {const count = await this.repository.count(userId);if (count >= MAX_CONNECTIONS_PER_USER) {throw new ConnectionLimitReachedError();}- return count;}private async assertConnectionDoesNotExist(userId: UserID, type: ConnectionType, identifier: string): Promise<void> {@@ -75,11 +78,25 @@ export class ConnectionService extends IConnectionService {userId: UserID,type: ConnectionType,identifier: string,- ): Promise<number> {+ ): Promise<void> {this.assertConnectionTypeCanBeCreated(type);- const count = await this.requireAvailableConnectionSlot(userId);+ await this.requireAvailableConnectionSlot(userId);await this.assertConnectionDoesNotExist(userId, type, identifier);- return count;+ }++ private async createConnection(params: CreateConnectionParams): Promise<RevisionedUserConnectionRow> {+ const result = await this.repository.create(params);+ switch (result.status) {+ case 'duplicate':+ throw new ConnectionAlreadyExistsError();+ case 'limit_reached':+ throw new ConnectionLimitReachedError();+ case 'conflict':+ throw new ConflictError({code: APIErrorCodes.CONFLICT});+ case 'created':+ await this.dispatchConnectionsUpdate(params.user_id);+ return result.connection;+ }}private async dispatchConnectionsUpdate(userId: UserID): Promise<void> {@@ -91,6 +108,26 @@ export class ConnectionService extends IConnectionService {});}+ private async requireConnection(+ userId: UserID,+ connectionType: ConnectionType,+ connectionId: string,+ ): Promise<UserConnectionRow> {+ const connection = await this.repository.findById(userId, connectionType, connectionId);+ if (!connection) throw new ConnectionNotFoundError();+ return connection;+ }++ private async rejectSupersededConnection(snapshot: UserConnectionRow): Promise<never> {+ await this.requireConnection(snapshot.user_id, snapshot.connection_type, snapshot.connection_id);+ throw new ConflictError({code: APIErrorCodes.CONFLICT});+ }++ private async requireRevision(snapshot: UserConnectionRow): Promise<RevisionedUserConnectionRow> {+ const connection = await this.repository.ensureRevision(snapshot);+ return connection ?? this.rejectSupersededConnection(snapshot);+ }+async verifyAndCreateConnection(userId: UserID,type: ConnectionType,@@ -98,30 +135,25 @@ export class ConnectionService extends IConnectionService {verificationCode: string,visibilityFlags: number,): Promise<UserConnectionRow> {- const count = await this.requireConnectionCreationAllowed(userId, type, identifier);- const verifier = this.getVerifier(type);- const isValid = await verifier.verify({identifier, verification_token: verificationCode});+ await this.requireConnectionCreationAllowed(userId, type, identifier);+ const isValid = await new DomainConnectionVerifier().verify({identifier, verification_token: verificationCode});if (!isValid) {throw new ConnectionVerificationFailedError();}const connectionId = createDomainConnectionId(userId, identifier);- const sortOrder = count;const now = new Date();- const created = await this.repository.create({+ return this.createConnection({user_id: userId,connection_id: connectionId,connection_type: type,identifier,name: identifier,visibility_flags: visibilityFlags,- sort_order: sortOrder,verification_token: verificationCode,verified: true,verified_at: now,last_verified_at: now,});- await this.dispatchConnectionsUpdate(userId);- return created;}async updateConnection(@@ -130,135 +162,68 @@ export class ConnectionService extends IConnectionService {connectionId: string,patch: UpdateConnectionParams,): Promise<void> {- const connection = await this.repository.findById(userId, connectionType, connectionId);- if (!connection) {- throw new ConnectionNotFoundError();- }- await this.repository.update(userId, connectionType, connectionId, patch);+ const snapshot = await this.requireConnection(userId, connectionType, connectionId);+ const connection = await this.requireRevision(snapshot);+ const updated = await this.repository.update(connection, patch);+ if (!updated) return this.rejectSupersededConnection(connection);await this.dispatchConnectionsUpdate(userId);}async deleteConnection(userId: UserID, connectionType: ConnectionType, connectionId: string): Promise<void> {- const connection = await this.repository.findById(userId, connectionType, connectionId);- if (!connection) {- throw new ConnectionNotFoundError();- }- await this.repository.delete(userId, connectionType, connectionId);- await this.dispatchConnectionsUpdate(userId);- }-- async verifyConnection(- userId: UserID,- connectionType: ConnectionType,- connectionId: string,- ): Promise<UserConnectionRow> {- const connection = await this.repository.findById(userId, connectionType, connectionId);- if (!connection) {- throw new ConnectionNotFoundError();- }- const {isValid, updateParams} = await this.revalidateConnection(connection);- if (updateParams) {- await this.repository.update(userId, connectionType, connectionId, updateParams);- }- const updated = await this.repository.findById(userId, connectionType, connectionId);- if (!updated) {- throw new ConnectionNotFoundError();- }+ const snapshot = await this.requireConnection(userId, connectionType, connectionId);+ const connection = await this.requireRevision(snapshot);+ if (!(await this.repository.delete(connection))) return this.rejectSupersededConnection(connection);await this.dispatchConnectionsUpdate(userId);- if (!isValid) {- throw new ConnectionVerificationFailedError();- }- return updated;}async reorderConnections(userId: UserID, connectionIds: Array<string>): Promise<void> {const connections = await this.repository.findByUserId(userId);const byId = new Map(connections.map((connection) => [connection.connection_id, connection]));- const entries = new Map<string, {connectionType: ConnectionType; connectionId: string; sortOrder: number}>();+ const positions = new Map<UserConnectionRow, number>();connectionIds.forEach((connectionId, sortOrder) => {const connection = byId.get(connectionId);- if (connection) {- entries.set(connectionId, {connectionType: connection.connection_type, connectionId, sortOrder});- }+ if (connection) positions.set(connection, sortOrder);});- await this.repository.updateSortOrders(userId, Array.from(entries.values()));+ const entries: Array<ConnectionSortOrderUpdate> = [];+ for (const [connection, sortOrder] of positions) {+ entries.push({snapshot: await this.requireRevision(connection), sortOrder});+ }+ if (!(await this.repository.updateSortOrders(entries))) throw new ConflictError({code: APIErrorCodes.CONFLICT});await this.dispatchConnectionsUpdate(userId);}- async createOrUpdateBlueskyConnection(userId: UserID, did: string, handle: string): Promise<UserConnectionRow> {+ async createOrUpdateBlueskyConnection(result: BlueskyCallbackResult): Promise<UserConnectionRow> {+ const {userId, did, handle, grantId} = result;const existing = await this.repository.findByTypeAndIdentifier(userId, ConnectionTypes.BLUESKY, did);if (existing) {+ const snapshot = await this.requireRevision(existing);const now = new Date();- await this.repository.update(userId, ConnectionTypes.BLUESKY, existing.connection_id, {+ const updated = await this.repository.update(snapshot, {name: handle,+ oauth_grant_id: grantId,verified: true,- verified_at: existing.verified_at ?? now,+ verified_at: snapshot.verified_at ?? now,last_verified_at: now,});- const updated = await this.repository.findById(userId, ConnectionTypes.BLUESKY, existing.connection_id);+ if (!updated) return this.rejectSupersededConnection(snapshot);await this.dispatchConnectionsUpdate(userId);- return updated!;+ return updated;}- const count = await this.requireAvailableConnectionSlot(userId);+ await this.requireAvailableConnectionSlot(userId);const connectionId = randomUUID();const now = new Date();- const created = await this.repository.create({+ return this.createConnection({user_id: userId,connection_id: connectionId,connection_type: ConnectionTypes.BLUESKY,identifier: did,name: handle,visibility_flags: ConnectionVisibilityFlags.EVERYONE,- sort_order: count,verification_token: '',+ oauth_grant_id: grantId,verified: true,verified_at: now,last_verified_at: now,});- await this.dispatchConnectionsUpdate(userId);- return created;- }-- async revalidateConnection(connection: UserConnectionRow): Promise<{- isValid: boolean;- updateParams: UpdateConnectionParams | null;- }> {- const verifier = this.getVerifier(connection.connection_type);- const isValid = await verifier.verify({- identifier: connection.identifier,- verification_token: connection.verification_token,- });- const now = new Date();- if (!isValid && connection.verified) {- return {- isValid: false,- updateParams: {- verified: false,- verified_at: null,- last_verified_at: now,- },- };- }- if (isValid) {- return {- isValid: true,- updateParams: {- verified: true,- verified_at: connection.verified_at ? connection.verified_at : now,- last_verified_at: now,- },- };- }- return {isValid: false, updateParams: null};- }-- private getVerifier(type: ConnectionType): IConnectionVerifier {- if (type === ConnectionTypes.BLUESKY) {- return new BlueskyOAuthVerifier(this.blueskyOAuthService);- }- if (type === ConnectionTypes.DOMAIN) {- return new DomainConnectionVerifier();- }- throw new ConnectionInvalidTypeError();}}diff --git a/fluxer_api/src/api/connection/IConnectionRepository.ts b/fluxer_api/src/api/connection/IConnectionRepository.tsindex 1b3573ef1..2d871662e 100644--- a/fluxer_api/src/api/connection/IConnectionRepository.ts+++ b/fluxer_api/src/api/connection/IConnectionRepository.ts@@ -2,7 +2,7 @@import type {ConnectionType} from '@fluxer/constants/src/ConnectionConstants';import type {UserID} from '../BrandedTypes';-import type {UserConnectionRow} from '../database/types/ConnectionTypes';+import type {RevisionedUserConnectionRow, UserConnectionRow} from '../database/types/ConnectionTypes';export interface CreateConnectionParams {user_id: UserID;@@ -11,8 +11,9 @@ export interface CreateConnectionParams {identifier: string;name: string;visibility_flags: number;- sort_order: number;+ sort_order?: number;verification_token: string;+ oauth_grant_id?: string | null;verified?: boolean;verified_at?: Date | null;last_verified_at?: Date | null;@@ -22,11 +23,21 @@ export interface UpdateConnectionParams {name?: string;visibility_flags?: number;sort_order?: number;+ oauth_grant_id?: string | null;verified?: boolean;verified_at?: Date | null;last_verified_at?: Date | null;}+export interface ConnectionSortOrderUpdate {+ snapshot: RevisionedUserConnectionRow;+ sortOrder: number;+}++export type ConnectionCreationResult =+ | {status: 'created'; connection: RevisionedUserConnectionRow}+ | {status: 'duplicate' | 'limit_reached' | 'conflict'};+export abstract class IConnectionRepository {abstract findByUserId(userId: UserID): Promise<Array<UserConnectionRow>>;@@ -42,21 +53,20 @@ export abstract class IConnectionRepository {identifier: string,): Promise<UserConnectionRow | null>;- abstract create(params: CreateConnectionParams): Promise<UserConnectionRow>;+ abstract create(params: CreateConnectionParams): Promise<ConnectionCreationResult>;++ abstract ensureRevision(snapshot: UserConnectionRow): Promise<RevisionedUserConnectionRow | null>;abstract update(- userId: UserID,- connectionType: ConnectionType,- connectionId: string,+ snapshot: RevisionedUserConnectionRow,params: UpdateConnectionParams,- ): Promise<void>;+ ): Promise<RevisionedUserConnectionRow | null>;- abstract updateSortOrders(- userId: UserID,- entries: Array<{connectionType: ConnectionType; connectionId: string; sortOrder: number}>,- ): Promise<void>;+ abstract updateSortOrders(entries: ReadonlyArray<ConnectionSortOrderUpdate>): Promise<boolean>;++ abstract delete(snapshot: RevisionedUserConnectionRow): Promise<boolean>;- abstract delete(userId: UserID, connectionType: ConnectionType, connectionId: string): Promise<void>;+ abstract sealAndDeleteForUser(userId: UserID): Promise<void>;abstract count(userId: UserID): Promise<number>;}diff --git a/fluxer_api/src/api/connection/IConnectionService.ts b/fluxer_api/src/api/connection/IConnectionService.tsindex d896fe901..fd2b43d0b 100644--- a/fluxer_api/src/api/connection/IConnectionService.ts+++ b/fluxer_api/src/api/connection/IConnectionService.ts@@ -2,6 +2,7 @@import type {ConnectionType} from '@fluxer/constants/src/ConnectionConstants';import type {UserID} from '../BrandedTypes';+import type {BlueskyCallbackResult} from '../bluesky/IBlueskyOAuthService';import type {UserConnectionRow} from '../database/types/ConnectionTypes';import type {UpdateConnectionParams} from './IConnectionRepository';@@ -33,18 +34,7 @@ export abstract class IConnectionService {abstract deleteConnection(userId: UserID, connectionType: ConnectionType, connectionId: string): Promise<void>;- abstract verifyConnection(- userId: UserID,- connectionType: ConnectionType,- connectionId: string,- ): Promise<UserConnectionRow>;-abstract reorderConnections(userId: UserID, connectionIds: Array<string>): Promise<void>;- abstract revalidateConnection(connection: UserConnectionRow): Promise<{- isValid: boolean;- updateParams: UpdateConnectionParams | null;- }>;-- abstract createOrUpdateBlueskyConnection(userId: UserID, did: string, handle: string): Promise<UserConnectionRow>;+ abstract createOrUpdateBlueskyConnection(result: BlueskyCallbackResult): Promise<UserConnectionRow>;}diff --git a/fluxer_api/src/api/connection/errors/BlueskyOAuthCallbackFailedError.ts b/fluxer_api/src/api/connection/errors/BlueskyOAuthCallbackFailedError.tsdeleted file mode 100644index 70c82e8f7..000000000--- a/fluxer_api/src/api/connection/errors/BlueskyOAuthCallbackFailedError.ts+++ /dev/null@@ -1,10 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';-import {BadRequestError} from '@fluxer/errors/src/domains/core/BadRequestError';--export class BlueskyOAuthCallbackFailedError extends BadRequestError {- constructor() {- super({code: APIErrorCodes.BLUESKY_OAUTH_CALLBACK_FAILED});- }-}diff --git a/fluxer_api/src/api/connection/errors/BlueskyOAuthStateInvalidError.ts b/fluxer_api/src/api/connection/errors/BlueskyOAuthStateInvalidError.tsdeleted file mode 100644index 2d72b28b2..000000000--- a/fluxer_api/src/api/connection/errors/BlueskyOAuthStateInvalidError.ts+++ /dev/null@@ -1,10 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';-import {BadRequestError} from '@fluxer/errors/src/domains/core/BadRequestError';--export class BlueskyOAuthStateInvalidError extends BadRequestError {- constructor() {- super({code: APIErrorCodes.BLUESKY_OAUTH_STATE_INVALID});- }-}diff --git a/fluxer_api/src/api/connection/tests/ConnectionLimit.test.ts b/fluxer_api/src/api/connection/tests/ConnectionLimit.test.tsindex 5ae667b64..3d5b4d3b6 100644--- a/fluxer_api/src/api/connection/tests/ConnectionLimit.test.ts+++ b/fluxer_api/src/api/connection/tests/ConnectionLimit.test.ts@@ -8,7 +8,6 @@ import {} from '@fluxer/constants/src/ConnectionConstants';import {afterEach, beforeEach, describe, expect, it} from 'vitest';import {createUserID, type UserID} from '../../BrandedTypes';-import type {IBlueskyOAuthService} from '../../bluesky/IBlueskyOAuthService';import {setCassandraQueryExecutorForTesting} from '../../database/CassandraQueryExecution';import type {UserConnectionRow} from '../../database/types/ConnectionTypes';import type {IGatewayService} from '../../infrastructure/IGatewayService';@@ -54,11 +53,7 @@ describe('ConnectionService connection limit', () => {for (let index = 0; index < MAX_CONNECTIONS_PER_USER; index++) {await repository.create(connectionRow(userId, `connection-${index}`, index));}- const service = new ConnectionService(- repository,- {} as unknown as IGatewayService,- {} as unknown as IBlueskyOAuthService,- );+ const service = new ConnectionService(repository, {} as unknown as IGatewayService);const error = await service.initiateConnection(userId, ConnectionTypes.DOMAIN, 'over-the-limit.example').then(() => null,@@ -78,11 +73,7 @@ describe('ConnectionService connection limit', () => {for (let index = 0; index < MAX_CONNECTIONS_PER_USER - 1; index++) {await repository.create(connectionRow(userId, `connection-${index}`, index));}- const service = new ConnectionService(- repository,- {} as unknown as IGatewayService,- {} as unknown as IBlueskyOAuthService,- );+ const service = new ConnectionService(repository, {} as unknown as IGatewayService);await expect(service.initiateConnection(userId, ConnectionTypes.DOMAIN, 'under-the-limit.example'),diff --git a/fluxer_api/src/api/connection/tests/ConnectionRecheckDispatch.test.ts b/fluxer_api/src/api/connection/tests/ConnectionRecheckDispatch.test.tsdeleted file mode 100644index 6b4378167..000000000--- a/fluxer_api/src/api/connection/tests/ConnectionRecheckDispatch.test.ts+++ /dev/null@@ -1,108 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';-import {ConnectionTypes, ConnectionVisibilityFlags} from '@fluxer/constants/src/ConnectionConstants';-import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';-import {createUserID, type UserID} from '../../BrandedTypes';-import type {IBlueskyOAuthService} from '../../bluesky/IBlueskyOAuthService';-import {setCassandraQueryExecutorForTesting} from '../../database/CassandraQueryExecution';-import type {UserConnectionRow} from '../../database/types/ConnectionTypes';-import type {IGatewayService} from '../../infrastructure/IGatewayService';-import {InMemoryCassandraQueryExecutor} from '../../test/InMemoryCassandraQueryExecutor';-import {ConnectionRepository} from '../ConnectionRepository';-import {ConnectionService} from '../ConnectionService';-import {ConnectionVerificationFailedError} from '../errors/ConnectionVerificationFailedError';--function connectionRow(userId: UserID, connectionId: string, verified: boolean): UserConnectionRow {- return {- user_id: userId,- connection_id: connectionId,- connection_type: ConnectionTypes.BLUESKY,- identifier: `did:plc:${connectionId}`,- name: `${connectionId}.bsky.social`,- verified,- visibility_flags: ConnectionVisibilityFlags.EVERYONE,- sort_order: 0,- verification_token: '',- verified_at: verified ? new Date(0) : null,- last_verified_at: verified ? new Date(0) : null,- created_at: new Date(0),- version: 1,- };-}--function failingBlueskyOAuthService(): IBlueskyOAuthService {- return {- restoreAndVerify: vi.fn().mockResolvedValue(null),- } as unknown as IBlueskyOAuthService;-}--describe('ConnectionService.verifyConnection failed recheck', () => {- let executor: InMemoryCassandraQueryExecutor;-- beforeEach(() => {- executor = new InMemoryCassandraQueryExecutor();- setCassandraQueryExecutorForTesting(executor);- });-- afterEach(() => {- executor.reset();- setCassandraQueryExecutorForTesting(null);- });-- it('publishes the connections update before rejecting a recheck that unverified the connection', async () => {- const userId = createUserID(1n);- const repository = new ConnectionRepository();- await repository.create(connectionRow(userId, 'alice', true));- const dispatchPresence = vi.fn().mockResolvedValue(undefined);- const service = new ConnectionService(- repository,- {dispatchPresence} as unknown as IGatewayService,- failingBlueskyOAuthService(),- );-- const error = await service.verifyConnection(userId, ConnectionTypes.BLUESKY, 'alice').then(- () => null,- (caught: unknown) => caught,- );-- expect(error).toBeInstanceOf(ConnectionVerificationFailedError);- const response = (error as ConnectionVerificationFailedError).getResponse();- expect(response.status).toBe(403);- expect(await response.json()).toMatchObject({code: APIErrorCodes.CONNECTION_VERIFICATION_FAILED});-- expect(dispatchPresence).toHaveBeenCalledTimes(1);- expect(dispatchPresence).toHaveBeenCalledWith({- userId,- event: 'USER_CONNECTIONS_UPDATE',- data: {connections: [expect.objectContaining({id: 'alice', verified: false})]},- });-- const stored = await repository.findById(userId, ConnectionTypes.BLUESKY, 'alice');- expect(stored?.verified).toBe(false);- expect(stored?.verified_at).toBeNull();- });-- it('publishes the connections update when the recheck fails against an already unverified connection', async () => {- const userId = createUserID(2n);- const repository = new ConnectionRepository();- await repository.create(connectionRow(userId, 'bob', false));- const dispatchPresence = vi.fn().mockResolvedValue(undefined);- const service = new ConnectionService(- repository,- {dispatchPresence} as unknown as IGatewayService,- failingBlueskyOAuthService(),- );-- await expect(service.verifyConnection(userId, ConnectionTypes.BLUESKY, 'bob')).rejects.toBeInstanceOf(- ConnectionVerificationFailedError,- );-- expect(dispatchPresence).toHaveBeenCalledTimes(1);- expect(dispatchPresence).toHaveBeenCalledWith({- userId,- event: 'USER_CONNECTIONS_UPDATE',- data: {connections: [expect.objectContaining({id: 'bob', verified: false})]},- });- });-});diff --git a/fluxer_api/src/api/connection/tests/ConnectionReorder.test.ts b/fluxer_api/src/api/connection/tests/ConnectionReorder.test.tsindex 0bfb43327..9f95a82e4 100644--- a/fluxer_api/src/api/connection/tests/ConnectionReorder.test.ts+++ b/fluxer_api/src/api/connection/tests/ConnectionReorder.test.ts@@ -3,7 +3,6 @@import {ConnectionTypes, ConnectionVisibilityFlags} from '@fluxer/constants/src/ConnectionConstants';import {afterEach, beforeEach, describe, expect, it, vi} from 'vitest';import {createUserID, type UserID} from '../../BrandedTypes';-import type {IBlueskyOAuthService} from '../../bluesky/IBlueskyOAuthService';import {type CassandraQueryExecutorForTesting,setCassandraQueryExecutorForTesting,@@ -14,15 +13,18 @@ import type {IGatewayService} from '../../infrastructure/IGatewayService';import {InMemoryCassandraQueryExecutor} from '../../test/InMemoryCassandraQueryExecutor';import {ConnectionRepository} from '../ConnectionRepository';import {ConnectionService} from '../ConnectionService';-import type {IConnectionRepository} from '../IConnectionRepository';-class BatchFaultInjectingExecutor implements CassandraQueryExecutorForTesting {+class ConditionalBatchFaultExecutor implements CassandraQueryExecutorForTesting {failNextBatch = false;private readonly inner = new InMemoryCassandraQueryExecutor();async executeQuery<T = Record<string, unknown>, P extends CassandraParams = CassandraParams>(query: PreparedQuery<P>,): Promise<Array<T>> {+ if (this.failNextBatch && query.kvMeta?.action === 'batch' && query.kvMeta.batchEntries) {+ this.failNextBatch = false;+ throw new Error('batch rejected');+ }return this.inner.executeQuery<T>(query);}@@ -30,10 +32,6 @@ class BatchFaultInjectingExecutor implements CassandraQueryExecutorForTesting {queries: Array<{query: string; params: object; meta?: KvQueryMeta}>,atomic?: boolean,): Promise<void> {- if (this.failNextBatch) {- this.failNextBatch = false;- throw new Error('batch rejected');- }await this.inner.executeBatch(queries, atomic);}@@ -61,47 +59,21 @@ function connectionRow(userId: UserID, connectionId: string, sortOrder: number):}describe('ConnectionService.reorderConnections', () => {- it('writes every sort order through a single batched repository call', async () => {- const userId = createUserID(1n);- const updateSortOrders = vi.fn().mockResolvedValue(undefined);- const update = vi.fn().mockResolvedValue(undefined);- const repository = {- findByUserId: vi- .fn()- .mockResolvedValue([- connectionRow(userId, 'a', 0),- connectionRow(userId, 'b', 1),- connectionRow(userId, 'c', 2),- ]),- update,- updateSortOrders,- } as unknown as IConnectionRepository;- const dispatchPresence = vi.fn().mockResolvedValue(undefined);- const service = new ConnectionService(- repository,- {dispatchPresence} as unknown as IGatewayService,- {} as unknown as IBlueskyOAuthService,- );-- await service.reorderConnections(userId, ['c', 'missing', 'a', 'b']);-- expect(update).not.toHaveBeenCalled();- expect(updateSortOrders).toHaveBeenCalledTimes(1);- expect(updateSortOrders).toHaveBeenCalledWith(userId, [- {connectionType: ConnectionTypes.DOMAIN, connectionId: 'c', sortOrder: 0},- {connectionType: ConnectionTypes.DOMAIN, connectionId: 'a', sortOrder: 2},- {connectionType: ConnectionTypes.DOMAIN, connectionId: 'b', sortOrder: 3},- ]);- expect(dispatchPresence).toHaveBeenCalledTimes(1);- });-});--describe('ConnectionService.reorderConnections batch failure', () => {- let executor: BatchFaultInjectingExecutor;-- beforeEach(() => {- executor = new BatchFaultInjectingExecutor();+ const userId = createUserID(1n);+ const dispatchPresence = vi.fn().mockResolvedValue(undefined);+ let executor: ConditionalBatchFaultExecutor;+ let repository: ConnectionRepository;+ let service: ConnectionService;++ beforeEach(async () => {+ executor = new ConditionalBatchFaultExecutor();setCassandraQueryExecutorForTesting(executor);+ repository = new ConnectionRepository();+ for (const [index, connectionId] of ['a', 'b', 'c'].entries()) {+ await repository.create(connectionRow(userId, connectionId, index));+ }+ dispatchPresence.mockClear();+ service = new ConnectionService(repository, {dispatchPresence} as unknown as IGatewayService);});afterEach(() => {@@ -109,19 +81,23 @@ describe('ConnectionService.reorderConnections batch failure', () => {setCassandraQueryExecutorForTesting(null);});- it('leaves every sort order untouched and publishes no dispatch when the batch fails', async () => {- const userId = createUserID(1n);- const repository = new ConnectionRepository();- for (const [index, connectionId] of ['a', 'b', 'c'].entries()) {- await repository.create(connectionRow(userId, connectionId, index));- }- const dispatchPresence = vi.fn().mockResolvedValue(undefined);- const service = new ConnectionService(- repository,- {dispatchPresence} as unknown as IGatewayService,- {} as unknown as IBlueskyOAuthService,+ it('writes every sort order through a single batched repository call', async () => {+ const updateSortOrders = vi.spyOn(repository, 'updateSortOrders');+ await service.reorderConnections(userId, ['c', 'missing', 'a', 'b']);++ expect(updateSortOrders).toHaveBeenCalledTimes(1);+ const connections = await repository.findByUserId(userId);+ expect(new Map(connections.map((row) => [row.connection_id, row.sort_order]))).toEqual(+ new Map([+ ['c', 0],+ ['a', 2],+ ['b', 3],+ ]),);+ expect(dispatchPresence).toHaveBeenCalledTimes(1);+ });+ it('leaves every sort order untouched and publishes no dispatch when the batch fails', async () => {executor.failNextBatch = true;await expect(service.reorderConnections(userId, ['c', 'b', 'a'])).rejects.toThrow('batch rejected');diff --git a/fluxer_api/src/api/connection/verification/BlueskyOAuthVerifier.ts b/fluxer_api/src/api/connection/verification/BlueskyOAuthVerifier.tsdeleted file mode 100644index 0f92b3980..000000000--- a/fluxer_api/src/api/connection/verification/BlueskyOAuthVerifier.ts+++ /dev/null@@ -1,29 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import type {IBlueskyOAuthService} from '../../bluesky/IBlueskyOAuthService';-import {Logger} from '../../Logger';-import {BlueskyOAuthNotEnabledError} from '../errors/BlueskyOAuthNotEnabledError';-import type {ConnectionVerificationParams, IConnectionVerifier} from './IConnectionVerifier';--export class BlueskyOAuthVerifier implements IConnectionVerifier {- constructor(private readonly oauthService: IBlueskyOAuthService) {}-- async verify(params: ConnectionVerificationParams): Promise<boolean> {- try {- const result = await this.oauthService.restoreAndVerify(params.identifier);- return result !== null;- } catch (error) {- if (error instanceof BlueskyOAuthNotEnabledError) {- throw error;- }- Logger.error(- {- identifier: params.identifier,- error: error instanceof Error ? error.message : String(error),- },- 'Failed to verify Bluesky connection',- );- return false;- }- }-}diff --git a/fluxer_api/src/api/connection/verification/DomainConnectionVerifier.ts b/fluxer_api/src/api/connection/verification/DomainConnectionVerifier.tsindex 1ad154c06..68af3af21 100644--- a/fluxer_api/src/api/connection/verification/DomainConnectionVerifier.ts+++ b/fluxer_api/src/api/connection/verification/DomainConnectionVerifier.ts@@ -111,6 +111,7 @@ export class DomainConnectionVerifier implements IConnectionVerifier {serviceName: 'connection_verification',});if (response.status < 200 || response.status >= 300) {+ FetchUtils.discardResponseBody(response.stream, response.status);return false;}const body = await FetchUtils.streamToStringWithLimit(response.stream, {diff --git a/fluxer_api/src/api/constants/LimitConfig.ts b/fluxer_api/src/api/constants/LimitConfig.tsindex 400fc6e25..c7a06b9a2 100644--- a/fluxer_api/src/api/constants/LimitConfig.ts+++ b/fluxer_api/src/api/constants/LimitConfig.ts@@ -1,5 +1,6 @@// SPDX-License-Identifier: AGPL-3.0-or-later+import assert from 'node:assert/strict';import {GuildFeatures} from '@fluxer/constants/src/GuildConstants';import type {LimitKey} from '@fluxer/constants/src/LimitConfigMetadata';import {LIMIT_KEYS} from '@fluxer/constants/src/LimitConfigMetadata';@@ -13,17 +14,11 @@ const LIMIT_RULE_IDS = {VERY_LARGE_GUILD: 'very_large_guild',} as const;-export interface CachedLimitConfig {- config: LimitConfigSnapshot;- defaultsHash: string;-}--export function getLimitConfigKvKey(selfHosted: boolean): string {+export function getLegacyLimitConfigKvKey(selfHosted: boolean): string {return `limit_config:${selfHosted ? 'self_hosted' : 'saas'}`;}export const LIMIT_CONFIG_REFRESH_CHANNEL = 'limit-config-refresh';-export const LIMIT_CONFIG_REFRESH_LOCK_KEY = 'limit-config-refresh-lock';function cloneLimitConfigSnapshot(config: LimitConfigSnapshot): LimitConfigSnapshot {return structuredClone(config);@@ -107,6 +102,8 @@ export function mergeWithCurrentDefaults(const selfHosted = options?.selfHosted ?? false;const premiumMode = options?.premiumMode ?? 'everyone';const newDefaults = createDefaultLimitConfig({selfHosted, premiumMode});+ const defaultBaseRule = newDefaults.rules.find((rule) => rule.id === LIMIT_RULE_IDS.DEFAULT);+ assert(defaultBaseRule, 'Limit configuration defaults must include a default rule');const mergedRules: Array<LimitRule> = [];const existingRulesMap = new Map<string, LimitRule>();for (const rule of stored.rules) {@@ -119,14 +116,9 @@ export function mergeWithCurrentDefaults(continue;}const mergedLimits: Partial<Record<LimitKey, number>> = {...defaultRule.limits};- const modifiedFields: Array<LimitKey> = [];- for (const key of LIMIT_KEYS) {- const existingValue = existingRule.limits[key];- const defaultValue = defaultRule.limits[key];- if (existingValue !== undefined && existingValue !== defaultValue) {- mergedLimits[key] = existingValue;- modifiedFields.push(key);- }+ const modifiedFields = findModifiedLimits(existingRule.limits, defaultRule.limits);+ for (const key of modifiedFields) {+ mergedLimits[key] = existingRule.limits[key];}mergedRules.push({id: existingRule.id,@@ -137,11 +129,12 @@ export function mergeWithCurrentDefaults(existingRulesMap.delete(defaultRule.id);}for (const [, rule] of existingRulesMap) {+ const modifiedFields = findModifiedLimits(rule.limits, defaultBaseRule.limits);mergedRules.push({id: rule.id,filters: rule.filters,limits: rule.limits,- modifiedFields: rule.modifiedFields ?? (Object.keys(rule.limits) as Array<LimitKey>),+ modifiedFields: modifiedFields.length > 0 ? modifiedFields : undefined,});}return {@@ -149,3 +142,13 @@ export function mergeWithCurrentDefaults(rules: mergedRules,};}++function findModifiedLimits(+ currentLimits: Partial<Record<LimitKey, number>>,+ defaultLimits: Partial<Record<LimitKey, number>>,+): Array<LimitKey> {+ return LIMIT_KEYS.filter((key) => {+ const currentValue = currentLimits[key];+ return currentValue !== undefined && currentValue !== defaultLimits[key];+ });+}diff --git a/fluxer_api/src/api/csam/NcmecSubmissionService.ts b/fluxer_api/src/api/csam/NcmecSubmissionService.tsindex 050be057f..768bc766c 100644--- a/fluxer_api/src/api/csam/NcmecSubmissionService.ts+++ b/fluxer_api/src/api/csam/NcmecSubmissionService.ts@@ -652,18 +652,14 @@ export class NcmecSubmissionService {const privateReason = `Confirmed CSAM - NCMEC Report ${ncmecReportId} - ${contextLabel}`;const pendingDeletionAt = new Date();pendingDeletionAt.setDate(pendingDeletionAt.getDate() + NCMEC_DELETION_GRACE_DAYS);- const updatedUser = await this.deps.userRepository.patchUpsert(- userId,- {- flags: user.flags | UserFlags.DELETED | UserFlags.DISABLED,- temp_banned_until: null,- pending_deletion_at: pendingDeletionAt,- deletion_reason_code: DeletionReasons.CHILD_SEXUAL_CONTENT,- deletion_public_reason: null,- deletion_audit_log_reason: privateReason,- },- user.toRow(),- );+ const updatedUser = await this.deps.userRepository.updateDeletionSchedule(user, {+ flags: user.flags | UserFlags.DELETED | UserFlags.DISABLED,+ temp_banned_until: null,+ pending_deletion_at: pendingDeletionAt,+ deletion_reason_code: DeletionReasons.CHILD_SEXUAL_CONTENT,+ deletion_public_reason: null,+ deletion_audit_log_reason: privateReason,+ });await reschedulePendingDeletion({userId,currentPendingDeletionAt: user.pendingDeletionAt,diff --git a/fluxer_api/src/api/database/CassandraQueryExecution.ts b/fluxer_api/src/api/database/CassandraQueryExecution.tsindex 1cbb82cee..fd6a3b428 100644--- a/fluxer_api/src/api/database/CassandraQueryExecution.ts+++ b/fluxer_api/src/api/database/CassandraQueryExecution.ts@@ -8,7 +8,13 @@ import {chunkArray} from '../utils/ArrayUtils';import {logBatch, logQuery} from './CassandraDevLogger';import {getIsDev} from './CassandraMetaRegistry';import type {CassandraParams, KvQueryMeta, PreparedQuery, QueryTemplate} from './CassandraTypes';-import {assertNoUndefinedParams, getStatementMeta, normalizeExecuteArgs, normalizeInParams} from './CassandraTypes';+import {+ assertNoUndefinedParams,+ getStatementMeta,+ isConditionalQuery,+ normalizeExecuteArgs,+ normalizeInParams,+} from './CassandraTypes';const DEFAULT_MAX_PARTITION_KEYS_PER_QUERY = 100;@@ -77,6 +83,10 @@ export interface PagedQueryResult<T> {pageState: string | null;}+interface CassandraReadOptions {+ consistency: 'all' | 'serial';+}+async function collectSelectRows<T>(queryType: string, result: cassandra.types.ResultSet): Promise<Array<T>> {if (queryType !== 'SELECT' || !result.pageState) {return (result.rows ?? []) as Array<T>;@@ -91,6 +101,7 @@ async function collectSelectRows<T>(queryType: string, result: cassandra.types.Rexport async function executeQuery<T = Record<string, unknown>, P extends CassandraParams = CassandraParams>(queryOrPrepared: string | PreparedQuery<P>,params?: P,+ readOptions?: CassandraReadOptions,): Promise<Array<T>> {const {cql, params: boundRaw} = normalizeExecuteArgs(queryOrPrepared, params);const meta = getStatementMeta(cql);@@ -98,6 +109,9 @@ export async function executeQuery<T = Record<string, unknown>, P extends Cassanif (meta.unsafe) {throw new Error('Cannot prepare a statement that looks like `SELECT *`');}+ if (readOptions && meta.type !== 'SELECT') {+ throw new Error('Read consistency options require a SELECT query');+ }assertNoUndefinedParams(bound as Record<string, unknown>);const executor = activeExecutor();if (executor) {@@ -110,7 +124,10 @@ export async function executeQuery<T = Record<string, unknown>, P extends Cassanconst isDev = getIsDev();const startTime = isDev ? performance.now() : 0;try {- const result = await getClient().execute(cql, bound, {prepare: true});+ const result = await getClient().execute(cql, bound, {+ prepare: true,+ ...(readOptions ? {consistency: cassandra.types.consistencies[readOptions.consistency]} : {}),+ });const rows = await collectSelectRows<T>(meta.type, result);if (isDev) {const durationMs = performance.now() - startTime;@@ -138,6 +155,23 @@ export async function executeQuery<T = Record<string, unknown>, P extends Cassan}}+export async function executeConditional(query: PreparedQuery): Promise<boolean> {+ if (!isConditionalQuery(query)) {+ throw new Error('executeConditional requires a conditional query');+ }+ const rows = await executeQuery(query);+ const applied = rows[0]?.['[applied]'];+ const isBatch = query.kvMeta?.action === 'batch';+ if (+ typeof applied !== 'boolean' ||+ (!isBatch && rows.length !== 1) ||+ rows.some((row) => row['[applied]'] !== applied)+ ) {+ throw new Error('Conditional write returned an invalid database result');+ }+ return applied;+}+export async function fetchOne<T = Record<string, unknown>, P extends CassandraParams = CassandraParams>(queryOrPrepared: PreparedQuery<P> | string,params?: P,@@ -149,8 +183,9 @@ export async function fetchOne<T = Record<string, unknown>, P extends CassandraPexport async function fetchMany<T = Record<string, unknown>, P extends CassandraParams = CassandraParams>(queryOrPrepared: PreparedQuery<P> | string,params?: P,+ readOptions?: CassandraReadOptions,): Promise<Array<T>> {- return executeQuery<T, P>(queryOrPrepared, params);+ return executeQuery<T, P>(queryOrPrepared, params, readOptions);}export async function fetchPage<T = Record<string, unknown>, P extends CassandraParams = CassandraParams>(@@ -228,6 +263,7 @@ export async function upsertOne<P extends CassandraParams = CassandraParams>(queryOrPrepared: PreparedQuery<P> | string,params?: P,): Promise<void> {+ assertUnconditional(normalizeExecuteArgs(queryOrPrepared, params));await executeQuery(queryOrPrepared, params);}@@ -235,9 +271,16 @@ export async function deleteOneOrMany<P extends CassandraParams = CassandraParamqueryOrPrepared: PreparedQuery<P> | string,params?: P,): Promise<void> {+ assertUnconditional(normalizeExecuteArgs(queryOrPrepared, params));await executeQuery(queryOrPrepared, params);}+function assertUnconditional(query: PreparedQuery): void {+ if (isConditionalQuery(query)) {+ throw new Error('Conditional writes must use executeConditional to preserve their result');+ }+}+interface BatchQuery {query: string;params: object;@@ -246,7 +289,8 @@ interface BatchQuery {async function executeBatch(queries: Array<BatchQuery>, atomic = true): Promise<void> {if (queries.length === 0) return;- for (const {query} of queries) {+ for (const {query, params, meta} of queries) {+ assertUnconditional({cql: query, params: params as CassandraParams, kvMeta: meta});if (getStatementMeta(query).unsafe) {throw new Error('Cannot prepare a statement that looks like `SELECT *`');}diff --git a/fluxer_api/src/api/database/CassandraTableDsl.ts b/fluxer_api/src/api/database/CassandraTableDsl.tsindex d6eede066..895ae02b6 100644--- a/fluxer_api/src/api/database/CassandraTableDsl.ts+++ b/fluxer_api/src/api/database/CassandraTableDsl.ts@@ -1,11 +1,15 @@// SPDX-License-Identifier: AGPL-3.0-or-later+import {isDeepStrictEqual} from 'node:util';import {registerKvMeta, registerTableSpec} from './CassandraMetaRegistry';import type {CassandraParam,CassandraParams,ColumnName,+ ConditionalWriteEntry,DbOp,+ KvConditionalBatchEntry,+ KvQueryCondition,KvQueryMeta,KvTableSpec,OrderBy,@@ -15,7 +19,7 @@ import type {Table,WhereExpr,} from './CassandraTypes';-import {prepared} from './CassandraTypes';+import {prepared, validateTtlSeconds} from './CassandraTypes';const DEFAULT_TTL_PARAM_NAME = 'ttl_seconds_bind';const DEFAULT_LIMIT_PARAM_NAME = 'limit_bind';@@ -66,6 +70,14 @@ function opToValue(op: DbOp<unknown>): CassandraParam {return op.kind === 'clear' ? null : (op.value as CassandraParam);}+function assertConditionalValue(value: unknown, column: string): void {+ if (value === null || typeof value === 'string' || typeof value === 'boolean' || typeof value === 'bigint') return;+ if (typeof value === 'number' && Number.isFinite(value)) return;+ if (value instanceof Date && Number.isFinite(value.getTime())) return;+ if (Buffer.isBuffer(value)) return;+ throw new Error(`Conditional writes require a finite scalar, date or buffer for "${column}"`);+}+export function defineTable<Row extends object, PK extends ColumnName<Row>, PartKey extends ColumnName<Row> = PK>(def: {name: string;columns: ReadonlyArray<ColumnName<Row>>;@@ -237,6 +249,179 @@ WHERE ${pk.map((k) => `${k} = :${k}`).join(' AND ')};};return prepared(cql, params, kvMeta as KvQueryMeta<Record<string, unknown>>);}+ function withConditions(query: PreparedQuery, expected: Partial<Row>): PreparedQuery {+ const keys = Object.keys(expected) as Array<ColumnName<Row>>;+ if (keys.length === 0) {+ throw new Error(`Conditional writes require expected values for table "${def.name}"`);+ }+ if (!query.kvMeta) {+ throw new Error(`Conditional writes require query metadata for table "${def.name}"`);+ }+ const params = {...query.params};+ for (const col of pk) {+ if (!Object.hasOwn(params, col) || params[col] == null) {+ throw new Error(`Conditional writes require a primary key value for "${def.name}.${col}"`);+ }+ }+ const conditions: Array<KvQueryCondition<Row>> = [];+ let hasNonNullValue = false;+ keys.sort((a, b) => columns.indexOf(a) - columns.indexOf(b));+ for (const col of keys) {+ if (!columns.includes(col) || pk.includes(col as PK)) {+ throw new Error(`Invalid conditional write column "${def.name}.${col}"`);+ }+ const value = expected[col];+ if (value === undefined) {+ throw new Error(`Missing expected value for "${def.name}.${col}"`);+ }+ assertConditionalValue(value, `${def.name}.${col}`);+ const expectedParam = `expected_${col}`;+ if (Object.hasOwn(params, expectedParam)) {+ throw new Error(`Conditional write parameter "${expectedParam}" conflicts with a column value`);+ }+ params[expectedParam] = value as CassandraParam;+ conditions.push({col, expectedParam});+ hasNonNullValue ||= value !== null;+ }+ if (!hasNonNullValue) {+ throw new Error(`Conditional writes require a non-null expected value for table "${def.name}"`);+ }+ const conditionCql = conditions.map(({col, expectedParam}) => `${col} = :${expectedParam}`).join(' AND ');+ const cql = query.cql.replace(/;\s*$/, ` IF ${conditionCql};`);+ const kvMeta: KvQueryMeta<Row> = {+ action: query.kvMeta.action,+ table: tableSpec,+ pkColumns: pk,+ patchKeys: query.kvMeta.patchKeys as ReadonlyArray<ColumnName<Row>> | undefined,+ ttlParamName: query.kvMeta.ttlParamName,+ conditions,+ };+ return prepared(cql, params, kvMeta as KvQueryMeta<Record<string, unknown>>);+ }+ function assertConditionalPatchColumns(patch: object): void {+ for (const col of Object.keys(patch)) {+ if (!nonPkColumns.includes(col as Exclude<ColumnName<Row>, PK>)) {+ throw new Error(`Invalid conditional patch column "${def.name}.${col}"`);+ }+ }+ }+ function conditionalPatchByPk(+ pkValues: Pick<Row, PK>,+ patch: Partial<{+ [K in Exclude<ColumnName<Row>, PK>]: DbOp<RowValue<Row, K>>;+ }>,+ expected: Partial<Row>,+ ): PreparedQuery {+ assertConditionalPatchColumns(patch);+ return withConditions(patchByPk(pkValues, patch), expected);+ }+ function conditionalPatchByPkWithTtl(+ pkValues: Pick<Row, PK>,+ patch: Partial<{+ [K in Exclude<ColumnName<Row>, PK>]: DbOp<RowValue<Row, K>>;+ }>,+ expected: Partial<Row>,+ ttlSeconds: number,+ ): PreparedQuery {+ assertConditionalPatchColumns(patch);+ return withConditions(patchByPkWithTtl(pkValues, patch, validateTtlSeconds(ttlSeconds)), expected);+ }+ function conditionalBatch(entries: ReadonlyArray<ConditionalWriteEntry<Row, PK>>): PreparedQuery {+ const first = entries[0];+ if (!first) {+ throw new Error(`Conditional batches require at least one row for table "${def.name}"`);+ }+ const params: CassandraParams = {};+ const statements: Array<string> = [];+ const batchEntries: Array<KvConditionalBatchEntry<Row>> = [];+ const firstKey = first.action === 'insert' ? first.row : first.pk;+ const firstPartition = partitionKey.map((col) => Reflect.get(firstKey, col));+ const seenKeys: Array<Pick<Row, PK>> = [];+ for (const [index, entry] of entries.entries()) {+ const entryKey = entry.action === 'insert' ? entry.row : entry.pk;+ for (const col of pk) {+ if (entryKey[col] == null) {+ throw new Error(`Conditional batches require a primary key value for "${def.name}.${col}"`);+ }+ }+ if (+ !isDeepStrictEqual(+ partitionKey.map((col) => Reflect.get(entryKey, col)),+ firstPartition,+ )+ ) {+ throw new Error(`Conditional batches must stay within one partition of table "${def.name}"`);+ }+ if (seenKeys.some((other) => pk.every((col) => isDeepStrictEqual(entryKey[col], other[col])))) {+ throw new Error(`Conditional batches cannot repeat a row of table "${def.name}"`);+ }+ seenKeys.push(entryKey);+ const query = conditionalEntryQuery(entry);+ const prefix = `entry_${index}_`;+ for (const [name, value] of Object.entries(query.params)) params[`${prefix}${name}`] = value;+ statements.push(query.cql.replace(/:([A-Za-z_][A-Za-z0-9_]*)/g, (_match, name: string) => `:${prefix}${name}`));+ batchEntries.push(conditionalEntryMeta(entry, query, prefix));+ }+ const kvMeta: KvQueryMeta<Row> = {+ action: 'batch',+ table: tableSpec,+ batchEntries,+ };+ return prepared(+ `BEGIN BATCH\n${statements.join('\n')}\nAPPLY BATCH;`,+ params,+ kvMeta as KvQueryMeta<Record<string, unknown>>,+ );+ }+ function conditionalEntryQuery(entry: ConditionalWriteEntry<Row, PK>): PreparedQuery {+ switch (entry.action) {+ case 'insert':+ return entry.ttlSeconds === undefined+ ? insertIfNotExists(entry.row)+ : insertIfNotExistsWithTtl(entry.row, entry.ttlSeconds);+ case 'patch':+ return entry.ttlSeconds === undefined+ ? conditionalPatchByPk(entry.pk, entry.patch, entry.expected)+ : conditionalPatchByPkWithTtl(entry.pk, entry.patch, entry.expected, entry.ttlSeconds);+ case 'delete':+ return conditionalDeleteByPk(entry.pk, entry.expected);+ }+ }+ function conditionalEntryMeta(+ entry: ConditionalWriteEntry<Row, PK>,+ query: PreparedQuery,+ prefix: string,+ ): KvConditionalBatchEntry<Row> {+ const key = pk.map((col) => ({col, param: `${prefix}${col}`}));+ const ttlMetadata =+ query.kvMeta?.ttlParamName === undefined ? {} : {ttlParamName: `${prefix}${query.kvMeta.ttlParamName}`};+ if (entry.action === 'insert') {+ return {+ action: 'insert',+ pk: key,+ values: columns.map((col) => ({col, param: `${prefix}${col}`})),+ ...ttlMetadata,+ };+ }+ if (!query.kvMeta?.conditions) {+ throw new Error(`Conditional batch entry has incomplete metadata for table "${def.name}"`);+ }+ const conditions = query.kvMeta.conditions.map(({col, expectedParam}) => ({+ col: col as ColumnName<Row>,+ expectedParam: `${prefix}${expectedParam}`,+ }));+ if (entry.action === 'delete') return {action: 'delete', pk: key, conditions};+ if (!query.kvMeta.patchKeys) {+ throw new Error(`Conditional batch patch has incomplete metadata for table "${def.name}"`);+ }+ return {+ action: 'patch',+ pk: key,+ patch: query.kvMeta.patchKeys.map((col) => ({col: col as ColumnName<Row>, param: `${prefix}${col}`})),+ conditions,+ ...ttlMetadata,+ };+ }const deleteByPkCql = `DELETE FROM ${def.name} WHERE ${pk.map((k) => `${k} = :${k}`).join(' AND ')};`;registerKvMeta(deleteByPkCql, {action: 'delete',@@ -281,10 +466,14 @@ WHERE ${pk.map((k) => `${k} = :${k}`).join(' AND ')};const kvMeta: KvQueryMeta<Row> = {action: 'delete',table: tableSpec,+ pkColumns: pk,where: pk.map((col) => ({kind: 'eq', col, param: col})) as ReadonlyArray<WhereExpr<Row>>,} as KvQueryMeta<Row>;return prepared(deleteByPkCql, params, kvMeta as KvQueryMeta<Record<string, unknown>>);}+ function conditionalDeleteByPk(pkValues: Pick<Row, PK>, expected: Partial<Row>): PreparedQuery {+ return withConditions(deleteByPk(pkValues), expected);+ }function deletePartition(partKeyValues: Pick<Row, PartKey>): PreparedQuery {if (partitionKey.length === 0) {throw new Error(`Table "${def.name}" has empty partitionKey; cannot deletePartition()`);@@ -317,6 +506,18 @@ WHERE ${pk.map((k) => `${k} = :${k}`).join(' AND ')};const kvMeta: KvQueryMeta<Row> = {action: 'upsert', table: tableSpec, ifNotExists: true};return prepared(cql, params, kvMeta as KvQueryMeta<Record<string, unknown>>);}+ function insertIfNotExistsWithTtl(row: Row, ttlSeconds: number): PreparedQuery {+ const cql = `${insertBaseCql} IF NOT EXISTS USING TTL :${DEFAULT_TTL_PARAM_NAME};`;+ const params = paramsFromRow(row);+ params[DEFAULT_TTL_PARAM_NAME] = validateTtlSeconds(ttlSeconds);+ const kvMeta: KvQueryMeta<Row> = {+ action: 'upsert',+ table: tableSpec,+ ifNotExists: true,+ ttlParamName: DEFAULT_TTL_PARAM_NAME,+ };+ return prepared(cql, params, kvMeta as KvQueryMeta<Record<string, unknown>>);+ }function insertWithTtl(row: Row, ttlSeconds: number): PreparedQuery {const cql = `${insertBaseCql} USING TTL :${DEFAULT_TTL_PARAM_NAME};`;const params = paramsFromRow(row);@@ -501,13 +702,18 @@ WHERE ${pk.map((k) => `${k} = :${k}`).join(' AND ')};return prepared(cql, params, kvMeta as KvQueryMeta<Record<string, unknown>>);},patchByPk,+ conditionalPatchByPk,+ conditionalPatchByPkWithTtl,+ conditionalBatch,deleteCql,delete: del,deleteByPk,+ conditionalDeleteByPk,deletePartition,insertCql,insert,insertIfNotExists,+ insertIfNotExistsWithTtl,insertWithTtl,insertWithTtlParam,selectCountCql,diff --git a/fluxer_api/src/api/database/CassandraTypes.ts b/fluxer_api/src/api/database/CassandraTypes.tsindex 6cd936ff7..2ef31960f 100644--- a/fluxer_api/src/api/database/CassandraTypes.ts+++ b/fluxer_api/src/api/database/CassandraTypes.ts@@ -2,6 +2,8 @@import type cassandra from 'cassandra-driver';+const MAX_TTL_SECONDS = 630_720_000;+export type DbOp<T> =| {kind: 'set';@@ -24,6 +26,13 @@ export function nextVersion(current: number | null | undefined): number {return (current ?? 0) + 1;}+export function validateTtlSeconds(value: number): number {+ if (!Number.isInteger(value) || value < 0 || value > MAX_TTL_SECONDS) {+ throw new Error(`Cassandra TTL must be an integer between 0 and ${MAX_TTL_SECONDS} seconds`);+ }+ return value;+}+export type ColumnName<Row> = Extract<keyof Row, string>;export type RowValue<Row, K extends ColumnName<Row>> = Row[K & keyof Row];export type CassandraParam =@@ -49,6 +58,32 @@ export interface KvTableSpec<Row extends object = Record<string, unknown>> {partitionKey: ReadonlyArray<ColumnName<Row>>;}+export interface KvColumnParam<Row extends object = Record<string, unknown>> {+ col: ColumnName<Row>;+ param: string;+}++export interface KvQueryCondition<Row extends object = Record<string, unknown>> {+ col: ColumnName<Row>;+ expectedParam: string;+}++interface KvConditionalBatchKey<Row extends object> {+ pk: ReadonlyArray<KvColumnParam<Row>>;+}++export type KvConditionalBatchEntry<Row extends object = Record<string, unknown>> = KvConditionalBatchKey<Row> &+ (+ | {action: 'insert'; values: ReadonlyArray<KvColumnParam<Row>>; ttlParamName?: string}+ | {+ action: 'patch';+ patch: ReadonlyArray<KvColumnParam<Row>>;+ conditions: ReadonlyArray<KvQueryCondition<Row>>;+ ttlParamName?: string;+ }+ | {action: 'delete'; conditions: ReadonlyArray<KvQueryCondition<Row>>}+ );+export interface KvQueryMeta<Row extends object = Record<string, unknown>> {action: KvAction;table: KvTableSpec<Row>;@@ -62,11 +97,8 @@ export interface KvQueryMeta<Row extends object = Record<string, unknown>> {ttlSeconds?: number;ttlParamName?: string;nowColumn?: ColumnName<Row>;- condition?: {- col: ColumnName<Row>;- expectedParam: string;- expectedValue: unknown;- };+ conditions?: ReadonlyArray<KvQueryCondition<Row>>;+ batchEntries?: ReadonlyArray<KvConditionalBatchEntry<Row>>;ifNotExists?: boolean;}@@ -80,6 +112,15 @@ export function prepared<P extends CassandraParams>(cql: string, params: P, kvMereturn {cql, params, kvMeta};}+export function isConditionalQuery(query: PreparedQuery): boolean {+ return (+ query.kvMeta?.conditions !== undefined ||+ query.kvMeta?.batchEntries !== undefined ||+ query.kvMeta?.ifNotExists === true ||+ /\bIF\b/i.test(query.cql)+ );+}+export interface QueryTemplate<P extends CassandraParams = CassandraParams> {cql: string;bind(params: P): PreparedQuery<P>;@@ -131,6 +172,19 @@ export type OrderBy<Row extends object> = {direction?: 'ASC' | 'DESC';};+export type ConditionalWriteEntry<Row extends object, PK extends ColumnName<Row>> =+ | {action: 'insert'; row: Row; ttlSeconds?: number}+ | {+ action: 'patch';+ pk: Pick<Row, PK>;+ patch: Partial<{+ [K in Exclude<ColumnName<Row>, PK>]: DbOp<RowValue<Row, K>>;+ }>;+ expected: Partial<Row>;+ ttlSeconds?: number;+ }+ | {action: 'delete'; pk: Pick<Row, PK>; expected: Partial<Row>};+export interface Table<Row extends object, PK extends ColumnName<Row>, PartKey extends ColumnName<Row> = PK> {name: string;columns: ReadonlyArray<ColumnName<Row>>;@@ -157,13 +211,31 @@ export interface Table<Row extends object, PK extends ColumnName<Row>, PartKey e[K in Exclude<ColumnName<Row>, PK>]: DbOp<RowValue<Row, K>>;}>,): PreparedQuery;+ conditionalPatchByPk(+ pk: Pick<Row, PK>,+ patch: Partial<{+ [K in Exclude<ColumnName<Row>, PK>]: DbOp<RowValue<Row, K>>;+ }>,+ expected: Partial<Row>,+ ): PreparedQuery;+ conditionalPatchByPkWithTtl(+ pk: Pick<Row, PK>,+ patch: Partial<{+ [K in Exclude<ColumnName<Row>, PK>]: DbOp<RowValue<Row, K>>;+ }>,+ expected: Partial<Row>,+ ttlSeconds: number,+ ): PreparedQuery;+ conditionalBatch(entries: ReadonlyArray<ConditionalWriteEntry<Row, PK>>): PreparedQuery;deleteCql(opts?: {where?: WhereExpr<Row> | ReadonlyArray<WhereExpr<Row>>}): string;delete(opts?: {where?: WhereExpr<Row> | ReadonlyArray<WhereExpr<Row>>}): QueryTemplate;deleteByPk(pk: Pick<Row, PK>): PreparedQuery;+ conditionalDeleteByPk(pk: Pick<Row, PK>, expected: Partial<Row>): PreparedQuery;deletePartition(pk: Pick<Row, PartKey>): PreparedQuery;insertCql(opts?: {ttlParam?: string}): string;insert(row: Row): PreparedQuery;insertIfNotExists(row: Row): PreparedQuery;+ insertIfNotExistsWithTtl(row: Row, ttlSeconds: number): PreparedQuery;insertWithTtl(row: Row, ttlSeconds: number): PreparedQuery;insertWithTtlParam(row: Row, ttlParamName: string): PreparedQuery;selectCountCql(opts?: {where?: WhereExpr<Row> | ReadonlyArray<WhereExpr<Row>>}): string;diff --git a/fluxer_api/src/api/database/PostgresKvQueryExecutor.ts b/fluxer_api/src/api/database/PostgresKvQueryExecutor.tsindex 52bf25b2f..a6d68b38c 100644--- a/fluxer_api/src/api/database/PostgresKvQueryExecutor.ts+++ b/fluxer_api/src/api/database/PostgresKvQueryExecutor.ts@@ -4,7 +4,8 @@ import {type IPostgresClient, type PostgresQueryable, quoteIdentifier} from '@pkimport cassandra from 'cassandra-driver';import {Logger} from '../Logger';import {getKvMeta, getTableMetadata} from './CassandraMetaRegistry';-import type {CassandraParams, ColumnName, KvQueryMeta, PreparedQuery, WhereExpr} from './CassandraTypes';+import type {CassandraParams, ColumnName, KvColumnParam, KvQueryMeta, PreparedQuery, WhereExpr} from './CassandraTypes';+import {isConditionalQuery, validateTtlSeconds} from './CassandraTypes';type Row = Record<string, unknown>;type EqWhereExpr = Extract<WhereExpr<Row>, {kind: 'eq'}>;@@ -202,6 +203,17 @@ function paramsRow(params: CassandraParams, columns: ReadonlyArray<string>): Rowreturn row;}+function boundColumns(params: CassandraParams, columns: ReadonlyArray<KvColumnParam>): CassandraParams {+ const row: CassandraParams = {};+ for (const {col, param} of columns) {+ if (!Object.hasOwn(params, param) || params[param] === undefined) {+ throw new Error(`Missing conditional write parameter: ${param}`);+ }+ row[col] = params[param];+ }+ return row;+}+function rowFromParams(meta: KvQueryMeta, params: CassandraParams): Row {const row: Row = {};for (const column of meta.table.columns) {@@ -667,7 +679,8 @@ function ttlExpiresAt(meta: KvQueryMeta, params: CassandraParams): Date | null |if (typeof ttlRaw !== 'number') {throw new Error(`TTL parameter ${ttlParam} must be a number`);}- return new Date(Date.now() + ttlRaw * 1000);+ const ttlSeconds = validateTtlSeconds(ttlRaw);+ return ttlSeconds === 0 ? null : new Date(Date.now() + ttlSeconds * 1000);}function encodePageState(pageState: PageState): string {@@ -945,6 +958,9 @@ export class PostgresKvQueryExecutor {db: PostgresQueryable = this.client,): Promise<Array<T>> {const meta = this.meta(query);+ if (meta.conditions !== undefined) {+ return (await this.conditionalWrite(meta, query.params, db)) as Array<T>;+ }switch (meta.action) {case 'select':return (await this.select(meta, query.params, buildCandidatePlan(meta, query.params), db)) as Array<T>;@@ -961,7 +977,11 @@ export class PostgresKvQueryExecutor {await this.delete(meta, query.params, db);return [];case 'batch':- return [];+ if (meta.batchEntries === undefined) return [];+ if (db !== this.client) {+ throw new Error('Conditional batches must own their database transaction');+ }+ return (await this.conditionalBatch(meta, query.params)) as Array<T>;default: {const _exhaustive: never = meta.action;throw new Error(`Unsupported Postgres KV action: ${_exhaustive}`);@@ -1047,6 +1067,11 @@ export class PostgresKvQueryExecutor {queries: Array<{query: string; params: object; meta?: KvQueryMeta}>,atomic = true,): Promise<void> {+ for (const query of queries) {+ if (isConditionalQuery({cql: query.query, params: query.params as CassandraParams, kvMeta: query.meta})) {+ throw new Error('Conditional writes must use executeConditional to preserve their result');+ }+ }if (atomic) {await this.client.transaction(async (db) => {for (const query of queries) {@@ -1182,6 +1207,132 @@ WHERE NOT $6`,return [];}+ private async conditionalWrite(+ meta: KvQueryMeta,+ params: CassandraParams,+ db: PostgresQueryable,+ ): Promise<Array<Row>> {+ if (meta.action !== 'patch' && meta.action !== 'delete') {+ throw new Error(`Unsupported conditional write action: ${meta.action}`);+ }+ if (!meta.conditions?.length) {+ throw new Error('Conditional writes require expected values');+ }+ const bindings: Array<unknown> = [meta.table.name, rowKeyFromParams(meta, params)];+ const predicates = ['kv.table_name = $1', 'kv.row_key = $2', '(kv.expires_at IS NULL OR kv.expires_at > now())'];+ for (const {col, expectedParam} of meta.conditions) {+ if (!Object.hasOwn(params, expectedParam) || params[expectedParam] === undefined) {+ throw new Error(`Missing conditional write parameter: ${expectedParam}`);+ }+ bindings.push(col, JSON.stringify(encodeValue(params[expectedParam])));+ predicates.push(+ `COALESCE(kv.row_data -> $${bindings.length - 1}::text, 'null'::jsonb) = $${bindings.length}::jsonb`,+ );+ }+ const where = predicates.join(' AND ');+ let sql = `DELETE FROM ${this.table} kv WHERE ${where}`;+ if (meta.action === 'patch') {+ if (!meta.patchKeys?.length) {+ throw new Error('Conditional patches require at least one column');+ }+ bindings.push(JSON.stringify(encodeRow(paramsRow(params, meta.patchKeys))));+ const assignments = [`row_data = kv.row_data || $${bindings.length}::jsonb`, 'updated_at = now()'];+ const expiresAt = ttlExpiresAt(meta, params);+ if (expiresAt !== undefined) {+ bindings.push(expiresAt);+ assignments.push(`expires_at = $${bindings.length}`);+ }+ sql = `UPDATE ${this.table} kv SET ${assignments.join(', ')} WHERE ${where}`;+ }+ const result = await db.query(sql, bindings);+ if (result.rowCount !== 0 && result.rowCount !== 1) {+ throw new Error('Conditional write returned an invalid affected row count');+ }+ return [{'[applied]': result.rowCount === 1}];+ }++ private async conditionalBatch(meta: KvQueryMeta, params: CassandraParams): Promise<Array<Row>> {+ const entries = meta.batchEntries;+ if (!entries?.length) {+ throw new Error('Conditional batches require at least one row');+ }+ const writes = entries.map((entry) => {+ const values = boundColumns(params, entry.pk);+ const writeMeta: KvQueryMeta = {+ action: entry.action,+ table: meta.table,+ pkColumns: entry.pk.map(({col}) => col),+ };+ if (entry.action === 'insert') {+ Object.assign(values, boundColumns(params, entry.values));+ writeMeta.ifNotExists = true;+ } else {+ if (entry.conditions.length === 0) {+ throw new Error('Conditional batch updates and deletes require expected values');+ }+ if (entry.action === 'patch') {+ if (entry.patch.length === 0) {+ throw new Error('Conditional batch patches require at least one column');+ }+ Object.assign(values, boundColumns(params, entry.patch));+ writeMeta.patchKeys = entry.patch.map(({col}) => col);+ }+ const expected = boundColumns(+ params,+ entry.conditions.map(({col, expectedParam}) => ({col, param: expectedParam})),+ );+ writeMeta.conditions = Object.entries(expected).map(([col, value]) => {+ const expectedParam = `expected_${col}`;+ if (Object.hasOwn(values, expectedParam)) {+ throw new Error(`Conditional batch parameter conflicts with a column value: ${expectedParam}`);+ }+ values[expectedParam] = value;+ return {col, expectedParam};+ });+ }+ if (entry.action !== 'delete' && entry.ttlParamName !== undefined) {+ const ttl = params[entry.ttlParamName];+ if (typeof ttl !== 'number') {+ throw new Error(`TTL parameter ${entry.ttlParamName} must be a number`);+ }+ if (Object.hasOwn(values, entry.ttlParamName)) {+ throw new Error(`Conditional batch TTL parameter conflicts with a column value: ${entry.ttlParamName}`);+ }+ values[entry.ttlParamName] = validateTtlSeconds(ttl);+ writeMeta.ttlParamName = entry.ttlParamName;+ }+ const key = rowKey(meta, values);+ return {key, keyBytes: Buffer.from(key), partition: partitionKey(meta, values), meta: writeMeta, params: values};+ });+ if (new Set(writes.map(({key}) => key)).size !== writes.length) {+ throw new Error('Conditional batches cannot repeat a row');+ }+ if (new Set(writes.map(({partition}) => partition)).size !== 1) {+ throw new Error('Conditional batches must stay within one partition');+ }+ writes.sort((left, right) => Buffer.compare(left.keyBytes, right.keyBytes));+ const rejected = new Error('Conditional batch was not applied');+ try {+ await this.client.transaction(async (db) => {+ for (const write of writes) {+ const result =+ write.meta.action === 'insert'+ ? await this.upsert(write.meta, write.params, db)+ : await this.conditionalWrite(write.meta, write.params, db);+ const applied = result[0]?.['[applied]'];+ if (result.length !== 1 || typeof applied !== 'boolean') {+ throw new Error('Conditional batch entry returned an invalid database result');+ }+ if (!applied) throw rejected;+ }+ });+ } catch (error) {+ if (error !== rejected) throw error;+ return [{'[applied]': false}];+ }+ return [{'[applied]': true}];+ }+private async patch(meta: KvQueryMeta, params: CassandraParams, db: PostgresQueryable): Promise<void> {const key = rowKeyFromParams(meta, params);const incoming = paramsRow(params, (meta.pkColumns ?? meta.table.primaryKey) as ReadonlyArray<string>);diff --git a/fluxer_api/src/api/database/types/AdminArchiveTypes.ts b/fluxer_api/src/api/database/types/AdminArchiveTypes.tsindex 340003c12..043ec4e82 100644--- a/fluxer_api/src/api/database/types/AdminArchiveTypes.ts+++ b/fluxer_api/src/api/database/types/AdminArchiveTypes.ts@@ -2,15 +2,27 @@import type {ArchiveSubjectType} from '@fluxer/schema/src/domains/admin/AdminArchiveSchemas';-export interface AdminArchiveRow {+export interface AdminArchiveIndexRow {subject_type: ArchiveSubjectType;subject_id: bigint;archive_id: bigint;requested_by: bigint;+}++export const ADMIN_ARCHIVE_INDEX_COLUMNS = [+ 'subject_type',+ 'subject_id',+ 'archive_id',+ 'requested_by',+] as const satisfies ReadonlyArray<keyof AdminArchiveIndexRow>;++export interface AdminArchiveRow extends AdminArchiveIndexRow {requested_at: Date;+ attempt_id?: string | null;started_at: Date | null;completed_at: Date | null;failed_at: Date | null;+ terminal_failed_at?: Date | null;storage_key: string | null;file_size: bigint | null;progress_percent: number;@@ -21,14 +33,13 @@ export interface AdminArchiveRow {}export const ADMIN_ARCHIVE_COLUMNS = [- 'subject_type',- 'subject_id',- 'archive_id',- 'requested_by',+ ...ADMIN_ARCHIVE_INDEX_COLUMNS,'requested_at',+ 'attempt_id','started_at','completed_at','failed_at',+ 'terminal_failed_at','storage_key','file_size','progress_percent',diff --git a/fluxer_api/src/api/database/types/ConnectionTypes.ts b/fluxer_api/src/api/database/types/ConnectionTypes.tsindex bc675e6dd..32b5dfd49 100644--- a/fluxer_api/src/api/database/types/ConnectionTypes.ts+++ b/fluxer_api/src/api/database/types/ConnectionTypes.ts@@ -3,11 +3,28 @@import type {ConnectionType} from '@fluxer/constants/src/ConnectionConstants';import type {UserID} from '../../BrandedTypes';-type Nullish<T> = T | null;--export interface UserConnectionRow {+export interface UserConnectionStorageRow {user_id: UserID;connection_id: string;+ connection_type: string;+ identifier: string | null;+ name: string | null;+ verified: boolean | null;+ visibility_flags: number | null;+ sort_order: number | null;+ verification_token: string | null;+ oauth_grant_id?: string | null;+ verified_at: Date | null;+ last_verified_at: Date | null;+ created_at: Date | null;+ revision?: string | null;+ version: number | null;+ membership?: string | null;+ credential_payload?: string | null;+ credential_expires_at?: Date | null;+}++export interface UserConnectionRow extends UserConnectionStorageRow {connection_type: ConnectionType;identifier: string;name: string;@@ -15,10 +32,15 @@ export interface UserConnectionRow {visibility_flags: number;sort_order: number;verification_token: string;- verified_at: Nullish<Date>;- last_verified_at: Nullish<Date>;created_at: Date;version: number;+ membership?: null;+ credential_payload?: null;+ credential_expires_at?: null;+}++export interface RevisionedUserConnectionRow extends UserConnectionRow {+ revision: string;}export const USER_CONNECTION_COLUMNS = [@@ -31,8 +53,19 @@ export const USER_CONNECTION_COLUMNS = ['visibility_flags','sort_order','verification_token',+ 'oauth_grant_id','verified_at','last_verified_at','created_at',+ 'revision','version',] as const satisfies ReadonlyArray<keyof UserConnectionRow>;++export const USER_CONNECTION_STORAGE_COLUMNS = [+ ...USER_CONNECTION_COLUMNS,+ 'membership',+ 'credential_payload',+ 'credential_expires_at',+] as const satisfies ReadonlyArray<keyof UserConnectionStorageRow>;++export const USER_CONNECTION_CREDENTIAL_TYPE = '_oauth_grant';diff --git a/fluxer_api/src/api/database/types/UserTypes.ts b/fluxer_api/src/api/database/types/UserTypes.tsindex e642923b4..4cc0619bb 100644--- a/fluxer_api/src/api/database/types/UserTypes.ts+++ b/fluxer_api/src/api/database/types/UserTypes.ts@@ -66,6 +66,7 @@ export interface UserRow {pending_bulk_message_deletion_channel_count: Nullish<number>;pending_bulk_message_deletion_message_count: Nullish<number>;pending_deletion_at: Nullish<Date>;+ deletion_started_at?: Nullish<Date>;deletion_reason_code: Nullish<number>;deletion_public_reason: Nullish<string>;deletion_audit_log_reason: Nullish<string>;@@ -129,6 +130,7 @@ export const USER_COLUMNS = ['pending_bulk_message_deletion_channel_count','pending_bulk_message_deletion_message_count','pending_deletion_at',+ 'deletion_started_at','deletion_reason_code','deletion_public_reason','deletion_audit_log_reason',@@ -191,6 +193,7 @@ export const EMPTY_USER_ROW: UserRow = {pending_bulk_message_deletion_channel_count: null,pending_bulk_message_deletion_message_count: null,pending_deletion_at: null,+ deletion_started_at: null,deletion_reason_code: null,deletion_public_reason: null,deletion_audit_log_reason: null,@@ -391,9 +394,11 @@ export interface UserHarvestRow {user_id: UserID;harvest_id: bigint;requested_at: Date;+ attempt_id?: string | null;started_at: Nullish<Date>;completed_at: Nullish<Date>;failed_at: Nullish<Date>;+ terminal_failed_at?: Date | null;storage_key: Nullish<string>;file_size: Nullish<bigint>;progress_percent: number;@@ -406,9 +411,11 @@ export const USER_HARVEST_COLUMNS = ['user_id','harvest_id','requested_at',+ 'attempt_id','started_at','completed_at','failed_at',+ 'terminal_failed_at','storage_key','file_size','progress_percent',diff --git a/fluxer_api/src/api/download/DownloadService.ts b/fluxer_api/src/api/download/DownloadService.tsindex 8f6c02c1a..05a285bfb 100644--- a/fluxer_api/src/api/download/DownloadService.ts+++ b/fluxer_api/src/api/download/DownloadService.ts@@ -103,7 +103,7 @@ function desktopArtifactPrefix(params: {plat: DesktopPlatform;arch: DesktopArch;test?: boolean;-}): string | null {+}): string {return `${desktopBucketPrefix(params.test)}/${params.channel}/${params.plat}/${params.arch}`;}@@ -261,9 +261,6 @@ export class DownloadService {test?: boolean;}): Promise<string | null> {const prefix = desktopArtifactPrefix(params);- if (!prefix) {- return null;- }const manifestKey = `${prefix}/manifest.json`;const releasability = new Map<string, boolean>();try {@@ -305,7 +302,7 @@ export class DownloadService {test: params.test,});} catch (error) {- if (error instanceof S3ServiceException && (error.name === 'NoSuchKey' || error.name === 'NotFound')) {+ if (isStorageNotFoundError(error)) {return this.resolveLatestDesktopKeyFromObjects(params, releasability);}throw error;@@ -320,9 +317,6 @@ export class DownloadService {test?: boolean;}): Promise<VersionInfo | null> {const prefix = desktopArtifactPrefix(params);- if (!prefix) {- return null;- }const manifestKey = `${prefix}/manifest.json`;const releasability = new Map<string, boolean>();try {@@ -338,7 +332,7 @@ export class DownloadService {return result;}} catch (error) {- if (error instanceof S3ServiceException && (error.name === 'NoSuchKey' || error.name === 'NotFound')) {+ if (isStorageNotFoundError(error)) {return this.getLatestDesktopVersionFromObjects(params, releasability);}throw error;@@ -395,9 +389,6 @@ export class DownloadService {return null;}const prefix = desktopArtifactPrefix(params);- if (!prefix) {- return null;- }const s3Prefix = `${prefix}/`;for (const filename of filenames) {const key = `${s3Prefix}${filename}`;@@ -407,7 +398,7 @@ export class DownloadService {return key;}} catch (error) {- if (error instanceof S3ServiceException && (error.name === 'NoSuchKey' || error.name === 'NotFound')) {+ if (isStorageNotFoundError(error)) {continue;}throw error;@@ -454,9 +445,6 @@ export class DownloadService {return this.buildDesktopChecksumFile(key, filename, objectSha256);}const prefix = desktopArtifactPrefix(params);- if (!prefix) {- return null;- }const manifest = await this.readOptionalJsonObjectFromStorage(`${prefix}/manifest.json`);const versionInfo =isDesktopManifest(manifest) && manifest.version === params.version@@ -485,7 +473,7 @@ export class DownloadService {return candidateKey;}} catch (error) {- if (error instanceof S3ServiceException && (error.name === 'NoSuchKey' || error.name === 'NotFound')) {+ if (isStorageNotFoundError(error)) {continue;}throw error;@@ -784,11 +772,7 @@ export class DownloadService {arch: DesktopArch;test?: boolean;}): Promise<Array<ListedDesktopVersion>> {- const basePrefix = desktopArtifactPrefix(params);- if (!basePrefix) {- return [];- }- const prefix = `${basePrefix}/`;+ const prefix = `${desktopArtifactPrefix(params)}/`;try {const objects = await this.listDesktopArtifacts(prefix);const versionMap = new Map<string, ListedDesktopVersion>();@@ -828,7 +812,7 @@ export class DownloadService {}return Array.from(versionMap.values()).sort((left, right) => this.compareVersions(left.version, right.version));} catch (error) {- if (error instanceof S3ServiceException && (error.name === 'NoSuchKey' || error.name === 'NotFound')) {+ if (isStorageNotFoundError(error)) {return [];}throw error;@@ -1115,9 +1099,6 @@ export class DownloadService {test?: boolean;}): Promise<string | null> {const prefix = desktopArtifactPrefix(params);- if (!prefix) {- return null;- }const manifestKey = `${prefix}/manifest.json`;try {const manifest = await this.readJsonObjectFromStorage(manifestKey);@@ -1154,7 +1135,7 @@ export class DownloadService {test: params.test,});} catch (error) {- if (error instanceof S3ServiceException && (error.name === 'NoSuchKey' || error.name === 'NotFound')) {+ if (isStorageNotFoundError(error)) {return null;}throw error;@@ -1292,9 +1273,6 @@ export class DownloadService {filename: params.resolvedFilename,test: params.test,});- if (!key) {- return null;- }return this.readDesktopSha256ForArtifactKey(key);}@@ -1324,14 +1302,11 @@ export class DownloadService {test?: boolean;}): Promise<boolean> {const key = this.buildDesktopArtifactKey(params);- if (!key) {- return false;- }try {const metadata = await this.storageService.getObjectMetadata(Config.s3.buckets.downloads, key);return metadata != null;} catch (error) {- if (error instanceof S3ServiceException && (error.name === 'NoSuchKey' || error.name === 'NotFound')) {+ if (isStorageNotFoundError(error)) {return false;}throw error;@@ -1344,9 +1319,8 @@ export class DownloadService {arch: DesktopArch;filename: string;test?: boolean;- }): string | null {- const prefix = desktopArtifactPrefix(params);- return prefix ? `${prefix}/${params.filename}` : null;+ }): string {+ return `${desktopArtifactPrefix(params)}/${params.filename}`;}private filenameFromKey(key: string): string {diff --git a/fluxer_api/src/api/experiment/tests/ExperimentController.test.ts b/fluxer_api/src/api/experiment/tests/ExperimentController.test.tsindex c1bd29e8b..24cbd9b20 100644--- a/fluxer_api/src/api/experiment/tests/ExperimentController.test.ts+++ b/fluxer_api/src/api/experiment/tests/ExperimentController.test.ts@@ -146,7 +146,7 @@ describe('GET /experiments', () => {const etag = first.response.headers.get('etag');expect(etag).toMatch(/^"[0-9a-f]{64}"$/);expect(first.response.headers.get('cache-control')).toBe('private, no-cache');- expect(first.response.headers.get('vary')).toBe('Authorization');+ expect(first.response.headers.get('vary')).toBe('Authorization, Origin');const revalidated = await createBuilder<ExperimentAssignmentsResponse>(harness, account.token).get(ENDPOINT)@@ -156,6 +156,7 @@ describe('GET /experiments', () => {expect(revalidated.response.status).toBe(NOT_MODIFIED);expect(revalidated.json).toBeUndefined();expect(revalidated.response.headers.get('etag')).toBe(etag);+ expect(revalidated.response.headers.get('vary')).toBe('Authorization, Origin');});it('lets a cross-origin client send If-None-Match and read the etag back', async () => {diff --git a/fluxer_api/src/api/gif/NatsGifProvider.ts b/fluxer_api/src/api/gif/NatsGifProvider.tsindex 428f502c4..13fa18bb5 100644--- a/fluxer_api/src/api/gif/NatsGifProvider.ts+++ b/fluxer_api/src/api/gif/NatsGifProvider.ts@@ -13,12 +13,14 @@ import {NatsConnectionManager} from '@pkgs/nats/src/NatsConnectionManager';import {StringCodec} from 'nats';import {Config} from '../Config';import {Logger} from '../Logger';+import {readOptionalIntegerEnv, requireIntegerInRange} from '../utils/IntegerOptions';import {isJsonRecord, parseJsonUnknown} from '../utils/JsonBoundaryUtils';import type {GifProviderMeta, IGifProvider} from './IGifProvider';const GIF_SERVICE_SUBJECT = process.env.FLUXER_GIF_SERVICE_SUBJECT || 'svc.gifs';const DEFAULT_GIF_SERVICE_TIMEOUT_MS = 12_000;const DEFAULT_GIF_SERVICE_REGISTER_SHARE_TIMEOUT_MS = 3_000;+const MAX_REQUEST_TIMEOUT_MS = 2_147_483_647;const GIF_PROVIDER_META: GifProviderMeta = {name: 'klipy',displayName: 'Klipy',@@ -73,13 +75,6 @@ export function buildKlipyShareUrl(slug: string): string {return `${KLIPY_SHARE_ORIGIN}/gifs/${encodeURIComponent(trimmed)}`;}-function readPositiveIntegerEnv(name: string, fallback: number): number {- const value = process.env[name];- if (!value) return fallback;- const parsed = Number(value);- return Number.isInteger(parsed) && parsed > 0 ? parsed : fallback;-}-function readFailedMessage(value: unknown): string | null {if (!isJsonRecord(value)) return null;if (typeof value.error === 'string') return value.error;@@ -147,16 +142,18 @@ class NatsGifProvider implements IGifProvider {constructor(private readonly connectionManager: INatsConnectionManager,private readonly apiKeyResolver: GifApiKeyResolver,- private readonly requestTimeoutMs = readPositiveIntegerEnv(- 'FLUXER_GIF_SERVICE_TIMEOUT_MS',- DEFAULT_GIF_SERVICE_TIMEOUT_MS,- ),- private readonly registerShareTimeoutMs = readPositiveIntegerEnv(- 'FLUXER_GIF_SERVICE_REGISTER_SHARE_TIMEOUT_MS',- DEFAULT_GIF_SERVICE_REGISTER_SHARE_TIMEOUT_MS,- ),+ private readonly requestTimeoutMs = DEFAULT_GIF_SERVICE_TIMEOUT_MS,+ private readonly registerShareTimeoutMs = DEFAULT_GIF_SERVICE_REGISTER_SHARE_TIMEOUT_MS,private readonly subject = GIF_SERVICE_SUBJECT,- ) {}+ ) {+ requireIntegerInRange('FLUXER_GIF_SERVICE_TIMEOUT_MS', requestTimeoutMs, 1, MAX_REQUEST_TIMEOUT_MS);+ requireIntegerInRange(+ 'FLUXER_GIF_SERVICE_REGISTER_SHARE_TIMEOUT_MS',+ registerShareTimeoutMs,+ 1,+ MAX_REQUEST_TIMEOUT_MS,+ );+ }async isAvailable(): Promise<boolean> {return Boolean((await this.apiKeyResolver())?.trim());@@ -283,8 +280,14 @@ export function createNatsGifProvider(apiKeyResolver: GifApiKeyResolver): NatsGitoken: Config.nats.authToken || undefined,name: process.env.FLUXER_GIF_SERVICE_NATS_CLIENT_NAME || 'fluxer-api-gifs',});+ const provider = new NatsGifProvider(+ manager,+ apiKeyResolver,+ readOptionalIntegerEnv('FLUXER_GIF_SERVICE_TIMEOUT_MS'),+ readOptionalIntegerEnv('FLUXER_GIF_SERVICE_REGISTER_SHARE_TIMEOUT_MS'),+ );void manager.connect().catch((error) => {Logger.warn({error}, '[gif-service] Failed to establish NATS connection');});- return new NatsGifProvider(manager, apiKeyResolver);+ return provider;}diff --git a/fluxer_api/src/api/guild/services/data/GuildOperationsService.ts b/fluxer_api/src/api/guild/services/data/GuildOperationsService.tsindex 274bd04dc..173c3ca8e 100644--- a/fluxer_api/src/api/guild/services/data/GuildOperationsService.ts+++ b/fluxer_api/src/api/guild/services/data/GuildOperationsService.ts@@ -75,12 +75,27 @@ const DEFAULT_VOICE_CATEGORY_NAME = 'Voice Channels';const DEFAULT_TEXT_CHANNEL_NAME = 'general';const DEFAULT_VOICE_CHANNEL_NAME = 'General';-interface PreparedGuildAssets {- icon: PreparedAssetUpload | null;- banner: PreparedAssetUpload | null;- splash: PreparedAssetUpload | null;- embed_splash: PreparedAssetUpload | null;-}+const GUILD_IMAGE_FIELDS = [+ {field: 'icon', hash: 'icon_hash', dimensions: null, gate: null},+ {+ field: 'banner',+ hash: 'banner_hash',+ dimensions: {width: 'banner_width', height: 'banner_height'},+ gate: {feature: GuildFeatures.BANNER, error: ValidationErrorCodes.GUILD_BANNER_REQUIRES_FEATURE},+ },+ {+ field: 'splash',+ hash: 'splash_hash',+ dimensions: {width: 'splash_width', height: 'splash_height'},+ gate: {feature: GuildFeatures.INVITE_SPLASH, error: ValidationErrorCodes.INVITE_SPLASH_REQUIRES_FEATURE},+ },+ {+ field: 'embed_splash',+ hash: 'embed_splash_hash',+ dimensions: {width: 'embed_splash_width', height: 'embed_splash_height'},+ gate: {feature: GuildFeatures.INVITE_SPLASH, error: ValidationErrorCodes.EMBED_SPLASH_REQUIRES_FEATURE},+ },+] as const;interface TemplateGuildSettings {verificationLevel: number;@@ -451,130 +466,10 @@ export class GuildOperationsService {}const updatedFeatures = this.computeUpdatedFeatures(previousFeatures, data.features);const featuresChanged = !setsEqual(previousFeatures, updatedFeatures);- const preparedAssets: PreparedGuildAssets = {icon: null, banner: null, splash: null, embed_splash: null};const patch: Partial<GuildRow> = {};if (data.name !== undefined) {patch.name = data.name;}- if (data.icon !== undefined) {- preparedAssets.icon = await this.entityAssetService.prepareAssetUpload({- assetType: 'icon',- entityType: 'guild',- entityId: guildId,- previousHash: currentGuild.iconHash,- base64Image: data.icon,- errorPath: 'icon',- });- patch.icon_hash = preparedAssets.icon.newHash;- }- if (data.banner !== undefined) {- if (data.banner && !currentGuild.features.has(GuildFeatures.BANNER)) {- await this.rollbackPreparedAssets(preparedAssets);- throw InputValidationError.fromCode('banner', ValidationErrorCodes.GUILD_BANNER_REQUIRES_FEATURE);- }- if (data.banner === null) {- patch.banner_hash = null;- patch.banner_width = null;- patch.banner_height = null;- } else {- try {- preparedAssets.banner = await this.entityAssetService.prepareAssetUpload({- assetType: 'banner',- entityType: 'guild',- entityId: guildId,- previousHash: currentGuild.bannerHash,- base64Image: data.banner,- errorPath: 'banner',- });- if (preparedAssets.banner.isAnimated && !currentGuild.features.has(GuildFeatures.ANIMATED_BANNER)) {- await this.rollbackPreparedAssets(preparedAssets);- throw InputValidationError.fromCode('banner', ValidationErrorCodes.ANIMATED_GUILD_BANNER_REQUIRES_FEATURE);- }- patch.banner_hash = preparedAssets.banner.newHash;- patch.banner_height =- preparedAssets.banner.newHash === currentGuild.bannerHash && currentGuild.bannerHeight != null- ? currentGuild.bannerHeight- : (preparedAssets.banner.height ?? null);- patch.banner_width =- preparedAssets.banner.newHash === currentGuild.bannerHash && currentGuild.bannerWidth != null- ? currentGuild.bannerWidth- : (preparedAssets.banner.width ?? null);- } catch (error) {- await this.rollbackPreparedAssets(preparedAssets);- throw error;- }- }- }- if (data.splash !== undefined) {- if (data.splash && !currentGuild.features.has(GuildFeatures.INVITE_SPLASH)) {- await this.rollbackPreparedAssets(preparedAssets);- throw InputValidationError.fromCode('splash', ValidationErrorCodes.INVITE_SPLASH_REQUIRES_FEATURE);- }- if (data.splash === null) {- patch.splash_hash = null;- patch.splash_width = null;- patch.splash_height = null;- } else {- try {- preparedAssets.splash = await this.entityAssetService.prepareAssetUpload({- assetType: 'splash',- entityType: 'guild',- entityId: guildId,- previousHash: currentGuild.splashHash,- base64Image: data.splash,- errorPath: 'splash',- });- patch.splash_hash = preparedAssets.splash.newHash;- patch.splash_height =- preparedAssets.splash.newHash === currentGuild.splashHash && currentGuild.splashHeight != null- ? currentGuild.splashHeight- : (preparedAssets.splash.height ?? null);- patch.splash_width =- preparedAssets.splash.newHash === currentGuild.splashHash && currentGuild.splashWidth != null- ? currentGuild.splashWidth- : (preparedAssets.splash.width ?? null);- } catch (error) {- await this.rollbackPreparedAssets(preparedAssets);- throw error;- }- }- }- if (data.embed_splash !== undefined) {- if (data.embed_splash && !currentGuild.features.has(GuildFeatures.INVITE_SPLASH)) {- await this.rollbackPreparedAssets(preparedAssets);- throw InputValidationError.fromCode('embed_splash', ValidationErrorCodes.EMBED_SPLASH_REQUIRES_FEATURE);- }- if (data.embed_splash === null) {- patch.embed_splash_hash = null;- patch.embed_splash_width = null;- patch.embed_splash_height = null;- } else {- try {- preparedAssets.embed_splash = await this.entityAssetService.prepareAssetUpload({- assetType: 'embed_splash',- entityType: 'guild',- entityId: guildId,- previousHash: currentGuild.embedSplashHash,- base64Image: data.embed_splash,- errorPath: 'embed_splash',- });- patch.embed_splash_hash = preparedAssets.embed_splash.newHash;- patch.embed_splash_height =- preparedAssets.embed_splash.newHash === currentGuild.embedSplashHash &&- currentGuild.embedSplashHeight != null- ? currentGuild.embedSplashHeight- : (preparedAssets.embed_splash.height ?? null);- patch.embed_splash_width =- preparedAssets.embed_splash.newHash === currentGuild.embedSplashHash &&- currentGuild.embedSplashWidth != null- ? currentGuild.embedSplashWidth- : (preparedAssets.embed_splash.width ?? null);- } catch (error) {- await this.rollbackPreparedAssets(preparedAssets);- throw error;- }- }- }if (data.splash_card_alignment !== undefined) {patch.splash_card_alignment = data.splash_card_alignment;}@@ -663,14 +558,12 @@ export class GuildOperationsService {const cutoffDate = new Date(data.message_history_cutoff);const guildCreationTimestamp = extractTimestamp(guildId.toString());if (cutoffDate.getTime() < guildCreationTimestamp) {- await this.rollbackPreparedAssets(preparedAssets);throw InputValidationError.fromCode('message_history_cutoff',ValidationErrorCodes.MESSAGE_HISTORY_CUTOFF_BEFORE_GUILD_CREATION,);}if (cutoffDate.getTime() > Date.now()) {- await this.rollbackPreparedAssets(preparedAssets);throw InputValidationError.fromCode('message_history_cutoff',ValidationErrorCodes.MESSAGE_HISTORY_CUTOFF_IN_FUTURE,@@ -682,6 +575,7 @@ export class GuildOperationsService {if (featuresChanged) {patch.features = updatedFeatures;}+ const preparedAssets = await this.prepareGuildAssetUpdates(currentGuild, data, patch);let updatedGuild: Guild;if (Object.keys(patch).length === 0) {updatedGuild = currentGuild;@@ -689,13 +583,12 @@ export class GuildOperationsService {try {updatedGuild = await this.guildRepository.upsertPartial(guildId, patch, currentGuild.toRow());} catch (error) {- await this.rollbackPreparedAssets(preparedAssets);- Logger.error({error, guildId}, 'Guild update failed, rolled back asset uploads');+ Logger.error({error, guildId}, 'Guild update failed with unknown commit status; retaining uploaded assets');throw error;}}try {- await this.commitPreparedAssets(preparedAssets);+ await this.entityAssetService.commitAssetChanges(preparedAssets);} catch (error) {Logger.error({error, guildId}, 'Failed to commit asset changes after successful guild update');}@@ -730,12 +623,6 @@ export class GuildOperationsService {changes: auditLogChanges,});}- if (data.name !== undefined && currentGuild.name !== updatedGuild.name) {- }- if (data.icon !== undefined && currentGuild.iconHash !== updatedGuild.iconHash) {- }- if (data.banner !== undefined && currentGuild.bannerHash !== updatedGuild.bannerHash) {- }return {guild: mapGuildToGuildResponse(updatedGuild),previousFeatures,@@ -769,40 +656,48 @@ export class GuildOperationsService {return next;}- private async rollbackPreparedAssets(assets: PreparedGuildAssets): Promise<void> {- const rollbackPromises: Array<Promise<void>> = [];- if (assets.icon) {- rollbackPromises.push(this.entityAssetService.rollbackAssetUpload(assets.icon));- }- if (assets.banner) {- rollbackPromises.push(this.entityAssetService.rollbackAssetUpload(assets.banner));- }- if (assets.splash) {- rollbackPromises.push(this.entityAssetService.rollbackAssetUpload(assets.splash));- }- if (assets.embed_splash) {- rollbackPromises.push(this.entityAssetService.rollbackAssetUpload(assets.embed_splash));- }- await Promise.all(rollbackPromises);- }-- private async commitPreparedAssets(assets: PreparedGuildAssets): Promise<void> {- const commitPromises: Array<Promise<void>> = [];- if (assets.icon) {- commitPromises.push(this.entityAssetService.commitAssetChange({prepared: assets.icon, deferDeletion: true}));- }- if (assets.banner) {- commitPromises.push(this.entityAssetService.commitAssetChange({prepared: assets.banner, deferDeletion: true}));- }- if (assets.splash) {- commitPromises.push(this.entityAssetService.commitAssetChange({prepared: assets.splash, deferDeletion: true}));- }- if (assets.embed_splash) {- commitPromises.push(- this.entityAssetService.commitAssetChange({prepared: assets.embed_splash, deferDeletion: true}),- );+ private async prepareGuildAssetUpdates(+ guild: Guild,+ data: GuildUpdateRequest,+ patch: Partial<GuildRow>,+ ): Promise<Array<PreparedAssetUpload>> {+ const previous = guild.toRow();+ const preparedAssets: Array<PreparedAssetUpload> = [];+ try {+ for (const {field, hash, dimensions, gate} of GUILD_IMAGE_FIELDS) {+ const image = data[field];+ if (image === undefined) continue;+ if (image && gate && !guild.features.has(gate.feature)) {+ throw InputValidationError.fromCode(field, gate.error);+ }+ const prepared = await this.entityAssetService.prepareAssetUpload({+ assetType: field,+ entityType: 'guild',+ entityId: guild.id,+ previousHash: previous[hash],+ base64Image: image,+ errorPath: field,+ });+ preparedAssets.push(prepared);+ if (field === 'banner' && prepared.isAnimated && !guild.features.has(GuildFeatures.ANIMATED_BANNER)) {+ throw InputValidationError.fromCode(field, ValidationErrorCodes.ANIMATED_GUILD_BANNER_REQUIRES_FEATURE);+ }+ patch[hash] = prepared.newHash;+ if (!dimensions) continue;+ if (image === null) {+ patch[dimensions.width] = null;+ patch[dimensions.height] = null;+ continue;+ }+ const sameHash = prepared.newHash === previous[hash];+ patch[dimensions.width] = (sameHash ? previous[dimensions.width] : null) ?? prepared.width ?? null;+ patch[dimensions.height] = (sameHash ? previous[dimensions.height] : null) ?? prepared.height ?? null;+ }+ return preparedAssets;+ } catch (error) {+ await Promise.all(preparedAssets.map((prepared) => this.entityAssetService.rollbackAssetUpload(prepared)));+ throw error;}- await Promise.all(commitPromises);}async deleteGuild(diff --git a/fluxer_api/src/api/guild/services/member/GuildMemberOperationsService.ts b/fluxer_api/src/api/guild/services/member/GuildMemberOperationsService.tsindex 5451db4ee..acbd1fe43 100644--- a/fluxer_api/src/api/guild/services/member/GuildMemberOperationsService.ts+++ b/fluxer_api/src/api/guild/services/member/GuildMemberOperationsService.ts@@ -359,10 +359,13 @@ export class GuildMemberOperationsService {try {updatedMember = await this.guildRepository.upsertMember(updatedMemberData);} catch (error) {- await this.rollbackPreparedAssets(preparedAssets);+ Logger.error(+ {error, guildId, userId: targetId},+ 'Guild member update failed with unknown commit status; retaining uploaded assets',+ );throw error;}- await this.commitPreparedAssets(preparedAssets);+ await this.entityAssetService.commitAssetChanges([preparedAssets.avatar, preparedAssets.banner]);if (shouldRemoveTemporaryStatus) {await this.gatewayService.removeTemporaryGuild({userId: targetId, guildId});}@@ -1034,17 +1037,6 @@ export class GuildMemberOperationsService {await Promise.all(rollbackPromises);}- private async commitPreparedAssets(preparedAssets: PreparedMemberAssets): Promise<void> {- const commitPromises: Array<Promise<void>> = [];- if (preparedAssets.avatar) {- commitPromises.push(this.entityAssetService.commitAssetChange({prepared: preparedAssets.avatar}));- }- if (preparedAssets.banner) {- commitPromises.push(this.entityAssetService.commitAssetChange({prepared: preparedAssets.banner}));- }- await Promise.all(commitPromises);- }-private async snapshotMembershipMetadata(member: GuildMember): Promise<void> {const existingMetadata = await this.guildRepository.getMembershipMetadata(member.guildId, member.userId);await this.guildRepository.upsertMembershipMetadata(diff --git a/fluxer_api/src/api/guild/services/member/GuildMemberSearchIndexService.ts b/fluxer_api/src/api/guild/services/member/GuildMemberSearchIndexService.tsindex 572c2f8b5..0de89d84a 100644--- a/fluxer_api/src/api/guild/services/member/GuildMemberSearchIndexService.ts+++ b/fluxer_api/src/api/guild/services/member/GuildMemberSearchIndexService.ts@@ -6,29 +6,43 @@ import type {GuildMember} from '../../../models/GuildMember';import type {User} from '../../../models/User';import {getGuildMemberSearchService} from '../../../SearchFactory';import type {IGuildMemberSearchService} from '../../../search/IGuildMemberSearchService';+import type {IGuildRepositoryAggregate} from '../../repositories/IGuildRepositoryAggregate';interface GuildMemberSearchIndexOptions {includeDefault?: boolean;}-function getGuildMemberIndexServices(options: GuildMemberSearchIndexOptions = {}): Array<IGuildMemberSearchService> {- const services: Array<IGuildMemberSearchService> = [];+function getGuildMemberIndexService(options: GuildMemberSearchIndexOptions = {}): IGuildMemberSearchService | null {const includeDefault = options.includeDefault ?? true;- const defaultService = getGuildMemberSearchService();- if (includeDefault && defaultService) {- services.push(defaultService);- }- return services;+ const service = getGuildMemberSearchService();+ return includeDefault ? service : null;}export class GuildMemberSearchIndexService {+ async updateUserMembers(+ user: User,+ guildIds: Array<GuildID>,+ guildRepository: IGuildRepositoryAggregate,+ ): Promise<void> {+ if (guildIds.length === 0) return;+ const guilds = await guildRepository.listGuilds(guildIds);+ const indexedGuilds = guilds.filter((guild) => guild.membersIndexedAt != null);+ if (indexedGuilds.length === 0) return;+ const members = await Promise.all(indexedGuilds.map((guild) => guildRepository.getMember(guild.id, user.id)));+ for (const member of members) {+ if (member) {+ void this.updateMember(member, user);+ }+ }+ }+async indexMember(member: GuildMember, user: User, options?: GuildMemberSearchIndexOptions): Promise<void> {try {- const searchServices = getGuildMemberIndexServices(options);- if (searchServices.length === 0) {+ const searchService = getGuildMemberIndexService(options);+ if (!searchService) {return;}- await Promise.all(searchServices.map((searchService) => searchService.indexMember(member, user)));+ await searchService.indexMember(member, user);} catch (error) {Logger.error({@@ -43,11 +57,11 @@ export class GuildMemberSearchIndexService {async updateMember(member: GuildMember, user: User, options?: GuildMemberSearchIndexOptions): Promise<void> {try {- const searchServices = getGuildMemberIndexServices(options);- if (searchServices.length === 0) {+ const searchService = getGuildMemberIndexService(options);+ if (!searchService) {return;}- await Promise.all(searchServices.map((searchService) => searchService.updateMember(member, user)));+ await searchService.updateMember(member, user);} catch (error) {Logger.error({@@ -62,11 +76,11 @@ export class GuildMemberSearchIndexService {async deleteMember(guildId: GuildID, userId: UserID, options?: GuildMemberSearchIndexOptions): Promise<void> {try {- const searchServices = getGuildMemberIndexServices(options);- if (searchServices.length === 0) {+ const searchService = getGuildMemberIndexService(options);+ if (!searchService) {return;}- await Promise.all(searchServices.map((searchService) => searchService.deleteMember(guildId, userId)));+ await searchService.deleteMember(guildId, userId);} catch (error) {Logger.error({diff --git a/fluxer_api/src/api/infrastructure/AssetDeletionQueue.ts b/fluxer_api/src/api/infrastructure/AssetDeletionQueue.tsindex cebc106be..0532c0ff4 100644--- a/fluxer_api/src/api/infrastructure/AssetDeletionQueue.ts+++ b/fluxer_api/src/api/infrastructure/AssetDeletionQueue.ts@@ -3,6 +3,7 @@import type {IKVProvider} from '@pkgs/kv_client/src/IKVProvider';import {Logger} from '../Logger';import {isJsonRecord, parseJsonWithGuard} from '../utils/JsonBoundaryUtils';+import {isValidTimestamp} from '../utils/TimestampUtils';import type {IAssetDeletionQueue, QueuedAssetDeletion, QueuedAssetReference} from './IAssetDeletionQueue';const QUEUE_KEY = 'asset:deletion:queue';@@ -30,8 +31,12 @@ function isQueuedAssetDeletion(value: unknown): value is QueuedAssetDeletion {(typeof value.cdnUrl === 'string' || value.cdnUrl === null) &&typeof value.reason === 'string' &&(value.staleReference === undefined || isQueuedAssetReference(value.staleReference)) &&- (value.queuedAt === undefined || typeof value.queuedAt === 'number') &&- (value.retryCount === undefined || typeof value.retryCount === 'number')+ (value.queuedAt === undefined || isValidTimestamp(value.queuedAt)) &&+ (value.retryCount === undefined ||+ (typeof value.retryCount === 'number' &&+ Number.isInteger(value.retryCount) &&+ value.retryCount >= 0 &&+ value.retryCount <= MAX_RETRIES)));}@@ -54,20 +59,11 @@ export class AssetDeletionQueue implements IAssetDeletionQueue {}async queueCdnPurge(cdnUrl: string): Promise<void> {- const item: QueuedAssetDeletion = {+ await this.queueDeletion({s3Key: '',cdnUrl,reason: 'cdn_purge_only',- queuedAt: Date.now(),- retryCount: 0,- };- try {- await this.kvClient.rpush(QUEUE_KEY, JSON.stringify(item));- Logger.debug({cdnUrl}, 'Queued CDN URL for purge');- } catch (error) {- Logger.error({error, cdnUrl}, 'Failed to queue CDN URL for purge');- throw error;- }+ });}async getBatch(count: number): Promise<Array<QueuedAssetDeletion>> {@@ -76,9 +72,6 @@ export class AssetDeletionQueue implements IAssetDeletionQueue {}try {const items = await this.kvClient.lpop(QUEUE_KEY, count);- if (items.length === 0) {- return [];- }const parsed: Array<QueuedAssetDeletion> = [];for (const item of items) {const queuedItem = parseJsonWithGuard(item, isQueuedAssetDeletion);diff --git a/fluxer_api/src/api/infrastructure/BunnyPurgeQueue.ts b/fluxer_api/src/api/infrastructure/BunnyPurgeQueue.tsindex 0115ecfd6..228191ae7 100644--- a/fluxer_api/src/api/infrastructure/BunnyPurgeQueue.ts+++ b/fluxer_api/src/api/infrastructure/BunnyPurgeQueue.ts@@ -1,6 +1,6 @@// SPDX-License-Identifier: AGPL-3.0-or-later-import type {IKVProvider} from '@pkgs/kv_client/src/IKVProvider';+import type {IKVProvider, KVPurgeBatchResult} from '@pkgs/kv_client/src/IKVProvider';import {Logger} from '../Logger';export interface IPurgeQueue {@@ -59,7 +59,10 @@ export class BunnyPurgeQueue implements IPurgeQueue {await Promise.all(ops);Logger.debug({exact: exactUrls.length, prefix: prefixUrls.length}, 'Added URLs to CDN purge queue');} catch (error) {- Logger.error({error, urls}, 'Failed to add URLs to CDN purge queue');+ Logger.error(+ {error, exact: exactUrls.length, prefix: prefixUrls.length},+ 'Failed to add URLs to CDN purge queue',+ );throw error;}}@@ -87,10 +90,7 @@ export class BunnyPurgeQueue implements IPurgeQueue {}}- async dequeueExactBatch(maxItems: number): Promise<{- urls: Array<string>;- tokensConsumed: number;- }> {+ async dequeueExactBatch(maxItems: number): Promise<KVPurgeBatchResult> {return this.kvClient.dequeuePurgeBatch(EXACT_QUEUE_KEY,EXACT_BUCKET_KEY,@@ -101,10 +101,7 @@ export class BunnyPurgeQueue implements IPurgeQueue {);}- async dequeuePrefixBatch(maxItems: number): Promise<{- urls: Array<string>;- tokensConsumed: number;- }> {+ async dequeuePrefixBatch(maxItems: number): Promise<KVPurgeBatchResult> {return this.kvClient.dequeuePurgeBatch(PREFIX_QUEUE_KEY,PREFIX_BUCKET_KEY,diff --git a/fluxer_api/src/api/infrastructure/DeletionQueueMember.ts b/fluxer_api/src/api/infrastructure/DeletionQueueMember.tsnew file mode 100644index 000000000..619be3eb3--- /dev/null+++ b/fluxer_api/src/api/infrastructure/DeletionQueueMember.ts@@ -0,0 +1,34 @@+import {SnowflakeType} from '@fluxer/schema/src/primitives/SchemaPrimitives';++const MAX_USER_ID_LENGTH = 19;+const MAX_PAYLOAD_LENGTH = 17;+const MAX_MEMBER_LENGTH = MAX_USER_ID_LENGTH + 1 + MAX_PAYLOAD_LENGTH;++interface DeletionQueueMember {+ userId: bigint;+ payload: string;+}++export function parseDeletionQueueUserId(value: string): bigint {+ if (value.length === 0 || value.length > MAX_USER_ID_LENGTH || /\D/.test(value)) {+ throw new TypeError('Deletion queue user ID must be a canonical snowflake');+ }+ const parsed = SnowflakeType.safeParse(value);+ if (!parsed.success) throw new TypeError('Deletion queue user ID must be a canonical snowflake');+ return parsed.data;+}++export function parseDeletionQueueMember(value: string): DeletionQueueMember {+ if (value.length > MAX_MEMBER_LENGTH) throw new TypeError('Deletion queue member exceeds the maximum length');+ const separator = value.indexOf('|');+ if (separator <= 0 || separator === value.length - 1 || value.indexOf('|', separator + 1) !== -1) {+ throw new TypeError('Deletion queue member must contain exactly two nonempty fields');+ }+ if (value.length - separator - 1 > MAX_PAYLOAD_LENGTH) {+ throw new TypeError('Deletion queue payload exceeds the maximum length');+ }+ return {+ userId: parseDeletionQueueUserId(value.slice(0, separator)),+ payload: value.slice(separator + 1),+ };+}diff --git a/fluxer_api/src/api/infrastructure/EntityAssetService.ts b/fluxer_api/src/api/infrastructure/EntityAssetService.tsindex 305d81f4c..e67f0f593 100644--- a/fluxer_api/src/api/infrastructure/EntityAssetService.ts+++ b/fluxer_api/src/api/infrastructure/EntityAssetService.ts@@ -1,6 +1,7 @@// SPDX-License-Identifier: AGPL-3.0-or-laterimport crypto from 'node:crypto';+import {setTimeout as delay} from 'node:timers/promises';import {type AssetKind,formatAssetUploadExtensions,@@ -17,6 +18,7 @@ import {Config} from '../Config';import {Logger} from '../Logger';import type {LimitConfigService} from '../limits/LimitConfigService';import {createLimitMatchContext} from '../limits/LimitMatchContextBuilder';+import {awaitAll} from '../utils/ConcurrencyUtils';import type {IAssetDeletionQueue, QueuedAssetReference} from './IAssetDeletionQueue';import type {IMediaService, MediaProxyMetadataResponse} from './IMediaService';import type {IStorageService} from './IStorageService';@@ -71,16 +73,9 @@ interface PrepareAssetUploadOptions {errorPath: string;}-interface CommitAssetChangeOptions {- prepared: PreparedAssetUpload;- deferDeletion?: boolean;-}-type LimitConfigSnapshotProvider = Pick<LimitConfigService, 'getConfigSnapshot'>;export class EntityAssetService {- private activeTimeouts: Set<NodeJS.Timeout> = new Set();-constructor(private readonly storageService: IStorageService,private readonly mediaService: IMediaService,@@ -108,7 +103,7 @@ export class EntityAssetService {async prepareAssetUpload(options: PrepareAssetUploadOptions): Promise<PreparedAssetUpload> {const {assetType, entityType, entityId, guildId, previousHash, base64Image, errorPath} = options;const s3KeyBase = this.buildS3KeyBase(assetType, entityType, entityId, guildId);- const cdnUrlBase = this.buildCdnUrlBase(assetType, entityType, entityId, guildId);+ const cdnUrlBase = `${Config.endpoints.media}/${s3KeyBase}`;const previousS3Key = previousHash ? `${s3KeyBase}/${this.stripAnimationPrefix(previousHash)}` : null;const previousCdnUrl = previousHash ? `${cdnUrlBase}/${previousHash}` : null;const previousReference = previousHash@@ -129,35 +124,36 @@ export class EntityAssetService {contentType: null,};}- const {imageBuffer, format, height, width, contentType, animated} = await this.validateAndProcessImage(- base64Image,- errorPath,- assetType,- );+ const {+ imageBuffer,+ format,+ height,+ width,+ contentType,+ animated: isAnimated,+ } = await this.validateAndProcessImage(base64Image, errorPath, assetType);const imageHash = crypto.createHash('md5').update(Buffer.from(imageBuffer)).digest('hex');const imageHashShort = imageHash.slice(0, 8);- const newHash = animated ? `a_${imageHashShort}` : imageHashShort;- const isAnimated = animated;+ const newHash = isAnimated ? `a_${imageHashShort}` : imageHashShort;const newS3Key = `${s3KeyBase}/${imageHashShort}`;const newCdnUrl = `${cdnUrlBase}/${newHash}.${format}`;- if (newHash === previousHash) {- return {- newHash,- previousHash,- isAnimated,- newS3Key,- previousS3Key,- newCdnUrl,- previousCdnUrl,- previousReference,- height,- width,- _uploaded: false,- imageBuffer,- format,- contentType,- };- }+ const prepared: PreparedAssetUpload = {+ newHash,+ previousHash,+ isAnimated,+ newS3Key,+ previousS3Key,+ newCdnUrl,+ previousCdnUrl,+ previousReference,+ height,+ width,+ _uploaded: false,+ imageBuffer,+ format,+ contentType,+ };+ if (newHash === previousHash) return prepared;let uploadBuffer = imageBuffer;try {const isJpeg = format === 'jpg' || format === 'jpeg';@@ -176,47 +172,31 @@ export class EntityAssetService {);throw InputValidationError.fromCode(errorPath, ValidationErrorCodes.FAILED_TO_UPLOAD_IMAGE);}- const prepared: PreparedAssetUpload = {- newHash,- previousHash,- isAnimated,- newS3Key,- previousS3Key,- newCdnUrl,- previousCdnUrl,- previousReference,- height,- width,- _uploaded: true,- imageBuffer,- format,- contentType,- };+ prepared._uploaded = true;return prepared;}- async commitAssetChange(options: CommitAssetChangeOptions): Promise<void> {- const {prepared, deferDeletion = true} = options;- if (!prepared.previousHash || !prepared.previousS3Key) {+ async commitAssetChange(prepared: PreparedAssetUpload): Promise<void> {+ if (!prepared.previousHash || !prepared.previousS3Key || prepared.newHash === prepared.previousHash) {return;}- if (prepared.newHash === prepared.previousHash) {- return;- }- if (deferDeletion) {- await this.assetDeletionQueue.queueDeletion({- s3Key: prepared.previousS3Key,- cdnUrl: prepared.previousCdnUrl,- reason: 'asset_replaced',- staleReference: prepared.previousReference ?? undefined,- });- Logger.debug(- {previousS3Key: prepared.previousS3Key, previousCdnUrl: prepared.previousCdnUrl},- 'Queued old asset for deferred deletion',- );- } else {- await this.deleteAssetImmediately(prepared.previousS3Key, prepared.previousCdnUrl);- }+ await this.assetDeletionQueue.queueDeletion({+ s3Key: prepared.previousS3Key,+ cdnUrl: prepared.previousCdnUrl,+ reason: 'asset_replaced',+ staleReference: prepared.previousReference ?? undefined,+ });+ Logger.debug(+ {previousS3Key: prepared.previousS3Key, previousCdnUrl: prepared.previousCdnUrl},+ 'Queued old asset for deferred deletion',+ );+ }++ async commitAssetChanges(preparedAssets: ReadonlyArray<PreparedAssetUpload | null>): Promise<void> {+ await awaitAll(+ preparedAssets.filter((prepared) => prepared !== null).map(async (prepared) => this.commitAssetChange(prepared)),+ 'Failed to commit asset changes',+ );}async rollbackAssetUpload(prepared: PreparedAssetUpload): Promise<void> {@@ -231,16 +211,6 @@ export class EntityAssetService {}}- async verifyAssetExists(assetType: AssetType, entityType: EntityType, s3Key: string): Promise<boolean> {- try {- const metadata = await this.storageService.getObjectMetadata(Config.s3.buckets.cdn, s3Key);- return metadata !== null;- } catch (error) {- Logger.error({error, s3Key, assetType, entityType}, 'Error checking asset existence');- return false;- }- }-private resolveAvatarSizeLimit(): number {const ctx = createLimitMatchContext({user: null});const resolved = resolveLimit(this.limitConfigService.getConfigSnapshot(), ctx, 'avatar_max_size');@@ -250,7 +220,7 @@ export class EntityAssetService {return Math.floor(resolved);}- async verifyAssetExistsWithRetry(+ private async verifyAssetExistsWithRetry(assetType: AssetType,entityType: EntityType,s3Key: string,@@ -270,71 +240,13 @@ export class EntityAssetService {Logger.warn({error, s3Key, assetType, entityType, attempt}, 'Asset verification attempt failed');}if (attempt < maxRetries) {- await new Promise<void>((resolve) => {- const timeout = setTimeout(() => {- this.activeTimeouts.delete(timeout);- resolve();- }, delayMs * attempt);- this.activeTimeouts.add(timeout);- timeout.unref?.();- });+ await delay(delayMs * attempt, undefined, {ref: false});}}Logger.error({s3Key, assetType, entityType, maxRetries}, 'Asset verification failed after all retries');return false;}- public cleanup(): void {- for (const timeout of this.activeTimeouts) {- clearTimeout(timeout);- }- this.activeTimeouts.clear();- }-- public getActiveTimeoutCount(): number {- return this.activeTimeouts.size;- }-- getS3KeyForHash(- assetType: AssetType,- entityType: EntityType,- entityId: bigint,- hash: string,- guildId?: bigint,- ): string {- const s3KeyBase = this.buildS3KeyBase(assetType, entityType, entityId, guildId);- return `${s3KeyBase}/${this.stripAnimationPrefix(hash)}`;- }-- getCdnUrlForHash(- assetType: AssetType,- entityType: EntityType,- entityId: bigint,- hash: string,- guildId?: bigint,- ): string {- const cdnUrlBase = this.buildCdnUrlBase(assetType, entityType, entityId, guildId);- return `${cdnUrlBase}/${hash}`;- }-- async queueAssetDeletion(- assetType: AssetType,- entityType: EntityType,- entityId: bigint,- hash: string,- guildId?: bigint,- reason: string = 'manual_clear',- ): Promise<void> {- const s3Key = this.getS3KeyForHash(assetType, entityType, entityId, hash, guildId);- const cdnUrl = this.getCdnUrlForHash(assetType, entityType, entityId, hash, guildId);- await this.assetDeletionQueue.queueDeletion({- s3Key,- cdnUrl,- reason,- staleReference: this.buildQueuedAssetReference(assetType, entityType, entityId, hash, guildId),- });- }-private buildQueuedAssetReference(assetType: AssetType,entityType: EntityType,@@ -366,17 +278,6 @@ export class EntityAssetService {return `${prefix}/${entityId}`;}- private buildCdnUrlBase(assetType: AssetType, entityType: EntityType, entityId: bigint, guildId?: bigint): string {- const prefix = ASSET_TYPE_TO_PREFIX[assetType];- if (entityType === 'guild_member') {- if (!guildId) {- throw new Error('guildId is required for guild_member assets');- }- return `${Config.endpoints.media}/guilds/${guildId}/users/${entityId}/${prefix}`;- }- return `${Config.endpoints.media}/${prefix}/${entityId}`;- }-private async validateAndProcessImage(base64Image: string,errorPath: string,@@ -472,16 +373,4 @@ export class EntityAssetService {throw new Error(`Failed to upload asset to S3: ${error instanceof Error ? error.message : 'Unknown error'}`);}}-- private async deleteAssetImmediately(s3Key: string, cdnUrl: string | null): Promise<void> {- try {- await this.storageService.deleteObject(Config.s3.buckets.cdn, s3Key);- Logger.debug({s3Key}, 'Deleted asset from S3');- } catch (error) {- Logger.error({error, s3Key}, 'Failed to delete asset from S3');- }- if (cdnUrl) {- await this.assetDeletionQueue.queueCdnPurge(cdnUrl);- }- }}diff --git a/fluxer_api/src/api/infrastructure/ISnowflakeService.ts b/fluxer_api/src/api/infrastructure/ISnowflakeService.tsindex 7628755b4..f74c7f4f5 100644--- a/fluxer_api/src/api/infrastructure/ISnowflakeService.ts+++ b/fluxer_api/src/api/infrastructure/ISnowflakeService.ts@@ -2,7 +2,6 @@export interface ISnowflakeService {initialize(): Promise<void>;- reinitialize(): Promise<void>;shutdown(): Promise<void>;generate(): Promise<bigint>;generateForChannel(channelId: string | bigint): Promise<bigint>;diff --git a/fluxer_api/src/api/infrastructure/KVAccountDeletionQueueService.ts b/fluxer_api/src/api/infrastructure/KVAccountDeletionQueueService.tsindex 5945c500b..ee0af983c 100644--- a/fluxer_api/src/api/infrastructure/KVAccountDeletionQueueService.ts+++ b/fluxer_api/src/api/infrastructure/KVAccountDeletionQueueService.ts@@ -1,5 +1,6 @@// SPDX-License-Identifier: AGPL-3.0-or-later+import {Int32Type} from '@fluxer/schema/src/primitives/SchemaPrimitives';import {generateLockToken} from '@pkgs/cache/src/CacheLockValidation';import type {IKVProvider} from '@pkgs/kv_client/src/IKVProvider';import {ms, seconds} from 'itty-time';@@ -7,6 +8,8 @@ import type {UserID} from '../BrandedTypes';import {Logger} from '../Logger';import type {UserRepository} from '../user/repositories/UserRepository';import {isPendingDeletionBlocked, resolvePendingDeletionReasonCode} from '../user/services/PendingDeletionCoordinator';+import {getValidTimestamp, parseStoredTimestamp} from '../utils/TimestampUtils';+import {parseDeletionQueueMember, parseDeletionQueueUserId} from './DeletionQueueMember';interface QueuedDeletion {userId: bigint;@@ -25,32 +28,44 @@ export class KVAccountDeletionQueueService {) {}private serializeQueueItem(item: QueuedDeletion): string {- return `${item.userId}|${item.deletionReasonCode}`;+ const userId = parseDeletionQueueUserId(item.userId.toString());+ const reasonCode = this.validateReasonCode(item.deletionReasonCode);+ return `${userId}|${reasonCode}`;}private deserializeQueueItem(value: string): QueuedDeletion {- const parts = value.split('|');+ const {userId, payload} = parseDeletionQueueMember(value);+ if (payload.length > 10 || /\D/.test(payload)) {+ throw new TypeError('Deletion queue reason code must be a decimal nonnegative 32-bit integer');+ }return {- userId: BigInt(parts[0]),- deletionReasonCode: parseInt(parts[1], 10),+ userId,+ deletionReasonCode: this.validateReasonCode(Number(payload)),};}+ private validateReasonCode(value: number): number {+ const parsed = Int32Type.safeParse(value);+ if (!parsed.success) {+ throw new TypeError('Deletion queue reason code must be a decimal nonnegative 32-bit integer');+ }+ return parsed.data;+ }+async needsRebuild(): Promise<boolean> {try {- const versionExists = await this.kvClient.exists(STATE_VERSION_KEY);- if (!versionExists) {+ const stateVersion = parseStoredTimestamp(+ await this.kvClient.get(STATE_VERSION_KEY),+ 'Deletion queue state version',+ );+ if (stateVersion === null) {Logger.debug('Deletion queue needs rebuild: no state version');return true;}- const stateVersionStr = await this.kvClient.get(STATE_VERSION_KEY);- if (stateVersionStr) {- const stateVersion = parseInt(stateVersionStr, 10);- const ageMs = Date.now() - stateVersion;- if (ageMs > ms('1 day')) {- Logger.debug({ageMs, maxAgeMs: ms('1 day')}, 'Deletion queue needs rebuild: state too old');- return true;- }+ const ageMs = Date.now() - stateVersion;+ if (ageMs > ms('1 day')) {+ Logger.debug({ageMs, maxAgeMs: ms('1 day')}, 'Deletion queue needs rebuild: state too old');+ return true;}return false;} catch (error) {@@ -68,39 +83,30 @@ export class KVAccountDeletionQueueService {let totalProcessed = 0;let totalQueued = 0;const batchSize = 1000;- while (true) {+ do {const page = await this.userRepository.scanAllUsersPage(batchSize, pageState);+ pageState = page.pageState;const users = page.users;- if (users.length === 0) {- break;- }- let batchQueued = 0;for (const user of users) {- if (user.pendingDeletionAt && !isPendingDeletionBlocked(user)) {- const queueItem: QueuedDeletion = {- userId: user.id,- deletionReasonCode: resolvePendingDeletionReasonCode(user, 0),- };- const score = user.pendingDeletionAt.getTime();- const value = this.serializeQueueItem(queueItem);- const secondaryKey = this.getSecondaryKey(user.id);- await this.kvClient.scheduleBulkDeletion(QUEUE_KEY, secondaryKey, score, value);- batchQueued++;- }+ if (!user.pendingDeletionAt || (!user.deletionStartedAt && isPendingDeletionBlocked(user))) continue;+ const queueItem: QueuedDeletion = {+ userId: user.id,+ deletionReasonCode: resolvePendingDeletionReasonCode(user, 0),+ };+ const score = getValidTimestamp(user.pendingDeletionAt, `Pending deletion timestamp for user ${user.id}`);+ const value = this.serializeQueueItem(queueItem);+ const secondaryKey = this.getSecondaryKey(user.id);+ await this.kvClient.scheduleBulkDeletion(QUEUE_KEY, secondaryKey, score, value);+ totalQueued++;}- totalQueued += batchQueued;totalProcessed += users.length;- pageState = page.pageState;if (lockToken !== null) {await this.renewRebuildLock(lockToken);}- if (totalProcessed % 10000 === 0) {+ if (users.length > 0 && totalProcessed % 10000 === 0) {Logger.debug({totalProcessed, totalQueued}, 'Deletion queue rebuild progress');}- if (!pageState) {- break;- }- }+ } while (pageState);await this.kvClient.set(STATE_VERSION_KEY, Date.now().toString());Logger.info({totalProcessed, totalQueued}, 'Deletion queue rebuild completed');} catch (error) {@@ -115,7 +121,7 @@ export class KVAccountDeletionQueueService {userId,deletionReasonCode: reasonCode,};- const score = pendingAt.getTime();+ const score = getValidTimestamp(pendingAt, `Pending deletion timestamp for user ${userId}`);const value = this.serializeQueueItem(queueItem);const secondaryKey = this.getSecondaryKey(userId);await this.kvClient.removeBulkDeletion(QUEUE_KEY, secondaryKey);@@ -147,12 +153,23 @@ export class KVAccountDeletionQueueService {try {const results = await this.kvClient.zrangebyscore(QUEUE_KEY, '-inf', nowMs, 'LIMIT', 0, limit);const deletions: Array<QueuedDeletion> = [];+ const unparseable: Array<string> = [];for (const result of results) {try {- const deletion = this.deserializeQueueItem(result);- deletions.push(deletion);- } catch (parseError) {- Logger.error({error: parseError, result}, 'Failed to parse queued deletion');+ deletions.push(this.deserializeQueueItem(result));+ } catch {+ unparseable.push(result);+ }+ }+ if (unparseable.length > 0) {+ Logger.error({unparseableCount: unparseable.length}, 'Dropped unparseable deletion queue members');+ try {+ await this.kvClient.zrem(QUEUE_KEY, ...unparseable);+ } catch (error) {+ Logger.error(+ {error, unparseableCount: unparseable.length},+ 'Failed to remove unparseable deletion queue members',+ );}}return deletions;@@ -212,8 +229,7 @@ export class KVAccountDeletionQueueService {async getStateVersion(): Promise<number | null> {try {- const versionStr = await this.kvClient.get(STATE_VERSION_KEY);- return versionStr ? parseInt(versionStr, 10) : null;+ return parseStoredTimestamp(await this.kvClient.get(STATE_VERSION_KEY), 'Deletion queue state version');} catch (error) {Logger.error({error}, 'Failed to get state version');throw error;diff --git a/fluxer_api/src/api/infrastructure/KVActivityTracker.ts b/fluxer_api/src/api/infrastructure/KVActivityTracker.tsindex 604de3304..5830f3d26 100644--- a/fluxer_api/src/api/infrastructure/KVActivityTracker.ts+++ b/fluxer_api/src/api/infrastructure/KVActivityTracker.ts@@ -6,30 +6,22 @@ import {seconds} from 'itty-time';import type {UserID} from '../BrandedTypes';import {Logger} from '../Logger';import {UserRepository} from '../user/repositories/UserRepository';+import {getValidTimestamp, parseStoredTimestamp} from '../utils/TimestampUtils';const TTL_SECONDS = seconds('90 days');const STATE_VERSION_KEY = 'activity_tracker:state_version';const STATE_VERSION_TTL_SECONDS = seconds('1 day');const REBUILD_BATCH_SIZE = 100;-function parseActivityValue(value: string | null): Date | null {- if (!value) {- return null;- }- const timestamp = parseInt(value, 10);- if (Number.isNaN(timestamp)) {- return null;- }- return new Date(timestamp);+function parseActivityValue(value: string | null, userId: UserID): Date | null {+ const timestamp = parseStoredTimestamp(value, `Activity timestamp for user ${userId}`);+ return timestamp === null ? null : new Date(timestamp);}export class KVActivityTracker {- private kvClient: IKVProvider;private isShuttingDown = false;- constructor(kvClient: IKVProvider) {- this.kvClient = kvClient;- }+ constructor(private readonly kvClient: IKVProvider) {}shutdown(): void {this.isShuttingDown = true;@@ -41,13 +33,13 @@ export class KVActivityTracker {async updateActivity(userId: UserID, timestamp: Date): Promise<void> {const key = this.getActivityKey(userId);- const value = timestamp.getTime().toString();+ const value = getValidTimestamp(timestamp, `Activity timestamp for user ${userId}`).toString();await this.kvClient.setex(key, TTL_SECONDS, value);}async getActivity(userId: UserID): Promise<Date | null> {const key = this.getActivityKey(userId);- return parseActivityValue(await this.kvClient.get(key));+ return parseActivityValue(await this.kvClient.get(key), userId);}async getActivities(userIds: ReadonlyArray<UserID>): Promise<Map<UserID, Date | null>> {@@ -57,22 +49,13 @@ export class KVActivityTracker {}const values = await this.kvClient.mget(...userIds.map((userId) => this.getActivityKey(userId)));for (const [index, userId] of userIds.entries()) {- activities.set(userId, parseActivityValue(values[index] ?? null));+ activities.set(userId, parseActivityValue(values[index], userId));}return activities;}async needsRebuild(): Promise<boolean> {- const exists = await this.kvClient.exists(STATE_VERSION_KEY);- if (exists === 0) {- return true;- }- const ttl = await this.kvClient.ttl(STATE_VERSION_KEY);- if (ttl < 0) {- return true;- }- const age = STATE_VERSION_TTL_SECONDS - ttl;- return age > STATE_VERSION_TTL_SECONDS;+ return (await this.kvClient.ttl(STATE_VERSION_KEY)) < 0;}private async writeActivityBatch(entries: ReadonlyArray<{key: string; value: string}>): Promise<void> {@@ -103,21 +86,18 @@ export class KVActivityTracker {while (!this.isShuttingDown) {const page = await userRepository.scanAllUsersPage(REBUILD_BATCH_SIZE, pageState);const users = page.users;- if (users.length === 0) {- break;- }for (const user of users) {- if (user.lastActiveAt) {- batch.push({key: this.getActivityKey(user.id), value: user.lastActiveAt.getTime().toString()});- usersWithActivity++;- if (batch.length >= kvBatchSize) {- await this.writeActivityBatch(batch);- batch = [];- }+ if (!user.lastActiveAt) continue;+ const timestamp = getValidTimestamp(user.lastActiveAt, `Last activity timestamp for user ${user.id}`);+ batch.push({key: this.getActivityKey(user.id), value: timestamp.toString()});+ usersWithActivity++;+ if (batch.length >= kvBatchSize) {+ await this.writeActivityBatch(batch);+ batch = [];}- processedCount++;}- if (processedCount % 10000 === 0) {+ processedCount += users.length;+ if (users.length > 0 && processedCount % 10000 === 0) {Logger.debug({processedCount, usersWithActivity}, 'Activity tracker rebuild progress');}pageState = page.pageState;diff --git a/fluxer_api/src/api/infrastructure/KVBulkMessageDeletionQueueService.ts b/fluxer_api/src/api/infrastructure/KVBulkMessageDeletionQueueService.tsindex be5184bb8..d2dae784b 100644--- a/fluxer_api/src/api/infrastructure/KVBulkMessageDeletionQueueService.ts+++ b/fluxer_api/src/api/infrastructure/KVBulkMessageDeletionQueueService.ts@@ -1,11 +1,14 @@// SPDX-License-Identifier: AGPL-3.0-or-later+import assert from 'node:assert/strict';import {generateLockToken} from '@pkgs/cache/src/CacheLockValidation';import type {IKVProvider} from '@pkgs/kv_client/src/IKVProvider';import {ms, seconds} from 'itty-time';import type {UserID} from '../BrandedTypes';import {Logger} from '../Logger';import type {UserRepository} from '../user/repositories/UserRepository';+import {getValidTimestamp, parseStoredTimestamp} from '../utils/TimestampUtils';+import {parseDeletionQueueMember, parseDeletionQueueUserId} from './DeletionQueueMember';interface QueuedBulkMessageDeletion {userId: bigint;@@ -29,32 +32,34 @@ export class KVBulkMessageDeletionQueueService {}private serializeQueueItem(item: QueuedBulkMessageDeletion): string {- return `${item.userId}|${item.scheduledAt}`;+ const userId = parseDeletionQueueUserId(item.userId.toString());+ return `${userId}|${item.scheduledAt}`;}private deserializeQueueItem(value: string): QueuedBulkMessageDeletion {- const [userIdStr, scheduledAtStr] = value.split('|');+ const {userId, payload} = parseDeletionQueueMember(value);+ const scheduledAt = parseStoredTimestamp(payload, 'Bulk message deletion queue timestamp');+ assert(scheduledAt !== null, 'A non-null bulk message deletion timestamp must not parse as null');return {- userId: BigInt(userIdStr),- scheduledAt: Number.parseInt(scheduledAtStr, 10),+ userId,+ scheduledAt,};}async needsRebuild(): Promise<boolean> {try {- const versionExists = await this.kvClient.exists(STATE_VERSION_KEY);- if (!versionExists) {+ const stateVersion = parseStoredTimestamp(+ await this.kvClient.get(STATE_VERSION_KEY),+ 'Bulk message deletion queue state version',+ );+ if (stateVersion === null) {Logger.debug('Bulk message deletion queue needs rebuild: no state version');return true;}- const stateVersionStr = await this.kvClient.get(STATE_VERSION_KEY);- if (stateVersionStr) {- const stateVersion = Number.parseInt(stateVersionStr, 10);- const ageMs = Date.now() - stateVersion;- if (ageMs > ms('1 day')) {- Logger.debug({ageMs, maxAgeMs: ms('1 day')}, 'Bulk message deletion queue needs rebuild: state too old');- return true;- }+ const ageMs = Date.now() - stateVersion;+ if (ageMs > ms('1 day')) {+ Logger.debug({ageMs, maxAgeMs: ms('1 day')}, 'Bulk message deletion queue needs rebuild: state too old');+ return true;}return false;} catch (error) {@@ -72,27 +77,21 @@ export class KVBulkMessageDeletionQueueService {let totalProcessed = 0;let totalQueued = 0;const batchSize = 1000;- while (true) {+ do {const page = await this.userRepository.scanAllUsersPage(batchSize, pageState);+ pageState = page.pageState;const users = page.users;- if (users.length === 0) {- break;- }+ if (users.length === 0) continue;for (const user of users) {- if (user.pendingBulkMessageDeletionAt) {- await this.scheduleDeletion(user.id, user.pendingBulkMessageDeletionAt);- totalQueued++;- }+ if (!user.pendingBulkMessageDeletionAt) continue;+ await this.scheduleDeletion(user.id, user.pendingBulkMessageDeletionAt);+ totalQueued++;}totalProcessed += users.length;- pageState = page.pageState;if (totalProcessed % 10000 === 0) {Logger.debug({totalProcessed, totalQueued}, 'Bulk message deletion queue rebuild progress');}- if (!pageState) {- break;- }- }+ } while (pageState);await this.kvClient.set(STATE_VERSION_KEY, Date.now().toString());Logger.info({totalProcessed, totalQueued}, 'Bulk message deletion queue rebuild completed');} catch (error) {@@ -105,7 +104,7 @@ export class KVBulkMessageDeletionQueueService {try {const entry: QueuedBulkMessageDeletion = {userId,- scheduledAt: scheduledAt.getTime(),+ scheduledAt: getValidTimestamp(scheduledAt, `Pending bulk message deletion timestamp for user ${userId}`),};const value = this.serializeQueueItem(entry);const secondaryKey = this.getSecondaryKey(userId);@@ -136,12 +135,23 @@ export class KVBulkMessageDeletionQueueService {try {const results = await this.kvClient.zrangebyscore(QUEUE_KEY, '-inf', nowMs, 'LIMIT', 0, limit);const deletions: Array<QueuedBulkMessageDeletion> = [];+ const unparseable: Array<string> = [];for (const result of results) {try {- const deletion = this.deserializeQueueItem(result);- deletions.push(deletion);+ deletions.push(this.deserializeQueueItem(result));+ } catch {+ unparseable.push(result);+ }+ }+ if (unparseable.length > 0) {+ Logger.error({unparseableCount: unparseable.length}, 'Dropped unparseable bulk message deletion queue members');+ try {+ await this.kvClient.zrem(QUEUE_KEY, ...unparseable);} catch (error) {- Logger.error({error, result}, 'Failed to parse queued bulk message deletion entry');+ Logger.error(+ {error, unparseableCount: unparseable.length},+ 'Failed to remove unparseable bulk message deletion queue members',+ );}}return deletions;diff --git a/fluxer_api/src/api/infrastructure/SnowflakeService.ts b/fluxer_api/src/api/infrastructure/SnowflakeService.tsindex 03d8a6d39..0bbdef751 100644--- a/fluxer_api/src/api/infrastructure/SnowflakeService.ts+++ b/fluxer_api/src/api/infrastructure/SnowflakeService.ts@@ -1,8 +1,11 @@// SPDX-License-Identifier: AGPL-3.0-or-later+import assert from 'node:assert/strict';+import {ServiceUnavailableError} from '@fluxer/errors/src/domains/core/ServiceUnavailableError';import type {INatsConnectionManager} from '@pkgs/nats/src/INatsConnectionManager';import {StringCodec} from 'nats';import {Logger} from '../Logger';+import {requireIntegerInRange} from '../utils/IntegerOptions';import {isJsonRecord, parseJsonWithGuard} from '../utils/JsonBoundaryUtils';import type {ISnowflakeService} from './ISnowflakeService';@@ -12,6 +15,16 @@ const DEFAULT_REMOTE_LOW_WATERMARK = 32;const DEFAULT_REMOTE_TIMEOUT_MS = 6000;const DEFAULT_REMOTE_MAX_BUFFER_AGE_MS = 5000;const MAX_REMOTE_BATCH_SIZE = 512;+const MAX_PENDING_GENERATIONS = 1024;+const MAX_REMOTE_RESPONSE_BYTES = 16 * 1024;+const MAX_REMOTE_ID = 0xffffffffffffffffn;++class SnowflakeServiceStoppedError extends Error {+ constructor() {+ super('SnowflakeService is shut down');+ this.name = 'SnowflakeServiceStoppedError';+ }+}interface SnowflakeServiceOptions {connectionManager: INatsConnectionManager;@@ -41,11 +54,15 @@ function isRemoteSnowflakeResponse(value: unknown): value is RemoteSnowflakeResp);}-function resolveIntegerOption(value: number | undefined, fallback: number, min: number, max: number): number {- if (typeof value !== 'number' || !Number.isInteger(value)) {- return fallback;+function parseRemoteSnowflakeId(value: string): bigint {+ if (value.length === 0 || value.length > 20 || /\D/.test(value)) {+ throw new Error('Snowflake ID must be a canonical unsigned 64-bit integer');+ }+ const id = BigInt(value);+ if (id > MAX_REMOTE_ID || id.toString() !== value) {+ throw new Error('Snowflake ID must be a canonical unsigned 64-bit integer');}- return Math.min(max, Math.max(min, value));+ return id;}export class SnowflakeService implements ISnowflakeService {@@ -56,110 +73,174 @@ export class SnowflakeService implements ISnowflakeService {private readonly requestTimeoutMs: number;private readonly maxBufferAgeMs: number;private readonly codec = StringCodec();- private initialized = false;- private shutdownRequested = false;+ private phase: 'idle' | 'starting' | 'ready' | 'stopping' | 'stopped' = 'idle';private buffer: Array<bigint> = [];private bufferOffset = 0;private bufferFetchedAtMs: number | null = null;private initializationPromise: Promise<void> | null = null;private refillPromise: Promise<void> | null = null;+ private shutdownPromise: Promise<void> | null = null;+ private pendingGenerations = 0;+ private resolveGenerationsDrained: (() => void) | null = null;- constructor(options: SnowflakeServiceOptions) {- this.connectionManager = options.connectionManager;- this.subject = options.subject ?? DEFAULT_REMOTE_SUBJECT;- this.batchSize = resolveIntegerOption(options.batchSize, DEFAULT_REMOTE_BATCH_SIZE, 1, MAX_REMOTE_BATCH_SIZE);- this.lowWatermark = Math.min(- resolveIntegerOption(options.lowWatermark, DEFAULT_REMOTE_LOW_WATERMARK, 0, MAX_REMOTE_BATCH_SIZE),- Math.max(0, this.batchSize - 1),+ constructor({+ connectionManager,+ subject = DEFAULT_REMOTE_SUBJECT,+ batchSize = DEFAULT_REMOTE_BATCH_SIZE,+ lowWatermark = Math.min(DEFAULT_REMOTE_LOW_WATERMARK, batchSize - 1),+ requestTimeoutMs = DEFAULT_REMOTE_TIMEOUT_MS,+ maxBufferAgeMs = DEFAULT_REMOTE_MAX_BUFFER_AGE_MS,+ }: SnowflakeServiceOptions) {+ this.connectionManager = connectionManager;+ this.subject = subject;+ this.batchSize = requireIntegerInRange('FLUXER_SNOWFLAKE_SERVICE_BATCH_SIZE', batchSize, 1, MAX_REMOTE_BATCH_SIZE);+ this.lowWatermark = requireIntegerInRange(+ 'FLUXER_SNOWFLAKE_SERVICE_LOW_WATERMARK',+ lowWatermark,+ 0,+ this.batchSize - 1,+ );+ this.requestTimeoutMs = requireIntegerInRange(+ 'FLUXER_SNOWFLAKE_SERVICE_REQUEST_TIMEOUT_MS',+ requestTimeoutMs,+ 1,+ 60_000,+ );+ this.maxBufferAgeMs = requireIntegerInRange(+ 'FLUXER_SNOWFLAKE_SERVICE_MAX_BUFFER_AGE_MS',+ maxBufferAgeMs,+ 1,+ 60_000,);- this.requestTimeoutMs = resolveIntegerOption(options.requestTimeoutMs, DEFAULT_REMOTE_TIMEOUT_MS, 1, 60000);- this.maxBufferAgeMs = resolveIntegerOption(options.maxBufferAgeMs, DEFAULT_REMOTE_MAX_BUFFER_AGE_MS, 1, 60000);}async initialize(): Promise<void> {- if (this.shutdownRequested) {- return;- }- if (this.initialized) {- return;- }+ this.assertActive();+ if (this.phase === 'ready') return;if (!this.initializationPromise) {- this.initializationPromise = (async () => {- await this.ensureConnected();- await this.refillBuffer();- this.initialized = true;- })().finally(() => {+ this.phase = 'starting';+ this.initializationPromise = this.start().finally(() => {this.initializationPromise = null;});}await this.initializationPromise;}- async reinitialize(): Promise<void> {- this.shutdownRequested = false;- this.initialized = false;- this.buffer = [];- this.bufferOffset = 0;- this.bufferFetchedAtMs = null;- this.initializationPromise = null;- await this.initialize();+ private async start(): Promise<void> {+ try {+ await this.refillBuffer();+ this.assertActive();+ this.phase = 'ready';+ } catch (error) {+ if (this.phase === 'starting') this.phase = 'idle';+ throw error;+ }}- async shutdown(): Promise<void> {- this.shutdownRequested = true;- this.initialized = false;- this.buffer = [];- this.bufferOffset = 0;- this.bufferFetchedAtMs = null;- const refillPromise = this.refillPromise;- this.refillPromise = null;- if (refillPromise) {- await refillPromise.catch(() => undefined);- }- await this.connectionManager.drain();+ shutdown(): Promise<void> {+ if (this.shutdownPromise) return this.shutdownPromise;+ this.phase = 'stopping';+ this.clearBuffer();+ this.shutdownPromise = this.close();+ return this.shutdownPromise;}- async generate(): Promise<bigint> {- await this.ensureInitialized();- this.discardExpiredBuffer();- const bufferedId = this.takeBufferedId();- if (bufferedId != null) {- this.scheduleRefillIfNeeded();- return bufferedId;- }- await this.refillBuffer();- const refilledId = this.takeBufferedId();- if (refilledId == null) {- throw new Error('Snowflake service returned no IDs');+ private async close(): Promise<void> {+ try {+ await Promise.allSettled([this.initializationPromise, this.refillPromise]);+ if (this.pendingGenerations > 0) {+ await new Promise<void>((resolve) => {+ this.resolveGenerationsDrained = resolve;+ });+ }+ await this.connectionManager.drain();+ } finally {+ this.phase = 'stopped';+ this.clearBuffer();}- this.scheduleRefillIfNeeded();- return refilledId;}- async generateForChannel(channelId: string | bigint): Promise<bigint> {- await this.ensureInitialized();- const routingKey = `channel:${channelId.toString()}`;- const ids = await this.requestBatch(1, routingKey);- const id = ids[0];- if (id == null) {- throw new Error('Snowflake service returned no IDs');- }- return id;+ generate(): Promise<bigint> {+ return this.withGeneration(async (deadline) => {+ await this.ensureInitialized(deadline);+ for (;;) {+ this.assertActive();+ this.remainingTime(deadline);+ this.discardExpiredBuffer();+ const id = this.takeBufferedId();+ if (id !== null) {+ this.scheduleRefillIfNeeded();+ return id;+ }+ await this.waitFor(this.refillBuffer(), deadline);+ }+ });+ }++ generateForChannel(channelId: string | bigint): Promise<bigint> {+ return this.withGeneration(async (deadline) => {+ const routingKey = `channel:${parseRemoteSnowflakeId(channelId.toString())}`;+ await this.ensureInitialized(deadline);+ const ids = await this.requestBatch(1, routingKey);+ return ids[0]!;+ });}- private async ensureInitialized(): Promise<void> {- if (this.shutdownRequested) {- throw new Error('SnowflakeService is shut down');+ private async withGeneration(operation: (deadline: number) => Promise<bigint>): Promise<bigint> {+ this.assertActive();+ if (this.pendingGenerations >= MAX_PENDING_GENERATIONS) {+ Logger.warn(+ {pendingGenerations: this.pendingGenerations, limit: MAX_PENDING_GENERATIONS},+ 'Snowflake generation capacity exceeded',+ );+ throw new ServiceUnavailableError({headers: {'Retry-After': '1'}});}- if (!this.initialized) {- await this.initialize();+ this.pendingGenerations++;+ try {+ const id = await operation(performance.now() + this.requestTimeoutMs);+ this.assertActive();+ return id;+ } finally {+ this.pendingGenerations--;+ if (this.pendingGenerations === 0) {+ this.resolveGenerationsDrained?.();+ this.resolveGenerationsDrained = null;+ }}- if (!this.initialized) {- throw new Error('SnowflakeService not initialized');+ }++ private assertActive(): void {+ if (this.phase === 'stopping' || this.phase === 'stopped') throw new SnowflakeServiceStoppedError();+ }++ private remainingTime(deadline: number): number {+ const remaining = deadline - performance.now();+ if (remaining <= 0) throw new Error('Snowflake generation timed out');+ return remaining;+ }++ private async waitFor(task: Promise<void>, deadline: number): Promise<void> {+ let timer: NodeJS.Timeout | undefined;+ const timeout = new Promise<never>((_, reject) => {+ timer = setTimeout(() => reject(new Error('Snowflake generation timed out')), this.remainingTime(deadline));+ timer.unref();+ });+ try {+ await Promise.race([task, timeout]);+ } finally {+ clearTimeout(timer);}}+ private async ensureInitialized(deadline: number): Promise<void> {+ this.assertActive();+ if (this.phase !== 'ready') await this.waitFor(this.initialize(), deadline);+ this.assertActive();+ assert(this.phase === 'ready', 'Snowflake initialization completed without becoming ready');+ }+private async refillBuffer(): Promise<void> {+ this.assertActive();if (this.refillPromise) {await this.refillPromise;return;@@ -167,9 +248,7 @@ export class SnowflakeService implements ISnowflakeService {this.refillPromise = (async () => {await this.ensureConnected();const ids = await this.requestBatch(this.batchSize);- if (ids.length === 0) {- throw new Error('Snowflake service returned an empty batch');- }+ this.assertActive();this.discardExpiredBuffer();this.compactBuffer();if (this.buffer.length === 0) {@@ -183,6 +262,8 @@ export class SnowflakeService implements ISnowflakeService {}private async requestBatch(count: number, routingKey?: string): Promise<Array<bigint>> {+ this.assertActive();+ assert(Number.isInteger(count) && count > 0 && count <= MAX_REMOTE_BATCH_SIZE, 'Invalid snowflake batch size');const connection = this.connectionManager.getConnection();const request: RemoteSnowflakeRequest = {op: 'GenerateBatch',@@ -194,37 +275,50 @@ export class SnowflakeService implements ISnowflakeService {const responseMessage = await connection.request(this.subject, this.codec.encode(JSON.stringify(request)), {timeout: this.requestTimeoutMs,});+ this.assertActive();+ if (responseMessage.data.byteLength > MAX_REMOTE_RESPONSE_BYTES) {+ throw new Error('Snowflake service response exceeds the byte limit');+ }const response = parseJsonWithGuard(this.codec.decode(responseMessage.data), isRemoteSnowflakeResponse);if (!response) {throw new Error('Snowflake service returned an invalid response');}- if (response.error) {+ if (response.error !== undefined) {throw new Error(`Snowflake service error: ${response.error}`);}- if (!Array.isArray(response.ids)) {- throw new Error('Snowflake service returned an invalid response');+ if (!response.ids || response.ids.length !== count) {+ throw new Error('Snowflake service returned an incorrect batch size');}- return response.ids.map((id) => BigInt(id));+ let previous = -1n;+ return response.ids.map((value) => {+ const id = parseRemoteSnowflakeId(value);+ if (id <= previous) throw new Error('Snowflake service returned duplicate or unordered IDs');+ previous = id;+ return id;+ });}private async ensureConnected(): Promise<void> {+ this.assertActive();if (this.connectionManager.isClosed()) {await this.connectionManager.connect();}+ this.assertActive();+ }++ private clearBuffer(): void {+ this.buffer = [];+ this.bufferOffset = 0;+ this.bufferFetchedAtMs = null;}private takeBufferedId(): bigint | null {if (this.bufferOffset >= this.buffer.length) {- this.buffer = [];- this.bufferOffset = 0;- this.bufferFetchedAtMs = null;+ this.clearBuffer();return null;}const id = this.buffer[this.bufferOffset];this.bufferOffset += 1;- if (this.bufferOffset > 1024) {- this.compactBuffer();- }return id;}@@ -250,16 +344,15 @@ export class SnowflakeService implements ISnowflakeService {if (Date.now() - this.bufferFetchedAtMs <= this.maxBufferAgeMs) {return;}- this.buffer = [];- this.bufferOffset = 0;- this.bufferFetchedAtMs = null;+ this.clearBuffer();}private scheduleRefillIfNeeded(): void {- if (this.shutdownRequested || this.availableIds() > this.lowWatermark || this.refillPromise) {+ if (this.phase !== 'ready' || this.availableIds() > this.lowWatermark || this.refillPromise) {return;}void this.refillBuffer().catch((error) => {+ if (error instanceof SnowflakeServiceStoppedError) return;Logger.error({error}, 'Failed to refill snowflake buffer');});}diff --git a/fluxer_api/src/api/infrastructure/StorageService.ts b/fluxer_api/src/api/infrastructure/StorageService.tsindex f165539f2..8195f1994 100644--- a/fluxer_api/src/api/infrastructure/StorageService.ts+++ b/fluxer_api/src/api/infrastructure/StorageService.ts@@ -240,6 +240,12 @@ export class StorageService implements IStorageService {return;}const stream = fs.createReadStream(filePath, {highWaterMark: 1024 * 1024});+ const errors = new Set<unknown>();+ const onSourceError = (error: Error) => {+ errors.add(error);+ };+ stream.on('error', onSourceError);+ const closed = new Promise<void>((resolve) => stream.once('close', resolve));try {const upload = new Upload({client: this.client,@@ -255,10 +261,18 @@ export class StorageService implements IStorageService {leavePartsOnError: false,});await upload.done();+ if (!stream.readableEnded) {+ throw new Error('File upload completed before its source stream ended');+ }} catch (error) {+ errors.add(error);+ } finally {stream.destroy();- throw error;+ await closed;+ stream.off('error', onSourceError);}+ if (errors.size === 1) throw errors.values().next().value;+ if (errors.size > 1) throw new AggregateError(errors, 'File upload and source stream failed');}async getPresignedDownloadURL({diff --git a/fluxer_api/src/api/infrastructure/UsersServiceClient.ts b/fluxer_api/src/api/infrastructure/UsersServiceClient.tsindex 75482e65e..53ad875cf 100644--- a/fluxer_api/src/api/infrastructure/UsersServiceClient.ts+++ b/fluxer_api/src/api/infrastructure/UsersServiceClient.ts@@ -4,57 +4,63 @@ import type {UserPartialResponse} from '@fluxer/schema/src/domains/user/UserRespimport type {INatsConnectionManager} from '@pkgs/nats/src/INatsConnectionManager';import {NatsConnectionManager} from '@pkgs/nats/src/NatsConnectionManager';import {StringCodec} from 'nats';-import {createUserID, type UserID} from '../BrandedTypes';+import type {UserID} from '../BrandedTypes';import {Config} from '../Config';import {Logger} from '../Logger';+import {awaitAll} from '../utils/ConcurrencyUtils';+import {readOptionalIntegerEnv, requireIntegerInRange} from '../utils/IntegerOptions';import {isJsonRecord, parseJsonRecord, parseJsonWithGuard} from '../utils/JsonBoundaryUtils';import {throwForSvcErrorReply} from './SvcErrorReply';const USERS_SERVICE_SUBJECT = process.env.FLUXER_USERS_SERVICE_SUBJECT || 'svc.users';const DEFAULT_USERS_SERVICE_TIMEOUT_MS = 6000;const DEFAULT_USERS_SERVICE_INFLIGHT_MAX_ENTRIES = 10000;+const MAX_REQUEST_TIMEOUT_MS = 2_147_483_647;export interface IUsersServiceClient {getUserPartialResponses(userIds: Array<UserID>): Promise<Map<UserID, UserPartialResponse>>;invalidateUserCache(userId: UserID): Promise<void>;}-type UsersServiceResponse =+type PendingUserPartials = Promise<Map<UserID, UserPartialResponse>>;++type UsersServiceRequest =| {- FoundApiPartials: Array<UserPartialResponse>;+ op: 'GetApiPartialsByIds';+ user_ids: Array<string>;}| {- FoundApiPartial: UserPartialResponse;- }- | 'NotFound'- | 'Invalidated';+ op: 'Invalidate';+ user_id: string;+ };++interface UserPartialsResponse {+ FoundApiPartials: Array<UserPartialResponse>;+}function isUserPartialResponse(value: unknown): value is UserPartialResponse {return isJsonRecord(value) && typeof value.id === 'string';}-function isUsersServiceResponse(value: unknown): value is UsersServiceResponse {- if (value === 'NotFound' || value === 'Invalidated') return true;- if (!isJsonRecord(value)) return false;- if ('FoundApiPartials' in value) {- return Array.isArray(value.FoundApiPartials) && value.FoundApiPartials.every(isUserPartialResponse);- }- if ('FoundApiPartial' in value) {- return isUserPartialResponse(value.FoundApiPartial);- }- return false;+function isUserPartialsResponse(value: unknown): value is UserPartialsResponse {+ return (+ isJsonRecord(value) && Array.isArray(value.FoundApiPartials) && value.FoundApiPartials.every(isUserPartialResponse)+ );}export class NatsUsersServiceClient implements IUsersServiceClient {private readonly codec = StringCodec();- private readonly inflightPartials = new Map<string, Promise<UserPartialResponse | undefined>>();+ private readonly inflightPartials = new Map<UserID, PendingUserPartials>();constructor(private readonly connectionManager: INatsConnectionManager,private readonly requestTimeoutMs = DEFAULT_USERS_SERVICE_TIMEOUT_MS,private readonly subject = USERS_SERVICE_SUBJECT,private readonly maxInflightEntries = DEFAULT_USERS_SERVICE_INFLIGHT_MAX_ENTRIES,- ) {}+ ) {+ requireIntegerInRange('FLUXER_USERS_SERVICE_TIMEOUT_MS', requestTimeoutMs, 1, MAX_REQUEST_TIMEOUT_MS);+ requireIntegerInRange('FLUXER_USERS_SERVICE_INFLIGHT_MAX_ENTRIES', maxInflightEntries, 0, Number.MAX_SAFE_INTEGER);+ }async getUserPartialResponses(userIds: Array<UserID>): Promise<Map<UserID, UserPartialResponse>> {const uniqueUserIds = uniqueSortedUserIds(userIds);@@ -62,100 +68,93 @@ export class NatsUsersServiceClient implements IUsersServiceClient {return new Map();}const result = new Map<UserID, UserPartialResponse>();- const existing: Array<Promise<void>> = [];+ const lookups = new Map<PendingUserPartials, Array<UserID>>();const misses: Array<UserID> = [];for (const userId of uniqueUserIds) {- const key = userId.toString();- const inflight = this.inflightPartials.get(key);- if (inflight) {- existing.push(this.copyInflightPartial(userId, inflight, result));+ const batch = this.inflightPartials.get(userId);+ if (!batch) {+ misses.push(userId);continue;}- misses.push(userId);+ const assignedUserIds = lookups.get(batch);+ if (assignedUserIds) assignedUserIds.push(userId);+ else lookups.set(batch, [userId]);+ }+ const capacity = Math.max(0, this.maxInflightEntries - this.inflightPartials.size);+ const coalesced = misses.slice(0, capacity);+ const direct = misses.slice(capacity);+ if (coalesced.length > 0) {+ lookups.set(this.fetchCoalescedPartials(coalesced), coalesced);+ }+ if (direct.length > 0) {+ lookups.set(this.fetchUserPartialResponses(direct), direct);}- const newlyFetched = this.fetchAndCoalesceMissingPartials(misses, result);- await Promise.all([...existing, newlyFetched]);+ await awaitAll(+ Array.from(lookups, async ([batch, assignedUserIds]) => {+ const partials = await batch;+ for (const userId of assignedUserIds) {+ const partial = partials.get(userId);+ if (partial) result.set(userId, partial);+ }+ }),+ '[users-service] failed to fetch user partials',+ );return result;}private async fetchUserPartialResponses(userIds: Array<UserID>): Promise<Map<UserID, UserPartialResponse>> {- const response = await this.request({- op: 'GetApiPartialsByIds',- user_ids: userIds.map((userId) => userId.toString()),- });- const partials =- typeof response === 'object' && 'FoundApiPartials' in response- ? response.FoundApiPartials- : typeof response === 'object' && 'FoundApiPartial' in response- ? [response.FoundApiPartial]- : [];+ const requestedUserIds = new Map(userIds.map((userId) => [userId.toString(), userId]));+ const response = await this.request(+ {+ op: 'GetApiPartialsByIds',+ user_ids: Array.from(requestedUserIds.keys()),+ },+ isUserPartialsResponse,+ );const result = new Map<UserID, UserPartialResponse>();- for (const partial of partials) {- try {- const userId = createUserID(BigInt(partial.id));- result.set(userId, partial);- } catch (error) {- Logger.warn({userId: partial.id, error}, '[users-service] invalid user partial id');+ for (const partial of response.FoundApiPartials) {+ const userId = requestedUserIds.get(partial.id);+ if (userId === undefined) {+ throw new Error('[users-service] response contains an invalid or unrequested user ID');+ }+ if (result.has(userId)) {+ throw new Error('[users-service] response contains a duplicate user ID');}+ result.set(userId, partial);}return result;}- private async fetchAndCoalesceMissingPartials(- userIds: Array<UserID>,- result: Map<UserID, UserPartialResponse>,- ): Promise<void> {- if (userIds.length === 0) {- return;- }- const capacity = Math.max(0, this.maxInflightEntries - this.inflightPartials.size);- const coalesced = userIds.slice(0, capacity);- const direct = userIds.slice(capacity);- const tasks: Array<Promise<void>> = [];- if (coalesced.length > 0) {- const batch = this.fetchUserPartialResponses(coalesced);- for (const userId of coalesced) {- const key = userId.toString();- const partial = batch- .then((partials) => partials.get(userId))- .finally(() => {- this.inflightPartials.delete(key);- });- this.inflightPartials.set(key, partial);- tasks.push(this.copyInflightPartial(userId, partial, result));+ private fetchCoalescedPartials(userIds: Array<UserID>): PendingUserPartials {+ const batch = this.fetchUserPartialResponses(userIds).finally(() => {+ for (const userId of userIds) {+ if (this.inflightPartials.get(userId) === batch) {+ this.inflightPartials.delete(userId);+ }}+ });+ for (const userId of userIds) {+ this.inflightPartials.set(userId, batch);}- if (direct.length > 0) {- tasks.push(- this.fetchUserPartialResponses(direct).then((partials) => {- for (const [userId, partial] of partials) {- result.set(userId, partial);- }- }),- );- }- await Promise.all(tasks);- }-- private async copyInflightPartial(- userId: UserID,- partialPromise: Promise<UserPartialResponse | undefined>,- result: Map<UserID, UserPartialResponse>,- ): Promise<void> {- const partial = await partialPromise;- if (partial) {- result.set(userId, partial);- }+ return batch;}async invalidateUserCache(userId: UserID): Promise<void> {- await this.request({- op: 'Invalidate',- user_id: userId.toString(),- });+ this.inflightPartials.delete(userId);+ try {+ await this.request(+ {+ op: 'Invalidate',+ user_id: userId.toString(),+ },+ (value): value is 'Invalidated' => value === 'Invalidated',+ );+ } finally {+ this.inflightPartials.delete(userId);+ }}- private async request(payload: Record<string, unknown>): Promise<UsersServiceResponse> {+ private async request<T>(payload: UsersServiceRequest, responseGuard: (value: unknown) => value is T): Promise<T> {try {if (this.connectionManager.isClosed()) {await this.connectionManager.connect();@@ -165,8 +164,8 @@ export class NatsUsersServiceClient implements IUsersServiceClient {timeout: this.requestTimeoutMs,});const decoded = this.codec.decode(response.data);- const parsed = parseJsonWithGuard(decoded, isUsersServiceResponse);- if (!parsed) {+ const parsed = parseJsonWithGuard(decoded, responseGuard);+ if (parsed === null) {throwForSvcErrorReply('users-service', parseJsonRecord(decoded));throw new Error('[users-service] invalid response payload');}@@ -198,27 +197,18 @@ export function createUsersServiceClient(): IUsersServiceClient {token: Config.nats.authToken || undefined,name: process.env.FLUXER_USERS_SERVICE_NATS_CLIENT_NAME || 'fluxer-api-users',});- void manager.connect().catch((error) => {- Logger.warn({error}, '[users-service] Failed to establish NATS connection');- });usersServiceClient = new NatsUsersServiceClient(manager,- readPositiveIntegerEnv('FLUXER_USERS_SERVICE_TIMEOUT_MS'),+ readOptionalIntegerEnv('FLUXER_USERS_SERVICE_TIMEOUT_MS'),USERS_SERVICE_SUBJECT,- readPositiveIntegerEnv('FLUXER_USERS_SERVICE_INFLIGHT_MAX_ENTRIES', DEFAULT_USERS_SERVICE_INFLIGHT_MAX_ENTRIES),+ readOptionalIntegerEnv('FLUXER_USERS_SERVICE_INFLIGHT_MAX_ENTRIES'),);+ void manager.connect().catch((error) => {+ Logger.warn({error}, '[users-service] Failed to establish NATS connection');+ });return usersServiceClient;}-function readPositiveIntegerEnv(name: string, fallback = DEFAULT_USERS_SERVICE_TIMEOUT_MS): number {- const value = process.env[name];- if (!value) {- return fallback;- }- const parsed = Number(value);- return Number.isInteger(parsed) && parsed > 0 ? parsed : fallback;-}-function uniqueSortedUserIds(userIds: Array<UserID>): Array<UserID> {const seen = new Map<string, UserID>();for (const userId of userIds) {diff --git a/fluxer_api/src/api/instance/InstanceConfigCache.ts b/fluxer_api/src/api/instance/InstanceConfigCache.tsnew file mode 100644index 000000000..31a826199--- /dev/null+++ b/fluxer_api/src/api/instance/InstanceConfigCache.ts@@ -0,0 +1,114 @@+import {randomUUID} from 'node:crypto';+import type {IKVProvider} from '@pkgs/kv_client/src/IKVProvider';+import {Logger} from '../Logger';+import {parseJsonRecord} from '../utils/JsonBoundaryUtils';+import {RefreshSubscription, RefreshSubscriptionUnavailableError} from '../utils/RefreshSubscription';++interface InstanceConfigCacheOptions {+ provider: IKVProvider | null;+ channel: string;+ load: () => Promise<Map<string, string>>;+ onRefresh: (snapshot: ReadonlyMap<string, string>) => void;+}++export class InstanceConfigCache {+ readonly sourceId = randomUUID();+ private active = true;+ private snapshot: Map<string, string> | null = null;+ private writesDuringRefresh: Map<string, string> | null = null;+ private initialization: Promise<boolean> | null = null;+ private shutdownCompletion: Promise<void> | null = null;+ private readonly subscription: RefreshSubscription;++ constructor(+ private readonly options: InstanceConfigCacheOptions,+ private readonly previousShutdown: Promise<void> = Promise.resolve(),+ ) {+ this.subscription = new RefreshSubscription({+ name: 'InstanceConfigCache',+ channels: [options.channel],+ shouldRefresh: (_channel, message) => parseJsonRecord(message)?.source_id !== this.sourceId,+ drainInitialNotifications: true,+ refresh: () => this.refresh(),+ onRefreshError: (error) => {+ Logger.error({error}, 'Failed to refresh instance config cache from pubsub');+ },+ });+ }++ assertActive(): void {+ if (!this.active) throw new Error('Instance config cache is shutting down or shut down');+ }++ async getSnapshot(): Promise<ReadonlyMap<string, string> | null> {+ this.assertActive();+ if (!this.subscription.isReady) {+ this.initialization ??= this.initialize().finally(() => {+ this.initialization = null;+ });+ const cached = await this.initialization;+ this.assertActive();+ if (!cached) return null;+ }+ if (this.snapshot === null) throw new Error('Instance config cache is ready without a snapshot');+ return this.snapshot;+ }++ private async initialize(): Promise<boolean> {+ await this.previousShutdown;+ this.assertActive();+ if (this.options.provider === null) return false;+ try {+ await this.subscription.start(this.options.provider);+ return true;+ } catch (error) {+ this.assertActive();+ if (!(error instanceof RefreshSubscriptionUnavailableError)) throw error;+ Logger.error({error}, 'Instance config subscription unavailable, reading directly from the database');+ return false;+ }+ }++ private async refresh(): Promise<void> {+ this.assertActive();+ if (this.writesDuringRefresh !== null) throw new Error('Instance config refresh already in progress');+ const writes = new Map<string, string>();+ this.writesDuringRefresh = writes;+ try {+ const snapshot = await this.options.load();+ if (!this.active) return;+ for (const [key, value] of writes) snapshot.set(key, value);+ this.options.onRefresh(snapshot);+ this.snapshot = snapshot;+ } finally {+ this.writesDuringRefresh = null;+ }+ }++ update(key: string, value: string): void {+ if (!this.active) return;+ this.snapshot?.set(key, value);+ this.writesDuringRefresh?.set(key, value);+ }++ shutdown(): Promise<void> {+ if (this.shutdownCompletion) return this.shutdownCompletion;+ this.active = false;+ this.snapshot = null;+ this.shutdownCompletion = this.close();+ return this.shutdownCompletion;+ }++ private async close(): Promise<void> {+ const [subscription, previous] = await Promise.allSettled([+ this.subscription.stop(),+ this.previousShutdown,+ this.initialization,+ ]);+ const errors: Array<unknown> = [subscription, previous].flatMap((result) =>+ result.status === 'rejected' ? [result.reason] : [],+ );+ if (errors.length === 1) throw errors[0];+ if (errors.length > 1) throw new AggregateError(errors, 'Failed to shut down instance config cache');+ }+}diff --git a/fluxer_api/src/api/instance/InstanceConfigRepository.test.ts b/fluxer_api/src/api/instance/InstanceConfigRepository.test.tsindex 487720e46..57334411c 100644--- a/fluxer_api/src/api/instance/InstanceConfigRepository.test.ts+++ b/fluxer_api/src/api/instance/InstanceConfigRepository.test.ts@@ -21,6 +21,9 @@ import {const VOICE_NOISE_SUPPRESSION_CONFIG_KEY = 'voice_noise_suppression_config';const EXPERIMENT_DELIVERY_CONFIG_KEY = 'experiment_delivery_config';+const APP_PUBLIC_CONFIG_KEY = 'app_public_config';+const INSTANCE_POLICY_CONFIG_KEY = 'instance_policy_config';+const INSTANCE_INTEGRATIONS_CONFIG_KEY = 'instance_integrations_config';class CountingInMemoryCassandraQueryExecutor extends InMemoryCassandraQueryExecutor {instanceConfigSelects = 0;@@ -158,6 +161,106 @@ describe('InstanceConfigRepository', () => {});});+ it('keeps the stored setup state when a branding field is invalid', async () => {+ const executor = new CountingInMemoryCassandraQueryExecutor();+ setCassandraQueryExecutorForTesting(executor);+ const kvProvider = new MockKVProvider();+ const repository = createRepository(kvProvider);++ await repository.setConfig(+ APP_PUBLIC_CONFIG_KEY,+ JSON.stringify({branding: {product_name: 'Kept', icon_url: 42}, setup: {configured: false}}),+ );++ const config = await repository.getAppPublicConfig();+ expect(config.setup.configured).toBe(false);+ expect(config.branding.product_name).toBe('Kept');+ });++ it('keeps valid stored instance policy flags when one field is invalid', async () => {+ const executor = new CountingInMemoryCassandraQueryExecutor();+ setCassandraQueryExecutorForTesting(executor);+ const kvProvider = new MockKVProvider();+ const repository = createRepository(kvProvider);++ await repository.setConfig(+ INSTANCE_POLICY_CONFIG_KEY,+ JSON.stringify({direct_messages_disabled: true, single_community_enabled: true, premium_mode: 'nonsense'}),+ );++ const policy = await repository.getInstancePolicyConfig();+ expect(policy.direct_messages_disabled).toBe(true);+ expect(policy.single_community_enabled).toBe(true);+ expect(policy.premium_mode).toBe('everyone');+ });++ it('keeps valid stored integration settings when one field is invalid', async () => {+ const executor = new CountingInMemoryCassandraQueryExecutor();+ setCassandraQueryExecutorForTesting(executor);+ const kvProvider = new MockKVProvider();+ const repository = createRepository(kvProvider);++ await repository.setConfig(+ INSTANCE_INTEGRATIONS_CONFIG_KEY,+ JSON.stringify({bluesky: {client_name: 'Kept Instance', enabled: 'yes'}}),+ );++ expect((await repository.getEffectiveBlueskyConfig()).client_name).toBe('Kept Instance');+ expect((await repository.getInstanceIntegrationsConfig()).bluesky.enabled).toBeNull();+ });++ it('drops invalid stored SSO allowed domains and keeps the valid ones', async () => {+ const executor = new CountingInMemoryCassandraQueryExecutor();+ setCassandraQueryExecutorForTesting(executor);+ const kvProvider = new MockKVProvider();+ const repository = createRepository(kvProvider);++ await repository.setConfig('sso_allowed_domains', JSON.stringify(['example.com', '[email protected]', 'Kept.ORG']));++ expect((await repository.getSsoConfig()).allowedEmailDomains).toEqual(['example.com', 'kept.org']);+ });++ it('falls back to the default SSO flags when a stored flag is not a boolean', async () => {+ const executor = new CountingInMemoryCassandraQueryExecutor();+ setCassandraQueryExecutorForTesting(executor);+ const kvProvider = new MockKVProvider();+ const repository = createRepository(kvProvider);++ await repository.setConfig('sso_enabled', 'yes');+ await repository.setConfig('sso_enforced', 'sometimes');+ await repository.setConfig('sso_auto_provision', 'maybe');++ const config = await repository.getSsoConfig();+ expect(config.enabled).toBe(false);+ expect(config.enforced).toBe(false);+ expect(config.autoProvision).toBe(true);+ });++ it('clears an invalid allowed domain list only while SSO is disabled', async () => {+ const executor = new CountingInMemoryCassandraQueryExecutor();+ setCassandraQueryExecutorForTesting(executor);+ const kvProvider = new MockKVProvider();+ const repository = createRepository(kvProvider);++ const cleared = await repository.setSsoConfig({enabled: false, allowedEmailDomains: ['[email protected]']});+ expect(cleared.allowedEmailDomains).toEqual([]);++ await expect(repository.setSsoConfig({enabled: true, allowedEmailDomains: ['[email protected]']})).rejects.toThrow();+ });++ it('keeps an all-invalid stored allowed domain list non-empty so SSO still rejects every domain', async () => {+ const executor = new CountingInMemoryCassandraQueryExecutor();+ setCassandraQueryExecutorForTesting(executor);+ const kvProvider = new MockKVProvider();+ const repository = createRepository(kvProvider);++ await repository.setConfig('sso_allowed_domains', JSON.stringify(['[email protected]', 'bad/domain']));++ const domains = (await repository.getSsoConfig()).allowedEmailDomains;+ expect(domains.length).toBeGreaterThan(0);+ expect(domains).not.toContain('example.com');+ });+it('returns the default voice noise suppression config when the key is absent', async () => {const executor = new CountingInMemoryCassandraQueryExecutor();setCassandraQueryExecutorForTesting(executor);diff --git a/fluxer_api/src/api/instance/InstanceConfigRepository.ts b/fluxer_api/src/api/instance/InstanceConfigRepository.tsindex 4442560a0..d66fba5d8 100644--- a/fluxer_api/src/api/instance/InstanceConfigRepository.ts+++ b/fluxer_api/src/api/instance/InstanceConfigRepository.ts@@ -2,6 +2,12 @@import crypto from 'node:crypto';import type {LimitConfigSnapshot} from '@fluxer/limits/src/LimitTypes';+import {+ InstanceConfigResponse,+ InstanceConfigUpdateRequest,+ type PendingRegistrationResponse,+ type RegistrationUrlResponse,+} from '@fluxer/schema/src/domains/admin/AdminSchemas';import {type GatewayRolloutConfig,GatewayRolloutConfigSchema,@@ -16,28 +22,31 @@ import {} from '@fluxer/schema/src/domains/experiment/ExperimentSchemas';import {type InstanceAppPublic,+ InstanceAppPublicSchema,type InstanceBranding,type InstanceCaptchaProvider,InstanceCaptchaProviderSchema,type InstanceCommunity,type InstanceRegistration,- type InstanceRegistrationMode,- InstanceRegistrationModeSchema,+ InstanceRegistrationSchema,type InstanceServices,type InstanceSetup,} from '@fluxer/schema/src/domains/instance/InstanceSchemas';-import type {IKVProvider, IKVSubscription} from '@pkgs/kv_client/src/IKVProvider';+import {normalizeString, SnowflakeType} from '@fluxer/schema/src/primitives/SchemaPrimitives';+import type {IKVProvider} from '@pkgs/kv_client/src/IKVProvider';+import {z} from 'zod';import {Config} from '../Config';import type {APIConfig, BlueskyOAuthConfig, BlueskyOAuthKeyConfig} from '../config/APIConfig';-import {sanitizeLimitConfigForInstance} from '../constants/LimitConfig';import {fetchMany, fetchOne, upsertOne} from '../database/CassandraQueryExecution';import type {InstanceConfigurationRow} from '../database/types/InstanceConfigTypes';import {Logger} from '../Logger';+import {isLimitConfigSnapshot} from '../limits/LimitConfigValidation';import {resolveDeferredPhoneGateEnabled, setCachedDeferredPhoneGateEnabled} from '../risk/DeferredPhoneGateCache';import {InstanceConfiguration} from '../Tables';import {DEFAULT_DECAY_CONSTANTS, DEFAULT_RENEWAL_CONSTANTS} from '../utils/AttachmentDecay';-import {isJsonRecord, parseJsonArray, parseJsonRecord} from '../utils/JsonBoundaryUtils';+import {isJsonRecord} from '../utils/JsonBoundaryUtils';import {getDefaultDateOfBirthCollection, setCachedDateOfBirthCollection} from './DateOfBirthCollectionCache';+import {InstanceConfigCache} from './InstanceConfigCache';import {normalizeSsoAllowedEmailDomains} from './SsoConfigValidation';const GATEWAY_ROLLOUT_CONFIG_KEY = 'gateway_rollout_config';@@ -49,22 +58,12 @@ const REGISTRATION_PENDING_APPROVALS_KEY = 'registration_pending_approvals';const APP_PUBLIC_CONFIG_KEY = 'app_public_config';const ADMIN_BOOTSTRAP_KEY = 'admin_bootstrapped';const INSTANCE_POLICY_CONFIG_KEY = 'instance_policy_config';+const LIMIT_CONFIG_KEY = 'limit_config';const INSTANCE_INTEGRATIONS_CONFIG_KEY = 'instance_integrations_config';const INSTANCE_MEDIA_CONFIG_KEY = 'instance_media_config';export const INSTANCE_CONFIG_REFRESH_CHANNEL = 'instance-config-refresh';export const REGISTRATION_PENDING_APPROVAL_TRAIT = 'registration_pending_approval';export const REGISTRATION_REJECTED_TRAIT = 'registration_rejected';-const DEFAULT_GATEWAY_ROLLOUT_CONFIG: GatewayRolloutConfig = {- session_rollout_percentage: 100,- session_rollout_mode: 'modulo',- guild_rollout_percentage: 100,- rpc_request_timeout_ms: 10000,- max_concurrent_session_starts: 512,- max_concurrent_guild_starts: 256,- gateway_dispatch_relay_shards: 32,- gateway_dispatch_relay_max_queue: 50000,- voice_e2ee_scope: 'guild_feature_only',-};export type InstanceRegistrationConfig = InstanceRegistration;@@ -74,6 +73,11 @@ interface InstanceAppPublicConfig extends Omit<InstanceAppPublic, 'setup'> {export type InstancePremiumMode = 'mirror' | 'everyone';+interface LimitConfigInputs {+ config: LimitConfigSnapshot | null;+ premiumMode: InstancePremiumMode;+}+export interface InstancePolicyConfig {single_community_enabled: boolean;single_community_guild_id: string | null;@@ -258,34 +262,13 @@ interface InstanceMediaConfigPatch {attachment_decay?: Partial<InstanceAttachmentDecayConfig>;}-export interface InstanceRegistrationUrl {- id: string;- label: string | null;+export interface InstanceRegistrationUrl extends RegistrationUrlResponse {code_hash: string;- created_by_user_id: string;- created_at: string;- expires_at: string | null;- max_uses: number | null;- use_count: number;- revoked_at: string | null;- approval_required: boolean;- last_used_at: string | null;- last_used_by_user_id: string | null;-}--type InstanceRegistrationUrlPublic = Omit<InstanceRegistrationUrl, 'code_hash'>;--interface InstancePendingRegistration {- user_id: string;- username: string;- discriminator: number;- global_name: string | null;- email: string | null;- requested_at: string;- registration_url_id: string | null;- client_ip: string | null;}+type InstanceRegistrationUrlPublic = RegistrationUrlResponse;+type InstancePendingRegistration = PendingRegistrationResponse;+const DEFAULT_REGISTRATION_CONFIG: InstanceRegistrationConfig = {mode: 'open',admin_registration_urls_enabled: true,@@ -295,44 +278,44 @@ const FETCH_CONFIG_QUERY = InstanceConfiguration.selectCql({limit: 1,});const FETCH_ALL_CONFIG_QUERY = InstanceConfiguration.selectCql();+const FETCH_LIMIT_CONFIG_INPUTS_QUERY = InstanceConfiguration.selectCql({+ where: InstanceConfiguration.where.in('key', 'keys'),+});-function isStringArray(value: unknown): value is Array<string> {- return Array.isArray(value) && value.every((entry) => typeof entry === 'string');-}--function isRegistrationMode(value: unknown): value is InstanceRegistrationMode {- return InstanceRegistrationModeSchema.safeParse(value).success;-}--function normalizeNullableString(value: unknown): string | null {- return typeof value === 'string' && value.trim().length > 0 ? value : null;+function parseStoredLimitConfig(raw: string | null): LimitConfigSnapshot | null {+ if (raw === null) return null;+ let parsed: unknown;+ try {+ parsed = JSON.parse(raw);+ } catch (error) {+ Logger.error({error}, 'Stored limit configuration is not valid JSON, falling back to default limits');+ return null;+ }+ if (!isLimitConfigSnapshot(parsed)) {+ Logger.error('Stored limit configuration has an invalid shape, falling back to default limits');+ return null;+ }+ return parsed;}-function normalizePublicString(value: unknown): string | null {+function normalizeOptionalString(value: unknown): string | null {return typeof value === 'string' && value.trim().length > 0 ? value.trim() : null;}-function normalizeOptionalPublicString(- value: Record<string, unknown>,- key: string,- fallback: string | null,-): string | null {- if (!Object.hasOwn(value, key)) {- return fallback;- }- return normalizePublicString(value[key]);+function normalizeOptionalPublicString(value: string | null | undefined, fallback: string | null): string | null {+ return value === undefined ? fallback : normalizeOptionalString(value);}function getDefaultAppPublicConfig(): InstanceAppPublicConfig {return {branding: {product_name: Config.instance.branding.productName || 'Fluxer',- icon_url: normalizePublicString(Config.instance.branding.iconUrl),- symbol_url: normalizePublicString(Config.instance.branding.symbolUrl),- logo_url: normalizePublicString(Config.instance.branding.logoUrl),- wordmark_url: normalizePublicString(Config.instance.branding.wordmarkUrl),- favicon_url: normalizePublicString(Config.instance.branding.faviconUrl),- theme_color: normalizePublicString(Config.instance.branding.themeColor),+ icon_url: normalizeOptionalString(Config.instance.branding.iconUrl),+ symbol_url: normalizeOptionalString(Config.instance.branding.symbolUrl),+ logo_url: normalizeOptionalString(Config.instance.branding.logoUrl),+ wordmark_url: normalizeOptionalString(Config.instance.branding.wordmarkUrl),+ favicon_url: normalizeOptionalString(Config.instance.branding.faviconUrl),+ theme_color: normalizeOptionalString(Config.instance.branding.themeColor),},setup: {configured: !Config.instance.selfHosted || Config.instance.setup.configured,@@ -347,272 +330,355 @@ function getDefaultAppPublicConfig(): InstanceAppPublicConfig {};}-function parseAppPublicConfig(raw: string): InstanceAppPublicConfig {+type StoredConfigSection =+ | 'app public'+ | 'gateway rollout'+ | 'voice noise suppression'+ | 'experiment delivery'+ | 'instance policy'+ | 'integrations'+ | 'media'+ | 'registration'+ | 'registration URLs'+ | 'pending registrations'+ | 'SSO flags'+ | 'SSO allowed domains';++function parseStoredConfigValue(raw: string | null, section: StoredConfigSection): unknown {+ if (raw === null) return {};try {- const parsed: unknown = JSON.parse(raw);- return normalizeAppPublicConfig(parsed);- } catch (error) {- Logger.warn({error}, 'Invalid app public config JSON, returning defaults');- return getDefaultAppPublicConfig();+ return JSON.parse(raw);+ } catch {+ throw new Error(`Stored ${section} configuration is not valid JSON`);}}-function normalizeAppPublicConfig(value: unknown): InstanceAppPublicConfig {- const defaults = getDefaultAppPublicConfig();- if (!isJsonRecord(value)) {- return defaults;- }- const branding = isJsonRecord(value.branding) ? value.branding : {};- const setup = isJsonRecord(value.setup) ? value.setup : {};- const legal = isJsonRecord(value.legal) ? value.legal : {};- const registration = isJsonRecord(value.registration) ? value.registration : {};- return {- branding: {- product_name: normalizePublicString(branding.product_name) ?? defaults.branding.product_name,- icon_url: normalizeOptionalPublicString(branding, 'icon_url', defaults.branding.icon_url),- symbol_url: normalizeOptionalPublicString(branding, 'symbol_url', defaults.branding.symbol_url),- logo_url: normalizeOptionalPublicString(branding, 'logo_url', defaults.branding.logo_url),- wordmark_url: normalizeOptionalPublicString(branding, 'wordmark_url', defaults.branding.wordmark_url),- favicon_url: normalizeOptionalPublicString(branding, 'favicon_url', defaults.branding.favicon_url),- theme_color: normalizeOptionalPublicString(branding, 'theme_color', defaults.branding.theme_color),- },- setup: {- configured: typeof setup.configured === 'boolean' ? setup.configured : defaults.setup.configured,- },- legal: {- terms_url: normalizeOptionalPublicString(legal, 'terms_url', defaults.legal.terms_url),- privacy_url: normalizeOptionalPublicString(legal, 'privacy_url', defaults.legal.privacy_url),- },- registration: {- collect_date_of_birth:- typeof registration.collect_date_of_birth === 'boolean'- ? registration.collect_date_of_birth- : defaults.registration.collect_date_of_birth,- },- };+function describeInvalidFields(issues: ReadonlyArray<{path: ReadonlyArray<PropertyKey>}>, index?: number): string {+ const maxReportedIssues = 8;+ const invalidFields = new Set(+ issues.slice(0, maxReportedIssues).map((issue) => {+ const path = index === undefined ? issue.path : [index, ...issue.path];+ return path.length === 0 ? '<root>' : path.join('.');+ }),+ );+ const suffix = issues.length > maxReportedIssues ? ', ...' : '';+ return `${[...invalidFields].join(', ')}${suffix}`;}-const DEFAULT_INSTANCE_POLICY_CONFIG: InstancePolicyConfig = {- single_community_enabled: false,- single_community_guild_id: null,- direct_messages_disabled: false,- direct_messages_locked: false,- premium_mode: 'everyone',- gif_enabled: null,- youtube_enabled: null,- bluesky_enabled: null,- deferred_phone_gate_enabled: false,- deferred_phone_gate_window_hours: 6,- deferred_phone_gate_member_threshold: 50,-};+function validateStoredConfig<T>(+ schema: z.ZodType<T>,+ value: unknown,+ section: StoredConfigSection,+ index?: number,+): T {+ const result = schema.safeParse(value);+ if (!result.success) {+ throw new Error(+ `Stored ${section} configuration has invalid fields: ${describeInvalidFields(result.error.issues, index)}`,+ );+ }+ return result.data;+}-function isPremiumMode(value: unknown): value is InstancePremiumMode {- return value === 'mirror' || value === 'everyone';+function removeStoredPaths(value: unknown, paths: ReadonlyArray<ReadonlyArray<PropertyKey>>): void {+ const arrays = new Set<Array<unknown>>();+ for (const path of paths) {+ let parent: unknown = value;+ for (const key of path.slice(0, -1)) {+ if (typeof parent !== 'object' || parent === null) break;+ parent = (parent as Record<PropertyKey, unknown>)[key];+ }+ if (typeof parent !== 'object' || parent === null) continue;+ delete (parent as Record<PropertyKey, unknown>)[path.at(-1)!];+ if (Array.isArray(parent)) arrays.add(parent);+ }+ for (const array of arrays) {+ array.splice(0, array.length, ...array.filter(() => true));+ }}-function normalizeNullableBoolean(value: unknown): boolean | null {- return typeof value === 'boolean' ? value : null;+function salvageStoredConfig<T>(schema: z.ZodType<T>, value: unknown, section: StoredConfigSection): T {+ const strict = schema.safeParse(value);+ if (strict.success) return strict.data;+ Logger.error(+ {section, invalidFields: describeInvalidFields(strict.error.issues)},+ 'Invalid stored instance configuration, falling back to defaults for the invalid fields',+ );+ const signature = (issues: ReadonlyArray<{path: ReadonlyArray<PropertyKey>}>) =>+ issues.map((issue) => issue.path.join('.')).join('|');+ const salvaged = structuredClone(value);+ let issues = strict.error.issues;+ let trim = 0;+ for (let attempt = 0; attempt < 64; attempt++) {+ const paths = issues.map((issue) => issue.path.slice(0, Math.max(0, issue.path.length - trim)));+ if (paths.some((path) => path.length === 0)) break;+ removeStoredPaths(salvaged, paths);+ const result = schema.safeParse(salvaged);+ if (result.success) return result.data;+ trim = signature(result.error.issues) === signature(issues) ? trim + 1 : 0;+ issues = result.error.issues;+ }+ return schema.parse({});}-function normalizePositiveNumber(value: unknown, fallback: number): number {- if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) {- return fallback;- }- return value;+function parseStoredConfig<T>(schema: z.ZodType<T>, raw: string | null, section: StoredConfigSection): T {+ return validateStoredConfig(schema, parseStoredConfigValue(raw, section), section);}-function normalizeInstancePolicyConfig(value: unknown): InstancePolicyConfig {- if (!isJsonRecord(value)) {- return {...DEFAULT_INSTANCE_POLICY_CONFIG};+function readStoredConfigOrDefault<T>(section: StoredConfigSection, decode: () => T, fallback: () => T): T {+ try {+ return decode();+ } catch (error) {+ Logger.error({error, section}, 'Invalid stored instance configuration, falling back to defaults');+ return fallback();}- return {- single_community_enabled: value.single_community_enabled === true,- single_community_guild_id: normalizeNullableString(value.single_community_guild_id),- direct_messages_disabled: value.direct_messages_disabled === true,- direct_messages_locked: value.direct_messages_locked === true,- premium_mode: isPremiumMode(value.premium_mode) ? value.premium_mode : DEFAULT_INSTANCE_POLICY_CONFIG.premium_mode,- gif_enabled: normalizeNullableBoolean(value.gif_enabled),- youtube_enabled: normalizeNullableBoolean(value.youtube_enabled),- bluesky_enabled: normalizeNullableBoolean(value.bluesky_enabled),- deferred_phone_gate_enabled: value.deferred_phone_gate_enabled === true,- deferred_phone_gate_window_hours: normalizePositiveNumber(- value.deferred_phone_gate_window_hours,- DEFAULT_INSTANCE_POLICY_CONFIG.deferred_phone_gate_window_hours,- ),- deferred_phone_gate_member_threshold: normalizePositiveNumber(- value.deferred_phone_gate_member_threshold,- DEFAULT_INSTANCE_POLICY_CONFIG.deferred_phone_gate_member_threshold,- ),- };}-const DEFAULT_INSTANCE_INTEGRATIONS_CONFIG: InstanceIntegrationsConfig = {- gif: {- klipy_api_key: null,- },- youtube: {- api_key: null,- },- captcha: {- provider: null,- hcaptcha_site_key: null,- hcaptcha_secret_key: null,- turnstile_site_key: null,- turnstile_secret_key: null,- },- email: {- enabled: null,- provider: null,- from_email: null,- from_name: null,- smtp: {- host: null,- port: null,- username: null,- password: null,- secure: null,- },- disable_new_ip_authorization: null,- },- bluesky: {- enabled: null,- client_name: null,- client_uri: null,- logo_uri: null,- tos_uri: null,- policy_uri: null,- keys: [],- },-};--const DEFAULT_INSTANCE_ATTACHMENT_DECAY_CONFIG: InstanceAttachmentDecayConfig = {- enabled: null,- min_size_mb: null,- max_size_mb: null,- max_eligible_size_mb: null,- min_lifetime_days: null,- max_lifetime_days: null,- curve: null,- renew_threshold_days: null,- renew_window_days: null,-};+function parseStoredConfigOrDefault<T>(schema: z.ZodType<T>, raw: string | null, section: StoredConfigSection): T {+ return readStoredConfigOrDefault(+ section,+ () => parseStoredConfig(schema, raw, section),+ () => parseStoredConfig(schema, null, section),+ );+}-const DEFAULT_INSTANCE_MEDIA_CONFIG: InstanceMediaConfig = {- attachment_decay: DEFAULT_INSTANCE_ATTACHMENT_DECAY_CONFIG,-};+function readStoredConfigValue(raw: string | null, section: StoredConfigSection): unknown {+ return readStoredConfigOrDefault(+ section,+ () => parseStoredConfigValue(raw, section),+ () => ({}),+ );+}-function isCaptchaProvider(value: unknown): value is InstanceCaptchaProvider {- return InstanceCaptchaProviderSchema.safeParse(value).success;+function checkStoredConfig(section: StoredConfigSection, decode: () => unknown): void {+ readStoredConfigOrDefault(section, decode, () => null);}-function isEmailProvider(value: unknown): value is InstanceEmailProvider {- return value === 'smtp' || value === 'none';+function decodeGatewayRolloutConfig(value: unknown): GatewayRolloutConfig {+ const input =+ isJsonRecord(value) &&+ !Object.hasOwn(value, 'rpc_request_timeout_ms') &&+ Object.hasOwn(value, 'nats_request_timeout_ms')+ ? {...value, rpc_request_timeout_ms: value.nats_request_timeout_ms}+ : value;+ return validateStoredConfig(GatewayRolloutConfigSchema, input, 'gateway rollout');}-function normalizeSecretString(value: unknown): string | null {- return typeof value === 'string' && value.trim().length > 0 ? value.trim() : null;+function parseStoredGatewayRolloutConfig(raw: string | null): GatewayRolloutConfig {+ return decodeGatewayRolloutConfig(parseStoredConfigValue(raw, 'gateway rollout'));}-function secretIsSet(value: unknown): boolean {- return typeof value === 'string' && value.trim().length > 0;+function parseStoredVoiceNoiseSuppressionConfig(raw: string | null): VoiceNoiseSuppressionConfig {+ return parseStoredConfigOrDefault(VoiceNoiseSuppressionConfigSchema, raw, 'voice noise suppression');}-function normalizeNullablePort(value: unknown): number | null {- if (typeof value !== 'number' || !Number.isInteger(value) || value < 1 || value > 65535) return null;- return value;+function parseStoredExperimentDeliveryConfig(raw: string | null): ExperimentDeliveryConfig {+ return parseStoredConfigOrDefault(ExperimentDeliveryConfigSchema, raw, 'experiment delivery');}-function normalizeNullablePositiveNumber(value: unknown): number | null {- if (typeof value !== 'number' || !Number.isFinite(value) || value <= 0) return null;- return value;+function validateStoredCollection<T>(schema: z.ZodType<T>, value: unknown, section: StoredConfigSection): Array<T> {+ if (!Array.isArray(value)) {+ throw new Error(`Stored ${section} configuration must be an array`);+ }+ return Array.from(value, (entry, index) => validateStoredConfig(schema, entry, section, index));}-function normalizeNullablePositiveInteger(value: unknown): number | null {- if (typeof value !== 'number' || !Number.isInteger(value) || value < 1) return null;- return value;+function parseStoredCollection<T>(schema: z.ZodType<T>, raw: string | null, section: StoredConfigSection): Array<T> {+ return raw === null ? [] : validateStoredCollection(schema, parseStoredConfigValue(raw, section), section);}-function normalizeNullableCurve(value: unknown): number | null {- if (typeof value !== 'number' || !Number.isFinite(value) || value < 0 || value > 1) return null;- return value;+const StoredInstanceAppPublicSchema = InstanceAppPublicSchema.extend({+ branding: InstanceAppPublicSchema.shape.branding.partial().optional(),+ setup: InstanceAppPublicSchema.shape.setup.pick({configured: true}).partial().optional(),+ legal: InstanceAppPublicSchema.shape.legal.partial().optional(),+ registration: InstanceAppPublicSchema.shape.registration.partial().optional(),+});++function parseStoredAppPublicConfig(raw: string | null): InstanceAppPublicConfig {+ return buildAppPublicConfig(+ salvageStoredConfig(StoredInstanceAppPublicSchema, readStoredConfigValue(raw, 'app public'), 'app public'),+ );}-function normalizeBlueskyKey(value: unknown): InstanceBlueskyKeyIntegrationConfig | null {- if (!isJsonRecord(value)) return null;- const kid = normalizePublicString(value.kid);- if (!kid) return null;- return {- kid,- private_key: normalizeSecretString(value.private_key),- };+function decodeAppPublicConfig(value: unknown): InstanceAppPublicConfig {+ return buildAppPublicConfig(validateStoredConfig(StoredInstanceAppPublicSchema, value, 'app public'));}-function normalizeInstanceIntegrationsConfig(value: unknown): InstanceIntegrationsConfig {- const defaults = DEFAULT_INSTANCE_INTEGRATIONS_CONFIG;- if (!isJsonRecord(value)) {- return structuredClone(defaults);- }- const gif = isJsonRecord(value.gif) ? value.gif : {};- const youtube = isJsonRecord(value.youtube) ? value.youtube : {};- const captcha = isJsonRecord(value.captcha) ? value.captcha : {};- const email = isJsonRecord(value.email) ? value.email : {};- const smtp = isJsonRecord(email.smtp) ? email.smtp : {};- const bluesky = isJsonRecord(value.bluesky) ? value.bluesky : {};- const blueskyKeys = Array.isArray(bluesky.keys)- ? bluesky.keys.flatMap((entry) => {- const normalized = normalizeBlueskyKey(entry);- return normalized ? [normalized] : [];- })- : defaults.bluesky.keys;+function buildAppPublicConfig(config: z.infer<typeof StoredInstanceAppPublicSchema>): InstanceAppPublicConfig {+ const defaults = getDefaultAppPublicConfig();+ const {branding = {}, setup = {}, legal = {}, registration = {}} = config;return {- gif: {- klipy_api_key: normalizeSecretString(gif.klipy_api_key),- },- youtube: {- api_key: normalizeSecretString(youtube.api_key),+ branding: {+ product_name: normalizeOptionalString(branding.product_name) ?? defaults.branding.product_name,+ icon_url: normalizeOptionalPublicString(branding.icon_url, defaults.branding.icon_url),+ symbol_url: normalizeOptionalPublicString(branding.symbol_url, defaults.branding.symbol_url),+ logo_url: normalizeOptionalPublicString(branding.logo_url, defaults.branding.logo_url),+ wordmark_url: normalizeOptionalPublicString(branding.wordmark_url, defaults.branding.wordmark_url),+ favicon_url: normalizeOptionalPublicString(branding.favicon_url, defaults.branding.favicon_url),+ theme_color: normalizeOptionalPublicString(branding.theme_color, defaults.branding.theme_color),},- captcha: {- provider: isCaptchaProvider(captcha.provider) ? captcha.provider : defaults.captcha.provider,- hcaptcha_site_key: normalizeSecretString(captcha.hcaptcha_site_key),- hcaptcha_secret_key: normalizeSecretString(captcha.hcaptcha_secret_key),- turnstile_site_key: normalizeSecretString(captcha.turnstile_site_key),- turnstile_secret_key: normalizeSecretString(captcha.turnstile_secret_key),+ setup: {+ configured: setup.configured ?? defaults.setup.configured,},- email: {- enabled: normalizeNullableBoolean(email.enabled),- provider: isEmailProvider(email.provider) ? email.provider : defaults.email.provider,- from_email: normalizePublicString(email.from_email),- from_name: normalizePublicString(email.from_name),- smtp: {- host: normalizePublicString(smtp.host),- port: normalizeNullablePort(smtp.port),- username: normalizePublicString(smtp.username),- password: normalizeSecretString(smtp.password),- secure: normalizeNullableBoolean(smtp.secure),- },- disable_new_ip_authorization: normalizeNullableBoolean(email.disable_new_ip_authorization),+ legal: {+ terms_url: normalizeOptionalPublicString(legal.terms_url, defaults.legal.terms_url),+ privacy_url: normalizeOptionalPublicString(legal.privacy_url, defaults.legal.privacy_url),},- bluesky: {- enabled: normalizeNullableBoolean(bluesky.enabled),- client_name: normalizePublicString(bluesky.client_name),- client_uri: normalizePublicString(bluesky.client_uri),- logo_uri: normalizePublicString(bluesky.logo_uri),- tos_uri: normalizePublicString(bluesky.tos_uri),- policy_uri: normalizePublicString(bluesky.policy_uri),- keys: blueskyKeys,+ registration: {+ collect_date_of_birth: registration.collect_date_of_birth ?? defaults.registration.collect_date_of_birth,},};}-function normalizeInstanceAttachmentDecayConfig(value: unknown): InstanceAttachmentDecayConfig {- if (!isJsonRecord(value)) {- return {...DEFAULT_INSTANCE_ATTACHMENT_DECAY_CONFIG};- }- const minSizeMb = normalizeNullablePositiveNumber(value.min_size_mb);- let maxSizeMb = normalizeNullablePositiveNumber(value.max_size_mb);- let maxEligibleSizeMb = normalizeNullablePositiveNumber(value.max_eligible_size_mb);- const minLifetimeDays = normalizeNullablePositiveInteger(value.min_lifetime_days);- let maxLifetimeDays = normalizeNullablePositiveInteger(value.max_lifetime_days);+const InstancePolicyUpdateSchema = InstanceConfigUpdateRequest.shape.policy.unwrap().unwrap();+const InstancePolicyServiceUpdateSchema = InstancePolicyUpdateSchema.shape.services.unwrap().unwrap();+const InstancePolicyPhoneGateUpdateSchema = InstancePolicyUpdateSchema.shape.deferred_phone_gate.unwrap().unwrap();+const StoredSnowflakeStringSchema = z+ .string()+ .refine((value) => value.length <= 19 && !/\D/.test(value) && SnowflakeType.safeParse(value).success);+const StoredInstancePolicySchema = z.object({+ single_community_enabled: InstancePolicyUpdateSchema.shape.single_community_enabled.default(false),+ single_community_guild_id: StoredSnowflakeStringSchema.nullable().default(null),+ direct_messages_disabled: InstancePolicyUpdateSchema.shape.direct_messages_disabled.default(false),+ direct_messages_locked: z.boolean().default(false),+ premium_mode: InstancePolicyUpdateSchema.shape.premium_mode.default('everyone'),+ gif_enabled: InstancePolicyServiceUpdateSchema.shape.gif_enabled.default(null),+ youtube_enabled: InstancePolicyServiceUpdateSchema.shape.youtube_enabled.default(null),+ bluesky_enabled: InstancePolicyServiceUpdateSchema.shape.bluesky_enabled.default(null),+ deferred_phone_gate_enabled: InstancePolicyPhoneGateUpdateSchema.shape.enabled.default(false),+ deferred_phone_gate_window_hours: InstancePolicyPhoneGateUpdateSchema.shape.window_hours.default(6),+ deferred_phone_gate_member_threshold: InstancePolicyPhoneGateUpdateSchema.shape.member_threshold.default(50),+}) satisfies z.ZodType<InstancePolicyConfig>;++function decodeInstancePolicyConfig(value: unknown): InstancePolicyConfig {+ return validateStoredConfig(StoredInstancePolicySchema, value, 'instance policy');+}++function parseStoredInstancePolicyConfig(raw: string | null): InstancePolicyConfig {+ return salvageStoredConfig(+ StoredInstancePolicySchema,+ readStoredConfigValue(raw, 'instance policy'),+ 'instance policy',+ );+}++const IntegrationUpdateSchema = InstanceConfigUpdateRequest.shape.integrations.unwrap().unwrap();+const EmailIntegrationUpdateSchema = IntegrationUpdateSchema.shape.email.unwrap().unwrap();+const SmtpIntegrationUpdateSchema = EmailIntegrationUpdateSchema.shape.smtp.unwrap().unwrap();+const StoredIntegrationStringSchema = z+ .string()+ .trim()+ .nullable()+ .default(null)+ .transform((value) => value || null);+const StoredNullableBooleanSchema = z.boolean().nullable().default(null);+const StoredBlueskyKeysSchema = z+ .array(z.object({kid: z.string().trim().min(1), private_key: StoredIntegrationStringSchema}))+ .default([])+ .refine((keys) => {+ const activeIds = new Set<string>();+ for (const key of keys) {+ if (key.private_key === null) continue;+ if (activeIds.has(key.kid)) return false;+ activeIds.add(key.kid);+ }+ return true;+ });+const StoredInstanceIntegrationsSchema = z.object({+ gif: z.object({klipy_api_key: StoredIntegrationStringSchema}).prefault({}),+ youtube: z.object({api_key: StoredIntegrationStringSchema}).prefault({}),+ captcha: z+ .object({+ provider: InstanceCaptchaProviderSchema.nullable().default(null),+ hcaptcha_site_key: StoredIntegrationStringSchema,+ hcaptcha_secret_key: StoredIntegrationStringSchema,+ turnstile_site_key: StoredIntegrationStringSchema,+ turnstile_secret_key: StoredIntegrationStringSchema,+ })+ .prefault({}),+ email: z+ .object({+ enabled: StoredNullableBooleanSchema,+ provider: EmailIntegrationUpdateSchema.shape.provider.default(null),+ from_email: StoredIntegrationStringSchema,+ from_name: StoredIntegrationStringSchema,+ smtp: z+ .object({+ host: StoredIntegrationStringSchema,+ port: SmtpIntegrationUpdateSchema.shape.port.default(null),+ username: StoredIntegrationStringSchema,+ password: StoredIntegrationStringSchema,+ secure: StoredNullableBooleanSchema,+ })+ .prefault({}),+ disable_new_ip_authorization: StoredNullableBooleanSchema,+ })+ .prefault({}),+ bluesky: z+ .object({+ enabled: StoredNullableBooleanSchema,+ client_name: StoredIntegrationStringSchema,+ client_uri: StoredIntegrationStringSchema,+ logo_uri: StoredIntegrationStringSchema,+ tos_uri: StoredIntegrationStringSchema,+ policy_uri: StoredIntegrationStringSchema,+ keys: StoredBlueskyKeysSchema,+ })+ .prefault({}),+}) satisfies z.ZodType<InstanceIntegrationsConfig>;++function decodeInstanceIntegrationsConfig(value: unknown): InstanceIntegrationsConfig {+ return validateStoredConfig(StoredInstanceIntegrationsSchema, value, 'integrations');+}++function parseStoredInstanceIntegrationsConfig(raw: string | null): InstanceIntegrationsConfig {+ return salvageStoredConfig(+ StoredInstanceIntegrationsSchema,+ readStoredConfigValue(raw, 'integrations'),+ 'integrations',+ );+}++function secretIsSet(value: unknown): boolean {+ return typeof value === 'string' && value.trim().length > 0;+}++const AttachmentDecayUpdateSchema = InstanceConfigUpdateRequest.shape.media+ .unwrap()+ .unwrap()+ .shape.attachment_decay.unwrap()+ .unwrap();+const StoredAttachmentDecaySchema = z+ .object({+ enabled: AttachmentDecayUpdateSchema.shape.enabled.default(null),+ min_size_mb: AttachmentDecayUpdateSchema.shape.min_size_mb.default(null),+ max_size_mb: AttachmentDecayUpdateSchema.shape.max_size_mb.default(null),+ max_eligible_size_mb: AttachmentDecayUpdateSchema.shape.max_eligible_size_mb.default(null),+ min_lifetime_days: AttachmentDecayUpdateSchema.shape.min_lifetime_days.default(null),+ max_lifetime_days: AttachmentDecayUpdateSchema.shape.max_lifetime_days.default(null),+ curve: AttachmentDecayUpdateSchema.shape.curve.default(null),+ renew_threshold_days: AttachmentDecayUpdateSchema.shape.renew_threshold_days.default(null),+ renew_window_days: AttachmentDecayUpdateSchema.shape.renew_window_days.default(null),+ })+ .transform(normalizeAttachmentDecayBounds)+ .refine(+ (value) => {+ const minSizeMb = value.min_size_mb ?? DEFAULT_DECAY_CONSTANTS.MIN_MB;+ const maxSizeMb = computeAttachmentDecayMaxSize(minSizeMb, value.max_size_mb ?? DEFAULT_DECAY_CONSTANTS.MAX_MB);+ return Number.isFinite(maxSizeMb) && maxSizeMb > minSizeMb;+ },+ {path: ['min_size_mb']},+ );+const StoredInstanceMediaSchema = z.object({+ attachment_decay: StoredAttachmentDecaySchema.prefault({}),+}) satisfies z.ZodType<InstanceMediaConfig>;++function normalizeAttachmentDecayBounds(value: InstanceAttachmentDecayConfig): InstanceAttachmentDecayConfig {+ const minSizeMb = value.min_size_mb;+ let maxSizeMb = value.max_size_mb;+ let maxEligibleSizeMb = value.max_eligible_size_mb;+ const minLifetimeDays = value.min_lifetime_days;+ let maxLifetimeDays = value.max_lifetime_days;if (minSizeMb !== null && maxSizeMb !== null && maxSizeMb <= minSizeMb) {maxSizeMb = null;}@@ -623,25 +689,27 @@ function normalizeInstanceAttachmentDecayConfig(value: unknown): InstanceAttachmmaxLifetimeDays = null;}return {- enabled: normalizeNullableBoolean(value.enabled),- min_size_mb: minSizeMb,+ ...value,max_size_mb: maxSizeMb,max_eligible_size_mb: maxEligibleSizeMb,- min_lifetime_days: minLifetimeDays,max_lifetime_days: maxLifetimeDays,- curve: normalizeNullableCurve(value.curve),- renew_threshold_days: normalizeNullablePositiveInteger(value.renew_threshold_days),- renew_window_days: normalizeNullablePositiveInteger(value.renew_window_days),};}-function normalizeInstanceMediaConfig(value: unknown): InstanceMediaConfig {- if (!isJsonRecord(value)) {- return structuredClone(DEFAULT_INSTANCE_MEDIA_CONFIG);- }- return {- attachment_decay: normalizeInstanceAttachmentDecayConfig(value.attachment_decay),- };+function computeAttachmentDecayMaxSize(minSizeMb: number, configuredMaxSizeMb: number): number {+ if (configuredMaxSizeMb > minSizeMb) return configuredMaxSizeMb;+ const incrementedMin = minSizeMb + 1;+ const largerMin =+ incrementedMin > minSizeMb ? incrementedMin : Math.min(Number.MAX_VALUE, minSizeMb + minSizeMb * Number.EPSILON);+ return Math.max(DEFAULT_DECAY_CONSTANTS.MAX_MB, largerMin);+}++function decodeInstanceMediaConfig(value: unknown): InstanceMediaConfig {+ return validateStoredConfig(StoredInstanceMediaSchema, value, 'media');+}++function parseStoredInstanceMediaConfig(raw: string | null): InstanceMediaConfig {+ return decodeInstanceMediaConfig(parseStoredConfigValue(raw, 'media'));}function hasCompleteSmtpConfig(config: APIConfig['email']): boolean {@@ -655,82 +723,70 @@ function hasCompleteSmtpConfig(config: APIConfig['email']): boolean {);}-function normalizeIsoDateString(value: unknown): string | null {- if (typeof value !== 'string') return null;- const time = Date.parse(value);- return Number.isFinite(time) ? new Date(time).toISOString() : null;-}--function normalizePositiveInteger(value: unknown): number | null {- if (typeof value !== 'number' || !Number.isInteger(value) || value < 1) return null;- return value;-}--function normalizeNonNegativeInteger(value: unknown): number {- if (typeof value !== 'number' || !Number.isInteger(value) || value < 0) return 0;- return value;-}+const StoredRegistrationConfigSchema = InstanceRegistrationSchema.extend({+ mode: InstanceRegistrationSchema.shape.mode.default(DEFAULT_REGISTRATION_CONFIG.mode),+ admin_registration_urls_enabled: InstanceRegistrationSchema.shape.admin_registration_urls_enabled.default(+ DEFAULT_REGISTRATION_CONFIG.admin_registration_urls_enabled,+ ),+});-function normalizeRegistrationConfig(value: unknown): InstanceRegistrationConfig {- if (!isJsonRecord(value)) {- return {...DEFAULT_REGISTRATION_CONFIG};- }- const mode = isRegistrationMode(value.mode) ? value.mode : DEFAULT_REGISTRATION_CONFIG.mode;- const adminRegistrationUrlsEnabled =- typeof value.admin_registration_urls_enabled === 'boolean'- ? value.admin_registration_urls_enabled- : typeof value.adminRegistrationUrlsEnabled === 'boolean'- ? value.adminRegistrationUrlsEnabled- : DEFAULT_REGISTRATION_CONFIG.admin_registration_urls_enabled;- return {- mode,- admin_registration_urls_enabled: adminRegistrationUrlsEnabled,- };+function decodeRegistrationConfig(value: unknown): InstanceRegistrationConfig {+ const input =+ isJsonRecord(value) &&+ !Object.hasOwn(value, 'admin_registration_urls_enabled') &&+ Object.hasOwn(value, 'adminRegistrationUrlsEnabled')+ ? {...value, admin_registration_urls_enabled: value.adminRegistrationUrlsEnabled}+ : value;+ return validateStoredConfig(StoredRegistrationConfigSchema, input, 'registration');}-function normalizeRegistrationUrl(value: unknown): InstanceRegistrationUrl | null {- if (!isJsonRecord(value)) return null;- if (- typeof value.id !== 'string' ||- typeof value.code_hash !== 'string' ||- typeof value.created_by_user_id !== 'string'- ) {- return null;- }- const createdAt = normalizeIsoDateString(value.created_at);- if (!createdAt) return null;- return {- id: value.id,- label: normalizeNullableString(value.label),- code_hash: value.code_hash,- created_by_user_id: value.created_by_user_id,- created_at: createdAt,- expires_at: normalizeIsoDateString(value.expires_at),- max_uses: normalizePositiveInteger(value.max_uses),- use_count: normalizeNonNegativeInteger(value.use_count),- revoked_at: normalizeIsoDateString(value.revoked_at),- approval_required: value.approval_required === true,- last_used_at: normalizeIsoDateString(value.last_used_at),- last_used_by_user_id: normalizeNullableString(value.last_used_by_user_id),- };+function parseStoredRegistrationConfig(raw: string | null): InstanceRegistrationConfig {+ return decodeRegistrationConfig(parseStoredConfigValue(raw, 'registration'));}-function normalizePendingRegistration(value: unknown): InstancePendingRegistration | null {- if (!isJsonRecord(value)) return null;- if (typeof value.user_id !== 'string' || typeof value.username !== 'string') return null;- const requestedAt = normalizeIsoDateString(value.requested_at);- if (!requestedAt) return null;- return {- user_id: value.user_id,- username: value.username,- discriminator: typeof value.discriminator === 'number' ? value.discriminator : 0,- global_name: normalizeNullableString(value.global_name),- email: normalizeNullableString(value.email),- requested_at: requestedAt,- registration_url_id: normalizeNullableString(value.registration_url_id),- client_ip: normalizeNullableString(value.client_ip),- };-}+const RegistrationUrlSchema = InstanceConfigResponse.shape.registration.shape.urls.element;+const PendingRegistrationSchema = InstanceConfigResponse.shape.registration.shape.pending_registrations.element;+const StoredRegistrationTimestampSchema = z.iso+ .datetime({offset: true})+ .refine((value) => value === value.trim() && Number.isFinite(Date.parse(value)))+ .transform((value): string => new Date(value).toISOString())+ .pipe(RegistrationUrlSchema.shape.created_at);+const StoredNullableStringSchema = z+ .string()+ .nullable()+ .default(null)+ .transform((value) => (value === null || value.trim().length === 0 ? null : value));+const StoredRegistrationUrlIdSchema = z+ .string()+ .min(1)+ .max(128)+ .refine((value) => normalizeString(value) === value);+const StoredRegistrationUrlSchema = RegistrationUrlSchema.extend({+ id: StoredRegistrationUrlIdSchema,+ label: StoredNullableStringSchema,+ code_hash: z+ .string()+ .length(64)+ .regex(/^[a-f0-9]{64}$/),+ created_by_user_id: StoredSnowflakeStringSchema,+ created_at: StoredRegistrationTimestampSchema,+ expires_at: StoredRegistrationTimestampSchema.nullable().default(null),+ max_uses: RegistrationUrlSchema.shape.max_uses.default(null),+ use_count: RegistrationUrlSchema.shape.use_count.default(0),+ revoked_at: StoredRegistrationTimestampSchema.nullable().default(null),+ approval_required: RegistrationUrlSchema.shape.approval_required.default(false),+ last_used_at: StoredRegistrationTimestampSchema.nullable().default(null),+ last_used_by_user_id: StoredNullableStringSchema.pipe(StoredSnowflakeStringSchema.nullable()),+}) satisfies z.ZodType<InstanceRegistrationUrl>;+const StoredPendingRegistrationSchema = PendingRegistrationSchema.extend({+ user_id: StoredSnowflakeStringSchema,+ discriminator: PendingRegistrationSchema.shape.discriminator.default(0),+ global_name: StoredNullableStringSchema,+ email: StoredNullableStringSchema,+ requested_at: StoredRegistrationTimestampSchema,+ registration_url_id: StoredNullableStringSchema.pipe(StoredRegistrationUrlIdSchema.nullable()),+ client_ip: StoredNullableStringSchema,+}) satisfies z.ZodType<InstancePendingRegistration>;function isRegistrationUrlUsable(registrationUrl: InstanceRegistrationUrl, now: Date): boolean {if (registrationUrl.revoked_at) return false;@@ -744,31 +800,13 @@ function redactRegistrationUrl(registrationUrl: InstanceRegistrationUrl): Instanreturn redacted;}-function isLimitRuleSnapshot(value: unknown): value is LimitConfigSnapshot['rules'][number] {- if (!isJsonRecord(value) || typeof value.id !== 'string' || !isJsonRecord(value.limits)) return false;- const filters = value.filters;- return (- (filters === undefined ||- (isJsonRecord(filters) &&- (filters.traits === undefined || isStringArray(filters.traits)) &&- (filters.guildFeatures === undefined || isStringArray(filters.guildFeatures)))) &&- (value.modifiedFields === undefined || isStringArray(value.modifiedFields))- );-}--function isLimitConfigSnapshot(value: unknown): value is LimitConfigSnapshot {- return (- isJsonRecord(value) &&- (value.version === undefined || typeof value.version === 'number') &&- isStringArray(value.traitDefinitions) &&- Array.isArray(value.rules) &&- value.rules.every(isLimitRuleSnapshot)- );-}--export interface InstanceSsoConfig {+interface InstanceSsoFlags {enabled: boolean;enforced: boolean;+ autoProvision: boolean;+}++export interface InstanceSsoConfig extends InstanceSsoFlags {displayName: string | null;issuer: string | null;authorizationUrl: string | null;@@ -780,53 +818,149 @@ export interface InstanceSsoConfig {clientSecretSet?: boolean;scope: string | null;allowedEmailDomains: Array<string>;- autoProvision: boolean;redirectUri: string | null;}+const MAX_SSO_ALLOWED_DOMAINS = 100;++function readStoredSsoBoolean(+ configs: ReadonlyMap<string, string>,+ key: 'sso_enabled' | 'sso_enforced' | 'sso_auto_provision',+ fallback: boolean,+ options?: {invalidFallback?: boolean; log?: boolean},+): boolean {+ const value = configs.get(key);+ if (value === undefined) return fallback;+ if (value === 'true') return true;+ if (value === 'false') return false;+ if (options?.log) {+ Logger.warn({key}, 'Invalid stored SSO flag, falling back to its default');+ }+ return options?.invalidFallback ?? fallback;+}++function readStoredSsoFlags(configs: ReadonlyMap<string, string>, log = false): InstanceSsoFlags {+ const enabled = readStoredSsoBoolean(configs, 'sso_enabled', false, {log});+ return {+ enabled,+ enforced: readStoredSsoBoolean(configs, 'sso_enforced', enabled, {invalidFallback: false, log}),+ autoProvision: readStoredSsoBoolean(configs, 'sso_auto_provision', true, {log}),+ };+}++function parseStoredSsoAllowedEmailDomains(raw: string | undefined, log = false): Array<string> {+ if (raw === undefined || raw.trim().length === 0) return [];+ let value: unknown;+ try {+ value = JSON.parse(raw);+ } catch {+ value = null;+ }+ const entries: ReadonlyArray<unknown> = Array.isArray(value) ? value : raw.split(',');+ const domains = new Set<string>();+ const unusable = new Set<string>();+ for (const entry of entries) {+ try {+ for (const domain of normalizeSsoAllowedEmailDomains([entry])) {+ domains.add(domain);+ }+ } catch {+ const text = String(entry).trim();+ if (text.length > 0) unusable.add(text);+ }+ }+ if (domains.size === 0 && unusable.size > 0) {+ if (log) {+ Logger.error(+ {unusable: unusable.size},+ 'Every stored SSO allowed email domain is invalid, keeping them so the allowlist still matches nothing',+ );+ }+ return Array.from(unusable).slice(0, MAX_SSO_ALLOWED_DOMAINS);+ }+ if (log && unusable.size > 0) {+ Logger.warn({dropped: unusable.size}, 'Dropped invalid stored SSO allowed email domains');+ }+ if (log && domains.size > MAX_SSO_ALLOWED_DOMAINS) {+ Logger.warn(+ {dropped: domains.size - MAX_SSO_ALLOWED_DOMAINS},+ 'Truncated the stored SSO allowed email domain list to its maximum length',+ );+ }+ return Array.from(domains).slice(0, MAX_SSO_ALLOWED_DOMAINS);+}+export class InstanceConfigRepository {- private readonly pubSubSourceId = crypto.randomUUID();private readonly kvClient: IKVProvider | null;- private configCache: Map<string, string> | null = null;- private cacheInitializationPromise: Promise<void> | null = null;- private refreshPromise: Promise<void> | null = null;- private refreshRequested = false;- private kvSubscription: IKVSubscription | null = null;- private subscriberInitialized = false;- private subscriberInitializationPromise: Promise<boolean> | null = null;- private messageHandler: ((channel: string, message: string) => void) | null = null;+ private configCache: InstanceConfigCache;private effectiveBlueskyConfig: BlueskyOAuthConfig | null = null;private effectiveBlueskyConfigSource: string | null = null;constructor(kvClient: IKVProvider | null = null) {this.kvClient = kvClient;+ this.configCache = this.createConfigCache();+ }++ private createConfigCache(previousShutdown?: Promise<void>): InstanceConfigCache {+ return new InstanceConfigCache(+ {+ provider: this.kvClient,+ channel: INSTANCE_CONFIG_REFRESH_CHANNEL,+ load: () => this.fetchAllConfigsFromDatabase(),+ onRefresh: (snapshot) => this.syncConfigCaches(snapshot),+ },+ previousShutdown,+ );+ }++ async initialize(): Promise<void> {+ const cache = this.configCache;+ const snapshot = await cache.getSnapshot();+ cache.assertActive();+ if (snapshot !== null) return;+ const configs = await this.fetchAllConfigsFromDatabase();+ cache.assertActive();+ this.syncConfigCaches(configs);}async getConfig(key: string): Promise<string | null> {- if (!(await this.ensureCacheReadable())) {- return this.fetchConfigFromDatabase(key);- }- return this.configCache?.get(key) ?? null;+ const cache = this.configCache;+ const snapshot = await cache.getSnapshot();+ cache.assertActive();+ return snapshot === null ? this.fetchConfigFromDatabase(key) : (snapshot.get(key) ?? null);}async getAllConfigs(): Promise<Map<string, string>> {- if (!(await this.ensureCacheReadable())) {- return this.fetchAllConfigsFromDatabase();- }- return new Map(this.configCache ?? []);+ const cache = this.configCache;+ const snapshot = await cache.getSnapshot();+ cache.assertActive();+ return snapshot === null ? this.fetchAllConfigsFromDatabase() : new Map(snapshot);}- async setConfig(key: string, value: string): Promise<void> {- await this.writeConfig(key, value);- this.updateCachedConfigs([[key, value]]);- await this.publishRefresh();+ setConfig(key: string, value: string): Promise<void> {+ return this.setConfigs([[key, value]]);}private async setConfigs(entries: Array<[string, string]>): Promise<void> {if (entries.length === 0) return;- await Promise.all(entries.map(([key, value]) => this.writeConfig(key, value)));- this.updateCachedConfigs(entries);- await this.publishRefresh();+ const cache = this.configCache;+ cache.assertActive();+ const results = await Promise.allSettled(+ entries.map(async ([key, value]) => {+ await this.writeConfig(key, value);+ cache.update(key, value);+ }),+ );+ const errors: Array<unknown> = results.flatMap((result) => (result.status === 'rejected' ? [result.reason] : []));+ if (results.some((result) => result.status === 'fulfilled')) {+ try {+ await this.publishRefresh(cache.sourceId);+ } catch (error) {+ errors.push(error);+ }+ }+ if (errors.length === 1) throw errors[0];+ if (errors.length > 1) throw new AggregateError(errors, 'Failed to write or publish instance config');}private async writeConfig(key: string, value: string): Promise<void> {@@ -855,149 +989,63 @@ export class InstanceConfigRepository {return configs;}- private async ensureCacheReadable(): Promise<boolean> {- if (!this.kvClient) {- return false;- }- if (this.configCache !== null) {- return true;- }- if (!this.cacheInitializationPromise) {- this.cacheInitializationPromise = (async () => {- const subscribed = await this.ensureSubscriberInitialized();- if (!subscribed) {- return;- }- await this.refreshCacheFromDatabase();- })().finally(() => {- this.cacheInitializationPromise = null;- });- }- await this.cacheInitializationPromise;- return this.configCache !== null;- }-- private async ensureSubscriberInitialized(): Promise<boolean> {- if (this.subscriberInitialized) {- return true;- }- if (!this.kvClient) {- return false;- }- if (!this.subscriberInitializationPromise) {- this.subscriberInitializationPromise = this.startSubscriber()- .then(() => true)- .catch((error) => {- Logger.error({error}, 'Failed to subscribe to instance config refresh channel');- this.closeSubscription();- return false;- })- .finally(() => {- this.subscriberInitializationPromise = null;- });- }- return this.subscriberInitializationPromise;- }-- private async startSubscriber(): Promise<void> {- if (!this.kvClient) {- return;- }- const subscription = this.kvClient.duplicate();- this.kvSubscription = subscription;- this.messageHandler = (channel: string, message: string) => {- if (channel !== INSTANCE_CONFIG_REFRESH_CHANNEL) {- return;- }- if (this.isOwnRefreshMessage(message)) {- return;- }- this.refreshCacheFromDatabase().catch((error) => {- Logger.error({error}, 'Failed to refresh instance config cache from pubsub');- });- };- subscription.on('message', this.messageHandler);- await subscription.connect();- await subscription.subscribe(INSTANCE_CONFIG_REFRESH_CHANNEL);- this.subscriberInitialized = true;- }-- private async refreshCacheFromDatabase(): Promise<void> {- if (this.refreshPromise) {- this.refreshRequested = true;- await this.refreshPromise;- return;- }- this.refreshPromise = (async () => {- do {- this.refreshRequested = false;- this.configCache = await this.fetchAllConfigsFromDatabase();- } while (this.refreshRequested);- this.syncDeferredPhoneGateCache(this.configCache.get(INSTANCE_POLICY_CONFIG_KEY) ?? null);- this.syncDateOfBirthCollectionCache(this.configCache.get(APP_PUBLIC_CONFIG_KEY) ?? null);- })().finally(() => {- this.refreshPromise = null;- });- await this.refreshPromise;- }-- private syncDeferredPhoneGateCache(raw: string | null): void {- const policy = raw ? normalizeInstancePolicyConfig(parseJsonRecord(raw)) : {...DEFAULT_INSTANCE_POLICY_CONFIG};+ private syncConfigCaches(snapshot: ReadonlyMap<string, string>): void {+ checkStoredConfig('gateway rollout', () =>+ parseStoredGatewayRolloutConfig(snapshot.get(GATEWAY_ROLLOUT_CONFIG_KEY) ?? null),+ );+ parseStoredVoiceNoiseSuppressionConfig(snapshot.get(VOICE_NOISE_SUPPRESSION_CONFIG_KEY) ?? null);+ parseStoredExperimentDeliveryConfig(snapshot.get(EXPERIMENT_DELIVERY_CONFIG_KEY) ?? null);+ const policy = parseStoredInstancePolicyConfig(snapshot.get(INSTANCE_POLICY_CONFIG_KEY) ?? null);+ checkStoredConfig('registration', () =>+ parseStoredRegistrationConfig(snapshot.get(REGISTRATION_CONFIG_KEY) ?? null),+ );+ checkStoredConfig('registration URLs', () =>+ parseStoredCollection(+ StoredRegistrationUrlSchema,+ snapshot.get(REGISTRATION_URLS_KEY) ?? null,+ 'registration URLs',+ ),+ );+ checkStoredConfig('pending registrations', () =>+ parseStoredCollection(+ StoredPendingRegistrationSchema,+ snapshot.get(REGISTRATION_PENDING_APPROVALS_KEY) ?? null,+ 'pending registrations',+ ),+ );+ checkStoredConfig('SSO flags', () => readStoredSsoFlags(snapshot, true));+ checkStoredConfig('SSO allowed domains', () =>+ parseStoredSsoAllowedEmailDomains(snapshot.get('sso_allowed_domains'), true),+ );+ checkStoredConfig('integrations', () =>+ parseStoredInstanceIntegrationsConfig(snapshot.get(INSTANCE_INTEGRATIONS_CONFIG_KEY) ?? null),+ );+ checkStoredConfig('media', () => parseStoredInstanceMediaConfig(snapshot.get(INSTANCE_MEDIA_CONFIG_KEY) ?? null));+ const appPublic = parseStoredAppPublicConfig(snapshot.get(APP_PUBLIC_CONFIG_KEY) ?? null);setCachedDeferredPhoneGateEnabled(resolveDeferredPhoneGateEnabled(policy));- }-- private syncDateOfBirthCollectionCache(raw: string | null): void {- const appPublic = raw ? normalizeAppPublicConfig(parseJsonRecord(raw)) : getDefaultAppPublicConfig();setCachedDateOfBirthCollection(appPublic.registration.collect_date_of_birth);}- private updateCachedConfigs(entries: Array<[string, string]>): void {- if (!this.configCache) {- return;- }- for (const [key, value] of entries) {- this.configCache.set(key, value);- }- }-- private async publishRefresh(): Promise<void> {+ private async publishRefresh(sourceId: string): Promise<void> {if (!this.kvClient) {return;}await this.kvClient.publish(INSTANCE_CONFIG_REFRESH_CHANNEL,- JSON.stringify({source_id: this.pubSubSourceId, type: 'refresh'}),+ JSON.stringify({source_id: sourceId, type: 'refresh'}),);}- private isOwnRefreshMessage(message: string): boolean {- const parsed = parseJsonRecord(message);- return parsed?.source_id === this.pubSubSourceId;- }-- private closeSubscription(): void {- if (this.kvSubscription && this.messageHandler) {- this.kvSubscription.off('message', this.messageHandler);- }- if (this.kvSubscription) {- this.kvSubscription.disconnect();- this.kvSubscription = null;- }- this.messageHandler = null;- this.subscriberInitialized = false;- }-- shutdown(): void {- this.closeSubscription();+ shutdown(): Promise<void> {+ return this.configCache.shutdown();}clearCacheForTesting(): void {- this.closeSubscription();- this.configCache = null;- this.cacheInitializationPromise = null;- this.refreshPromise = null;- this.refreshRequested = false;- this.subscriberInitializationPromise = null;+ const shutdown = this.shutdown();+ this.configCache = this.createConfigCache(shutdown);+ void shutdown.catch((error) => {+ Logger.error({error}, 'Failed to clear instance config cache');+ });}async isAdminBootstrapped(): Promise<boolean> {@@ -1010,107 +1058,56 @@ export class InstanceConfigRepository {async getGatewayRolloutConfig(): Promise<GatewayRolloutConfig> {const raw = await this.getConfig(GATEWAY_ROLLOUT_CONFIG_KEY);- if (!raw) {- return {...DEFAULT_GATEWAY_ROLLOUT_CONFIG};- }- try {- const parsed = parseJsonRecord(raw);- if (!parsed) {- return {...DEFAULT_GATEWAY_ROLLOUT_CONFIG};- }- const normalizedParsed: Record<string, unknown> = {...parsed};- if (- normalizedParsed.rpc_request_timeout_ms === undefined &&- typeof normalizedParsed.nats_request_timeout_ms === 'number'- ) {- normalizedParsed.rpc_request_timeout_ms = normalizedParsed.nats_request_timeout_ms;- }- return GatewayRolloutConfigSchema.parse({...DEFAULT_GATEWAY_ROLLOUT_CONFIG, ...normalizedParsed});- } catch (error) {- Logger.error({error}, 'Invalid gateway rollout config');- throw error;- }+ return parseStoredGatewayRolloutConfig(raw);}async setGatewayRolloutConfig(config: GatewayRolloutConfig): Promise<void> {- await this.setConfig(GATEWAY_ROLLOUT_CONFIG_KEY, JSON.stringify(config));+ await this.setConfig(GATEWAY_ROLLOUT_CONFIG_KEY, JSON.stringify(decodeGatewayRolloutConfig(config)));}async getVoiceNoiseSuppressionConfig(): Promise<VoiceNoiseSuppressionConfig> {const raw = await this.getConfig(VOICE_NOISE_SUPPRESSION_CONFIG_KEY);- if (!raw) {- return VoiceNoiseSuppressionConfigSchema.parse({});- }- const parsed = parseJsonRecord(raw);- if (!parsed) {- return VoiceNoiseSuppressionConfigSchema.parse({});- }- const result = VoiceNoiseSuppressionConfigSchema.safeParse(parsed);- if (!result.success) {- Logger.error({error: result.error}, 'Invalid voice noise suppression config');- return VoiceNoiseSuppressionConfigSchema.parse({});- }- return result.data;+ return parseStoredVoiceNoiseSuppressionConfig(raw);}async setVoiceNoiseSuppressionConfig(config: VoiceNoiseSuppressionConfig): Promise<void> {- await this.setConfig(VOICE_NOISE_SUPPRESSION_CONFIG_KEY, JSON.stringify(config));+ const validated = validateStoredConfig(VoiceNoiseSuppressionConfigSchema, config, 'voice noise suppression');+ await this.setConfig(VOICE_NOISE_SUPPRESSION_CONFIG_KEY, JSON.stringify(validated));}async getExperimentDeliveryConfig(): Promise<ExperimentDeliveryConfig> {const raw = await this.getConfig(EXPERIMENT_DELIVERY_CONFIG_KEY);- if (!raw) {- return ExperimentDeliveryConfigSchema.parse({});- }- const parsed = parseJsonRecord(raw);- if (!parsed) {- return ExperimentDeliveryConfigSchema.parse({});- }- const result = ExperimentDeliveryConfigSchema.safeParse(parsed);- if (!result.success) {- Logger.error({error: result.error}, 'Invalid experiment delivery config');- return ExperimentDeliveryConfigSchema.parse({});- }- return result.data;+ return parseStoredExperimentDeliveryConfig(raw);}async setExperimentDeliveryConfig(config: ExperimentDeliveryConfig): Promise<void> {- await this.setConfig(EXPERIMENT_DELIVERY_CONFIG_KEY, JSON.stringify(config));- }-- async hasLimitConfig(): Promise<boolean> {- const raw = await this.getConfig('limit_config');- return raw !== null;+ const validated = validateStoredConfig(ExperimentDeliveryConfigSchema, config, 'experiment delivery');+ await this.setConfig(EXPERIMENT_DELIVERY_CONFIG_KEY, JSON.stringify(validated));}- async getLimitConfig(): Promise<LimitConfigSnapshot | null> {- const raw = await this.getConfig('limit_config');- if (!raw) {- return null;- }- try {- const parsed: unknown = JSON.parse(raw);- if (!isLimitConfigSnapshot(parsed)) {- return null;- }- const policy = await this.getInstancePolicyConfig();- return sanitizeLimitConfigForInstance(parsed, {- selfHosted: Config.instance.selfHosted,- premiumMode: policy.premium_mode,- });- } catch (error) {- Logger.warn({error}, 'Invalid limit config JSON, returning null');- return null;- }+ async readLimitConfigInputs(): Promise<LimitConfigInputs> {+ const cache = this.configCache;+ cache.assertActive();+ const rows = await fetchMany<InstanceConfigurationRow>(FETCH_LIMIT_CONFIG_INPUTS_QUERY, {+ keys: [LIMIT_CONFIG_KEY, INSTANCE_POLICY_CONFIG_KEY],+ });+ cache.assertActive();+ const values = new Map(rows.map((row) => [row.key, row.value]));+ const policyRaw = values.get(INSTANCE_POLICY_CONFIG_KEY) ?? null;+ const policy = parseStoredInstancePolicyConfig(policyRaw);+ return {+ config: parseStoredLimitConfig(values.get(LIMIT_CONFIG_KEY) ?? null),+ premiumMode: policy.premium_mode,+ };}async setLimitConfig(config: LimitConfigSnapshot): Promise<void> {- await this.setConfig('limit_config', JSON.stringify(config));+ await this.setConfig(LIMIT_CONFIG_KEY, JSON.stringify(config));}async getAppPublicConfig(): Promise<InstanceAppPublicConfig> {const raw = await this.getConfig(APP_PUBLIC_CONFIG_KEY);- const config = raw ? parseAppPublicConfig(raw) : getDefaultAppPublicConfig();+ const config = parseStoredAppPublicConfig(raw);setCachedDateOfBirthCollection(config.registration.collect_date_of_birth);return config;}@@ -1122,7 +1119,7 @@ export class InstanceConfigRepository {registration?: Partial<InstanceAppPublicConfig['registration']>;}): Promise<InstanceAppPublicConfig> {const current = await this.getAppPublicConfig();- const next = normalizeAppPublicConfig({+ const next = decodeAppPublicConfig({branding: {...current.branding,...(config.branding ?? {}),@@ -1147,14 +1144,22 @@ export class InstanceConfigRepository {async getInstancePolicyConfig(): Promise<InstancePolicyConfig> {const raw = await this.getConfig(INSTANCE_POLICY_CONFIG_KEY);- const policy = raw ? normalizeInstancePolicyConfig(parseJsonRecord(raw)) : {...DEFAULT_INSTANCE_POLICY_CONFIG};+ const policy = parseStoredInstancePolicyConfig(raw);setCachedDeferredPhoneGateEnabled(resolveDeferredPhoneGateEnabled(policy));return policy;}+ async readStoredInstancePolicyConfig(): Promise<InstancePolicyConfig> {+ const cache = this.configCache;+ cache.assertActive();+ const raw = await this.fetchConfigFromDatabase(INSTANCE_POLICY_CONFIG_KEY);+ cache.assertActive();+ return parseStoredInstancePolicyConfig(raw);+ }+async setInstancePolicyConfig(config: Partial<InstancePolicyConfig>): Promise<InstancePolicyConfig> {- const current = await this.getInstancePolicyConfig();- const next = normalizeInstancePolicyConfig({...current, ...config});+ const current = await this.readStoredInstancePolicyConfig();+ const next = decodeInstancePolicyConfig({...current, ...config});await this.setConfig(INSTANCE_POLICY_CONFIG_KEY, JSON.stringify(next));setCachedDeferredPhoneGateEnabled(resolveDeferredPhoneGateEnabled(next));return next;@@ -1162,15 +1167,12 @@ export class InstanceConfigRepository {async getInstanceIntegrationsConfig(): Promise<InstanceIntegrationsConfig> {const raw = await this.getConfig(INSTANCE_INTEGRATIONS_CONFIG_KEY);- if (!raw) {- return normalizeInstanceIntegrationsConfig(null);- }- return normalizeInstanceIntegrationsConfig(parseJsonRecord(raw));+ return parseStoredInstanceIntegrationsConfig(raw);}async setInstanceIntegrationsConfig(config: InstanceIntegrationsConfigPatch): Promise<InstanceIntegrationsConfig> {const current = await this.getInstanceIntegrationsConfig();- const next = normalizeInstanceIntegrationsConfig({+ const next = decodeInstanceIntegrationsConfig({gif: {...current.gif,...(config.gif ?? {}),@@ -1203,15 +1205,12 @@ export class InstanceConfigRepository {async getInstanceMediaConfig(): Promise<InstanceMediaConfig> {const raw = await this.getConfig(INSTANCE_MEDIA_CONFIG_KEY);- if (!raw) {- return normalizeInstanceMediaConfig(null);- }- return normalizeInstanceMediaConfig(parseJsonRecord(raw));+ return parseStoredInstanceMediaConfig(raw);}async setInstanceMediaConfig(config: InstanceMediaConfigPatch): Promise<InstanceMediaConfig> {const current = await this.getInstanceMediaConfig();- const next = normalizeInstanceMediaConfig({+ const next = decodeInstanceMediaConfig({attachment_decay: {...current.attachment_decay,...(config.attachment_decay ?? {}),@@ -1226,8 +1225,7 @@ export class InstanceConfigRepository {const attachmentDecay = media.attachment_decay;const minSizeMb = attachmentDecay.min_size_mb ?? DEFAULT_DECAY_CONSTANTS.MIN_MB;const configuredMaxSizeMb = attachmentDecay.max_size_mb ?? DEFAULT_DECAY_CONSTANTS.MAX_MB;- const maxSizeMb =- configuredMaxSizeMb > minSizeMb ? configuredMaxSizeMb : Math.max(DEFAULT_DECAY_CONSTANTS.MAX_MB, minSizeMb + 1);+ const maxSizeMb = computeAttachmentDecayMaxSize(minSizeMb, configuredMaxSizeMb);const configuredMaxEligibleSizeMb = attachmentDecay.max_eligible_size_mb ?? DEFAULT_DECAY_CONSTANTS.PLAN_MB;const maxEligibleSizeMb = Math.max(maxSizeMb, configuredMaxEligibleSizeMb);const minLifetimeDays = attachmentDecay.min_lifetime_days ?? DEFAULT_DECAY_CONSTANTS.MIN_DAYS;@@ -1268,7 +1266,7 @@ export class InstanceConfigRepository {async getEffectiveGifConfig(): Promise<InstanceGifEffectiveConfig> {const integrations = await this.getInstanceIntegrationsConfig();- const klipyApiKey = integrations.gif.klipy_api_key ?? normalizeSecretString(Config.klipy.apiKey);+ const klipyApiKey = integrations.gif.klipy_api_key ?? normalizeOptionalString(Config.klipy.apiKey);return {klipy_api_key: klipyApiKey,active_api_key: klipyApiKey,@@ -1278,20 +1276,20 @@ export class InstanceConfigRepository {async getEffectiveYoutubeApiKey(): Promise<string | null> {const integrations = await this.getInstanceIntegrationsConfig();- return integrations.youtube.api_key ?? normalizeSecretString(Config.youtube.apiKey);+ return integrations.youtube.api_key ?? normalizeOptionalString(Config.youtube.apiKey);}async getEffectiveCaptchaConfig(): Promise<InstanceCaptchaEffectiveConfig> {const integrations = await this.getInstanceIntegrationsConfig();const provider = integrations.captcha.provider ?? (Config.captcha.enabled ? Config.captcha.provider : 'none');const hcaptchaSiteKey =- integrations.captcha.hcaptcha_site_key ?? normalizeSecretString(Config.captcha.hcaptcha?.siteKey);+ integrations.captcha.hcaptcha_site_key ?? normalizeOptionalString(Config.captcha.hcaptcha?.siteKey);const hcaptchaSecretKey =- integrations.captcha.hcaptcha_secret_key ?? normalizeSecretString(Config.captcha.hcaptcha?.secretKey);+ integrations.captcha.hcaptcha_secret_key ?? normalizeOptionalString(Config.captcha.hcaptcha?.secretKey);const turnstileSiteKey =- integrations.captcha.turnstile_site_key ?? normalizeSecretString(Config.captcha.turnstile?.siteKey);+ integrations.captcha.turnstile_site_key ?? normalizeOptionalString(Config.captcha.turnstile?.siteKey);const turnstileSecretKey =- integrations.captcha.turnstile_secret_key ?? normalizeSecretString(Config.captcha.turnstile?.secretKey);+ integrations.captcha.turnstile_secret_key ?? normalizeOptionalString(Config.captcha.turnstile?.secretKey);const providerReady =provider === 'hcaptcha'? Boolean(hcaptchaSiteKey && hcaptchaSecretKey)@@ -1347,7 +1345,7 @@ export class InstanceConfigRepository {if (memoized && this.effectiveBlueskyConfigSource === raw) {return memoized;}- const integrations = normalizeInstanceIntegrationsConfig(raw ? parseJsonRecord(raw) : null);+ const integrations = parseStoredInstanceIntegrationsConfig(raw);const runtimeKeys = integrations.bluesky.keys.flatMap((key): Array<BlueskyOAuthKeyConfig> => {if (!key.private_key) return [];return [{kid: key.kid, private_key: key.private_key}];@@ -1453,16 +1451,12 @@ export class InstanceConfigRepository {async getRegistrationConfig(): Promise<InstanceRegistrationConfig> {const raw = await this.getConfig(REGISTRATION_CONFIG_KEY);- if (!raw) {- return {...DEFAULT_REGISTRATION_CONFIG};- }- const parsed = parseJsonRecord(raw);- return normalizeRegistrationConfig(parsed);+ return parseStoredRegistrationConfig(raw);}async setRegistrationConfig(config: Partial<InstanceRegistrationConfig>): Promise<InstanceRegistrationConfig> {const current = await this.getRegistrationConfig();- const next = normalizeRegistrationConfig({+ const next = decodeRegistrationConfig({mode: config.mode ?? current.mode,admin_registration_urls_enabled:config.admin_registration_urls_enabled ?? current.admin_registration_urls_enabled,@@ -1477,18 +1471,7 @@ export class InstanceConfigRepository {async getRegistrationUrls(): Promise<Array<InstanceRegistrationUrl>> {const raw = await this.getConfig(REGISTRATION_URLS_KEY);- if (!raw) {- return [];- }- const parsed = parseJsonArray(raw);- if (!parsed) {- Logger.warn('Invalid registration URL config JSON, returning empty list');- return [];- }- return parsed.flatMap((entry) => {- const normalized = normalizeRegistrationUrl(entry);- return normalized ? [normalized] : [];- });+ return parseStoredCollection(StoredRegistrationUrlSchema, raw, 'registration URLs');}async getRegistrationUrlsForAdmin(): Promise<Array<InstanceRegistrationUrlPublic>> {@@ -1571,20 +1554,9 @@ export class InstanceConfigRepository {async getPendingRegistrations(): Promise<Array<InstancePendingRegistration>> {const raw = await this.getConfig(REGISTRATION_PENDING_APPROVALS_KEY);- if (!raw) {- return [];- }- const parsed = parseJsonArray(raw);- if (!parsed) {- Logger.warn('Invalid pending registration config JSON, returning empty list');- return [];- }- return parsed- .flatMap((entry) => {- const normalized = normalizePendingRegistration(entry);- return normalized ? [normalized] : [];- })- .toSorted((a, b) => Date.parse(a.requested_at) - Date.parse(b.requested_at));+ return parseStoredCollection(StoredPendingRegistrationSchema, raw, 'pending registrations').toSorted(+ (a, b) => Date.parse(a.requested_at) - Date.parse(b.requested_at),+ );}async addPendingRegistration(pendingRegistration: InstancePendingRegistration): Promise<void> {@@ -1593,44 +1565,27 @@ export class InstanceConfigRepository {pendingRegistration,...pendingRegistrations.filter((entry) => entry.user_id !== pendingRegistration.user_id),];- await this.setConfig(REGISTRATION_PENDING_APPROVALS_KEY, JSON.stringify(next));+ await this.setPendingRegistrations(next);}async removePendingRegistration(userId: string): Promise<void> {const pendingRegistrations = await this.getPendingRegistrations();- await this.setConfig(- REGISTRATION_PENDING_APPROVALS_KEY,- JSON.stringify(pendingRegistrations.filter((entry) => entry.user_id !== userId)),- );+ await this.setPendingRegistrations(pendingRegistrations.filter((entry) => entry.user_id !== userId));}async getSsoConfig(options?: {includeSecret?: boolean}): Promise<InstanceSsoConfig> {const configs = await this.getAllConfigs();+ const flags = readStoredSsoFlags(configs);const read = (key: string): string | null => {const v = configs.get(key);if (!v) return null;const trimmed = v.trim();return trimmed.length === 0 ? null : trimmed;};- const allowedDomainsRaw = configs.get('sso_allowed_domains');- let allowedDomains: Array<string> = [];- if (allowedDomainsRaw) {- const parsed = parseJsonArray(allowedDomainsRaw);- if (parsed) {- allowedDomains = parsed.map((item) => String(item)).filter((item) => item.length > 0);- } else {- allowedDomains = allowedDomainsRaw- .split(',')- .map((s) => s.trim())- .filter((s) => s.length > 0);- }- }+ const allowedDomains = parseStoredSsoAllowedEmailDomains(configs.get('sso_allowed_domains'));const clientSecret = read('sso_client_secret');- const enabled = configs.get('sso_enabled') === 'true';- const enforcedRaw = configs.get('sso_enforced');return {- enabled,- enforced: enforcedRaw == null ? enabled : enforcedRaw === 'true',+ ...flags,displayName: read('sso_display_name'),issuer: read('sso_issuer'),authorizationUrl: read('sso_authorization_url'),@@ -1642,7 +1597,6 @@ export class InstanceConfigRepository {clientSecretSet: Boolean(clientSecret),scope: read('sso_scope'),allowedEmailDomains: allowedDomains,- autoProvision: configs.get('sso_auto_provision') !== 'false',redirectUri: null,};}@@ -1662,7 +1616,7 @@ export class InstanceConfigRepository {}let allowedEmailDomains: Array<string>;try {- allowedEmailDomains = normalizeSsoAllowedEmailDomains(next.allowedEmailDomains ?? []);+ allowedEmailDomains = normalizeSsoAllowedEmailDomains(next.allowedEmailDomains);} catch (error) {if (next.enabled) {throw error;@@ -1693,7 +1647,17 @@ export class InstanceConfigRepository {}private async setRegistrationUrls(registrationUrls: Array<InstanceRegistrationUrl>): Promise<void> {- await this.setConfig(REGISTRATION_URLS_KEY, JSON.stringify(registrationUrls));+ const validated = validateStoredCollection(StoredRegistrationUrlSchema, registrationUrls, 'registration URLs');+ await this.setConfig(REGISTRATION_URLS_KEY, JSON.stringify(validated));+ }++ private async setPendingRegistrations(pendingRegistrations: Array<InstancePendingRegistration>): Promise<void> {+ const validated = validateStoredCollection(+ StoredPendingRegistrationSchema,+ pendingRegistrations,+ 'pending registrations',+ );+ await this.setConfig(REGISTRATION_PENDING_APPROVALS_KEY, JSON.stringify(validated));}private hashRegistrationUrlCode(code: string): string {diff --git a/fluxer_api/src/api/instance/SingleCommunityService.ts b/fluxer_api/src/api/instance/SingleCommunityService.tsindex 0c5541bc0..ed1198511 100644--- a/fluxer_api/src/api/instance/SingleCommunityService.ts+++ b/fluxer_api/src/api/instance/SingleCommunityService.ts@@ -1,6 +1,7 @@// SPDX-License-Identifier: AGPL-3.0-or-laterimport {JoinSourceTypes} from '@fluxer/constants/src/GuildConstants';+import {UnknownGuildError} from '@fluxer/errors/src/domains/guild/UnknownGuildError';import {createGuildID, type GuildID, type UserID} from '../BrandedTypes';import type {GuildDataService} from '../guild/services/GuildDataService';import type {GuildMemberService} from '../guild/services/GuildMemberService';@@ -18,19 +19,15 @@ export class SingleCommunityService {async getStockCommunityId(): Promise<GuildID | null> {const policy = await this.instanceConfigRepository.getInstancePolicyConfig();- if (!policy.single_community_enabled || !policy.single_community_guild_id) {- return null;- }- try {- return createGuildID(BigInt(policy.single_community_guild_id));- } catch {+ if (!policy.single_community_enabled || policy.single_community_guild_id === null) {return null;}+ return createGuildID(BigInt(policy.single_community_guild_id));}async joinStockCommunity(userId: UserID, requestCache: RequestCache): Promise<void> {const guildId = await this.getStockCommunityId();- if (!guildId) {+ if (guildId === null) {return;}try {@@ -64,20 +61,16 @@ export class SingleCommunityService {}private async findDesignatedGuild(rawGuildId: string | null): Promise<GuildID | null> {- if (!rawGuildId) {- return null;- }- let guildId: GuildID;- try {- guildId = createGuildID(BigInt(rawGuildId));- } catch {+ if (rawGuildId === null) {return null;}+ const guildId = createGuildID(BigInt(rawGuildId));try {await this.guildDataService.getGuildSystem(guildId);return guildId;- } catch {- return null;+ } catch (error) {+ if (error instanceof UnknownGuildError) return null;+ throw error;}}diff --git a/fluxer_api/src/api/instance/SsoConfigValidation.ts b/fluxer_api/src/api/instance/SsoConfigValidation.tsindex 0cc2ea9b9..f86e8a74b 100644--- a/fluxer_api/src/api/instance/SsoConfigValidation.ts+++ b/fluxer_api/src/api/instance/SsoConfigValidation.ts@@ -3,6 +3,7 @@import {domainToASCII} from 'node:url';import {ValidationErrorCodes} from '@fluxer/constants/src/ValidationErrorCodes';import {InputValidationError} from '@fluxer/errors/src/domains/core/InputValidationError';+import {InstanceConfigResponse} from '@fluxer/schema/src/domains/admin/AdminSchemas';import type {RequestUrlPolicy} from '@pkgs/http_client/src/HttpClientTypes';import {createPublicInternetRequestUrlPolicy} from '@pkgs/http_client/src/PublicInternetRequestUrlPolicy';import {Config} from '../Config';@@ -38,6 +39,7 @@ export function getSsoRequestUrlPolicy(): RequestUrlPolicy {return ssoRequestUrlPolicy;}const DOMAIN_LABEL_REGEX = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;+const SsoAllowedDomainsSchema = InstanceConfigResponse.shape.sso.shape.allowed_domains;function normalizeOptionalSsoString(value: string | null): string | null {if (typeof value !== 'string') {@@ -69,9 +71,11 @@ export function isTestSsoProvider();}-export function normalizeSsoAllowedEmailDomains(domains: Array<string>): Array<string> {+export function normalizeSsoAllowedEmailDomains(domains: unknown): Array<string> {+ const result = SsoAllowedDomainsSchema.safeParse(domains);+ if (!result.success) throwInvalidDomain();const normalized = new Set<string>();- for (const rawDomain of domains) {+ for (const rawDomain of result.data) {const trimmed = rawDomain.trim().toLowerCase();if (!trimmed) {continue;diff --git a/fluxer_api/src/api/instance/tests/SingleCommunityService.test.ts b/fluxer_api/src/api/instance/tests/SingleCommunityService.test.tsindex f2f83c04e..6a6d4818e 100644--- a/fluxer_api/src/api/instance/tests/SingleCommunityService.test.ts+++ b/fluxer_api/src/api/instance/tests/SingleCommunityService.test.ts@@ -1,5 +1,6 @@// SPDX-License-Identifier: AGPL-3.0-or-later+import {UnknownGuildError} from '@fluxer/errors/src/domains/guild/UnknownGuildError';import {describe, expect, it} from 'vitest';import type {User} from '../../models/User';import type {InstancePolicyConfig} from '../InstanceConfigRepository';@@ -30,7 +31,7 @@ function createHarness(params: {designatedGuildId: string | null; designatedGuilconst guildDataService = {getGuildSystem: async () => {if (!params.designatedGuildExists) {- throw new Error('unknown guild');+ throw new UnknownGuildError();}return {} as never;},@@ -70,9 +71,9 @@ describe('SingleCommunityService.ensureStockCommunity', () => {expect(harness.createdNames).toEqual(['Fluxer']);});- it('creates a fresh community when the stored guild id is not a snowflake', async () => {+ it('rejects an invalid stored guild id without creating a community', async () => {const harness = createHarness({designatedGuildId: 'not-a-snowflake', designatedGuildExists: true});- await harness.service.ensureStockCommunity({owner: OWNER, name: 'Fluxer'});- expect(harness.createdNames).toEqual(['Fluxer']);+ await expect(harness.service.ensureStockCommunity({owner: OWNER, name: 'Fluxer'})).rejects.toThrow(SyntaxError);+ expect(harness.createdNames).toEqual([]);});});diff --git a/fluxer_api/src/api/limits/LimitConfigService.ts b/fluxer_api/src/api/limits/LimitConfigService.tsindex b4f09e69f..edc571638 100644--- a/fluxer_api/src/api/limits/LimitConfigService.ts+++ b/fluxer_api/src/api/limits/LimitConfigService.ts@@ -1,176 +1,205 @@// SPDX-License-Identifier: AGPL-3.0-or-later+import {ServiceUnavailableError} from '@fluxer/errors/src/domains/core/ServiceUnavailableError';import {computeWireFormat} from '@fluxer/limits/src/LimitDiffer';-import {computeDefaultsHash} from '@fluxer/limits/src/LimitHashing';import type {LimitConfigSnapshot, LimitConfigWireFormat} from '@fluxer/limits/src/LimitTypes';import type {ICacheService} from '@pkgs/cache/src/ICacheService';-import type {IKVProvider, IKVSubscription} from '@pkgs/kv_client/src/IKVProvider';+import type {IKVProvider} from '@pkgs/kv_client/src/IKVProvider';import {Config} from '../Config';-import type {CachedLimitConfig} from '../constants/LimitConfig';import {createDefaultLimitConfig,- getLimitConfigKvKey,+ getLegacyLimitConfigKvKey,LIMIT_CONFIG_REFRESH_CHANNEL,- LIMIT_CONFIG_REFRESH_LOCK_KEY,mergeWithCurrentDefaults,sanitizeLimitConfigForInstance,} from '../constants/LimitConfig';-import type {InstanceConfigRepository, InstancePremiumMode} from '../instance/InstanceConfigRepository';+import {+ INSTANCE_CONFIG_REFRESH_CHANNEL,+ type InstanceConfigRepository,+ type InstancePolicyConfig,+ type InstancePremiumMode,+} from '../instance/InstanceConfigRepository';import {Logger} from '../Logger';+import {awaitAll} from '../utils/ConcurrencyUtils';+import {RefreshSubscription} from '../utils/RefreshSubscription';import {setCachedInstancePremiumMode} from './InstancePremiumModeCache';+const MAX_PENDING_OPERATIONS = 32;+let globalLimitConfigService: LimitConfigService | null = null;+interface LimitBuildOptions {+ selfHosted: boolean;+ premiumMode: InstancePremiumMode;+}+export class LimitConfigService {private premiumMode: InstancePremiumMode = 'everyone';private config: LimitConfigSnapshot = createDefaultLimitConfig({selfHosted: Config.instance.selfHosted,premiumMode: 'everyone',});- private repository: InstanceConfigRepository;- private cacheService: ICacheService;- private kvClient: IKVProvider | null;- private kvSubscription: IKVSubscription | null = null;- private subscriberInitialized = false;- private readonly cacheKey: string;- private messageHandler: ((channel: string) => void) | null = null;-- constructor(repository: InstanceConfigRepository, cacheService: ICacheService, kvClient: IKVProvider | null = null) {- this.repository = repository;- this.cacheService = cacheService;- this.kvClient = kvClient;- this.cacheKey = getLimitConfigKvKey(Config.instance.selfHosted);- }-- private get limitBuildOptions(): {selfHosted: boolean; premiumMode: InstancePremiumMode} {- return {selfHosted: Config.instance.selfHosted, premiumMode: this.premiumMode};- }+ private hasLifecycleStarted = false;+ private lifecycleGeneration = 0;+ private initialization: Promise<void> | null = null;+ private stopping: Promise<void> | null = null;+ private operationTail: Promise<void> = Promise.resolve();+ private pendingOperations = 0;+ private readonly refreshSubscription = new RefreshSubscription({+ name: 'LimitConfigService',+ channels: [LIMIT_CONFIG_REFRESH_CHANNEL, INSTANCE_CONFIG_REFRESH_CHANNEL],+ refresh: () => this.refreshCache(),+ onRefreshError: (err) => {+ Logger.error({err}, 'Failed to refresh limit config from pubsub');+ },+ closeMode: 'quit',+ });- getPremiumMode(): InstancePremiumMode {- return this.premiumMode;- }+ constructor(+ private readonly repository: InstanceConfigRepository,+ private readonly cacheService: ICacheService,+ private readonly kvClient: IKVProvider | null = null,+ ) {}setAsGlobalInstance(): void {+ const defaultOnly = this.kvClient === null && !this.hasLifecycleStarted;+ if (!defaultOnly && !this.refreshSubscription.isReady) {+ throw new Error('Cannot publish LimitConfigService before initialization or after shutdown');+ }globalLimitConfigService = this;}async initialize(): Promise<void> {- await this.refreshCache();- this.initializeSubscriber();- Logger.info('LimitConfigService initialized');+ if (this.stopping) throw new Error('Cannot initialize LimitConfigService while it is shutting down');+ this.initialization ??= this.start().finally(() => {+ this.initialization = null;+ });+ await this.initialization;+ }++ private async start(): Promise<void> {+ this.hasLifecycleStarted = true;+ const generation = this.lifecycleGeneration;+ try {+ await this.refreshSubscription.start(this.kvClient);+ this.assertRefreshActive(generation);+ Logger.info('LimitConfigService initialized');+ } catch (error) {+ try {+ await this.shutdown();+ } catch (cleanupError) {+ throw new AggregateError([error, cleanupError], 'Limit config initialization and cleanup failed');+ }+ throw error;+ }}getConfigSnapshot(): LimitConfigSnapshot {return this.config;}+ getDefaultConfigSnapshot(): LimitConfigSnapshot {+ return createDefaultLimitConfig({selfHosted: Config.instance.selfHosted, premiumMode: this.premiumMode});+ }+getConfigWireFormat(): LimitConfigWireFormat {return computeWireFormat(this.config);}- async refreshCache(): Promise<void> {- const policyConfig = await this.repository.getInstancePolicyConfig();- this.premiumMode = policyConfig.premium_mode;- setCachedInstancePremiumMode(this.premiumMode);- const currentHash = computeDefaultsHash();- const lockToken = await this.cacheService.acquireLock(LIMIT_CONFIG_REFRESH_LOCK_KEY, 10);- if (!lockToken) {- Logger.debug('Limit config refresh already in progress, waiting for cache update');- await this.sleep(50);- const cached = await this.cacheService.get<CachedLimitConfig>(this.cacheKey);- if (cached && cached.defaultsHash === currentHash) {- this.config = sanitizeLimitConfigForInstance(cached.config, this.limitBuildOptions);- return;- }- this.config = createDefaultLimitConfig(this.limitBuildOptions);- return;+ refreshCache(): Promise<void> {+ return this.runOperation((generation) => this.refreshConfig(generation));+ }++ private assertRefreshActive(generation: number): void {+ if (generation !== this.lifecycleGeneration) {+ throw new Error('Limit config operation was interrupted by shutdown');}- try {- const cached = await this.cacheService.get<CachedLimitConfig>(this.cacheKey);- if (cached && cached.defaultsHash === currentHash) {- this.config = sanitizeLimitConfigForInstance(cached.config, this.limitBuildOptions);- return;- }- const dbConfig = await this.repository.getLimitConfig();- if (dbConfig === null) {- this.config = createDefaultLimitConfig(this.limitBuildOptions);- await this.cacheService.delete(this.cacheKey);- Logger.debug('No database limit config, using fresh defaults');- return;- }- Logger.info(- {hashMismatch: cached?.defaultsHash !== currentHash},- 'Merging database config with current defaults',- );- const merged = mergeWithCurrentDefaults(dbConfig, this.limitBuildOptions);- await this.repository.setLimitConfig(merged);- await this.cacheService.set(this.cacheKey, {- config: merged,- defaultsHash: currentHash,- });- this.config = sanitizeLimitConfigForInstance(merged, this.limitBuildOptions);- } finally {- await this.cacheService.releaseLock(LIMIT_CONFIG_REFRESH_LOCK_KEY, lockToken);+ if (this.stopping || (this.hasLifecycleStarted && !this.refreshSubscription.isActive)) {+ throw new Error('LimitConfigService is not active');}}- private sleep(ms: number): Promise<void> {- return new Promise((resolve) => setTimeout(resolve, ms));+ private async runOperation(operation: (generation: number) => Promise<void>): Promise<void> {+ const generation = this.lifecycleGeneration;+ this.assertRefreshActive(generation);+ if (this.pendingOperations >= MAX_PENDING_OPERATIONS) {+ Logger.warn({pendingOperations: this.pendingOperations}, 'Limit config operation capacity exceeded');+ throw new ServiceUnavailableError();+ }+ this.pendingOperations++;+ const completion = this.operationTail+ .then(() => {+ this.assertRefreshActive(generation);+ return operation(generation);+ })+ .finally(() => {+ this.pendingOperations--;+ });+ this.operationTail = completion.then(+ () => undefined,+ () => undefined,+ );+ await completion;}- async updateConfig(config: LimitConfigSnapshot): Promise<void> {- const normalized = sanitizeLimitConfigForInstance(config, this.limitBuildOptions);- await this.repository.setLimitConfig(normalized);- await this.cacheService.delete(this.cacheKey);- await this.refreshCache();- await this.cacheService.publish(LIMIT_CONFIG_REFRESH_CHANNEL, 'refresh');- Logger.info({ruleCount: normalized.rules.length}, 'Limit config updated');+ private async refreshConfig(generation: number): Promise<void> {+ this.assertRefreshActive(generation);+ const {config: stored, premiumMode} = await this.repository.readLimitConfigInputs();+ this.assertRefreshActive(generation);+ const buildOptions: LimitBuildOptions = {+ selfHosted: Config.instance.selfHosted,+ premiumMode,+ };+ this.config =+ stored === null+ ? createDefaultLimitConfig(buildOptions)+ : mergeWithCurrentDefaults(sanitizeLimitConfigForInstance(stored, buildOptions), buildOptions);+ this.premiumMode = premiumMode;+ setCachedInstancePremiumMode(premiumMode);}- async reloadForPolicyChange(): Promise<void> {- await this.cacheService.delete(this.cacheKey);- await this.refreshCache();- await this.cacheService.publish(LIMIT_CONFIG_REFRESH_CHANNEL, 'refresh');+ updateConfig(config: LimitConfigSnapshot): Promise<void> {+ return this.runOperation(async (generation) => {+ const policy = await this.repository.readStoredInstancePolicyConfig();+ this.assertRefreshActive(generation);+ const buildOptions: LimitBuildOptions = {+ selfHosted: Config.instance.selfHosted,+ premiumMode: policy.premium_mode,+ };+ const normalized = mergeWithCurrentDefaults(sanitizeLimitConfigForInstance(config, buildOptions), buildOptions);+ await this.repository.setLimitConfig(normalized);+ await this.reloadConfig(generation);+ Logger.info({ruleCount: normalized.rules.length}, 'Limit config updated');+ });}- private initializeSubscriber(): void {- if (this.subscriberInitialized || !this.kvClient) {- return;- }- const subscription = this.kvClient.duplicate();- this.kvSubscription = subscription;- this.messageHandler = (channel: string) => {- if (channel === LIMIT_CONFIG_REFRESH_CHANNEL) {- this.refreshCache().catch((err) => {- Logger.error({err}, 'Failed to refresh limit config from pubsub');- });- }- };- subscription- .connect()- .then(() => subscription.subscribe(LIMIT_CONFIG_REFRESH_CHANNEL))- .then(() => {- if (this.messageHandler) {- subscription.on('message', this.messageHandler);- }- })- .catch((error) => {- Logger.error({error}, 'Failed to subscribe to limit config refresh channel');- });- this.subscriberInitialized = true;+ updatePolicyConfig(patch: Partial<InstancePolicyConfig>): Promise<void> {+ return this.runOperation(async (generation) => {+ await this.repository.setInstancePolicyConfig(patch);+ await this.reloadConfig(generation);+ });}- shutdown(): void {- if (this.kvSubscription && this.messageHandler) {- this.kvSubscription.off('message', this.messageHandler);- }- if (this.kvSubscription) {- this.kvSubscription.quit().catch((err) => {- Logger.error({err}, 'Failed to close KV subscription');- });- this.kvSubscription = null;- }- this.messageHandler = null;+ private async reloadConfig(generation: number): Promise<void> {+ this.assertRefreshActive(generation);+ await this.cacheService.delete(getLegacyLimitConfigKvKey(Config.instance.selfHosted));+ await this.refreshConfig(generation);+ this.assertRefreshActive(generation);+ await this.cacheService.publish(LIMIT_CONFIG_REFRESH_CHANNEL, 'refresh');+ }++ shutdown(): Promise<void> {+ if (this.stopping) return this.stopping;+ this.hasLifecycleStarted = true;+ this.lifecycleGeneration++;+ if (globalLimitConfigService === this) globalLimitConfigService = null;+ this.stopping = awaitAll(+ [this.refreshSubscription.stop(), this.operationTail],+ 'Limit config shutdown failed',+ ).finally(() => {+ this.stopping = null;+ });+ return this.stopping;}}diff --git a/fluxer_api/src/api/limits/LimitConfigValidation.ts b/fluxer_api/src/api/limits/LimitConfigValidation.tsnew file mode 100644index 000000000..e8c38eeff--- /dev/null+++ b/fluxer_api/src/api/limits/LimitConfigValidation.ts@@ -0,0 +1,28 @@+import type {LimitConfigSnapshot, LimitRule} from '@fluxer/limits/src/LimitTypes';+import {isJsonRecord} from '../utils/JsonBoundaryUtils';++function isStringArray(value: unknown): value is Array<string> {+ return Array.isArray(value) && value.every((entry) => typeof entry === 'string');+}++function isLimitRuleSnapshot(value: unknown): value is LimitRule {+ if (!isJsonRecord(value) || typeof value.id !== 'string' || !isJsonRecord(value.limits)) return false;+ const filters = value.filters;+ return (+ (filters === undefined ||+ (isJsonRecord(filters) &&+ (filters.traits === undefined || isStringArray(filters.traits)) &&+ (filters.guildFeatures === undefined || isStringArray(filters.guildFeatures)))) &&+ (value.modifiedFields === undefined || isStringArray(value.modifiedFields))+ );+}++export function isLimitConfigSnapshot(value: unknown): value is LimitConfigSnapshot {+ return (+ isJsonRecord(value) &&+ (value.version === undefined || typeof value.version === 'number') &&+ isStringArray(value.traitDefinitions) &&+ Array.isArray(value.rules) &&+ value.rules.every(isLimitRuleSnapshot)+ );+}diff --git a/fluxer_api/src/api/middleware/AbusiveIpAutoBanner.ts b/fluxer_api/src/api/middleware/AbusiveIpAutoBanner.tsindex 0ff13c628..12f58eb9f 100644--- a/fluxer_api/src/api/middleware/AbusiveIpAutoBanner.ts+++ b/fluxer_api/src/api/middleware/AbusiveIpAutoBanner.ts@@ -36,6 +36,13 @@ interface OutboundEntry {newTokenHashes: Set<string>;}+interface OutboundDeltaBatchEntry {+ key: string;+ pending: OutboundEntry;+ scoreDelta: number;+ tokenHashes: Set<string>;+}+interface PersistentScoreState {count: number;lastWindowStartMs: number;@@ -129,11 +136,7 @@ const recordedClientErrorRequests = new WeakSet<Request>();const pendingAutoBanTasks = new Set<Promise<void>>();const adminRepository = new AdminRepository();-let kvPublisher: IKVProvider | null = null;-let flushTimer: NodeJS.Timeout | null = null;-let kvSubscription: IKVSubscription | null = null;-let messageHandler: ((channel: string, message: string) => void) | null = null;-let errorHandler: ((error: Error) => void) | null = null;+let abuseReplication: AbuseReplicationSubscriber | null = null;let ipClassPendingTtlMs = DEFAULT_IP_CLASS_PENDING_TTL_MS;let ipClassNegativeTtlMs = DEFAULT_IP_CLASS_NEGATIVE_TTL_MS;let ipClassHintTtlMs = DEFAULT_IP_CLASS_HINT_TTL_MS;@@ -339,7 +342,7 @@ function queueOutboundDelta(tokenHash: string | undefined,hadToken: boolean,): void {- if (!kvPublisher) return;+ if (!abuseReplication?.isActive) return;if (!outboundDeltas.has(signalIp.banKey) && outboundDeltas.size >= MAX_TRACKED_IPS) return;const outbound = getOrInitOutbound(signalIp);outbound.scoreDelta += weight;@@ -377,7 +380,7 @@ function markScoreThresholdWindow(key: string, rec: AbuseRecord, now: number): nasync function claimIpClassLookup(key: string): Promise<boolean> {if (!IP_CLASS_CLAIM_ENABLED) return true;- if (!kvPublisher) return true;+ if (!abuseReplication?.isActive) return true;try {return await getKVClient().setnx(`${IP_CLASS_CLAIM_PREFIX}${key}`, POD_ID, IP_CLASS_CLAIM_TTL_SECONDS);} catch {@@ -558,10 +561,10 @@ function applyReplicatedTick(tick: ReplicatedTick): void {maybeFireAutoBan(banKey, rec);}-async function flushOutbound(): Promise<void> {- if (!kvPublisher || outboundDeltas.size === 0) return;+async function flushOutbound(publisher: IKVProvider): Promise<void> {+ if (outboundDeltas.size === 0) return;const ticks: Array<ReplicatedTick> = [];- const selectedKeys: Array<string> = [];+ const batch: Array<OutboundDeltaBatchEntry> = [];for (const [key, entry] of outboundDeltas) {const tokenHashes: Array<string> = [];for (const tokenHash of entry.newTokenHashes) {@@ -569,40 +572,54 @@ async function flushOutbound(): Promise<void> {if (tokenHashes.length >= MAX_NEW_TOKENS_PER_TICK) break;}ticks.push([key, entry.scoreDelta, tokenHashes, entry.lookupIp]);- selectedKeys.push(key);+ batch.push({key, pending: entry, scoreDelta: entry.scoreDelta, tokenHashes: entry.newTokenHashes});+ entry.scoreDelta = 0;+ entry.newTokenHashes = new Set();if (ticks.length >= MAX_BATCH_TICKS) break;}const message: ReplicationMessage = {sender: POD_ID, ticks, ts: Date.now()};try {- await kvPublisher.publish(REPLICATION_CHANNEL, JSON.stringify(message));- for (const key of selectedKeys) {- outboundDeltas.delete(key);+ await publisher.publish(REPLICATION_CHANNEL, JSON.stringify(message));+ for (const {key, pending} of batch) {+ if (outboundDeltas.get(key) === pending && pending.scoreDelta === 0) {+ outboundDeltas.delete(key);+ }}} catch (err) {+ for (const {key, pending, scoreDelta, tokenHashes} of batch) {+ if (outboundDeltas.get(key) !== pending) continue;+ pending.scoreDelta += scoreDelta;+ for (const tokenHash of pending.newTokenHashes) {+ tokenHashes.add(tokenHash);+ }+ pending.newTokenHashes = tokenHashes;+ }Logger.warn({err, tickCount: ticks.length}, '[abuse-auto-ban] Failed to publish abuse replication batch');}}function queueOutboundIpClass(key: string, lookupIp: string, ipClass: IpClass): void {- if (!kvPublisher) return;+ if (!abuseReplication?.isActive) return;if (!outboundIpClasses.has(key) && outboundIpClasses.size >= MAX_TRACKED_IPS) return;outboundIpClasses.set(key, {lookupIp, ipClass});}-async function flushOutboundIpClasses(): Promise<void> {- if (!kvPublisher || outboundIpClasses.size === 0) return;+async function flushOutboundIpClasses(publisher: IKVProvider): Promise<void> {+ if (outboundIpClasses.size === 0) return;const entries: Array<IpClassEntry> = [];- const selectedKeys: Array<string> = [];+ const batch: Array<[string, OutboundIpClass]> = [];for (const [key, entry] of outboundIpClasses) {entries.push([key, entry.lookupIp, entry.ipClass]);- selectedKeys.push(key);+ batch.push([key, entry]);if (entries.length >= MAX_BATCH_TICKS) break;}const message: IpClassMessage = {sender: POD_ID, entries, ts: Date.now()};try {- await kvPublisher.publish(IP_CLASS_CHANNEL, JSON.stringify(message));- for (const key of selectedKeys) {- outboundIpClasses.delete(key);+ await publisher.publish(IP_CLASS_CHANNEL, JSON.stringify(message));+ for (const [key, entry] of batch) {+ if (outboundIpClasses.get(key) === entry) {+ outboundIpClasses.delete(key);+ }}} catch (err) {Logger.warn({err, entryCount: entries.length}, '[abuse-auto-ban] Failed to publish abuse IP class batch');@@ -655,57 +672,118 @@ function handleReplicationMessage(channel: string, message: string): void {}}-export async function startAbuseReplicationSubscriber(kvClient: IKVProvider | null): Promise<void> {- if (!kvClient || kvSubscription) return;- kvPublisher = kvClient;- const subscription = kvClient.duplicate();- kvSubscription = subscription;- messageHandler = handleReplicationMessage;- errorHandler = (error: Error) => {- Logger.warn({error}, '[abuse-auto-ban] Abuse replication subscription error');+class AbuseReplicationSubscriber {+ private readonly subscription: IKVSubscription;+ private readonly flushes = new Map<string, Promise<void>>();+ private phase: 'starting' | 'running' | 'stopping' | 'stopped' = 'starting';+ private startCompletion: Promise<void> | null = null;+ private stopCompletion: Promise<void> | null = null;+ private flushTimer: NodeJS.Timeout | null = null;+ private readonly messageHandler = (channel: string, message: string): void => {+ if (this.isActive) handleReplicationMessage(channel, message);};- try {- await subscription.connect();- await subscription.subscribe(REPLICATION_CHANNEL, IP_CLASS_CHANNEL);- subscription.on('message', messageHandler);- subscription.on('error', errorHandler);- flushTimer = setInterval(() => {- void flushOutbound();- void flushOutboundIpClasses();+ private readonly errorHandler = (error: Error): void => {+ if (this.isActive) Logger.warn({error}, '[abuse-auto-ban] Abuse replication subscription error');+ };++ constructor(private readonly publisher: IKVProvider) {+ this.subscription = publisher.duplicate();+ }++ get isActive(): boolean {+ return this.phase === 'starting' || this.phase === 'running';+ }++ start(): Promise<void> {+ this.assertActive();+ this.startCompletion ??= this.connect();+ return this.startCompletion;+ }++ private async connect(): Promise<void> {+ this.subscription.on('message', this.messageHandler);+ this.subscription.on('error', this.errorHandler);+ await this.subscription.connect();+ this.assertActive();+ await this.subscription.subscribe(REPLICATION_CHANNEL, IP_CLASS_CHANNEL);+ this.assertActive();+ this.phase = 'running';+ this.flushTimer = setInterval(() => {+ this.flush(REPLICATION_CHANNEL, flushOutbound);+ this.flush(IP_CLASS_CHANNEL, flushOutboundIpClasses);}, BATCH_FLUSH_MS);- if (typeof flushTimer === 'object' && flushTimer && 'unref' in flushTimer) {- (flushTimer as {unref(): void}).unref();+ this.flushTimer.unref();+ }++ private assertActive(): void {+ if (!this.isActive) {+ throw new Error('Abuse replication subscriber is stopping or stopped');}+ }++ private flush(channel: string, publish: (publisher: IKVProvider) => Promise<void>): void {+ if (!this.isActive || this.flushes.has(channel)) return;+ const task = publish(this.publisher)+ .catch((err) => {+ Logger.error({err, channel}, '[abuse-auto-ban] Abuse replication flush failed');+ })+ .finally(() => {+ this.flushes.delete(channel);+ });+ this.flushes.set(channel, task);+ }++ stop(): Promise<void> {+ if (this.stopCompletion) return this.stopCompletion;+ this.phase = 'stopping';+ if (this.flushTimer) clearInterval(this.flushTimer);+ this.flushTimer = null;+ this.subscription.off('message', this.messageHandler);+ this.subscription.off('error', this.errorHandler);+ this.stopCompletion = this.close();+ return this.stopCompletion;+ }++ private async close(): Promise<void> {+ try {+ const [disconnected] = await Promise.allSettled([+ Promise.resolve().then(() => this.subscription.disconnect()),+ this.startCompletion,+ ...this.flushes.values(),+ ]);+ if (disconnected.status === 'rejected') throw disconnected.reason;+ } finally {+ this.phase = 'stopped';+ }+ }+}++export async function startAbuseReplicationSubscriber(kvClient: IKVProvider | null): Promise<void> {+ if (!kvClient) return;+ const subscriber = (abuseReplication ??= new AbuseReplicationSubscriber(kvClient));+ try {+ await subscriber.start();} catch (err) {Logger.error({err}, '[abuse-auto-ban] Failed to start abuse replication subscriber');- kvSubscription = null;- messageHandler = null;- errorHandler = null;- kvPublisher = null;+ try {+ await subscriber.stop();+ } catch (cleanupError) {+ Logger.error({err: cleanupError}, '[abuse-auto-ban] Failed to close abuse replication subscriber');+ } finally {+ if (abuseReplication === subscriber) abuseReplication = null;+ }throw err;}}export async function stopAbuseReplicationSubscriber(): Promise<void> {- if (flushTimer) {- clearInterval(flushTimer);- flushTimer = null;- }- if (kvSubscription && messageHandler) {- kvSubscription.off('message', messageHandler);- }- if (kvSubscription && errorHandler) {- kvSubscription.off('error', errorHandler);- }- if (kvSubscription) {- try {- await kvSubscription.disconnect();- } catch {}+ const subscriber = abuseReplication;+ if (!subscriber) return;+ try {+ await subscriber.stop();+ } finally {+ if (abuseReplication === subscriber) abuseReplication = null;}- kvSubscription = null;- messageHandler = null;- errorHandler = null;- kvPublisher = null;}export async function drainAbuseAutoBanTasksForTests(): Promise<void> {diff --git a/fluxer_api/src/api/middleware/BannedAvatarHashCache.ts b/fluxer_api/src/api/middleware/BannedAvatarHashCache.tsindex 842963b0c..6f979e406 100644--- a/fluxer_api/src/api/middleware/BannedAvatarHashCache.ts+++ b/fluxer_api/src/api/middleware/BannedAvatarHashCache.ts@@ -1,9 +1,10 @@// SPDX-License-Identifier: AGPL-3.0-or-later-import type {IKVProvider, IKVSubscription} from '@pkgs/kv_client/src/IKVProvider';+import type {IKVProvider} from '@pkgs/kv_client/src/IKVProvider';import {AdminRepository} from '../admin/AdminRepository';import {BANNED_AVATAR_HASHES_REFRESH_CHANNEL} from '../constants/ContentModeration';import {Logger} from '../Logger';+import {RefreshSubscription} from '../utils/RefreshSubscription';function stripAnimationPrefix(hash: string): string {return hash.startsWith('a_') ? hash.substring(2) : hash;@@ -11,55 +12,31 @@ function stripAnimationPrefix(hash: string): string {class BannedAvatarHashCache {private banned: Set<string> = new Set();- private isInitialized = false;private adminRepository = new AdminRepository();private kvClient: IKVProvider | null = null;- private kvSubscription: IKVSubscription | null = null;- private subscriberInitialized = false;- private messageHandler: ((channel: string) => void) | null = null;private consecutiveFailures = 0;private readonly maxConsecutiveFailures = 5;+ private readonly refreshSubscription = new RefreshSubscription({+ name: 'avatar-hash blocklist cache',+ channels: [BANNED_AVATAR_HASHES_REFRESH_CHANNEL],+ refresh: () => this.refresh(),+ onRefreshError: (err) => {+ this.consecutiveFailures++;+ const message = err instanceof Error ? err.message : String(err);+ if (this.consecutiveFailures >= this.maxConsecutiveFailures) {+ Logger.error({error: message}, 'Failed to refresh avatar-hash blocklist cache after notification');+ } else {+ Logger.warn({error: message}, 'Failed to refresh avatar-hash blocklist cache after notification');+ }+ },+ });setRefreshSubscriber(kvClient: IKVProvider | null): void {this.kvClient = kvClient;}- async initialize(): Promise<void> {- if (this.isInitialized) return;- await this.refresh();- this.isInitialized = true;- this.setupSubscriber();- }-- private setupSubscriber(): void {- if (this.subscriberInitialized || !this.kvClient) return;- const subscription = this.kvClient.duplicate();- this.kvSubscription = subscription;- this.messageHandler = (channel: string) => {- if (channel === BANNED_AVATAR_HASHES_REFRESH_CHANNEL) {- this.refresh().catch((err) => {- this.consecutiveFailures++;- const message = err instanceof Error ? err.message : String(err);- if (this.consecutiveFailures >= this.maxConsecutiveFailures) {- Logger.error({error: message}, 'Failed to refresh avatar-hash blocklist cache after notification');- } else {- Logger.warn({error: message}, 'Failed to refresh avatar-hash blocklist cache after notification');- }- });- }- };- subscription- .connect()- .then(() => subscription.subscribe(BANNED_AVATAR_HASHES_REFRESH_CHANNEL))- .then(() => {- if (this.messageHandler) {- subscription.on('message', this.messageHandler);- }- })- .catch((error) => {- Logger.error({error}, 'Failed to subscribe to avatar-hash blocklist refresh channel');- });- this.subscriberInitialized = true;+ initialize(): Promise<void> {+ return this.refreshSubscription.start(this.kvClient);}async refresh(): Promise<void> {@@ -90,23 +67,16 @@ class BannedAvatarHashCache {}resetForTesting(): void {- this.shutdown();+ void this.shutdown().catch((error) => {+ Logger.error({error}, 'Failed to shut down avatar-hash blocklist cache');+ });this.banned = new Set();this.kvClient = null;- this.subscriberInitialized = false;this.consecutiveFailures = 0;- this.isInitialized = false;}- shutdown(): void {- if (this.kvSubscription && this.messageHandler) {- this.kvSubscription.off('message', this.messageHandler);- }- if (this.kvSubscription) {- this.kvSubscription.disconnect();- this.kvSubscription = null;- }- this.messageHandler = null;+ shutdown(): Promise<void> {+ return this.refreshSubscription.stop();}}diff --git a/fluxer_api/src/api/middleware/FileShaCache.ts b/fluxer_api/src/api/middleware/FileShaCache.tsindex 53e4439f9..b852514fb 100644--- a/fluxer_api/src/api/middleware/FileShaCache.ts+++ b/fluxer_api/src/api/middleware/FileShaCache.ts@@ -1,61 +1,38 @@// SPDX-License-Identifier: AGPL-3.0-or-later-import type {IKVProvider, IKVSubscription} from '@pkgs/kv_client/src/IKVProvider';+import type {IKVProvider} from '@pkgs/kv_client/src/IKVProvider';import {AdminRepository} from '../admin/AdminRepository';import {BANNED_FILE_SHAS_REFRESH_CHANNEL} from '../constants/ContentModeration';import {Logger} from '../Logger';+import {RefreshSubscription} from '../utils/RefreshSubscription';class FileShaCache {private banned: Set<string> = new Set();- private isInitialized = false;private adminRepository = new AdminRepository();private kvClient: IKVProvider | null = null;- private kvSubscription: IKVSubscription | null = null;- private subscriberInitialized = false;- private messageHandler: ((channel: string) => void) | null = null;private consecutiveFailures = 0;private readonly maxConsecutiveFailures = 5;+ private readonly refreshSubscription = new RefreshSubscription({+ name: 'file-SHA blocklist cache',+ channels: [BANNED_FILE_SHAS_REFRESH_CHANNEL],+ refresh: () => this.refresh(),+ onRefreshError: (err) => {+ this.consecutiveFailures++;+ const message = err instanceof Error ? err.message : String(err);+ if (this.consecutiveFailures >= this.maxConsecutiveFailures) {+ Logger.error({error: message}, 'Failed to refresh file-SHA blocklist cache after notification');+ } else {+ Logger.warn({error: message}, 'Failed to refresh file-SHA blocklist cache after notification');+ }+ },+ });setRefreshSubscriber(kvClient: IKVProvider | null): void {this.kvClient = kvClient;}- async initialize(): Promise<void> {- if (this.isInitialized) return;- await this.refresh();- this.isInitialized = true;- this.setupSubscriber();- }-- private setupSubscriber(): void {- if (this.subscriberInitialized || !this.kvClient) return;- const subscription = this.kvClient.duplicate();- this.kvSubscription = subscription;- this.messageHandler = (channel: string) => {- if (channel === BANNED_FILE_SHAS_REFRESH_CHANNEL) {- this.refresh().catch((err) => {- this.consecutiveFailures++;- const message = err instanceof Error ? err.message : String(err);- if (this.consecutiveFailures >= this.maxConsecutiveFailures) {- Logger.error({error: message}, 'Failed to refresh file-SHA blocklist cache after notification');- } else {- Logger.warn({error: message}, 'Failed to refresh file-SHA blocklist cache after notification');- }- });- }- };- subscription- .connect()- .then(() => subscription.subscribe(BANNED_FILE_SHAS_REFRESH_CHANNEL))- .then(() => {- if (this.messageHandler) {- subscription.on('message', this.messageHandler);- }- })- .catch((error) => {- Logger.error({error}, 'Failed to subscribe to file-SHA blocklist refresh channel');- });- this.subscriberInitialized = true;+ initialize(): Promise<void> {+ return this.refreshSubscription.start(this.kvClient);}async refresh(): Promise<void> {@@ -86,23 +63,16 @@ class FileShaCache {}resetForTesting(): void {- this.shutdown();+ void this.shutdown().catch((error) => {+ Logger.error({error}, 'Failed to shut down file-SHA blocklist cache');+ });this.banned = new Set();this.kvClient = null;- this.subscriberInitialized = false;this.consecutiveFailures = 0;- this.isInitialized = false;}- shutdown(): void {- if (this.kvSubscription && this.messageHandler) {- this.kvSubscription.off('message', this.messageHandler);- }- if (this.kvSubscription) {- this.kvSubscription.disconnect();- this.kvSubscription = null;- }- this.messageHandler = null;+ shutdown(): Promise<void> {+ return this.refreshSubscription.stop();}}diff --git a/fluxer_api/src/api/middleware/IpBanMiddleware.ts b/fluxer_api/src/api/middleware/IpBanMiddleware.tsindex 293a59a92..fe9ae614a 100644--- a/fluxer_api/src/api/middleware/IpBanMiddleware.ts+++ b/fluxer_api/src/api/middleware/IpBanMiddleware.ts@@ -2,7 +2,7 @@import {IpBannedError} from '@fluxer/errors/src/domains/moderation/IpBannedError';import {getSameIpDecisionKey, type IpAddressFamily} from '@fluxer/ip_utils/src/IpAddress';-import type {IKVProvider, IKVSubscription} from '@pkgs/kv_client/src/IKVProvider';+import type {IKVProvider} from '@pkgs/kv_client/src/IKVProvider';import {createMiddleware} from 'hono/factory';import {AdminRepository} from '../admin/AdminRepository';import type {BannedIpEntry, BannedIpKind} from '../admin/IAdminRepository';@@ -11,6 +11,7 @@ import {Logger} from '../Logger';import {isIpBanExempt} from '../risk/IpBanExemptions';import type {HonoEnv} from '../types/HonoEnv';import {parseIpBanEntry, tryParseSingleIp} from '../utils/IpRangeUtils';+import {RefreshSubscription} from '../utils/RefreshSubscription';import {getRequestClientIp} from '../utils/RequestClientIp';type FamilyMap<T> = Record<IpAddressFamily, Map<string, T>>;@@ -59,15 +60,32 @@ class IpBanCache {private singleIpBans: FamilyMap<SingleCacheEntry>;private rangeIpBans: FamilyMap<RangeCacheEntry>;private sameIpDecisionBans: Map<string, IpBanCount>;- private isInitialized = false;private adminRepository = new AdminRepository();private consecutiveFailures = 0;- private maxConsecutiveFailures = 5;+ private readonly maxConsecutiveFailures = 5;private kvClient: IKVProvider | null = null;- private kvSubscription: IKVSubscription | null = null;- private subscriberInitialized = false;- private messageHandler: ((channel: string) => void) | null = null;- private periodicRefreshTimer: NodeJS.Timeout | null = null;+ private readonly refreshSubscription = new RefreshSubscription({+ name: 'IP ban cache',+ channels: [IP_BAN_REFRESH_CHANNEL],+ refresh: () => this.refresh(),+ periodicIntervalMs: () => {+ const intervalMs = Number(process.env.FLUXER_IP_BAN_REFRESH_INTERVAL_MS ?? '300000');+ return Number.isFinite(intervalMs) && intervalMs > 0 ? intervalMs : null;+ },+ onRefreshError: (err, trigger) => {+ const message = err instanceof Error ? err.message : String(err);+ if (trigger === 'periodic') {+ Logger.warn({error: message}, 'Periodic IP ban cache refresh failed');+ return;+ }+ this.consecutiveFailures++;+ if (this.consecutiveFailures >= this.maxConsecutiveFailures) {+ Logger.error({error: message}, 'Failed to refresh IP ban cache after notification');+ } else {+ Logger.warn({error: message}, 'Failed to refresh IP ban cache after notification');+ }+ },+ });constructor() {const state = this.createEmptyState();@@ -80,64 +98,8 @@ class IpBanCache {this.kvClient = kvClient;}- async initialize(): Promise<void> {- if (this.isInitialized) return;- await this.refresh();- this.isInitialized = true;- this.setupSubscriber();- this.startPeriodicRefresh();- }-- private startPeriodicRefresh(): void {- if (this.periodicRefreshTimer) return;- const intervalMs = Number(process.env.FLUXER_IP_BAN_REFRESH_INTERVAL_MS ?? '300000');- if (!Number.isFinite(intervalMs) || intervalMs <= 0) return;- this.periodicRefreshTimer = setInterval(() => {- this.refresh().catch((err) => {- const message = err instanceof Error ? err.message : String(err);- Logger.warn({error: message}, 'Periodic IP ban cache refresh failed');- });- }, intervalMs);- if (- typeof this.periodicRefreshTimer === 'object' &&- this.periodicRefreshTimer &&- 'unref' in this.periodicRefreshTimer- ) {- (this.periodicRefreshTimer as {unref(): void}).unref();- }- }-- private setupSubscriber(): void {- if (this.subscriberInitialized || !this.kvClient) {- return;- }- const subscription = this.kvClient.duplicate();- this.kvSubscription = subscription;- this.messageHandler = (channel: string) => {- if (channel === IP_BAN_REFRESH_CHANNEL) {- this.refresh().catch((err) => {- this.consecutiveFailures++;- const message = err instanceof Error ? err.message : String(err);- if (this.consecutiveFailures >= this.maxConsecutiveFailures) {- Logger.error({error: message}, 'Failed to refresh IP ban cache after notification');- } else {- Logger.warn({error: message}, 'Failed to refresh IP ban cache after notification');- }- });- }- };- subscription- .connect()- .then(() => subscription.subscribe(IP_BAN_REFRESH_CHANNEL))- .then(() => {- if (this.messageHandler) {- subscription.on('message', this.messageHandler);- }- })- .catch((error) => {- Logger.error({error}, 'Failed to subscribe to IP ban refresh channel');- });- this.subscriberInitialized = true;+ initialize(): Promise<void> {+ return this.refreshSubscription.start(this.kvClient);}async refresh(): Promise<void> {@@ -350,21 +312,8 @@ class IpBanCache {}}- shutdown(): void {- if (this.periodicRefreshTimer) {- clearInterval(this.periodicRefreshTimer);- this.periodicRefreshTimer = null;- }- if (this.kvSubscription && this.messageHandler) {- this.kvSubscription.off('message', this.messageHandler);- }- if (this.kvSubscription) {- void this.kvSubscription.disconnect();- this.kvSubscription = null;- }- this.messageHandler = null;- this.subscriberInitialized = false;- this.isInitialized = false;+ shutdown(): Promise<void> {+ return this.refreshSubscription.stop();}}diff --git a/fluxer_api/src/api/middleware/PhraseBlocklistCache.ts b/fluxer_api/src/api/middleware/PhraseBlocklistCache.tsindex a53c6dcad..860337e90 100644--- a/fluxer_api/src/api/middleware/PhraseBlocklistCache.ts+++ b/fluxer_api/src/api/middleware/PhraseBlocklistCache.ts@@ -1,10 +1,11 @@// SPDX-License-Identifier: AGPL-3.0-or-later-import type {IKVProvider, IKVSubscription} from '@pkgs/kv_client/src/IKVProvider';+import type {IKVProvider} from '@pkgs/kv_client/src/IKVProvider';import {AdminRepository} from '../admin/AdminRepository';import {BANNED_PHRASES_REFRESH_CHANNEL} from '../constants/ContentModeration';import {Logger} from '../Logger';import {buildPhraseMatchForms, canonicalizeStoredPhrase} from '../utils/PhraseBlocklistNormalization';+import {RefreshSubscription} from '../utils/RefreshSubscription';import {SubstringMatcher} from '../utils/SubstringMatcher';export class PhraseBlocklistCache {@@ -15,55 +16,31 @@ export class PhraseBlocklistCache {private compactMatcher: SubstringMatcher | null = null;private asciiWordMatcher: SubstringMatcher | null = null;private asciiCompactMatcher: SubstringMatcher | null = null;- private isInitialized = false;private adminRepository = new AdminRepository();private kvClient: IKVProvider | null = null;- private kvSubscription: IKVSubscription | null = null;- private subscriberInitialized = false;- private messageHandler: ((channel: string) => void) | null = null;private consecutiveFailures = 0;private readonly maxConsecutiveFailures = 5;+ private readonly refreshSubscription = new RefreshSubscription({+ name: 'phrase blocklist cache',+ channels: [BANNED_PHRASES_REFRESH_CHANNEL],+ refresh: () => this.refresh(),+ onRefreshError: (err) => {+ this.consecutiveFailures++;+ const message = err instanceof Error ? err.message : String(err);+ if (this.consecutiveFailures >= this.maxConsecutiveFailures) {+ Logger.error({error: message}, 'Failed to refresh phrase blocklist cache after notification');+ } else {+ Logger.warn({error: message}, 'Failed to refresh phrase blocklist cache after notification');+ }+ },+ });setRefreshSubscriber(kvClient: IKVProvider | null): void {this.kvClient = kvClient;}- async initialize(): Promise<void> {- if (this.isInitialized) return;- await this.refresh();- this.isInitialized = true;- this.setupSubscriber();- }-- private setupSubscriber(): void {- if (this.subscriberInitialized || !this.kvClient) return;- const subscription = this.kvClient.duplicate();- this.kvSubscription = subscription;- this.messageHandler = (channel: string) => {- if (channel === BANNED_PHRASES_REFRESH_CHANNEL) {- this.refresh().catch((err) => {- this.consecutiveFailures++;- const message = err instanceof Error ? err.message : String(err);- if (this.consecutiveFailures >= this.maxConsecutiveFailures) {- Logger.error({error: message}, 'Failed to refresh phrase blocklist cache after notification');- } else {- Logger.warn({error: message}, 'Failed to refresh phrase blocklist cache after notification');- }- });- }- };- subscription- .connect()- .then(() => subscription.subscribe(BANNED_PHRASES_REFRESH_CHANNEL))- .then(() => {- if (this.messageHandler) {- subscription.on('message', this.messageHandler);- }- })- .catch((error) => {- Logger.error({error}, 'Failed to subscribe to phrase blocklist refresh channel');- });- this.subscriberInitialized = true;+ initialize(): Promise<void> {+ return this.refreshSubscription.start(this.kvClient);}async refresh(): Promise<void> {@@ -140,25 +117,18 @@ export class PhraseBlocklistCache {}resetForTesting(): void {- this.shutdown();+ void this.shutdown().catch((error) => {+ Logger.error({error}, 'Failed to shut down phrase blocklist cache');+ });this.rawPhrases = [];this.rawPhraseSet = new Set();this.rebuildMatchers();this.kvClient = null;- this.subscriberInitialized = false;this.consecutiveFailures = 0;- this.isInitialized = false;}- shutdown(): void {- if (this.kvSubscription && this.messageHandler) {- this.kvSubscription.off('message', this.messageHandler);- }- if (this.kvSubscription) {- this.kvSubscription.disconnect();- this.kvSubscription = null;- }- this.messageHandler = null;+ shutdown(): Promise<void> {+ return this.refreshSubscription.stop();}}diff --git a/fluxer_api/src/api/middleware/ProfileSubstringBlocklistCache.ts b/fluxer_api/src/api/middleware/ProfileSubstringBlocklistCache.tsindex f177473dd..bea0463a1 100644--- a/fluxer_api/src/api/middleware/ProfileSubstringBlocklistCache.ts+++ b/fluxer_api/src/api/middleware/ProfileSubstringBlocklistCache.ts@@ -1,11 +1,12 @@// SPDX-License-Identifier: AGPL-3.0-or-later-import type {IKVProvider, IKVSubscription} from '@pkgs/kv_client/src/IKVProvider';+import type {IKVProvider} from '@pkgs/kv_client/src/IKVProvider';import {AdminRepository} from '../admin/AdminRepository';import {BANNED_PROFILE_SUBSTRINGS_REFRESH_CHANNEL} from '../constants/ContentModeration';import type {BannedProfileSubstringScope} from '../database/types/AdminArchiveTypes';import {Logger} from '../Logger';import {buildPhraseMatchForms, canonicalizeStoredPhrase} from '../utils/PhraseBlocklistNormalization';+import {RefreshSubscription} from '../utils/RefreshSubscription';type ProfileScope = BannedProfileSubstringScope;@@ -27,55 +28,31 @@ function emptyMatchers(): ScopeMatchers {export class ProfileSubstringBlocklistCache {private byScope: Map<ProfileScope, ScopeMatchers> = new Map();- private isInitialized = false;private adminRepository = new AdminRepository();private kvClient: IKVProvider | null = null;- private kvSubscription: IKVSubscription | null = null;- private subscriberInitialized = false;- private messageHandler: ((channel: string) => void) | null = null;private consecutiveFailures = 0;private readonly maxConsecutiveFailures = 5;+ private readonly refreshSubscription = new RefreshSubscription({+ name: 'profile-substring blocklist cache',+ channels: [BANNED_PROFILE_SUBSTRINGS_REFRESH_CHANNEL],+ refresh: () => this.refresh(),+ onRefreshError: (err) => {+ this.consecutiveFailures++;+ const message = err instanceof Error ? err.message : String(err);+ if (this.consecutiveFailures >= this.maxConsecutiveFailures) {+ Logger.error({error: message}, 'Failed to refresh profile-substring blocklist cache after notification');+ } else {+ Logger.warn({error: message}, 'Failed to refresh profile-substring blocklist cache after notification');+ }+ },+ });setRefreshSubscriber(kvClient: IKVProvider | null): void {this.kvClient = kvClient;}- async initialize(): Promise<void> {- if (this.isInitialized) return;- await this.refresh();- this.isInitialized = true;- this.setupSubscriber();- }-- private setupSubscriber(): void {- if (this.subscriberInitialized || !this.kvClient) return;- const subscription = this.kvClient.duplicate();- this.kvSubscription = subscription;- this.messageHandler = (channel: string) => {- if (channel === BANNED_PROFILE_SUBSTRINGS_REFRESH_CHANNEL) {- this.refresh().catch((err) => {- this.consecutiveFailures++;- const message = err instanceof Error ? err.message : String(err);- if (this.consecutiveFailures >= this.maxConsecutiveFailures) {- Logger.error({error: message}, 'Failed to refresh profile-substring blocklist cache after notification');- } else {- Logger.warn({error: message}, 'Failed to refresh profile-substring blocklist cache after notification');- }- });- }- };- subscription- .connect()- .then(() => subscription.subscribe(BANNED_PROFILE_SUBSTRINGS_REFRESH_CHANNEL))- .then(() => {- if (this.messageHandler) {- subscription.on('message', this.messageHandler);- }- })- .catch((error) => {- Logger.error({error}, 'Failed to subscribe to profile-substring blocklist refresh channel');- });- this.subscriberInitialized = true;+ initialize(): Promise<void> {+ return this.refreshSubscription.start(this.kvClient);}async refresh(): Promise<void> {@@ -181,23 +158,16 @@ export class ProfileSubstringBlocklistCache {}resetForTesting(): void {- this.shutdown();+ void this.shutdown().catch((error) => {+ Logger.error({error}, 'Failed to shut down profile-substring blocklist cache');+ });this.byScope = new Map();this.kvClient = null;- this.subscriberInitialized = false;this.consecutiveFailures = 0;- this.isInitialized = false;}- shutdown(): void {- if (this.kvSubscription && this.messageHandler) {- this.kvSubscription.off('message', this.messageHandler);- }- if (this.kvSubscription) {- this.kvSubscription.disconnect();- this.kvSubscription = null;- }- this.messageHandler = null;+ shutdown(): Promise<void> {+ return this.refreshSubscription.stop();}}diff --git a/fluxer_api/src/api/middleware/ServiceMiddleware.ts b/fluxer_api/src/api/middleware/ServiceMiddleware.tsindex 7c43f3930..500e88b10 100644--- a/fluxer_api/src/api/middleware/ServiceMiddleware.ts+++ b/fluxer_api/src/api/middleware/ServiceMiddleware.ts@@ -767,11 +767,7 @@ class RequestServices implements RequestScopedServices {}get connectionService(): ConnectionService {- this.cachedConnectionService ??= new ConnectionService(- getConnectionRepository(),- this.gatewayService,- this.bluesky,- );+ this.cachedConnectionService ??= new ConnectionService(getConnectionRepository(), this.gatewayService);return this.cachedConnectionService;}diff --git a/fluxer_api/src/api/middleware/ServiceRegistry.ts b/fluxer_api/src/api/middleware/ServiceRegistry.tsindex e5c0a95cb..e5a690b07 100644--- a/fluxer_api/src/api/middleware/ServiceRegistry.ts+++ b/fluxer_api/src/api/middleware/ServiceRegistry.ts@@ -26,30 +26,13 @@ import type {InstanceConfigRepository} from '../instance/InstanceConfigRepositorimport {Logger} from '../Logger';import {setInjectedSearchProvider} from '../SearchFactory';import type {ISearchProvider} from '../search/ISearchProvider';+import {readOptionalIntegerEnv} from '../utils/IntegerOptions';import {VoiceAvailabilityService} from '../voice/VoiceAvailabilityService';import {VoiceRepository} from '../voice/VoiceRepository';import {VoiceServerLoadTracker} from '../voice/VoiceServerLoad';import {VoiceTopology} from '../voice/VoiceTopology';import type {WorkerTaskName} from '../worker/WorkerLaneConfig';-const DEFAULT_SNOWFLAKE_SERVICE_BATCH_SIZE = 128;-const DEFAULT_SNOWFLAKE_SERVICE_LOW_WATERMARK = 32;-const DEFAULT_SNOWFLAKE_SERVICE_MAX_BUFFER_AGE_MS = 5000;-const DEFAULT_SNOWFLAKE_SERVICE_REQUEST_TIMEOUT_MS = 6000;--function readPositiveIntegerEnv(names: string | Array<string>, fallback: number): number {- const envNames = Array.isArray(names) ? names : [names];- const value = envNames.map((name) => process.env[name]).find((candidate) => candidate && candidate.length > 0);- if (!value) {- return fallback;- }- const parsed = Number(value);- if (!Number.isInteger(parsed) || parsed <= 0) {- return fallback;- }- return parsed;-}-export function createSnowflakeService(): SnowflakeService {const connectionManager = new NatsConnectionManager({url: Config.nats.coreUrl,@@ -58,24 +41,15 @@ export function createSnowflakeService(): SnowflakeService {});return new SnowflakeService({connectionManager,- subject: process.env.FLUXER_SNOWFLAKE_SERVICE_SUBJECT || 'svc.snowflakes',- batchSize: readPositiveIntegerEnv('FLUXER_SNOWFLAKE_SERVICE_BATCH_SIZE', DEFAULT_SNOWFLAKE_SERVICE_BATCH_SIZE),- lowWatermark: readPositiveIntegerEnv(- 'FLUXER_SNOWFLAKE_SERVICE_LOW_WATERMARK',- DEFAULT_SNOWFLAKE_SERVICE_LOW_WATERMARK,- ),- maxBufferAgeMs: readPositiveIntegerEnv(- 'FLUXER_SNOWFLAKE_SERVICE_MAX_BUFFER_AGE_MS',- DEFAULT_SNOWFLAKE_SERVICE_MAX_BUFFER_AGE_MS,- ),- requestTimeoutMs: readPositiveIntegerEnv(- 'FLUXER_SNOWFLAKE_SERVICE_REQUEST_TIMEOUT_MS',- DEFAULT_SNOWFLAKE_SERVICE_REQUEST_TIMEOUT_MS,- ),+ subject: process.env.FLUXER_SNOWFLAKE_SERVICE_SUBJECT || undefined,+ batchSize: readOptionalIntegerEnv('FLUXER_SNOWFLAKE_SERVICE_BATCH_SIZE'),+ lowWatermark: readOptionalIntegerEnv('FLUXER_SNOWFLAKE_SERVICE_LOW_WATERMARK'),+ maxBufferAgeMs: readOptionalIntegerEnv('FLUXER_SNOWFLAKE_SERVICE_MAX_BUFFER_AGE_MS'),+ requestTimeoutMs: readOptionalIntegerEnv('FLUXER_SNOWFLAKE_SERVICE_REQUEST_TIMEOUT_MS'),});}-let _kvClient: IKVProvider | null = null;+let _kvClient: KVClient | null = null;let _injectedKVProvider: IKVProvider | undefined;export function setInjectedKVProvider(provider: IKVProvider | undefined): void {@@ -97,6 +71,15 @@ export function getKVClient(): IKVProvider {return _kvClient;}+export function closeOwnedKVClient(): void {+ const client = _kvClient;+ if (client === null) {+ return;+ }+ client.close();+ _kvClient = null;+}+let _injectedWorkerService: IWorkerService<WorkerTaskName> | undefined;export function setInjectedWorkerService(service: IWorkerService<WorkerTaskName> | undefined): void {@@ -126,6 +109,11 @@ export function getGatewayService(): IGatewayService {let _snowflakeService: SnowflakeService | null = null;let _injectedSnowflakeService: ISnowflakeService | undefined;+export interface SnowflakeServiceHandle {+ readonly service: ISnowflakeService;+ readonly owned: boolean;+}+export function setInjectedSnowflakeService(service: ISnowflakeService | undefined): void {_injectedSnowflakeService = service;}@@ -140,6 +128,19 @@ export function getSnowflakeService(): ISnowflakeService {return _snowflakeService;}+export function acquireSnowflakeService(): SnowflakeServiceHandle {+ return {service: getSnowflakeService(), owned: _injectedSnowflakeService === undefined};+}++export async function releaseSnowflakeService({service, owned}: SnowflakeServiceHandle): Promise<void> {+ if (!owned) return;+ try {+ await service.shutdown();+ } finally {+ if (_snowflakeService === service) _snowflakeService = null;+ }+}+let _billingRepository: BillingRepository | null = null;let _injectedBillingRepository: BillingRepository | undefined;@@ -177,17 +178,26 @@ export function getInjectedSearchProvider(): ISearchProvider | undefined {return _injectedSearchProvider;}+interface BlueskyOAuthServiceSelection {+ readonly config: BlueskyOAuthConfig;+ readonly signature: string;+ readonly service: Promise<IBlueskyOAuthService>;+}+let _injectedBlueskyOAuthService: IBlueskyOAuthService | undefined;-let _blueskyOAuthService: IBlueskyOAuthService | undefined;-let _blueskyOAuthInitializationPromise: Promise<IBlueskyOAuthService> | null = null;-let _blueskyOAuthConfigSignature: string | null = null;-let _blueskyOAuthInitializationSignature: string | null = null;-let _blueskyOAuthSignatureSource: BlueskyOAuthConfig | null = null;-let _blueskyOAuthSignatureValue: string | null = null;+let _blueskyOAuthSelection: BlueskyOAuthServiceSelection | undefined;+let _blueskyOAuthGeneration = Symbol();let _disabledBlueskyOAuthService: DisabledBlueskyOAuthService | undefined;export function setInjectedBlueskyOAuthService(service: IBlueskyOAuthService | undefined): void {_injectedBlueskyOAuthService = service;+ resetBlueskyOAuthServiceCache();+}++function resetBlueskyOAuthServiceCache(): void {+ _blueskyOAuthSelection = undefined;+ _blueskyOAuthGeneration = Symbol();+ _disabledBlueskyOAuthService = undefined;}function getDisabledBlueskyOAuthService(): DisabledBlueskyOAuthService {@@ -197,14 +207,19 @@ function getDisabledBlueskyOAuthService(): DisabledBlueskyOAuthService {return _disabledBlueskyOAuthService;}-function getBlueskyOAuthConfigSignature(config: BlueskyOAuthConfig): string {- if (_blueskyOAuthSignatureSource === config && _blueskyOAuthSignatureValue !== null) {- return _blueskyOAuthSignatureValue;+async function createBlueskyOAuthService(config: BlueskyOAuthConfig): Promise<IBlueskyOAuthService> {+ const disabledService = getDisabledBlueskyOAuthService();+ if (!config.enabled) return disabledService;+ if (config.keys.length === 0) {+ Logger.warn('Bluesky OAuth is enabled but no signing keys are configured; disabling Bluesky OAuth.');+ return disabledService;+ }+ try {+ return await BlueskyOAuthService.create(config, getKVClient(), Config.endpoints.apiPublic);+ } catch (error) {+ Logger.error({error}, 'Bluesky OAuth initialization failed; disabling Bluesky OAuth for this configuration.');+ return disabledService;}- const signature = JSON.stringify(config);- _blueskyOAuthSignatureSource = config;- _blueskyOAuthSignatureValue = signature;- return signature;}export async function resolveBlueskyOAuthService(@@ -213,127 +228,150 @@ export async function resolveBlueskyOAuthService(if (_injectedBlueskyOAuthService) {return _injectedBlueskyOAuthService;}+ const generation = _blueskyOAuthGeneration;const blueskyConfig = instanceConfigRepository? await instanceConfigRepository.getEffectiveBlueskyConfig(): Config.auth.bluesky;- const signature = getBlueskyOAuthConfigSignature(blueskyConfig);- if (_blueskyOAuthService !== undefined && _blueskyOAuthConfigSignature === signature) {- return _blueskyOAuthService;+ if (_injectedBlueskyOAuthService) {+ return _injectedBlueskyOAuthService;+ }+ if (generation !== _blueskyOAuthGeneration) {+ throw new Error('Bluesky OAuth service resolution was invalidated before initialization');+ }+ const selection = _blueskyOAuthSelection;+ if (selection?.config === blueskyConfig) return selection.service;+ const signature = JSON.stringify(blueskyConfig);+ if (selection?.signature === signature) return selection.service;+ const next: BlueskyOAuthServiceSelection = {+ config: blueskyConfig,+ signature,+ service: createBlueskyOAuthService(blueskyConfig),+ };+ _blueskyOAuthSelection = next;+ return next.service;+}++interface VoiceResources {+ readonly topology: VoiceTopology | null;+ readonly availability: VoiceAvailabilityService | null;+ readonly liveKit: ILiveKitService;+ readonly roomStore: IVoiceRoomStore;+}++class VoiceResourceSession {+ readonly ready: Promise<void>;+ private current: VoiceResources | null = null;+ private stopCompletion: Promise<void> | null = null;++ constructor(+ private readonly topology: VoiceTopology | null,+ createResources: () => VoiceResources,+ ) {+ this.ready = Promise.resolve().then(() => this.initialize(createResources));+ }++ get resources(): VoiceResources | null {+ return this.current;+ }++ get isStopped(): boolean {+ return this.stopCompletion !== null;}- if (!blueskyConfig.enabled) {- _blueskyOAuthService = getDisabledBlueskyOAuthService();- _blueskyOAuthConfigSignature = signature;- return _blueskyOAuthService;++ private async initialize(createResources: () => VoiceResources): Promise<void> {+ try {+ if (this.isStopped) throw new Error('Voice resources stopped before initialization');+ await this.topology?.initialize();+ if (this.isStopped) throw new Error('Voice resources stopped during initialization');+ this.current = createResources();+ } catch (error) {+ try {+ await this.topology?.shutdown();+ } catch (cleanupError) {+ throw new AggregateError([error, cleanupError], 'Failed to initialize and close voice resources');+ }+ throw error;+ }}- if (blueskyConfig.keys.length === 0) {- Logger.warn(- 'Bluesky OAuth is enabled but no signing keys are configured – disabling. Run scripts/bootstrap/generate_bluesky_oauth_keys.sh or configure keys manually.',- );- _blueskyOAuthService = getDisabledBlueskyOAuthService();- _blueskyOAuthConfigSignature = signature;- return _blueskyOAuthService;++ shutdown(): Promise<void> {+ this.current = null;+ this.stopCompletion ??= this.close();+ return this.stopCompletion;}- if (!_blueskyOAuthInitializationPromise || _blueskyOAuthInitializationSignature !== signature) {- _blueskyOAuthInitializationSignature = signature;- _blueskyOAuthInitializationPromise = BlueskyOAuthService.create(- blueskyConfig,- getKVClient(),- Config.endpoints.apiPublic,- )- .then((service) => {- _blueskyOAuthService = service;- _blueskyOAuthConfigSignature = signature;- return service;- })- .catch((error) => {- Logger.error({error}, 'Bluesky OAuth signing keys were rejected – disabling Bluesky OAuth.');- _blueskyOAuthService = getDisabledBlueskyOAuthService();- _blueskyOAuthConfigSignature = signature;- return _blueskyOAuthService;- })- .finally(() => {- _blueskyOAuthInitializationPromise = null;- _blueskyOAuthInitializationSignature = null;- });++ private async close(): Promise<void> {+ const [closed] = await Promise.allSettled([this.topology?.shutdown(), this.ready]);+ if (closed.status === 'rejected') throw closed.reason;}- return _blueskyOAuthInitializationPromise;}-let voiceTopology: VoiceTopology | null = null;-let voiceAvailabilityService: VoiceAvailabilityService | null = null;-let liveKitServiceInstance: ILiveKitService | null = null;-let voiceRoomStoreInstance: IVoiceRoomStore | null = null;-let voiceConfigSubscriber: IKVProvider | null = null;-let voiceInitializationPromise: Promise<void> | null = null;+let voiceSession: VoiceResourceSession | null = null;+let voiceResourcesStopped = false;-export async function ensureVoiceResourcesInitialized(): Promise<void> {+function createVoiceSession(): VoiceResourceSession {if (!Config.voice.enabled) {- if (!liveKitServiceInstance) {- liveKitServiceInstance = new DisabledLiveKitService();- }- if (!voiceRoomStoreInstance) {- voiceRoomStoreInstance = new InMemoryVoiceRoomStore();- }- voiceTopology = null;- voiceAvailabilityService = null;- return;+ return new VoiceResourceSession(null, () => ({+ topology: null,+ availability: null,+ liveKit: new DisabledLiveKitService(),+ roomStore: new InMemoryVoiceRoomStore(),+ }));}- if (voiceTopology && voiceAvailabilityService && liveKitServiceInstance && voiceRoomStoreInstance) {- return;- }- if (!voiceInitializationPromise) {- voiceInitializationPromise = (async () => {- const voiceRepository = new VoiceRepository();- if (!voiceConfigSubscriber) {- voiceConfigSubscriber = getKVClient();- }- const topology = new VoiceTopology(voiceRepository, voiceConfigSubscriber);- await topology.initialize();- voiceTopology = topology;- voiceAvailabilityService = new VoiceAvailabilityService(- topology,- new VoiceServerLoadTracker({gatewayService: getGatewayService()}),- );- liveKitServiceInstance = new LiveKitService(topology);- voiceRoomStoreInstance = new VoiceRoomStore(getKVClient());- })().finally(() => {- voiceInitializationPromise = null;- });+ const kvClient = getKVClient();+ const gatewayService = getGatewayService();+ const topology = new VoiceTopology(new VoiceRepository(), kvClient);+ return new VoiceResourceSession(topology, () => ({+ topology,+ availability: new VoiceAvailabilityService(topology, new VoiceServerLoadTracker({gatewayService})),+ liveKit: new LiveKitService(topology),+ roomStore: new VoiceRoomStore(kvClient),+ }));+}++export async function ensureVoiceResourcesInitialized(): Promise<void> {+ if (voiceResourcesStopped) throw new Error('Voice resources are shut down');+ const session = (voiceSession ??= createVoiceSession());+ try {+ await session.ready;+ } catch (error) {+ if (voiceSession === session) voiceSession = null;+ throw error;}- await voiceInitializationPromise;+ if (voiceSession !== session) throw new Error('Voice resource initialization was superseded');+ if (session.isStopped) throw new Error('Voice resources stopped during initialization');+}++export async function shutdownVoiceResources(): Promise<void> {+ voiceResourcesStopped = true;+ await voiceSession?.shutdown();}export function getVoiceTopology(): VoiceTopology | null {- return voiceTopology;+ return voiceSession?.resources?.topology ?? null;}export function getVoiceAvailabilityService(): VoiceAvailabilityService | null {- return voiceAvailabilityService;+ return voiceSession?.resources?.availability ?? null;}export function getLiveKitServiceInstance(): ILiveKitService | null {- return liveKitServiceInstance;+ return voiceSession?.resources?.liveKit ?? null;}export function getVoiceRoomStoreInstance(): IVoiceRoomStore | null {- return voiceRoomStoreInstance;+ return voiceSession?.resources?.roomStore ?? null;}export function resetServiceRegistryForTesting(): void {_kvClient = null;_snowflakeService = null;_billingRepository = null;- _blueskyOAuthService = undefined;- _blueskyOAuthInitializationPromise = null;- _blueskyOAuthConfigSignature = null;- _blueskyOAuthInitializationSignature = null;- _blueskyOAuthSignatureSource = null;- _blueskyOAuthSignatureValue = null;- _disabledBlueskyOAuthService = undefined;- voiceTopology = null;- voiceAvailabilityService = null;- liveKitServiceInstance = null;- voiceRoomStoreInstance = null;- voiceConfigSubscriber = null;- voiceInitializationPromise = null;+ resetBlueskyOAuthServiceCache();+ const previousVoiceSession = voiceSession;+ voiceSession = null;+ voiceResourcesStopped = false;+ void previousVoiceSession?.shutdown().catch((error) => {+ Logger.error({error}, 'Failed to close voice resources during registry reset');+ });}diff --git a/fluxer_api/src/api/middleware/ServiceSingletons.ts b/fluxer_api/src/api/middleware/ServiceSingletons.tsindex 56036f04b..8e1a4c69f 100644--- a/fluxer_api/src/api/middleware/ServiceSingletons.ts+++ b/fluxer_api/src/api/middleware/ServiceSingletons.ts@@ -90,16 +90,20 @@ import {UserRepository} from '../user/repositories/UserRepository';import {VisionarySlotRepository} from '../user/repositories/VisionarySlotRepository';import {UserActivityBuffer} from '../user/services/UserActivityBuffer';import {UserContactChangeLogService} from '../user/services/UserContactChangeLogService';+import {awaitAll} from '../utils/ConcurrencyUtils';import {UserPermissionUtils} from '../utils/UserPermissionUtils';import {VoiceRepository} from '../voice/VoiceRepository';import {SweegoWebhookService} from '../webhook/SweegoWebhookService';import {WebhookRepository} from '../webhook/WebhookRepository';import {+ acquireSnowflakeService,getGatewayService,getKVClient,getMediaService,getSnowflakeService,getWorkerService,+ releaseSnowflakeService,+ type SnowflakeServiceHandle,} from './ServiceRegistry';import {clearSingletonsForTesting, singleton} from './Singleton';@@ -123,10 +127,25 @@ export const getPasswordChangeRepository = singleton(() => new PasswordChangeRepconst getUserContactChangeLogRepository = singleton(() => new UserContactChangeLogRepository());export const getDonationRepository = singleton(() => new DonationRepository());const getAdminApiKeyRepository = singleton(() => new AdminApiKeyRepository());+let instanceConfigRepositoryInstance: InstanceConfigRepository | null = null;export const getInstanceConfigRepository = singleton(- () => new InstanceConfigRepository(getKVClient()),- (repository) => repository.shutdown(),+ () => {+ const repository = new InstanceConfigRepository(getKVClient());+ instanceConfigRepositoryInstance = repository;+ return repository;+ },+ (repository) => {+ if (instanceConfigRepositoryInstance === repository) instanceConfigRepositoryInstance = null;+ void repository.shutdown().catch((error) => {+ Logger.error({error}, 'Failed to shut down instance config repository');+ });+ },);++export async function shutdownInstanceConfigRepository(): Promise<void> {+ await instanceConfigRepositoryInstance?.shutdown();+}+export const getGatewayRolloutConfigPublisher = singleton(() =>new GatewayRolloutConfigPublisher(@@ -203,9 +222,22 @@ const getDownloadsStorageService: () => IStorageService = (() => {return () => override() ?? getStorageService();})();export const getErrorI18nService = singleton(() => new ErrorI18nService());+let limitConfigServiceInstance: LimitConfigService | null = null;export const getLimitConfigService = singleton(- () => new LimitConfigService(getInstanceConfigRepository(), getCacheService(), getKVClient()),- (service) => service.shutdown(),+ () => {+ const service = new LimitConfigService(getInstanceConfigRepository(), getCacheService(), getKVClient());+ limitConfigServiceInstance = service;+ return service;+ },+ (service) => {+ const shutdown = limitConfigServiceInstance === service ? shutdownServiceSingletons() : service.shutdown();+ if (limitConfigServiceInstance === service) {+ limitConfigServiceInstance = null;+ }+ void shutdown.catch((err) => {+ Logger.error({err}, 'Failed to shut down service singletons');+ });+ },);export const getPurgeQueue: () => IPurgeQueue = singleton(() =>Config.bunny.purgeEnabled ? new BunnyPurgeQueue(getKVClient()) : new NoopPurgeQueue(),@@ -455,26 +487,102 @@ export function createUserCacheService(): UserCacheService {return new UserCacheService(createUsersServiceClient());}+interface ServiceSingletonInitializationOwner {+ stopping: boolean;+ snowflake: SnowflakeServiceHandle;+ limitConfigService: LimitConfigService | null;+}++let serviceSingletonInitializationOwner: ServiceSingletonInitializationOwner | null = null;let serviceSingletonInitializationPromise: Promise<void> | null = null;+let serviceSingletonShutdownPromise: Promise<void> | null = null;++function assertServiceSingletonInitializationActive(owner: ServiceSingletonInitializationOwner): void {+ if (owner.stopping) {+ throw new Error('Service singleton initialization was stopped');+ }+}export async function initializeServiceSingletons(): Promise<void> {+ if (serviceSingletonShutdownPromise) {+ throw new Error('Service singletons are shutting down');+ }if (!serviceSingletonInitializationPromise) {+ const owner: ServiceSingletonInitializationOwner = {+ stopping: false,+ snowflake: acquireSnowflakeService(),+ limitConfigService: null,+ };+ serviceSingletonInitializationOwner = owner;serviceSingletonInitializationPromise = (async () => {- const snowflakeService = getSnowflakeService();- await snowflakeService.initialize();+ await owner.snowflake.service.initialize();+ assertServiceSingletonInitializationActive(owner);const limitConfigService = getLimitConfigService();+ owner.limitConfigService = limitConfigService;+ await getInstanceConfigRepository().initialize();+ assertServiceSingletonInitializationActive(owner);await limitConfigService.initialize();+ assertServiceSingletonInitializationActive(owner);limitConfigService.setAsGlobalInstance();})();}- await serviceSingletonInitializationPromise;+ const initialization = serviceSingletonInitializationPromise;+ try {+ await initialization;+ } catch (error) {+ if (serviceSingletonInitializationPromise === initialization) {+ try {+ await shutdownServiceSingletons();+ } catch (cleanupError) {+ throw new AggregateError([error, cleanupError], 'Service singleton initialization and cleanup failed');+ }+ }+ throw error;+ }+}++export async function shutdownServiceSingletons(): Promise<void> {+ if (serviceSingletonShutdownPromise) {+ return await serviceSingletonShutdownPromise;+ }+ const initialization = serviceSingletonInitializationPromise;+ const owner = serviceSingletonInitializationOwner;+ const service = owner?.limitConfigService ?? limitConfigServiceInstance;+ if (!initialization && !owner && !service) return;+ if (owner) owner.stopping = true;+ const shutdown = awaitAll(+ [+ Promise.resolve().then(() => service?.shutdown()),+ (async () => {+ await Promise.allSettled([initialization]);+ if (owner) await releaseSnowflakeService(owner.snowflake);+ })(),+ ],+ 'Failed to shut down service singletons',+ );+ serviceSingletonShutdownPromise = shutdown;+ try {+ await shutdown;+ } finally {+ if (serviceSingletonInitializationPromise === initialization) {+ serviceSingletonInitializationPromise = null;+ }+ if (serviceSingletonInitializationOwner === owner) {+ serviceSingletonInitializationOwner = null;+ }+ if (serviceSingletonShutdownPromise === shutdown) {+ serviceSingletonShutdownPromise = null;+ }+ }}export function resetServiceSingletonsForTesting(): void {+ void shutdownServiceSingletons().catch((error) => {+ Logger.error({error}, 'Failed to reset service singletons');+ });activityTracker?.shutdown();clearSingletonsForTesting();_virusScanInitPromise = null;- serviceSingletonInitializationPromise = null;bulkMessageDeletionQueue = null;bulkMessageDeletionQueueClient = null;premiumStateQueue = null;diff --git a/fluxer_api/src/api/middleware/TorExitListCache.ts b/fluxer_api/src/api/middleware/TorExitListCache.tsindex a5fa81fee..a33141bbf 100644--- a/fluxer_api/src/api/middleware/TorExitListCache.ts+++ b/fluxer_api/src/api/middleware/TorExitListCache.ts@@ -1,13 +1,17 @@// SPDX-License-Identifier: AGPL-3.0-or-laterimport {randomInt, randomUUID} from 'node:crypto';+import {setTimeout as delay} from 'node:timers/promises';import {parseIpAddress} from '@fluxer/ip_utils/src/IpAddress';import type {IKVProvider} from '@pkgs/kv_client/src/IKVProvider';+import {z} from 'zod';import {Logger} from '../Logger';+import {streamToStringWithLimit} from '../utils/FetchUtils';const ONIONOO_URL ='https://onionoo.torproject.org/details?type=relay&running=true&flag=Exit&fields=exit_addresses,or_addresses';const FETCH_TIMEOUT_MS = 30000;+const MAX_RESPONSE_BYTES = 8 * 1024 * 1024;const REFRESH_INTERVAL_MS = 30 * 60 * 1000;const REFRESH_JITTER_MS = 2 * 60 * 1000;const OPPORTUNISTIC_REFRESH_MIN_MS = 60000;@@ -20,17 +24,19 @@ const HYDRATE_WAIT_MS = 60000;const HYDRATE_POLL_MIN_MS = 500;const HYDRATE_POLL_MAX_MS = 5000;-type FetchResult =- | {- kind: 'fetched';- payload: string;- }- | {- kind: 'not_modified';- }- | {- kind: 'failed';- };+const OnionooDetailsSchema = z.object({+ relays: z.array(+ z.object({+ or_addresses: z.array(z.string()).optional(),+ exit_addresses: z.array(z.string()).optional(),+ }),+ ),+});++interface TorExitSnapshot {+ readonly payload: string;+ readonly lastModified: string | null;+}class TorExitListCache {private ipv4Exits: ReadonlySet<string> = new Set();@@ -38,32 +44,41 @@ class TorExitListCache {private kvClient: IKVProvider | null = null;private refreshTimer: NodeJS.Timeout | null = null;private initPromise: Promise<void> | null = null;- private lastModified: string | null = null;- private inflightFetch: AbortController | null = null;+ private refreshPromise: Promise<void> | null = null;+ private shutdownPromise: Promise<void> | null = null;+ private lifecycle = new AbortController();+ private fetchedSnapshot: TorExitSnapshot | null = null;setKvClient(kv: IKVProvider | null): void {this.kvClient = kv;}initialize(): Promise<void> {+ if (this.shutdownPromise) return Promise.reject(new Error('Tor exit list cache is shutting down'));+ if (this.lifecycle.signal.aborted) this.lifecycle = new AbortController();if (!this.initPromise) {- this.initPromise = this.doInitialize().catch((err) => {- this.initPromise = null;- throw err;- });+ this.initPromise = Promise.resolve(this.refreshPromise)+ .then(() => this.doInitialize())+ .catch((err) => {+ this.initPromise = null;+ throw err;+ });}return this.initPromise;}- shutdown(): void {+ shutdown(): Promise<void> {+ if (this.shutdownPromise) return this.shutdownPromise;+ this.lifecycle.abort(new Error('Tor exit list cache is shut down'));if (this.refreshTimer) {clearTimeout(this.refreshTimer);this.refreshTimer = null;}- if (this.inflightFetch) {- this.inflightFetch.abort();- this.inflightFetch = null;- }+ this.shutdownPromise = Promise.allSettled([this.initPromise, this.refreshPromise]).then(() => {+ this.initPromise = null;+ this.shutdownPromise = null;+ });+ return this.shutdownPromise;}isTorExit(ip: string): boolean {@@ -73,7 +88,7 @@ class TorExitListCache {}async forceRefresh(): Promise<void> {- await this.tryRefresh();+ await this.refresh();}seedForTesting(ips: Iterable<string>): void {@@ -83,11 +98,13 @@ class TorExitListCache {clearForTesting(): void {this.ipv4Exits = new Set();this.ipv6Exits = new Set();+ this.fetchedSnapshot = null;}private async doInitialize(): Promise<void> {+ this.lifecycle.signal.throwIfAborted();const cached = await this.readPayloadFromKv();- if (cached) {+ if (cached !== null) {this.applyPayload(cached);Logger.info({ipv4Count: this.ipv4Exits.size, ipv6Count: this.ipv6Exits.size}, 'Tor exit list hydrated from KV');this.scheduleNextRefresh(this.opportunisticRefreshDelayMs());@@ -98,6 +115,8 @@ class TorExitListCache {}private scheduleNextRefresh(baseDelayMs: number): void {+ const signal = this.lifecycle.signal;+ if (signal.aborted) return;if (this.refreshTimer) {clearTimeout(this.refreshTimer);this.refreshTimer = null;@@ -106,12 +125,14 @@ class TorExitListCache {const delay = Math.max(1000, baseDelayMs + jitter);this.refreshTimer = setTimeout(() => {this.refreshTimer = null;- this.tryRefresh()+ this.refresh().catch((err) => {- Logger.warn({error: err instanceof Error ? err.message : String(err)}, 'Tor exit list refresh failed');+ if (!signal.aborted) {+ Logger.warn({error: err instanceof Error ? err.message : String(err)}, 'Tor exit list refresh failed');+ }}).finally(() => {- this.scheduleNextRefresh(REFRESH_INTERVAL_MS);+ if (!signal.aborted) this.scheduleNextRefresh(REFRESH_INTERVAL_MS);});}, delay);this.refreshTimer.unref?.();@@ -122,24 +143,35 @@ class TorExitListCache {return OPPORTUNISTIC_REFRESH_MIN_MS + randomInt(range);}+ private async refresh(): Promise<void> {+ this.lifecycle.signal.throwIfAborted();+ this.refreshPromise ??= Promise.resolve(this.initPromise)+ .then(() => this.tryRefresh())+ .finally(() => {+ this.refreshPromise = null;+ });+ await this.refreshPromise;+ }+private async tryRefresh(): Promise<void> {+ this.lifecycle.signal.throwIfAborted();const kv = this.kvClient;- if (!kv) return;+ if (!kv) {+ const payload = await this.fetchFromTor();+ if (payload !== null) this.applyPayload(payload);+ return;+ }await this.withKvLock(kv, async (acquired) => {if (!acquired) {const cached = await this.readPayloadFromKv();- if (cached) this.applyPayload(cached);+ if (cached !== null) this.applyPayload(cached);return;}- const result = await this.fetchFromTor();- if (result.kind !== 'fetched') return;- await kv.setex(KV_PAYLOAD_KEY, PAYLOAD_TTL_SECONDS, result.payload).catch((err) => {- Logger.warn(- {error: err instanceof Error ? err.message : String(err)},- 'Failed to write Tor exit list payload to KV',- );- });- this.applyPayload(result.payload);+ const payload = await this.fetchFromTor();+ this.lifecycle.signal.throwIfAborted();+ if (payload === null) return;+ await this.writePayloadToKv(kv, payload);+ this.applyPayload(payload);Logger.info({ipv4Count: this.ipv4Exits.size, ipv6Count: this.ipv6Exits.size}, 'Tor exit list refreshed');});}@@ -147,9 +179,9 @@ class TorExitListCache {private async hydrateFromTorOrWait(): Promise<void> {const kv = this.kvClient;if (!kv) {- const result = await this.fetchFromTor();- if (result.kind === 'fetched') {- this.applyPayload(result.payload);+ const payload = await this.fetchFromTor();+ if (payload !== null) {+ this.applyPayload(payload);return;}Logger.warn('Tor exit list bootstrap could not fetch; continuing with empty list');@@ -157,13 +189,14 @@ class TorExitListCache {}const fetchedAsWinner = await this.withKvLock(kv, async (acquired) => {if (!acquired) return false;- const result = await this.fetchFromTor();- if (result.kind !== 'fetched') {+ const payload = await this.fetchFromTor();+ this.lifecycle.signal.throwIfAborted();+ if (payload === null) {Logger.warn('Tor exit list bootstrap could not fetch; continuing with empty list');return true;}- await kv.setex(KV_PAYLOAD_KEY, PAYLOAD_TTL_SECONDS, result.payload).catch(() => undefined);- this.applyPayload(result.payload);+ await this.writePayloadToKv(kv, payload);+ this.applyPayload(payload);Logger.info({ipv4Count: this.ipv4Exits.size, ipv6Count: this.ipv6Exits.size},'Tor exit list fetched and hydrated on startup',@@ -172,7 +205,7 @@ class TorExitListCache {});if (fetchedAsWinner) return;const cached = await this.pollForPeerPayload();- if (cached) {+ if (cached !== null) {this.applyPayload(cached);Logger.info({ipv4Count: this.ipv4Exits.size, ipv6Count: this.ipv6Exits.size},@@ -181,30 +214,32 @@ class TorExitListCache {return;}Logger.warn('Tor exit list not available via KV after wait; fetching directly');- const result = await this.fetchFromTor();- if (result.kind !== 'fetched') {+ const payload = await this.fetchFromTor();+ if (payload === null) {Logger.warn('Tor exit list bootstrap could not fetch; continuing with empty list');return;}- this.applyPayload(result.payload);+ this.applyPayload(payload);}private async pollForPeerPayload(): Promise<string | null> {const deadline = Date.now() + HYDRATE_WAIT_MS;let backoff = HYDRATE_POLL_MIN_MS;while (Date.now() < deadline) {- await sleep(backoff);+ await delay(backoff, undefined, {signal: this.lifecycle.signal});const cached = await this.readPayloadFromKv();- if (cached) return cached;+ if (cached !== null) return cached;backoff = Math.min(backoff * 2, HYDRATE_POLL_MAX_MS);}return null;}private async withKvLock<T>(kv: IKVProvider, fn: (acquired: boolean) => Promise<T>): Promise<T> {+ this.lifecycle.signal.throwIfAborted();const lockToken = randomUUID();const acquired = await kv.acquireLock(KV_LOCK_KEY, lockToken, LOCK_TTL_SECONDS).catch(() => false);try {+ this.lifecycle.signal.throwIfAborted();return await fn(acquired);} finally {if (acquired) {@@ -219,104 +254,129 @@ class TorExitListCache {}private async readPayloadFromKv(): Promise<string | null> {+ this.lifecycle.signal.throwIfAborted();const kv = this.kvClient;if (!kv) return null;try {- return await kv.get(KV_PAYLOAD_KEY);+ const payload = await kv.get(KV_PAYLOAD_KEY);+ this.lifecycle.signal.throwIfAborted();+ return payload;} catch (err) {+ this.lifecycle.signal.throwIfAborted();Logger.warn({error: err instanceof Error ? err.message : String(err)}, 'Failed reading Tor exit list from KV');return null;}}- private async fetchFromTor(): Promise<FetchResult> {- const controller = new AbortController();- const timeout = setTimeout(() => controller.abort(), FETCH_TIMEOUT_MS);- this.inflightFetch = controller;+ private async writePayloadToKv(kv: IKVProvider, payload: string): Promise<void> {+ this.lifecycle.signal.throwIfAborted();+ try {+ await kv.setex(KV_PAYLOAD_KEY, PAYLOAD_TTL_SECONDS, payload);+ } catch (err) {+ Logger.warn(+ {error: err instanceof Error ? err.message : String(err)},+ 'Failed to write Tor exit list payload to KV',+ );+ }+ }++ private async fetchFromTor(): Promise<string | null> {+ const signal = this.lifecycle.signal;+ signal.throwIfAborted();+ const requestSignal = AbortSignal.any([AbortSignal.timeout(FETCH_TIMEOUT_MS), signal]);+ const snapshot = this.fetchedSnapshot;try {const headers: Record<string, string> = {Accept: 'application/json','Accept-Encoding': 'gzip',};- if (this.lastModified) {- headers['If-Modified-Since'] = this.lastModified;+ if (snapshot?.lastModified) {+ headers['If-Modified-Since'] = snapshot.lastModified;}const res = await fetch(ONIONOO_URL, {- signal: controller.signal,+ signal: requestSignal,headers,});if (res.status === 304) {- return {kind: 'not_modified'};+ if (!snapshot?.lastModified) throw new Error('Onionoo returned 304 without a cached response');+ return snapshot.payload;}- if (!res.ok) {+ if (res.status !== 200) {+ await res.body?.cancel();Logger.warn({status: res.status}, 'Onionoo fetch returned non-OK status');- return {kind: 'failed'};+ return null;}- const body = (await res.json()) as {- relays?: ReadonlyArray<{- exit_addresses?: ReadonlyArray<string>;- or_addresses?: ReadonlyArray<string>;- }>;- };+ const text = await streamToStringWithLimit(res.body, {+ maxBytes: MAX_RESPONSE_BYTES,+ headers: res.headers,+ description: 'Onionoo response',+ signal: requestSignal,+ });+ const parsed = OnionooDetailsSchema.safeParse(JSON.parse(text));+ if (!parsed.success) throw new Error('Onionoo returned invalid relay data');+ signal.throwIfAborted();const ips = new Set<string>();- for (const relay of body.relays ?? []) {- for (const addr of relay.exit_addresses ?? []) {- const ip = stripHostPort(addr);- if (ip) ips.add(ip);- }- for (const addr of relay.or_addresses ?? []) {- const ip = stripHostPort(addr);- if (ip) ips.add(ip);+ let invalidCount = 0;+ for (const relay of parsed.data.relays) {+ for (const address of [...(relay.or_addresses ?? []), ...(relay.exit_addresses ?? [])]) {+ const ip = parseIpAddress(stripHostPort(address) ?? '');+ if (!ip) {+ invalidCount++;+ continue;+ }+ ips.add(ip.normalized);}}- const lastModified = res.headers.get('last-modified');- if (lastModified) this.lastModified = lastModified;- return {kind: 'fetched', payload: Array.from(ips).join('\n')};+ if (invalidCount > 0) {+ Logger.warn({invalidCount}, 'Onionoo returned relay addresses that could not be parsed');+ }+ if (ips.size === 0 && parsed.data.relays.length > 0) {+ Logger.error(+ {relays: parsed.data.relays.length},+ 'Onionoo returned no usable relay addresses, keeping the current Tor exit list',+ );+ return null;+ }+ const payload = Array.from(ips).join('\n');+ this.fetchedSnapshot = {payload, lastModified: res.headers.get('last-modified')};+ return payload;} catch (err) {- const name = (- err as- | {- name?: string;- }- | undefined- )?.name;- if (name === 'AbortError') {- Logger.warn('Onionoo fetch aborted (timeout or shutdown)');+ signal.throwIfAborted();+ if (requestSignal.aborted) {+ Logger.warn('Onionoo fetch timed out');} else {Logger.warn({error: err instanceof Error ? err.message : String(err)}, 'Onionoo fetch failed');}- return {kind: 'failed'};- } finally {- clearTimeout(timeout);- if (this.inflightFetch === controller) {- this.inflightFetch = null;- }+ return null;}}private applyPayload(payload: string): void {const ipv4 = new Set<string>();const ipv6 = new Set<string>();+ let invalidCount = 0;for (const rawLine of payload.split('\n')) {const value = rawLine.trim();if (!value) continue;const parsed = parseIpAddress(value);- if (!parsed) continue;+ if (!parsed) {+ invalidCount++;+ continue;+ }if (parsed.family === 'ipv4') {ipv4.add(parsed.normalized);} else {ipv6.add(parsed.normalized);}}+ if (invalidCount > 0) {+ Logger.warn({invalidCount}, 'Tor exit list payload contained lines that could not be parsed');+ }this.ipv4Exits = ipv4;this.ipv6Exits = ipv6;}}-function sleep(ms: number): Promise<void> {- return new Promise((resolve) => setTimeout(resolve, ms));-}-function stripHostPort(value: string): string | null {const trimmed = value.trim();if (!trimmed) return null;diff --git a/fluxer_api/src/api/middleware/UrlBlocklistCache.ts b/fluxer_api/src/api/middleware/UrlBlocklistCache.tsindex 95b27aee9..0dec7e162 100644--- a/fluxer_api/src/api/middleware/UrlBlocklistCache.ts+++ b/fluxer_api/src/api/middleware/UrlBlocklistCache.ts@@ -1,25 +1,36 @@// SPDX-License-Identifier: AGPL-3.0-or-later-import type {IKVProvider, IKVSubscription} from '@pkgs/kv_client/src/IKVProvider';+import type {IKVProvider} from '@pkgs/kv_client/src/IKVProvider';import {AdminRepository} from '../admin/AdminRepository';import {BANNED_URL_DOMAINS_REFRESH_CHANNEL, BANNED_URLS_REFRESH_CHANNEL} from '../constants/ContentModeration';import type {IStorageService} from '../infrastructure/IStorageService';import {Logger} from '../Logger';import {RISK_S3_KEYS, readLinesFromS3} from '../risk/RiskBlocklistS3';+import {RefreshSubscription} from '../utils/RefreshSubscription';import {canonicalizeUrl} from '../utils/UrlNormalizer';class UrlBlocklistCache {private exactUrls: Set<string> = new Set();private blockedDomains: Set<string> = new Set();- private isInitialized = false;private adminRepository = new AdminRepository();private kvClient: IKVProvider | null = null;private storageService: IStorageService | null = null;- private kvSubscription: IKVSubscription | null = null;- private subscriberInitialized = false;- private messageHandler: ((channel: string) => void) | null = null;private consecutiveFailures = 0;private readonly maxConsecutiveFailures = 5;+ private readonly refreshSubscription = new RefreshSubscription({+ name: 'URL blocklist cache',+ channels: [BANNED_URLS_REFRESH_CHANNEL, BANNED_URL_DOMAINS_REFRESH_CHANNEL],+ refresh: () => this.refresh(),+ onRefreshError: (err) => {+ this.consecutiveFailures++;+ const message = err instanceof Error ? err.message : String(err);+ if (this.consecutiveFailures >= this.maxConsecutiveFailures) {+ Logger.error({error: message}, 'Failed to refresh URL blocklist cache after notification');+ } else {+ Logger.warn({error: message}, 'Failed to refresh URL blocklist cache after notification');+ }+ },+ });setRefreshSubscriber(kvClient: IKVProvider | null): void {this.kvClient = kvClient;@@ -29,43 +40,8 @@ class UrlBlocklistCache {this.storageService = storageService;}- async initialize(): Promise<void> {- if (this.isInitialized) return;- await this.refresh();- this.isInitialized = true;- this.setupSubscriber();- }-- private setupSubscriber(): void {- if (this.subscriberInitialized || !this.kvClient) return;- const subscription = this.kvClient.duplicate();- this.kvSubscription = subscription;- this.messageHandler = (channel: string) => {- if (channel === BANNED_URLS_REFRESH_CHANNEL || channel === BANNED_URL_DOMAINS_REFRESH_CHANNEL) {- this.refresh().catch((err) => {- this.consecutiveFailures++;- const message = err instanceof Error ? err.message : String(err);- if (this.consecutiveFailures >= this.maxConsecutiveFailures) {- Logger.error({error: message}, 'Failed to refresh URL blocklist cache after notification');- } else {- Logger.warn({error: message}, 'Failed to refresh URL blocklist cache after notification');- }- });- }- };- subscription- .connect()- .then(() => subscription.subscribe(BANNED_URLS_REFRESH_CHANNEL))- .then(() => subscription.subscribe(BANNED_URL_DOMAINS_REFRESH_CHANNEL))- .then(() => {- if (this.messageHandler) {- subscription.on('message', this.messageHandler);- }- })- .catch((error) => {- Logger.error({error}, 'Failed to subscribe to URL blocklist refresh channels');- });- this.subscriberInitialized = true;+ initialize(): Promise<void> {+ return this.refreshSubscription.start(this.kvClient);}async refresh(): Promise<void> {@@ -147,25 +123,18 @@ class UrlBlocklistCache {}resetForTesting(): void {- this.shutdown();+ void this.shutdown().catch((error) => {+ Logger.error({error}, 'Failed to shut down URL blocklist cache');+ });this.exactUrls = new Set();this.blockedDomains = new Set();this.kvClient = null;this.storageService = null;- this.subscriberInitialized = false;this.consecutiveFailures = 0;- this.isInitialized = false;}- shutdown(): void {- if (this.kvSubscription && this.messageHandler) {- this.kvSubscription.off('message', this.messageHandler);- }- if (this.kvSubscription) {- this.kvSubscription.disconnect();- this.kvSubscription = null;- }- this.messageHandler = null;+ shutdown(): Promise<void> {+ return this.refreshSubscription.stop();}}diff --git a/fluxer_api/src/api/models/User.ts b/fluxer_api/src/api/models/User.tsindex c59012ca9..3b7550fec 100644--- a/fluxer_api/src/api/models/User.ts+++ b/fluxer_api/src/api/models/User.ts@@ -64,6 +64,7 @@ export class User {readonly pendingBulkMessageDeletionChannelCount: number | null;readonly pendingBulkMessageDeletionMessageCount: number | null;readonly pendingDeletionAt: Date | null;+ readonly deletionStartedAt: Date | null;readonly deletionReasonCode: number | null;readonly deletionPublicReason: string | null;readonly deletionAuditLogReason: string | null;@@ -127,6 +128,7 @@ export class User {this.pendingBulkMessageDeletionChannelCount = row.pending_bulk_message_deletion_channel_count ?? null;this.pendingBulkMessageDeletionMessageCount = row.pending_bulk_message_deletion_message_count ?? null;this.pendingDeletionAt = row.pending_deletion_at ?? null;+ this.deletionStartedAt = row.deletion_started_at ?? null;this.deletionReasonCode = row.deletion_reason_code ?? null;this.deletionPublicReason = row.deletion_public_reason ?? null;this.deletionAuditLogReason = row.deletion_audit_log_reason ?? null;@@ -217,6 +219,7 @@ export class User {pending_bulk_message_deletion_channel_count: this.pendingBulkMessageDeletionChannelCount,pending_bulk_message_deletion_message_count: this.pendingBulkMessageDeletionMessageCount,pending_deletion_at: this.pendingDeletionAt,+ deletion_started_at: this.deletionStartedAt,deletion_reason_code: this.deletionReasonCode,deletion_public_reason: this.deletionPublicReason,deletion_audit_log_reason: this.deletionAuditLogReason,diff --git a/fluxer_api/src/api/oauth/ApplicationService.ts b/fluxer_api/src/api/oauth/ApplicationService.tsindex 95dd5ad07..3a6c9a2f4 100644--- a/fluxer_api/src/api/oauth/ApplicationService.ts+++ b/fluxer_api/src/api/oauth/ApplicationService.ts@@ -15,6 +15,7 @@ import {InternalServerError} from '@fluxer/errors/src/domains/core/InternalServeimport {BotUserNotFoundError} from '@fluxer/errors/src/domains/oauth/BotUserNotFoundError';import {UnclaimedAccountCannotCreateApplicationsError} from '@fluxer/errors/src/domains/oauth/UnclaimedAccountCannotCreateApplicationsError';import {UnknownApplicationError} from '@fluxer/errors/src/domains/oauth/UnknownApplicationError';+import type {BotProfileUpdateRequest} from '@fluxer/schema/src/domains/oauth/OAuthSchemas';import type {ApiContext} from '../ApiContext';import type {ApplicationID, UserID} from '../BrandedTypes';import {applicationIdToUserId} from '../BrandedTypes';@@ -31,6 +32,7 @@ import type {Application} from '../models/Application';import type {User} from '../models/User';import {enforceFluxerTagChangeRateLimit} from '../user/FluxerTagChangeRateLimit';import {hasPartialUserFieldsChanged, mapUserToPrivateResponse} from '../user/UserMappers';+import {runAllInOrder} from '../utils/ConcurrencyUtils';import {hashPassword} from '../utils/PasswordUtils';import {generateRandomUsername} from '../utils/UsernameGenerator';import {deriveUsernameFromDisplayName} from '../utils/UsernameSuggestionUtils';@@ -48,6 +50,11 @@ interface ApplicationServiceDeps {userCacheService: UserCacheService;}+const BOT_IMAGE_FIELDS = [+ {field: 'avatar', hash: 'avatar_hash', previousHash: 'avatarHash'},+ {field: 'banner', hash: 'banner_hash', previousHash: 'bannerHash'},+] as const;+export class ApplicationNotOwnedError extends ForbiddenError {constructor() {super({code: APIErrorCodes.APPLICATION_NOT_OWNED});@@ -435,23 +442,16 @@ export class ApplicationService {async updateBotProfile(userId: UserID,applicationId: ApplicationID,- args: {- username?: string;- discriminator?: number;- avatar?: string | null;- banner?: string | null;- bio?: string | null;- botFlags?: number;- },+ args: BotProfileUpdateRequest,): Promise<{user: User;application: Application;}> {const application = await this.verifyOwnership(userId, applicationId);- if (!application.hasBotUser()) {+ const botUserId = application.getBotUserId();+ if (botUserId === null) {throw new BotUserNotFoundError();}- const botUserId = application.getBotUserId()!;const botUser = await this.apiContext.services.users.findUnique(botUserId);if (!botUser) {throw new BotUserNotFoundError();@@ -493,77 +493,62 @@ export class ApplicationService {}}updates.global_name = null;- const assetPrep = await this.prepareBotAssets({- botUser,- botUserId,- avatar: args.avatar,- banner: args.banner,- });- if (assetPrep.avatarHash !== undefined) {- updates.avatar_hash = assetPrep.avatarHash;- }- if (assetPrep.bannerHash !== undefined) {- updates.banner_hash = assetPrep.bannerHash;- }if (args.bio !== undefined) {if (args.bio && profileSubstringBlocklistCache.containsBannedSubstring('bio', args.bio)) {throw new ContentBlockedError();}updates.bio = args.bio;}- if (args.botFlags !== undefined) {- const friendlyFlag = UserFlags.FRIENDLY_BOT;- const manualApprovalFlag = UserFlags.FRIENDLY_BOT_MANUAL_APPROVAL;- const desiredFriendly = (BigInt(args.botFlags) & friendlyFlag) === friendlyFlag;- const desiredManualApproval = (BigInt(args.botFlags) & manualApprovalFlag) === manualApprovalFlag;- const currentlyFriendly = (botUser.flags & friendlyFlag) === friendlyFlag;- const currentlyManualApproval = (botUser.flags & manualApprovalFlag) === manualApprovalFlag;- let updatedFlags = botUser.flags;- if (desiredFriendly && !currentlyFriendly) {- updatedFlags |= friendlyFlag;- } else if (!desiredFriendly && currentlyFriendly) {- updatedFlags &= ~friendlyFlag;- }- if (desiredManualApproval && !currentlyManualApproval) {- updatedFlags |= manualApprovalFlag;- } else if (!desiredManualApproval && currentlyManualApproval) {- updatedFlags &= ~manualApprovalFlag;- }+ if (args.bot_flags !== undefined) {+ const mask = UserFlags.FRIENDLY_BOT | UserFlags.FRIENDLY_BOT_MANUAL_APPROVAL;+ const updatedFlags = (botUser.flags & ~mask) | (BigInt(args.bot_flags) & mask);if (updatedFlags !== botUser.flags) {updates.flags = updatedFlags;}}- let updatedUser: User | null;+ const preparedAssets = await this.prepareBotAssets(botUser, args, updates);+ let updatedUser: User;try {updatedUser = await this.apiContext.services.users.patchUpsert(botUserId, updates, botUser.toRow());} catch (err) {- await this.rollbackBotAssets(assetPrep);+ Logger.error(+ {error: err, applicationId: applicationId.toString(), botUserId: botUserId.toString()},+ 'Bot profile update failed with unknown commit status; retaining uploaded assets',+ );throw err;}- if (!updatedUser) {- await this.rollbackBotAssets(assetPrep);- throw new BotUserNotFoundError();- }try {- await this.apiContext.services.contactChangeLog.recordDiff({- oldUser: botUser,- newUser: updatedUser,- reason: 'user_requested',- actorUserId: userId,- });- await this.commitBotAssets(assetPrep);+ await runAllInOrder(+ [+ () =>+ this.apiContext.services.contactChangeLog.recordDiff({+ oldUser: botUser,+ newUser: updatedUser,+ reason: 'user_requested',+ actorUserId: userId,+ }),+ () => this.deps.entityAssetService.commitAssetChanges(preparedAssets),+ () =>+ this.apiContext.services.gateway.dispatchPresence({+ userId: updatedUser.id,+ event: 'USER_UPDATE',+ data: mapUserToPrivateResponse(updatedUser),+ }),+ async () => {+ if (hasPartialUserFieldsChanged(botUser, updatedUser)) {+ await this.deps.userCacheService.setUserPartialResponseFromUser(updatedUser);+ }+ },+ ],+ 'Failed to finalize bot profile',+ );} catch (err) {- await this.rollbackBotAssets(assetPrep);+ Logger.error(+ {error: err, applicationId: applicationId.toString(), botUserId: botUserId.toString()},+ 'Failed to finalize bot profile after successful DB update',+ );throw err;}- await this.apiContext.services.gateway.dispatchPresence({- userId: updatedUser.id,- event: 'USER_UPDATE',- data: mapUserToPrivateResponse(updatedUser),- });- if (hasPartialUserFieldsChanged(botUser, updatedUser)) {- await this.deps.userCacheService.setUserPartialResponseFromUser(updatedUser);- }Logger.info({applicationId: applicationId.toString(), botUserId: botUserId.toString()},'Successfully updated bot profile',@@ -574,74 +559,26 @@ export class ApplicationService {};}- private async prepareBotAssets(params: {- botUser: User;- botUserId: UserID;- avatar?: string | null;- banner?: string | null;- }): Promise<{- avatarUpload: PreparedAssetUpload | null;- bannerUpload: PreparedAssetUpload | null;- avatarHash: string | null | undefined;- bannerHash: string | null | undefined;- }> {- const {botUser, botUserId, avatar, banner} = params;- let avatarUpload: PreparedAssetUpload | null = null;- let bannerUpload: PreparedAssetUpload | null = null;- let avatarHash: string | null | undefined;- let bannerHash: string | null | undefined;- if (avatar !== undefined) {- avatarUpload = await this.deps.entityAssetService.prepareAssetUpload({- assetType: 'avatar',- entityType: 'user',- entityId: botUserId,- previousHash: botUser.avatarHash,- base64Image: avatar,- errorPath: 'avatar',- });- avatarHash = avatarUpload.newHash;- if (avatarUpload.newHash === botUser.avatarHash) {- avatarUpload = null;- }- }- if (banner !== undefined) {- bannerUpload = await this.deps.entityAssetService.prepareAssetUpload({- assetType: 'banner',+ private async prepareBotAssets(+ user: User,+ data: BotProfileUpdateRequest,+ updates: Partial<UserRow>,+ ): Promise<Array<PreparedAssetUpload>> {+ const preparedAssets: Array<PreparedAssetUpload> = [];+ for (const {field, hash, previousHash} of BOT_IMAGE_FIELDS) {+ const image = data[field];+ if (image === undefined) continue;+ const prepared = await this.deps.entityAssetService.prepareAssetUpload({+ assetType: field,entityType: 'user',- entityId: botUserId,- previousHash: botUser.bannerHash,- base64Image: banner,- errorPath: 'banner',+ entityId: user.id,+ previousHash: user[previousHash],+ base64Image: image,+ errorPath: field,});- bannerHash = bannerUpload.newHash;- if (bannerUpload.newHash === botUser.bannerHash) {- bannerUpload = null;- }- }- return {avatarUpload, bannerUpload, avatarHash, bannerHash};- }-- private async commitBotAssets(assetPrep: {- avatarUpload: PreparedAssetUpload | null;- bannerUpload: PreparedAssetUpload | null;- }) {- if (assetPrep.avatarUpload) {- await this.deps.entityAssetService.commitAssetChange({prepared: assetPrep.avatarUpload, deferDeletion: true});- }- if (assetPrep.bannerUpload) {- await this.deps.entityAssetService.commitAssetChange({prepared: assetPrep.bannerUpload, deferDeletion: true});- }- }-- private async rollbackBotAssets(assetPrep: {- avatarUpload: PreparedAssetUpload | null;- bannerUpload: PreparedAssetUpload | null;- }) {- if (assetPrep.avatarUpload) {- await this.deps.entityAssetService.rollbackAssetUpload(assetPrep.avatarUpload);- }- if (assetPrep.bannerUpload) {- await this.deps.entityAssetService.rollbackAssetUpload(assetPrep.bannerUpload);+ updates[hash] = prepared.newHash;+ preparedAssets.push(prepared);}+ return preparedAssets;}}diff --git a/fluxer_api/src/api/oauth/OAuth2ApplicationsRequestService.ts b/fluxer_api/src/api/oauth/OAuth2ApplicationsRequestService.tsindex b6db91d25..56cb2bc0d 100644--- a/fluxer_api/src/api/oauth/OAuth2ApplicationsRequestService.ts+++ b/fluxer_api/src/api/oauth/OAuth2ApplicationsRequestService.ts@@ -157,14 +157,7 @@ export class OAuth2ApplicationsRequestService {body: BotProfileUpdateRequest,): Promise<BotProfileResponse> {try {- const result = await this.applicationService.updateBotProfile(userId, createApplicationID(applicationId), {- username: body.username,- discriminator: body.discriminator,- avatar: body.avatar,- banner: body.banner,- bio: body.bio,- botFlags: body.bot_flags,- });+ const result = await this.applicationService.updateBotProfile(userId, createApplicationID(applicationId), body);return mapBotProfileToResponse(result.user);} catch (err) {if (err instanceof ApplicationNotOwnedError) {diff --git a/fluxer_api/src/api/openapi/openapi.json b/fluxer_api/src/api/openapi/openapi.jsonindex 0e6440b87..c755e1d24 100644--- a/fluxer_api/src/api/openapi/openapi.json+++ b/fluxer_api/src/api/openapi/openapi.json@@ -14009,75 +14009,6 @@]}},- "/users/@me/connections/{type}/{connection_id}/verify": {- "post": {- "operationId": "verify_connection",- "summary": "Verify connection",- "tags": ["Connections"],- "responses": {- "200": {- "description": "Success",- "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ConnectionResponse"}}}- },- "400": {- "description": "Bad Request - The request was malformed or contained invalid data",- "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}- },- "401": {- "description": "Unauthorized - Authentication is required or the token is invalid",- "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}- },- "403": {- "description": "Forbidden - You do not have permission to perform this action",- "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}- },- "429": {- "description": "Too Many Requests - You are being rate limited",- "content": {"application/json": {"schema": {"$ref": "#/components/schemas/ThrottledError"}}},- "headers": {- "Retry-After": {- "description": "Number of seconds to wait before retrying (only on 429)",- "schema": {"type": "integer"}- },- "X-RateLimit-Limit": {- "description": "The number of requests that can be made in the current window",- "schema": {"type": "integer"}- },- "X-RateLimit-Remaining": {- "description": "The number of remaining requests that can be made",- "schema": {"type": "integer"}- },- "X-RateLimit-Reset": {- "description": "Unix timestamp when the rate limit resets",- "schema": {"type": "integer"}- }- }- },- "500": {- "description": "Internal Server Error - An unexpected error occurred",- "content": {"application/json": {"schema": {"$ref": "#/components/schemas/Error"}}}- }- },- "description": "Triggers verification for an external service connection.",- "security": [{"sessionToken": []}],- "parameters": [- {- "name": "type",- "in": "path",- "required": true,- "schema": {"$ref": "#/components/schemas/ConnectionType"},- "description": "The type of external connection"- },- {- "name": "connection_id",- "in": "path",- "required": true,- "schema": {"type": "string", "description": "The unique identifier of the connection"},- "description": "The unique identifier of the connection"- }- ]- }- },"/users/@me/delete": {"post": {"operationId": "delete_current_user_account",@@ -24259,25 +24190,6 @@"enum": ["bsky", "domain"],"type": "string"},- "ConnectionResponse": {- "type": "object",- "properties": {- "id": {"type": "string", "description": "The unique identifier for this connection"},- "type": {"description": "The type of connection", "$ref": "#/components/schemas/ConnectionType"},- "name": {"type": "string", "description": "The display name of the connection (handle or domain)"},- "verified": {"type": "boolean", "description": "Whether the connection has been verified"},- "visibility_flags": {- "description": "Bitfield controlling who can see this connection",- "$ref": "#/components/schemas/ConnectionVisibilityFlags"- },- "sort_order": {- "description": "The display order of this connection",- "$ref": "#/components/schemas/Int32Type"- }- },- "required": ["id", "type", "name", "verified", "visibility_flags", "sort_order"],- "additionalProperties": false- },"UpdateConnectionRequest": {"type": "object","properties": {@@ -24305,6 +24217,25 @@},"required": ["initiation_token"]},+ "ConnectionResponse": {+ "type": "object",+ "properties": {+ "id": {"type": "string", "description": "The unique identifier for this connection"},+ "type": {"description": "The type of connection", "$ref": "#/components/schemas/ConnectionType"},+ "name": {"type": "string", "description": "The display name of the connection (handle or domain)"},+ "verified": {"type": "boolean", "description": "Whether the connection has been verified"},+ "visibility_flags": {+ "description": "Bitfield controlling who can see this connection",+ "$ref": "#/components/schemas/ConnectionVisibilityFlags"+ },+ "sort_order": {+ "description": "The display order of this connection",+ "$ref": "#/components/schemas/Int32Type"+ }+ },+ "required": ["id", "type", "name", "verified", "visibility_flags", "sort_order"],+ "additionalProperties": false+ },"ReorderConnectionsRequest": {"type": "object","properties": {diff --git a/fluxer_api/src/api/rate_limit_configs/ConnectionRateLimitConfig.ts b/fluxer_api/src/api/rate_limit_configs/ConnectionRateLimitConfig.tsindex e708ba586..172d7aecb 100644--- a/fluxer_api/src/api/rate_limit_configs/ConnectionRateLimitConfig.ts+++ b/fluxer_api/src/api/rate_limit_configs/ConnectionRateLimitConfig.ts@@ -20,10 +20,6 @@ export const ConnectionRateLimitConfigs = {bucket: 'connection:delete',config: {limit: 10, windowMs: ms('1 minute')},} as RouteRateLimitConfig,- CONNECTION_VERIFY: {- bucket: 'connection:verify',- config: {limit: 5, windowMs: ms('1 minute')},- } as RouteRateLimitConfig,CONNECTION_VERIFY_AND_CREATE: {bucket: 'connection:verify_and_create',config: {limit: 5, windowMs: ms('1 minute')},diff --git a/fluxer_api/src/api/risk/adapters/DomainAgeChecker.ts b/fluxer_api/src/api/risk/adapters/DomainAgeChecker.tsindex 7c544126e..97d4908d5 100644--- a/fluxer_api/src/api/risk/adapters/DomainAgeChecker.ts+++ b/fluxer_api/src/api/risk/adapters/DomainAgeChecker.ts@@ -85,15 +85,15 @@ export function createDomainAgeChecker(opts: DomainAgeCheckerOptions = {}) {}async function fetchFromRdap(domain: string): Promise<CachedDomainAge> {+ const controller = new AbortController();+ const timeout = setTimeout(() => controller.abort(), RDAP_TIMEOUT_MS);try {- const controller = new AbortController();- const timeout = setTimeout(() => controller.abort(), RDAP_TIMEOUT_MS);const response = await fetch(`https://rdap.org/domain/${encodeURIComponent(domain)}`, {signal: controller.signal,headers: {Accept: 'application/rdap+json'},});- clearTimeout(timeout);if (!response.ok) {+ FetchUtils.discardResponseBody(response.body, response.status);return {domain,available: false,@@ -130,6 +130,8 @@ async function fetchFromRdap(domain: string): Promise<CachedDomainAge> {creationDate: null,failureNote: `RDAP lookup error: ${message.slice(0, 100)}`,};+ } finally {+ clearTimeout(timeout);}}diff --git a/fluxer_api/src/api/search/SearchWarmup.ts b/fluxer_api/src/api/search/SearchWarmup.tsindex a444078b2..24e305193 100644--- a/fluxer_api/src/api/search/SearchWarmup.ts+++ b/fluxer_api/src/api/search/SearchWarmup.ts@@ -44,7 +44,7 @@ export async function warmupAdminSearchIndexes(deps: SearchWarmupDeps): Promise<logger.info({total: testResult.total}, 'Guild index already populated, skipping warmup');}}- if (userSearchService && 'indexUser' in userSearchService) {+ if (userSearchService) {const testResult = await userSearchService.searchUsers('', {}, {limit: 1});if (testResult.total === 0) {logger.info('User index is empty, populating from database');@@ -93,19 +93,15 @@ async function warmupUsers(): Promise<void> {let pageState: string | null = null;let totalIndexed = 0;- while (true) {+ do {const page = await userRepository.scanAllUsersPage(BATCH_SIZE, pageState);- const users = page.users;- if (users.length > 0) {- await userSearchService.indexUsers(users);- totalIndexed += users.length;- logger.debug({count: users.length, total: totalIndexed}, 'Indexed user batch');- }pageState = page.pageState;- if (!pageState) {- break;- }- }+ const users = page.users;+ if (users.length === 0) continue;+ await userSearchService.indexUsers(users);+ totalIndexed += users.length;+ logger.debug({count: users.length, total: totalIndexed}, 'Indexed user batch');+ } while (pageState);logger.info({total: totalIndexed}, 'User warmup complete');}@@ -120,9 +116,7 @@ async function warmupReports(while (hasMore) {const reports = await reportRepository.listAllReportsPaginated(BATCH_SIZE, lastReportId);if (reports.length > 0) {- if ('indexReports' in reportSearchService) {- await reportSearchService.indexReports(reports);- }+ await reportSearchService.indexReports(reports);totalIndexed += reports.length;lastReportId = reports[reports.length - 1]!.reportId;logger.debug({count: reports.length, total: totalIndexed}, 'Indexed report batch');diff --git a/fluxer_api/src/api/search/meilisearch/MeilisearchDomainAdapters.ts b/fluxer_api/src/api/search/meilisearch/MeilisearchDomainAdapters.tsindex 9d53a9a57..6f607896e 100644--- a/fluxer_api/src/api/search/meilisearch/MeilisearchDomainAdapters.ts+++ b/fluxer_api/src/api/search/meilisearch/MeilisearchDomainAdapters.ts@@ -50,6 +50,15 @@ function snowflakeSeconds(snowflake: string): number {return Math.floor(snowflakeToDate(BigInt(snowflake)).getTime() / 1000);}+function buildSort(sortBy: string, sortOrder: 'asc' | 'desc' | undefined): Array<string> | undefined {+ if (sortBy === 'relevance') return undefined;+ return [`${sortBy}:${sortOrder ?? 'desc'}`, 'id:desc'];+}++function buildTimestampSort(filters: MessageSearchFilters | AuditLogSearchFilters): Array<string> | undefined {+ return buildSort(filters.sortBy === 'relevance' ? 'relevance' : 'createdAt', filters.sortOrder);+}+function buildMessageFilters(filters: MessageSearchFilters): Array<MeilisearchFilter | undefined> {const clauses: Array<MeilisearchFilter | undefined> = [];if (filters.guildId) clauses.push(meiliTermFilter('guildId', filters.guildId));@@ -119,13 +128,6 @@ function buildMessageFilters(filters: MessageSearchFilters): Array<MeilisearchFireturn compactMeiliFilters(clauses);}-function buildMessageSort(filters: MessageSearchFilters): Array<string> | undefined {- const sortBy = filters.sortBy ?? 'timestamp';- if (sortBy === 'relevance') return undefined;- const sortOrder = filters.sortOrder ?? 'desc';- return [`createdAt:${sortOrder}`, 'id:desc'];-}-function buildMessageQuery(query: string, filters: MessageSearchFilters): string {const terms = [...(filters.contents ?? []), query].filter((term) => term.trim().length > 0);const phrases = (filters.exactPhrases ?? []).map((phrase) => `"${phrase.replaceAll('"', '\\"')}"`);@@ -152,13 +154,6 @@ function buildGuildFilters(filters: GuildSearchFilters): Array<MeilisearchFilterreturn compactMeiliFilters(clauses);}-function buildGuildSort(filters: GuildSearchFilters): Array<string> | undefined {- const sortBy = filters.sortBy ?? 'createdAt';- if (sortBy === 'relevance') return undefined;- const sortOrder = filters.sortOrder ?? 'desc';- return [`${sortBy}:${sortOrder}`, 'id:desc'];-}-function buildUserFilters(filters: UserSearchFilters): Array<MeilisearchFilter | undefined> {const clauses: Array<MeilisearchFilter | undefined> = [];if (filters.isBot !== undefined) clauses.push(meiliTermFilter('isBot', filters.isBot));@@ -187,13 +182,6 @@ function buildUserFilters(filters: UserSearchFilters): Array<MeilisearchFilter |return compactMeiliFilters(clauses);}-function buildUserSort(filters: UserSearchFilters): Array<string> | undefined {- const sortBy = filters.sortBy ?? 'createdAt';- if (sortBy === 'relevance') return undefined;- const sortOrder = filters.sortOrder ?? 'desc';- return [`${sortBy}:${sortOrder}`, 'id:desc'];-}-function buildReportFilters(filters: ReportSearchFilters): Array<MeilisearchFilter | undefined> {const clauses: Array<MeilisearchFilter | undefined> = [];if (filters.reporterId) clauses.push(meiliTermFilter('reporterId', filters.reporterId));@@ -210,13 +198,6 @@ function buildReportFilters(filters: ReportSearchFilters): Array<MeilisearchFiltreturn compactMeiliFilters(clauses);}-function buildReportSort(filters: ReportSearchFilters): Array<string> | undefined {- const sortBy = filters.sortBy ?? 'reportedAt';- if (sortBy === 'relevance') return undefined;- const sortOrder = filters.sortOrder ?? 'desc';- return [`${sortBy}:${sortOrder}`, 'id:desc'];-}-function buildAuditLogFilters(filters: AuditLogSearchFilters): Array<MeilisearchFilter | undefined> {const clauses: Array<MeilisearchFilter | undefined> = [];if (filters.adminUserId) clauses.push(meiliTermFilter('adminUserId', filters.adminUserId));@@ -226,13 +207,6 @@ function buildAuditLogFilters(filters: AuditLogSearchFilters): Array<Meilisearchreturn compactMeiliFilters(clauses);}-function buildAuditLogSort(filters: AuditLogSearchFilters): Array<string> | undefined {- const sortBy = filters.sortBy ?? 'createdAt';- if (sortBy === 'relevance') return undefined;- const sortOrder = filters.sortOrder ?? 'desc';- return [`createdAt:${sortOrder}`, 'id:desc'];-}-function buildGuildMemberFilters(filters: GuildMemberSearchFilters): Array<MeilisearchFilter | undefined> {const clauses: Array<MeilisearchFilter | undefined> = [];clauses.push(meiliTermFilter('guildId', filters.guildId));@@ -253,20 +227,13 @@ function buildGuildMemberFilters(filters: GuildMemberSearchFilters): Array<Meilireturn compactMeiliFilters(clauses);}-function buildGuildMemberSort(filters: GuildMemberSearchFilters): Array<string> | undefined {- const sortBy = filters.sortBy ?? 'joinedAt';- if (sortBy === 'relevance') return undefined;- const sortOrder = filters.sortOrder ?? 'desc';- return [`${sortBy}:${sortOrder}`, 'id:desc'];-}-export class MeilisearchMessageAdapter extends MeilisearchIndexAdapter<MessageSearchFilters, SearchableMessage> {constructor(options: MeilisearchAdapterOptions) {super({client: options.client,index: MEILISEARCH_INDEX_DEFINITIONS.messages,buildFilters: buildMessageFilters,- buildSort: buildMessageSort,+ buildSort: buildTimestampSort,buildQuery: buildMessageQuery,});}@@ -278,7 +245,7 @@ export class MeilisearchGuildAdapter extends MeilisearchIndexAdapter<GuildSearchclient: options.client,index: MEILISEARCH_INDEX_DEFINITIONS.guilds,buildFilters: buildGuildFilters,- buildSort: buildGuildSort,+ buildSort: (filters) => buildSort(filters.sortBy ?? 'createdAt', filters.sortOrder),});}}@@ -289,7 +256,7 @@ export class MeilisearchUserAdapter extends MeilisearchIndexAdapter<UserSearchFiclient: options.client,index: MEILISEARCH_INDEX_DEFINITIONS.users,buildFilters: buildUserFilters,- buildSort: buildUserSort,+ buildSort: (filters) => buildSort(filters.sortBy ?? 'createdAt', filters.sortOrder),});}}@@ -300,7 +267,7 @@ export class MeilisearchReportAdapter extends MeilisearchIndexAdapter<ReportSearclient: options.client,index: MEILISEARCH_INDEX_DEFINITIONS.reports,buildFilters: buildReportFilters,- buildSort: buildReportSort,+ buildSort: (filters) => buildSort(filters.sortBy ?? 'reportedAt', filters.sortOrder),});}}@@ -311,7 +278,7 @@ export class MeilisearchAuditLogAdapter extends MeilisearchIndexAdapter<AuditLogclient: options.client,index: MEILISEARCH_INDEX_DEFINITIONS.audit_logs,buildFilters: buildAuditLogFilters,- buildSort: buildAuditLogSort,+ buildSort: buildTimestampSort,});}}@@ -325,7 +292,7 @@ export class MeilisearchGuildMemberAdapter extends MeilisearchIndexAdapter<client: options.client,index: MEILISEARCH_INDEX_DEFINITIONS.guild_members,buildFilters: buildGuildMemberFilters,- buildSort: buildGuildMemberSort,+ buildSort: (filters) => buildSort(filters.sortBy ?? 'joinedAt', filters.sortOrder),});}}diff --git a/fluxer_api/src/api/stripe/services/StripeDisputeWebhookHandler.ts b/fluxer_api/src/api/stripe/services/StripeDisputeWebhookHandler.tsindex 4529d92df..c47719aa1 100644--- a/fluxer_api/src/api/stripe/services/StripeDisputeWebhookHandler.ts+++ b/fluxer_api/src/api/stripe/services/StripeDisputeWebhookHandler.ts@@ -80,24 +80,20 @@ export class StripeDisputeWebhookHandler {throw new StripeError('User not found for chargeback withdrawal');}if (user.flags & UserFlags.DELETED && user.deletionReasonCode === DeletionReasons.BILLING_DISPUTE_OR_ABUSE) {+ const updatedUser = await this.userRepository.updateDeletionSchedule(user, {+ flags: user.flags & ~UserFlags.DELETED,+ pending_deletion_at: null,+ deletion_reason_code: null,+ deletion_public_reason: null,+ deletion_audit_log_reason: null,+ first_refund_at: user.firstRefundAt || new Date(),+ });await clearPendingDeletion({userId: payment.userId,pendingDeletionAt: user.pendingDeletionAt,userRepository: this.userRepository,deletionQueue: this.kvDeletionQueue,});- const updatedUser = await this.userRepository.patchUpsert(- payment.userId,- {- flags: user.flags & ~UserFlags.DELETED,- pending_deletion_at: null,- deletion_reason_code: null,- deletion_public_reason: null,- deletion_audit_log_reason: null,- first_refund_at: user.firstRefundAt || new Date(),- },- user.toRow(),- );await this.userCacheService.setUserPartialResponseFromUser(updatedUser);if (updatedUser.email) {await this.emailService.sendUnbanNotification(diff --git a/fluxer_api/src/api/stripe/services/StripePaymentFraudService.ts b/fluxer_api/src/api/stripe/services/StripePaymentFraudService.tsindex 114f6ed59..691fb926d 100644--- a/fluxer_api/src/api/stripe/services/StripePaymentFraudService.ts+++ b/fluxer_api/src/api/stripe/services/StripePaymentFraudService.ts@@ -191,22 +191,20 @@ export class StripePaymentFraudService {throw new StripeError('User not found for payment fraud action');}const pendingDeletionAt = new Date(Date.now() + FRAUD_DELETION_DELAY_MS);- const subscriptionCancelled = await this.cancelStripeSubscriptionImmediately(user);+ const cancelledUser = await this.cancelStripeSubscriptionImmediately(user);+ const subscriptionCancelled = cancelledUser !== null;+ const currentUser = cancelledUser ?? user;const auditReason = this.getAuditReason({source, fraudType});- const updatedUser = await this.deps.userRepository.patchUpsert(- userId,- {- flags: (user.flags | UserFlags.DELETED) & ~UserFlags.SELF_DELETED,- pending_deletion_at: pendingDeletionAt,- deletion_reason_code: DeletionReasons.BILLING_DISPUTE_OR_ABUSE,- deletion_public_reason: 'Payment fraud',- deletion_audit_log_reason: auditReason,- },- user.toRow(),- );+ const updatedUser = await this.deps.userRepository.updateDeletionSchedule(currentUser, {+ flags: (currentUser.flags | UserFlags.DELETED) & ~UserFlags.SELF_DELETED,+ pending_deletion_at: pendingDeletionAt,+ deletion_reason_code: DeletionReasons.BILLING_DISPUTE_OR_ABUSE,+ deletion_public_reason: 'Payment fraud',+ deletion_audit_log_reason: auditReason,+ });await reschedulePendingDeletion({userId,- currentPendingDeletionAt: user.pendingDeletionAt,+ currentPendingDeletionAt: currentUser.pendingDeletionAt,nextPendingDeletionAt: pendingDeletionAt,deletionReasonCode: DeletionReasons.BILLING_DISPUTE_OR_ABUSE,userRepository: this.deps.userRepository,@@ -536,9 +534,9 @@ export class StripePaymentFraudService {);}- private async cancelStripeSubscriptionImmediately(user: User): Promise<boolean> {+ private async cancelStripeSubscriptionImmediately(user: User): Promise<User | null> {if (!user.stripeSubscriptionId) {- return false;+ return null;}try {await this.getStripe().subscriptions.cancel(@@ -569,7 +567,7 @@ export class StripePaymentFraudService {user.toRow(),);await this.dispatchUser(updatedUser);- return true;+ return updatedUser;}private isMissingOrCancelledSubscriptionError(error: unknown): boolean {diff --git a/fluxer_api/src/api/stripe/tests/StripeWebhookDispute.test.ts b/fluxer_api/src/api/stripe/tests/StripeWebhookDispute.test.tsindex f2f06950a..77289f4fc 100644--- a/fluxer_api/src/api/stripe/tests/StripeWebhookDispute.test.ts+++ b/fluxer_api/src/api/stripe/tests/StripeWebhookDispute.test.ts@@ -468,21 +468,14 @@ describe('Stripe Webhook Dispute Events', () => {checkout_session_id: 'cs_test_dispute_won',payment_intent_id: paymentIntentId,});- await createBuilderWithoutAuth(harness)- .patch(`/test/users/${purchaser.userId}/flags`)- .body({flags: Number(UserFlags.DELETED)})- .execute();const userRepository = new UserRepository();const userId = createUserID(BigInt(purchaser.userId));- const user = await userRepository.findUnique(userId);- await userRepository.patchUpsert(- userId,- {- deletion_reason_code: DeletionReasons.BILLING_DISPUTE_OR_ABUSE,- pending_deletion_at: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000),- },- user!.toRow(),- );+ const user = await userRepository.findUniqueAssert(userId);+ await userRepository.updateDeletionSchedule(user, {+ flags: (user.flags | UserFlags.DELETED) & ~UserFlags.SELF_DELETED,+ deletion_reason_code: DeletionReasons.BILLING_DISPUTE_OR_ABUSE,+ pending_deletion_at: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000),+ });const userBeforeWin = await createBuilderWithoutAuth<UserDataExistsResponse>(harness).get(`/test/users/${purchaser.userId}/data-exists`).execute();@@ -523,21 +516,14 @@ describe('Stripe Webhook Dispute Events', () => {checkout_session_id: 'cs_test_dispute_lost',payment_intent_id: paymentIntentId,});- await createBuilderWithoutAuth(harness)- .patch(`/test/users/${purchaser.userId}/flags`)- .body({flags: Number(UserFlags.DELETED)})- .execute();const userRepository = new UserRepository();const userId = createUserID(BigInt(purchaser.userId));- const user = await userRepository.findUnique(userId);- await userRepository.patchUpsert(- userId,- {- deletion_reason_code: DeletionReasons.BILLING_DISPUTE_OR_ABUSE,- pending_deletion_at: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000),- },- user!.toRow(),- );+ const user = await userRepository.findUniqueAssert(userId);+ await userRepository.updateDeletionSchedule(user, {+ flags: (user.flags | UserFlags.DELETED) & ~UserFlags.SELF_DELETED,+ deletion_reason_code: DeletionReasons.BILLING_DISPUTE_OR_ABUSE,+ pending_deletion_at: new Date(Date.now() + 30 * 24 * 60 * 60 * 1000),+ });const eventData: StripeWebhookEventData = {type: 'charge.dispute.closed',data: {diff --git a/fluxer_api/src/api/test/ApiTestHarness.ts b/fluxer_api/src/api/test/ApiTestHarness.tsindex ce8e145ae..6c261a1b4 100644--- a/fluxer_api/src/api/test/ApiTestHarness.ts+++ b/fluxer_api/src/api/test/ApiTestHarness.ts@@ -92,7 +92,7 @@ export async function createApiTestHarness(options: CreateApiTestHarnessOptionsconst mockBlueskyOAuthService = new MockBlueskyOAuthService();setInjectedBlueskyOAuthService(mockBlueskyOAuthService);setInjectedAccountPolicyEvaluator(createCurrentBehaviorTestAccountPolicyEvaluator());- resetServiceStateForTesting();+ await resetServiceStateForTesting();const {app,initialize: initializeApp,@@ -154,7 +154,7 @@ export async function createApiTestHarness(options: CreateApiTestHarnessOptionssetInjectedMediaService(new TestMediaService(fallbackStorageService));setInjectedSearchProviderService(new NullSearchProvider());setInjectedBlueskyOAuthService(new MockBlueskyOAuthService());- resetServiceStateForTesting();+ await resetServiceStateForTesting();resetApiServicesForTesting();}async function requestJson(params: {diff --git a/fluxer_api/src/api/test/InMemoryCassandraQueryExecutor.ts b/fluxer_api/src/api/test/InMemoryCassandraQueryExecutor.tsindex dd0bebdf5..61be7906e 100644--- a/fluxer_api/src/api/test/InMemoryCassandraQueryExecutor.ts+++ b/fluxer_api/src/api/test/InMemoryCassandraQueryExecutor.ts@@ -2,7 +2,14 @@import {getKvMeta} from '../database/CassandraMetaRegistry';import type {CassandraQueryExecutorForTesting} from '../database/CassandraQueryExecution';-import type {CassandraParams, KvQueryMeta, PreparedQuery, WhereExpr} from '../database/CassandraTypes';+import type {+ CassandraParams,+ KvQueryCondition,+ KvQueryMeta,+ PreparedQuery,+ WhereExpr,+} from '../database/CassandraTypes';+import {isConditionalQuery} from '../database/CassandraTypes';type Row = Record<string, unknown>;@@ -30,6 +37,17 @@ function valuesEqual(a: unknown, b: unknown): boolean {return a === b;}+function matchesConditions(+ row: Row | undefined,+ conditions: ReadonlyArray<KvQueryCondition<Row>> | undefined,+ params: CassandraParams,+): row is Row {+ if (!conditions?.length) {+ throw new Error('Conditional mutations require at least one condition');+ }+ return row !== undefined && conditions.every(({col, expectedParam}) => valuesEqual(row[col], params[expectedParam]));+}+function cloneValue<T>(value: T): T {if (value instanceof Date) return new Date(value.getTime()) as T;if (value instanceof Set) return new Set([...value].map((entry) => cloneValue(entry))) as T;@@ -192,12 +210,20 @@ export class InMemoryCassandraQueryExecutor implements CassandraQueryExecutorForthis.upsert(meta, query.params);return [];case 'patch':- this.patch(meta, query.params);- return [];case 'delete':- this.delete(meta, query.params);+ if (meta.conditions) {+ return [{'[applied]': this.mutateConditionally(meta, query.params)}] as Array<T>;+ }+ if (meta.action === 'patch') {+ this.patch(meta, query.params);+ } else {+ this.delete(meta, query.params);+ }return [];case 'batch':+ if (meta.batchEntries) {+ return [{'[applied]': this.mutateBatchConditionally(meta, query.params)}] as Array<T>;+ }return [];}return [];@@ -207,6 +233,11 @@ export class InMemoryCassandraQueryExecutor implements CassandraQueryExecutorForqueries: Array<{query: string; params: object; meta?: KvQueryMeta}>,_atomic?: boolean,): Promise<void> {+ for (const query of queries) {+ if (isConditionalQuery({cql: query.query, params: query.params as CassandraParams, kvMeta: query.meta})) {+ throw new Error('Conditional writes must use executeConditional to preserve their result');+ }+ }for (const query of queries) {await this.executeQuery({cql: query.query,@@ -248,6 +279,55 @@ export class InMemoryCassandraQueryExecutor implements CassandraQueryExecutorForreturn true;}+ private mutateConditionally(meta: KvQueryMeta, params: CassandraParams): boolean {+ const table = this.table(meta);+ const key = this.keyFromParams(meta, params);+ const row = table.get(key);+ if (!matchesConditions(row, meta.conditions, params)) {+ return false;+ }+ if (meta.action === 'patch') {+ this.patch(meta, params);+ } else {+ table.delete(key);+ }+ return true;+ }++ private mutateBatchConditionally(meta: KvQueryMeta, params: CassandraParams): boolean {+ const entries = meta.batchEntries;+ if (!entries?.length) {+ throw new Error('Conditional batches require at least one entry');+ }+ const table = this.table(meta);+ const updates = new Map<string, Row | null>();+ for (const entry of entries) {+ const pk = Object.fromEntries(entry.pk.map(({col, param}) => [col, params[param]]));+ const key = pkKey(meta, pk);+ if (updates.has(key)) throw new Error('Conditional batches cannot repeat a row');+ const row = table.get(key);+ if (entry.action === 'insert') {+ if (row) return false;+ } else {+ if (!matchesConditions(row, entry.conditions, params)) return false;+ if (entry.action === 'delete') {+ updates.set(key, null);+ continue;+ }+ }+ const updated = {...row};+ for (const {col, param} of entry.action === 'insert' ? entry.values : entry.patch) {+ updated[col] = cloneValue(params[param]);+ }+ updates.set(key, updated);+ }+ for (const [key, row] of updates) {+ if (row === null) table.delete(key);+ else table.set(key, row);+ }+ return true;+ }+private patch(meta: KvQueryMeta, params: CassandraParams): void {const table = this.table(meta);const key = this.keyFromParams(meta, params);diff --git a/fluxer_api/src/api/test/ResetServiceState.ts b/fluxer_api/src/api/test/ResetServiceState.tsindex ef72875bd..91b302203 100644--- a/fluxer_api/src/api/test/ResetServiceState.ts+++ b/fluxer_api/src/api/test/ResetServiceState.ts@@ -18,7 +18,7 @@ import {resetAdminSecretHashForTesting} from '../oauth/repositories/ApplicationRimport {resetIpBanExemptionsForTesting} from '../risk/IpBanExemptions';import {setThemeCssMaxBytesForTesting} from '../theme/ThemeService';-export function resetServiceStateForTesting(): void {+export async function resetServiceStateForTesting(): Promise<void> {resetServiceRegistryForTesting();resetServiceSingletonsForTesting();resetServiceMiddlewareForTesting();@@ -28,9 +28,9 @@ export function resetServiceStateForTesting(): void {resetSsoRequestUrlPolicyForTesting();resetAdminSecretHashForTesting();setThemeCssMaxBytesForTesting(undefined);- ipBanCache.shutdown();+ await ipBanCache.shutdown();ipBanCache.resetCaches();- torExitListCache.shutdown();+ await torExitListCache.shutdown();torExitListCache.clearForTesting();urlBlocklistCache.resetForTesting();resetGeoipReadersForTesting();diff --git a/fluxer_api/src/api/test/TestHarnessController.ts b/fluxer_api/src/api/test/TestHarnessController.tsindex 3c97b8dbf..eb08ac2ac 100644--- a/fluxer_api/src/api/test/TestHarnessController.ts+++ b/fluxer_api/src/api/test/TestHarnessController.ts@@ -22,7 +22,6 @@ import {UnknownSuspiciousFlagError} from '@fluxer/errors/src/domains/core/Unknowimport {UpdateFailedError} from '@fluxer/errors/src/domains/core/UpdateFailedError';import {UnknownGuildError} from '@fluxer/errors/src/domains/guild/UnknownGuildError';import {UnknownGuildMemberError} from '@fluxer/errors/src/domains/guild/UnknownGuildMemberError';-import {UnknownHarvestError} from '@fluxer/errors/src/domains/moderation/UnknownHarvestError';import {InvalidBotFlagError} from '@fluxer/errors/src/domains/oauth/InvalidBotFlagError';import {UnknownUserError} from '@fluxer/errors/src/domains/user/UnknownUserError';import {UnknownUserFlagError} from '@fluxer/errors/src/domains/user/UnknownUserFlagError';@@ -81,6 +80,7 @@ import {IpAuthorizationTokens, OAuth2AccessTokensByUser} from '../Tables';import type {HonoApp, HonoEnv} from '../types/HonoEnv';import {UserSearchRepository} from '../user/repositories/account/crud/UserSearchRepository';import {AuthSessionRepository} from '../user/repositories/auth/AuthSessionRepository';+import type {UserDeletionScheduleUpdate} from '../user/repositories/IUserAccountRepository';import {UserChannelRepository} from '../user/repositories/UserChannelRepository';import {UserRepository} from '../user/repositories/UserRepository';import {processUserDeletion} from '../user/services/UserDeletionService';@@ -591,13 +591,13 @@ export function TestHarnessController(app: HonoApp) {} catch {throw new InvalidTimestampError();}- const updates: Record<string, unknown> = {pending_deletion_at: date};+ const updates: UserDeletionScheduleUpdate = {pending_deletion_at: date};const shouldSetSelfDeleted = setSelfDeletedFlag !== false;if (shouldSetSelfDeleted) {const nextFlags = (user.flags ?? 0n) | UserFlags.SELF_DELETED;updates['flags'] = nextFlags;}- const updated = await userRepository.patchUpsert(userId, updates, user.toRow());+ const updated = await userRepository.updateDeletionSchedule(user, updates);const kvClient = getKVClient();const kvDeletionQueue = new KVAccountDeletionQueueService(kvClient, userRepository);try {@@ -1630,8 +1630,7 @@ export function TestHarnessController(app: HonoApp) {continue;}const pendingDeletionAt = user.pendingDeletionAt;- await processUserDeletion(userId, deletion.deletionReasonCode, workerDeps);- await userRepository.removePendingDeletion(userId, pendingDeletionAt);+ await processUserDeletion(userId, pendingDeletionAt, deletion.deletionReasonCode, workerDeps);await kvDeletionQueue.removeFromQueue(userId);Logger.info({userId: userId.toString()}, '[test/worker/process-pending-deletions] Deletion completed');processed++;@@ -1694,7 +1693,7 @@ export function TestHarnessController(app: HonoApp) {try {const snowflakeService = getSnowflakeService();const workerDeps = await initializeWorkerDepsWithHarnessEmail(ctx, snowflakeService);- await processUserDeletion(userId, deletionReasonCode, workerDeps);+ await processUserDeletion(userId, user.pendingDeletionAt, deletionReasonCode, workerDeps);Logger.info({userId: userId.toString()},'[test/worker/process-pending-deletion/:userId] Deletion completed successfully',@@ -2135,12 +2134,7 @@ export function TestHarnessController(app: HonoApp) {throw new InvalidTimestampError();}const harvestRepository = new UserHarvestRepository();- const harvest = await harvestRepository.findByUserAndHarvestId(userId, harvestId);- if (!harvest) {- throw new UnknownHarvestError();- }- harvest.downloadUrlExpiresAt = date;- await harvestRepository.update(harvest);+ await harvestRepository.setDownloadUrlExpiry(userId, harvestId, date);return ctx.json({success: true}, 200);});app.get('/test/users/:userId/presence/has-active', async (ctx) => {diff --git a/fluxer_api/src/api/test/mocks/MockBlueskyOAuthService.ts b/fluxer_api/src/api/test/mocks/MockBlueskyOAuthService.tsindex 3ffc10093..3fe6008de 100644--- a/fluxer_api/src/api/test/mocks/MockBlueskyOAuthService.ts+++ b/fluxer_api/src/api/test/mocks/MockBlueskyOAuthService.ts@@ -11,9 +11,6 @@ import type {interface MockBlueskyOAuthServiceOptions {authorizeResult?: BlueskyAuthorizeResult;callbackResult?: BlueskyCallbackResult;- restoreAndVerifyResult?: {- handle: string;- } | null;shouldFailAuthorize?: boolean;shouldFailCallback?: boolean;}@@ -21,8 +18,6 @@ interface MockBlueskyOAuthServiceOptions {export class MockBlueskyOAuthService implements IBlueskyOAuthService {readonly authorizeSpy = vi.fn();readonly callbackSpy = vi.fn();- readonly restoreAndVerifySpy = vi.fn();- readonly revokeSpy = vi.fn();readonly clientMetadata: Record<string, unknown> = {client_id: 'https://test/metadata.json'};readonly jwks: Record<string, unknown> = {keys: []};private options: MockBlueskyOAuthServiceOptions;@@ -48,10 +43,6 @@ export class MockBlueskyOAuthService implements IBlueskyOAuthService {}return this.options.callbackResult;});- this.restoreAndVerifySpy.mockImplementation(async () => {- return this.options.restoreAndVerifyResult ?? null;- });- this.revokeSpy.mockResolvedValue(undefined);}async authorize(handle: string, userId: UserID): Promise<BlueskyAuthorizeResult> {@@ -62,16 +53,6 @@ export class MockBlueskyOAuthService implements IBlueskyOAuthService {return this.callbackSpy(params);}- async restoreAndVerify(did: string): Promise<{- handle: string;- } | null> {- return this.restoreAndVerifySpy(did);- }-- async revoke(did: string): Promise<void> {- return this.revokeSpy(did);- }-configure(options: Partial<MockBlueskyOAuthServiceOptions>): void {this.options = {...this.options, ...options};this.setupDefaults();@@ -80,8 +61,6 @@ export class MockBlueskyOAuthService implements IBlueskyOAuthService {reset(): void {this.authorizeSpy.mockReset();this.callbackSpy.mockReset();- this.restoreAndVerifySpy.mockReset();- this.revokeSpy.mockReset();this.options = {};this.setupDefaults();}diff --git a/fluxer_api/src/api/user/FluxerTagChangeRateLimit.ts b/fluxer_api/src/api/user/FluxerTagChangeRateLimit.tsindex 2b9830fc3..367edfcc8 100644--- a/fluxer_api/src/api/user/FluxerTagChangeRateLimit.ts+++ b/fluxer_api/src/api/user/FluxerTagChangeRateLimit.ts@@ -2,19 +2,14 @@import {ValidationErrorCodes} from '@fluxer/constants/src/ValidationErrorCodes';import {InputValidationError} from '@fluxer/errors/src/domains/core/InputValidationError';-import type {IRateLimitService, RateLimitResult} from '@pkgs/rate_limit/src/IRateLimitService';+import type {IRateLimitService} from '@pkgs/rate_limit/src/IRateLimitService';import {ms} from 'itty-time';import type {UserID} from '../BrandedTypes';+import {getRetryAfterSeconds} from '../utils/RateLimitUtils';const FLUXER_TAG_CHANGE_MAX_ATTEMPTS = 5;const FLUXER_TAG_CHANGE_WINDOW_MS = ms('3 hours');-function retryAfterMinutes(result: RateLimitResult): number {- const retryAfterSeconds =- result.retryAfter ?? Math.max(0, Math.ceil((result.resetTime.getTime() - Date.now()) / 1000));- return Math.max(1, Math.ceil(retryAfterSeconds / 60));-}-export async function enforceFluxerTagChangeRateLimit(params: {rateLimitService: IRateLimitService;userId: UserID;@@ -27,7 +22,7 @@ export async function enforceFluxerTagChangeRateLimit(params: {});if (!rateLimit.allowed) {throw InputValidationError.fromCode(params.errorPath, ValidationErrorCodes.USERNAME_CHANGED_TOO_MANY_TIMES, {- minutes: retryAfterMinutes(rateLimit),+ minutes: Math.max(1, Math.ceil(getRetryAfterSeconds(rateLimit) / 60)),});}}diff --git a/fluxer_api/src/api/user/UserHarvestModel.ts b/fluxer_api/src/api/user/UserHarvestModel.tsindex cbd394577..60b38bbcd 100644--- a/fluxer_api/src/api/user/UserHarvestModel.ts+++ b/fluxer_api/src/api/user/UserHarvestModel.ts@@ -8,9 +8,11 @@ export class UserHarvest {userId: UserID;harvestId: bigint;requestedAt: Date;+ attemptId: string | null;startedAt: Date | null;completedAt: Date | null;failedAt: Date | null;+ terminalFailedAt: Date | null;storageKey: string | null;fileSize: bigint | null;progressPercent: number;@@ -22,9 +24,11 @@ export class UserHarvest {this.userId = row.user_id;this.harvestId = row.harvest_id;this.requestedAt = row.requested_at;+ this.attemptId = row.attempt_id ?? null;this.startedAt = row.started_at ?? null;this.completedAt = row.completed_at ?? null;this.failedAt = row.failed_at ?? null;+ this.terminalFailedAt = row.terminal_failed_at ?? null;this.storageKey = row.storage_key ?? null;this.fileSize = row.file_size ?? null;this.progressPercent = row.progress_percent;@@ -38,9 +42,11 @@ export class UserHarvest {user_id: this.userId,harvest_id: this.harvestId,requested_at: this.requestedAt,+ attempt_id: this.attemptId,started_at: this.startedAt,completed_at: this.completedAt,failed_at: this.failedAt,+ terminal_failed_at: this.terminalFailedAt,storage_key: this.storageKey,file_size: this.fileSize,progress_percent: this.progressPercent,diff --git a/fluxer_api/src/api/user/UserHarvestRepository.ts b/fluxer_api/src/api/user/UserHarvestRepository.tsindex f4cf0c8f2..ff01e187f 100644--- a/fluxer_api/src/api/user/UserHarvestRepository.ts+++ b/fluxer_api/src/api/user/UserHarvestRepository.ts@@ -1,8 +1,12 @@// SPDX-License-Identifier: AGPL-3.0-or-later+import assert from 'node:assert/strict';+import {randomUUID} from 'node:crypto';+import {UnknownHarvestError} from '@fluxer/errors/src/domains/moderation/UnknownHarvestError';+import {ArchiveAttemptSupersededError} from '../archive/ArchiveAttemptSupersededError';import type {UserID} from '../BrandedTypes';-import {fetchMany, fetchOne, upsertOne} from '../database/CassandraQueryExecution';-import {Db} from '../database/CassandraTypes';+import {executeConditional, fetchMany, fetchOne} from '../database/CassandraQueryExecution';+import {Db, type DbOp} from '../database/CassandraTypes';import type {UserHarvestRow} from '../database/types/UserTypes';import {Logger} from '../Logger';import {UserHarvests} from '../Tables';@@ -21,33 +25,25 @@ const FIND_LATEST_HARVEST_CQL = UserHarvests.selectCql({limit: 1,});+interface UserHarvestPatch {+ completed_at?: DbOp<Date>;+ failed_at?: DbOp<Date>;+ terminal_failed_at?: DbOp<Date>;+ storage_key?: DbOp<string>;+ file_size?: DbOp<bigint>;+ progress_percent?: DbOp<number>;+ progress_step?: DbOp<string>;+ error_message?: DbOp<string>;+ download_url_expires_at?: DbOp<Date>;+}+export class UserHarvestRepository {async create(harvest: UserHarvest): Promise<void> {- await upsertOne(UserHarvests.upsertAll(harvest.toRow()));+ const applied = await executeConditional(UserHarvests.insertIfNotExists(harvest.toRow()));+ if (!applied) throw new Error(`Harvest ${harvest.harvestId} for user ${harvest.userId} already exists`);Logger.debug({userId: harvest.userId, harvestId: harvest.harvestId}, 'Created harvest record');}- async update(harvest: UserHarvest): Promise<void> {- const row = harvest.toRow();- await upsertOne(- UserHarvests.patchByPk(- {user_id: row.user_id, harvest_id: row.harvest_id},- {- started_at: Db.set(row.started_at),- completed_at: Db.set(row.completed_at),- failed_at: Db.set(row.failed_at),- storage_key: Db.set(row.storage_key),- file_size: Db.set(row.file_size),- progress_percent: Db.set(row.progress_percent),- progress_step: Db.set(row.progress_step),- error_message: Db.set(row.error_message),- download_url_expires_at: Db.set(row.download_url_expires_at),- },- ),- );- Logger.debug({userId: harvest.userId, harvestId: harvest.harvestId}, 'Updated harvest record');- }-async findByUserAndHarvestId(userId: UserID, harvestId: bigint): Promise<UserHarvest | null> {const row = await fetchOne<UserHarvestRow>(FIND_HARVEST_CQL, {user_id: userId,@@ -72,73 +68,120 @@ export class UserHarvestRepository {return row ? new UserHarvest(row) : null;}- async updateProgress(- userId: UserID,- harvestId: bigint,- progressPercent: number,- progressStep: string,- ): Promise<void> {- await upsertOne(- UserHarvests.patchByPk(- {user_id: userId, harvest_id: harvestId},+ async markAsStarted(harvest: UserHarvest): Promise<UserHarvest> {+ const attemptId = randomUUID();+ const startedAt = new Date();+ const applied = await executeConditional(+ UserHarvests.conditionalPatchByPk(+ {user_id: harvest.userId, harvest_id: harvest.harvestId},{- progress_percent: Db.set(progressPercent),- progress_step: Db.set(progressStep),- },- ),- );- Logger.debug({userId, harvestId, progressPercent, progressStep}, 'Updated harvest progress');- }-- async markAsStarted(userId: UserID, harvestId: bigint): Promise<void> {- await upsertOne(- UserHarvests.patchByPk(- {user_id: userId, harvest_id: harvestId},- {- started_at: Db.set(new Date()),+ attempt_id: Db.set(attemptId),+ started_at: Db.set(startedAt),failed_at: Db.clear(),error_message: Db.clear(),progress_percent: Db.set(0),progress_step: Db.set('Starting harvest'),},+ {+ requested_at: harvest.requestedAt,+ attempt_id: harvest.attemptId ?? null,+ completed_at: null,+ terminal_failed_at: null,+ },),);- Logger.debug({userId, harvestId}, 'Marked harvest as started');+ if (!applied) throw new ArchiveAttemptSupersededError();+ Logger.debug({userId: harvest.userId, harvestId: harvest.harvestId, attemptId}, 'Claimed harvest attempt');+ return new UserHarvest({+ ...harvest.toRow(),+ attempt_id: attemptId,+ started_at: startedAt,+ failed_at: null,+ error_message: null,+ progress_percent: 0,+ progress_step: 'Starting harvest',+ });+ }++ async updateProgress(harvest: UserHarvest, progressPercent: number, progressStep: string): Promise<void> {+ await this.patchOwned(harvest, {+ progress_percent: Db.set(progressPercent),+ progress_step: Db.set(progressStep),+ });+ Logger.debug(+ {userId: harvest.userId, harvestId: harvest.harvestId, progressPercent, progressStep},+ 'Updated harvest progress',+ );}async markAsCompleted(- userId: UserID,- harvestId: bigint,+ harvest: UserHarvest,storageKey: string,fileSize: bigint,downloadUrlExpiresAt: Date,): Promise<void> {- await upsertOne(- UserHarvests.patchByPk(- {user_id: userId, harvest_id: harvestId},- {- completed_at: Db.set(new Date()),- storage_key: Db.set(storageKey),- file_size: Db.set(fileSize),- download_url_expires_at: Db.set(downloadUrlExpiresAt),- progress_percent: Db.set(100),- progress_step: Db.set('Completed'),- },- ),+ await this.patchOwned(harvest, {+ completed_at: Db.set(new Date()),+ failed_at: Db.clear(),+ error_message: Db.clear(),+ storage_key: Db.set(storageKey),+ file_size: Db.set(fileSize),+ download_url_expires_at: Db.set(downloadUrlExpiresAt),+ progress_percent: Db.set(100),+ progress_step: Db.set('Completed'),+ });+ Logger.debug(+ {userId: harvest.userId, harvestId: harvest.harvestId, storageKey, fileSize},+ 'Marked harvest as completed',);- Logger.debug({userId, harvestId, storageKey, fileSize}, 'Marked harvest as completed');}- async markAsFailed(userId: UserID, harvestId: bigint, errorMessage: string): Promise<void> {- await upsertOne(- UserHarvests.patchByPk(+ async markAsFailed(harvest: UserHarvest, errorMessage: string): Promise<void> {+ await this.patchOwned(harvest, {+ failed_at: Db.set(new Date()),+ error_message: Db.set(errorMessage),+ });+ Logger.error({userId: harvest.userId, harvestId: harvest.harvestId, errorMessage}, 'Marked harvest as failed');+ }++ async markAsTerminallyFailed(harvest: UserHarvest, errorMessage: string): Promise<void> {+ const failedAt = new Date();+ await this.patchOwned(harvest, {+ failed_at: Db.set(failedAt),+ terminal_failed_at: Db.set(failedAt),+ error_message: Db.set(errorMessage),+ progress_step: Db.set('Failed'),+ });+ Logger.error(+ {userId: harvest.userId, harvestId: harvest.harvestId, errorMessage},+ 'Marked harvest as terminally failed',+ );+ }++ async setDownloadUrlExpiry(userId: UserID, harvestId: bigint, expiresAt: Date): Promise<void> {+ const harvest = await this.findByUserAndHarvestId(userId, harvestId);+ if (!harvest) throw new UnknownHarvestError();+ const applied = await executeConditional(+ UserHarvests.conditionalPatchByPk({user_id: userId, harvest_id: harvestId},- {- failed_at: Db.set(new Date()),- error_message: Db.set(errorMessage),- },+ {download_url_expires_at: Db.set(expiresAt)},+ {requested_at: harvest.requestedAt},),);- Logger.error({userId, harvestId, errorMessage}, 'Marked harvest as failed');+ if (!applied) throw new UnknownHarvestError();+ }++ private async patchOwned(harvest: UserHarvest, patch: UserHarvestPatch): Promise<void> {+ assert(harvest.attemptId, 'A claimed harvest attempt is required');+ const applied = await executeConditional(+ UserHarvests.conditionalPatchByPk({user_id: harvest.userId, harvest_id: harvest.harvestId}, patch, {+ requested_at: harvest.requestedAt,+ attempt_id: harvest.attemptId,+ completed_at: null,+ failed_at: null,+ terminal_failed_at: null,+ }),+ );+ if (!applied) throw new ArchiveAttemptSupersededError();}}diff --git a/fluxer_api/src/api/user/repositories/IUserAccountRepository.ts b/fluxer_api/src/api/user/repositories/IUserAccountRepository.tsindex 14d280721..f4225e31b 100644--- a/fluxer_api/src/api/user/repositories/IUserAccountRepository.ts+++ b/fluxer_api/src/api/user/repositories/IUserAccountRepository.ts@@ -4,10 +4,24 @@ import type {GuildID, UserID} from '../../BrandedTypes';import type {UserRow} from '../../database/types/UserTypes';import type {User} from '../../models/User';+export interface UserDeletionScheduleUpdate {+ pending_deletion_at: Date | null;+ flags?: bigint;+ deletion_reason_code?: number | null;+ deletion_public_reason?: string | null;+ deletion_audit_log_reason?: string | null;+ temp_banned_until?: Date | null;+ first_refund_at?: Date | null;+}+export interface IUserAccountRepository {create(data: UserRow): Promise<User>;upsert(data: UserRow, oldData?: UserRow | null): Promise<User>;patchUpsert(userId: UserID, patchData: Partial<UserRow>, oldData?: UserRow | null): Promise<User>;+ updateDeletionSchedule(user: User, patch: UserDeletionScheduleUpdate): Promise<User>;+ startDeletion(userId: UserID, pendingDeletionAt: Date): Promise<User | null>;+ anonymizeForDeletion(user: User, patch: Partial<UserRow>): Promise<User>;+ completeDeletion(user: User): Promise<void>;findUnique(userId: UserID): Promise<User | null>;findUniqueAssert(userId: UserID): Promise<User>;findByUsernameDiscriminator(username: string, discriminator: number): Promise<User | null>;diff --git a/fluxer_api/src/api/user/repositories/IUserAuthRepository.ts b/fluxer_api/src/api/user/repositories/IUserAuthRepository.tsindex 59f24752e..cd2d92fab 100644--- a/fluxer_api/src/api/user/repositories/IUserAuthRepository.ts+++ b/fluxer_api/src/api/user/repositories/IUserAuthRepository.ts@@ -22,7 +22,6 @@ export interface IUserAuthRepository {createAuthSession(sessionData: AuthSessionRow): Promise<AuthSession>;updateAuthSessionLastUsed(sessionIdHash: Buffer): Promise<void>;deleteAuthSessions(userId: UserID, sessionIdHashes: Array<Buffer>): Promise<void>;- revokeAuthSession(sessionIdHash: Buffer): Promise<void>;deleteAllAuthSessions(userId: UserID): Promise<void>;recordCountrySighting(userId: UserID, country: string): Promise<void>;hasCountrySightingOutsideSet(userId: UserID, countryCodes: Iterable<string>): Promise<boolean>;diff --git a/fluxer_api/src/api/user/repositories/PushSubscriptionRepository.ts b/fluxer_api/src/api/user/repositories/PushSubscriptionRepository.tsindex 1cc6b1510..c0586862d 100644--- a/fluxer_api/src/api/user/repositories/PushSubscriptionRepository.ts+++ b/fluxer_api/src/api/user/repositories/PushSubscriptionRepository.ts@@ -5,6 +5,7 @@ import {deleteOneOrMany, fetchMany, upsertOne} from '../../database/CassandraQueimport type {PushSubscriptionRow} from '../../database/types/UserTypes';import {PushSubscription} from '../../models/PushSubscription';import {PushSubscriptions} from '../../Tables';+import {awaitAll} from '../../utils/ConcurrencyUtils';const FETCH_PUSH_SUBSCRIPTIONS_CQL = PushSubscriptions.selectCql({where: PushSubscriptions.where.eq('user_id'),@@ -43,8 +44,11 @@ export class PushSubscriptionRepository {return authSessionIdHashSet.has(subscription.authSessionIdHash);});if (subscriptionsToDelete.length === 0) return;- await Promise.all(- subscriptionsToDelete.map((subscription) => this.deletePushSubscription(userId, subscription.subscriptionId)),+ await awaitAll(+ subscriptionsToDelete.map(async (subscription) =>+ this.deletePushSubscription(userId, subscription.subscriptionId),+ ),+ 'Failed to delete push subscriptions for auth sessions',);}diff --git a/fluxer_api/src/api/user/repositories/UserAccountRepository.ts b/fluxer_api/src/api/user/repositories/UserAccountRepository.tsindex 4d2987dba..4baeca1a1 100644--- a/fluxer_api/src/api/user/repositories/UserAccountRepository.ts+++ b/fluxer_api/src/api/user/repositories/UserAccountRepository.ts@@ -10,7 +10,7 @@ import {UserDeletionRepository} from './account/UserDeletionRepository';import {UserGuildRepository} from './account/UserGuildRepository';import {UserLookupRepository} from './account/UserLookupRepository';import {TokenRepository} from './auth/TokenRepository';-import type {IUserAccountRepository} from './IUserAccountRepository';+import type {IUserAccountRepository, UserDeletionScheduleUpdate} from './IUserAccountRepository';export class UserAccountRepository implements IUserAccountRepository {private accountRepo: UserAccountCrudRepository;@@ -68,6 +68,22 @@ export class UserAccountRepository implements IUserAccountRepository {return this.accountRepo.patchUpsert(userId, patchData, oldData);}+ async updateDeletionSchedule(user: User, patch: UserDeletionScheduleUpdate): Promise<User> {+ return this.accountRepo.updateDeletionSchedule(user, patch);+ }++ async startDeletion(userId: UserID, pendingDeletionAt: Date): Promise<User | null> {+ return this.accountRepo.startDeletion(userId, pendingDeletionAt);+ }++ async anonymizeForDeletion(user: User, patch: Partial<UserRow>): Promise<User> {+ return this.accountRepo.anonymizeForDeletion(user, patch);+ }++ async completeDeletion(user: User): Promise<void> {+ return this.accountRepo.completeDeletion(user);+ }+async deleteUserSecondaryIndices(userId: UserID): Promise<void> {return this.accountRepo.deleteUserSecondaryIndices(userId);}diff --git a/fluxer_api/src/api/user/repositories/UserAuthRepository.ts b/fluxer_api/src/api/user/repositories/UserAuthRepository.tsindex 26d84f3b5..145ad23ae 100644--- a/fluxer_api/src/api/user/repositories/UserAuthRepository.ts+++ b/fluxer_api/src/api/user/repositories/UserAuthRepository.ts@@ -63,12 +63,6 @@ export class UserAuthRepository implements IUserAuthRepository {return this.authSessionRepository.deleteAuthSessions(userId, sessionIdHashes);}- async revokeAuthSession(sessionIdHash: Buffer): Promise<void> {- const session = await this.getAuthSessionByToken(sessionIdHash);- if (!session) return;- await this.deleteAuthSessions(session.userId, [sessionIdHash]);- }-async deleteAllAuthSessions(userId: UserID): Promise<void> {return this.authSessionRepository.deleteAllAuthSessions(userId);}diff --git a/fluxer_api/src/api/user/repositories/UserRepository.ts b/fluxer_api/src/api/user/repositories/UserRepository.tsindex fb5853c23..8992d4587 100644--- a/fluxer_api/src/api/user/repositories/UserRepository.ts+++ b/fluxer_api/src/api/user/repositories/UserRepository.ts@@ -39,6 +39,7 @@ import type {UserSettings} from '../../models/UserSettings';import type {VisionarySlot} from '../../models/VisionarySlot';import type {WebAuthnCredential} from '../../models/WebAuthnCredential';import {ReadStateRepository} from '../../read_state/ReadStateRepository';+import type {UserDeletionScheduleUpdate} from './IUserAccountRepository';import type {HistoricalDmChannelSummary,ListHistoricalDmChannelOptions,@@ -83,6 +84,22 @@ export class UserRepository implements IUserRepositoryAggregate {return this.accountRepo.patchUpsert(userId, patchData, oldData);}+ async updateDeletionSchedule(user: User, patch: UserDeletionScheduleUpdate): Promise<User> {+ return this.accountRepo.updateDeletionSchedule(user, patch);+ }++ async startDeletion(userId: UserID, pendingDeletionAt: Date): Promise<User | null> {+ return this.accountRepo.startDeletion(userId, pendingDeletionAt);+ }++ async anonymizeForDeletion(user: User, patch: Partial<UserRow>): Promise<User> {+ return this.accountRepo.anonymizeForDeletion(user, patch);+ }++ async completeDeletion(user: User): Promise<void> {+ return this.accountRepo.completeDeletion(user);+ }+async findUnique(userId: UserID): Promise<User | null> {return this.accountRepo.findUnique(userId);}@@ -260,10 +277,6 @@ export class UserRepository implements IUserRepositoryAggregate {return this.authRepo.deleteAuthSessions(userId, sessionIdHashes);}- async revokeAuthSession(sessionIdHash: Buffer): Promise<void> {- return this.authRepo.revokeAuthSession(sessionIdHash);- }-async deleteAllAuthSessions(userId: UserID): Promise<void> {return this.authRepo.deleteAllAuthSessions(userId);}diff --git a/fluxer_api/src/api/user/repositories/account/UserAccountRepository.ts b/fluxer_api/src/api/user/repositories/account/UserAccountRepository.tsindex f6df49dbf..b5fe928a7 100644--- a/fluxer_api/src/api/user/repositories/account/UserAccountRepository.ts+++ b/fluxer_api/src/api/user/repositories/account/UserAccountRepository.ts@@ -10,7 +10,8 @@ import type {UserID} from '../../../BrandedTypes';import {Db, type DbOp} from '../../../database/CassandraTypes';import type {UserRow} from '../../../database/types/UserTypes';import {User} from '../../../models/User';-import {UserDataRepository} from './crud/UserDataRepository';+import type {UserDeletionScheduleUpdate} from '../IUserAccountRepository';+import {UserDataRepository, type UserDeletionTransition} from './crud/UserDataRepository';import {type EmailClaimReservation, UserEmailOwnershipRepository} from './crud/UserEmailOwnershipRepository';import {UserIndexRepository} from './crud/UserIndexRepository';import {UserSearchRepository} from './crud/UserSearchRepository';@@ -96,23 +97,45 @@ export class UserAccountRepository {}async patchUpsert(userId: UserID, patchData: Partial<UserRow>, oldData?: UserRow | null): Promise<User> {+ return this.patchAccount(userId, patchData, oldData);+ }++ async updateDeletionSchedule(user: User, patch: UserDeletionScheduleUpdate): Promise<User> {+ return this.patchAccount(user.id, patch, user.toRow(), 'schedule');+ }++ async startDeletion(userId: UserID, pendingDeletionAt: Date): Promise<User | null> {+ return this.dataRepo.startDeletion(userId, pendingDeletionAt);+ }++ async anonymizeForDeletion(user: User, patch: Partial<UserRow>): Promise<User> {+ return this.patchAccount(user.id, patch, user.toRow(), 'anonymise');+ }++ async completeDeletion(user: User): Promise<void> {+ await this.dataRepo.patchDeletion(user, {pending_deletion_at: Db.clear()}, 'complete');+ }++ private async patchAccount(+ userId: UserID,+ patchData: Partial<UserRow>,+ oldData?: UserRow | null,+ deletionTransition?: UserDeletionTransition,+ ): Promise<User> {if (!oldData) {const existingUser = await this.findUniqueAssert(userId);oldData = existingUser.toRow();}patchData = this.migratePremiumFlagsInPatch(patchData, oldData);- const definedPatchData = Object.fromEntries(Object.entries(patchData).filter(([, v]) => v !== undefined));const userPatch: Record<string, DbOp<unknown>> = {};- for (const [key, value] of Object.entries(definedPatchData)) {- if (key === 'user_id') continue;- const userRowKey = key as keyof UserRow;- if (value === null) {- const oldVal = oldData?.[userRowKey];- if (oldVal !== null && oldVal !== undefined) {- userPatch[key] = Db.clear();- }- } else {+ for (const [key, value] of Object.entries(patchData)) {+ if (key === 'user_id' || value === undefined) continue;+ if (value !== null) {userPatch[key] = Db.set(value);+ continue;+ }+ if (oldData[key as keyof UserRow] != null) {+ userPatch[key] = Db.clear();}}const nextEmail = typeof patchData.email === 'string' ? patchData.email : null;@@ -123,7 +146,9 @@ export class UserAccountRepository {}let dataCommitted = false;try {- const result = await this.dataRepo.patchUser(userId, userPatch, oldData);+ const result = deletionTransition+ ? await this.dataRepo.patchDeletion(new User(oldData), userPatch, deletionTransition)+ : await this.dataRepo.patchUser(userId, userPatch, oldData);if (result.finalVersion === null) {throw new Error(`Failed to update user ${userId} due to concurrent modification`);}@@ -133,7 +158,9 @@ export class UserAccountRepository {const updatedUser = new User(updatedData);await this.emailOwnershipRepo.finalizeEmailClaim(emailClaim);await this.releasePreviousEmailIfChanged(previousData, updatedData);- await this.indexRepo.syncIndices(updatedData, previousData);+ if (deletionTransition !== 'anonymise') {+ await this.indexRepo.syncIndices(updatedData, previousData);+ }await this.searchRepo.updateUser(updatedUser);return updatedUser;} catch (error) {diff --git a/fluxer_api/src/api/user/repositories/account/crud/UserDataRepository.ts b/fluxer_api/src/api/user/repositories/account/crud/UserDataRepository.tsindex d82105bfc..74068af3f 100644--- a/fluxer_api/src/api/user/repositories/account/crud/UserDataRepository.ts+++ b/fluxer_api/src/api/user/repositories/account/crud/UserDataRepository.ts@@ -1,11 +1,19 @@// SPDX-License-Identifier: AGPL-3.0-or-later+import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';import {DELETED_USER_ID, UserFlags} from '@fluxer/constants/src/UserConstants';+import {ConflictError} from '@fluxer/errors/src/domains/core/ConflictError';import {UnknownUserError} from '@fluxer/errors/src/domains/user/UnknownUserError';import {BACKGROUND_READ_TIMEOUT_MS} from '@pkgs/cassandra/src/Client';import {createUserID, type UserID} from '../../../../BrandedTypes';import {isSyntheticUserId} from '../../../../constants/Core';-import {fetchMany, fetchOne, fetchPage, upsertOne} from '../../../../database/CassandraQueryExecution';+import {+ executeConditional,+ fetchMany,+ fetchOne,+ fetchPage,+ upsertOne,+} from '../../../../database/CassandraQueryExecution';import {Db, type DbOp, nextVersion} from '../../../../database/CassandraTypes';import {applyPatchToRow,@@ -16,6 +24,7 @@ import type {UserRow} from '../../../../database/types/UserTypes';import {EMPTY_USER_ROW, USER_COLUMNS} from '../../../../database/types/UserTypes';import {User} from '../../../../models/User';import {Users} from '../../../../Tables';+import {isPendingDeletionBlocked} from '../../../services/PendingDeletionCoordinator';const FLUXER_BOT_USER_ID = 0n;const FETCH_USERS_BY_IDS_CQL = Users.selectCql({@@ -46,6 +55,14 @@ type UserPatch = Partial<{[K in Exclude<keyof UserRow, 'user_id'> & string]: DbOp<UserRow[K]>;}>;+export type UserDeletionTransition = 'schedule' | 'anonymise' | 'complete';++function assertOrdinaryUserPatch(patch: UserPatch): void {+ if (patch.pending_deletion_at || patch.deletion_started_at) {+ throw new Error('User deletion state must be changed through the deletion lifecycle');+ }+}+function assertWritableUserId(userId: UserID): void {if (isSyntheticUserId(userId)) {throw new Error(`Refusing to write a users row for synthetic user ${userId}`);@@ -137,10 +154,11 @@ export class UserDataRepository {async () => {return fetchOne<UserRow>(FETCH_USER_BY_ID_CQL, {user_id: userId});},- (current) => ({- pk: {user_id: userId},- patch: buildPatchFromData(data, current, USER_COLUMNS, ['user_id']),- }),+ (current) => {+ const patch = buildPatchFromData(data, current, USER_COLUMNS, ['user_id']);+ assertOrdinaryUserPatch(patch);+ return {pk: {user_id: userId}, patch};+ },Users,{initialData: oldData},);@@ -161,6 +179,7 @@ export class UserDataRepository {updatedData: UserRow;}> {assertWritableUserId(userId);+ assertOrdinaryUserPatch(patch);const result = await executeVersionedUpdate<UserRow, 'user_id'>(async () => {return fetchOne<UserRow>(FETCH_USER_BY_ID_CQL, {user_id: userId});@@ -181,6 +200,70 @@ export class UserDataRepository {return {finalVersion: result.finalVersion, previousData, updatedData};}+ async patchDeletion(+ user: User,+ patch: UserPatch,+ transition: UserDeletionTransition,+ ): Promise<{+ finalVersion: number;+ previousData: UserRow;+ updatedData: UserRow;+ }> {+ assertWritableUserId(user.id);+ if (patch.deletion_started_at) throw new Error('The deletion start marker is immutable');+ if (transition === 'schedule' && user.deletionStartedAt) {+ throw new ConflictError({code: APIErrorCodes.CONFLICT, message: 'Account deletion has already started'});+ }+ if (transition !== 'schedule' && (!user.deletionStartedAt || !user.pendingDeletionAt)) {+ throw new Error('Account deletion must be started before completion');+ }+ if (transition === 'anonymise' && patch.pending_deletion_at) {+ throw new Error('Account deletion must retain its schedule until cleanup completes');+ }+ const previousData = user.toRow();+ const finalVersion = nextVersion(user.version);+ const applied = await executeConditional(+ Users.conditionalPatchByPk(+ {user_id: user.id},+ {...patch, version: Db.set(finalVersion)},+ {+ pending_deletion_at: user.pendingDeletionAt,+ deletion_started_at: transition === 'schedule' ? null : user.deletionStartedAt,+ flags: previousData.flags,+ version: user.version,+ },+ ),+ );+ if (!applied) {+ throw new ConflictError({code: APIErrorCodes.CONFLICT, message: 'Account deletion state has changed'});+ }+ const updatedData = {...previousData, ...applyPatchToRow(previousData, patch), version: finalVersion};+ return {finalVersion, previousData, updatedData};+ }++ async startDeletion(userId: UserID, pendingDeletionAt: Date): Promise<User | null> {+ assertWritableUserId(userId);+ const scheduledAt = pendingDeletionAt.getTime();+ if (!Number.isFinite(scheduledAt)) throw new Error('Account deletion requires a valid captured schedule');+ const user = await this.findUnique(userId);+ if (!user || user.pendingDeletionAt?.getTime() !== scheduledAt) return null;+ if (user.deletionStartedAt) return user;+ const startedAt = new Date();+ if (scheduledAt > startedAt.getTime() || isPendingDeletionBlocked(user)) return null;+ const version = nextVersion(user.version);+ const applied = await executeConditional(+ Users.conditionalPatchByPk(+ {user_id: userId},+ {deletion_started_at: Db.set(startedAt), version: Db.set(version)},+ {pending_deletion_at: pendingDeletionAt, deletion_started_at: null, flags: user.flags, version: user.version},+ ),+ );+ if (!applied) {+ throw new ConflictError({code: APIErrorCodes.CONFLICT, message: 'Account deletion state has changed'});+ }+ return new User({...user.toRow(), deletion_started_at: startedAt, version});+ }+async updateLastActiveAt(params: {userId: UserID; lastActiveAt: Date; lastActiveIp?: string}): Promise<{previousData: {last_active_at: Date | null;diff --git a/fluxer_api/src/api/user/repositories/account/crud/UserSearchRepository.ts b/fluxer_api/src/api/user/repositories/account/crud/UserSearchRepository.tsindex eb7f925c5..c81b91a76 100644--- a/fluxer_api/src/api/user/repositories/account/crud/UserSearchRepository.ts+++ b/fluxer_api/src/api/user/repositories/account/crud/UserSearchRepository.ts@@ -7,7 +7,7 @@ import {getUserSearchService} from '../../../../SearchFactory';export class UserSearchRepository {async indexUser(user: User): Promise<void> {const userSearchService = getUserSearchService();- if (userSearchService && 'indexUser' in userSearchService) {+ if (userSearchService) {await userSearchService.indexUser(user).catch((error) => {Logger.error({userId: user.id, error}, 'Failed to index user in search');});@@ -16,7 +16,7 @@ export class UserSearchRepository {async updateUser(user: User): Promise<void> {const userSearchService = getUserSearchService();- if (userSearchService && 'updateUser' in userSearchService) {+ if (userSearchService) {await userSearchService.updateUser(user).catch((error) => {Logger.error({userId: user.id, error}, 'Failed to update user in search');});diff --git a/fluxer_api/src/api/user/repositories/auth/AuthSessionRepository.ts b/fluxer_api/src/api/user/repositories/auth/AuthSessionRepository.tsindex ae01c04a1..4259c8b73 100644--- a/fluxer_api/src/api/user/repositories/auth/AuthSessionRepository.ts+++ b/fluxer_api/src/api/user/repositories/auth/AuthSessionRepository.ts@@ -1,5 +1,7 @@// SPDX-License-Identifier: AGPL-3.0-or-later+import {SnowflakeType} from '@fluxer/schema/src/primitives/SchemaPrimitives';+import {z} from 'zod';import {createUserID, type UserID} from '../../../BrandedTypes';import {BatchBuilder, fetchMany, fetchOne, upsertOne} from '../../../database/CassandraQueryExecution';import {Db} from '../../../database/CassandraTypes';@@ -8,6 +10,8 @@ import {Logger} from '../../../Logger';import {getCacheService, getPhoneFraudGraphService} from '../../../middleware/ServiceSingletons';import {AuthSession, AuthSessionTombstone} from '../../../models/AuthSession';import {AuthSessions, AuthSessionsByUserId, AuthSessionTombstones, UserCountryHistory} from '../../../Tables';+import {awaitAll} from '../../../utils/ConcurrencyUtils';+import {isValidTimestamp} from '../../../utils/TimestampUtils';const AUTH_SESSION_CACHE_TTL_SECONDS = 30;const AUTH_SESSION_MISS_CACHE_TTL_SECONDS = 5;@@ -24,6 +28,20 @@ interface CachedAuthSession {version: number;}+const CachedAuthSessionSchema = z.object({+ user_id: z+ .string()+ .refine((value) => value.length <= 19 && !/\D/.test(value) && SnowflakeType.safeParse(value).success),+ session_id_hash: z.string(),+ created_at: z.custom<number>(isValidTimestamp),+ approx_last_used_at: z.custom<number>(isValidTimestamp),+ client_ip: z.string(),+ client_user_agent: z.string().nullable(),+ client_os: z.string().nullable(),+ client_country: z.string().nullable(),+ version: z.int().nonnegative(),+}) satisfies z.ZodType<CachedAuthSession>;+function authSessionCacheKey(sessionIdHash: Buffer): string {return `auth:session:${sessionIdHash.toString('base64url')}`;}@@ -42,10 +60,18 @@ function encodeCachedAuthSession(row: AuthSessionRow): CachedAuthSession {};}-function decodeCachedAuthSession(cached: CachedAuthSession): AuthSessionRow {+function decodeCachedAuthSession(value: unknown, sessionIdHash: Buffer): AuthSessionRow {+ const parsed = CachedAuthSessionSchema.safeParse(value);+ if (!parsed.success) {+ throw new TypeError('Cached auth session has an invalid shape', {cause: parsed.error});+ }+ const cached = parsed.data;+ if (cached.session_id_hash !== sessionIdHash.toString('base64url')) {+ throw new Error('Cached auth session does not match the requested token hash');+ }return {user_id: createUserID(BigInt(cached.user_id)),- session_id_hash: Buffer.from(cached.session_id_hash, 'base64url'),+ session_id_hash: Buffer.from(sessionIdHash),created_at: new Date(cached.created_at),approx_last_used_at: new Date(cached.approx_last_used_at),client_ip: cached.client_ip,@@ -60,7 +86,10 @@ async function invalidateAuthSessionCache(sessionIdHashes: ReadonlyArray<Buffer>if (sessionIdHashes.length === 0) return;try {const cache = getCacheService();- await Promise.all(sessionIdHashes.map((sessionIdHash) => cache.delete(authSessionCacheKey(sessionIdHash))));+ await awaitAll(+ sessionIdHashes.map(async (sessionIdHash) => cache.delete(authSessionCacheKey(sessionIdHash))),+ 'Failed to invalidate cached auth sessions',+ );} catch (error) {Logger.error({error}, 'Failed to invalidate cached auth sessions; they expire with the cache ttl');}@@ -163,19 +192,21 @@ export class AuthSessionRepository {}async getAuthSessionByToken(sessionIdHash: Buffer): Promise<AuthSession | null> {+ let sessionRead: Promise<AuthSessionRow | null> | undefined;+ const readSession = () => (sessionRead ??= this.fetchAuthSessionByToken(sessionIdHash));try {- const cached = await getCacheService().getOrSet<CachedAuthSession | null>(+ const cached = await getCacheService().getOrSet<unknown>(authSessionCacheKey(sessionIdHash),async () => {- const session = await this.fetchAuthSessionByToken(sessionIdHash);+ const session = await readSession();return session ? encodeCachedAuthSession(session) : null;},(value) => (value === null ? AUTH_SESSION_MISS_CACHE_TTL_SECONDS : AUTH_SESSION_CACHE_TTL_SECONDS),);- return cached ? new AuthSession(decodeCachedAuthSession(cached)) : null;+ return cached === null ? null : new AuthSession(decodeCachedAuthSession(cached, sessionIdHash));} catch (error) {+ const session = await readSession();Logger.warn({error}, 'Auth session cache lookup failed; falling back to the datastore');- const session = await this.fetchAuthSessionByToken(sessionIdHash);return session ? new AuthSession(session) : null;}}@@ -217,18 +248,9 @@ export class AuthSessionRepository {async deleteAuthSessions(userId: UserID, sessionIdHashes: Array<Buffer>): Promise<void> {if (sessionIdHashes.length === 0) return;await invalidateAuthSessionCache(sessionIdHashes);- let originals: Array<AuthSessionRow> = [];- try {- originals = await fetchMany<AuthSessionRow>(FETCH_AUTH_SESSIONS_CQL, {- session_id_hashes: sessionIdHashes,- });- } catch (error) {- Logger.warn(- {userId: userId.toString(), error},- 'Failed to read auth sessions before delete; aborting to avoid cross-user deletion',- );- return;- }+ const originals = await fetchMany<AuthSessionRow>(FETCH_AUTH_SESSIONS_CQL, {+ session_id_hashes: sessionIdHashes,+ });const owned = originals.filter((original) => original.user_id === userId);if (owned.length === 0) return;const deletedAt = new Date();diff --git a/fluxer_api/src/api/user/services/UserAccountLifecycleService.ts b/fluxer_api/src/api/user/services/UserAccountLifecycleService.tsindex 1819a873b..5fb3611c1 100644--- a/fluxer_api/src/api/user/services/UserAccountLifecycleService.ts+++ b/fluxer_api/src/api/user/services/UserAccountLifecycleService.ts@@ -100,15 +100,11 @@ export class UserAccountLifecycleService {}const gracePeriodMs = Config.deletionGracePeriodHours * ms('1 hour');const pendingDeletionAt = new Date(Date.now() + gracePeriodMs);- const updatedUser = await this.deps.userAccountRepository.patchUpsert(- userId,- {- flags: user.flags | UserFlags.SELF_DELETED,- pending_deletion_at: pendingDeletionAt,- deletion_reason_code: DeletionReasons.USER_REQUESTED,- },- user.toRow(),- );+ const updatedUser = await this.deps.userAccountRepository.updateDeletionSchedule(user, {+ flags: user.flags | UserFlags.SELF_DELETED,+ pending_deletion_at: pendingDeletionAt,+ deletion_reason_code: DeletionReasons.USER_REQUESTED,+ });await reschedulePendingDeletion({userId,currentPendingDeletionAt: user.pendingDeletionAt,diff --git a/fluxer_api/src/api/user/services/UserAccountProfileService.ts b/fluxer_api/src/api/user/services/UserAccountProfileService.tsindex 0ec76a1fa..76e149af2 100644--- a/fluxer_api/src/api/user/services/UserAccountProfileService.ts+++ b/fluxer_api/src/api/user/services/UserAccountProfileService.ts@@ -23,17 +23,11 @@ import {deriveDominantAvatarColor} from '../../utils/AvatarColorUtils';import * as EmojiUtils from '../../utils/EmojiUtils';import type {IUserAccountRepository} from '../repositories/IUserAccountRepository';import {canUseProfileTimezone, isProfileSubstringExempt} from '../UserHelpers';-import type {UserAccountUpdatePropagator} from './UserAccountUpdatePropagator';--interface UserUpdateMetadata {- invalidateAuthSessions?: boolean;-}type UserFieldUpdates = Partial<UserRow>;interface ProfileUpdateResult {updates: UserFieldUpdates;- metadata: UserUpdateMetadata;preparedAvatarUpload: PreparedAssetUpload | null;preparedBannerUpload: PreparedAssetUpload | null;}@@ -43,10 +37,17 @@ interface UserAccountProfileServiceDeps {guildRepository: IGuildRepositoryAggregate;entityAssetService: EntityAssetService;rateLimitService: IRateLimitService;- updatePropagator: UserAccountUpdatePropagator;limitConfigService: LimitConfigService;}+const PREMIUM_BADGE_FIELDS = [+ {field: 'premium_badge_hidden', flag: PremiumFlags.BADGE_HIDDEN},+ {field: 'premium_badge_masked', flag: PremiumFlags.BADGE_MASKED},+ {field: 'premium_badge_timestamp_hidden', flag: PremiumFlags.BADGE_TIMESTAMP_HIDDEN},+ {field: 'premium_badge_sequence_hidden', flag: PremiumFlags.BADGE_SEQUENCE_HIDDEN},+ {field: 'premium_enabled_override', flag: PremiumFlags.ENABLED_OVERRIDE},+] as const;+export class UserAccountProfileService {constructor(private readonly deps: UserAccountProfileServiceDeps) {}@@ -57,7 +58,6 @@ export class UserAccountProfileService {banner_hash: user.bannerHash,flags: user.flags,};- const metadata: UserUpdateMetadata = {};let preparedAvatarUpload: PreparedAssetUpload | null = null;let preparedBannerUpload: PreparedAssetUpload | null = null;if (data.bio !== undefined) {@@ -97,6 +97,9 @@ export class UserAccountProfileService {updates,});}+ if (!user.isBot) {+ this.processPremiumBadgeFlags({user, data, updates});+ }if (data.avatar !== undefined) {preparedAvatarUpload = await this.processAvatarUpdate({user, avatar: data.avatar, updates});}@@ -111,38 +114,17 @@ export class UserAccountProfileService {}}if (!user.isBot) {- this.processPremiumBadgeFlags({user, data, updates});- this.processPremiumOnboardingDismissal({user, data, updates});+ this.processPremiumOnboardingDismissal({data, updates});this.processGiftInventoryRead({user, data, updates});}if (data.mention_flags !== undefined) {updates.mention_flags = data.mention_flags;}- return {updates, metadata, preparedAvatarUpload, preparedBannerUpload};+ return {updates, preparedAvatarUpload, preparedBannerUpload};}async commitAssetChanges(result: ProfileUpdateResult): Promise<void> {- if (result.preparedAvatarUpload) {- await this.deps.entityAssetService.commitAssetChange({- prepared: result.preparedAvatarUpload,- deferDeletion: true,- });- }- if (result.preparedBannerUpload) {- await this.deps.entityAssetService.commitAssetChange({- prepared: result.preparedBannerUpload,- deferDeletion: true,- });- }- }-- async rollbackAssetChanges(result: ProfileUpdateResult): Promise<void> {- if (result.preparedAvatarUpload) {- await this.deps.entityAssetService.rollbackAssetUpload(result.preparedAvatarUpload);- }- if (result.preparedBannerUpload) {- await this.deps.entityAssetService.rollbackAssetUpload(result.preparedBannerUpload);- }+ await this.deps.entityAssetService.commitAssetChanges([result.preparedAvatarUpload, result.preparedBannerUpload]);}private async processBioUpdate(params: {user: User; bio: string | null; updates: UserFieldUpdates}): Promise<void> {@@ -387,66 +369,21 @@ export class UserAccountProfileService {private processPremiumBadgeFlags(params: {user: User; data: UserUpdateRequest; updates: UserFieldUpdates}): void {const {user, data, updates} = params;- let flagsUpdated = false;- let newPremiumFlags = user.premiumFlags;- if (data.premium_badge_hidden !== undefined) {- if (data.premium_badge_hidden) {- newPremiumFlags = newPremiumFlags | PremiumFlags.BADGE_HIDDEN;- } else {- newPremiumFlags = newPremiumFlags & ~PremiumFlags.BADGE_HIDDEN;- }- flagsUpdated = true;- }- if (data.premium_badge_masked !== undefined) {- if (data.premium_badge_masked) {- newPremiumFlags = newPremiumFlags | PremiumFlags.BADGE_MASKED;- } else {- newPremiumFlags = newPremiumFlags & ~PremiumFlags.BADGE_MASKED;- }- flagsUpdated = true;- }- if (data.premium_badge_timestamp_hidden !== undefined) {- if (data.premium_badge_timestamp_hidden) {- newPremiumFlags = newPremiumFlags | PremiumFlags.BADGE_TIMESTAMP_HIDDEN;- } else {- newPremiumFlags = newPremiumFlags & ~PremiumFlags.BADGE_TIMESTAMP_HIDDEN;- }- flagsUpdated = true;- }- if (data.premium_badge_sequence_hidden !== undefined) {- if (data.premium_badge_sequence_hidden) {- newPremiumFlags = newPremiumFlags | PremiumFlags.BADGE_SEQUENCE_HIDDEN;- } else {- newPremiumFlags = newPremiumFlags & ~PremiumFlags.BADGE_SEQUENCE_HIDDEN;- }- flagsUpdated = true;+ if (data.premium_enabled_override !== undefined && !(user.flags & UserFlags.STAFF)) {+ throw new MissingAccessError();}- if (data.premium_enabled_override !== undefined) {- if (!(user.flags & UserFlags.STAFF)) {- throw new MissingAccessError();- }- if (data.premium_enabled_override) {- newPremiumFlags = newPremiumFlags | PremiumFlags.ENABLED_OVERRIDE;- } else {- newPremiumFlags = newPremiumFlags & ~PremiumFlags.ENABLED_OVERRIDE;- }- flagsUpdated = true;- }- if (flagsUpdated) {- updates.premium_flags = newPremiumFlags;+ for (const {field, flag} of PREMIUM_BADGE_FIELDS) {+ const enabled = data[field];+ if (enabled === undefined) continue;+ const flags = updates.premium_flags ?? user.premiumFlags;+ updates.premium_flags = enabled ? flags | flag : flags & ~flag;}}- private processPremiumOnboardingDismissal(params: {- user: User;- data: UserUpdateRequest;- updates: UserFieldUpdates;- }): void {+ private processPremiumOnboardingDismissal(params: {data: UserUpdateRequest; updates: UserFieldUpdates}): void {const {data, updates} = params;- if (data.has_dismissed_premium_onboarding !== undefined) {- if (data.has_dismissed_premium_onboarding) {- updates.premium_onboarding_dismissed_at = new Date();- }+ if (data.has_dismissed_premium_onboarding) {+ updates.premium_onboarding_dismissed_at = new Date();}}diff --git a/fluxer_api/src/api/user/services/UserAccountSecurityService.ts b/fluxer_api/src/api/user/services/UserAccountSecurityService.tsindex 07ef0790b..39566527a 100644--- a/fluxer_api/src/api/user/services/UserAccountSecurityService.ts+++ b/fluxer_api/src/api/user/services/UserAccountSecurityService.ts@@ -127,8 +127,6 @@ export class UserAccountSecurityService {if (user.isBot) {updates.global_name = null;} else if (data.global_name !== undefined) {- if (data.global_name !== user.globalName) {- }if (data.global_name &&!isProfileSubstringExempt(user) &&diff --git a/fluxer_api/src/api/user/services/UserAccountService.ts b/fluxer_api/src/api/user/services/UserAccountService.tsindex 0a3580fd0..00606bcd7 100644--- a/fluxer_api/src/api/user/services/UserAccountService.ts+++ b/fluxer_api/src/api/user/services/UserAccountService.ts@@ -17,6 +17,7 @@ import {Logger} from '../../Logger';import type {LimitConfigService} from '../../limits/LimitConfigService';import type {AuthSession} from '../../models/AuthSession';import type {User} from '../../models/User';+import {runAllInOrder} from '../../utils/ConcurrencyUtils';import type {IUserAccountRepository} from '../repositories/IUserAccountRepository';import type {IUserChannelRepository} from '../repositories/IUserChannelRepository';import type {IUserRelationshipRepository} from '../repositories/IUserRelationshipRepository';@@ -102,7 +103,6 @@ export class UserAccountService {guildRepository,entityAssetService,rateLimitService,- updatePropagator: this.updatePropagator,limitConfigService,});this.securityService = new UserAccountSecurityService({@@ -150,10 +150,11 @@ export class UserAccountService {const profileFlags = profileResult.updates.flags ?? user.flags;updates.flags = profileFlags | (securityResult.updates.flags & ~user.flags);}- const metadata = {- ...securityResult.metadata,- ...profileResult.metadata,- };+ const securityPremiumFlags = securityResult.updates.premium_flags;+ if (securityPremiumFlags !== undefined && securityPremiumFlags !== null) {+ const profilePremiumFlags = profileResult.updates.premium_flags ?? user.premiumFlags;+ updates.premium_flags = profilePremiumFlags | (securityPremiumFlags & ~user.premiumFlags);+ }const emailChanged = data.email !== undefined;if (emailChanged) {updates.email_verified = !!emailVerifiedViaToken;@@ -168,55 +169,57 @@ export class UserAccountService {try {updatedUser = await this.userAccountRepository.patchUpsert(user.id, updates, user.toRow());} catch (error) {- await this.profileService.rollbackAssetChanges(profileResult);- Logger.error({error, userId: user.id}, 'User update failed, rolled back asset uploads');+ Logger.error(+ {error, userId: user.id},+ 'User profile update failed with unknown commit status; retaining uploaded assets',+ );throw error;}- await this.contactChangeLogService.recordDiff({- oldUser: user,- newUser: updatedUser,- reason: 'user_requested',- actorUserId: user.id,- });- await this.profileService.commitAssetChanges(profileResult).catch((error) => {- Logger.error({error, userId: user.id}, 'Failed to commit asset changes after successful DB update');- });- await this.updatePropagator.dispatchUserUpdate(updatedUser);- if (hasPartialUserFieldsChanged(user, updatedUser)) {- await this.updatePropagator.updateUserCache(updatedUser);- }- const nameChanged =- user.username !== updatedUser.username ||- user.discriminator !== updatedUser.discriminator ||- user.globalName !== updatedUser.globalName;- if (nameChanged) {- void this.reindexGuildMembersForUser(updatedUser);- }- if (metadata.invalidateAuthSessions) {- await this.securityService.invalidateAndRecreateSessions({user, oldAuthSession, request});- await this.userAccountRepository.deleteAllPasswordResetTokens(user.id);+ const finalizationSteps: Array<() => Promise<unknown>> = [+ () =>+ this.contactChangeLogService.recordDiff({+ oldUser: user,+ newUser: updatedUser,+ reason: 'user_requested',+ actorUserId: user.id,+ }),+ async () => {+ try {+ await this.profileService.commitAssetChanges(profileResult);+ } catch (error) {+ Logger.error({error, userId: user.id}, 'Failed to commit asset changes after successful DB update');+ }+ },+ () => this.updatePropagator.dispatchUserUpdate(updatedUser),+ async () => {+ if (hasPartialUserFieldsChanged(user, updatedUser)) {+ await this.updatePropagator.updateUserCache(updatedUser);+ }+ },+ async () => {+ const nameChanged =+ user.username !== updatedUser.username ||+ user.discriminator !== updatedUser.discriminator ||+ user.globalName !== updatedUser.globalName;+ if (nameChanged) {+ void this.reindexGuildMembersForUser(updatedUser);+ }+ },+ ];+ if (securityResult.metadata.invalidateAuthSessions) {+ finalizationSteps.push(+ () => this.securityService.invalidateAndRecreateSessions({user, oldAuthSession, request}),+ () => this.userAccountRepository.deleteAllPasswordResetTokens(user.id),+ );}+ await runAllInOrder(finalizationSteps, 'Failed to finalize user update');return updatedUser;}private async reindexGuildMembersForUser(updatedUser: User): Promise<void> {try {const guildIds = await this.userAccountRepository.getUserGuildIds(updatedUser.id);- if (guildIds.length === 0) return;- const guilds = await this.guildRepository.listGuilds(guildIds);- const indexedGuilds = guilds.filter((guild) => guild.membersIndexedAt != null);- if (indexedGuilds.length === 0) return;- const members = await Promise.all(- indexedGuilds.map((guild) => this.guildRepository.getMember(guild.id, updatedUser.id)),- );- for (let i = 0; i < members.length; i++) {- const member = members[i];- if (member) {- const guild = indexedGuilds[i]!;- const includeDefault = guild.membersIndexedAt != null;- void this.searchIndexService.updateMember(member, updatedUser, {includeDefault});- }- }+ await this.searchIndexService.updateUserMembers(updatedUser, guildIds, this.guildRepository);} catch (error) {Logger.error({userId: updatedUser.id.toString(), error}, 'Failed to reindex guild members after user update');}diff --git a/fluxer_api/src/api/user/services/UserActivityBuffer.ts b/fluxer_api/src/api/user/services/UserActivityBuffer.tsindex 6c240ca3c..09c6dbdef 100644--- a/fluxer_api/src/api/user/services/UserActivityBuffer.ts+++ b/fluxer_api/src/api/user/services/UserActivityBuffer.ts@@ -60,6 +60,29 @@ function isStringRecord(value: unknown): value is Record<string, string> {return Object.values(value).every((entry) => typeof entry === 'string');}+async function flushActivityEntries<T>(+ entries: ReadonlyArray<T>,+ write: (entry: T) => Promise<unknown>,+ failureMessage: string,+): Promise<FlushStats> {+ let written = 0;+ let skipped = 0;+ for (let index = 0; index < entries.length; index += WRITE_CONCURRENCY) {+ const results = await Promise.allSettled(+ entries.slice(index, index + WRITE_CONCURRENCY).map(async (entry) => write(entry)),+ );+ for (const result of results) {+ if (result.status === 'fulfilled') {+ written += 1;+ } else {+ skipped += 1;+ Logger.warn({error: result.reason}, failureMessage);+ }+ }+ }+ return {drained: entries.length, written, skipped};+}+export class UserActivityBuffer {private readonly kv: IKVProvider;private readonly writer: ActivityWriter;@@ -130,81 +153,61 @@ export class UserActivityBuffer {private async drainAndFlushUsers(): Promise<FlushStats> {const drained = await this.atomicDrain();- if (drained.length === 0) {- return {drained: 0, written: 0, skipped: 0};- }- let written = 0;- let skipped = 0;- for (let i = 0; i < drained.length; i += WRITE_CONCURRENCY) {- const chunk = drained.slice(i, i + WRITE_CONCURRENCY);- const results = await Promise.allSettled(- chunk.map(({userId, entry}) =>- this.accounts.updateLastActiveAt({- userId,- lastActiveAt: new Date(entry.ts),- lastActiveIp: entry.ip ?? undefined,- }),- ),- );- for (const r of results) {- if (r.status === 'fulfilled') {- written += 1;- } else {- skipped += 1;- Logger.warn({error: r.reason}, 'Failed to flush a user activity entry');- }- }- }- return {drained: drained.length, written, skipped};+ return flushActivityEntries(+ drained,+ ({userId, entry}) =>+ this.accounts.updateLastActiveAt({+ userId,+ lastActiveAt: new Date(entry.ts),+ lastActiveIp: entry.ip ?? undefined,+ }),+ 'Failed to flush a user activity entry',+ );}private async drainAndFlushAuthSessions(): Promise<FlushStats> {const drained = await this.atomicDrainAuthSessions();- if (drained.length === 0) {- return {drained: 0, written: 0, skipped: 0};- }- let written = 0;- let skipped = 0;- for (let i = 0; i < drained.length; i += WRITE_CONCURRENCY) {- const chunk = drained.slice(i, i + WRITE_CONCURRENCY);- const results = await Promise.allSettled(- chunk.map(async ({sessionIdHash, entry}) => {- const approximateLastUsedAt = new Date(entry.ts);- await this.writer(- AuthSessions.patchByPk(- {session_id_hash: sessionIdHash},- {approx_last_used_at: Db.set(approximateLastUsedAt)},- ),- );- }),- );- for (const r of results) {- if (r.status === 'fulfilled') {- written += 1;- } else {- skipped += 1;- Logger.warn({error: r.reason}, 'Failed to flush an auth session activity entry');- }- }- }- return {drained: drained.length, written, skipped};+ return flushActivityEntries(+ drained,+ ({sessionIdHash, entry}) =>+ this.writer(+ AuthSessions.patchByPk({session_id_hash: sessionIdHash}, {approx_last_used_at: Db.set(new Date(entry.ts))}),+ ),+ 'Failed to flush an auth session activity entry',+ );}- private async atomicDrain(): Promise<Array<{userId: UserID; entry: PendingEntry}>> {- const result = await this.kv.multi().hgetall(PENDING_HASH_KEY).del(PENDING_HASH_KEY).exec();- if (!result || result.length === 0) {- return [];+ private async drainPendingHash(key: string): Promise<Array<[string, string]>> {+ const result = await this.kv.multi().hgetall(key).del(key).exec();+ const [readResult, deleteResult] = result;+ if (result.length !== 2 || !readResult || !deleteResult) {+ throw new Error(`Failed to drain activity hash ${key}: expected two transaction results`);+ }+ const [readError, pending] = readResult;+ const [deleteError, deleted] = deleteResult;+ if (readError) {+ throw new Error(`Failed to drain activity hash ${key}: HGETALL failed`, {cause: readError});+ }+ if (deleteError) {+ throw new Error(`Failed to drain activity hash ${key}: DEL failed`, {cause: deleteError});+ }+ if (!isStringRecord(pending)) {+ throw new Error(`Failed to drain activity hash ${key}: HGETALL returned an invalid hash`);}- const hgetallResult = result[0];- if (!hgetallResult || hgetallResult[0]) {- return [];+ if (deleted !== 0 && deleted !== 1) {+ throw new Error(`Failed to drain activity hash ${key}: DEL returned an invalid deletion count`);}- const raw = hgetallResult[1];- if (!isStringRecord(raw)) {- return [];+ const entries = Object.entries(pending);+ if (entries.length > 0 && deleted !== 1) {+ throw new Error(`Failed to drain activity hash ${key}: DEL did not remove the non-empty hash`);}+ return entries;+ }++ private async atomicDrain(): Promise<Array<{userId: UserID; entry: PendingEntry}>> {+ const entries = await this.drainPendingHash(PENDING_HASH_KEY);const out: Array<{userId: UserID; entry: PendingEntry}> = [];- for (const [userIdStr, json] of Object.entries(raw)) {+ for (const [userIdStr, json] of entries) {let userId: bigint;try {userId = BigInt(userIdStr);@@ -219,24 +222,9 @@ export class UserActivityBuffer {}private async atomicDrainAuthSessions(): Promise<Array<{sessionIdHash: Buffer; entry: PendingAuthSessionEntry}>> {- const result = await this.kv- .multi()- .hgetall(PENDING_AUTH_SESSION_HASH_KEY)- .del(PENDING_AUTH_SESSION_HASH_KEY)- .exec();- if (!result || result.length === 0) {- return [];- }- const hgetallResult = result[0];- if (!hgetallResult || hgetallResult[0]) {- return [];- }- const raw = hgetallResult[1];- if (!isStringRecord(raw)) {- return [];- }+ const entries = await this.drainPendingHash(PENDING_AUTH_SESSION_HASH_KEY);const out: Array<{sessionIdHash: Buffer; entry: PendingAuthSessionEntry}> = [];- for (const [encodedSessionIdHash, json] of Object.entries(raw)) {+ for (const [encodedSessionIdHash, json] of entries) {let sessionIdHash: Buffer;try {sessionIdHash = Buffer.from(encodedSessionIdHash, 'base64url');diff --git a/fluxer_api/src/api/user/services/UserContactChangeLogService.ts b/fluxer_api/src/api/user/services/UserContactChangeLogService.tsindex 7a6d1339a..188d56074 100644--- a/fluxer_api/src/api/user/services/UserContactChangeLogService.ts+++ b/fluxer_api/src/api/user/services/UserContactChangeLogService.ts@@ -3,10 +3,17 @@import type {UserID} from '../../BrandedTypes';import type {UserContactChangeLogRow} from '../../database/types/UserTypes';import type {User} from '../../models/User';+import {awaitAll} from '../../utils/ConcurrencyUtils';import type {UserContactChangeLogRepository} from '../repositories/UserContactChangeLogRepository';type ContactChangeReason = 'user_requested' | 'admin_action';+interface ContactChange {+ field: 'email' | 'has_verified_phone' | 'fluxer_tag';+ oldValue: string | null;+ newValue: string | null;+}+interface RecordDiffParams {oldUser: User | null;newUser: User;@@ -28,55 +35,37 @@ export class UserContactChangeLogService {async recordDiff(params: RecordDiffParams): Promise<void> {const {oldUser, newUser, reason, actorUserId, eventAt} = params;- const tasks: Array<Promise<void>> = [];- const oldEmail = oldUser?.email?.toLowerCase() ?? null;- const newEmail = newUser.email?.toLowerCase() ?? null;- if (oldEmail !== newEmail) {- tasks.push(- this.repo.insertLog({- userId: newUser.id,- field: 'email',- oldValue: oldEmail,- newValue: newEmail,- reason,- actorUserId,- eventAt,- }),- );- }- const oldHasVerifiedPhone = oldUser?.hasVerifiedPhone ?? false;- const newHasVerifiedPhone = newUser.hasVerifiedPhone;- if (oldHasVerifiedPhone !== newHasVerifiedPhone) {- tasks.push(- this.repo.insertLog({- userId: newUser.id,- field: 'has_verified_phone',- oldValue: String(oldHasVerifiedPhone),- newValue: String(newHasVerifiedPhone),- reason,- actorUserId,- eventAt,- }),- );- }- const oldTag = oldUser ? this.buildFluxerTag(oldUser) : null;- const newTag = this.buildFluxerTag(newUser);- if (oldTag !== newTag) {- tasks.push(- this.repo.insertLog({- userId: newUser.id,- field: 'fluxer_tag',- oldValue: oldTag,- newValue: newTag,- reason,- actorUserId,- eventAt,- }),- );- }- if (tasks.length > 0) {- await Promise.all(tasks);- }+ const changes: Array<ContactChange> = [+ {+ field: 'email',+ oldValue: oldUser?.email?.toLowerCase() ?? null,+ newValue: newUser.email?.toLowerCase() ?? null,+ },+ {+ field: 'has_verified_phone',+ oldValue: String(oldUser?.hasVerifiedPhone ?? false),+ newValue: String(newUser.hasVerifiedPhone),+ },+ {+ field: 'fluxer_tag',+ oldValue: this.buildFluxerTag(oldUser),+ newValue: this.buildFluxerTag(newUser),+ },+ ];+ await awaitAll(+ changes+ .filter(({oldValue, newValue}) => oldValue !== newValue)+ .map(async (change) =>+ this.repo.insertLog({+ userId: newUser.id,+ ...change,+ reason,+ actorUserId,+ eventAt,+ }),+ ),+ 'Failed to record user contact changes',+ );}async listLogs(params: ListLogsParams): Promise<Array<UserContactChangeLogRow>> {diff --git a/fluxer_api/src/api/user/services/UserDeletionEligibilityService.ts b/fluxer_api/src/api/user/services/UserDeletionEligibilityService.tsindex eecbc2cad..23c59dfb7 100644--- a/fluxer_api/src/api/user/services/UserDeletionEligibilityService.ts+++ b/fluxer_api/src/api/user/services/UserDeletionEligibilityService.ts@@ -6,12 +6,13 @@ import {ms, seconds} from 'itty-time';import type {UserID} from '../../BrandedTypes';import {Config} from '../../Config';import type {User} from '../../models/User';+import {getValidTimestamp, parseStoredTimestamp} from '../../utils/TimestampUtils';-export class UserDeletionEligibilityService {- private readonly INACTIVITY_WARNING_TTL_DAYS = 30;- private readonly INACTIVITY_WARNING_PREFIX = 'inactivity_warning_sent';+const INACTIVITY_WARNING_TTL_DAYS = 30;+const INACTIVITY_WARNING_PREFIX = 'inactivity_warning_sent';- constructor(private kvClient: IKVProvider) {}+export class UserDeletionEligibilityService {+ constructor(private readonly kvClient: IKVProvider) {}async isEligibleForInactivityDeletion(user: User): Promise<boolean> {if (user.isBot) {@@ -30,11 +31,8 @@ export class UserDeletionEligibilityService {return false;}const inactivityThresholdMs = this.getInactivityThresholdMs();- const timeSinceLastActiveMs = Date.now() - user.lastActiveAt.getTime();- if (timeSinceLastActiveMs < inactivityThresholdMs) {- return false;- }- return true;+ const lastActiveAt = getValidTimestamp(user.lastActiveAt, `Last activity timestamp for user ${user.id}`);+ return Date.now() - lastActiveAt >= inactivityThresholdMs;}async isEligibleForWarningEmail(user: User): Promise<boolean> {@@ -42,16 +40,12 @@ export class UserDeletionEligibilityService {if (!isEligibleForDeletion) {return false;}- const alreadySentWarning = await this.hasWarningSent(user.id);- if (alreadySentWarning) {- return false;- }- return true;+ return !(await this.hasWarningSent(user.id));}async markWarningSent(userId: UserID): Promise<void> {const key = this.getWarningKey(userId);- const ttlSeconds = seconds(`${this.INACTIVITY_WARNING_TTL_DAYS + 5} days`);+ const ttlSeconds = seconds(`${INACTIVITY_WARNING_TTL_DAYS + 5} days`);const timestamp = Date.now().toString();await this.kvClient.setex(key, ttlSeconds, timestamp);}@@ -64,12 +58,7 @@ export class UserDeletionEligibilityService {async getWarningSentTimestamp(userId: UserID): Promise<number | null> {const key = this.getWarningKey(userId);- const value = await this.kvClient.get(key);- if (!value) {- return null;- }- const timestamp = parseInt(value, 10);- return Number.isNaN(timestamp) ? null : timestamp;+ return parseStoredTimestamp(await this.kvClient.get(key), `Inactivity warning timestamp for user ${userId}`);}async hasWarningGracePeriodExpired(userId: UserID): Promise<boolean> {@@ -78,7 +67,7 @@ export class UserDeletionEligibilityService {return false;}const timeSinceWarningMs = Date.now() - timestamp;- const gracePeriodMs = this.INACTIVITY_WARNING_TTL_DAYS * ms('1 day');+ const gracePeriodMs = INACTIVITY_WARNING_TTL_DAYS * ms('1 day');return timeSinceWarningMs >= gracePeriodMs;}@@ -88,7 +77,7 @@ export class UserDeletionEligibilityService {}private getWarningKey(userId: UserID): string {- return `${this.INACTIVITY_WARNING_PREFIX}:${userId}`;+ return `${INACTIVITY_WARNING_PREFIX}:${userId}`;}private isAppStoreReviewer(user: User): boolean {diff --git a/fluxer_api/src/api/user/services/UserDeletionService.ts b/fluxer_api/src/api/user/services/UserDeletionService.tsindex c74a5729b..e41c0721d 100644--- a/fluxer_api/src/api/user/services/UserDeletionService.ts+++ b/fluxer_api/src/api/user/services/UserDeletionService.ts@@ -17,6 +17,7 @@ import {createMessageID, createUserID, type MessageID, type UserID} from '../../import {Config} from '../../Config';import {mapChannelToResponse} from '../../channel/ChannelMappers';import type {ChannelRepository} from '../../channel/ChannelRepository';+import type {IConnectionRepository} from '../../connection/IConnectionRepository';import type {FavoriteMemeRepository} from '../../favorite_meme/FavoriteMemeRepository';import type {GuildRepository} from '../../guild/repositories/GuildRepository';import type {IPurgeQueue} from '../../infrastructure/BunnyPurgeQueue';@@ -32,6 +33,7 @@ import type {ApplicationRepository} from '../../oauth/repositories/ApplicationReimport type {OAuth2TokenRepository} from '../../oauth/repositories/OAuth2TokenRepository';import type {WorkerTaskName} from '../../worker/WorkerLaneConfig';import type {UserRepository} from '../repositories/UserRepository';+import {isPendingDeletionBlocked} from './PendingDeletionCoordinator';const CHUNK_SIZE = 100;@@ -50,10 +52,12 @@ interface UserDeletionDependencies {stripe: Stripe | null;applicationRepository: ApplicationRepository;workerService: IWorkerService<WorkerTaskName>;+ connectionRepository: IConnectionRepository;}export async function processUserDeletion(userId: UserID,+ pendingDeletionAt: Date,deletionReasonCode: number,deps: UserDeletionDependencies,): Promise<void> {@@ -71,29 +75,35 @@ export async function processUserDeletion(stripe,applicationRepository,workerService,+ connectionRepository,} = deps;Logger.debug({userId, deletionReasonCode}, 'Starting user account deletion');- const user = await userRepository.findUnique(userId);- if (!user) {- Logger.warn({userId}, 'User not found, skipping deletion');+ const scheduledUser = await userRepository.findUnique(userId);+ if (+ !scheduledUser ||+ scheduledUser.pendingDeletionAt?.getTime() !== pendingDeletionAt.getTime() ||+ (!scheduledUser.deletionStartedAt &&+ (pendingDeletionAt.getTime() > Date.now() || isPendingDeletionBlocked(scheduledUser)))+ ) {+ Logger.info({userId, pendingDeletionAt}, 'Account deletion schedule is no longer eligible');return;}- if (user.stripeSubscriptionId && stripe) {+ if (scheduledUser.stripeSubscriptionId && stripe) {const MAX_RETRIES = 3;let lastError: unknown = null;for (let attempt = 0; attempt < MAX_RETRIES; attempt++) {try {Logger.debug(- {userId, subscriptionId: user.stripeSubscriptionId, attempt},+ {userId, subscriptionId: scheduledUser.stripeSubscriptionId, attempt},'Canceling active Stripe subscription',);- const canceledSubscription = await stripe.subscriptions.cancel(user.stripeSubscriptionId, {+ const canceledSubscription = await stripe.subscriptions.cancel(scheduledUser.stripeSubscriptionId, {invoice_now: false,prorate: false,});try {await getBillingRepository().subscriptions.upsertFromStripe(canceledSubscription, {- knownUserId: user.id,+ knownUserId: scheduledUser.id,snapshotCapturedAt: new Date(),});} catch (mirrorErr) {@@ -102,7 +112,10 @@ export async function processUserDeletion('Mirror upsert failed after Stripe write; reconciler will heal',);}- Logger.debug({userId, subscriptionId: user.stripeSubscriptionId}, 'Stripe subscription cancelled successfully');+ Logger.debug(+ {userId, subscriptionId: scheduledUser.stripeSubscriptionId},+ 'Stripe subscription cancelled successfully',+ );lastError = null;break;} catch (error) {@@ -112,7 +125,7 @@ export async function processUserDeletion({error,userId,- subscriptionId: user.stripeSubscriptionId,+ subscriptionId: scheduledUser.stripeSubscriptionId,attempt: attempt + 1,maxRetries: MAX_RETRIES,willRetry: !isLastAttempt,@@ -129,12 +142,18 @@ export async function processUserDeletion(}if (lastError) {const error = new Error(- `Failed to cancel Stripe subscription ${user.stripeSubscriptionId} for user ${userId} after ${MAX_RETRIES} attempts. User deletion halted to prevent billing issues.`,+ `Failed to cancel Stripe subscription ${scheduledUser.stripeSubscriptionId} for user ${userId} after ${MAX_RETRIES} attempts. User deletion halted to prevent billing issues.`,{cause: lastError},);throw error;}}+ const user = await userRepository.startDeletion(userId, pendingDeletionAt);+ if (!user) {+ Logger.info({userId, pendingDeletionAt}, 'Account deletion schedule is no longer eligible');+ return;+ }+ await connectionRepository.sealAndDeleteForUser(userId);const deletedUserId = createUserID(await snowflakeService.generate());Logger.debug({userId, deletedUserId}, 'Creating dedicated deleted user record');await userRepository.create({@@ -431,36 +450,33 @@ export async function processUserDeletion(await userRepository.deleteUserSecondaryIndices(userId);const userForAnonymization = await userRepository.findUniqueAssert(userId);Logger.debug({userId}, 'Anonymizing user record');- const anonymisedUser = await userRepository.patchUpsert(- userId,- {- username: DELETED_USER_USERNAME,- discriminator: DELETED_USER_DISCRIMINATOR,- global_name: DELETED_USER_GLOBAL_NAME,- email: null,- email_verified: false,- password_hash: null,- totp_secret: null,- avatar_hash: null,- banner_hash: null,- bio: null,- pronouns: null,- accent_color: null,- timezone: null,- timezone_privacy_flags: ProfileFieldPrivacyFlags.EVERYONE,- date_of_birth: null,- flags: UserFlags.DELETED,- premium_type: null,- premium_since: null,- premium_until: null,- premium_gift_extension_ends_at: null,- stripe_customer_id: null,- stripe_subscription_id: null,- pending_deletion_at: null,- authenticator_types: new Set(),- },- userForAnonymization.toRow(),- );+ const anonymisedUser = await userRepository.anonymizeForDeletion(userForAnonymization, {+ username: DELETED_USER_USERNAME,+ discriminator: DELETED_USER_DISCRIMINATOR,+ global_name: DELETED_USER_GLOBAL_NAME,+ email: null,+ email_verified: false,+ password_hash: null,+ totp_secret: null,+ avatar_hash: null,+ banner_hash: null,+ bio: null,+ pronouns: null,+ accent_color: null,+ timezone: null,+ timezone_privacy_flags: ProfileFieldPrivacyFlags.EVERYONE,+ date_of_birth: null,+ flags: UserFlags.DELETED,+ premium_type: null,+ premium_since: null,+ premium_until: null,+ premium_gift_extension_ends_at: null,+ stripe_customer_id: null,+ stripe_subscription_id: null,+ authenticator_types: new Set(),+ });+ await userRepository.removePendingDeletion(userId, pendingDeletionAt);await userCacheService.setUserPartialResponseFromUser(anonymisedUser);+ await userRepository.completeDeletion(anonymisedUser);Logger.debug({userId, deletionReasonCode}, 'User account anonymization completed successfully');}diff --git a/fluxer_api/src/api/user/tests/HarvestTestUtils.ts b/fluxer_api/src/api/user/tests/HarvestTestUtils.tsindex 4bbf140f8..a34d16486 100644--- a/fluxer_api/src/api/user/tests/HarvestTestUtils.ts+++ b/fluxer_api/src/api/user/tests/HarvestTestUtils.ts@@ -45,19 +45,29 @@ export async function expectHarvestDownloadFailsWithError(export async function markHarvestCompleted(userId: string, harvestId: string, expiresAt: Date): Promise<void> {const harvestRepository = new UserHarvestRepository();- const userIdTyped = createUserID(BigInt(userId));- const harvestIdTyped = BigInt(harvestId);- await harvestRepository.markAsCompleted(userIdTyped, harvestIdTyped, `test/${harvestId}.zip`, 1024n, expiresAt);+ const harvest = await claimHarvest(harvestRepository, userId, harvestId);+ await harvestRepository.markAsCompleted(harvest, `test/${harvestId}.zip`, 1024n, expiresAt);}export async function markHarvestFailed(userId: string, harvestId: string, errorMessage: string): Promise<void> {const harvestRepository = new UserHarvestRepository();- await harvestRepository.markAsFailed(createUserID(BigInt(userId)), BigInt(harvestId), errorMessage);+ const harvest = await claimHarvest(harvestRepository, userId, harvestId);+ await harvestRepository.markAsFailed(harvest, errorMessage);}export async function markHarvestStarted(userId: string, harvestId: string): Promise<void> {const harvestRepository = new UserHarvestRepository();- await harvestRepository.markAsStarted(createUserID(BigInt(userId)), BigInt(harvestId));+ await claimHarvest(harvestRepository, userId, harvestId);+}++async function claimHarvest(+ repository: UserHarvestRepository,+ userId: string,+ harvestId: string,+): Promise<UserHarvest> {+ const harvest = await repository.findByUserAndHarvestId(createUserID(BigInt(userId)), BigInt(harvestId));+ if (!harvest) throw new Error(`Harvest ${harvestId} for user ${userId} not found`);+ return repository.markAsStarted(harvest);}export async function findHarvest(userId: string, harvestId: string): Promise<UserHarvest | null> {diff --git a/fluxer_api/src/api/utils/AttachmentDecay.ts b/fluxer_api/src/api/utils/AttachmentDecay.tsindex ab4007f55..4d198523b 100644--- a/fluxer_api/src/api/utils/AttachmentDecay.ts+++ b/fluxer_api/src/api/utils/AttachmentDecay.ts@@ -1,6 +1,8 @@// SPDX-License-Identifier: AGPL-3.0-or-laterimport {ms} from 'itty-time';+import {requireIntegerInRange} from './IntegerOptions';+import {getValidTimestamp} from './TimestampUtils';export interface AttachmentDecayRules {minMb: number;@@ -47,6 +49,11 @@ function toMb(sizeBytes: bigint | number): number {return n / 1024 / 1024;}+function logRatio(value: number, base: number): number {+ const ratio = value / base;+ return Number.isFinite(ratio) ? Math.log(ratio) : Math.log(value) - Math.log(base);+}+export function computeDecay({sizeBytes, uploadedAt, rules}: AttachmentDecayInput): AttachmentDecayResult | null {const constants = {minMb: rules?.minMb ?? DEFAULT_DECAY_CONSTANTS.MIN_MB,@@ -66,18 +73,16 @@ export function computeDecay({sizeBytes, uploadedAt, rules}: AttachmentDecayInpulifetimeDays = constants.minDays;} else {const linearFrac = (sizeMB - constants.minMb) / (constants.maxMb - constants.minMb);- const logFrac = Math.log(sizeMB / constants.minMb) / Math.log(constants.maxMb / constants.minMb);+ const logFrac = logRatio(sizeMB, constants.minMb) / logRatio(constants.maxMb, constants.minMb);const blend = (1 - constants.curve) * linearFrac + constants.curve * logFrac;lifetimeDays = constants.maxDays - blend * (constants.maxDays - constants.minDays);}- const expiresAt = new Date(uploadedAt);+ const expiresAt = new Date(getValidTimestamp(uploadedAt, 'Attachment upload date'));expiresAt.setUTCDate(expiresAt.getUTCDate() + lifetimeDays);- const sizeTB = (typeof sizeBytes === 'bigint' ? Number(sizeBytes) : sizeBytes) / 1024 / 1024 / 1024 / 1024;- const lifetimeMonths = lifetimeDays / 30;- const cost = sizeTB * constants.pricePerTBPerMonth * lifetimeMonths;+ getValidTimestamp(expiresAt, 'Attachment decay expiry');return {expiresAt,- cost,+ cost: computeCost({sizeBytes, lifetimeDays, pricePerTBPerMonth: constants.pricePerTBPerMonth}),days: Math.round(lifetimeDays),};}@@ -99,14 +104,17 @@ export function computeCost({}export function getExpiryBucket(expiresAt: Date): number {- return Number(+ getValidTimestamp(expiresAt, 'Attachment expiry');+ const bucket = Number(`${expiresAt.getUTCFullYear()}${String(expiresAt.getUTCMonth() + 1).padStart(2, '0')}${String(expiresAt.getUTCDate()).padStart(2, '0')}`,);+ return requireIntegerInRange('Attachment expiry bucket', bucket, -2_147_483_648, 2_147_483_647);}export function extendExpiry(currentExpiry: Date | null, newlyComputed: Date): Date {+ const newTimestamp = getValidTimestamp(newlyComputed, 'Computed attachment expiry');if (!currentExpiry) return newlyComputed;- return currentExpiry > newlyComputed ? currentExpiry : newlyComputed;+ return getValidTimestamp(currentExpiry, 'Current attachment expiry') > newTimestamp ? currentExpiry : newlyComputed;}export function maybeRenewExpiry({@@ -124,16 +132,19 @@ export function maybeRenewExpiry({}): Date | null {if (!currentExpiry) return null;if (windowDays <= 0) return null;- const remainingMs = currentExpiry.getTime() - now.getTime();+ const currentTimestamp = getValidTimestamp(currentExpiry, 'Current attachment expiry');+ const nowTimestamp = getValidTimestamp(now, 'Attachment renewal time');+ const remainingMs = currentTimestamp - nowTimestamp;if (remainingMs > thresholdDays * MS_PER_DAY) {return null;}- const targetMs = now.getTime() + windowDays * MS_PER_DAY;- const cappedTargetMs = maxExpiry ? Math.min(maxExpiry.getTime(), targetMs) : targetMs;- if (cappedTargetMs <= currentExpiry.getTime()) {+ const targetMs = nowTimestamp + windowDays * MS_PER_DAY;+ const cappedTargetMs = maxExpiry+ ? Math.min(getValidTimestamp(maxExpiry, 'Maximum attachment expiry'), targetMs)+ : targetMs;+ if (cappedTargetMs <= currentTimestamp) {return null;}- const target = new Date(now);- target.setTime(cappedTargetMs);- return target;+ const target = new Date(cappedTargetMs);+ return getValidTimestamp(target, 'Renewed attachment expiry') > currentTimestamp ? target : null;}diff --git a/fluxer_api/src/api/utils/ConcurrencyUtils.ts b/fluxer_api/src/api/utils/ConcurrencyUtils.tsindex cfaadebc4..9b617e317 100644--- a/fluxer_api/src/api/utils/ConcurrencyUtils.ts+++ b/fluxer_api/src/api/utils/ConcurrencyUtils.ts@@ -2,6 +2,35 @@import assert from 'node:assert/strict';+export async function awaitAll(tasks: ReadonlyArray<Promise<unknown>>, failureMessage: string): Promise<void> {+ const results = await Promise.allSettled(tasks);+ const errors: Array<unknown> = [];+ for (const result of results) {+ if (result.status === 'rejected') errors.push(result.reason);+ }+ throwCompletionErrors(errors, failureMessage);+}++export async function runAllInOrder(+ steps: ReadonlyArray<() => Promise<unknown>>,+ failureMessage: string,+): Promise<void> {+ const errors: Array<unknown> = [];+ for (const step of steps) {+ try {+ await step();+ } catch (error) {+ errors.push(error);+ }+ }+ throwCompletionErrors(errors, failureMessage);+}++function throwCompletionErrors(errors: ReadonlyArray<unknown>, failureMessage: string): void {+ if (errors.length === 1) throw errors[0];+ if (errors.length > 1) throw new AggregateError(errors, failureMessage);+}+export async function mapWithConcurrency<T, TResult>(items: ReadonlyArray<T>,concurrency: number,@@ -10,13 +39,18 @@ export async function mapWithConcurrency<T, TResult>(assert(Number.isSafeInteger(concurrency) && concurrency > 0, 'Concurrency must be a positive safe integer');const results = new Array<TResult>(items.length);let nextIndex = 0;+ let failure: {error: unknown} | undefined;async function worker(): Promise<void> {- for (;;) {+ while (!failure && nextIndex < items.length) {const index = nextIndex++;- if (index >= items.length) return;- results[index] = await mapper(items[index]!, index);+ try {+ results[index] = await mapper(items[index]!, index);+ } catch (error) {+ failure ??= {error};+ }}}await Promise.all(Array.from({length: Math.min(concurrency, items.length)}, () => worker()));+ if (failure) throw failure.error;return results;}diff --git a/fluxer_api/src/api/utils/FetchUtils.ts b/fluxer_api/src/api/utils/FetchUtils.tsindex 22fd21bfe..862896271 100644--- a/fluxer_api/src/api/utils/FetchUtils.ts+++ b/fluxer_api/src/api/utils/FetchUtils.ts@@ -1,6 +1,8 @@// SPDX-License-Identifier: AGPL-3.0-or-laterimport {createHttpClient} from '@pkgs/http_client/src/HttpClient';+import {formatUrlForDiagnostics} from '@pkgs/http_client/src/HttpClientDiagnostics';+import {DEFAULT_MAX_REDIRECTS, normalizeMaxRedirects} from '@pkgs/http_client/src/HttpClientRequestInternals';import type {HttpClient,RequestOptions,@@ -9,13 +11,14 @@ import type {StreamResponse,} from '@pkgs/http_client/src/HttpClientTypes';import {createPublicInternetRequestUrlPolicy} from '@pkgs/http_client/src/PublicInternetRequestUrlPolicy';+import {Logger} from '../Logger';const requestUrlPolicy = createPublicInternetRequestUrlPolicy();const client: HttpClient = createHttpClient({userAgent: 'fluxer-api',requestUrlPolicy,});-const scopedClients = new Map<RequestUrlPolicy, Map<number, HttpClient>>();+const scopedClients = new WeakMap<RequestUrlPolicy, Map<number, HttpClient>>();interface SendRequestOptions {maxRedirects?: number;@@ -24,8 +27,8 @@ interface SendRequestOptions {function getHttpClientForRequest(options?: SendRequestOptions): HttpClient {const policy = options?.requestUrlPolicy ?? requestUrlPolicy;- const maxRedirects = options?.maxRedirects ?? 0;- if (policy === requestUrlPolicy && maxRedirects === 0) {+ const maxRedirects = normalizeMaxRedirects(options?.maxRedirects);+ if (policy === requestUrlPolicy && maxRedirects === DEFAULT_MAX_REDIRECTS) {return client;}let clientsForPolicy = scopedClients.get(policy);@@ -39,7 +42,7 @@ function getHttpClientForRequest(options?: SendRequestOptions): HttpClient {}const scopedClient = createHttpClient({userAgent: 'fluxer-api',- ...(maxRedirects > 0 ? {maxRedirects} : {}),+ maxRedirects,requestUrlPolicy: policy,});clientsForPolicy.set(maxRedirects, scopedClient);@@ -51,6 +54,12 @@ export async function sendRequest(opts: RequestOptions, options?: SendRequestOptreturn requestClient.sendRequest(opts);}+export function discardResponseBody(stream: ResponseStream, status: number): void {+ void stream?.cancel().catch(() => {+ Logger.warn({status}, 'Failed to cancel discarded HTTP response body');+ });+}+export class ResponseBodyTooLargeError extends Error {constructor(message: string,@@ -87,7 +96,7 @@ function createResponseBodyTooLargeError(actualBytes: number | null,): ResponseBodyTooLargeError {const description = options.description ?? 'Response body';- const source = options.url ? ` from ${options.url}` : '';+ const source = options.url ? ` from ${formatUrlForDiagnostics(options.url)}` : '';const actual = actualBytes == null ? 'unknown size' : `${actualBytes} bytes`;return new ResponseBodyTooLargeError(`${description}${source} exceeds the ${options.maxBytes}-byte limit (${actual})`,@@ -100,6 +109,13 @@ export async function streamToBufferWithLimit(stream: ResponseStream,options: ResponseBodyReadOptions,): Promise<Uint8Array> {+ if (!Number.isSafeInteger(options.maxBytes) || options.maxBytes < 0) {+ const error = new RangeError('maxBytes must be a nonnegative safe integer');+ void stream?.cancel(error).catch(() => {+ Logger.warn('Failed to cancel HTTP response body after invalid maxBytes');+ });+ throw error;+ }if (!stream) {return new Uint8Array(0);}diff --git a/fluxer_api/src/api/utils/IntegerOptions.ts b/fluxer_api/src/api/utils/IntegerOptions.tsnew file mode 100644index 000000000..1f6b8a92c--- /dev/null+++ b/fluxer_api/src/api/utils/IntegerOptions.ts@@ -0,0 +1,16 @@+export function readOptionalIntegerEnv(name: string): number | undefined {+ const raw = process.env[name]?.trim();+ if (raw === undefined || raw === '') return undefined;+ const value = Number(raw);+ if (!/^-?\d+$/.test(raw) || !Number.isSafeInteger(value)) {+ throw new Error(`${name} must be a safe integer`);+ }+ return value;+}++export function requireIntegerInRange(name: string, value: number, min: number, max: number): number {+ if (!Number.isSafeInteger(value) || value < min || value > max) {+ throw new RangeError(`${name} must be an integer between ${min} and ${max}`);+ }+ return value;+}diff --git a/fluxer_api/src/api/utils/IpUtils.ts b/fluxer_api/src/api/utils/IpUtils.tsindex bc32f5b92..7f9ad7118 100644--- a/fluxer_api/src/api/utils/IpUtils.ts+++ b/fluxer_api/src/api/utils/IpUtils.ts@@ -44,13 +44,14 @@ export async function getIpAddressReverse(if (cached !== null) return cached === '' ? null : cached;}let result: string | null = null;+ let timeout: NodeJS.Timeout | undefined;try {const reversePromise: Promise<Array<string>> = dns.promises.reverse(ip);let hostnames: Array<string>;if (options.timeoutMs !== undefined) {const timeoutMs = options.timeoutMs;const timeoutPromise = new Promise<Array<string>>((_, reject) => {- setTimeout(() => reject(new Error(`reverse DNS timeout after ${timeoutMs}ms`)), timeoutMs);+ timeout = setTimeout(() => reject(new Error(`reverse DNS timeout after ${timeoutMs}ms`)), timeoutMs);});hostnames = await Promise.race([reversePromise, timeoutPromise]);} else {@@ -59,6 +60,8 @@ export async function getIpAddressReverse(result = hostnames[0] ?? null;} catch {result = null;+ } finally {+ clearTimeout(timeout);}if (cacheService) {await cacheService.set(cacheKey, result ?? '', options.cacheTtlSeconds ?? REVERSE_DNS_CACHE_TTL_SECONDS);diff --git a/fluxer_api/src/api/utils/JsonBoundaryUtils.ts b/fluxer_api/src/api/utils/JsonBoundaryUtils.tsindex 0fb5084fe..94375ced5 100644--- a/fluxer_api/src/api/utils/JsonBoundaryUtils.ts+++ b/fluxer_api/src/api/utils/JsonBoundaryUtils.ts@@ -12,21 +12,11 @@ export function parseJsonUnknown(text: string): unknown {}export function parseJsonRecord(text: string): JsonRecord | null {- try {- const parsed = parseJsonUnknown(text);- return isJsonRecord(parsed) ? parsed : null;- } catch {- return null;- }+ return parseJsonWithGuard(text, isJsonRecord);}export function parseJsonArray(text: string): Array<unknown> | null {- try {- const parsed = parseJsonUnknown(text);- return Array.isArray(parsed) ? parsed : null;- } catch {- return null;- }+ return parseJsonWithGuard(text, Array.isArray);}export function parseJsonWithGuard<T>(text: string, guard: (value: unknown) => value is T): T | null {diff --git a/fluxer_api/src/api/utils/LosslessJsonParser.ts b/fluxer_api/src/api/utils/LosslessJsonParser.tsindex 8457d6f97..7a544f8a2 100644--- a/fluxer_api/src/api/utils/LosslessJsonParser.ts+++ b/fluxer_api/src/api/utils/LosslessJsonParser.ts@@ -7,19 +7,17 @@ function isDigit(char: string): boolean {return char >= '0' && char <= '9';}-function isValidJsonIntegerToken(token: string): boolean {- if (!/^-?\d+$/.test(token)) return false;- if (token === '0' || token === '-0') return true;+function isUnsafeIntegerToken(token: string): boolean {+ if (!/^-?(?:0|[1-9]\d*)$/.test(token)) return false;const digits = token[0] === '-' ? token.slice(1) : token;- return digits.length > 0 && digits[0] !== '0';+ return digits.length === MAX_SAFE_INTEGER_DECIMAL.length+ ? digits > MAX_SAFE_INTEGER_DECIMAL+ : digits.length > MAX_SAFE_INTEGER_DECIMAL.length;}-function isUnsafeIntegerToken(token: string): boolean {- const digits = token[0] === '-' ? token.slice(1) : token;- if (digits === '0') return false;- if (digits.length < MAX_SAFE_INTEGER_DECIMAL.length) return false;- if (digits.length > MAX_SAFE_INTEGER_DECIMAL.length) return true;- return digits > MAX_SAFE_INTEGER_DECIMAL;+function isFollowedByColon(jsonText: string, index: number): boolean {+ while (index < jsonText.length && ' \t\r\n'.includes(jsonText[index]!)) index++;+ return jsonText[index] === ':';}export function coerceUnsafeIntegersToStrings(jsonText: string): string {@@ -58,7 +56,7 @@ export function coerceUnsafeIntegersToStrings(jsonText: string): string {break;}const token = jsonText.slice(start, i);- if (isValidJsonIntegerToken(token) && isUnsafeIntegerToken(token)) {+ if (isUnsafeIntegerToken(token) && !isFollowedByColon(jsonText, i)) {if (!outputParts) {outputParts = [];}diff --git a/fluxer_api/src/api/utils/RandomUtils.ts b/fluxer_api/src/api/utils/RandomUtils.tsindex eaeef8511..5379b44cb 100644--- a/fluxer_api/src/api/utils/RandomUtils.ts+++ b/fluxer_api/src/api/utils/RandomUtils.ts@@ -1,12 +1,14 @@// SPDX-License-Identifier: AGPL-3.0-or-later+import assert from 'node:assert/strict';import crypto from 'node:crypto';const RANDOM_STRING_ALPHABET = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';const RANDOM_DIGIT_ALPHABET = '0123456789';-export function randomNumericCode(length: number): string {- const alphabetLength = RANDOM_DIGIT_ALPHABET.length;+function randomFromAlphabet(length: number, alphabet: string): string {+ assert(Number.isSafeInteger(length) && length >= 0, 'Random string length must be a nonnegative safe integer');+ const alphabetLength = alphabet.length;const rangeSize = 256 - (256 % alphabetLength);const randomBytes = new Uint8Array(length * 2);crypto.getRandomValues(randomBytes);@@ -19,28 +21,15 @@ export function randomNumericCode(length: number): string {}const randomByte = randomBytes[byteIndex++]!;if (randomByte >= rangeSize) continue;- result += RANDOM_DIGIT_ALPHABET.charAt(randomByte % alphabetLength);+ result += alphabet.charAt(randomByte % alphabetLength);}return result;}-export function randomString(length: number) {- const alphabetLength = RANDOM_STRING_ALPHABET.length;- const rangeSize = 256 - (256 % alphabetLength);- const randomBytes = new Uint8Array(length * 2);- crypto.getRandomValues(randomBytes);- let result = '';- let byteIndex = 0;- while (result.length < length) {- if (byteIndex >= randomBytes.length) {- crypto.getRandomValues(randomBytes);- byteIndex = 0;- }- const randomByte = randomBytes[byteIndex++];- if (randomByte >= rangeSize) {- continue;- }- result += RANDOM_STRING_ALPHABET.charAt(randomByte % alphabetLength);- }- return result;+export function randomNumericCode(length: number): string {+ return randomFromAlphabet(length, RANDOM_DIGIT_ALPHABET);+}++export function randomString(length: number): string {+ return randomFromAlphabet(length, RANDOM_STRING_ALPHABET);}diff --git a/fluxer_api/src/api/utils/RateLimitUtils.ts b/fluxer_api/src/api/utils/RateLimitUtils.tsnew file mode 100644index 000000000..64a391b6d--- /dev/null+++ b/fluxer_api/src/api/utils/RateLimitUtils.ts@@ -0,0 +1,14 @@+import {RateLimitError} from '@fluxer/errors/src/domains/core/RateLimitError';+import type {RateLimitResult} from '@pkgs/rate_limit/src/IRateLimitService';++export function getRetryAfterSeconds(result: RateLimitResult): number {+ return result.retryAfter ?? Math.max(0, Math.ceil((result.resetTime.getTime() - Date.now()) / 1000));+}++export function createRateLimitError(result: RateLimitResult): RateLimitError {+ return new RateLimitError({+ retryAfter: getRetryAfterSeconds(result),+ limit: result.limit,+ resetTime: result.resetTime,+ });+}diff --git a/fluxer_api/src/api/utils/RefreshSubscription.ts b/fluxer_api/src/api/utils/RefreshSubscription.tsnew file mode 100644index 000000000..b01e7baeb--- /dev/null+++ b/fluxer_api/src/api/utils/RefreshSubscription.ts@@ -0,0 +1,196 @@+import type {IKVProvider, IKVSubscription} from '@pkgs/kv_client/src/IKVProvider';++type RefreshTrigger = 'notification' | 'periodic';++interface RefreshSubscriptionOptions {+ name: string;+ channels: ReadonlyArray<string>;+ refresh: () => Promise<void>;+ onRefreshError: (error: unknown, trigger: RefreshTrigger) => void;+ shouldRefresh?: (channel: string, message: string) => boolean;+ drainInitialNotifications?: boolean;+ periodicIntervalMs?: () => number | null;+ closeMode?: 'disconnect' | 'quit';+}++export class RefreshSubscriptionUnavailableError extends Error {+ constructor(name: string, cause: unknown) {+ super(`Failed to subscribe ${name}`, {cause});+ this.name = 'RefreshSubscriptionUnavailableError';+ }+}++export class RefreshSubscription {+ private session: RefreshSubscriptionSession | null = null;++ constructor(private readonly options: RefreshSubscriptionOptions) {}++ get isActive(): boolean {+ return this.session?.isActive ?? false;+ }++ get isReady(): boolean {+ return this.session?.isReady ?? false;+ }++ async start(provider: IKVProvider | null): Promise<void> {+ const session = (this.session ??= new RefreshSubscriptionSession(this.options, provider));+ try {+ await session.start();+ } catch (error) {+ try {+ await session.stop();+ } catch (cleanupError) {+ throw new AggregateError([error, cleanupError], `Failed to initialize and close ${this.options.name}`);+ } finally {+ if (this.session === session) this.session = null;+ }+ if (error instanceof RefreshSubscriptionUnavailableError) throw error;+ throw new Error(`Failed to initialize ${this.options.name}`, {cause: error});+ }+ }++ async stop(): Promise<void> {+ const session = this.session;+ if (!session) return;+ try {+ await session.stop();+ } finally {+ if (this.session === session) this.session = null;+ }+ }+}++class RefreshSubscriptionSession {+ private readonly subscription: IKVSubscription | null;+ private phase: 'starting' | 'running' | 'stopping' | 'stopped' = 'starting';+ private startCompletion: Promise<void> | null = null;+ private stopCompletion: Promise<void> | null = null;+ private refreshTask: Promise<void> | null = null;+ private pendingRefresh: RefreshTrigger | null = null;+ private timer: NodeJS.Timeout | null = null;+ private readonly messageHandler = (channel: string, message: string): void => {+ if (!this.options.channels.includes(channel)) return;+ if (this.options.shouldRefresh && !this.options.shouldRefresh(channel, message)) return;+ this.requestRefresh('notification');+ };++ constructor(+ private readonly options: RefreshSubscriptionOptions,+ provider: IKVProvider | null,+ ) {+ try {+ this.subscription = provider?.duplicate() ?? null;+ } catch (error) {+ throw new RefreshSubscriptionUnavailableError(options.name, error);+ }+ }++ get isReady(): boolean {+ return this.phase === 'running';+ }++ get isActive(): boolean {+ return this.phase === 'starting' || this.phase === 'running';+ }++ start(): Promise<void> {+ this.assertActive();+ this.startCompletion ??= Promise.resolve().then(() => this.initialize());+ return this.startCompletion;+ }++ private async initialize(): Promise<void> {+ this.assertActive();+ if (this.subscription) {+ this.subscription.on('message', this.messageHandler);+ try {+ await this.subscription.connect();+ this.assertActive();+ for (const channel of this.options.channels) {+ await this.subscription.subscribe(channel);+ this.assertActive();+ }+ } catch (error) {+ this.assertActive();+ throw new RefreshSubscriptionUnavailableError(this.options.name, error);+ }+ }+ await this.options.refresh();+ this.assertActive();+ while (this.options.drainInitialNotifications && this.pendingRefresh !== null) {+ this.pendingRefresh = null;+ await this.options.refresh();+ this.assertActive();+ }+ this.phase = 'running';+ const intervalMs = this.options.periodicIntervalMs?.();+ if (intervalMs !== undefined && intervalMs !== null) {+ this.timer = setInterval(() => this.requestRefresh('periodic'), intervalMs);+ this.timer.unref();+ }+ this.startPendingRefresh();+ }++ private assertActive(): void {+ if (!this.isActive) {+ throw new Error(`${this.options.name} is stopping or stopped`);+ }+ }++ private requestRefresh(trigger: RefreshTrigger): void {+ if (this.phase === 'stopping' || this.phase === 'stopped') return;+ if (this.pendingRefresh !== 'notification') this.pendingRefresh = trigger;+ this.startPendingRefresh();+ }++ private startPendingRefresh(): void {+ if (!this.isReady || this.refreshTask || this.pendingRefresh === null) return;+ this.refreshTask = Promise.resolve()+ .then(() => this.refreshPending())+ .finally(() => {+ this.refreshTask = null;+ this.startPendingRefresh();+ });+ }++ private async refreshPending(): Promise<void> {+ while (this.isReady && this.pendingRefresh !== null) {+ const trigger = this.pendingRefresh;+ this.pendingRefresh = null;+ try {+ await this.options.refresh();+ } catch (error) {+ this.options.onRefreshError(error, trigger);+ }+ }+ }++ stop(): Promise<void> {+ if (this.stopCompletion) return this.stopCompletion;+ const wasStarting = this.phase === 'starting';+ this.phase = 'stopping';+ this.pendingRefresh = null;+ if (this.timer) clearInterval(this.timer);+ this.timer = null;+ this.subscription?.off('message', this.messageHandler);+ this.stopCompletion = this.close(wasStarting);+ return this.stopCompletion;+ }++ private async close(wasStarting: boolean): Promise<void> {+ try {+ const [closed] = await Promise.allSettled([+ Promise.resolve().then(() => {+ if (wasStarting || this.options.closeMode !== 'quit') return this.subscription?.disconnect();+ return this.subscription?.quit();+ }),+ this.startCompletion,+ this.refreshTask,+ ]);+ if (closed.status === 'rejected') throw closed.reason;+ } finally {+ this.phase = 'stopped';+ }+ }+}diff --git a/fluxer_api/src/api/utils/RequestPathUtils.ts b/fluxer_api/src/api/utils/RequestPathUtils.tsindex 4cb1767d8..37a86cf1f 100644--- a/fluxer_api/src/api/utils/RequestPathUtils.ts+++ b/fluxer_api/src/api/utils/RequestPathUtils.ts@@ -1,30 +1,14 @@// SPDX-License-Identifier: AGPL-3.0-or-later-const VERSION_PATTERN = /^\/v\d+/;+const VERSION_PATTERN = /^\/v\d+(?=\/|$)/;export function stripApiPrefix(path: string): string {if (path === '/api') {return '/';}- if (path.startsWith('/api/')) {- const afterApi = path.slice(4);- if (VERSION_PATTERN.test(afterApi)) {- const versionMatch = afterApi.match(VERSION_PATTERN);- if (versionMatch) {- const remaining = afterApi.slice(versionMatch[0].length);- return remaining === '' ? '/' : remaining;- }- }- return afterApi;- }- if (VERSION_PATTERN.test(path)) {- const versionMatch = path.match(VERSION_PATTERN);- if (versionMatch) {- const remaining = path.slice(versionMatch[0].length);- return remaining === '' ? '/' : remaining;- }- }- return path;+ const unprefixedPath = path.startsWith('/api/') ? path.slice(4) : path;+ const versionMatch = unprefixedPath.match(VERSION_PATTERN);+ return versionMatch ? unprefixedPath.slice(versionMatch[0].length) || '/' : unprefixedPath;}export function normalizeRequestPath(path: string): string {diff --git a/fluxer_api/src/api/utils/TimestampUtils.ts b/fluxer_api/src/api/utils/TimestampUtils.tsnew file mode 100644index 000000000..2a3b67d88--- /dev/null+++ b/fluxer_api/src/api/utils/TimestampUtils.ts@@ -0,0 +1,25 @@+const MAX_DATE_TIMESTAMP = 8640000000000000;++export function isValidTimestamp(timestamp: unknown): timestamp is number {+ return typeof timestamp === 'number' && Number.isInteger(timestamp) && Math.abs(timestamp) <= MAX_DATE_TIMESTAMP;+}++function validateTimestamp(timestamp: number, fieldName: string): number {+ if (!isValidTimestamp(timestamp)) {+ throw new RangeError(`${fieldName} must be an integer within the valid Date range`);+ }+ return timestamp;+}++export function getValidTimestamp(date: Date, fieldName: string): number {+ return validateTimestamp(date.getTime(), fieldName);+}++export function parseStoredTimestamp(value: string | null, fieldName: string): number | null {+ if (value === null) return null;+ const digits = value.startsWith('-') ? value.slice(1) : value;+ if (digits.length === 0 || /\D/.test(digits)) {+ throw new TypeError(`${fieldName} must be a decimal millisecond timestamp`);+ }+ return validateTimestamp(Number(value), fieldName);+}diff --git a/fluxer_api/src/api/utils/tests/ConcurrencyUtils.test.ts b/fluxer_api/src/api/utils/tests/ConcurrencyUtils.test.tsindex d82890dda..7028d1442 100644--- a/fluxer_api/src/api/utils/tests/ConcurrencyUtils.test.ts+++ b/fluxer_api/src/api/utils/tests/ConcurrencyUtils.test.ts@@ -91,16 +91,20 @@ describe('mapWithConcurrency', () => {expect(calls).toBe(0);});- it('propagates a mapper rejection without waiting for another in-flight item', async () => {+ it('waits for in-flight work before propagating a mapper rejection', async () => {const first = Promise.withResolvers<number>();const second = Promise.withResolvers<number>();const failure = new Error('Mapper failed');+ const completed: Array<unknown> = [];+ const secondCompleted = second.promise.then((value) => completed.push(value));const result = mapWithConcurrency([first.promise, second.promise], 2, (promise) => promise);- const rejected = expect(result).rejects.toBe(failure);+ const rejected = result.catch((error) => completed.push(error));first.reject(failure);- await rejected;+ await new Promise<void>((resolve) => setImmediate(resolve));second.resolve(2);- await second.promise;+ await Promise.all([rejected, secondCompleted]);+ expect(completed).toEqual([2, failure]);+ expect(completed[1]).toBe(failure);});it('rejects synchronous mapper failures without starting queued serial work', async () => {diff --git a/fluxer_api/src/api/voice/VoiceTopology.ts b/fluxer_api/src/api/voice/VoiceTopology.tsindex c56ace069..f404f0cb2 100644--- a/fluxer_api/src/api/voice/VoiceTopology.ts+++ b/fluxer_api/src/api/voice/VoiceTopology.ts@@ -1,7 +1,8 @@// SPDX-License-Identifier: AGPL-3.0-or-later-import type {IKVProvider, IKVSubscription} from '@pkgs/kv_client/src/IKVProvider';+import type {IKVProvider} from '@pkgs/kv_client/src/IKVProvider';import {Logger} from '../Logger';+import {RefreshSubscription, RefreshSubscriptionUnavailableError} from '../utils/RefreshSubscription';import type {IVoiceRepository} from './IVoiceRepository';import {VOICE_CONFIGURATION_CHANNEL} from './VoiceConstants';import type {VoiceRegionMetadata, VoiceRegionRecord, VoiceServerRecord} from './VoiceModel';@@ -9,15 +10,20 @@ import type {VoiceRegionMetadata, VoiceRegionRecord, VoiceServerRecord} from './type Subscriber = () => void;export class VoiceTopology {- private initialized = false;- private reloadPromise: Promise<void> | null = null;private regions: Map<string, VoiceRegionRecord> = new Map();private serversByRegion: Map<string, Array<VoiceServerRecord>> = new Map();private defaultRegionId: string | null = null;private subscribers: Set<Subscriber> = new Set();private serverRotationIndex: Map<string, number> = new Map();- private kvSubscription: IKVSubscription | null = null;- private messageHandler: ((channel: string) => void) | null = null;+ private stopped = false;+ private readonly refreshSubscription = new RefreshSubscription({+ name: 'VoiceTopology',+ channels: [VOICE_CONFIGURATION_CHANNEL],+ refresh: () => this.reload(),+ onRefreshError: (error) => {+ Logger.error({error}, 'Failed to reload voice topology from KV notification');+ },+ });constructor(private voiceRepository: IVoiceRepository,@@ -25,29 +31,13 @@ export class VoiceTopology {) {}async initialize(): Promise<void> {- if (this.initialized) {- return;+ try {+ await this.refreshSubscription.start(this.kvClient);+ } catch (error) {+ if (!(error instanceof RefreshSubscriptionUnavailableError)) throw error;+ Logger.error({error}, 'Voice configuration subscription unavailable, loading topology without live updates');+ await this.reload();}- await this.reload();- if (this.kvClient) {- try {- const subscription = this.kvClient.duplicate();- this.kvSubscription = subscription;- await subscription.connect();- await subscription.subscribe(VOICE_CONFIGURATION_CHANNEL);- this.messageHandler = (channel: string) => {- if (channel === VOICE_CONFIGURATION_CHANNEL) {- this.reload().catch((error) => {- Logger.error({error}, 'Failed to reload voice topology from KV notification');- });- }- };- subscription.on('message', this.messageHandler);- } catch (error) {- Logger.error({error}, 'Failed to subscribe to voice configuration channel');- }- }- this.initialized = true;}getDefaultRegion(): VoiceRegionRecord | null {@@ -114,59 +104,47 @@ export class VoiceTopology {}private async reload(): Promise<void> {- if (this.reloadPromise) {- return this.reloadPromise;- }- this.reloadPromise = (async () => {- const regionsWithServers = await this.voiceRepository.listRegionsWithServers();- const newRegions: Map<string, VoiceRegionRecord> = new Map();- const newServers: Map<string, Array<VoiceServerRecord>> = new Map();- for (const region of regionsWithServers) {- const sortedServers = region.servers.slice().sort((a, b) => a.serverId.localeCompare(b.serverId));- const regionRecord: VoiceRegionRecord = {- id: region.id,- name: region.name,- emoji: region.emoji,- latitude: region.latitude,- longitude: region.longitude,- isDefault: region.isDefault,+ const regionsWithServers = await this.voiceRepository.listRegionsWithServers();+ if (this.stopped) return;+ const newRegions: Map<string, VoiceRegionRecord> = new Map();+ const newServers: Map<string, Array<VoiceServerRecord>> = new Map();+ for (const region of regionsWithServers) {+ const sortedServers = region.servers.slice().sort((a, b) => a.serverId.localeCompare(b.serverId));+ const regionRecord: VoiceRegionRecord = {+ id: region.id,+ name: region.name,+ emoji: region.emoji,+ latitude: region.latitude,+ longitude: region.longitude,+ isDefault: region.isDefault,+ restrictions: {+ vipOnly: region.restrictions.vipOnly,+ requiredGuildFeatures: new Set(region.restrictions.requiredGuildFeatures),+ allowedGuildIds: new Set(region.restrictions.allowedGuildIds),+ allowedUserIds: new Set(region.restrictions.allowedUserIds),+ },+ createdAt: region.createdAt,+ updatedAt: region.updatedAt,+ };+ newRegions.set(region.id, regionRecord);+ newServers.set(+ region.id,+ sortedServers.map((server) => ({+ ...server,restrictions: {- vipOnly: region.restrictions.vipOnly,- requiredGuildFeatures: new Set(region.restrictions.requiredGuildFeatures),- allowedGuildIds: new Set(region.restrictions.allowedGuildIds),- allowedUserIds: new Set(region.restrictions.allowedUserIds),+ vipOnly: server.restrictions.vipOnly,+ requiredGuildFeatures: new Set(server.restrictions.requiredGuildFeatures),+ allowedGuildIds: new Set(server.restrictions.allowedGuildIds),+ allowedUserIds: new Set(server.restrictions.allowedUserIds),},- createdAt: region.createdAt,- updatedAt: region.updatedAt,- };- newRegions.set(region.id, regionRecord);- newServers.set(- region.id,- sortedServers.map((server) => ({- ...server,- restrictions: {- vipOnly: server.restrictions.vipOnly,- requiredGuildFeatures: new Set(server.restrictions.requiredGuildFeatures),- allowedGuildIds: new Set(server.restrictions.allowedGuildIds),- allowedUserIds: new Set(server.restrictions.allowedUserIds),- },- })),- );- }- this.regions = newRegions;- this.serversByRegion = newServers;- this.recalculateServerRotation();- this.recalculateDefaultRegion();- this.notifySubscribers();- })()- .catch((error) => {- Logger.error({error}, 'Failed to reload voice topology');- throw error;- })- .finally(() => {- this.reloadPromise = null;- });- return this.reloadPromise;+ })),+ );+ }+ this.regions = newRegions;+ this.serversByRegion = newServers;+ this.recalculateServerRotation();+ this.recalculateDefaultRegion();+ this.notifySubscribers();}private recalculateServerRotation(): void {@@ -206,14 +184,8 @@ export class VoiceTopology {}}- shutdown(): void {- if (this.kvSubscription && this.messageHandler) {- this.kvSubscription.off('message', this.messageHandler);- }- if (this.kvSubscription) {- this.kvSubscription.disconnect();- this.kvSubscription = null;- }- this.messageHandler = null;+ shutdown(): Promise<void> {+ this.stopped = true;+ return this.refreshSubscription.stop();}}diff --git a/fluxer_api/src/api/worker/CronScheduler.ts b/fluxer_api/src/api/worker/CronScheduler.tsindex d47b1d924..eed569faa 100644--- a/fluxer_api/src/api/worker/CronScheduler.ts+++ b/fluxer_api/src/api/worker/CronScheduler.ts@@ -9,80 +9,85 @@ import type {WorkerService} from './WorkerService';const MAX_CATCHUP_SECONDS = 60;+interface CronSchedule {+ seconds: ReadonlySet<number>;+ minutes: ReadonlySet<number>;+ hours: ReadonlySet<number>;+ daysOfMonth: ReadonlySet<number>;+ months: ReadonlySet<number>;+ daysOfWeek: ReadonlySet<number>;+}+interface CronDefinition {id: string;taskType: WorkerTaskName;payload: WorkerJobPayload;- cronExpression: string;+ schedule: CronSchedule;ledger: boolean;lastFired: number;}-function parseCronField(field: string, min: number, max: number): Array<number> {- if (field === '*') {- return [];- }- const values: Array<number> = [];+function parseCronField(field: string, name: string, min: number, max: number): ReadonlySet<number> {+ const values = new Set<number>();for (const part of field.split(',')) {- const stepMatch = part.match(/^(.+)\/(\d+)$/);- if (stepMatch) {- const [, range, stepStr] = stepMatch;- const step = Number.parseInt(stepStr!, 10);- let start = min;- let end = max;- if (range !== '*') {- const rangeParts = range!.split('-');- start = Number.parseInt(rangeParts[0]!, 10);- if (rangeParts.length > 1) {- end = Number.parseInt(rangeParts[1]!, 10);- }- }- for (let i = start; i <= end; i += step) {- values.push(i);- }- } else if (part.includes('-')) {- const [startStr, endStr] = part.split('-');- const start = Number.parseInt(startStr!, 10);- const end = Number.parseInt(endStr!, 10);- for (let i = start; i <= end; i++) {- values.push(i);- }- } else {- values.push(Number.parseInt(part, 10));+ const match = /^(\*|\d+)(?:-(\d+))?(?:\/(\d+))?$/.exec(part);+ if (!match) {+ throw new Error(`Invalid cron ${name} field ${JSON.stringify(field)}: malformed term ${JSON.stringify(part)}`);+ }+ const [, startText, endText, stepText] = match;+ const wildcard = startText === '*';+ if (wildcard && endText !== undefined) {+ throw new Error(`Invalid cron ${name} field ${JSON.stringify(field)}: a range must start with a number`);+ }+ const start = wildcard ? min : Number(startText);+ const defaultEnd = wildcard || stepText !== undefined ? max : start;+ const end = endText === undefined ? defaultEnd : Number(endText);+ const step = stepText === undefined ? 1 : Number(stepText);+ if (start < min || start > max || end < min || end > max) {+ throw new Error(`Invalid cron ${name} field ${JSON.stringify(field)}: values must be between ${min} and ${max}`);+ }+ if (start > end) {+ throw new Error(`Invalid cron ${name} field ${JSON.stringify(field)}: range start exceeds its end`);+ }+ if (!Number.isSafeInteger(step) || step < 1) {+ throw new Error(`Invalid cron ${name} field ${JSON.stringify(field)}: step must be a positive safe integer`);+ }+ for (let value = start; value <= end; value += step) {+ values.add(value);}}return values;}-function matchesCronExpression(expression: string, date: Date): boolean {- const parts = expression.trim().split(/\s+/);- if (parts.length !== 6) {- return false;- }- const [secField, minField, hourField, domField, monField, dowField] = parts;- const second = date.getSeconds();- const minute = date.getMinutes();- const hour = date.getHours();- const dayOfMonth = date.getDate();- const month = date.getMonth() + 1;- const dayOfWeek = date.getDay();- function matches(field: string, value: number, min: number, max: number): boolean {- const allowed = parseCronField(field, min, max);- return allowed.length === 0 || allowed.includes(value);+function compileCronSchedule(expression: string): CronSchedule {+ const fields = expression.trim().split(/\s+/);+ if (fields.length !== 6) {+ throw new Error(`Cron expression must contain 6 fields, received ${fields.length}: ${JSON.stringify(expression)}`);}+ return {+ seconds: parseCronField(fields[0]!, 'seconds', 0, 59),+ minutes: parseCronField(fields[1]!, 'minutes', 0, 59),+ hours: parseCronField(fields[2]!, 'hours', 0, 23),+ daysOfMonth: parseCronField(fields[3]!, 'day of month', 1, 31),+ months: parseCronField(fields[4]!, 'month', 1, 12),+ daysOfWeek: parseCronField(fields[5]!, 'day of week', 0, 6),+ };+}++function matchesCronSchedule(schedule: CronSchedule, date: Date): boolean {return (- matches(secField!, second, 0, 59) &&- matches(minField!, minute, 0, 59) &&- matches(hourField!, hour, 0, 23) &&- matches(domField!, dayOfMonth, 1, 31) &&- matches(monField!, month, 1, 12) &&- matches(dowField!, dayOfWeek, 0, 6)+ schedule.seconds.has(date.getSeconds()) &&+ schedule.minutes.has(date.getMinutes()) &&+ schedule.hours.has(date.getHours()) &&+ schedule.daysOfMonth.has(date.getDate()) &&+ schedule.months.has(date.getMonth() + 1) &&+ schedule.daysOfWeek.has(date.getDay()));}-function findLatestDueSecond(expression: string, fromSeconds: number, toSeconds: number): number | null {+function findLatestDueSecond(schedule: CronSchedule, fromSeconds: number, toSeconds: number): number | null {for (let second = toSeconds; second >= fromSeconds; second--) {- if (matchesCronExpression(expression, new Date(second * 1000))) {+ if (matchesCronSchedule(schedule, new Date(second * 1000))) {return second;}}@@ -96,6 +101,8 @@ export class CronScheduler {private readonly heartbeat: WorkerHeartbeat | null;private readonly definitions: Map<string, CronDefinition> = new Map();private intervalId: NodeJS.Timeout | null = null;+ private tickPromise: Promise<void> | null = null;+ private stopPromise: Promise<void> | null = null;private lastTickSecond: number | null = null;private heartbeatSignal: WorkerHeartbeatSignal | null = null;@@ -122,33 +129,44 @@ export class CronScheduler {id,taskType,payload,- cronExpression,+ schedule: compileCronSchedule(cronExpression),ledger: options.ledger,lastFired: 0,});}start(): void {+ if (this.stopPromise) throw new Error('Cron scheduler is stopping');if (this.intervalId !== null) {return;}this.heartbeatSignal = this.heartbeat?.register('cron', WORKER_CRON_STALE_AFTER_MS) ?? null;this.intervalId = setInterval(() => {- this.tick().catch((error) => {- this.logger.error({err: error}, 'Cron scheduler tick failed');- });+ if (this.intervalId === null || this.tickPromise !== null) return;+ this.tickPromise = this.tick()+ .catch((error) => {+ this.logger.error({err: error}, 'Cron scheduler tick failed');+ })+ .finally(() => {+ this.tickPromise = null;+ });}, 1000);this.logger.info(`Cron scheduler started with ${this.definitions.size} definitions`);}- stop(): void {+ stop(): Promise<void> {+ if (this.stopPromise) return this.stopPromise;if (this.intervalId !== null) {clearInterval(this.intervalId);this.intervalId = null;}this.heartbeatSignal?.release();this.heartbeatSignal = null;- this.lastTickSecond = null;+ this.stopPromise = (this.tickPromise ?? Promise.resolve()).finally(() => {+ this.lastTickSecond = null;+ this.stopPromise = null;+ });+ return this.stopPromise;}private async tick(): Promise<void> {@@ -168,7 +186,8 @@ export class CronScheduler {? nowSeconds: Math.max(previousTickSecond + 1, nowSeconds - MAX_CATCHUP_SECONDS);for (const def of this.definitions.values()) {- const dueSecond = findLatestDueSecond(def.cronExpression, fromSeconds, nowSeconds);+ if (this.intervalId === null) return;+ const dueSecond = findLatestDueSecond(def.schedule, fromSeconds, nowSeconds);if (dueSecond === null || def.lastFired === dueSecond) {continue;}diff --git a/fluxer_api/src/api/worker/JetStreamWorkerQueue.ts b/fluxer_api/src/api/worker/JetStreamWorkerQueue.tsindex f08c0729b..b483ac438 100644--- a/fluxer_api/src/api/worker/JetStreamWorkerQueue.ts+++ b/fluxer_api/src/api/worker/JetStreamWorkerQueue.ts@@ -5,10 +5,14 @@ import type {JetStreamConnectionManager} from '@pkgs/nats/src/JetStreamConnectioimport type {WorkerJobPayload} from '@pkgs/worker/src/contracts/WorkerTypes';import {AckPolicy,+ type ConsumerInfo,+ type ConsumerUpdateConfig,+ DeliverPolicy,DiscardPolicy,type JetStreamManager,NatsError,nanos,+ ReplayPolicy,RetentionPolicy,StorageType,type StreamConfig,@@ -30,17 +34,65 @@ const STREAM_MIN_BYTES = 64 * 1024 * 1024;const STREAM_MAX_MSGS_PER_SUBJECT = 250_000;const DLQ_MAX_BYTES = 64 * 1024 * 1024;const DLQ_MIN_BYTES = 8 * 1024 * 1024;+const DLQ_PUBLISH_TIMEOUT_MS = 5000;+const DUPLICATE_WINDOW_MS = 2 * 60 * 1000;const STREAM_FULL_ERR_CODES = new Set([10023, 10077]);const STREAM_NO_STORAGE_ERR_CODE = 10047;const STREAM_NAME_IN_USE_ERR_CODE = 10058;+const STREAM_NOT_FOUND_ERR_CODE = 10059;+const CONSUMER_NOT_FOUND_ERR_CODE = 10014;+const CONSUMER_EXISTS_ERR_CODES = new Set([10013, 10148]);-const STREAM_LIMITS = {- max_msgs: STREAM_MAX_MSGS,- max_bytes: STREAM_MAX_BYTES,- max_msgs_per_subject: STREAM_MAX_MSGS_PER_SUBJECT,+interface WorkerStreamDefinition {+ name: string;+ subject: string;+ retention: RetentionPolicy;+ maxAgeMs: number;+ minBytes: number;+ maxMessages: number;+ maxMessagesPerSubject: number;+ discard: DiscardPolicy;+ discardNewPerSubject: boolean;+}++interface WorkerStreamConfiguration extends StreamConfig {+ persist_mode?: string;+ allow_msg_ttl?: boolean;+ allow_msg_counter?: boolean;+}++const JOBS_STREAM: WorkerStreamDefinition = {+ name: STREAM_NAME,+ subject: `${SUBJECT_PREFIX}>`,+ retention: RetentionPolicy.Workqueue,+ maxAgeMs: MAX_AGE_MS,+ minBytes: STREAM_MIN_BYTES,+ maxMessages: STREAM_MAX_MSGS,+ maxMessagesPerSubject: STREAM_MAX_MSGS_PER_SUBJECT,discard: DiscardPolicy.New,- discard_new_per_subject: true,-} satisfies Partial<StreamConfig>;+ discardNewPerSubject: true,+};++const DEAD_LETTER_STREAM: WorkerStreamDefinition = {+ name: DLQ_STREAM_NAME,+ subject: `${DLQ_SUBJECT_PREFIX}>`,+ retention: RetentionPolicy.Limits,+ maxAgeMs: DLQ_MAX_AGE_MS,+ minBytes: DLQ_MIN_BYTES,+ maxMessages: -1,+ maxMessagesPerSubject: -1,+ discard: DiscardPolicy.Old,+ discardNewPerSubject: false,+};++export interface WorkerDeadLetterMetadata {+ messageId: string;+ originalSeq: number;+ errorMessage: string;+ deliveryCount: number;+ lane: string;+ runAt?: string;+}function jsErrorCode(error: unknown): number | null {if (!(error instanceof NatsError)) {@@ -65,33 +117,135 @@ export class JetStreamWorkerQueue {private streamReady = false;private dlqStreamReady = false;private consumersReady = false;+ private streamSetup: Promise<void> | null = null;+ private dlqStreamSetup: Promise<void> | null = null;constructor(connectionManager: JetStreamConnectionManager) {this.connectionManager = connectionManager;}async ensureStream(): Promise<void> {- if (this.streamReady) {- return;- }+ if (this.streamReady) return;+ this.streamSetup ??= this.initializeStream().finally(() => {+ this.streamSetup = null;+ });+ await this.streamSetup;+ }++ private async initializeStream(): Promise<void> {const jsm = await this.connectionManager.getJetStreamManager();- const existingConfig = await this.readStreamConfig(jsm, STREAM_NAME);+ const existingConfig = await this.readStreamConfig(jsm, JOBS_STREAM);if (existingConfig === null) {await this.addStream(jsm);- } else if (!this.hasStreamLimits(existingConfig)) {+ } else {await this.applyStreamLimits(jsm, existingConfig);}this.streamReady = true;}- private async readStreamConfig(jsm: JetStreamManager, name: string): Promise<StreamConfig | null> {+ private async oversizedSubjects(jsm: JetStreamManager): Promise<Array<[string, number]> | null> {try {- return (await jsm.streams.info(name)).config;- } catch {+ const info = await jsm.streams.info(STREAM_NAME, {subjects_filter: JOBS_STREAM.subject});+ const subjects = info.state.subjects;+ if (subjects === undefined) return [];+ return Object.entries(subjects).filter(([, count]) => count > STREAM_MAX_MSGS_PER_SUBJECT);+ } catch (error) {+ Logger.warn({err: error, stream: STREAM_NAME}, 'Could not read jobs stream subject counts, leaving limits alone');return null;}}+ private async applyStreamLimits(jsm: JetStreamManager, existing: WorkerStreamConfiguration): Promise<void> {+ const unmanaged = this.unmanagedStreamSettings(existing, JOBS_STREAM);+ if (unmanaged.length > 0) {+ Logger.warn(+ {stream: STREAM_NAME, unmanaged},+ 'Jobs stream has settings this service does not own, change them explicitly with publishers and workers stopped',+ );+ }+ const drifted = this.diffStreamLimits(existing, JOBS_STREAM);+ if (drifted.length === 0) return;+ const oversized = await this.oversizedSubjects(jsm);+ if (oversized === null) return;+ if (oversized.length > 0) {+ Logger.error(+ {stream: STREAM_NAME, drifted, oversized, limit: STREAM_MAX_MSGS_PER_SUBJECT},+ 'Jobs stream limits are out of date but tightening them would drop queued jobs, drain these subjects then migrate the stream explicitly',+ );+ return;+ }+ const startBytes = existing.max_bytes > 0 ? existing.max_bytes : STREAM_MAX_BYTES;+ try {+ const maxBytes = await this.fitToStorageBudget(startBytes, STREAM_MIN_BYTES, (bytes) =>+ jsm.streams.update(STREAM_NAME, {+ max_msgs: JOBS_STREAM.maxMessages,+ max_bytes: bytes,+ max_msgs_per_subject: JOBS_STREAM.maxMessagesPerSubject,+ discard: JOBS_STREAM.discard,+ discard_new_per_subject: JOBS_STREAM.discardNewPerSubject,+ }),+ );+ Logger.info({stream: STREAM_NAME, drifted, max_bytes: maxBytes}, 'Applied jobs stream limits');+ } catch (error) {+ Logger.error(+ {err: error, stream: STREAM_NAME, drifted},+ 'Could not apply jobs stream limits, continuing with the limits the stream already has',+ );+ }+ }++ private async readStreamConfig(jsm: JetStreamManager, stream: WorkerStreamDefinition): Promise<StreamConfig | null> {+ try {+ const {config} = await jsm.streams.info(stream.name);+ this.assertStreamIdentity(config, stream);+ return config;+ } catch (error) {+ if (jsErrorCode(error) === STREAM_NOT_FOUND_ERR_CODE) return null;+ throw error;+ }+ }++ private assertStreamIdentity(config: WorkerStreamConfiguration, stream: WorkerStreamDefinition): void {+ const incompatible: Array<string> = [];+ if (config.name !== stream.name) incompatible.push('name');+ if (config.subjects?.length !== 1 || config.subjects[0] !== stream.subject) incompatible.push('subjects');+ if (config.retention !== stream.retention) incompatible.push('retention');+ if (config.storage !== StorageType.File) incompatible.push('storage');+ for (const field of ['sealed', 'no_ack', 'mirror', 'republish', 'subject_transform'] as const) {+ if (config[field]) incompatible.push(field);+ }+ if (config.sources?.length) incompatible.push('sources');+ if (incompatible.length > 0) {+ throw new Error(+ `Worker stream ${stream.name} has incompatible ${incompatible.join(', ')} configuration, stop publishers and workers and migrate it explicitly before startup`,+ );+ }+ }++ private diffStreamLimits(config: WorkerStreamConfiguration, stream: WorkerStreamDefinition): Array<string> {+ const drifted: Array<string> = [];+ if (!Number.isSafeInteger(config.max_bytes) || config.max_bytes < stream.minBytes) drifted.push('max_bytes');+ if (config.max_msgs !== stream.maxMessages) drifted.push('max_msgs');+ if (config.max_msgs_per_subject !== stream.maxMessagesPerSubject) drifted.push('max_msgs_per_subject');+ if (config.discard !== stream.discard) drifted.push('discard');+ if ((config.discard_new_per_subject ?? false) !== stream.discardNewPerSubject) {+ drifted.push('discard_new_per_subject');+ }+ return drifted;+ }++ private unmanagedStreamSettings(config: WorkerStreamConfiguration, stream: WorkerStreamDefinition): Array<string> {+ const unmanaged: Array<string> = [];+ if (config.max_age !== nanos(stream.maxAgeMs)) unmanaged.push('max_age');+ if (config.duplicate_window !== nanos(DUPLICATE_WINDOW_MS)) unmanaged.push('duplicate_window');+ if (config.max_msg_size !== undefined && config.max_msg_size !== -1) unmanaged.push('max_msg_size');+ if (config.persist_mode !== undefined && config.persist_mode !== 'default') unmanaged.push('persist_mode');+ for (const field of ['allow_rollup_hdrs', 'allow_msg_ttl', 'allow_msg_counter'] as const) {+ if (config[field]) unmanaged.push(field);+ }+ return unmanaged;+ }+private async fitToStorageBudget(startBytes: number,minBytes: number,@@ -111,36 +265,48 @@ export class JetStreamWorkerQueue {}}- private async adoptConcurrentStream(jsm: JetStreamManager, name: string, error: unknown): Promise<boolean> {+ private async adoptConcurrentStream(+ jsm: JetStreamManager,+ stream: WorkerStreamDefinition,+ error: unknown,+ ): Promise<StreamConfig | null> {if (jsErrorCode(error) !== STREAM_NAME_IN_USE_ERR_CODE) {- return false;+ return null;}- const config = await this.readStreamConfig(jsm, name);- if (config === null) {- return false;+ const config = await this.readStreamConfig(jsm, stream);+ if (config !== null) {+ Logger.info({stream: stream.name, max_bytes: config.max_bytes}, 'Stream was created concurrently, adopting it');}- Logger.info({stream: name, max_bytes: config.max_bytes}, 'Stream was created concurrently, adopting it');- return true;+ return config;+ }++ private async createStream(jsm: JetStreamManager, stream: WorkerStreamDefinition, maxBytes: number): Promise<void> {+ const {config} = await jsm.streams.add({+ name: stream.name,+ subjects: [stream.subject],+ retention: stream.retention,+ storage: StorageType.File,+ max_age: nanos(stream.maxAgeMs),+ duplicate_window: nanos(DUPLICATE_WINDOW_MS),+ num_replicas: 1,+ max_msgs: stream.maxMessages,+ max_bytes: maxBytes,+ max_msgs_per_subject: stream.maxMessagesPerSubject,+ discard: stream.discard,+ discard_new_per_subject: stream.discardNewPerSubject,+ });+ this.assertStreamIdentity(config, stream);}private async addStream(jsm: JetStreamManager): Promise<void> {let maxBytes: number;try {maxBytes = await this.fitToStorageBudget(STREAM_MAX_BYTES, STREAM_MIN_BYTES, (bytes) =>- jsm.streams.add({- name: STREAM_NAME,- subjects: [`${SUBJECT_PREFIX}>`],- retention: RetentionPolicy.Workqueue,- storage: StorageType.File,- max_age: nanos(MAX_AGE_MS),- duplicate_window: nanos(2 * 60 * 1000),- num_replicas: 1,- ...STREAM_LIMITS,- max_bytes: bytes,- }),+ this.createStream(jsm, JOBS_STREAM, bytes),);} catch (error) {- if (await this.adoptConcurrentStream(jsm, STREAM_NAME, error)) {+ const adopted = await this.adoptConcurrentStream(jsm, JOBS_STREAM, error);+ if (adopted !== null) {return;}if (jsErrorCode(error) === STREAM_NO_STORAGE_ERR_CODE) {@@ -159,41 +325,17 @@ export class JetStreamWorkerQueue {}}- private hasStreamLimits(config: StreamConfig): boolean {- return (- config.max_msgs === STREAM_MAX_MSGS &&- config.max_bytes > 0 &&- config.max_msgs_per_subject === STREAM_MAX_MSGS_PER_SUBJECT &&- config.discard === DiscardPolicy.New &&- config.discard_new_per_subject- );- }-- private async applyStreamLimits(jsm: JetStreamManager, existingConfig: StreamConfig): Promise<void> {- const startBytes = existingConfig.max_bytes > 0 ? existingConfig.max_bytes : STREAM_MAX_BYTES;- try {- const maxBytes = await this.fitToStorageBudget(startBytes, STREAM_MIN_BYTES, (bytes) =>- jsm.streams.update(STREAM_NAME, {...STREAM_LIMITS, max_bytes: bytes}),- );- Logger.info({stream: STREAM_NAME, ...STREAM_LIMITS, max_bytes: maxBytes}, 'Applied jobs stream limits');- } catch (error) {- if (jsErrorCode(error) !== STREAM_NO_STORAGE_ERR_CODE) {- Logger.error({err: error, stream: STREAM_NAME}, 'Failed to apply jobs stream limits');- return;- }- Logger.warn(- {err: error, stream: STREAM_NAME, max_bytes: existingConfig.max_bytes},- 'JetStream has no room to bound the jobs stream, it keeps the limits it already has',- );- }+ async ensureDlqStream(): Promise<void> {+ if (this.dlqStreamReady) return;+ this.dlqStreamSetup ??= this.initializeDlqStream().finally(() => {+ this.dlqStreamSetup = null;+ });+ await this.dlqStreamSetup;}- async ensureDlqStream(): Promise<void> {- if (this.dlqStreamReady) {- return;- }+ private async initializeDlqStream(): Promise<void> {const jsm = await this.connectionManager.getJetStreamManager();- if ((await this.readStreamConfig(jsm, DLQ_STREAM_NAME)) === null) {+ if ((await this.readStreamConfig(jsm, DEAD_LETTER_STREAM)) === null) {if (!(await this.addDlqStream(jsm))) {return;}@@ -204,21 +346,12 @@ export class JetStreamWorkerQueue {private async addDlqStream(jsm: JetStreamManager): Promise<boolean> {try {const maxBytes = await this.fitToStorageBudget(DLQ_MAX_BYTES, DLQ_MIN_BYTES, (bytes) =>- jsm.streams.add({- name: DLQ_STREAM_NAME,- subjects: [`${DLQ_SUBJECT_PREFIX}>`],- retention: RetentionPolicy.Limits,- storage: StorageType.File,- max_age: nanos(DLQ_MAX_AGE_MS),- num_replicas: 1,- max_bytes: bytes,- discard: DiscardPolicy.Old,- }),+ this.createStream(jsm, DEAD_LETTER_STREAM, bytes),);Logger.info({stream: DLQ_STREAM_NAME, max_bytes: maxBytes}, 'Dead-letter stream created');return true;} catch (error) {- if (await this.adoptConcurrentStream(jsm, DLQ_STREAM_NAME, error)) {+ if ((await this.adoptConcurrentStream(jsm, DEAD_LETTER_STREAM, error)) !== null) {return true;}if (jsErrorCode(error) !== STREAM_NO_STORAGE_ERR_CODE) {@@ -238,59 +371,98 @@ export class JetStreamWorkerQueue {}const jsm = await this.connectionManager.getJetStreamManager();for (const lane of lanes) {- const filterSubjects = [...lane.taskTypes, ...lane.retiredTaskTypes].map((t) => `${SUBJECT_PREFIX}${t}`);- const config = {- durable_name: lane.consumerName,- ack_policy: AckPolicy.Explicit,- max_deliver: lane.maxDeliver,- ack_wait: nanos(lane.ackWaitMs),- max_ack_pending: lane.maxAckPending,- filter_subjects: filterSubjects,- };+ await this.ensureConsumer(jsm, lane);+ }+ this.consumersReady = true;+ }++ private async readConsumer(jsm: JetStreamManager, name: string): Promise<ConsumerInfo | null> {+ try {+ return await jsm.consumers.info(STREAM_NAME, name);+ } catch (error) {+ if (jsErrorCode(error) === CONSUMER_NOT_FOUND_ERR_CODE) {+ return null;+ }+ throw error;+ }+ }++ private async ensureConsumer(jsm: JetStreamManager, lane: WorkerLaneDefinition): Promise<void> {+ const config = {+ max_deliver: lane.maxDeliver,+ ack_wait: nanos(lane.ackWaitMs),+ max_ack_pending: lane.maxAckPending,+ filter_subject: undefined,+ filter_subjects: [...lane.taskTypes, ...lane.retiredTaskTypes].map((task) => `${SUBJECT_PREFIX}${task}`),+ } satisfies ConsumerUpdateConfig;+ let existing = await this.readConsumer(jsm, lane.consumerName);+ if (existing === null) {try {- await jsm.consumers.add(STREAM_NAME, config);+ const created = await jsm.consumers.add(STREAM_NAME, {+ ...config,+ durable_name: lane.consumerName,+ ack_policy: AckPolicy.Explicit,+ deliver_policy: DeliverPolicy.All,+ replay_policy: ReplayPolicy.Instant,+ });+ this.requireConsumerConfiguration(created, lane.consumerName);Logger.info({lane: lane.name, consumer: lane.consumerName}, 'Consumer created');+ return;} catch (error) {- const message = error instanceof Error ? error.message : String(error);- if (message.includes('consumer already exists') || message.includes('consumer name already')) {- Logger.info(- {lane: lane.name, consumer: lane.consumerName},- 'Consumer already exists, deleting and recreating with updated config',- );- try {- await jsm.consumers.delete(STREAM_NAME, lane.consumerName);- await jsm.consumers.add(STREAM_NAME, config);- Logger.info({lane: lane.name, consumer: lane.consumerName}, 'Consumer recreated');- } catch (recreateError) {- Logger.error(- {lane: lane.name, consumer: lane.consumerName, err: recreateError},- 'Failed to recreate consumer',- );- throw recreateError;- }- } else {+ if (!CONSUMER_EXISTS_ERR_CODES.has(jsErrorCode(error) ?? 0)) {+ throw error;+ }+ existing = await this.readConsumer(jsm, lane.consumerName);+ if (existing === null) {throw error;}}}- this.consumersReady = true;+ this.requireConsumerConfiguration(existing, lane.consumerName);+ const updated = await jsm.consumers.update(STREAM_NAME, lane.consumerName, config);+ this.requireConsumerConfiguration(updated, lane.consumerName);+ if (updated.created !== existing.created) {+ throw new Error(`Worker consumer ${lane.consumerName} was replaced during startup`);+ }+ Logger.info({lane: lane.name, consumer: lane.consumerName}, 'Consumer updated without resetting delivery state');+ }++ private requireConsumerConfiguration(consumer: ConsumerInfo, name: string): void {+ const current = consumer.config;+ if (+ current.durable_name !== name ||+ current.ack_policy !== AckPolicy.Explicit ||+ current.deliver_policy !== DeliverPolicy.All ||+ current.replay_policy !== ReplayPolicy.Instant ||+ current.deliver_subject ||+ current.headers_only ||+ (current.inactive_threshold ?? 0) > 0 ||+ (current.backoff?.length ?? 0) > 0+ ) {+ throw new Error(+ `Worker consumer ${name} has an incompatible configuration, migrate it explicitly with workers stopped`,+ );+ }}- async migrateOldConsumer(): Promise<void> {+ private async migrateLegacyConsumer(): Promise<void> {const jsm = await this.connectionManager.getJetStreamManager();+ if ((await this.readConsumer(jsm, LEGACY_CONSUMER_NAME)) === null) return;try {- await jsm.consumers.info(STREAM_NAME, LEGACY_CONSUMER_NAME);await jsm.consumers.delete(STREAM_NAME, LEGACY_CONSUMER_NAME);- Logger.info('Legacy consumer deleted, lane consumers will handle any unacked messages');- } catch {- Logger.debug('Legacy consumer does not exist, nothing to migrate');+ Logger.info({consumer: LEGACY_CONSUMER_NAME}, 'Legacy consumer deleted, lane consumers will handle its messages');+ } catch (error) {+ Logger.error(+ {err: error, consumer: LEGACY_CONSUMER_NAME},+ 'Could not delete the legacy worker consumer, delete it manually once legacy workers are stopped',+ );}}async ensureInfrastructure(lanes: ReadonlyArray<WorkerLaneDefinition>): Promise<void> {await this.ensureStream();await this.ensureDlqStream();- await this.migrateOldConsumer();+ await this.migrateLegacyConsumer();await this.ensureConsumers(lanes);}@@ -332,13 +504,7 @@ export class JetStreamWorkerQueue {async publishToDlq(taskType: string,originalPayload: Record<string, unknown>,- meta: {- originalSeq: number;- errorMessage: string;- deliveryCount: number;- lane: string;- runAt?: string;- },+ meta: WorkerDeadLetterMetadata,): Promise<void> {const js = this.connectionManager.getJetStreamClient();const subject = `${DLQ_SUBJECT_PREFIX}${taskType}`;@@ -353,7 +519,8 @@ export class JetStreamWorkerQueue {failed_at: new Date().toISOString(),});await js.publish(subject, body, {- msgID: randomUUID(),+ msgID: meta.messageId,+ timeout: DLQ_PUBLISH_TIMEOUT_MS,});}diff --git a/fluxer_api/src/api/worker/WorkerDependencies.ts b/fluxer_api/src/api/worker/WorkerDependencies.tsindex b0b1d8c24..569eb6917 100644--- a/fluxer_api/src/api/worker/WorkerDependencies.ts+++ b/fluxer_api/src/api/worker/WorkerDependencies.ts@@ -25,14 +25,12 @@ import type {GuildRepository} from '../guild/repositories/GuildRepository';import type {GuildService} from '../guild/services/GuildService';import type {AvatarService} from '../infrastructure/AvatarService';import type {IPurgeQueue} from '../infrastructure/BunnyPurgeQueue';-import {DisabledLiveKitService} from '../infrastructure/DisabledLiveKitService';import type {DiscriminatorService} from '../infrastructure/DiscriminatorService';import type {EmbedService} from '../infrastructure/EmbedService';import type {IAssetDeletionQueue} from '../infrastructure/IAssetDeletionQueue';import type {IGatewayService} from '../infrastructure/IGatewayService';import type {ILiveKitService} from '../infrastructure/ILiveKitService';import type {IMediaService} from '../infrastructure/IMediaService';-import {InMemoryVoiceRoomStore} from '../infrastructure/InMemoryVoiceRoomStore';import type {ISnowflakeService} from '../infrastructure/ISnowflakeService';import type {IStorageService} from '../infrastructure/IStorageService';import type {IUnfurlerService} from '../infrastructure/IUnfurlerService';@@ -58,7 +56,6 @@ import {getVoiceRoomStoreInstance,getVoiceTopology,getWorkerService,- resolveBlueskyOAuthService,} from '../middleware/ServiceRegistry';import {createUserCacheService,@@ -192,7 +189,9 @@ export async function initializeWorkerDependencies(snowflakeService: ISnowflakeSconst userHarvestRepository = new UserHarvestRepository();const connectionRepository = getConnectionRepository();const cacheService = getCacheService();+ const instanceConfigRepository = getInstanceConfigRepository();const limitConfigService = getLimitConfigService();+ await instanceConfigRepository.initialize();await limitConfigService.initialize();limitConfigService.setAsGlobalInstance();const userCacheService = createUserCacheService();@@ -200,9 +199,7 @@ export async function initializeWorkerDependencies(snowflakeService: ISnowflakeSconst assetDeletionQueue = getAssetDeletionQueue();const purgeQueue = getPurgeQueue();const gatewayService = getGatewayService();- const instanceConfigRepository = getInstanceConfigRepository();- const blueskyOAuthService = await resolveBlueskyOAuthService(instanceConfigRepository);- const connectionService = new ConnectionService(connectionRepository, gatewayService, blueskyOAuthService);+ const connectionService = new ConnectionService(connectionRepository, gatewayService);const mediaService = getMediaService();const discriminatorService = getDiscriminatorService();const ncmecSubmissionService = getNcmecSubmissionService();@@ -226,8 +223,11 @@ export async function initializeWorkerDependencies(snowflakeService: ISnowflakeSawait ensureVoiceResourcesInitialized();const voiceRepository = getVoiceRepository();const voiceTopology = getVoiceTopology();- const voiceRoomStore = getVoiceRoomStoreInstance() ?? new InMemoryVoiceRoomStore();- const liveKitService = getLiveKitServiceInstance() ?? new DisabledLiveKitService();+ const voiceRoomStore = getVoiceRoomStoreInstance();+ const liveKitService = getLiveKitServiceInstance();+ if (voiceRoomStore === null || liveKitService === null) {+ throw new Error('Voice resources are unavailable during worker initialization');+ }const voiceAvailabilityService = getVoiceAvailabilityService();if (Config.voice.enabled && voiceTopology !== null) {Logger.info('Voice services initialized');diff --git a/fluxer_api/src/api/worker/WorkerLaneConfig.ts b/fluxer_api/src/api/worker/WorkerLaneConfig.tsindex 965c03027..58505c531 100644--- a/fluxer_api/src/api/worker/WorkerLaneConfig.ts+++ b/fluxer_api/src/api/worker/WorkerLaneConfig.ts@@ -49,7 +49,6 @@ const LANE_CONFIG = {'harvestUserData','batchGuildAuditLogMessageDeletes','reconcileUserPayments',- 'revalidateUserConnections','bulkUpdateUserFlags','bulkUpdateSuspiciousActivityFlags','bulkScheduleUserDeletion',diff --git a/fluxer_api/src/api/worker/WorkerMain.ts b/fluxer_api/src/api/worker/WorkerMain.tsindex 89a0b1620..b66da262b 100644--- a/fluxer_api/src/api/worker/WorkerMain.ts+++ b/fluxer_api/src/api/worker/WorkerMain.ts@@ -10,15 +10,20 @@ import {Config} from '../Config';import {setDatabaseQueryExecutor} from '../database/CassandraQueryExecution';import {ensurePostgresKvSchema, PostgresKvQueryExecutor} from '../database/PostgresKvQueryExecutor';import type {ISnowflakeService} from '../infrastructure/ISnowflakeService';+import type {InstanceConfigRepository} from '../instance/InstanceConfigRepository';import {JobLedgerRepository} from '../jobs/JobLedgerRepository';import {Logger} from '../Logger';+import type {LimitConfigService} from '../limits/LimitConfigService';import {+ closeOwnedKVClient,createSnowflakeService,setInjectedSnowflakeService,setInjectedWorkerService,+ shutdownVoiceResources,} from '../middleware/ServiceRegistry';-import {getCacheService} from '../middleware/ServiceSingletons';+import {getCacheService, getInstanceConfigRepository, getLimitConfigService} from '../middleware/ServiceSingletons';import {initializeSearch, shutdownSearch} from '../SearchFactory';+import {awaitAll} from '../utils/ConcurrencyUtils';import {CronScheduler} from './CronScheduler';import {JetStreamWorkerQueue} from './JetStreamWorkerQueue';import {clearWorkerDependencies, setWorkerDependencies} from './WorkerContext';@@ -88,12 +93,14 @@ export async function startWorkerMain(): Promise<void> {let postgresInitialized = false;let jsConnectionManager: JetStreamConnectionManager | null = null;let snowflakeService: ISnowflakeService | null = null;+ let limitConfigService: LimitConfigService | null = null;+ let instanceConfigRepository: InstanceConfigRepository | null = null;let dependencies: WorkerDependencies | null = null;let cron: CronScheduler | null = null;const heartbeat = new WorkerHeartbeat({logger: Logger});const runners: Array<WorkerRunner> = [];let searchInitialized = false;- let shuttingDown = false;+ let shutdownPromise: Promise<void> | null = null;const cleanupStep = async (label: string, fn: () => Promise<void> | void): Promise<void> => {try {@@ -103,17 +110,18 @@ export async function startWorkerMain(): Promise<void> {}};- const shutdown = async (): Promise<void> => {- if (shuttingDown) {- return;- }- shuttingDown = true;+ const performShutdown = async (): Promise<void> => {Logger.info('Shutting down worker backend...');+ const voiceShutdown = cleanupStep('voice resources', shutdownVoiceResources);await cleanupStep('heartbeat', () => heartbeat.stop());await cleanupStep('cron', () => cron?.stop());await cleanupStep('runners', async () => {- await Promise.all(runners.map((runner) => runner.stop()));+ await awaitAll(+ runners.map((runner) => runner.stop()),+ 'Failed to stop worker runners',+ );});+ await voiceShutdown;await cleanupStep('jetstream', async () => {await jsConnectionManager?.drain();jsConnectionManager = null;@@ -123,6 +131,18 @@ export async function startWorkerMain(): Promise<void> {clearWorkerDependencies();setInjectedWorkerService(undefined);});+ await cleanupStep('limit config', async () => {+ if (limitConfigService) {+ await limitConfigService.shutdown();+ limitConfigService = null;+ }+ });+ await cleanupStep('instance config repository', async () => {+ if (instanceConfigRepository) {+ await instanceConfigRepository.shutdown();+ instanceConfigRepository = null;+ }+ });await cleanupStep('search', async () => {if (searchInitialized) {await shutdownSearch();@@ -149,15 +169,20 @@ export async function startWorkerMain(): Promise<void> {}setInjectedSnowflakeService(undefined);});+ await cleanupStep('key-value client', closeOwnedKVClient);+ };+ const shutdown = (): Promise<void> => {+ shutdownPromise ??= Promise.resolve().then(performShutdown);+ return shutdownPromise;};try {if (Config.database.backend === 'postgres') {- await initPostgres(Config.postgres);+ await initPostgres(Config.postgres, (diagnostic) => Logger.error(diagnostic, 'Postgres connection error'));+ postgresInitialized = true;const postgres = getDefaultPostgresClient();await ensurePostgresKvSchema(postgres);setDatabaseQueryExecutor(new PostgresKvQueryExecutor(postgres));- postgresInitialized = true;Logger.info('Postgres KV client initialised for worker backend');}if (Config.database.backend === 'cassandra') {@@ -209,6 +234,8 @@ export async function startWorkerMain(): Promise<void> {const jobLedger = new JobLedgerRepository();const workerService = new WorkerService(queue, snowflakeService, jobLedger);setInjectedWorkerService(workerService);+ instanceConfigRepository = getInstanceConfigRepository();+ limitConfigService = getLimitConfigService();dependencies = await initializeWorkerDependencies(snowflakeService);setWorkerDependencies(dependencies);if (Config.blocklistFeeds.enabled) {diff --git a/fluxer_api/src/api/worker/WorkerRunner.ts b/fluxer_api/src/api/worker/WorkerRunner.tsindex f0d393a57..e4ac5dd17 100644--- a/fluxer_api/src/api/worker/WorkerRunner.ts+++ b/fluxer_api/src/api/worker/WorkerRunner.ts@@ -1,13 +1,16 @@// SPDX-License-Identifier: AGPL-3.0-or-later-import {randomUUID} from 'node:crypto';+import {createHash, randomUUID} from 'node:crypto';import type {IWorkerService} from '@pkgs/worker/src/contracts/IWorkerService';import {JobCancelledError, type WorkerTaskHandler} from '@pkgs/worker/src/contracts/WorkerTask';-import type {ConsumerMessages, JsMsg} from 'nats';+import type {ConsumerMessages, FetchOptions, JsMsg} from 'nats';+import {ArchiveAttemptSupersededError} from '../archive/ArchiveAttemptSupersededError';+import {ArchiveTaskDeferredError, ArchiveTerminalFailureError, isArchiveTask} from '../archive/ArchiveTask';import type {IJobLedgerRepository} from '../jobs/IJobLedgerRepository';import {Logger} from '../Logger';import {getWorkerService} from '../middleware/ServiceRegistry';import {isJsonRecord, parseJsonRecord} from '../utils/JsonBoundaryUtils';+import type {WorkerDeadLetterMetadata} from './JetStreamWorkerQueue';import {WORKER_LANE_HEARTBEAT_INTERVAL_MS,WORKER_LANE_STALE_AFTER_MS,@@ -16,18 +19,19 @@ import {} from './WorkerHeartbeat';const MAX_DLQ_PUBLISH_ATTEMPTS = 3;+const DLQ_RETRY_DELAY_MS = 250;const MIN_ACK_HEARTBEAT_MS = 1000;+const MAX_ACK_WAIT_MS = 2 * 2_147_483_647;const RESUBSCRIBE_DELAY_MS = 5000;const RETIRED_TASK_REASON = 'task type retired';+interface WorkerRunnerConsumer {+ fetch(options: FetchOptions): Promise<ConsumerMessages>;+}+interface WorkerRunnerJetStreamClient {consumers: {- get(- streamName: string,- consumerName: string,- ): Promise<{- consume(options: {max_messages: number; idle_heartbeat: number}): Promise<ConsumerMessages>;- }>;+ get(streamName: string, consumerName: string): Promise<WorkerRunnerConsumer>;};}@@ -35,18 +39,14 @@ interface WorkerRunnerConnectionManager {getJetStreamClient(): WorkerRunnerJetStreamClient;}-interface WorkerRunnerDlqMeta {- originalSeq: number;- errorMessage: string;- deliveryCount: number;- lane: string;- runAt?: string;-}-interface WorkerRunnerQueue {getConnectionManager(): WorkerRunnerConnectionManager;getStreamName(): string;- publishToDlq(taskType: string, originalPayload: Record<string, unknown>, meta: WorkerRunnerDlqMeta): Promise<void>;+ publishToDlq(+ taskType: string,+ originalPayload: Record<string, unknown>,+ meta: WorkerDeadLetterMetadata,+ ): Promise<void>;}interface WorkerRunnerOptions {@@ -80,6 +80,8 @@ export class WorkerRunner {private heartbeatTimer: NodeJS.Timeout | null = null;private running = false;private consumerMessages: ConsumerMessages | null = null;+ private startup: Promise<void> | null = null;+ private shutdown: Promise<void> | null = null;private processingLoop: Promise<void> | null = null;private readonly inFlightJobs = new Set<Promise<void>>();@@ -91,43 +93,93 @@ export class WorkerRunner {this.laneName = options.laneName;this.workerId = options.workerId ?? `worker-${options.laneName}-${randomUUID()}`;this.concurrency = options.concurrency ?? 1;+ if (!Number.isSafeInteger(this.concurrency) || this.concurrency < 1) {+ throw new RangeError('Worker concurrency must be a positive safe integer');+ }this.maxDeliver = options.maxDeliver ?? 5;+ if (!Number.isSafeInteger(this.maxDeliver) || this.maxDeliver < 1) {+ throw new RangeError('Worker maxDeliver must be a positive safe integer');+ }this.ackWaitMs = options.ackWaitMs ?? 60000;+ if (+ !Number.isSafeInteger(this.ackWaitMs) ||+ this.ackWaitMs < MIN_ACK_HEARTBEAT_MS * 2 ||+ this.ackWaitMs > MAX_ACK_WAIT_MS+ ) {+ throw new RangeError(+ `Worker ackWaitMs must be a safe integer between ${MIN_ACK_HEARTBEAT_MS * 2} and ${MAX_ACK_WAIT_MS}`,+ );+ }this.workerService = getWorkerService();this.ledger = options.ledger;this.heartbeat = options.heartbeat ?? null;}async start(): Promise<void> {- if (this.running) {- Logger.warn({workerId: this.workerId}, 'Worker already running');+ if (this.startup !== null) {+ await this.startup;+ return;+ }+ if (this.running || this.shutdown !== null || this.processingLoop !== null) {+ Logger.warn({workerId: this.workerId}, 'Worker already running or stopping');return;}this.running = true;Logger.info({workerId: this.workerId, lane: this.laneName, concurrency: this.concurrency}, 'Worker starting');- this.startHeartbeat();- this.consumerMessages = await this.openConsumerMessages();- this.processingLoop = this.consumeUntilStopped(this.consumerMessages).finally(() => {- this.stopHeartbeatTicker();+ this.startup = this.startConsuming().finally(() => {+ this.startup = null;});+ await this.startup;+ }++ private async startConsuming(): Promise<void> {+ try {+ this.startHeartbeat();+ const consumer = await this.openConsumer();+ if (!this.running) {+ return;+ }+ this.processingLoop = this.consumeUntilStopped(consumer).finally(() => {+ this.running = false;+ this.processingLoop = null;+ this.stopHeartbeat();+ });+ } catch (error) {+ this.running = false;+ this.stopHeartbeat();+ throw error;+ }}async stop(): Promise<void> {- if (!this.running) {+ if (this.shutdown !== null) {+ await this.shutdown;return;}- this.running = false;- if (this.consumerMessages !== null) {- await this.consumerMessages.close();- this.consumerMessages = null;+ if (!this.running && this.startup === null && this.processingLoop === null) {+ return;}- if (this.processingLoop !== null) {- await this.processingLoop;- this.processingLoop = null;+ this.running = false;+ this.shutdown = this.stopConsuming().finally(() => {+ this.shutdown = null;+ });+ await this.shutdown;+ }++ private async stopConsuming(): Promise<void> {+ const startupResult = await Promise.allSettled([this.startup]);+ const messages = this.consumerMessages;+ const stopResults = await Promise.allSettled([+ Promise.resolve().then(() => messages?.close()),+ this.processingLoop,+ ]);+ this.stopHeartbeat();+ const errors = [...startupResult, ...stopResults]+ .filter((result) => result.status === 'rejected')+ .map((result) => result.reason);+ if (errors.length > 0) {+ throw new AggregateError(errors, 'Worker shutdown failed');}- this.stopHeartbeatTicker();- this.heartbeatSignal?.release();- this.heartbeatSignal = null;Logger.info({workerId: this.workerId}, 'Worker stopped');}@@ -141,34 +193,30 @@ export class WorkerRunner {}, WORKER_LANE_HEARTBEAT_INTERVAL_MS);}- private stopHeartbeatTicker(): void {+ private stopHeartbeat(): void {if (this.heartbeatTimer !== null) {clearInterval(this.heartbeatTimer);this.heartbeatTimer = null;}+ this.heartbeatSignal?.release();+ this.heartbeatSignal = null;}- private async openConsumerMessages(): Promise<ConsumerMessages> {+ private async openConsumer(): Promise<WorkerRunnerConsumer> {const js = this.queue.getConnectionManager().getJetStreamClient();- const consumer = await js.consumers.get(this.queue.getStreamName(), this.consumerName);- const prefetch = Math.max(this.concurrency * 2, 16);- return await consumer.consume({- max_messages: prefetch,- idle_heartbeat: 5000,- });+ return await js.consumers.get(this.queue.getStreamName(), this.consumerName);}- private async consumeUntilStopped(initialMessages: ConsumerMessages): Promise<void> {- let messages: ConsumerMessages | null = initialMessages;+ private async consumeUntilStopped(initialConsumer: WorkerRunnerConsumer): Promise<void> {+ let consumer: WorkerRunnerConsumer | null = initialConsumer;while (this.running) {- if (messages === null) {+ if (consumer === null) {await new Promise((resolve) => setTimeout(resolve, RESUBSCRIBE_DELAY_MS));if (!this.running) {break;}try {- messages = await this.openConsumerMessages();- this.consumerMessages = messages;+ consumer = await this.openConsumer();} catch (error) {Logger.error({workerId: this.workerId, lane: this.laneName, err: error},@@ -178,12 +226,11 @@ export class WorkerRunner {continue;}try {- await this.processMessages(messages);+ await this.processMessages(consumer);} catch (error) {Logger.error({workerId: this.workerId, err: error}, 'Worker message processing failed unexpectedly');}- messages = null;- this.consumerMessages = null;+ consumer = null;if (this.running) {Logger.error({workerId: this.workerId, lane: this.laneName},@@ -194,53 +241,106 @@ export class WorkerRunner {Logger.info({workerId: this.workerId}, 'Worker message iterator ended');}- private async processMessages(consumerMessages: ConsumerMessages): Promise<void> {- for await (const msg of consumerMessages) {- if (!this.running) {- break;- }- while (this.inFlightJobs.size >= this.concurrency) {- await Promise.race(this.inFlightJobs);- }- const taskType = msg.subject.startsWith('jobs.') ? msg.subject.slice(5) : msg.subject;- Logger.info(- {- workerId: this.workerId,- lane: this.laneName,- taskType,- seq: msg.seq,- redelivered: msg.redelivered,- },- 'Processing job',- );- const jobPromise = this.processJob(taskType, msg)- .then((succeeded) => {- if (succeeded) {- Logger.info({workerId: this.workerId, taskType, seq: msg.seq}, 'Job completed successfully');+ private async processMessages(consumer: WorkerRunnerConsumer): Promise<void> {+ try {+ while (this.running) {+ while (this.inFlightJobs.size >= this.concurrency) {+ await Promise.race(this.inFlightJobs);+ }+ if (!this.running) {+ break;+ }+ const messages = await consumer.fetch({+ max_messages: this.concurrency - this.inFlightJobs.size,+ idle_heartbeat: 5000,+ });+ this.consumerMessages = messages;+ if (!this.running) {+ messages.stop();+ }+ let admissionError: Error | null = null;+ try {+ for await (const msg of messages) {+ if (!this.running || admissionError !== null) {+ continue;+ }+ try {+ if (this.inFlightJobs.size >= this.concurrency) {+ throw new Error('Worker consumer delivered a message without available capacity');+ }+ this.admitJob(msg);+ } catch (error) {+ admissionError = error instanceof Error ? error : new Error('Worker admission failed', {cause: error});+ messages.stop(admissionError);+ }}- })- .catch((error) => {- Logger.error({workerId: this.workerId, taskType, seq: msg.seq, err: error}, 'Job processing crashed');+ if (admissionError !== null) {+ throw admissionError;+ }+ } finally {try {- msg.nak(5000);- } catch (nakError) {- Logger.error({workerId: this.workerId, taskType, seq: msg.seq, err: nakError}, 'Failed to NAK crashed job');+ await messages.close();+ } finally {+ this.consumerMessages = null;}- })- .finally(() => {- this.inFlightJobs.delete(jobPromise);- });- this.inFlightJobs.add(jobPromise);+ }+ }+ } finally {+ await Promise.allSettled(this.inFlightJobs);}- await Promise.allSettled(this.inFlightJobs);+ }++ private admitJob(msg: JsMsg): void {+ const taskType = msg.subject.startsWith('jobs.') ? msg.subject.slice(5) : msg.subject;+ Logger.info(+ {+ workerId: this.workerId,+ lane: this.laneName,+ taskType,+ seq: msg.seq,+ redelivered: msg.redelivered,+ },+ 'Processing job',+ );+ const jobPromise = this.processJob(taskType, msg)+ .then((succeeded) => {+ if (succeeded) {+ Logger.info({workerId: this.workerId, taskType, seq: msg.seq}, 'Job completed successfully');+ }+ })+ .catch((error) => {+ Logger.error({workerId: this.workerId, taskType, seq: msg.seq, err: error}, 'Job processing crashed');+ if (isArchiveTask(this.tasks[taskType])) {+ return;+ }+ try {+ msg.nak(5000);+ } catch (nakError) {+ Logger.error({workerId: this.workerId, taskType, seq: msg.seq, err: nakError}, 'Failed to NAK crashed job');+ }+ })+ .finally(() => {+ this.inFlightJobs.delete(jobPromise);+ });+ this.inFlightJobs.add(jobPromise);}protected async processJob(taskType: string, msg: JsMsg): Promise<boolean> {+ const ackHeartbeat = this.startAckHeartbeat(taskType, msg);+ try {+ return await this.executeJob(taskType, msg);+ } finally {+ clearInterval(ackHeartbeat);+ }+ }++ private async executeJob(taskType: string, msg: JsMsg): Promise<boolean> {+ const task = this.tasks[taskType];+ const archiveTask = isArchiveTask(task);if (this.retiredTaskTypes.has(taskType)) {await this.retireJob(taskType, msg);return false;}- const task = this.tasks[taskType];if (!task) {Logger.error({taskType, seq: msg.seq}, 'Unknown task type, terminating message');msg.term(`unknown task type: ${taskType}`);@@ -265,7 +365,14 @@ export class WorkerRunner {}delete jobPayload['__jobId'];}- } catch {+ } catch (error) {+ if (archiveTask) {+ Logger.error(+ {taskType, seq: msg.seq, err: error},+ 'Invalid archive job payload, leaving message unacknowledged',+ );+ return false;+ }Logger.error({taskType, seq: msg.seq}, 'Failed to decode job payload, terminating message');msg.term('invalid payload');return false;@@ -277,14 +384,14 @@ export class WorkerRunner {if (delayMs > 0) {Logger.debug({taskType, seq: msg.seq, runAt, delayMs},- 'Job scheduled for future execution, redelivering with delay',+ 'Job scheduled for future execution, deferring execution',);- msg.nak(delayMs);+ if (!archiveTask) msg.nak(delayMs);return false;}}}- if (ledgerJobId !== null) {+ if (ledgerJobId !== null && !archiveTask) {try {await this.ledger.markRunning(ledgerJobId, this.laneName);} catch (err) {@@ -296,6 +403,7 @@ export class WorkerRunner {const helpers = {logger: Logger.child({taskType, seq: msg.seq, jobId: capturedJobId?.toString()}),jobId: capturedJobId ?? 0n,+ attempt: {isLastAttempt: msg.info.deliveryCount >= this.maxDeliver},addJob: this.workerService.addJob.bind(this.workerService),reportProgress: async (current: number, total: number | null, message?: string | null) => {if (capturedJobId === null) return;@@ -323,7 +431,6 @@ export class WorkerRunner {}},};- const ackHeartbeat = this.startAckHeartbeat(taskType, msg);try {await task(jobPayload, helpers);if (ledgerJobId !== null) {@@ -336,6 +443,22 @@ export class WorkerRunner {msg.ack();return true;} catch (error) {+ if (archiveTask && !(error instanceof ArchiveTerminalFailureError)) {+ if (error instanceof ArchiveAttemptSupersededError) {+ Logger.info({taskType, seq: msg.seq}, 'Archive attempt was superseded');+ } else if (error instanceof ArchiveTaskDeferredError) {+ Logger.warn(+ {taskType, seq: msg.seq, err: error},+ 'Archive attempt deferred without changing queue disposition',+ );+ } else {+ Logger.error(+ {taskType, seq: msg.seq, err: error},+ 'Archive attempt failed without a confirmed terminal state',+ );+ }+ return false;+ }const isCancelled = error instanceof JobCancelledError;if (isCancelled) {if (ledgerJobId !== null) {@@ -352,11 +475,17 @@ export class WorkerRunner {const deliveryCount = msg.info.deliveryCount;const isLastDelivery = deliveryCount >= this.maxDeliver;const errorMessage = error instanceof Error ? error.message : String(error);- if (isLastDelivery) {+ if (archiveTask || isLastDelivery) {Logger.error({taskType, seq: msg.seq, deliveryCount, err: error},- 'Job failed on final delivery attempt, moving to dead-letter queue',+ 'Job failed permanently, publishing to dead-letter queue',);+ const published = await this.publishToDlqWithRetry(+ taskType,+ jobPayload,+ this.createDeadLetterMetadata(msg, errorMessage, runAt),+ );+ if (!published) return false;if (ledgerJobId !== null) {try {await this.ledger.markDeadletter(ledgerJobId, errorMessage);@@ -364,31 +493,7 @@ export class WorkerRunner {Logger.warn({err, jobId: ledgerJobId.toString()}, 'Ledger markDeadletter failed');}}- try {- await this.queue.publishToDlq(taskType, jobPayload, {- originalSeq: msg.seq,- errorMessage,- deliveryCount,- lane: this.laneName,- runAt,- });- msg.term('moved to dead-letter queue');- } catch (dlqError) {- const dlqPublishAttempts = deliveryCount - this.maxDeliver;- if (dlqPublishAttempts >= MAX_DLQ_PUBLISH_ATTEMPTS) {- Logger.error(- {taskType, seq: msg.seq, deliveryCount, err: dlqError},- 'Failed to publish to dead-letter queue after repeated attempts, dropping message to avoid poison loop',- );- msg.term('dead-letter publish failed repeatedly');- } else {- Logger.error(- {taskType, seq: msg.seq, deliveryCount, err: dlqError},- 'Failed to publish to dead-letter queue, will retry on redelivery',- );- msg.nak(5000);- }- }+ msg.term('moved to dead-letter queue');} else {Logger.error({taskType, seq: msg.seq, err: error}, 'Job failed');if (ledgerJobId !== null) {@@ -401,11 +506,50 @@ export class WorkerRunner {msg.nak(5000);}return false;- } finally {- clearInterval(ackHeartbeat);}}+ private createDeadLetterMetadata(msg: JsMsg, errorMessage: string, runAt?: string): WorkerDeadLetterMetadata {+ const identity = [this.queue.getStreamName(), msg.subject, msg.seq, msg.headers?.get('Nats-Msg-Id') ?? null];+ const digest = createHash('sha256').update(JSON.stringify(identity)).update('\0').update(msg.data).digest('hex');+ return {+ messageId: `dlq:${digest}`,+ originalSeq: msg.seq,+ errorMessage,+ deliveryCount: msg.info.deliveryCount,+ lane: this.laneName,+ runAt,+ };+ }++ private async publishToDlqWithRetry(+ taskType: string,+ payload: Record<string, unknown>,+ meta: WorkerDeadLetterMetadata,+ maxAttempts = MAX_DLQ_PUBLISH_ATTEMPTS,+ ): Promise<boolean> {+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {+ try {+ await this.queue.publishToDlq(taskType, payload, meta);+ return true;+ } catch (error) {+ if (attempt === maxAttempts) {+ Logger.error(+ {taskType, seq: meta.originalSeq, deliveryCount: meta.deliveryCount, attempts: attempt, err: error},+ 'Failed to publish to dead-letter queue, leaving original message unacknowledged',+ );+ return false;+ }+ Logger.warn(+ {taskType, seq: meta.originalSeq, attempt, err: error},+ 'Dead-letter publish failed, retrying within this delivery',+ );+ await new Promise((resolve) => setTimeout(resolve, DLQ_RETRY_DELAY_MS * attempt));+ }+ }+ return false;+ }+private async retireJob(taskType: string, msg: JsMsg): Promise<void> {const decoded = parseJsonRecord(new TextDecoder().decode(msg.data));const jobPayload = decoded && isJsonRecord(decoded.payload) ? decoded.payload : {};@@ -424,17 +568,15 @@ export class WorkerRunner {{taskType, seq: msg.seq, jobId: ledgerJobId?.toString()},'Retired task type from an older release, moving to dead-letter queue',);- try {- await this.queue.publishToDlq(taskType, jobPayload, {- originalSeq: msg.seq,- errorMessage: RETIRED_TASK_REASON,- deliveryCount: msg.info.deliveryCount,- lane: this.laneName,- runAt,- });- } catch (error) {- Logger.error({taskType, seq: msg.seq, err: error}, 'Failed to dead-letter a retired job');- msg.nak(5000);+ const isLastDelivery = msg.info.deliveryCount >= this.maxDeliver;+ const published = await this.publishToDlqWithRetry(+ taskType,+ jobPayload,+ this.createDeadLetterMetadata(msg, RETIRED_TASK_REASON, runAt),+ isLastDelivery ? MAX_DLQ_PUBLISH_ATTEMPTS : 1,+ );+ if (!published) {+ if (!isLastDelivery) msg.nak(5000);return;}if (ledgerJobId !== null) {@@ -458,9 +600,7 @@ export class WorkerRunner {},Math.max(MIN_ACK_HEARTBEAT_MS, Math.floor(this.ackWaitMs / 2)),);- if (typeof heartbeat === 'object' && heartbeat && 'unref' in heartbeat) {- (heartbeat as {unref(): void}).unref();- }+ heartbeat.unref();return heartbeat;}}diff --git a/fluxer_api/src/api/worker/WorkerTaskRegistry.ts b/fluxer_api/src/api/worker/WorkerTaskRegistry.tsindex 4c3f37a0b..3c9fcfa74 100644--- a/fluxer_api/src/api/worker/WorkerTaskRegistry.ts+++ b/fluxer_api/src/api/worker/WorkerTaskRegistry.ts@@ -35,7 +35,6 @@ import processStripeWebhook from './tasks/ProcessStripeWebhook';import prunePostgresKvTtl from './tasks/PrunePostgresKvTtl';import reconcileUserPayments from './tasks/ReconcileUserPayments';import refreshSearchIndex from './tasks/RefreshSearchIndex';-import revalidateUserConnections from './tasks/RevalidateUserConnections';import {sendSystemDm} from './tasks/SendSystemDm';import syncDiscoveryIndex from './tasks/SyncDiscoveryIndex';import syncDisposableEmailDomains from './tasks/SyncDisposableEmailDomains';@@ -79,7 +78,6 @@ export const workerTasks: Record<WorkerTaskName, WorkerTaskHandler> = {reconcileUserPayments,prunePostgresKvTtl,refreshSearchIndex,- revalidateUserConnections,sendSystemDm,syncFileShaBlocklists,syncUrlBlocklists,diff --git a/fluxer_api/src/api/worker/tasks/HarvestGuildData.ts b/fluxer_api/src/api/worker/tasks/HarvestGuildData.tsindex 94453a1bb..3194b9cf6 100644--- a/fluxer_api/src/api/worker/tasks/HarvestGuildData.ts+++ b/fluxer_api/src/api/worker/tasks/HarvestGuildData.ts@@ -1,18 +1,26 @@// SPDX-License-Identifier: AGPL-3.0-or-later+import assert from 'node:assert/strict';import fs from 'node:fs';import os from 'node:os';import path from 'node:path';import {GUILD_TEXT_BASED_CHANNEL_TYPES} from '@fluxer/constants/src/ChannelConstants';import {snowflakeToDate} from '@fluxer/snowflake/src/Snowflake';-import type {WorkerTaskHandler} from '@pkgs/worker/src/contracts/WorkerTask';-import archiver from 'archiver';-import {ms} from 'itty-time';import {z} from 'zod';+import {ArchiveAttemptSupersededError} from '../../archive/ArchiveAttemptSupersededError';+import {+ type ArchiveTaskHandler,+ ArchiveTerminalFailureError,+ createArchiveTask,+ throwIfArchiveTerminallyFailed,+} from '../../archive/ArchiveTask';import {type AttachmentID, type ChannelID, createGuildID, type MessageID} from '../../BrandedTypes';import {Config} from '../../Config';import {makeAttachmentCdnKey, makeAttachmentCdnUrl} from '../../channel/services/message/MessageHelpers';+import type {IStorageService} from '../../infrastructure/IStorageService';import {Logger} from '../../Logger';+import {mapWithConcurrency} from '../../utils/ConcurrencyUtils';+import {writeZipArchive} from '../utils/ArchiveFile';import {createArchiveJsonBuffer} from '../utils/ArchiveJson';import {buildHashedAssetKey,@@ -21,7 +29,6 @@ import {getEmojiExtension,} from '../utils/AssetArchiveHelpers';import {getWorkerDependencies} from '../WorkerContext';-import type {WorkerDependencies} from '../WorkerDependencies';const CHANNEL_CONCURRENCY = 4;const ASSET_CONCURRENCY = 8;@@ -32,7 +39,6 @@ const P_MESSAGES = 60;const P_ASSETS = 68;const P_ATTACHMENTS = 88;const P_ZIP = 95;-const P_DONE = 100;const MESSAGE_BATCH_SIZE = 100;const MESSAGE_LIMIT_PER_CHANNEL = 1000;const PayloadSchema = z.object({@@ -48,66 +54,57 @@ interface PendingAttachmentDownload {filename: string;}-async function parallel<T>(- items: Array<T>,- concurrency: number,- fn: (item: T, index: number) => Promise<void>,-): Promise<void> {- let i = 0;- const worker = async () => {- while (true) {- const idx = i++;- if (idx >= items.length) return;- await fn(items[idx]!, idx);- }- };- await Promise.all(Array.from({length: Math.min(concurrency, items.length || 1)}, worker));-}-function cdnBucket(): string {return Config.s3.buckets.cdn;}async function downloadToDisk(- storageService: WorkerDependencies['storageService'],+ storageService: IStorageService,bucket: string,key: string,destPath: string,-): Promise<boolean> {+): Promise<void> {try {await fs.promises.mkdir(path.dirname(destPath), {recursive: true});await storageService.writeObjectToDisk(bucket, key, destPath);- return true;- } catch (err) {- const name = err instanceof Error ? err.name : String(err);- if (name === 'NoSuchKey' || name === 'NotFound') return false;- Logger.warn({key, err: name}, 'Skipping unreadable S3 object during harvest');- return false;+ } catch (error) {+ if (!(error instanceof Error) || (error.name !== 'NoSuchKey' && error.name !== 'NotFound')) throw error;+ Logger.warn({key}, 'Skipping missing S3 object during harvest');}}-const harvestGuildData: WorkerTaskHandler = async (payload, helpers) => {+const harvestGuildData: ArchiveTaskHandler = async (payload, helpers, attempt) => {const validated = PayloadSchema.parse(payload);helpers.logger.debug({payload}, 'Processing harvestGuildData task');const guildId = createGuildID(BigInt(validated.guildId));const archiveId = BigInt(validated.archiveId);const guildIdStr = guildId.toString();const {guildRepository, channelRepository, adminArchiveRepository, storageService} = getWorkerDependencies();- const adminArchive = await adminArchiveRepository.findBySubjectAndArchiveId('guild', guildId, archiveId);- if (!adminArchive) throw new Error('Admin archive record not found for guild');- const upd = (pct: number, step: string) => adminArchiveRepository.updateProgress(adminArchive, pct, step);- const fail = (msg: string) => adminArchiveRepository.markAsFailed(adminArchive, msg);- const done = (key: string, size: bigint, exp: Date) =>- adminArchiveRepository.markAsCompleted(adminArchive, key, size, exp);- const tmpDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'fluxer-guild-archive-'));- const contentDir = path.join(tmpDir, 'content');- const zipPath = path.join(tmpDir, 'archive.zip');- await fs.promises.mkdir(contentDir);+ const existingArchive = await adminArchiveRepository.findBySubjectAndArchiveId('guild', guildId, archiveId);+ if (!existingArchive) throw new Error('Admin archive record not found for guild');+ throwIfArchiveTerminallyFailed(existingArchive);+ if (existingArchive.completedAt) {+ Logger.info({guildId, archiveId}, 'Guild archive already completed, skipping');+ return;+ }+ const adminArchive = await adminArchiveRepository.markAsStarted(existingArchive, 'Starting guild archive');+ const {attemptId, expiresAt} = adminArchive;+ assert(attemptId !== null && expiresAt !== null, 'Claimed guild archive is incomplete');+ let progressUpdate = Promise.resolve();+ const updateProgress = (percent: number, step: string): Promise<void> => {+ progressUpdate = progressUpdate.then(() => adminArchiveRepository.updateProgress(adminArchive, percent, step));+ return progressUpdate;+ };+ let storageKey: string;+ let fileSize: bigint;try {- await adminArchiveRepository.markAsStarted(adminArchive, 'Starting guild archive');+ await using tmpDir = await fs.promises.mkdtempDisposable(path.join(os.tmpdir(), 'fluxer-guild-archive-'));+ const contentDir = path.join(tmpDir.path, 'content');+ const zipPath = path.join(tmpDir.path, 'archive.zip');+ await fs.promises.mkdir(contentDir);const guild = await guildRepository.findUnique(guildId);if (!guild) throw new Error(`Guild ${guildIdStr} not found`);- await upd(P_START, 'Collecting guild metadata');+ await updateProgress(P_START, 'Collecting guild metadata');const [roles, members, channels, emojis, stickers] = await Promise.all([guildRepository.listRoles(guildId),guildRepository.listMembers(guildId),@@ -115,7 +112,7 @@ const harvestGuildData: WorkerTaskHandler = async (payload, helpers) => {guildRepository.listEmojis(guildId),guildRepository.listStickers(guildId),]);- await upd(P_META, 'Writing guild metadata');+ await updateProgress(P_META, 'Writing guild metadata');const guildJson = {guild: {id: guild.id.toString(),@@ -170,11 +167,11 @@ const harvestGuildData: WorkerTaskHandler = async (payload, helpers) => {})),};await fs.promises.writeFile(path.join(contentDir, 'guild.json'), createArchiveJsonBuffer(guildJson));- await upd(P_META, `Harvesting messages from ${channels.length} channels`);+ await updateProgress(P_META, `Harvesting messages from ${channels.length} channels`);const textChannels = channels.filter((c) => GUILD_TEXT_BASED_CHANNEL_TYPES.has(c.type));const pendingDownloads: Array<PendingAttachmentDownload> = [];let processedChannels = 0;- await parallel(textChannels, CHANNEL_CONCURRENCY, async (channel) => {+ await mapWithConcurrency(textChannels, CHANNEL_CONCURRENCY, async (channel) => {const messages: Array<object> = [];let beforeMessageId: MessageID | undefined;let channelDownloads: Array<PendingAttachmentDownload> = [];@@ -220,11 +217,9 @@ const harvestGuildData: WorkerTaskHandler = async (payload, helpers) => {channelDownloads = [];processedChannels++;const pct = P_META + Math.floor((processedChannels / Math.max(textChannels.length, 1)) * (P_MESSAGES - P_META));- upd(pct, `Messages: ${processedChannels}/${textChannels.length} channels`).catch((error: unknown) =>- Logger.warn({error}, 'Failed to report guild archive progress'),- );+ await updateProgress(pct, `Messages: ${processedChannels}/${textChannels.length} channels`);});- await upd(P_MESSAGES, 'Downloading guild assets');+ await updateProgress(P_MESSAGES, 'Downloading guild assets');type AssetJob = {key: string;dest: string;@@ -257,14 +252,14 @@ const harvestGuildData: WorkerTaskHandler = async (payload, helpers) => {dest: path.join(contentDir, 'assets', 'guild', 'stickers', `${id}.${sticker.animated ? 'gif' : 'png'}`),});}- await parallel(assetJobs, ASSET_CONCURRENCY, async ({key, dest}) => {+ await mapWithConcurrency(assetJobs, ASSET_CONCURRENCY, async ({key, dest}) => {await downloadToDisk(storageService, cdnBucket(), key, dest);});- await upd(P_ASSETS, `Downloading ${pendingDownloads.length} attachments`);+ await updateProgress(P_ASSETS, `Downloading ${pendingDownloads.length} attachments`);if (pendingDownloads.length > 0) {let doneCount = 0;let lastPct = P_ASSETS;- await parallel(pendingDownloads, ATTACHMENT_CONCURRENCY, async (dl) => {+ await mapWithConcurrency(pendingDownloads, ATTACHMENT_CONCURRENCY, async (dl) => {const storageKey = makeAttachmentCdnKey(dl.channelId, dl.attachmentId, dl.filename);const dest = path.join(contentDir,@@ -278,43 +273,42 @@ const harvestGuildData: WorkerTaskHandler = async (payload, helpers) => {const newPct = P_ASSETS + Math.floor((doneCount / pendingDownloads.length) * (P_ATTACHMENTS - P_ASSETS));if (newPct > lastPct) {lastPct = newPct;- upd(newPct, `Attachments: ${doneCount}/${pendingDownloads.length}`).catch((error: unknown) =>- Logger.warn({error}, 'Failed to report guild archive progress'),- );+ await updateProgress(newPct, `Attachments: ${doneCount}/${pendingDownloads.length}`);}});}- await upd(P_ATTACHMENTS, 'Creating archive');- await new Promise<void>((resolve, reject) => {- const output = fs.createWriteStream(zipPath);- const arc = archiver('zip', {zlib: {level: 6}});- arc.on('error', reject);- output.on('error', reject);- output.on('close', resolve);- arc.pipe(output);- arc.directory(contentDir, false);- arc.finalize();- });- await upd(P_ZIP, 'Uploading archive');- const expiresAt = new Date(Date.now() + ms('1 year'));- const storageKey = `archives/guilds/${guildId}/${archiveId}/guild-archive.zip`;- const fileSize = BigInt((await fs.promises.stat(zipPath)).size);- await storageService.uploadObject({+ await updateProgress(P_ATTACHMENTS, 'Creating archive');+ await writeZipArchive(zipPath, (archive) => archive.directory(contentDir));+ await updateProgress(P_ZIP, 'Uploading archive');+ storageKey = `archives/guilds/${guildId}/${archiveId}/${attemptId}/guild-archive.zip`;+ const zipStat = await fs.promises.stat(zipPath);+ fileSize = BigInt(zipStat.size);+ await storageService.uploadObjectFromFile({bucket: Config.s3.buckets.harvests,key: storageKey,- body: fs.createReadStream(zipPath),+ filePath: zipPath,+ contentLength: zipStat.size,contentType: 'application/zip',expiresAt,});- await done(storageKey, fileSize, expiresAt);- await upd(P_DONE, 'Completed');} catch (error) {+ if (error instanceof ArchiveAttemptSupersededError) throw error;Logger.error({error, guildId, archiveId}, 'Failed to harvest guild data');- await fail(error instanceof Error ? error.message : String(error));+ const message = error instanceof Error ? error.message : String(error);+ try {+ if (attempt.isLastAttempt) {+ await adminArchiveRepository.markAsTerminallyFailed(adminArchive, message);+ } else {+ await adminArchiveRepository.markAsFailed(adminArchive, message);+ }+ } catch (failureError) {+ if (failureError instanceof ArchiveAttemptSupersededError) throw failureError;+ throw new AggregateError([error, failureError], 'Failed to prepare guild archive and record its failure');+ }+ if (attempt.isLastAttempt) throw new ArchiveTerminalFailureError(message);throw error;- } finally {- await fs.promises.rm(tmpDir, {recursive: true, force: true});}+ await adminArchiveRepository.markAsCompleted(adminArchive, storageKey, fileSize, expiresAt);};-export default harvestGuildData;+export default createArchiveTask(harvestGuildData);diff --git a/fluxer_api/src/api/worker/tasks/HarvestUserData.ts b/fluxer_api/src/api/worker/tasks/HarvestUserData.tsindex a49635f4c..46531be25 100644--- a/fluxer_api/src/api/worker/tasks/HarvestUserData.ts+++ b/fluxer_api/src/api/worker/tasks/HarvestUserData.ts@@ -1,5 +1,6 @@// SPDX-License-Identifier: AGPL-3.0-or-later+import assert from 'node:assert/strict';import fs from 'node:fs';import os from 'node:os';import path from 'node:path';@@ -9,11 +10,15 @@ import {syncedPreferencesToJson,} from '@fluxer/schema/src/domains/user/SyncedPreferencesCodec';import {snowflakeToDate} from '@fluxer/snowflake/src/Snowflake';-import type {WorkerTaskHandler} from '@pkgs/worker/src/contracts/WorkerTask';-import archiver from 'archiver';import {ms} from 'itty-time';import {z} from 'zod';-import type {AdminArchive} from '../../admin/models/AdminArchiveModel';+import {ArchiveAttemptSupersededError} from '../../archive/ArchiveAttemptSupersededError';+import {+ type ArchiveTaskHandler,+ ArchiveTerminalFailureError,+ createArchiveTask,+ throwIfArchiveTerminallyFailed,+} from '../../archive/ArchiveTask';import {type ChannelID,createAttachmentID,@@ -31,6 +36,7 @@ import {type SelfMessageEligibilityContext,type SelfMessageFilter,} from '../../channel/services/message/SelfMessageFilter';+import type {UserConnectionRow} from '../../database/types/ConnectionTypes';import type {IStorageService} from '../../infrastructure/IStorageService';import {Logger} from '../../Logger';import type {Application} from '../../models/Application';@@ -51,12 +57,15 @@ import type {UserGuildSettings} from '../../models/UserGuildSettings';import type {UserSettings} from '../../models/UserSettings';import type {WebAuthnCredential} from '../../models/WebAuthnCredential';import {buildHarvestDownloadUrl} from '../../user/services/HarvestDownloadUrl';+import {mapWithConcurrency} from '../../utils/ConcurrencyUtils';import {resolveSessionClientInfo} from '../../utils/SessionClientIdentity';+import {writeZipArchive} from '../utils/ArchiveFile';import {createArchiveJsonBuffer} from '../utils/ArchiveJson';import {appendAssetToArchive, buildHashedAssetKey, getAnimatedAssetExtension} from '../utils/AssetArchiveHelpers';import {ContentAddressedAttachmentCollector} from '../utils/ContentAddressedAttachmentCollector';import {deserializeSelfMessageFilter, SelfMessageFilterPayload} from '../utils/SelfMessageFilterPayload';import {getWorkerDependencies} from '../WorkerContext';+import type {WorkerDependencies} from '../WorkerDependencies';const PayloadSchema = z.object({userId: z.string(),@@ -120,6 +129,7 @@ interface UserDataJsonParams {createdGiftCodes: Array<GiftCode>;payments: Array<Payment>;oauthClients: Array<Application>;+ connections: Array<UserConnectionRow>;pinnedDms: Array<{channel_id: bigint;sort_order: number;@@ -136,6 +146,8 @@ interface UserDataJsonParams {interface ArchiveParams {userId: UserID;harvestId: bigint;+ attemptId: string;+ expiresAt: Date;isAdminArchive: boolean;includeAttachments: boolean;userDataJsonBuffer: Buffer;@@ -160,15 +172,67 @@ interface ArchiveResult {downloadUrl: string;}+interface PreparedUserArchive {+ user: User;+ totalMessages: number;+ archive: ArchiveResult;+}++interface HarvestProgressReporter {+ attemptId: string;+ expiresAt: Date | null;+ updateProgress(percent: number, step: string): Promise<void>;+ markAsCompleted(storageKey: string, fileSize: bigint, expiresAt: Date): Promise<void>;+ markAsFailed(message: string): Promise<void>;+ markAsTerminallyFailed(message: string): Promise<void>;+}++async function claimUserArchive(+ userId: UserID,+ harvestId: bigint,+ isAdminArchive: boolean,+ {userHarvestRepository, adminArchiveRepository}: WorkerDependencies,+): Promise<HarvestProgressReporter | null> {+ if (isAdminArchive) {+ const archive = await adminArchiveRepository.findBySubjectAndArchiveId('user', userId, harvestId);+ if (!archive) throw new Error(`Admin archive ${harvestId} for user ${userId} not found`);+ throwIfArchiveTerminallyFailed(archive);+ if (archive.completedAt) return null;+ const attempt = await adminArchiveRepository.markAsStarted(archive);+ assert(attempt.attemptId !== null && attempt.expiresAt !== null, 'Claimed admin archive is incomplete');+ return {+ attemptId: attempt.attemptId,+ expiresAt: attempt.expiresAt,+ updateProgress: (percent, step) => adminArchiveRepository.updateProgress(attempt, percent, step),+ markAsCompleted: (key, size, expiry) => adminArchiveRepository.markAsCompleted(attempt, key, size, expiry),+ markAsFailed: (message) => adminArchiveRepository.markAsFailed(attempt, message),+ markAsTerminallyFailed: (message) => adminArchiveRepository.markAsTerminallyFailed(attempt, message),+ };+ }+ const harvest = await userHarvestRepository.findByUserAndHarvestId(userId, harvestId);+ if (!harvest) throw new Error(`Harvest ${harvestId} for user ${userId} not found`);+ throwIfArchiveTerminallyFailed(harvest);+ if (harvest.completedAt) return null;+ const attempt = await userHarvestRepository.markAsStarted(harvest);+ assert(attempt.attemptId !== null, 'Claimed harvest has no attempt ID');+ return {+ attemptId: attempt.attemptId,+ expiresAt: null,+ updateProgress: (percent, step) => userHarvestRepository.updateProgress(attempt, percent, step),+ markAsCompleted: (key, size, expiry) => userHarvestRepository.markAsCompleted(attempt, key, size, expiry),+ markAsFailed: (message) => userHarvestRepository.markAsFailed(attempt, message),+ markAsTerminallyFailed: (message) => userHarvestRepository.markAsTerminallyFailed(attempt, message),+ };+}+// A harvest is every message the account wrote, so the read pages to the end of// the account rather than stopping at a count. The page size is what bounds one// query, not what bounds the archive.const HARVEST_MESSAGE_CHUNK_SIZE = 1000;-const CONCURRENT_MESSAGE_LIMIT = 10;+const HARVEST_READ_CONCURRENCY = 10;const INITIAL_PROGRESS = 5;const MESSAGES_PROGRESS_MAX = 55;const METADATA_PROGRESS = 60;-const COMPLETE_PROGRESS = 100;const ZIP_EXPIRY_MS = ms('7 days');function mapPayment(payment: Payment) {@@ -219,26 +283,25 @@ interface HarvestMessagesFilterArgs {findChannel: (channelId: ChannelID) => Promise<Channel | null>;}+interface HarvestMessageReference {+ channelId: ChannelID;+ messageId: MessageID;+}++interface HarvestMessageRepository {+ listMessagesByAuthor(+ userId: UserID,+ limit: number,+ lastMessageId?: MessageID,+ ): Promise<Array<HarvestMessageReference>>;+ getMessage(+ channelId: ChannelID,+ messageId: MessageID,+ ): Promise<{content: string | null; attachments?: Array<Attachment>} | null>;+}+export async function harvestMessages(- channelRepository: {- listMessagesByAuthor: (- userId: UserID,- limit: number,- lastMessageId?: MessageID,- ) => Promise<- Array<{- channelId: ChannelID;- messageId: MessageID;- }>- >;- getMessage: (- channelId: ChannelID,- messageId: MessageID,- ) => Promise<{- content: string | null;- attachments?: Array<Attachment>;- } | null>;- },+ channelRepository: HarvestMessageRepository,userId: UserID,startTime: number,filterArgs: HarvestMessagesFilterArgs | null,@@ -251,55 +314,34 @@ export async function harvestMessages(let scannedMessages = 0;let totalMessages = 0;- const readMessage = async ({- channelId,- messageId,- }: {- channelId: ChannelID;- messageId: MessageID;- }): Promise<ChannelHarvestResult | null> => {- try {- const message = await channelRepository.getMessage(channelId, messageId);- if (!message) {- Logger.warn(- {channelId: channelId.toString(), messageId: messageId.toString()},- 'Message not found during harvest',- );- return null;- }- const timestamp = snowflakeToDate(messageId);- const attachments: Array<HarvestedAttachment> = [];- if (message.attachments) {- for (const attachment of message.attachments) {- attachments.push({- attachment_id: attachment.id.toString(),- filename: attachment.filename,- size: attachment.size.toString(),- content_type: attachment.contentType,- content_hash: null,- archive_path: null,- cdn_url: makeAttachmentCdnUrl(channelId, attachment.id, attachment.filename),- width: attachment.width,- height: attachment.height,- });- }- }- return {- channelId: channelId.toString(),- messageData: {- id: messageId.toString(),- timestamp: timestamp.toISOString(),- content: message.content ?? '',- attachments,- },- };- } catch (error) {- Logger.error(- {error, channelId: channelId.toString(), messageId: messageId.toString()},- 'Failed to process message during harvest',+ const readMessage = async ({channelId, messageId}: HarvestMessageReference): Promise<ChannelHarvestResult | null> => {+ const message = await channelRepository.getMessage(channelId, messageId);+ if (!message) {+ Logger.warn(+ {channelId: channelId.toString(), messageId: messageId.toString()},+ 'Message not found during harvest',);return null;}+ return {+ channelId: channelId.toString(),+ messageData: {+ id: messageId.toString(),+ timestamp: snowflakeToDate(messageId).toISOString(),+ content: message.content ?? '',+ attachments: (message.attachments ?? []).map((attachment) => ({+ attachment_id: attachment.id.toString(),+ filename: attachment.filename,+ size: attachment.size.toString(),+ content_type: attachment.contentType,+ content_hash: null,+ archive_path: null,+ cdn_url: makeAttachmentCdnUrl(channelId, attachment.id, attachment.filename),+ width: attachment.width,+ height: attachment.height,+ })),+ },+ };};while (true) {@@ -310,7 +352,7 @@ export async function harvestMessages(scannedMessages += page.length;lastMessageId = page[page.length - 1].messageId;- const pageRefs: Array<{channelId: ChannelID; messageId: MessageID}> = [];+ const pageRefs: Array<HarvestMessageReference> = [];for (const ref of page) {if (!filterArgs) {pageRefs.push(ref);@@ -332,20 +374,16 @@ export async function harvestMessages(}}- for (let i = 0; i < pageRefs.length; i += CONCURRENT_MESSAGE_LIMIT) {- const batchResults = await Promise.all(pageRefs.slice(i, i + CONCURRENT_MESSAGE_LIMIT).map(readMessage));- for (const result of batchResults) {- if (result === null) {- continue;- }- let bucket = channelMessagesMap.get(result.channelId);- if (!bucket) {- bucket = [];- channelMessagesMap.set(result.channelId, bucket);- }- bucket.push(result.messageData);- totalMessages++;+ const pageResults = await mapWithConcurrency(pageRefs, HARVEST_READ_CONCURRENCY, readMessage);+ for (const result of pageResults) {+ if (result === null) continue;+ let bucket = channelMessagesMap.get(result.channelId);+ if (!bucket) {+ bucket = [];+ channelMessagesMap.set(result.channelId, bucket);}+ bucket.push(result.messageData);+ totalMessages++;}if (page.length < HARVEST_MESSAGE_CHUNK_SIZE) {@@ -385,6 +423,7 @@ function buildUserDataJson(params: UserDataJsonParams) {createdGiftCodes,payments,oauthClients,+ connections,pinnedDms,authorizedIps,activityData,@@ -588,6 +627,18 @@ function buildUserDataJson(params: UserDataJsonParams) {})),payments: payments.map(mapPayment),oauth_applications: oauthClients.map(mapOAuthApplication),+ connections: connections.map((connection) => ({+ id: connection.connection_id,+ type: connection.connection_type,+ identifier: connection.identifier,+ name: connection.name,+ verified: connection.verified,+ visibility_flags: connection.visibility_flags,+ sort_order: connection.sort_order,+ created_at: connection.created_at.toISOString(),+ verified_at: connection.verified_at?.toISOString() ?? null,+ last_verified_at: connection.last_verified_at?.toISOString() ?? null,+ })),pinned_dms: pinnedDms.map((pin) => ({channel_id: pin.channel_id.toString(),sort_order: pin.sort_order,@@ -600,6 +651,8 @@ async function createAndUploadArchive(params: ArchiveParams): Promise<ArchiveResconst {userId,harvestId,+ attemptId,+ expiresAt,isAdminArchive,includeAttachments,userDataJsonBuffer,@@ -612,14 +665,10 @@ async function createAndUploadArchive(params: ArchiveParams): Promise<ArchiveResstorageService,} = params;const userIdString = userId.toString();- const tempDir = await fs.promises.mkdtemp(path.join(os.tmpdir(), 'fluxer-harvest-'));- const zipPath = path.join(tempDir, `user-data-${userId}.zip`);- let output: fs.WriteStream | null = null;- try {- output = fs.createWriteStream(zipPath);- const archive = archiver('zip', {zlib: {level: 6}});- archive.pipe(output);- archive.append(userDataJsonBuffer, {name: 'user.json'});+ await using tempDir = await fs.promises.mkdtempDisposable(path.join(os.tmpdir(), 'fluxer-harvest-'));+ const zipPath = path.join(tempDir.path, `user-data-${userId}.zip`);+ await writeZipArchive(zipPath, async (archive) => {+ await archive.append(userDataJsonBuffer, {name: 'user.json'});if (user.avatarHash) {const avatarArchiveName = `assets/user/avatar.${getAnimatedAssetExtension(user.avatarHash)}`;const avatarStorageKey = buildHashedAssetKey('avatars', userIdString, user.avatarHash);@@ -664,139 +713,97 @@ async function createAndUploadArchive(params: ArchiveParams): Promise<ArchiveRes}}messages.sort((a, b) => a.timestamp.localeCompare(b.timestamp));- archive.append(createArchiveJsonBuffer(messages), {name: `channels/${channelId}/messages.json`});+ await archive.append(createArchiveJsonBuffer(messages), {name: `channels/${channelId}/messages.json`});}if (collector) {const manifest = collector.getManifest();- archive.append(createArchiveJsonBuffer(manifest), {name: 'attachments_manifest.json'});+ await archive.append(createArchiveJsonBuffer(manifest), {name: 'attachments_manifest.json'});}- archive.append(createArchiveJsonBuffer(payments.map(mapPayment)), {+ await archive.append(createArchiveJsonBuffer(payments.map(mapPayment)), {name: 'payments/payment_history.json',});- archive.append(createArchiveJsonBuffer({applications: oauthClients.map(mapOAuthApplication)}), {+ await archive.append(createArchiveJsonBuffer({applications: oauthClients.map(mapOAuthApplication)}), {name: 'integrations/oauth.json',});- archive.append(createArchiveJsonBuffer(mapSecurityData({authorizedIps, activityData})), {+ await archive.append(createArchiveJsonBuffer(mapSecurityData({authorizedIps, activityData})), {name: 'account/security.json',});- await archive.finalize();- await new Promise<void>((resolve, reject) => {- if (!output) {- reject(new Error('Output stream is null'));- return;- }- output.on('close', resolve);- output.on('error', reject);- });- const storageKey = isAdminArchive- ? `archives/users/${userId}/${harvestId}/user-data.zip`- : `exports/${userId}/${harvestId}/user-data.zip`;- const expiresAt = new Date(Date.now() + (isAdminArchive ? ms('1 year') : ZIP_EXPIRY_MS));- const zipStat = await fs.promises.stat(zipPath);- const fileSize = BigInt(zipStat.size);- await storageService.uploadObject({- bucket: Config.s3.buckets.harvests,- key: storageKey,- body: fs.createReadStream(zipPath),- contentType: 'application/zip',- expiresAt: expiresAt,- });- const downloadUrl = await buildHarvestDownloadUrl({- userId,- harvestId,- storageKey,- expiresInSeconds: ZIP_EXPIRY_MS / 1000,- storageService,- });- return {fileSize, storageKey, expiresAt, downloadUrl};- } finally {- if (output && !output.destroyed) {- output.destroy();- }- await fs.promises.rm(tempDir, {recursive: true, force: true});- }+ });+ const storageKey = isAdminArchive+ ? `archives/users/${userId}/${harvestId}/${attemptId}/user-data.zip`+ : `exports/${userId}/${harvestId}/${attemptId}/user-data.zip`;+ const zipStat = await fs.promises.stat(zipPath);+ const fileSize = BigInt(zipStat.size);+ await storageService.uploadObjectFromFile({+ bucket: Config.s3.buckets.harvests,+ key: storageKey,+ filePath: zipPath,+ contentLength: zipStat.size,+ contentType: 'application/zip',+ expiresAt,+ });+ const downloadUrl = await buildHarvestDownloadUrl({+ userId,+ harvestId,+ storageKey,+ expiresInSeconds: ZIP_EXPIRY_MS / 1000,+ storageService,+ });+ return {fileSize, storageKey, expiresAt, downloadUrl};}-const harvestUserData: WorkerTaskHandler = async (payload, helpers) => {+const harvestUserData: ArchiveTaskHandler = async (payload, helpers, attempt) => {const validated = PayloadSchema.parse(payload);helpers.logger.debug({payload}, 'Processing harvestUserData task');const startTime = Date.now();const userId = createUserID(BigInt(validated.userId));const harvestId = BigInt(validated.harvestId);Logger.info({userId, harvestId, startTime: new Date(startTime).toISOString()}, 'Task started');+ const dependencies = getWorkerDependencies();const {channelRepository,guildRepository,userRepository,- userHarvestRepository,- adminArchiveRepository,favoriteMemeRepository,paymentRepository,applicationRepository,+ connectionRepository,storageService,emailService,instanceConfigRepository,- } = getWorkerDependencies();+ } = dependencies;const adminRequestedBy = validated.adminRequestedBy ? BigInt(validated.adminRequestedBy) : null;const isAdminArchive = adminRequestedBy !== null;- const existingHarvest = isAdminArchive- ? await adminArchiveRepository.findBySubjectAndArchiveId('user', userId, harvestId)- : await userHarvestRepository.findByUserAndHarvestId(userId, harvestId);- if (isAdminArchive && !existingHarvest) {- throw new Error(`Admin archive ${harvestId.toString()} for user ${userId.toString()} not found`);- }- if (existingHarvest?.completedAt) {- Logger.info(- {userId, harvestId, completedAt: existingHarvest.completedAt},- 'Harvest already completed, skipping (idempotent early bailout)',- );+ const progressReporter = await claimUserArchive(userId, harvestId, isAdminArchive, dependencies);+ if (progressReporter === null) {+ Logger.info({userId, harvestId}, 'Harvest already completed, skipping');return;}- const adminArchive = isAdminArchive ? (existingHarvest as AdminArchive) : null;- const progressReporter = {- markAsStarted: () =>- isAdminArchive && adminArchive- ? adminArchiveRepository.markAsStarted(adminArchive)- : userHarvestRepository.markAsStarted(userId, harvestId),- updateProgress: (progressPercent: number, progressStep: string) =>- isAdminArchive && adminArchive- ? adminArchiveRepository.updateProgress(adminArchive, progressPercent, progressStep)- : userHarvestRepository.updateProgress(userId, harvestId, progressPercent, progressStep),- markAsCompleted: (storageKey: string, fileSize: bigint, expiresAt: Date) =>- isAdminArchive && adminArchive- ? adminArchiveRepository.markAsCompleted(adminArchive, storageKey, fileSize, expiresAt)- : userHarvestRepository.markAsCompleted(userId, harvestId, storageKey, fileSize, expiresAt),- markAsFailed: (message: string) =>- isAdminArchive && adminArchive- ? adminArchiveRepository.markAsFailed(adminArchive, message)- : userHarvestRepository.markAsFailed(userId, harvestId, message),- shouldSendEmail: !isAdminArchive,- };- let filterArgs: HarvestMessagesFilterArgs | null = null;- if (validated.filter) {- const filter = deserializeSelfMessageFilter(validated.filter);- const [privateChannelsForFilter, userGuildsForFilter] = await Promise.all([- userRepository.listPrivateChannels(userId),- guildRepository.listUserGuilds(userId),- ]);- const openDmChannelIds = new Set<string>();- for (const channel of privateChannelsForFilter) {- if (channel.type === ChannelTypes.DM || channel.type === ChannelTypes.GROUP_DM) {- openDmChannelIds.add(channel.id.toString());+ let prepared: PreparedUserArchive;+ try {+ let filterArgs: HarvestMessagesFilterArgs | null = null;+ if (validated.filter) {+ const filter = deserializeSelfMessageFilter(validated.filter);+ const [privateChannelsForFilter, userGuildsForFilter] = await Promise.all([+ userRepository.listPrivateChannels(userId),+ guildRepository.listUserGuilds(userId),+ ]);+ const openDmChannelIds = new Set<string>();+ for (const channel of privateChannelsForFilter) {+ if (channel.type === ChannelTypes.DM || channel.type === ChannelTypes.GROUP_DM) {+ openDmChannelIds.add(channel.id.toString());+ }}+ const context: SelfMessageEligibilityContext = {+ currentGuildIds: new Set(userGuildsForFilter.map((guild) => guild.id.toString())),+ openDmChannelIds,+ };+ filterArgs = {+ filter,+ context,+ findChannel: (channelId) => channelRepository.findUnique(channelId),+ };}- const context: SelfMessageEligibilityContext = {- currentGuildIds: new Set(userGuildsForFilter.map((guild) => guild.id.toString())),- openDmChannelIds,- };- filterArgs = {- filter,- context,- findChannel: (channelId) => channelRepository.findUnique(channelId),- };- }- try {- await progressReporter.markAsStarted();Logger.debug({userId, harvestId, elapsed: Date.now() - startTime}, 'Starting user data harvest');await progressReporter.updateProgress(INITIAL_PROGRESS, 'Harvesting messages');Logger.debug({elapsed: Date.now() - startTime}, 'Set progress to INITIAL_PROGRESS');@@ -836,51 +843,39 @@ const harvestUserData: WorkerTaskHandler = async (payload, helpers) => {createdGiftCodes,payments,oauthClients,+ connections,pinnedDms,authorizedIps,activityData,] = await Promise.all([- userRepository.listAuthSessions(userId) as Promise<Array<AuthSession>>,- userRepository.listRelationships(userId) as Promise<Array<Relationship>>,- userRepository.getUserNotes(userId) as Promise<Map<UserID, string>>,- userRepository.findSettings(userId) as Promise<UserSettings | null>,- userRepository.getUserGuildIds(userId) as Promise<Array<GuildID>>,- userRepository.listSavedMessages(userId, 1000) as Promise<Array<SavedMessage>>,- userRepository.listPrivateChannels(userId) as Promise<Array<Channel>>,- favoriteMemeRepository.findByUserId(userId) as Promise<Array<FavoriteMeme>>,- userRepository.listPushSubscriptions(userId) as Promise<Array<PushSubscription>>,- userRepository.listWebAuthnCredentials(userId) as Promise<Array<WebAuthnCredential>>,- userRepository.listMfaBackupCodes(userId) as Promise<Array<MfaBackupCode>>,- userRepository.findGiftCodesByCreator(userId) as Promise<Array<GiftCode>>,- paymentRepository.findPaymentsByUserId(userId) as Promise<Array<Payment>>,- applicationRepository.listApplicationsByOwner(userId) as Promise<Array<Application>>,- userRepository.getPinnedDmsWithDetails(userId) as Promise<- Array<{- channel_id: bigint;- sort_order: number;- }>- >,- userRepository.getAuthorizedIps(userId) as Promise<- Array<{- ip: string;- }>- >,- userRepository.getActivityTracking(userId) as Promise<{- last_active_at: Date | null;- last_active_ip: string | null;- }>,+ userRepository.listAuthSessions(userId),+ userRepository.listRelationships(userId),+ userRepository.getUserNotes(userId),+ userRepository.findSettings(userId),+ userRepository.getUserGuildIds(userId),+ userRepository.listSavedMessages(userId, 1000),+ userRepository.listPrivateChannels(userId),+ favoriteMemeRepository.findByUserId(userId),+ userRepository.listPushSubscriptions(userId),+ userRepository.listWebAuthnCredentials(userId),+ userRepository.listMfaBackupCodes(userId),+ userRepository.findGiftCodesByCreator(userId),+ paymentRepository.findPaymentsByUserId(userId),+ applicationRepository.listApplicationsByOwner(userId),+ connectionRepository.findByUserId(userId),+ userRepository.getPinnedDmsWithDetails(userId),+ userRepository.getAuthorizedIps(userId),+ userRepository.getActivityTracking(userId),]);const guilds = await guildRepository.listGuilds(guildIds);const guildsMap = new Map(guilds.map((guild) => [guild.id.toString(), guild]));- const guildMemberships = await Promise.all(- guildIds.map(async (guildId: GuildID) => {- const member = await guildRepository.getMember(guildId, userId);- const guild = guildsMap.get(guildId.toString()) ?? null;- return {member, guild, guildId};- }),- );- const guildSettings = await Promise.all(- guildIds.map((guildId: GuildID) => userRepository.findGuildSettings(userId, guildId)),+ const guildMemberships = await mapWithConcurrency(guildIds, HARVEST_READ_CONCURRENCY, async (guildId) => {+ const member = await guildRepository.getMember(guildId, userId);+ const guild = guildsMap.get(guildId.toString()) ?? null;+ return {member, guild, guildId};+ });+ const guildSettings = await mapWithConcurrency(guildIds, HARVEST_READ_CONCURRENCY, (guildId) =>+ userRepository.findGuildSettings(userId, guildId),);const {branding} = await instanceConfigRepository.getAppPublicConfig();const userData = buildUserDataJson({@@ -902,6 +897,7 @@ const harvestUserData: WorkerTaskHandler = async (payload, helpers) => {createdGiftCodes,payments,oauthClients,+ connections,pinnedDms,authorizedIps,activityData,@@ -911,9 +907,11 @@ const harvestUserData: WorkerTaskHandler = async (payload, helpers) => {const includeAttachments = validated.includeAttachments && isAdminArchive;await progressReporter.updateProgress(METADATA_PROGRESS + 5, 'Downloading attachments and creating archive');Logger.debug({elapsed: Date.now() - startTime}, 'Starting ZIP creation');- const {fileSize, storageKey, expiresAt, downloadUrl} = await createAndUploadArchive({+ const archive = await createAndUploadArchive({userId,harvestId,+ attemptId: progressReporter.attemptId,+ expiresAt: progressReporter.expiresAt ?? new Date(Date.now() + ZIP_EXPIRY_MS),isAdminArchive,includeAttachments,userDataJsonBuffer,@@ -926,34 +924,12 @@ const harvestUserData: WorkerTaskHandler = async (payload, helpers) => {storageService,});Logger.debug(- {userId, harvestId, zipSize: fileSize.toString(), elapsed: Date.now() - startTime},+ {userId, harvestId, zipSize: archive.fileSize.toString(), elapsed: Date.now() - startTime},'Uploaded final ZIP to S3 with TTL',);- await progressReporter.markAsCompleted(storageKey, fileSize, expiresAt);- Logger.debug({userId, harvestId}, 'Marked harvest as completed');- if (progressReporter.shouldSendEmail && user.email && (await instanceConfigRepository.isEmailEnabled())) {- await emailService.sendHarvestCompletedEmail(- user.email,- user.username,- downloadUrl,- totalMessages,- Number(fileSize),- expiresAt,- user.locale,- );- Logger.debug({userId, harvestId, email: user.email, totalMessages}, 'Sent harvest completion email');- }- await progressReporter.updateProgress(COMPLETE_PROGRESS, 'Completed');- Logger.info(- {- userId,- harvestId,- totalElapsed: Date.now() - startTime,- totalElapsedSeconds: Math.round((Date.now() - startTime) / 1000),- },- 'User data harvest completed successfully',- );+ prepared = {user, totalMessages, archive};} catch (error) {+ if (error instanceof ArchiveAttemptSupersededError) throw error;Logger.error({error,@@ -963,9 +939,45 @@ const harvestUserData: WorkerTaskHandler = async (payload, helpers) => {},'Failed to harvest user data',);- await progressReporter.markAsFailed(String(error));+ const message = error instanceof Error ? error.message : String(error);+ try {+ if (attempt.isLastAttempt) {+ await progressReporter.markAsTerminallyFailed(message);+ } else {+ await progressReporter.markAsFailed(message);+ }+ } catch (statusError) {+ if (statusError instanceof ArchiveAttemptSupersededError) throw statusError;+ throw new AggregateError([error, statusError], 'Harvest preparation and failure recording both failed');+ }+ if (attempt.isLastAttempt) throw new ArchiveTerminalFailureError(message);throw error;}+ const {user, totalMessages, archive} = prepared;+ await progressReporter.markAsCompleted(archive.storageKey, archive.fileSize, archive.expiresAt);+ Logger.debug({userId, harvestId}, 'Marked harvest as completed');+ if (!isAdminArchive && user.email && (await instanceConfigRepository.isEmailEnabled())) {+ const sent = await emailService.sendHarvestCompletedEmail(+ user.email,+ user.username,+ archive.downloadUrl,+ totalMessages,+ Number(archive.fileSize),+ archive.expiresAt,+ user.locale,+ );+ if (!sent) throw new Error(`Completion email for harvest ${harvestId} was not sent`);+ Logger.debug({userId, harvestId, totalMessages}, 'Sent harvest completion email');+ }+ Logger.info(+ {+ userId,+ harvestId,+ totalElapsed: Date.now() - startTime,+ totalElapsedSeconds: Math.round((Date.now() - startTime) / 1000),+ },+ 'User data harvest completed successfully',+ );};-export default harvestUserData;+export default createArchiveTask(harvestUserData);diff --git a/fluxer_api/src/api/worker/tasks/IndexGuildMembers.ts b/fluxer_api/src/api/worker/tasks/IndexGuildMembers.tsindex 1210be3b9..dc50cbac3 100644--- a/fluxer_api/src/api/worker/tasks/IndexGuildMembers.ts+++ b/fluxer_api/src/api/worker/tasks/IndexGuildMembers.ts@@ -7,7 +7,7 @@ import {createGuildID, createUserID} from '../../BrandedTypes';import {Logger} from '../../Logger';import type {User} from '../../models/User';import {getGuildMemberSearchService} from '../../SearchFactory';-import type {IGuildMemberSearchService} from '../../search/IGuildMemberSearchService';+import {chunkArray} from '../../utils/ArrayUtils';import {getWorkerDependencies} from '../WorkerContext';const PayloadSchema = z.object({@@ -18,17 +18,10 @@ const PAGE_SIZE = 1000;const INDEX_CONCURRENCY = 4;const INDEX_CHUNK_SIZE = 500;-function getGuildMemberIndexServices(): Array<IGuildMemberSearchService> {- const services = [getGuildMemberSearchService()].filter(- (service): service is IGuildMemberSearchService => service != null,- );- return Array.from(new Set(services));-}-const indexGuildMembers: WorkerTaskHandler = async (payload, _helpers) => {const validated = PayloadSchema.parse(payload);- const searchServices = getGuildMemberIndexServices();- if (searchServices.length === 0) {+ const searchService = getGuildMemberSearchService();+ if (!searchService) {return;}const guildId = createGuildID(BigInt(validated.guildId));@@ -45,34 +38,15 @@ const indexGuildMembers: WorkerTaskHandler = async (payload, _helpers) => {const uniqueUserIds = Array.from(new Set(members.map((m) => m.userId)));const users = await userRepository.listUsers(uniqueUserIds);const userMap = new Map<UserID, User>(users.map((u) => [u.id, u]));- const membersWithUsers = members- .map((member) => {- const user = userMap.get(member.userId);- return user ? {member, user} : null;- })- .filter((item): item is NonNullable<typeof item> => item != null);- if (membersWithUsers.length > 0) {- if (membersWithUsers.length <= INDEX_CHUNK_SIZE) {- await Promise.all(searchServices.map((searchService) => searchService.indexMembers(membersWithUsers)));- } else {- const chunks: Array<- Array<{- member: (typeof membersWithUsers)[0]['member'];- user: User;- }>- > = [];- for (let i = 0; i < membersWithUsers.length; i += INDEX_CHUNK_SIZE) {- chunks.push(membersWithUsers.slice(i, i + INDEX_CHUNK_SIZE));- }- for (let i = 0; i < chunks.length; i += INDEX_CONCURRENCY) {- const batch = chunks.slice(i, i + INDEX_CONCURRENCY);- await Promise.all(- batch.flatMap((chunk) => searchServices.map((searchService) => searchService.indexMembers(chunk))),- );- }- }- totalIndexed += membersWithUsers.length;+ const membersWithUsers = members.flatMap((member) => {+ const user = userMap.get(member.userId);+ return user ? [{member, user}] : [];+ });+ const chunks = chunkArray(membersWithUsers, INDEX_CHUNK_SIZE);+ for (const batch of chunkArray(chunks, INDEX_CONCURRENCY)) {+ await Promise.all(batch.map((chunk) => searchService.indexMembers(chunk)));}+ totalIndexed += membersWithUsers.length;Logger.debug({guildId: guildId.toString(),diff --git a/fluxer_api/src/api/worker/tasks/ProcessAssetDeletionQueue.ts b/fluxer_api/src/api/worker/tasks/ProcessAssetDeletionQueue.tsindex e822ae0ac..1f3173e49 100644--- a/fluxer_api/src/api/worker/tasks/ProcessAssetDeletionQueue.ts+++ b/fluxer_api/src/api/worker/tasks/ProcessAssetDeletionQueue.ts@@ -1,5 +1,6 @@// SPDX-License-Identifier: AGPL-3.0-or-later+import {SnowflakeType} from '@fluxer/schema/src/primitives/SchemaPrimitives';import type {WorkerTaskHandler} from '@pkgs/worker/src/contracts/WorkerTask';import {createGuildID, createUserID} from '../../BrandedTypes';import {Config} from '../../Config';@@ -8,7 +9,9 @@ import type {IPurgeQueue} from '../../infrastructure/BunnyPurgeQueue';import type {IAssetDeletionQueue,QueuedAssetDeletion,+ QueuedAssetEntityType,QueuedAssetReference,+ QueuedAssetType,} from '../../infrastructure/IAssetDeletionQueue';import type {IStorageService} from '../../infrastructure/IStorageService';import {Logger} from '../../Logger';@@ -24,264 +27,258 @@ interface ProcessItemResult {cdnPurged: boolean;}+interface AssetReferenceRepositories {+ userRepository: Pick<UserRepository, 'findUnique'>;+ guildRepository: Pick<GuildRepository, 'findUnique' | 'getMember'>;+}++interface AssetDeletionDependencies extends AssetReferenceRepositories {+ storageService: IStorageService;+ purgeQueue: IPurgeQueue;+}+const processAssetDeletionQueue: WorkerTaskHandler = async (_payload, _helpers) => {const {assetDeletionQueue, purgeQueue, storageService, userRepository, guildRepository} = getWorkerDependencies();const queueSize = await assetDeletionQueue.getQueueSize();+ if (!Number.isSafeInteger(queueSize) || queueSize < 0) {+ throw new Error('Asset deletion queue size must be a non-negative safe integer');+ }if (queueSize === 0) {Logger.debug('Asset deletion queue is empty');return;}Logger.info({queueSize}, 'Starting asset deletion queue processing');- const maxItems = Math.min(MAX_ITEMS_PER_RUN, queueSize);+ const dependencies: AssetDeletionDependencies = {storageService, purgeQueue, userRepository, guildRepository};+ let remainingReadBudget = Math.min(MAX_ITEMS_PER_RUN, queueSize);let totalProcessed = 0;let totalDeleted = 0;let totalSkipped = 0;let totalFailed = 0;let totalCdnPurged = 0;- while (totalProcessed < maxItems) {- const batch = await assetDeletionQueue.getBatch(Math.min(BATCH_SIZE, maxItems - totalProcessed));- if (batch.length === 0) {- break;- }- const results = await Promise.allSettled(- batch.map((item) =>- processItem(item, {- storageService,- purgeQueue,- assetDeletionQueue,- userRepository,- guildRepository,- }),- ),- );- for (let i = 0; i < results.length; i++) {- const result = results[i]!;- const item = batch[i]!;- if (result.status === 'fulfilled') {- if (result.value.storageDeleted) {- totalDeleted++;- }- if (result.value.storageSkipped) {- totalSkipped++;- }- if (result.value.cdnPurged) {- totalCdnPurged++;+ const failedItems: Array<QueuedAssetDeletion> = [];+ const errors: Array<unknown> = [];+ try {+ while (remainingReadBudget > 0) {+ const count = Math.min(BATCH_SIZE, remainingReadBudget);+ remainingReadBudget -= count;+ const batch = await assetDeletionQueue.getBatch(count);+ const results = await Promise.allSettled(batch.map((item) => processItem(item, dependencies)));+ for (const [index, result] of results.entries()) {+ if (result.status === 'fulfilled') {+ if (result.value.storageDeleted) totalDeleted++;+ if (result.value.storageSkipped) totalSkipped++;+ if (result.value.cdnPurged) totalCdnPurged++;+ continue;}- } else {+ const item = batch[index];totalFailed++;+ failedItems.push(item);Logger.error({error: result.reason, s3Key: item.s3Key, cdnUrl: item.cdnUrl},'Failed to process asset deletion',);}+ totalProcessed += batch.length;}- totalProcessed += batch.length;+ } catch (error) {+ errors.push(error);+ } finally {+ if (totalFailed > 0) {+ errors.push(+ new Error(+ `Asset deletion queue processing completed with ${totalFailed} failures out of ${totalProcessed} items`,+ ),+ );+ }+ errors.push(...(await requeueFailedItems(failedItems, assetDeletionQueue)));}- const remainingSize = await assetDeletionQueue.getQueueSize();- Logger.info(- {- totalProcessed,- totalDeleted,- totalSkipped,- totalFailed,- totalCdnPurged,- remainingSize,- },- 'Finished asset deletion queue processing',- );- if (totalFailed > 0) {- throw new Error(- `Asset deletion queue processing completed with ${totalFailed} failures out of ${totalProcessed} items`,+ try {+ const remainingSize = await assetDeletionQueue.getQueueSize();+ Logger.info(+ {+ totalProcessed,+ totalDeleted,+ totalSkipped,+ totalFailed,+ totalCdnPurged,+ remainingSize,+ },+ 'Finished asset deletion queue processing',);+ } catch (error) {+ errors.push(error);}+ if (errors.length === 1) throw errors[0];+ if (errors.length > 1) throw new AggregateError(errors, 'Asset deletion queue processing and retry failures');};-async function processItem(- item: QueuedAssetDeletion,- deps: {- storageService: IStorageService;- purgeQueue: IPurgeQueue;- assetDeletionQueue: IAssetDeletionQueue;- userRepository: Pick<UserRepository, 'findUnique'>;- guildRepository: Pick<GuildRepository, 'findUnique' | 'getMember'>;- },-): Promise<ProcessItemResult> {- const result: ProcessItemResult = {- storageDeleted: false,- storageSkipped: false,- cdnPurged: false,+async function requeueFailedItems(+ items: ReadonlyArray<QueuedAssetDeletion>,+ queue: IAssetDeletionQueue,+): Promise<Array<unknown>> {+ const errors: Array<unknown> = [];+ for (let offset = 0; offset < items.length; offset += BATCH_SIZE) {+ const batch = items.slice(offset, offset + BATCH_SIZE);+ const results = await Promise.allSettled(batch.map(async (item) => queue.requeueItem(item)));+ for (const [index, result] of results.entries()) {+ if (result.status === 'fulfilled') continue;+ const item = batch[index];+ errors.push(result.reason);+ Logger.error({error: result.reason, s3Key: item.s3Key, cdnUrl: item.cdnUrl}, 'Failed to requeue asset deletion');+ }+ }+ return errors;+}++async function processItem(item: QueuedAssetDeletion, deps: AssetDeletionDependencies): Promise<ProcessItemResult> {+ const storageResult = await processStoredAsset(item, deps);+ if (item.cdnUrl) {+ await deps.purgeQueue.addUrls([item.cdnUrl]);+ Logger.debug({cdnUrl: item.cdnUrl}, 'Queued asset CDN URL for purge');+ }+ return {+ storageDeleted: storageResult === 'deleted',+ storageSkipped: storageResult === 'skipped',+ cdnPurged: Boolean(item.cdnUrl),};+}++async function processStoredAsset(+ item: QueuedAssetDeletion,+ deps: AssetDeletionDependencies,+): Promise<'deleted' | 'skipped' | 'not_requested'> {+ if (!item.s3Key) return 'not_requested';+ if (await isQueuedAssetStillCurrent(item, deps)) {+ Logger.info({s3Key: item.s3Key, reason: item.reason}, 'Skipped deleting currently referenced asset');+ return 'skipped';+ }try {- if (item.s3Key) {- const isStillReferenced = await isQueuedAssetStillCurrent(item, deps);- if (isStillReferenced) {- result.storageSkipped = true;- Logger.info({s3Key: item.s3Key, reason: item.reason}, 'Skipped deleting currently referenced asset');- } else {- try {- await deps.storageService.deleteObject(Config.s3.buckets.cdn, item.s3Key);- result.storageDeleted = true;- Logger.debug({s3Key: item.s3Key, reason: item.reason}, 'Deleted asset from S3');- } catch (error: unknown) {- const isNotFound =- error instanceof Error &&- (('name' in error && error.name === 'NotFound') ||- ('code' in error &&- (- error as {- code?: string;- }- ).code === 'NoSuchKey'));- if (!isNotFound) {- throw error;- }- result.storageDeleted = true;- Logger.debug({s3Key: item.s3Key}, 'Asset already deleted from S3 (NotFound)');- }- }- }- if (item.cdnUrl) {- await deps.purgeQueue.addUrls([item.cdnUrl]);- result.cdnPurged = true;- Logger.debug({cdnUrl: item.cdnUrl}, 'Queued asset CDN URL for purge');- }- return result;+ await deps.storageService.deleteObject(Config.s3.buckets.cdn, item.s3Key);+ Logger.debug({s3Key: item.s3Key, reason: item.reason}, 'Deleted asset from S3');} catch (error) {- await deps.assetDeletionQueue.requeueItem(item);- throw error;+ const isNotFound =+ error instanceof Error && (error.name === 'NotFound' || ('code' in error && error.code === 'NoSuchKey'));+ if (!isNotFound) throw error;+ Logger.debug({s3Key: item.s3Key}, 'Asset already deleted from S3 (NotFound)');}+ return 'deleted';}async function isQueuedAssetStillCurrent(item: QueuedAssetDeletion,- deps: {- userRepository: Pick<UserRepository, 'findUnique'>;- guildRepository: Pick<GuildRepository, 'findUnique' | 'getMember'>;- },+ deps: AssetReferenceRepositories,): Promise<boolean> {- const reference = item.staleReference ?? inferStaleReferenceFromS3Key(item.s3Key);- if (!reference || stripAnimationPrefix(reference.hash) !== getStorageHashFromS3Key(item.s3Key)) {- return false;+ const references = inferAssetReferencesFromS3Key(item.s3Key);+ const {staleReference} = item;+ if (+ staleReference &&+ !references.some(+ (reference) =>+ reference.entityType === staleReference.entityType &&+ reference.assetType === staleReference.assetType &&+ reference.entityId === staleReference.entityId &&+ reference.guildId === staleReference.guildId &&+ reference.hash === stripAnimationPrefix(staleReference.hash),+ )+ ) {+ throw new Error('Asset deletion reference does not match its storage key');}- const currentHash = await getCurrentAssetHash(reference, deps);- return currentHash !== null && stripAnimationPrefix(currentHash) === stripAnimationPrefix(reference.hash);+ for (const reference of references) {+ if (!reference.hash || reference.hash === '.' || reference.hash === '..' || reference.hash.includes('\0')) {+ throw new Error('Asset deletion storage key has an invalid hash component');+ }+ const currentHash = await getCurrentAssetHash(reference, deps);+ if (currentHash !== null && stripAnimationPrefix(currentHash) === reference.hash) return true;+ }+ return false;}async function getCurrentAssetHash(reference: QueuedAssetReference,- deps: {- userRepository: Pick<UserRepository, 'findUnique'>;- guildRepository: Pick<GuildRepository, 'findUnique' | 'getMember'>;- },+ deps: AssetReferenceRepositories,): Promise<string | null> {- const entityId = parseDecimalBigInt(reference.entityId);- if (entityId === null) {- return null;- }- if (reference.entityType === 'user') {+ const entityId = parseAssetEntityId(reference.entityId, 'entityId');+ const {assetType} = reference;+ if (reference.entityType === 'user' && (assetType === 'avatar' || assetType === 'banner')) {const user = await deps.userRepository.findUnique(createUserID(entityId));- if (!user) {- return null;- }- switch (reference.assetType) {- case 'avatar':- return user.avatarHash;- case 'banner':- return user.bannerHash;- default:- return null;- }+ return (assetType === 'avatar' ? user?.avatarHash : user?.bannerHash) ?? null;}if (reference.entityType === 'guild') {const guild = await deps.guildRepository.findUnique(createGuildID(entityId));- if (!guild) {- return null;- }- switch (reference.assetType) {+ switch (assetType) {case 'icon':- return guild.iconHash;+ return guild?.iconHash ?? null;case 'banner':- return guild.bannerHash;+ return guild?.bannerHash ?? null;case 'splash':- return guild.splashHash;+ return guild?.splashHash ?? null;case 'embed_splash':- return guild.embedSplashHash;- default:- return null;+ return guild?.embedSplashHash ?? null;}}- if (reference.entityType === 'guild_member') {- const guildId = reference.guildId ? parseDecimalBigInt(reference.guildId) : null;- if (guildId === null) {- return null;- }+ if (reference.entityType === 'guild_member' && (assetType === 'avatar' || assetType === 'banner')) {+ const guildId = parseAssetEntityId(reference.guildId, 'guildId');const member = await deps.guildRepository.getMember(createGuildID(guildId), createUserID(entityId));- if (!member) {- return null;- }- switch (reference.assetType) {- case 'avatar':- return member.avatarHash;- case 'banner':- return member.bannerHash;- default:- return null;- }+ return (assetType === 'avatar' ? member?.avatarHash : member?.bannerHash) ?? null;}- return null;+ throw new Error('Asset deletion reference has an unsupported entity and asset combination');}-function inferStaleReferenceFromS3Key(s3Key: string): QueuedAssetReference | null {+function inferAssetReferencesFromS3Key(s3Key: string): Array<QueuedAssetReference> {const parts = s3Key.split('/');- if (parts.length === 3) {- const [prefix, entityId, hash] = parts;- switch (prefix) {- case 'avatars':- return {entityType: 'user', assetType: 'avatar', entityId: entityId!, hash: hash!};- case 'icons':- return {entityType: 'guild', assetType: 'icon', entityId: entityId!, hash: hash!};- case 'splashes':- return {entityType: 'guild', assetType: 'splash', entityId: entityId!, hash: hash!};- case 'embed-splashes':- return {entityType: 'guild', assetType: 'embed_splash', entityId: entityId!, hash: hash!};- default:- return null;- }- }- if (- parts.length === 6 &&- parts[0] === 'guilds' &&- parts[2] === 'users' &&- (parts[4] === 'avatars' || parts[4] === 'banners')- ) {- return {- entityType: 'guild_member',- assetType: parts[4] === 'avatars' ? 'avatar' : 'banner',- guildId: parts[1]!,- entityId: parts[3]!,- hash: parts[5]!,- };+ switch (parts[0]) {+ case 'avatars':+ return [createAssetReference(parts, 'user', 'avatar')];+ case 'icons':+ return [createAssetReference(parts, 'guild', 'icon')];+ case 'splashes':+ return [createAssetReference(parts, 'guild', 'splash')];+ case 'embed-splashes':+ return [createAssetReference(parts, 'guild', 'embed_splash')];+ case 'banners':+ return [createAssetReference(parts, 'user', 'banner'), createAssetReference(parts, 'guild', 'banner')];+ case 'branding':+ throw new Error('Branding asset deletion requires an instance reference lookup');+ case 'guilds':+ if (parts.length !== 6 || parts[2] !== 'users' || (parts[4] !== 'avatars' && parts[4] !== 'banners')) {+ throw new Error('Asset deletion storage key has an invalid guild member path');+ }+ return [+ {+ entityType: 'guild_member',+ assetType: parts[4] === 'avatars' ? 'avatar' : 'banner',+ guildId: parts[1],+ entityId: parts[3],+ hash: parts[5],+ },+ ];+ default:+ return [];}- return null;}-function parseDecimalBigInt(value: string): bigint | null {- if (!/^\d+$/.test(value)) {- return null;+function createAssetReference(+ parts: Array<string>,+ entityType: QueuedAssetEntityType,+ assetType: QueuedAssetType,+): QueuedAssetReference {+ if (parts.length !== 3) {+ throw new Error('Asset deletion storage key must contain an asset prefix, entity ID and hash');}- try {- return BigInt(value);- } catch {- return null;+ return {entityType, assetType, entityId: parts[1], hash: parts[2]};+}++function parseAssetEntityId(value: string | undefined, field: 'entityId' | 'guildId'): bigint {+ if (!value || value.length > 19 || /\D/.test(value)) {+ throw new Error(`Asset deletion reference has an invalid ${field}`);}+ const parsed = SnowflakeType.safeParse(value);+ if (!parsed.success) throw new Error(`Asset deletion reference has an invalid ${field}`);+ return parsed.data;}function stripAnimationPrefix(hash: string): string {return hash.startsWith('a_') ? hash.substring(2) : hash;}-function getStorageHashFromS3Key(s3Key: string): string | null {- return s3Key.split('/').pop() ?? null;-}-export default processAssetDeletionQueue;diff --git a/fluxer_api/src/api/worker/tasks/ProcessBunnyPurgeQueue.ts b/fluxer_api/src/api/worker/tasks/ProcessBunnyPurgeQueue.tsindex 001b9237b..e3a3456bd 100644--- a/fluxer_api/src/api/worker/tasks/ProcessBunnyPurgeQueue.ts+++ b/fluxer_api/src/api/worker/tasks/ProcessBunnyPurgeQueue.ts@@ -1,5 +1,6 @@// SPDX-License-Identifier: AGPL-3.0-or-later+import {formatUrlForDiagnostics} from '@pkgs/http_client/src/HttpClientDiagnostics';import type {WorkerTaskHandler} from '@pkgs/worker/src/contracts/WorkerTask';import {ms} from 'itty-time';import {Config} from '../../Config';@@ -59,6 +60,7 @@ async function purgeUrls(signal: AbortSignal.timeout(ms('30 seconds')),});if (response.status === 429) {+ FetchUtils.discardResponseBody(response.body, response.status);const remaining = urls.slice(index);await queue.addUrls(remaining);stats.requeued += remaining.length;@@ -68,21 +70,30 @@ async function purgeUrls(}if (!response.ok) {stats.failures++;- const errorText = await FetchUtils.streamToStringWithLimit(response.body, {+ const errorBody = await FetchUtils.streamToBufferWithLimit(response.body, {maxBytes: EXTERNAL_RESPONSE_LIMITS.bunnyErrorBytes,headers: response.headers,url: response.url,description: 'Bunny CDN purge response',});- Logger.error({status: response.status, error: errorText, url, label}, 'Failed to purge URL via Bunny CDN');+ Logger.error(+ {+ status: response.status,+ responseBodyBytes: errorBody.byteLength,+ url: formatUrlForDiagnostics(url),+ label,+ },+ 'Failed to purge URL via Bunny CDN',+ );await queue.addUrls([url]);stats.requeued++;continue;}+ FetchUtils.discardResponseBody(response.body, response.status);stats.purged++;} catch (error) {stats.failures++;- Logger.error({error, url, label}, 'Error purging URL via Bunny CDN');+ Logger.error({error, url: formatUrlForDiagnostics(url), label}, 'Error purging URL via Bunny CDN');await queue.addUrls([url]);stats.requeued++;}diff --git a/fluxer_api/src/api/worker/tasks/ProcessExpiredPremiumSweep.ts b/fluxer_api/src/api/worker/tasks/ProcessExpiredPremiumSweep.tsindex a1314b9e2..b9db9a3fe 100644--- a/fluxer_api/src/api/worker/tasks/ProcessExpiredPremiumSweep.ts+++ b/fluxer_api/src/api/worker/tasks/ProcessExpiredPremiumSweep.ts@@ -192,12 +192,11 @@ async function processExpiredPremiumSweepCore(deps: SweepDeps): Promise<SweepRes}Logger.debug('Starting expired premium sweep');let pageState: string | null = null;- while (true) {+ do {const page = await deps.userRepository.scanAllUsersPage(BATCH_SIZE, pageState);+ pageState = page.pageState;const users = page.users;- if (users.length === 0) {- break;- }+ if (users.length === 0) continue;for (const user of users) {try {await processUser(user, deps, result);@@ -207,17 +206,13 @@ async function processExpiredPremiumSweepCore(deps: SweepDeps): Promise<SweepRes}}result.processed += users.length;- pageState = page.pageState;if (result.processed % 1000 === 0) {Logger.debug({processed: result.processed, stripped: result.stripped, sanitized: result.sanitized},'Expired premium sweep progress',);}- if (!pageState) {- break;- }- }+ } while (pageState);Logger.info({processed: result.processed,diff --git a/fluxer_api/src/api/worker/tasks/ProcessInactivityDeletions.ts b/fluxer_api/src/api/worker/tasks/ProcessInactivityDeletions.tsindex 2ed0fef8c..18d758eee 100644--- a/fluxer_api/src/api/worker/tasks/ProcessInactivityDeletions.ts+++ b/fluxer_api/src/api/worker/tasks/ProcessInactivityDeletions.ts@@ -36,15 +36,11 @@ async function scheduleDeletion(): Promise<void> {const gracePeriodMs = Config.deletionGracePeriodHours * ms('1 hour');const pendingDeletionAt = new Date(Date.now() + gracePeriodMs);- await userRepository.patchUpsert(- userId,- {- flags: user.flags | UserFlags.SELF_DELETED,- pending_deletion_at: pendingDeletionAt,- deletion_reason_code: DeletionReasons.INACTIVITY,- },- user.toRow(),- );+ await userRepository.updateDeletionSchedule(user, {+ flags: user.flags | UserFlags.SELF_DELETED,+ pending_deletion_at: pendingDeletionAt,+ deletion_reason_code: DeletionReasons.INACTIVITY,+ });await reschedulePendingDeletion({userId,currentPendingDeletionAt: user.pendingDeletionAt,@@ -197,12 +193,11 @@ export async function processInactivityDeletionsCore(};let pageState: string | null = null;let processedUsers = 0;- while (true) {+ do {const page = await userRepository.scanAllUsersPage(BATCH_SIZE, pageState);+ pageState = page.pageState;const users = page.users;- if (users.length === 0) {- break;- }+ if (users.length === 0) continue;const pageActivities = await loadPageActivities(activityTracker, users);await mapWithConcurrency(users, USER_PROCESSING_CONCURRENCY, async (user) => {try {@@ -213,17 +208,13 @@ export async function processInactivityDeletionsCore(}});processedUsers += users.length;- pageState = page.pageState;if (processedUsers % 1000 === 0) {Logger.debug({processedUsers, warningsSent: result.warningsSent, deletionsScheduled: result.deletionsScheduled},'Inactivity deletion progress',);}- if (!pageState) {- break;- }- }+ } while (pageState);Logger.info({processedUsers,diff --git a/fluxer_api/src/api/worker/tasks/ProcessPendingBulkMessageDeletions.ts b/fluxer_api/src/api/worker/tasks/ProcessPendingBulkMessageDeletions.tsindex a902fdd2c..0983a6802 100644--- a/fluxer_api/src/api/worker/tasks/ProcessPendingBulkMessageDeletions.ts+++ b/fluxer_api/src/api/worker/tasks/ProcessPendingBulkMessageDeletions.ts@@ -3,6 +3,7 @@import type {WorkerTaskHandler} from '@pkgs/worker/src/contracts/WorkerTask';import {createUserID} from '../../BrandedTypes';import {Logger} from '../../Logger';+import {getValidTimestamp} from '../../utils/TimestampUtils';import {getWorkerDependencies} from '../WorkerContext';const processPendingBulkMessageDeletions: WorkerTaskHandler = async (_payload, helpers) => {@@ -17,9 +18,15 @@ const processPendingBulkMessageDeletions: WorkerTaskHandler = async (_payload, h}try {await bulkMessageDeletionQueueService.rebuildState();- } finally {- await bulkMessageDeletionQueueService.releaseRebuildLock(lockToken);+ } catch (error) {+ try {+ await bulkMessageDeletionQueueService.releaseRebuildLock(lockToken);+ } catch (releaseError) {+ Logger.error({error: releaseError}, 'Failed to release bulk message deletion queue lock after rebuild failure');+ }+ throw error;}+ await bulkMessageDeletionQueueService.releaseRebuildLock(lockToken);}const nowMs = Date.now();const pendingDeletions = await bulkMessageDeletionQueueService.getReadyDeletions(nowMs, 100);@@ -28,19 +35,19 @@ const processPendingBulkMessageDeletions: WorkerTaskHandler = async (_payload, htry {const userId = createUserID(deletion.userId);const user = await userRepository.findUnique(userId);- if (!user) {- await bulkMessageDeletionQueueService.removeFromQueue(userId);- continue;- }- if (!user.pendingBulkMessageDeletionAt) {+ if (!user?.pendingBulkMessageDeletionAt) {await bulkMessageDeletionQueueService.removeFromQueue(userId);continue;}- if (user.pendingBulkMessageDeletionAt.getTime() > nowMs) {+ const scheduledAt = getValidTimestamp(+ user.pendingBulkMessageDeletionAt,+ `Pending bulk message deletion timestamp for user ${userId}`,+ );+ if (scheduledAt > nowMs) {Logger.debug({userId: userId.toString(),- scheduledAt: user.pendingBulkMessageDeletionAt.getTime(),+ scheduledAt,},'Requeueing pending bulk message deletion that is not due yet',);@@ -51,14 +58,14 @@ const processPendingBulkMessageDeletions: WorkerTaskHandler = async (_payload, h'bulkDeleteUserMessages',{userId: userId.toString(),- scheduledAt: user.pendingBulkMessageDeletionAt.getTime(),+ scheduledAt,},{maxAttempts: 5},);Logger.debug({userId: userId.toString(),- scheduledAt: user.pendingBulkMessageDeletionAt.getTime(),+ scheduledAt,},'Queued worker job for pending bulk message deletion',);diff --git a/fluxer_api/src/api/worker/tasks/ProcessStripeWebhook.ts b/fluxer_api/src/api/worker/tasks/ProcessStripeWebhook.tsindex fba080f65..5560dba1c 100644--- a/fluxer_api/src/api/worker/tasks/ProcessStripeWebhook.ts+++ b/fluxer_api/src/api/worker/tasks/ProcessStripeWebhook.ts@@ -2,9 +2,8 @@import type {WorkerTaskHandler} from '@pkgs/worker/src/contracts/WorkerTask';import {z} from 'zod';+import {revokeAllAuthSessions} from '../../auth/AuthSessionRevocation';import type {ISessionTerminator} from '../../auth/ISessionTerminator';-import type {UserID} from '../../BrandedTypes';-import type {IGatewayService} from '../../infrastructure/IGatewayService';import {ProductRegistry} from '../../stripe/ProductRegistry';import {AgeVerificationService} from '../../stripe/services/AgeVerificationService';import {StripeCheckoutService} from '../../stripe/services/StripeCheckoutService';@@ -13,7 +12,6 @@ import {StripePremiumService} from '../../stripe/services/StripePremiumService';import {StripeRefundService} from '../../stripe/services/StripeRefundService';import {StripeSubscriptionService} from '../../stripe/services/StripeSubscriptionService';import {StripeWebhookService} from '../../stripe/services/StripeWebhookService';-import type {IUserRepositoryAggregate} from '../../user/repositories/IUserRepositoryAggregate';import {getWorkerDependencies} from '../WorkerContext';const PayloadSchema = z.object({@@ -21,26 +19,6 @@ const PayloadSchema = z.object({signature: z.string(),});-class WorkerSessionTerminator implements ISessionTerminator {- constructor(- private repository: IUserRepositoryAggregate,- private gatewayService: IGatewayService,- ) {}-- async terminateAllUserSessions(userId: UserID): Promise<void> {- const authSessions = await this.repository.listAuthSessions(userId);- await this.repository.deleteAllPushSubscriptions(userId);- await this.gatewayService.invalidatePushSubscriptions({userId});- if (authSessions.length === 0) return;- const hashes = authSessions.map((s) => s.sessionIdHash);- await this.repository.deleteAuthSessions(userId, hashes);- await this.gatewayService.terminateSession({- userId,- sessionIdHashes: authSessions.map((s) => Buffer.from(s.sessionIdHash).toString('base64url')),- });- }-}-const processStripeWebhook: WorkerTaskHandler = async (payload, helpers) => {const {body, signature} = PayloadSchema.parse(payload);const deps = getWorkerDependencies();@@ -49,7 +27,11 @@ const processStripeWebhook: WorkerTaskHandler = async (payload, helpers) => {return;}const productRegistry = new ProductRegistry();- const sessionTerminator = new WorkerSessionTerminator(deps.userRepository, deps.gatewayService);+ const sessionTerminator: ISessionTerminator = {+ async terminateAllUserSessions(userId) {+ await revokeAllAuthSessions({users: deps.userRepository, gateway: deps.gatewayService}, userId);+ },+ };const premiumService = new StripePremiumService(deps.userRepository,deps.gatewayService,diff --git a/fluxer_api/src/api/worker/tasks/RefreshSearchIndex.ts b/fluxer_api/src/api/worker/tasks/RefreshSearchIndex.tsindex 410b065d8..e77616d0b 100644--- a/fluxer_api/src/api/worker/tasks/RefreshSearchIndex.ts+++ b/fluxer_api/src/api/worker/tasks/RefreshSearchIndex.ts@@ -87,7 +87,7 @@ async function reportInProgress(interface PaginateAndIndexOptions<TCursor, TItem> {fetchPage: (cursor: TCursor | undefined) => Promise<Array<TItem>>;- indexBatch: (items: Array<TItem>) => Promise<void>;+ indexBatch: (items: Array<TItem>) => Promise<number>;getCursor: (item: TItem) => TCursor;label: string;kvClient: IKVProvider;@@ -102,11 +102,13 @@ async function paginateAndIndex<TCursor, TItem>(options: PaginateAndIndexOptionswhile (hasMore) {const items = await options.fetchPage(cursor);if (items.length > 0) {- await options.indexBatch(items);- indexedCount += items.length;+ const batchCount = await options.indexBatch(items);+ indexedCount += batchCount;cursor = options.getCursor(items[items.length - 1]!);- await reportInProgress(options.kvClient, options.progressKey, options.indexType, indexedCount);- Logger.debug({count: items.length, total: indexedCount}, `Indexed ${options.label} batch`);+ if (batchCount > 0) {+ await reportInProgress(options.kvClient, options.progressKey, options.indexType, indexedCount);+ Logger.debug({count: batchCount, total: indexedCount}, `Indexed ${options.label} batch`);+ }}hasMore = items.length === BATCH_SIZE;}@@ -127,7 +129,10 @@ const refreshGuilds: IndexHandler = async (_payload, _helpers, kvClient, progresawait searchService.deleteAllDocuments();return paginateAndIndex({fetchPage: (cursor?: GuildID) => guildRepository.listAllGuildsPaginated(BATCH_SIZE, cursor),- indexBatch: (guilds) => searchService.indexGuilds(guilds),+ indexBatch: async (guilds) => {+ await searchService.indexGuilds(guilds);+ return guilds.length;+ },getCursor: (guild) => guild.id,label: 'guild',kvClient,@@ -141,21 +146,16 @@ const refreshUsers: IndexHandler = async (_payload, _helpers, kvClient, progressawait searchService.deleteAllDocuments();let pageState: string | null = null;let indexedCount = 0;- while (true) {+ do {const page = await userRepository.scanAllUsersPage(BATCH_SIZE, pageState);+ pageState = page.pageState;const users = page.users;- if (users.length === 0) {- break;- }+ if (users.length === 0) continue;await searchService.indexUsers(users);indexedCount += users.length;await reportInProgress(kvClient, progressKey, 'users', indexedCount);Logger.debug({count: users.length, total: indexedCount}, 'Indexed user batch');- pageState = page.pageState;- if (!pageState) {- break;- }- }+ } while (pageState);Logger.debug({count: indexedCount}, 'Refreshed user search index');return indexedCount;};@@ -165,7 +165,10 @@ const refreshReports: IndexHandler = async (_payload, _helpers, kvClient, progreawait searchService.deleteAllDocuments();return paginateAndIndex({fetchPage: (cursor?: ReportID) => reportRepository.listAllReportsPaginated(BATCH_SIZE, cursor),- indexBatch: (reports) => searchService.indexReports(reports),+ indexBatch: async (reports) => {+ await searchService.indexReports(reports);+ return reports.length;+ },getCursor: (report) => report.reportId,label: 'report',kvClient,@@ -179,7 +182,10 @@ const refreshAuditLogs: IndexHandler = async (_payload, _helpers, kvClient, progawait searchService.deleteAllDocuments();return paginateAndIndex({fetchPage: (cursor?: bigint) => adminRepository.listAllAuditLogsPaginated(BATCH_SIZE, cursor),- indexBatch: (logs) => searchService.indexAuditLogs(logs),+ indexBatch: async (logs) => {+ await searchService.indexAuditLogs(logs);+ return logs.length;+ },getCursor: (log) => log.logId,label: 'audit log',kvClient,@@ -227,20 +233,21 @@ const refreshGuildMembers: IndexHandler = async (payload, _helpers, kvClient, prconst searchService = requireSearchService<IGuildMemberSearchService>(getGuildMemberSearchService());await searchService.deleteGuildMembers(guildId);const indexedCount = await paginateAndIndex({- fetchPage: async (cursor?: UserID) => {- const members = await guildRepository.listMembersPaginated(guildId, BATCH_SIZE, cursor);+ fetchPage: (cursor?: UserID) => guildRepository.listMembersPaginated(guildId, BATCH_SIZE, cursor),+ indexBatch: async (members) => {const uniqueUserIds = Array.from(new Set(members.map((m) => m.userId)));const users = await userRepository.listUsers(uniqueUserIds);const userMap = new Map<UserID, User>(users.map((u) => [u.id, u]));- return members- .map((member) => {- const user = userMap.get(member.userId);- return user ? {member, user} : null;- })- .filter((item): item is NonNullable<typeof item> => item != null);+ const membersWithUsers = members.flatMap((member) => {+ const user = userMap.get(member.userId);+ return user ? [{member, user}] : [];+ });+ if (membersWithUsers.length > 0) {+ await searchService.indexMembers(membersWithUsers);+ }+ return membersWithUsers.length;},- indexBatch: (membersWithUsers) => searchService.indexMembers(membersWithUsers),- getCursor: (item) => item.member.userId,+ getCursor: (member) => member.userId,label: 'guild member',kvClient,progressKey,diff --git a/fluxer_api/src/api/worker/tasks/RevalidateUserConnections.ts b/fluxer_api/src/api/worker/tasks/RevalidateUserConnections.tsdeleted file mode 100644index 626d117c2..000000000--- a/fluxer_api/src/api/worker/tasks/RevalidateUserConnections.ts+++ /dev/null@@ -1,69 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import type {WorkerTaskHandler} from '@pkgs/worker/src/contracts/WorkerTask';-import {z} from 'zod';-import {createUserID} from '../../BrandedTypes';-import {mapConnectionToResponse} from '../../connection/ConnectionMappers';-import {Logger} from '../../Logger';-import {getWorkerDependencies} from '../WorkerContext';--const PayloadSchema = z.object({- userId: z.string(),-});-const revalidateUserConnections: WorkerTaskHandler = async (payload, helpers) => {- const validated = PayloadSchema.parse(payload);- helpers.logger.debug({payload: validated}, 'Processing revalidateUserConnections task');- const userId = createUserID(BigInt(validated.userId));- const {connectionRepository, connectionService, gatewayService} = getWorkerDependencies();- const connections = await connectionRepository.findByUserId(userId);- const verifiedConnections = connections.filter((conn) => conn.verified);- if (verifiedConnections.length === 0) {- helpers.logger.debug({userId: userId.toString()}, 'No verified connections to revalidate');- return;- }- let hasChanges = false;- for (const connection of verifiedConnections) {- try {- const {isValid, updateParams} = await connectionService.revalidateConnection(connection);- if (updateParams) {- await connectionRepository.update(userId, connection.connection_type, connection.connection_id, updateParams);- hasChanges = true;- if (!isValid) {- Logger.info(- {- userId: userId.toString(),- connectionId: connection.connection_id,- connectionType: connection.connection_type,- },- 'Connection verification failed, marked as unverified',- );- }- }- } catch (error) {- Logger.error(- {- error,- userId: userId.toString(),- connectionId: connection.connection_id,- connectionType: connection.connection_type,- },- 'Failed to revalidate connection',- );- }- }- if (hasChanges) {- const updatedConnections = await connectionRepository.findByUserId(userId);- await gatewayService.dispatchPresence({- userId,- event: 'USER_CONNECTIONS_UPDATE',- data: {connections: updatedConnections.map(mapConnectionToResponse)},- });- Logger.info({userId: userId.toString()}, 'Dispatched USER_CONNECTIONS_UPDATE event');- }- helpers.logger.debug(- {userId: userId.toString(), checked: verifiedConnections.length, hasChanges},- 'Completed connection revalidation',- );-};--export default revalidateUserConnections;diff --git a/fluxer_api/src/api/worker/tasks/SyncDisposableEmailDomains.ts b/fluxer_api/src/api/worker/tasks/SyncDisposableEmailDomains.tsindex 4d3e3af3f..cd86efc06 100644--- a/fluxer_api/src/api/worker/tasks/SyncDisposableEmailDomains.ts+++ b/fluxer_api/src/api/worker/tasks/SyncDisposableEmailDomains.ts@@ -36,7 +36,10 @@ interface SourceCollectResult {async function fetchSource(url: string): Promise<SourceFetchResult> {const res = await fetch(url, {signal: AbortSignal.timeout(60000)});- if (!res.ok) throw new Error(`HTTP ${res.status} fetching ${url}`);+ if (!res.ok) {+ FetchUtils.discardResponseBody(res.body, res.status);+ throw new Error(`HTTP ${res.status} fetching ${url}`);+ }const contentType = res.headers.get('content-type') ?? '';const responseText = await FetchUtils.streamToStringWithLimit(res.body, {maxBytes: EXTERNAL_RESPONSE_LIMITS.disposableEmailBytes,@@ -62,7 +65,7 @@ function forEachTextLine(text: string, callback: (line: string) => void): numberfor (let i = 0; i <= text.length; i++) {const isEnd = i === text.length;if (!isEnd && text.charCodeAt(i) !== 10) continue;- const line = text.slice(start, isEnd ? i : i).trim();+ const line = text.slice(start, i).trim();start = i + 1;if (!line || line.startsWith('#')) continue;raw++;diff --git a/fluxer_api/src/api/worker/tasks/SyncFileShaBlocklists.ts b/fluxer_api/src/api/worker/tasks/SyncFileShaBlocklists.tsindex 50c6ddfcd..107225644 100644--- a/fluxer_api/src/api/worker/tasks/SyncFileShaBlocklists.ts+++ b/fluxer_api/src/api/worker/tasks/SyncFileShaBlocklists.ts@@ -15,7 +15,10 @@ const syncFileShaBlocklists: WorkerTaskHandler = async (_payload, helpers) => {let added = 0;try {const res = await fetch(MALWARE_BAZAAR_SHA256_URL, {signal: AbortSignal.timeout(120000)});- if (!res.ok) throw new Error(`HTTP ${res.status}`);+ if (!res.ok) {+ FetchUtils.discardResponseBody(res.body, res.status);+ throw new Error(`HTTP ${res.status}`);+ }const text = await FetchUtils.streamToStringWithLimit(res.body, {maxBytes: EXTERNAL_RESPONSE_LIMITS.fileBlocklistBytes,headers: res.headers,diff --git a/fluxer_api/src/api/worker/tasks/SyncUrlBlocklists.ts b/fluxer_api/src/api/worker/tasks/SyncUrlBlocklists.tsindex fa67d801d..751f02808 100644--- a/fluxer_api/src/api/worker/tasks/SyncUrlBlocklists.ts+++ b/fluxer_api/src/api/worker/tasks/SyncUrlBlocklists.ts@@ -49,7 +49,10 @@ const FEED_SOURCES: Array<FeedSource> = [async function fetchFeed(source: FeedSource): Promise<Array<string>> {const res = await fetch(source.url, {signal: AbortSignal.timeout(120000)});- if (!res.ok) throw new Error(`HTTP ${res.status} fetching ${source.url}`);+ if (!res.ok) {+ FetchUtils.discardResponseBody(res.body, res.status);+ throw new Error(`HTTP ${res.status} fetching ${source.url}`);+ }const text = await FetchUtils.streamToStringWithLimit(res.body, {maxBytes: EXTERNAL_RESPONSE_LIMITS.urlBlocklistBytes,headers: res.headers,diff --git a/fluxer_api/src/api/worker/tasks/UserProcessPendingDeletion.ts b/fluxer_api/src/api/worker/tasks/UserProcessPendingDeletion.tsindex 5bd1f746f..ef1556899 100644--- a/fluxer_api/src/api/worker/tasks/UserProcessPendingDeletion.ts+++ b/fluxer_api/src/api/worker/tasks/UserProcessPendingDeletion.ts@@ -10,6 +10,7 @@ import {getWorkerDependencies} from '../WorkerContext';const PayloadSchema = z.object({userId: z.string(),deletionReasonCode: z.number(),+ pendingDeletionAt: z.iso.datetime().optional(),});const userProcessPendingDeletion: WorkerTaskHandler = async (payload, helpers) => {const validated = PayloadSchema.parse(payload);@@ -17,7 +18,14 @@ const userProcessPendingDeletion: WorkerTaskHandler = async (payload, helpers) =const userId = createUserID(BigInt(validated.userId));try {const deps = getWorkerDependencies();- await processUserDeletion(userId, validated.deletionReasonCode, deps);+ const scheduledAt = validated.pendingDeletionAt+ ? new Date(validated.pendingDeletionAt)+ : ((await deps.userRepository.findUnique(userId))?.pendingDeletionAt ?? null);+ if (scheduledAt === null) {+ Logger.info({userId}, 'Account deletion schedule is no longer eligible');+ return;+ }+ await processUserDeletion(userId, scheduledAt, validated.deletionReasonCode, deps);} catch (error) {Logger.error({error, userId}, 'Failed to delete user account');throw error;diff --git a/fluxer_api/src/api/worker/tasks/UserProcessPendingDeletions.ts b/fluxer_api/src/api/worker/tasks/UserProcessPendingDeletions.tsindex 35f344e37..13b21bda4 100644--- a/fluxer_api/src/api/worker/tasks/UserProcessPendingDeletions.ts+++ b/fluxer_api/src/api/worker/tasks/UserProcessPendingDeletions.ts@@ -7,6 +7,7 @@ import {isPendingDeletionBlocked,resolvePendingDeletionReasonCode,} from '../../user/services/PendingDeletionCoordinator';+import {getValidTimestamp} from '../../utils/TimestampUtils';import {getWorkerDependencies} from '../WorkerContext';const userProcessPendingDeletions: WorkerTaskHandler = async (_payload, helpers) => {@@ -18,18 +19,21 @@ const userProcessPendingDeletions: WorkerTaskHandler = async (_payload, helpers)if (needsRebuild) {Logger.info('Deletion queue needs rebuild, acquiring lock');const lockToken = await deletionQueueService.acquireRebuildLock();- if (lockToken) {+ if (!lockToken) {+ Logger.info('Another worker is rebuilding the queue, skipping this run');+ return;+ }+ try {+ await deletionQueueService.rebuildState(lockToken);+ } catch (error) {try {- await deletionQueueService.rebuildState(lockToken);await deletionQueueService.releaseRebuildLock(lockToken);- } catch (error) {- await deletionQueueService.releaseRebuildLock(lockToken);- throw error;+ } catch (releaseError) {+ Logger.error({error: releaseError}, 'Failed to release deletion queue lock after rebuild failure');}- } else {- Logger.info('Another worker is rebuilding the queue, skipping this run');- return;+ throw error;}+ await deletionQueueService.releaseRebuildLock(lockToken);}const nowMs = Date.now();const pendingDeletions = await deletionQueueService.getReadyDeletions(nowMs, 1000);@@ -44,18 +48,24 @@ const userProcessPendingDeletions: WorkerTaskHandler = async (_payload, helpers)await deletionQueueService.removeFromQueue(userId);continue;}- if (isPendingDeletionBlocked(user)) {+ if (!user.deletionStartedAt && isPendingDeletionBlocked(user)) {Logger.info({userId}, 'User is not eligible for automated deletion, removing from KV');await deletionQueueService.removeFromQueue(userId);continue;}+ const scheduledAt = getValidTimestamp(user.pendingDeletionAt, `Pending deletion timestamp for user ${userId}`);const deletionReasonCode = resolvePendingDeletionReasonCode(user, deletion.deletionReasonCode);+ if (scheduledAt > nowMs) {+ Logger.debug({userId, scheduledAt}, 'Requeueing pending user deletion that is not due yet');+ await deletionQueueService.scheduleDeletion(userId, user.pendingDeletionAt, deletionReasonCode);+ continue;+ }await workerService.addJob('userProcessPendingDeletion', {userId: deletion.userId.toString(),deletionReasonCode,+ pendingDeletionAt: user.pendingDeletionAt.toISOString(),});await deletionQueueService.removeFromQueue(userId);- await userRepository.removePendingDeletion(userId, user.pendingDeletionAt);scheduled++;} catch (error) {Logger.error({error, userId: deletion.userId.toString()}, 'Failed to schedule user deletion');diff --git a/fluxer_api/src/api/worker/tasks/admin_bulk/BulkScheduleUserDeletion.ts b/fluxer_api/src/api/worker/tasks/admin_bulk/BulkScheduleUserDeletion.tsindex 7f4280787..ec0661024 100644--- a/fluxer_api/src/api/worker/tasks/admin_bulk/BulkScheduleUserDeletion.ts+++ b/fluxer_api/src/api/worker/tasks/admin_bulk/BulkScheduleUserDeletion.ts@@ -59,17 +59,13 @@ const handler: WorkerTaskHandler = async (rawPayload, helpers) => {if (!user) throw new Error('user_not_found');const pendingDeletionAt = new Date();pendingDeletionAt.setDate(pendingDeletionAt.getDate() + daysUntilDeletion);- const updatedUser = await deps.userRepository.patchUpsert(- userId,- {- flags: user.flags | UserFlags.DELETED,- pending_deletion_at: pendingDeletionAt,- deletion_reason_code: payload.reason_code,- deletion_public_reason: payload.public_reason ?? null,- deletion_audit_log_reason: payload.audit_log_reason ?? null,- },- user.toRow(),- );+ const updatedUser = await deps.userRepository.updateDeletionSchedule(user, {+ flags: user.flags | UserFlags.DELETED,+ pending_deletion_at: pendingDeletionAt,+ deletion_reason_code: payload.reason_code,+ deletion_public_reason: payload.public_reason ?? null,+ deletion_audit_log_reason: payload.audit_log_reason ?? null,+ });await reschedulePendingDeletion({userId,currentPendingDeletionAt: user.pendingDeletionAt,diff --git a/fluxer_api/src/api/worker/tests/JetStreamWorkerQueue.test.ts b/fluxer_api/src/api/worker/tests/JetStreamWorkerQueue.test.tsindex 56ccf35e2..93f77b3d8 100644--- a/fluxer_api/src/api/worker/tests/JetStreamWorkerQueue.test.ts+++ b/fluxer_api/src/api/worker/tests/JetStreamWorkerQueue.test.ts@@ -23,6 +23,8 @@ const LEGACY_CONFIG = {subjects: ['jobs.>'],retention: RetentionPolicy.Workqueue,storage: StorageType.File,+ max_age: 7 * 24 * 60 * 60 * 1_000_000_000,+ duplicate_window: 2 * 60 * 1_000_000_000,max_msgs: -1,max_bytes: -1,max_msgs_per_subject: -1,@@ -35,6 +37,27 @@ interface ConsumerAddConfig {filter_subjects: Array<string>;}+function withStreamDefaults(config: Partial<StreamConfig>): Partial<StreamConfig> {+ return {+ max_age: 0,+ duplicate_window: 2 * 60 * 1_000_000_000,+ max_msgs: -1,+ max_bytes: -1,+ max_msgs_per_subject: -1,+ max_msg_size: -1,+ discard: DiscardPolicy.Old,+ discard_new_per_subject: false,+ ...config,+ };+}++function missingResourceError(resource: 'stream' | 'consumer'): NatsError {+ const description = `${resource} not found`;+ const error = new NatsError(description, '404');+ error.api_error = {code: 404, err_code: resource === 'stream' ? 10059 : 10014, description};+ return error;+}+function streamLimitError(description: string): NatsError {const error = new NatsError('503', '503');error.api_error = {code: 503, err_code: 10077, description};@@ -77,6 +100,8 @@ function createQueue(params: {reject?: (config: Partial<StreamConfig>) => Error | null;updateError?: Error;publish?: (subject: string) => {seq: number};+ subjectCounts?: Record<string, number>;+ subjectCountsError?: Error;}): {queue: JetStreamWorkerQueue;added: Array<Partial<StreamConfig>>;@@ -94,22 +119,40 @@ function createQueue(params: {consumers: {add: (_stream: string, config: ConsumerAddConfig) => {consumerAdds.push(config);- return Promise.resolve({});+ return Promise.resolve({config});},delete: () => Promise.resolve(true),- info: () => Promise.reject(new Error('consumer not found')),+ info: () => Promise.reject(missingResourceError('consumer')),},streams: {- info: (name: string) => {+ info: (name: string, options?: {subjects_filter?: string}) => {+ if (name === 'JOBS' && options?.subjects_filter !== undefined) {+ if (params.subjectCountsError) {+ return Promise.reject(params.subjectCountsError);+ }+ return Promise.resolve({+ config: withStreamDefaults(params.existing ?? {}),+ state: {subjects: params.subjectCounts},+ });+ }if (name === 'JOBS_DLQ') {return params.dlqExists- ? Promise.resolve({config: {name} as StreamConfig})- : Promise.reject(new Error('stream not found'));+ ? Promise.resolve({+ config: withStreamDefaults({+ name,+ subjects: ['dlq.>'],+ retention: RetentionPolicy.Limits,+ storage: StorageType.File,+ max_age: 30 * 24 * 60 * 60 * 1_000_000_000,+ max_bytes: 64 * MIB,+ }),+ })+ : Promise.reject(missingResourceError('stream'));}if (!params.existing) {- return Promise.reject(new Error('stream not found'));+ return Promise.reject(missingResourceError('stream'));}- return Promise.resolve({config: params.existing});+ return Promise.resolve({config: withStreamDefaults(params.existing), state: {}});},add: (config: Partial<StreamConfig>) => {(config.name === 'JOBS_DLQ' ? dlqAdded : added).push(config);@@ -117,7 +160,7 @@ function createQueue(params: {if (rejection !== null) {return Promise.reject(rejection);}- return Promise.resolve({config});+ return Promise.resolve({config: withStreamDefaults(config)});},update: (_name: string, config: Partial<StreamConfig>) => {if (params.updateError) {@@ -128,7 +171,7 @@ function createQueue(params: {if (rejection !== null) {return Promise.reject(rejection);}- return Promise.resolve({config});+ return Promise.resolve({config: withStreamDefaults(config)});},},}),@@ -214,6 +257,33 @@ describe('jobs stream limits', () => {await expect(queue.ensureStream()).resolves.toBeUndefined();expect(updated).toHaveLength(8);});++ it('leaves the limits alone while a subject holds more than the per-subject limit', async () => {+ const {queue, updated} = createQueue({+ existing: LEGACY_CONFIG,+ subjectCounts: {'jobs.extractEmbeds': 300_000, 'jobs.processAssetDeletionQueue': 10},+ });+ await expect(queue.ensureStream()).resolves.toBeUndefined();+ expect(updated).toHaveLength(0);+ });++ it('leaves the limits alone when the subject counts cannot be read', async () => {+ const {queue, updated} = createQueue({existing: LEGACY_CONFIG, subjectCountsError: new Error('no responders')});+ await expect(queue.ensureStream()).resolves.toBeUndefined();+ expect(updated).toHaveLength(0);+ });++ it('applies the limits to a drained stream that reports no subjects', async () => {+ const {queue, updated} = createQueue({existing: LEGACY_CONFIG, subjectCounts: undefined});+ await queue.ensureStream();+ expect(updated).toHaveLength(1);+ expect(updated[0]).toEqual(EXPECTED_LIMITS);+ });++ it('refuses a stream that is not the worker stream', async () => {+ const {queue} = createQueue({existing: {...LEGACY_CONFIG, retention: RetentionPolicy.Limits} as StreamConfig});+ await expect(queue.ensureStream()).rejects.toThrow(/incompatible retention/);+ });});describe('dead-letter stream', () => {diff --git a/fluxer_api/src/api/worker/tests/UserProcessPendingDeletions.test.ts b/fluxer_api/src/api/worker/tests/UserProcessPendingDeletions.test.tsindex 862a14e6a..f2dbd88f7 100644--- a/fluxer_api/src/api/worker/tests/UserProcessPendingDeletions.test.ts+++ b/fluxer_api/src/api/worker/tests/UserProcessPendingDeletions.test.ts@@ -46,8 +46,8 @@ async function createHarness(users: Array<User>) {},} as unknown as UserRepository;const workerService = {- async addJob(name: string, payload: {userId: string}): Promise<bigint> {- scheduledJobs.push(`${name}:${payload.userId}`);+ async addJob(name: string, payload: {userId: string; pendingDeletionAt: string}): Promise<bigint> {+ scheduledJobs.push(`${name}:${payload.userId}:${payload.pendingDeletionAt}`);return 0n;},} as unknown as IWorkerService;@@ -94,8 +94,10 @@ describe('userProcessPendingDeletions', () => {const queueSizeAfterFirstPass = await harness.deletionQueueService.getQueueSize();await userProcessPendingDeletions({}, createHelpers());- expect(harness.scheduledJobs).toEqual([`userProcessPendingDeletion:${genuineUserId.toString()}`]);- expect(harness.removedPendingDeletions).toEqual([genuineUserId.toString()]);+ expect(harness.scheduledJobs).toEqual([+ `userProcessPendingDeletion:${genuineUserId.toString()}:${genuineAt.toISOString()}`,+ ]);+ expect(harness.removedPendingDeletions).toEqual([]);expect(queueSizeAfterFirstPass).toBe(1);expect(await harness.deletionQueueService.getQueueSize()).toBe(0);});diff --git a/fluxer_api/src/api/worker/tests/WorkerHeartbeat.test.ts b/fluxer_api/src/api/worker/tests/WorkerHeartbeat.test.tsindex 1bff88fa8..d2c009741 100644--- a/fluxer_api/src/api/worker/tests/WorkerHeartbeat.test.ts+++ b/fluxer_api/src/api/worker/tests/WorkerHeartbeat.test.ts@@ -36,6 +36,10 @@ class FakeConsumerMessages {private closed = false;async close(): Promise<void> {+ this.stop();+ }++ stop(): void {this.closed = true;const notify = this.notify;this.notify = null;@@ -59,7 +63,7 @@ function createRunner(messages: FakeConsumerMessages, heartbeat: WorkerHeartbeatgetJetStreamClient: () => ({consumers: {get: async () => ({- consume: async () => messages as unknown as ConsumerMessages,+ fetch: async () => messages as unknown as ConsumerMessages,}),},}),diff --git a/fluxer_api/src/api/worker/tests/WorkerRunnerResubscribe.test.ts b/fluxer_api/src/api/worker/tests/WorkerRunnerResubscribe.test.tsindex 6845a16f7..721328ab3 100644--- a/fluxer_api/src/api/worker/tests/WorkerRunnerResubscribe.test.ts+++ b/fluxer_api/src/api/worker/tests/WorkerRunnerResubscribe.test.ts@@ -35,6 +35,13 @@ class FakeConsumerMessages {this.end();}+ stop(error?: Error): void {+ if (error) {+ this.failure = error;+ }+ this.end();+ }+async *[Symbol.asyncIterator](): AsyncGenerator<JsMsg> {while (true) {while (this.pending.length > 0) {@@ -66,7 +73,7 @@ function createRunner(streams: Array<FakeConsumerMessages>): {runner: WorkerRunngetJetStreamClient: () => ({consumers: {get: async () => ({- consume: async () => {+ fetch: async () => {const stream = streams[consumed];consumed += 1;if (!stream) {diff --git a/fluxer_api/src/api/worker/tests/WorkerRunnerShutdown.test.ts b/fluxer_api/src/api/worker/tests/WorkerRunnerShutdown.test.tsindex c93ef34d0..fe7e4bc3b 100644--- a/fluxer_api/src/api/worker/tests/WorkerRunnerShutdown.test.ts+++ b/fluxer_api/src/api/worker/tests/WorkerRunnerShutdown.test.ts@@ -13,6 +13,7 @@ class FakeConsumerMessages {private readonly pending: Array<JsMsg> = [];private notify: (() => void) | null = null;private closed = false;+ private failure: Error | null = null;push(msg: JsMsg): void {this.pending.push(msg);@@ -20,6 +21,13 @@ class FakeConsumerMessages {}async close(): Promise<void> {+ this.stop();+ }++ stop(error?: Error): void {+ if (error) {+ this.failure = error;+ }this.closed = true;this.wake();}@@ -29,6 +37,9 @@ class FakeConsumerMessages {while (this.pending.length > 0) {yield this.pending.shift()!;}+ if (this.failure !== null) {+ throw this.failure;+ }if (this.closed) {return;}@@ -51,7 +62,7 @@ function createQueueStub(messages: FakeConsumerMessages) {getJetStreamClient: () => ({consumers: {get: async () => ({- consume: async () => messages as unknown as ConsumerMessages,+ fetch: async () => messages as unknown as ConsumerMessages,}),},}),diff --git a/fluxer_api/src/api/worker/utils/ArchiveFile.ts b/fluxer_api/src/api/worker/utils/ArchiveFile.tsnew file mode 100644index 000000000..499278948--- /dev/null+++ b/fluxer_api/src/api/worker/utils/ArchiveFile.ts@@ -0,0 +1,149 @@+import {createReadStream, createWriteStream, ReadStream} from 'node:fs';+import {lstat, opendir, readlink} from 'node:fs/promises';+import path from 'node:path';+import type {Readable} from 'node:stream';+import {finished, pipeline} from 'node:stream/promises';+import archiver, {type Archiver, type EntryData} from 'archiver';++export interface ArchiveEntryWriter {+ append(source: Readable | Buffer | string, data: EntryData): Promise<void>;+}++interface ArchiveFileWriter extends ArchiveEntryWriter {+ directory(directoryPath: string): Promise<void>;+}++interface ArchiveSymlinkEntry extends EntryData {+ type: 'symlink';+ linkname: string;+}++interface PendingArchiveEntry {+ resolve(): void;+ reject(error: unknown): void;+}++export async function writeZipArchive(+ filePath: string,+ produce: (archive: ArchiveFileWriter) => void | Promise<void>,+): Promise<void> {+ const archive: Archiver = archiver('zip', {zlib: {level: 6}});+ const output = createWriteStream(filePath);+ const outputClosed = new Promise<void>((resolve) => output.once('close', resolve));+ const archiveClosed = new Promise<void>((resolve) => archive.once('close', resolve));+ const inputs = new Map<Readable, Promise<void>>();+ const entries = new Map<EntryData, PendingArchiveEntry>();+ let failure: {error: unknown} | undefined;++ function fail(error: unknown): void {+ if (failure) return;+ failure = {error};+ for (const entry of entries.values()) entry.reject(error);+ entries.clear();+ const streamError = error instanceof Error ? error : new Error('Archive creation failed', {cause: error});+ for (const source of inputs.keys()) source.destroy(streamError);+ archive.abort();+ archive.destroy(streamError);+ output.destroy(streamError);+ }++ function requireWritable(): void {+ if (failure) throw failure.error;+ }++ async function append(source: Readable | Buffer | string, data: EntryData): Promise<void> {+ let completion = Promise.resolve();+ if (typeof source !== 'string' && !Buffer.isBuffer(source)) {+ const closed =+ source instanceof ReadStream && !source.closed+ ? new Promise<void>((resolve) => source.once('close', resolve))+ : Promise.resolve();+ source.on('error', fail);+ completion = finished(source, {cleanup: true, writable: false})+ .catch(fail)+ .then(async () => {+ try {+ await source[Symbol.asyncDispose]();+ } catch (error) {+ fail(error);+ }+ await closed;+ inputs.delete(source);+ source.off('error', fail);+ });+ inputs.set(source, completion);+ if (failure) source.destroy(new Error('Archive creation failed', {cause: failure.error}));+ }+ requireWritable();+ const entry = {...data};+ const processed = new Promise<void>((resolve, reject) => entries.set(entry, {resolve, reject}));+ const completed = Promise.all([processed, completion]);+ try {+ archive.append(source, entry);+ } catch (error) {+ fail(error);+ }+ await completed;+ requireWritable();+ }++ async function appendDirectory(directoryPath: string, prefix = ''): Promise<void> {+ requireWritable();+ const directory = await opendir(directoryPath);+ for await (const entry of directory) {+ requireWritable();+ const entryPath = path.join(directoryPath, entry.name);+ const name = path.posix.join(prefix, entry.name);+ const stats = await lstat(entryPath);+ if (stats.isDirectory()) {+ await append(Buffer.alloc(0), {name: `${name}/`, stats});+ await appendDirectory(entryPath, name);+ } else if (stats.isFile()) {+ await append(createReadStream(entryPath), {name, stats});+ } else if (stats.isSymbolicLink()) {+ const target = await readlink(entryPath);+ const data: ArchiveSymlinkEntry = {+ name,+ stats,+ type: 'symlink',+ linkname: path.relative(directoryPath, path.resolve(directoryPath, target)),+ };+ await append(Buffer.alloc(0), data);+ } else {+ throw new Error(`Unsupported archive entry: ${entryPath}`);+ }+ }+ }++ archive.on('warning', fail);+ archive.on('error', fail);+ archive.on('entry', (entry) => {+ if (failure) return;+ const pending = entries.get(entry);+ if (!pending) {+ fail(new Error('Archive completed an unknown entry'));+ return;+ }+ entries.delete(entry);+ pending.resolve();+ });+ output.on('error', fail);+ const written = pipeline(archive, output);+ void written.catch(fail);+ try {+ await produce({+ append,+ directory: (directoryPath) => appendDirectory(directoryPath),+ });+ requireWritable();+ await Promise.all([archive.finalize(), written]);+ } catch (error) {+ fail(error);+ } finally {+ archive.destroy();+ output.destroy();+ for (const source of inputs.keys()) source.destroy();+ await Promise.all([archiveClosed, outputClosed, written.catch(fail), ...inputs.values()]);+ }+ if (failure) throw failure.error;+}diff --git a/fluxer_api/src/api/worker/utils/AssetArchiveHelpers.ts b/fluxer_api/src/api/worker/utils/AssetArchiveHelpers.tsindex 95048d7e6..b1dd986ea 100644--- a/fluxer_api/src/api/worker/utils/AssetArchiveHelpers.ts+++ b/fluxer_api/src/api/worker/utils/AssetArchiveHelpers.ts@@ -2,10 +2,10 @@import type {Readable} from 'node:stream';import {S3ServiceException} from '@aws-sdk/client-s3';-import type archiver from 'archiver';import {Config} from '../../Config';import type {IStorageService} from '../../infrastructure/IStorageService';import {Logger} from '../../Logger';+import type {ArchiveEntryWriter} from './ArchiveFile';let _cdnBucket: string | null = null;@@ -74,7 +74,7 @@ export async function streamCdnAssetIfExists(}interface AppendAssetToArchiveParams {- archive: archiver.Archiver;+ archive: ArchiveEntryWriter;storageService: IStorageService;storageKey: string;archiveName: string;@@ -95,5 +95,5 @@ export async function appendAssetToArchive({Logger.warn({subjectId, storageKey}, `Skipping missing ${label}`);return;}- archive.append(buffer, {name: archiveName});+ await archive.append(buffer, {name: archiveName});}diff --git a/fluxer_api/src/api/worker/utils/ContentAddressedAttachmentCollector.ts b/fluxer_api/src/api/worker/utils/ContentAddressedAttachmentCollector.tsindex 9c8bd3166..1324d7e76 100644--- a/fluxer_api/src/api/worker/utils/ContentAddressedAttachmentCollector.ts+++ b/fluxer_api/src/api/worker/utils/ContentAddressedAttachmentCollector.ts@@ -5,6 +5,7 @@ import type {AttachmentID, ChannelID} from '../../BrandedTypes';import {makeAttachmentCdnKey} from '../../channel/services/message/MessageHelpers';import type {IStorageService} from '../../infrastructure/IStorageService';import {Logger} from '../../Logger';+import type {ArchiveEntryWriter} from './ArchiveFile';import {streamCdnAssetIfExists} from './AssetArchiveHelpers';interface CollectedAttachment {@@ -25,13 +26,9 @@ interface AttachmentManifestEntry {size: number;}-interface AttachmentArchiveWriter {- append(input: Buffer | NodeJS.ReadableStream | string, options: {name: string}): void;-}-interface CollectParams {storageService: IStorageService;- archive: AttachmentArchiveWriter;+ archive: ArchiveEntryWriter;channelId: ChannelID;attachmentId: AttachmentID | bigint;filename: string;@@ -44,6 +41,9 @@ export class ContentAddressedAttachmentCollector {const {storageService, archive, channelId, attachmentId, filename} = params;const storageKey = makeAttachmentCdnKey(channelId, attachmentId, filename);const STREAM_THRESHOLD = 10 * 1024 * 1024;+ const keyHash = crypto.createHash('sha256').update(storageKey).digest('hex');+ const existingStream = this.hashIndex.get(keyHash);+ if (existingStream) return {hash: keyHash, archivePath: existingStream.archivePath};const streamed = await streamCdnAssetIfExists(storageService, storageKey);if (!streamed) {Logger.warn(@@ -53,14 +53,8 @@ export class ContentAddressedAttachmentCollector {return null;}if (streamed.contentLength > STREAM_THRESHOLD) {- const keyHash = crypto.createHash('sha256').update(storageKey).digest('hex');- const existing = this.hashIndex.get(keyHash);- if (existing) {- streamed.body.resume();- return {hash: keyHash, archivePath: existing.archivePath};- }const archivePath = `attachments/${keyHash.slice(0, 16)}/${filename}`;- archive.append(streamed.body, {name: archivePath});+ await archive.append(streamed.body, {name: archivePath});this.hashIndex.set(keyHash, {archivePath, filename, size: streamed.contentLength});return {hash: keyHash, archivePath};}@@ -75,7 +69,7 @@ export class ContentAddressedAttachmentCollector {return {hash, archivePath: existing.archivePath};}const archivePath = `attachments/${hash.slice(0, 16)}/${filename}`;- archive.append(buffer, {name: archivePath});+ await archive.append(buffer, {name: archivePath});this.hashIndex.set(hash, {archivePath, filename, size: buffer.length});return {hash, archivePath};}diff --git a/packages/config/src/ConfigLoader.ts b/packages/config/src/ConfigLoader.tsindex 43dc5be7b..91e1bc41d 100644--- a/packages/config/src/ConfigLoader.ts+++ b/packages/config/src/ConfigLoader.ts@@ -1,7 +1,7 @@// SPDX-License-Identifier: AGPL-3.0-or-laterimport {createECDH} from 'node:crypto';-import {type ConfigObject, isConfigObject} from '@fluxer/config/src/config_loader/ConfigObject';+import {isConfigObject} from '@fluxer/config/src/config_loader/ConfigObject';import {buildNamedFluxerEnvOverrides} from '@fluxer/config/src/config_loader/EnvironmentOverrides';import {buildUrl,@@ -9,6 +9,7 @@ import {deriveEndpointsFromDomain,normalizePublicEndpoint,parsePublicOrigin,+ parseWebOrigin,} from '@fluxer/config/src/EndpointDerivation';import type {MasterConfig} from '@fluxer/config/src/MasterConfig';@@ -309,12 +310,12 @@ function mergeConfig<T>(base: T, overrides: unknown): T {if (!isConfigObject(base) || !isConfigObject(overrides)) {return overrides === undefined ? base : (overrides as T);}- const out: ConfigObject = {...base};+ const out = new Map(Object.entries(base));for (const [key, value] of Object.entries(overrides)) {- const current = out[key];- out[key] = isConfigObject(current) && isConfigObject(value) ? mergeConfig(current, value) : value;+ const current = out.get(key);+ out.set(key, isConfigObject(current) && isConfigObject(value) ? mergeConfig(current, value) : value);}- return out as T;+ return Object.fromEntries(out) as T;}function assertOneOf<T extends string>(value: string, allowed: ReadonlyArray<T>, path: string): asserts value is T {@@ -448,6 +449,54 @@ function validateApiWorkerConfig(config: MasterConfig): void {}}+function validateDomain(value: string, envName: string): void {+ if (value === '') return;+ const parsed = URL.parse(`http://${value}/`);+ const hasPort = value.startsWith('[') ? !value.endsWith(']') : value.includes(':');+ if (+ !parsed ||+ hasPort ||+ /[\s\p{Cc}/\\?#@%]/u.test(value) ||+ !parsed.hostname ||+ parsed.port ||+ parsed.username ||+ parsed.password ||+ parsed.pathname !== '/' ||+ parsed.search ||+ parsed.hash+ ) {+ throw new Error(`${envName} must be a hostname without a scheme, port, credentials, or path`);+ }+}++function validatePublicEndpoints(endpoints: DerivedEndpoints): void {+ for (const [key, value] of Object.entries(endpoints)) {+ const envName = `FLUXER_${key.toUpperCase()}_ENDPOINT`;+ requireString(value, envName);+ const gateway = key === 'gateway';+ const parsed = URL.parse(value);+ if (parsed?.port === '0') throw new Error(`${envName} must not use port 0`);+ const authority = /^[a-z]+:\/\/([^/?#]+)/i.exec(value)?.[1];+ const allowedProtocols = gateway ? ['ws:', 'wss:'] : ['http:', 'https:'];+ if (+ !parsed ||+ !authority ||+ !allowedProtocols.includes(parsed.protocol) ||+ !parsed.hostname ||+ /[\s\p{Cc}\\]/u.test(value) ||+ authority.includes('@') ||+ authority.endsWith(':') ||+ value.includes('#') ||+ (!gateway && value.includes('?'))+ ) {+ const expected = gateway+ ? 'ws/wss URL without credentials or a fragment'+ : 'http/https base URL without credentials, a query, or a fragment';+ throw new Error(`${envName} must be an absolute ${expected}`);+ }+ }+}+function normalizeConfig(config: MasterConfig): MasterConfig {assertOneOf(config.env, ['development', 'production', 'test'], 'FLUXER_ENV');assertOneOf(config.domain.public_scheme, ['http', 'https'], 'FLUXER_PUBLIC_SCHEME');@@ -471,6 +520,9 @@ function normalizeConfig(config: MasterConfig): MasterConfig {assertIntegerInRange(config.services.api.request_timeout_ms, 'FLUXER_API_REQUEST_TIMEOUT_MS', 1_000, 3_600_000);assertIntegerInRange(config.domain.public_port, 'FLUXER_PUBLIC_PORT', 1, 65_535);requireString(config.domain.base_domain, 'FLUXER_BASE_DOMAIN');+ for (const key of ['base_domain', 'static_cdn_domain', 'invite_domain', 'gift_domain'] as const) {+ validateDomain(config.domain[key], `FLUXER_${key.toUpperCase()}`);+ }requireString(config.auth.sudo_mode_secret, 'FLUXER_SUDO_MODE_SECRET');requireString(config.auth.connection_initiation_secret, 'FLUXER_CONNECTION_INITIATION_SECRET');validateVapidConfig(config);@@ -485,14 +537,14 @@ function normalizeConfig(config: MasterConfig): MasterConfig {}function applyPublicOrigin(config: MasterConfig): MasterConfig {- const raw = config.domain.public_origin.trim();- if (raw.length === 0) {+ const raw = config.domain.public_origin;+ if (raw.trim().length === 0 && !/\p{Cc}/u.test(raw)) {return config;}const origin = parsePublicOrigin(raw);if (!origin) {throw new Error(- `FLUXER_PUBLIC_ORIGIN must be a scheme, host and optional port such as https://chat.example.com:8443, got ${raw}`,+ 'FLUXER_PUBLIC_ORIGIN must be a scheme, host and optional port such as https://chat.example.com:8443',);}return {@@ -508,7 +560,8 @@ function applyPublicOrigin(config: MasterConfig): MasterConfig {function applyPublicPort(config: MasterConfig, endpoints: DerivedEndpoints): MasterConfig {const {base_domain, public_port} = config.domain;- const normalize = (url: string) => normalizePublicEndpoint(url, base_domain, public_port);+ const comparisonHost = new URL(buildUrl('http', base_domain)).hostname;+ const normalize = (url: string) => normalizePublicEndpoint(url, comparisonHost, public_port);const normalizeOptional = (url: string | undefined) => (url === undefined ? undefined : normalize(url));const normalizedEndpoints = {...endpoints};for (const key of Object.keys(normalizedEndpoints) as Array<keyof DerivedEndpoints>) {@@ -577,21 +630,33 @@ function applyPublicPort(config: MasterConfig, endpoints: DerivedEndpoints): Mas};}-function resolveAppOrigin(appEndpoint: string): string {- try {- return new URL(appEndpoint).origin;- } catch {- throw new Error(`FLUXER_APP_ENDPOINT must be a valid URL: ${appEndpoint}`);+function normalizePasskeyOrigin(origin: string, index: number): string {+ const webOrigin = parseWebOrigin(origin);+ if (webOrigin) {+ return webOrigin.origin;+ }+ const fingerprint = /^android:apk-key-hash:([A-Za-z0-9_-]{43})$/.exec(origin)?.[1];+ if (fingerprint) {+ const bytes = Buffer.from(fingerprint, 'base64url');+ if (bytes.length === 32 && bytes.toString('base64url') === fingerprint) {+ return origin;+ }}+ throw new Error(+ `FLUXER_PASSKEY_ADDITIONAL_ALLOWED_ORIGINS entry ${index + 1} must be an HTTP(S) origin or a canonical Android signing-certificate origin`,+ );}-function applyPasskeyDefaults(config: MasterConfig, endpoints: DerivedEndpoints): void {+function normalizePasskeys(config: MasterConfig, useDefaultOrigins: boolean): void {const passkeys = config.auth.passkeys;+ passkeys.additional_allowed_origins = passkeys.additional_allowed_origins.map(normalizePasskeyOrigin);if (passkeys.rp_id.trim().length === 0) {passkeys.rp_id = config.domain.base_domain;}- if (passkeys.additional_allowed_origins.length === 0) {- passkeys.additional_allowed_origins = [resolveAppOrigin(endpoints.app)];+ if (useDefaultOrigins || passkeys.additional_allowed_origins.length === 0) {+ passkeys.additional_allowed_origins = [+ ...new Set([...passkeys.additional_allowed_origins, new URL(config.endpoints.app).origin]),+ ];}}@@ -604,9 +669,9 @@ export async function loadConfig(): Promise<MasterConfig> {const normalized = normalizeConfig(merged);const derived = deriveEndpointsFromDomain(normalized.domain);const endpoints = {...derived, ...(normalized.endpoint_overrides ?? {})};- requireString(endpoints.api_client, 'FLUXER_API_CLIENT_ENDPOINT');+ validatePublicEndpoints(endpoints);const withPublicPort = applyPublicPort(normalized, endpoints);- applyPasskeyDefaults(withPublicPort, withPublicPort.endpoints);+ normalizePasskeys(withPublicPort, process.env.FLUXER_PASSKEY_ADDITIONAL_ALLOWED_ORIGINS === undefined);cachedConfig = withPublicPort;return cachedConfig;}diff --git a/packages/config/src/EndpointDerivation.ts b/packages/config/src/EndpointDerivation.tsindex a5af49676..8bef09ada 100644--- a/packages/config/src/EndpointDerivation.ts+++ b/packages/config/src/EndpointDerivation.ts@@ -53,27 +53,25 @@ function defaultPortForScheme(scheme: PublicOriginScheme): number {return scheme === 'https' ? 443 : 80;}-export function parsePublicOrigin(origin: string): PublicOrigin | null {+export function parseWebOrigin(origin: string): URL | null {const trimmed = origin.trim();- if (trimmed.length === 0) {- return null;- }- let parsed: URL;- try {- parsed = new URL(trimmed);- } catch {+ const authority = /^https?:\/\/([^/?#\\\s]+)\/?$/i.exec(trimmed)?.[1];+ if (!authority || /\p{Cc}/u.test(origin) || authority.includes('@') || authority.endsWith(':')) {return null;}- const scheme = parsed.protocol.slice(0, -1);- if (scheme !== 'http' && scheme !== 'https') {+ const parsed = URL.parse(trimmed);+ if (!parsed || parsed.port === '0' || (parsed.protocol !== 'http:' && parsed.protocol !== 'https:')) {return null;}- if (parsed.pathname !== '/' || parsed.search.length > 0 || parsed.hash.length > 0) {- return null;- }- if (parsed.username.length > 0 || parsed.password.length > 0) {+ return parsed;+}++export function parsePublicOrigin(origin: string): PublicOrigin | null {+ const parsed = parseWebOrigin(origin);+ if (!parsed) {return null;}+ const scheme = parsed.protocol === 'https:' ? 'https' : 'http';const base_domain = canonicalizeDomain(parsed.hostname);if (base_domain.length === 0) {return null;diff --git a/packages/config/src/__tests__/ConfigLoader.test.ts b/packages/config/src/__tests__/ConfigLoader.test.tsindex fa882ac0c..93632f919 100644--- a/packages/config/src/__tests__/ConfigLoader.test.ts+++ b/packages/config/src/__tests__/ConfigLoader.test.ts@@ -189,7 +189,7 @@ describe('ConfigLoader', () => {test('normalizes each passkey origin independently', async () => {stubMinimalEnv({FLUXER_PASSKEY_ADDITIONAL_ALLOWED_ORIGINS:- 'http://localhost,http://localhost:3000,https://desktop.example.net,android:apk-key-hash:abc',+ 'http://localhost,http://localhost:3000,https://desktop.example.net,android:apk-key-hash:keSY4bimyLqZQV7bKXgpa2xYuqXi0qZJzsYtp6gpx7w',});const config = await loadConfig();@@ -198,11 +198,11 @@ describe('ConfigLoader', () => {'http://localhost:8088','http://localhost:3000','https://desktop.example.net',- 'android:apk-key-hash:abc',+ 'android:apk-key-hash:keSY4bimyLqZQV7bKXgpa2xYuqXi0qZJzsYtp6gpx7w',]);});- test('leaves the default passkey origins untouched', async () => {+ test('includes the app origin alongside the default passkey origins', async () => {stubMinimalEnv();const config = await loadConfig();expect(config.auth.passkeys.additional_allowed_origins).toEqual([@@ -211,6 +211,7 @@ describe('ConfigLoader', () => {'https://web.canary.fluxer.app','android:apk-key-hash:keSY4bimyLqZQV7bKXgpa2xYuqXi0qZJzsYtp6gpx7w','android:apk-key-hash:zRmCKDKo3uCX2GDZISjJx8Rzo3J-Y3Gbp7s7mAaUH28',+ 'http://localhost:8088',]);});@@ -231,7 +232,7 @@ describe('ConfigLoader', () => {expect(config.auth.passkeys.rp_id).toBe('chat.example.com');});- test('derives the passkey origin only when the operator clears the default list', async () => {+ test('uses only the app origin when the operator clears the default list', async () => {stubMinimalEnv({FLUXER_BASE_DOMAIN: 'chat.example.com',FLUXER_PUBLIC_SCHEME: 'https',@@ -799,7 +800,7 @@ describe('FLUXER_PUBLIC_ORIGIN', () => {test('refuses to boot on an origin that is not a bare origin', async () => {stubMinimalEnv({FLUXER_PUBLIC_ORIGIN: 'https://chat.example.com/app'});await expect(loadConfig()).rejects.toThrow(- 'FLUXER_PUBLIC_ORIGIN must be a scheme, host and optional port such as https://chat.example.com:8443, got https://chat.example.com/app',+ 'FLUXER_PUBLIC_ORIGIN must be a scheme, host and optional port such as https://chat.example.com:8443',);});diff --git a/packages/config/src/config_loader/EnvironmentOverrides.ts b/packages/config/src/config_loader/EnvironmentOverrides.tsindex 99bf45b95..885906e00 100644--- a/packages/config/src/config_loader/EnvironmentOverrides.ts+++ b/packages/config/src/config_loader/EnvironmentOverrides.ts@@ -33,7 +33,7 @@ const NAMED_FLUXER_ENV_OVERRIDES: Record<string, NamedEnvOverride> = {FLUXER_MARKETING_ENDPOINT: {path: ['endpoint_overrides', 'marketing']},FLUXER_INVITE_ENDPOINT: {path: ['endpoint_overrides', 'invite']},FLUXER_GIFT_ENDPOINT: {path: ['endpoint_overrides', 'gift']},- FLUXER_TRUST_CLIENT_IP_HEADER: {path: ['proxy', 'trust_client_ip_header'], parse: parseEnvValue},+ FLUXER_TRUST_CLIENT_IP_HEADER: {path: ['proxy', 'trust_client_ip_header'], parse: parseBoolean},FLUXER_CLIENT_IP_HEADER_NAME: {path: ['proxy', 'client_ip_header']},FLUXER_CASSANDRA_HOSTS: {path: ['database', 'cassandra', 'hosts'], parse: parseCsv},FLUXER_CASSANDRA_PORT: {path: ['database', 'cassandra', 'port'], parse: parseInteger},@@ -47,11 +47,11 @@ const NAMED_FLUXER_ENV_OVERRIDES: Record<string, NamedEnvOverride> = {FLUXER_POSTGRES_DATABASE: {path: ['database', 'postgres', 'database']},FLUXER_POSTGRES_USERNAME: {path: ['database', 'postgres', 'username']},FLUXER_POSTGRES_PASSWORD: {path: ['database', 'postgres', 'password']},- FLUXER_POSTGRES_SSL: {path: ['database', 'postgres', 'ssl'], parse: parseEnvValue},+ FLUXER_POSTGRES_SSL: {path: ['database', 'postgres', 'ssl'], parse: parseBoolean},FLUXER_POSTGRES_SSL_CA: {path: ['database', 'postgres', 'ssl_ca']},FLUXER_POSTGRES_MAX_CONNECTIONS: {path: ['database', 'postgres', 'max_connections'], parse: parseInteger},FLUXER_POSTGRES_KV_TABLE: {path: ['database', 'postgres', 'kv_table']},- FLUXER_POSTGRES_PREPARED_STATEMENTS: {path: ['database', 'postgres', 'prepared_statements'], parse: parseEnvValue},+ FLUXER_POSTGRES_PREPARED_STATEMENTS: {path: ['database', 'postgres', 'prepared_statements'], parse: parseBoolean},FLUXER_DATABASE_BACKEND: {path: ['database', 'backend']},FLUXER_KV_URL: {path: ['internal', 'kv']},FLUXER_KV_PROVIDER: {path: ['internal', 'kv_provider']},@@ -61,7 +61,7 @@ const NAMED_FLUXER_ENV_OVERRIDES: Record<string, NamedEnvOverride> = {FLUXER_INTERNAL_MEDIA_PROXY_ENDPOINT: {path: ['internal', 'media_proxy']},FLUXER_S3_ENDPOINT: {path: ['s3', 'endpoint']},FLUXER_S3_PUBLIC_ENDPOINT: {path: ['s3', 'presigned_url_base']},- FLUXER_S3_FORCE_PATH_STYLE: {path: ['s3', 'force_path_style'], parse: parseEnvValue},+ FLUXER_S3_FORCE_PATH_STYLE: {path: ['s3', 'force_path_style'], parse: parseBoolean},FLUXER_S3_REGION: {path: ['s3', 'region']},FLUXER_S3_ACCESS_KEY_ID: {path: ['s3', 'access_key_id']},FLUXER_S3_SECRET_ACCESS_KEY: {path: ['s3', 'secret_access_key']},@@ -72,7 +72,7 @@ const NAMED_FLUXER_ENV_OVERRIDES: Record<string, NamedEnvOverride> = {FLUXER_S3_BUCKET_HARVESTS: {path: ['s3', 'buckets', 'harvests']},FLUXER_S3_DOWNLOADS_ENDPOINT: {path: ['s3_downloads', 'endpoint']},FLUXER_S3_DOWNLOADS_PUBLIC_ENDPOINT: {path: ['s3_downloads', 'presigned_url_base']},- FLUXER_S3_DOWNLOADS_FORCE_PATH_STYLE: {path: ['s3_downloads', 'force_path_style'], parse: parseEnvValue},+ FLUXER_S3_DOWNLOADS_FORCE_PATH_STYLE: {path: ['s3_downloads', 'force_path_style'], parse: parseBoolean},FLUXER_S3_DOWNLOADS_REGION: {path: ['s3_downloads', 'region']},FLUXER_S3_DOWNLOADS_ACCESS_KEY_ID: {path: ['s3_downloads', 'access_key_id']},FLUXER_S3_DOWNLOADS_SECRET_ACCESS_KEY: {path: ['s3_downloads', 'secret_access_key']},@@ -90,35 +90,35 @@ const NAMED_FLUXER_ENV_OVERRIDES: Record<string, NamedEnvOverride> = {},FLUXER_API_PRESIGNED_ATTACHMENT_UPLOADS_ENABLED: {path: ['services', 'api', 'presigned_attachment_uploads_enabled'],- parse: parseEnvValue,+ parse: parseBoolean,},FLUXER_API_PRESIGNED_DOWNLOADS_ENABLED: {path: ['services', 'api', 'presigned_downloads_enabled'],- parse: parseEnvValue,+ parse: parseBoolean,},FLUXER_API_PRESIGNED_HARVEST_DOWNLOADS_ENABLED: {path: ['services', 'api', 'presigned_harvest_downloads_enabled'],- parse: parseEnvValue,+ parse: parseBoolean,},FLUXER_API_WORKER_MODE: {path: ['services', 'api', 'worker', 'mode']},FLUXER_API_WORKER_LANE: {path: ['services', 'api', 'worker', 'lane']},FLUXER_API_WORKER_TASK: {path: ['services', 'api', 'worker', 'task']},FLUXER_API_WORKER_ENABLE_CRON_SCHEDULER: {path: ['services', 'api', 'worker', 'enable_cron_scheduler'],- parse: parseEnvValue,+ parse: parseBoolean,},FLUXER_API_WORKER_LANE_CONCURRENCY_OVERRIDES: {path: ['services', 'api', 'worker', 'lane_concurrency_overrides'],- parse: parseEnvValue,+ parse: parseJsonObject,},FLUXER_API_UNFURL_IGNORED_HOSTS: {path: ['services', 'api', 'unfurl_ignored_hosts'], parse: parseCsv},FLUXER_API_EMBEDS_OEMBED_HTML_ENABLED: {path: ['services', 'api', 'embeds', 'oembed_html_enabled'],- parse: parseEnvValue,+ parse: parseBoolean,},FLUXER_API_EMBEDS_OEMBED_HTML_ALLOW_UNTRUSTED_ON_SELF_HOSTED: {path: ['services', 'api', 'embeds', 'oembed_html_allow_untrusted_on_self_hosted'],- parse: parseEnvValue,+ parse: parseBoolean,},FLUXER_API_EMBEDS_OEMBED_HTML_ALLOWED_HOSTS: {path: ['services', 'api', 'embeds', 'oembed_html_allowed_hosts'],@@ -138,7 +138,7 @@ const NAMED_FLUXER_ENV_OVERRIDES: Record<string, NamedEnvOverride> = {},FLUXER_API_EMBEDS_CACHE_RESPECT_REMOTE_TTL: {path: ['services', 'api', 'embeds', 'cache_respect_remote_ttl'],- parse: parseEnvValue,+ parse: parseBoolean,},FLUXER_API_CONTENT_MODERATION_NSFW_THRESHOLD: {path: ['services', 'api', 'content_moderation', 'nsfw_threshold'],@@ -205,7 +205,7 @@ const NAMED_FLUXER_ENV_OVERRIDES: Record<string, NamedEnvOverride> = {},FLUXER_SUDO_MODE_SECRET: {path: ['auth', 'sudo_mode_secret']},FLUXER_CONNECTION_INITIATION_SECRET: {path: ['auth', 'connection_initiation_secret']},- FLUXER_SSO_ALLOW_PRIVATE_ADDRESSES: {path: ['auth', 'sso_allow_private_addresses'], parse: parseEnvValue},+ FLUXER_SSO_ALLOW_PRIVATE_ADDRESSES: {path: ['auth', 'sso_allow_private_addresses'], parse: parseBoolean},FLUXER_VAPID_PUBLIC_KEY: {path: ['auth', 'vapid', 'public_key']},FLUXER_VAPID_PRIVATE_KEY: {path: ['auth', 'vapid', 'private_key']},FLUXER_VAPID_EMAIL: {path: ['auth', 'vapid', 'email']},@@ -213,16 +213,16 @@ const NAMED_FLUXER_ENV_OVERRIDES: Record<string, NamedEnvOverride> = {FLUXER_PASSKEY_RP_ID: {path: ['auth', 'passkeys', 'rp_id']},FLUXER_PASSKEY_ADDITIONAL_ALLOWED_ORIGINS: {path: ['auth', 'passkeys', 'additional_allowed_origins'],- parse: parseCsv,+ parse: parsePasskeyOrigins,},- FLUXER_AUTH_BLUESKY_ENABLED: {path: ['auth', 'bluesky', 'enabled'], parse: parseEnvValue},+ FLUXER_AUTH_BLUESKY_ENABLED: {path: ['auth', 'bluesky', 'enabled'], parse: parseBoolean},FLUXER_AUTH_BLUESKY_CLIENT_NAME: {path: ['auth', 'bluesky', 'client_name']},FLUXER_AUTH_BLUESKY_CLIENT_URI: {path: ['auth', 'bluesky', 'client_uri']},FLUXER_AUTH_BLUESKY_LOGO_URI: {path: ['auth', 'bluesky', 'logo_uri']},FLUXER_AUTH_BLUESKY_TOS_URI: {path: ['auth', 'bluesky', 'tos_uri']},FLUXER_AUTH_BLUESKY_POLICY_URI: {path: ['auth', 'bluesky', 'policy_uri']},- FLUXER_AUTH_BLUESKY_KEYS: {path: ['auth', 'bluesky', 'keys'], parse: parseEnvValue},- FLUXER_EMAIL_ENABLED: {path: ['integrations', 'email', 'enabled'], parse: parseEnvValue},+ FLUXER_AUTH_BLUESKY_KEYS: {path: ['auth', 'bluesky', 'keys'], parse: parseJsonArray},+ FLUXER_EMAIL_ENABLED: {path: ['integrations', 'email', 'enabled'], parse: parseBoolean},FLUXER_EMAIL_PROVIDER: {path: ['integrations', 'email', 'provider']},FLUXER_EMAIL_FROM_EMAIL: {path: ['integrations', 'email', 'from_email']},FLUXER_EMAIL_FROM_NAME: {path: ['integrations', 'email', 'from_name']},@@ -232,27 +232,27 @@ const NAMED_FLUXER_ENV_OVERRIDES: Record<string, NamedEnvOverride> = {FLUXER_EMAIL_SMTP_PORT: {path: ['integrations', 'email', 'smtp', 'port'], parse: parseInteger},FLUXER_EMAIL_SMTP_USERNAME: {path: ['integrations', 'email', 'smtp', 'username']},FLUXER_EMAIL_SMTP_PASSWORD: {path: ['integrations', 'email', 'smtp', 'password']},- FLUXER_EMAIL_SMTP_SECURE: {path: ['integrations', 'email', 'smtp', 'secure'], parse: parseEnvValue},- FLUXER_SMS_ENABLED: {path: ['integrations', 'sms', 'enabled'], parse: parseEnvValue},+ FLUXER_EMAIL_SMTP_SECURE: {path: ['integrations', 'email', 'smtp', 'secure'], parse: parseBoolean},+ FLUXER_SMS_ENABLED: {path: ['integrations', 'sms', 'enabled'], parse: parseBoolean},FLUXER_SMS_ACCOUNT_SID: {path: ['integrations', 'sms', 'account_sid']},FLUXER_SMS_AUTH_TOKEN: {path: ['integrations', 'sms', 'auth_token']},FLUXER_SMS_VERIFY_SERVICE_SID: {path: ['integrations', 'sms', 'verify_service_sid']},FLUXER_SMS_INBOUND_CHALLENGE_NUMBER: {path: ['integrations', 'sms', 'inbound_challenge_number']},FLUXER_SMS_INBOUND_WEBHOOK_AUTH_TOKEN: {path: ['integrations', 'sms', 'inbound_webhook_auth_token']},FLUXER_SMS_INBOUND_WEBHOOK_PUBLIC_URL: {path: ['integrations', 'sms', 'inbound_webhook_public_url']},- FLUXER_CAPTCHA_ENABLED: {path: ['integrations', 'captcha', 'enabled'], parse: parseEnvValue},+ FLUXER_CAPTCHA_ENABLED: {path: ['integrations', 'captcha', 'enabled'], parse: parseBoolean},FLUXER_CAPTCHA_PROVIDER: {path: ['integrations', 'captcha', 'provider']},FLUXER_CAPTCHA_HCAPTCHA_SITE_KEY: {path: ['integrations', 'captcha', 'hcaptcha', 'site_key']},FLUXER_CAPTCHA_HCAPTCHA_SECRET_KEY: {path: ['integrations', 'captcha', 'hcaptcha', 'secret_key']},FLUXER_CAPTCHA_TURNSTILE_SITE_KEY: {path: ['integrations', 'captcha', 'turnstile', 'site_key']},FLUXER_CAPTCHA_TURNSTILE_SECRET_KEY: {path: ['integrations', 'captcha', 'turnstile', 'secret_key']},- FLUXER_LIVEKIT_ENABLED: {path: ['integrations', 'voice', 'enabled'], parse: parseEnvValue},+ FLUXER_LIVEKIT_ENABLED: {path: ['integrations', 'voice', 'enabled'], parse: parseBoolean},FLUXER_LIVEKIT_API_KEY: {path: ['integrations', 'voice', 'api_key']},FLUXER_LIVEKIT_API_SECRET: {path: ['integrations', 'voice', 'api_secret']},FLUXER_LIVEKIT_URL: {path: ['integrations', 'voice', 'url']},FLUXER_LIVEKIT_INTERNAL_URL: {path: ['integrations', 'voice', 'internal_url']},FLUXER_LIVEKIT_WEBHOOK_URL: {path: ['integrations', 'voice', 'webhook_url']},- FLUXER_LIVEKIT_DEFAULT_REGION: {path: ['integrations', 'voice', 'default_region'], parse: parseEnvValue},+ FLUXER_LIVEKIT_DEFAULT_REGION: {path: ['integrations', 'voice', 'default_region'], parse: parseJsonObject},FLUXER_SEARCH_ENGINE: {path: ['integrations', 'search', 'engine']},FLUXER_SEARCH_URL: {path: ['integrations', 'search', 'url']},FLUXER_SEARCH_API_KEY: {path: ['integrations', 'search', 'api_key']},@@ -260,13 +260,13 @@ const NAMED_FLUXER_ENV_OVERRIDES: Record<string, NamedEnvOverride> = {FLUXER_SEARCH_PASSWORD: {path: ['integrations', 'search', 'password']},FLUXER_SEARCH_TLS_REJECT_UNAUTHORIZED: {path: ['integrations', 'search', 'tls_reject_unauthorized'],- parse: parseEnvValue,+ parse: parseBoolean,},- FLUXER_STRIPE_ENABLED: {path: ['integrations', 'stripe', 'enabled'], parse: parseEnvValue},+ FLUXER_STRIPE_ENABLED: {path: ['integrations', 'stripe', 'enabled'], parse: parseBoolean},FLUXER_STRIPE_SECRET_KEY: {path: ['integrations', 'stripe', 'secret_key']},FLUXER_STRIPE_WEBHOOK_SECRET: {path: ['integrations', 'stripe', 'webhook_secret']},- FLUXER_STRIPE_PRICES: {path: ['integrations', 'stripe', 'prices'], parse: parseEnvValue},- FLUXER_STRIPE_LEGACY_PRICES: {path: ['integrations', 'stripe', 'legacy_prices'], parse: parseEnvValue},+ FLUXER_STRIPE_PRICES: {path: ['integrations', 'stripe', 'prices'], parse: parseJsonObject},+ FLUXER_STRIPE_LEGACY_PRICES: {path: ['integrations', 'stripe', 'legacy_prices'], parse: parseJsonObject},FLUXER_STRIPE_PRICE_MONTHLY_USD: {path: ['integrations', 'stripe', 'prices', 'monthly_usd']},FLUXER_STRIPE_PRICE_MONTHLY_EUR: {path: ['integrations', 'stripe', 'prices', 'monthly_eur']},FLUXER_STRIPE_PRICE_MONTHLY_BRL: {path: ['integrations', 'stripe', 'prices', 'monthly_brl']},@@ -307,22 +307,22 @@ const NAMED_FLUXER_ENV_OVERRIDES: Record<string, NamedEnvOverride> = {FLUXER_STRIPE_PRICE_GIFT_1_YEAR_INR: {path: ['integrations', 'stripe', 'prices', 'gift_1_year_inr']},FLUXER_STRIPE_PRICE_GIFT_1_YEAR_PLN: {path: ['integrations', 'stripe', 'prices', 'gift_1_year_pln']},FLUXER_STRIPE_PRICE_GIFT_1_YEAR_TRY: {path: ['integrations', 'stripe', 'prices', 'gift_1_year_try']},- FLUXER_NCMEC_ENABLED: {path: ['integrations', 'ncmec', 'enabled'], parse: parseEnvValue},+ FLUXER_NCMEC_ENABLED: {path: ['integrations', 'ncmec', 'enabled'], parse: parseBoolean},FLUXER_NCMEC_BASE_URL: {path: ['integrations', 'ncmec', 'base_url']},FLUXER_NCMEC_USERNAME: {path: ['integrations', 'ncmec', 'username']},FLUXER_NCMEC_PASSWORD: {path: ['integrations', 'ncmec', 'password']},FLUXER_NCMEC_REPORTER_EMAIL: {path: ['integrations', 'ncmec', 'reporter_email']},- FLUXER_CLAMAV_ENABLED: {path: ['integrations', 'clamav', 'enabled'], parse: parseEnvValue},+ FLUXER_CLAMAV_ENABLED: {path: ['integrations', 'clamav', 'enabled'], parse: parseBoolean},FLUXER_CLAMAV_HOST: {path: ['integrations', 'clamav', 'host']},FLUXER_CLAMAV_PORT: {path: ['integrations', 'clamav', 'port'], parse: parseInteger},- FLUXER_CLAMAV_FAIL_OPEN: {path: ['integrations', 'clamav', 'fail_open'], parse: parseEnvValue},+ FLUXER_CLAMAV_FAIL_OPEN: {path: ['integrations', 'clamav', 'fail_open'], parse: parseBoolean},FLUXER_KLIPY_API_KEY: {path: ['integrations', 'klipy', 'api_key']},FLUXER_YOUTUBE_API_KEY: {path: ['integrations', 'youtube', 'api_key']},- FLUXER_BUNNY_PURGE_ENABLED: {path: ['integrations', 'bunny', 'purge_enabled'], parse: parseEnvValue},- FLUXER_BLOCKLIST_FEEDS_ENABLED: {path: ['integrations', 'blocklist_feeds', 'enabled'], parse: parseEnvValue},+ FLUXER_BUNNY_PURGE_ENABLED: {path: ['integrations', 'bunny', 'purge_enabled'], parse: parseBoolean},+ FLUXER_BLOCKLIST_FEEDS_ENABLED: {path: ['integrations', 'blocklist_feeds', 'enabled'], parse: parseBoolean},FLUXER_BUNNY_API_KEY: {path: ['integrations', 'bunny', 'api_key']},FLUXER_BUNNY_PULL_ZONE_ID: {path: ['integrations', 'bunny', 'pull_zone_id'], parse: parseInteger},- FLUXER_RISK_INTEGRATION_ENABLED: {path: ['integrations', 'risk_integration', 'enabled'], parse: parseEnvValue},+ FLUXER_RISK_INTEGRATION_ENABLED: {path: ['integrations', 'risk_integration', 'enabled'], parse: parseBoolean},FLUXER_RISK_IPINFO_API_KEY: {path: ['integrations', 'risk_integration', 'ipinfo_api_key']},FLUXER_ACCOUNT_POLICY_DSL: {path: ['integrations', 'risk_integration', 'account_policy_dsl'],@@ -330,32 +330,32 @@ const NAMED_FLUXER_ENV_OVERRIDES: Record<string, NamedEnvOverride> = {},FLUXER_RISK_TOR_BLOCK_ALL_RELAYS: {path: ['integrations', 'risk_integration', 'tor', 'block_all_relays'],- parse: parseEnvValue,+ parse: parseBoolean,},FLUXER_RISK_TOR_REVERSE_DNS_HEURISTIC: {path: ['integrations', 'risk_integration', 'tor', 'reverse_dns_heuristic'],- parse: parseEnvValue,+ parse: parseBoolean,},FLUXER_RISK_TOR_REVERSE_DNS_TIMEOUT_MS: {path: ['integrations', 'risk_integration', 'tor', 'reverse_dns_timeout_ms'],parse: parseInteger,},- FLUXER_PUSH_APNS_ENABLED: {path: ['integrations', 'push', 'apns', 'enabled'], parse: parseEnvValue},+ FLUXER_PUSH_APNS_ENABLED: {path: ['integrations', 'push', 'apns', 'enabled'], parse: parseBoolean},FLUXER_PUSH_APNS_TEAM_ID: {path: ['integrations', 'push', 'apns', 'team_id']},FLUXER_PUSH_APNS_KEY_ID: {path: ['integrations', 'push', 'apns', 'key_id']},FLUXER_PUSH_APNS_PRIVATE_KEY: {path: ['integrations', 'push', 'apns', 'private_key']},FLUXER_PUSH_APNS_PRIVATE_KEY_PATH: {path: ['integrations', 'push', 'apns', 'private_key_path']},FLUXER_PUSH_APNS_DEFAULT_ENVIRONMENT: {path: ['integrations', 'push', 'apns', 'default_environment']},- FLUXER_PUSH_APNS_APPS: {path: ['integrations', 'push', 'apns', 'apps'], parse: parseEnvValue},- FLUXER_PUSH_FCM_ENABLED: {path: ['integrations', 'push', 'fcm', 'enabled'], parse: parseEnvValue},+ FLUXER_PUSH_APNS_APPS: {path: ['integrations', 'push', 'apns', 'apps'], parse: parseJsonArray},+ FLUXER_PUSH_FCM_ENABLED: {path: ['integrations', 'push', 'fcm', 'enabled'], parse: parseBoolean},FLUXER_PUSH_FCM_PROJECT_ID: {path: ['integrations', 'push', 'fcm', 'project_id']},FLUXER_PUSH_FCM_CLIENT_EMAIL: {path: ['integrations', 'push', 'fcm', 'client_email']},FLUXER_PUSH_FCM_PRIVATE_KEY: {path: ['integrations', 'push', 'fcm', 'private_key']},FLUXER_PUSH_FCM_PRIVATE_KEY_PATH: {path: ['integrations', 'push', 'fcm', 'private_key_path']},FLUXER_PUSH_FCM_SERVICE_ACCOUNT_JSON_PATH: {path: ['integrations', 'push', 'fcm', 'service_account_json_path']},FLUXER_PUSH_FCM_TOKEN_URI: {path: ['integrations', 'push', 'fcm', 'token_uri']},- FLUXER_PUSH_FCM_APPS: {path: ['integrations', 'push', 'fcm', 'apps'], parse: parseEnvValue},- FLUXER_SELF_HOSTED: {path: ['instance', 'self_hosted'], parse: parseEnvValue},+ FLUXER_PUSH_FCM_APPS: {path: ['integrations', 'push', 'fcm', 'apps'], parse: parseJsonArray},+ FLUXER_SELF_HOSTED: {path: ['instance', 'self_hosted'], parse: parseBoolean},FLUXER_AUTO_JOIN_INVITE_CODE: {path: ['instance', 'auto_join_invite_code']},FLUXER_VISIONARIES_GUILD_ID: {path: ['instance', 'visionaries_guild_id']},FLUXER_VISIONARIES_GUILD_VISIONARY_ROLE_ID: {path: ['instance', 'visionaries_guild_visionary_role_id']},@@ -366,7 +366,7 @@ const NAMED_FLUXER_ENV_OVERRIDES: Record<string, NamedEnvOverride> = {FLUXER_APP_WORDMARK_URL: {path: ['instance', 'branding', 'wordmark_url']},FLUXER_APP_FAVICON_URL: {path: ['instance', 'branding', 'favicon_url']},FLUXER_APP_THEME_COLOR: {path: ['instance', 'branding', 'theme_color']},- FLUXER_INSTANCE_SETUP_CONFIGURED: {path: ['instance', 'setup', 'configured'], parse: parseEnvValue},+ FLUXER_INSTANCE_SETUP_CONFIGURED: {path: ['instance', 'setup', 'configured'], parse: parseBoolean},FLUXER_ABUSE_INBOUND_PHONE_COUNTRY_CODES: {path: ['instance', 'abuse_policy', 'inbound_phone_country_codes'],parse: parseCsv,@@ -377,7 +377,7 @@ const NAMED_FLUXER_ENV_OVERRIDES: Record<string, NamedEnvOverride> = {},FLUXER_ABUSE_DIRECT_CONTACT_SPAM_ENABLED: {path: ['instance', 'abuse_policy', 'direct_contact_spam', 'enabled'],- parse: parseEnvValue,+ parse: parseBoolean,},FLUXER_ABUSE_DIRECT_CONTACT_SPAM_COUNTRY_CODES: {path: ['instance', 'abuse_policy', 'direct_contact_spam', 'country_codes'],@@ -394,14 +394,14 @@ const NAMED_FLUXER_ENV_OVERRIDES: Record<string, NamedEnvOverride> = {FLUXER_ABUSE_DIRECT_CONTACT_SPAM_ACTION: {path: ['instance', 'abuse_policy', 'direct_contact_spam', 'action'],},- FLUXER_DISCOVERY_ENABLED: {path: ['discovery', 'enabled'], parse: parseEnvValue},+ FLUXER_DISCOVERY_ENABLED: {path: ['discovery', 'enabled'], parse: parseBoolean},FLUXER_DISCOVERY_MIN_MEMBER_COUNT: {path: ['discovery', 'min_member_count'], parse: parseInteger},FLUXER_DELETION_GRACE_PERIOD_HOURS: {path: ['deletion_grace_period_hours'], parse: parseInteger},- FLUXER_RELAX_REGISTRATION_RATE_LIMITS: {path: ['dev', 'relax_registration_rate_limits'], parse: parseEnvValue},- FLUXER_DISABLE_RATE_LIMITS: {path: ['dev', 'disable_rate_limits'], parse: parseEnvValue},- FLUXER_TEST_MODE_ENABLED: {path: ['dev', 'test_mode_enabled'], parse: parseEnvValue},+ FLUXER_RELAX_REGISTRATION_RATE_LIMITS: {path: ['dev', 'relax_registration_rate_limits'], parse: parseBoolean},+ FLUXER_DISABLE_RATE_LIMITS: {path: ['dev', 'disable_rate_limits'], parse: parseBoolean},+ FLUXER_TEST_MODE_ENABLED: {path: ['dev', 'test_mode_enabled'], parse: parseBoolean},FLUXER_TEST_HARNESS_TOKEN: {path: ['dev', 'test_harness_token']},- FLUXER_VALIDATE_RESPONSES: {path: ['dev', 'validate_responses'], parse: parseEnvValue},+ FLUXER_VALIDATE_RESPONSES: {path: ['dev', 'validate_responses'], parse: parseBoolean},FLUXER_GEOIP_DB_PATH: {path: ['geoip', 'maxmind_db_path']},};@@ -414,10 +414,14 @@ function createChildContainer(nextKey: ConfigPathKey | undefined): ConfigContain}function getChildValue(target: ConfigContainer, key: ConfigPathKey): unknown {- return target[key as keyof typeof target];+ return Object.hasOwn(target, key) ? Reflect.get(target, key) : undefined;}function setChildValue(target: ConfigContainer, key: ConfigPathKey, value: unknown): void {+ if (key === '__proto__') {+ Object.defineProperty(target, key, {value, writable: true, enumerable: true, configurable: true});+ return;+ }if (Array.isArray(target) && typeof key === 'number') {target[key] = value;return;@@ -425,34 +429,53 @@ function setChildValue(target: ConfigContainer, key: ConfigPathKey, value: unkno(target as ConfigObject)[String(key)] = value;}-function toChildContainer(value: unknown, nextKey: ConfigPathKey | undefined): ConfigContainer {- if (isContainer(value)) {- return value;+function parseBoolean(raw: string): boolean {+ switch (raw.trim().toLowerCase()) {+ case 'true':+ return true;+ case 'false':+ return false;+ default:+ throw new Error('must be true or false');}- return createChildContainer(nextKey);+}++function parseJson(raw: string): unknown {+ const trimmed = raw.trim();+ if (trimmed.length === 0) return undefined;+ try {+ return JSON.parse(trimmed);+ } catch {+ throw new Error('must be valid JSON');+ }+}++function parseJsonObject(raw: string): ConfigObject | undefined {+ const value = parseJson(raw);+ if (value === undefined || isConfigObject(value)) return value;+ throw new Error('must be a JSON object');+}++function parseJsonArray(raw: string): Array<unknown> | undefined {+ const value = parseJson(raw);+ if (value === undefined || Array.isArray(value)) return value;+ throw new Error('must be a JSON array');}export function parseEnvValue(raw: string): unknown {const trimmed = raw.trim();const lower = trimmed.toLowerCase();- if (lower === 'true') {- return true;- }- if (lower === 'false') {- return false;- }+ if (lower === 'true' || lower === 'false') return parseBoolean(trimmed);if (/^-?\d+$/.test(trimmed)) {- return Number.parseInt(trimmed, 10);+ return parseInteger(trimmed);}if (/^-?\d+\.\d+$/.test(trimmed)) {- return Number.parseFloat(trimmed);+ const value = Number(trimmed);+ if (!Number.isFinite(value)) throw new Error('must be a finite number');+ return value;}if (trimmed.startsWith('{') || trimmed.startsWith('[')) {- try {- return JSON.parse(trimmed);- } catch (error) {- throw new Error(`must be valid JSON: ${error instanceof Error ? error.message : String(error)}`);- }+ return parseJson(trimmed);}return raw;}@@ -465,7 +488,9 @@ function parseInteger(raw: string): number | undefined {if (!/^-?\d+$/.test(trimmed)) {throw new Error(`must be an integer, got ${JSON.stringify(raw)}`);}- return Number.parseInt(trimmed, 10);+ const value = Number(trimmed);+ if (!Number.isSafeInteger(value)) throw new Error('must be a safe integer');+ return value;}function parseCsv(raw: string): Array<string> {@@ -475,6 +500,13 @@ function parseCsv(raw: string): Array<string> {.filter((part) => part.length > 0);}+function parsePasskeyOrigins(raw: string): Array<string> {+ if (/\p{Cc}/u.test(raw)) {+ throw new Error('must not contain control characters');+ }+ return parseCsv(raw);+}+export function setNestedValue(target: ConfigContainer, keys: Array<ConfigPathKey>, value: unknown): void {if (keys.length === 0) {return;@@ -484,11 +516,15 @@ export function setNestedValue(target: ConfigContainer, keys: Array<ConfigPathKesetChildValue(target, first, value);return;}- const child = getChildValue(target, first);- if (!isContainer(child)) {- setChildValue(target, first, createChildContainer(rest[0]));+ const current = getChildValue(target, first);+ let child: ConfigContainer;+ if (isContainer(current)) {+ child = current;+ } else {+ child = createChildContainer(rest[0]);+ setChildValue(target, first, child);}- setNestedValue(toChildContainer(getChildValue(target, first), rest[0]), rest, value);+ setNestedValue(child, rest, value);}const NAMED_FLUXER_ENV_ALIASES: Record<string, string | undefined> = {@@ -506,7 +542,7 @@ export function buildNamedFluxerEnvOverrides(env: NodeJS.ProcessEnv): ConfigObje}let parsed: unknown;try {- parsed = (mapping.parse ?? ((value: string) => value))(raw);+ parsed = mapping.parse ? mapping.parse(raw) : raw;} catch (error) {throw new Error(`${envKey} ${error instanceof Error ? error.message : String(error)}`);}diff --git a/packages/constants/src/ApiErrorCodes.ts b/packages/constants/src/ApiErrorCodes.tsindex 3d16cb73f..d88a948af 100644--- a/packages/constants/src/ApiErrorCodes.ts+++ b/packages/constants/src/ApiErrorCodes.ts@@ -7,9 +7,7 @@ export const APIErrorCodes = {BAD_GATEWAY: 'BAD_GATEWAY',BAD_REQUEST: 'BAD_REQUEST',BLUESKY_OAUTH_AUTHORIZATION_FAILED: 'BLUESKY_OAUTH_AUTHORIZATION_FAILED',- BLUESKY_OAUTH_CALLBACK_FAILED: 'BLUESKY_OAUTH_CALLBACK_FAILED',BLUESKY_OAUTH_NOT_ENABLED: 'BLUESKY_OAUTH_NOT_ENABLED',- BLUESKY_OAUTH_STATE_INVALID: 'BLUESKY_OAUTH_STATE_INVALID',ACCOUNT_SUSPENDED_PERMANENTLY: 'ACCOUNT_SUSPENDED_PERMANENTLY',ACCOUNT_SUSPENDED_TEMPORARILY: 'ACCOUNT_SUSPENDED_TEMPORARILY',ACCOUNT_SUSPICIOUS_ACTIVITY: 'ACCOUNT_SUSPICIOUS_ACTIVITY',diff --git a/packages/date_utils/src/DateDuration.ts b/packages/date_utils/src/DateDuration.tsindex 91668340a..6d2724597 100644--- a/packages/date_utils/src/DateDuration.ts+++ b/packages/date_utils/src/DateDuration.ts@@ -28,28 +28,28 @@ export function formatDuration(seconds: number): string {export function formatShortRelativeTime(timestamp: DateInput, minUnit: '1m' | 'now' = 'now'): string {const date = parseDate(timestamp);const now = new Date();- const diffMs = date.getTime() - now.getTime();+ const diffMs = Math.abs(date.getTime() - now.getTime());const diffSeconds = Math.floor(diffMs / 1000);const diffMinutes = Math.floor(diffSeconds / SECONDS_PER_MINUTE);const diffHours = Math.floor(diffMinutes / MINUTES_PER_HOUR);const diffDays = Math.floor(diffHours / HOURS_PER_DAY);- if (Math.abs(diffSeconds) < SECONDS_PER_MINUTE) {+ if (diffSeconds < SECONDS_PER_MINUTE) {return minUnit === '1m' ? '1m' : 'now';}- if (Math.abs(diffMinutes) < MINUTES_PER_HOUR) {- return `${Math.abs(diffMinutes)}m`;+ if (diffMinutes < MINUTES_PER_HOUR) {+ return `${diffMinutes}m`;}- if (Math.abs(diffHours) < HOURS_PER_DAY) {- return `${Math.abs(diffHours)}h`;+ if (diffHours < HOURS_PER_DAY) {+ return `${diffHours}h`;}- if (Math.abs(diffDays) < DAYS_PER_WEEK) {- return `${Math.abs(diffDays)}d`;+ if (diffDays < DAYS_PER_WEEK) {+ return `${diffDays}d`;}- if (Math.abs(diffDays) < DAYS_PER_MONTH) {- return `${Math.floor(Math.abs(diffDays) / DAYS_PER_WEEK)}w`;+ if (diffDays < DAYS_PER_MONTH) {+ return `${Math.floor(diffDays / DAYS_PER_WEEK)}w`;}- if (Math.abs(diffDays) < DAYS_PER_YEAR) {- return `${Math.floor(Math.abs(diffDays) / DAYS_PER_MONTH)}mo`;+ if (diffDays < DAYS_PER_YEAR) {+ return `${Math.floor(diffDays / DAYS_PER_MONTH)}mo`;}- return `${Math.floor(Math.abs(diffDays) / DAYS_PER_YEAR)}y`;+ return `${Math.floor(diffDays / DAYS_PER_YEAR)}y`;}diff --git a/packages/date_utils/src/DateHourCycle.ts b/packages/date_utils/src/DateHourCycle.tsindex e03d8f633..54305b40a 100644--- a/packages/date_utils/src/DateHourCycle.ts+++ b/packages/date_utils/src/DateHourCycle.ts@@ -1,26 +1,7 @@// SPDX-License-Identifier: AGPL-3.0-or-later-const TWELVE_HOUR_LOCALES = [- 'en-us',- 'en-ca',- 'en-au',- 'en-nz',- 'en-ph',- 'en-in',- 'en-pk',- 'en-bd',- 'en-za',- 'es-mx',- 'es-co',- 'ar',- 'hi',- 'bn',- 'ur',- 'fil',- 'tl',-];+import {getDateFormatter} from '@fluxer/date_utils/src/DateFormatterCache';export function localeUses12Hour(locale: string): boolean {- const lang = locale.toLowerCase();- return TWELVE_HOUR_LOCALES.some((l) => lang.startsWith(l));+ return getDateFormatter(locale, {hour: 'numeric'}).resolvedOptions().hour12 === true;}diff --git a/packages/date_utils/src/DateIntrospection.ts b/packages/date_utils/src/DateIntrospection.tsindex f08eaf900..853ac045b 100644--- a/packages/date_utils/src/DateIntrospection.ts+++ b/packages/date_utils/src/DateIntrospection.ts@@ -12,20 +12,17 @@ export function getDateFieldOrder(locale: string): Array<DateFieldType> {const parts = formatter.formatToParts(new Date(2000, 0, 1));const order: Array<DateFieldType> = [];for (const part of parts) {- if (part.type === 'month' && !order.includes('month')) {- order.push('month');- } else if (part.type === 'day' && !order.includes('day')) {- order.push('day');- } else if (part.type === 'year' && !order.includes('year')) {- order.push('year');+ if ((part.type === 'month' || part.type === 'day' || part.type === 'year') && !order.includes(part.type)) {+ order.push(part.type);}}return order;}export function getMonthNames(locale: string, format: 'long' | 'short' = 'long'): Array<string> {+ const formatter = getDateFormatter(locale, {month: format});return Array.from({length: 12}, (_, index) => {const monthDate = new Date(2000, index, 1);- return getDateFormatter(locale, {month: format}).format(monthDate);+ return formatter.format(monthDate);});}diff --git a/packages/date_utils/src/TimeZoneUtils.ts b/packages/date_utils/src/TimeZoneUtils.tsindex d586530c7..6094c1766 100644--- a/packages/date_utils/src/TimeZoneUtils.ts+++ b/packages/date_utils/src/TimeZoneUtils.ts@@ -1,19 +1,9 @@// SPDX-License-Identifier: AGPL-3.0-or-later-import {getTimeZones, timeZonesNames} from '@vvo/tzdb';+import {getTimeZones, type TimeZone, timeZonesNames} from '@vvo/tzdb';const UTC_TIME_ZONE_ID = 'UTC';-interface TimeZoneRecord {- readonly name: string;- readonly group: ReadonlyArray<string>;- readonly alternativeName?: string;- readonly countryName?: string;- readonly countryCode?: string;- readonly mainCities: ReadonlyArray<string>;- readonly currentTimeOffsetInMinutes: number;-}-interface TimeZoneDisplayOption {readonly value: string;readonly label: string;@@ -28,17 +18,15 @@ function cleanTimeZoneId(timeZone: string | null | undefined): string | null {return value ? value : null;}-function getDisplayTimeZones(): Array<TimeZoneRecord> {- return getTimeZones({includeUtc: true});+function getDisplayTimeZones(): Array<TimeZone> {+ return getTimeZones({includeUtc: true}).map((record) =>+ record.group.includes(UTC_TIME_ZONE_ID) ? {...record, name: UTC_TIME_ZONE_ID} : record,+ );}-function findTimeZone(timeZone: string | null | undefined): TimeZoneRecord | null {- const value = cleanTimeZoneId(timeZone);- if (!value) {- return null;- }+function findTimeZone(timeZone: string): TimeZone | null {for (const record of getDisplayTimeZones()) {- if (record.name === value || record.group.includes(value)) {+ if (record.name === timeZone || record.group.includes(timeZone)) {return record;}}@@ -81,7 +69,13 @@ export function isSupportedTimeZoneId(timeZone: string | null | undefined): bool}export function getCurrentTimeZoneOffsetMinutes(timeZone: string | null | undefined): number | null {- const record = findTimeZone(timeZone);+ const value = cleanTimeZoneId(timeZone);+ if (!value) return null;+ if (supportedTimeZoneIds.has(value)) {+ const offset = getRuntimeOffsetMinutes(value);+ if (offset !== null) return offset;+ }+ const record = findTimeZone(value);if (!record) {return null;}@@ -98,7 +92,7 @@ function formatUtcOffset(offsetMinutes: number): string {return `UTC${sign}${hours}:${minutes}`;}-function formatTimeZonePlace(record: TimeZoneRecord): string {+function formatTimeZonePlace(record: TimeZone): string {if (record.name === UTC_TIME_ZONE_ID) {return UTC_TIME_ZONE_ID;}diff --git a/packages/errors/src/ErrorHandler.ts b/packages/errors/src/ErrorHandler.tsindex 23eec3d5b..98285ac57 100644--- a/packages/errors/src/ErrorHandler.ts+++ b/packages/errors/src/ErrorHandler.ts@@ -1,25 +1,12 @@// SPDX-License-Identifier: AGPL-3.0-or-laterimport {HttpStatus} from '@fluxer/constants/src/HttpConstants';+import {getApiErrorCodeForStatus} from '@fluxer/errors/src/error_handling/ErrorIntrospection';import {createJsonErrorResponse, createXmlErrorResponse} from '@fluxer/errors/src/error_handling/ErrorResponse';import {FluxerError} from '@fluxer/errors/src/FluxerError';import type {Context, ErrorHandler} from 'hono';import {HTTPException} from 'hono/http-exception';-const HTTP_STATUS_TO_ERROR_CODE: Record<number, string> = {- 400: 'BAD_REQUEST',- 403: 'FORBIDDEN',- 404: 'NOT_FOUND',- 405: 'METHOD_NOT_ALLOWED',- 409: 'CONFLICT',- 410: 'GONE',- 500: 'INTERNAL_SERVER_ERROR',- 501: 'NOT_IMPLEMENTED',- 502: 'BAD_GATEWAY',- 503: 'SERVICE_UNAVAILABLE',- 504: 'GATEWAY_TIMEOUT',-};-export type ResponseFormat = 'json' | 'xml';export interface ErrorHandlerOptions {@@ -46,7 +33,7 @@ export function createErrorHandler(options: ErrorHandlerOptions = {}): ErrorHand}if (error instanceof HTTPException) {const status = error.status;- const code = HTTP_STATUS_TO_ERROR_CODE[status] ?? 'GENERAL_ERROR';+ const code = getApiErrorCodeForStatus(status);const message = error.message || 'An error occurred';if (responseFormat === 'xml') {return createXmlErrorResponse(status, code, message);diff --git a/packages/errors/src/domains/core/ErrorHandlers.ts b/packages/errors/src/domains/core/ErrorHandlers.tsindex d6c77f1de..a400ae589 100644--- a/packages/errors/src/domains/core/ErrorHandlers.ts+++ b/packages/errors/src/domains/core/ErrorHandlers.ts@@ -4,6 +4,7 @@ import {APIErrorCodes} from '@fluxer/constants/src/ApiErrorCodes';import {Locales} from '@fluxer/constants/src/Locales';import {OAuth2Error} from '@fluxer/errors/src/domains/auth/OAuth2Error';import {+ getApiErrorCodeForStatus,getErrorRecord,hasApiErrorCode,resolveApiErrorCode,@@ -202,20 +203,6 @@ function handleKnownErrorCode<E extends BaseHonoEnv>(err: unknown, errorCode: st});}-const HTTP_STATUS_TO_ERROR_CODE: Partial<Record<number, string>> = {- 400: APIErrorCodes.BAD_REQUEST,- 403: APIErrorCodes.FORBIDDEN,- 404: APIErrorCodes.NOT_FOUND,- 405: APIErrorCodes.METHOD_NOT_ALLOWED,- 409: APIErrorCodes.CONFLICT,- 410: APIErrorCodes.GONE,- 500: APIErrorCodes.INTERNAL_SERVER_ERROR,- 501: APIErrorCodes.NOT_IMPLEMENTED,- 502: APIErrorCodes.BAD_GATEWAY,- 503: APIErrorCodes.SERVICE_UNAVAILABLE,- 504: APIErrorCodes.GATEWAY_TIMEOUT,-};-function handleHTTPException<E extends BaseHonoEnv>(err: HTTPException, ctx: Context<E>): Response {const errorRecord = getErrorRecord(err);if (errorRecord && typeof errorRecord.code === 'string' && hasApiErrorCode(errorRecord.code)) {@@ -235,7 +222,7 @@ function handleHTTPException<E extends BaseHonoEnv>(err: HTTPException, ctx: Conheaders: resolveErrorHeaders(err),});}- const code = HTTP_STATUS_TO_ERROR_CODE[err.status] ?? APIErrorCodes.GENERAL_ERROR;+ const code = getApiErrorCodeForStatus(err.status);const {errorI18nService, locale} = getI18nContext(ctx);const resolvedMessage = resolveLocalizedMessage(errorI18nService, code, locale, undefined, err.message);return createJsonErrorResponse({diff --git a/packages/errors/src/error_handling/ErrorIntrospection.ts b/packages/errors/src/error_handling/ErrorIntrospection.tsindex 43db97a38..3dae99566 100644--- a/packages/errors/src/error_handling/ErrorIntrospection.ts+++ b/packages/errors/src/error_handling/ErrorIntrospection.ts@@ -6,6 +6,24 @@ import {HTTPException} from 'hono/http-exception';const apiErrorCodeSet = new Set<string>(Object.values(APIErrorCodes));+const HTTP_STATUS_TO_ERROR_CODE: Partial<Record<number, string>> = {+ 400: APIErrorCodes.BAD_REQUEST,+ 403: APIErrorCodes.FORBIDDEN,+ 404: APIErrorCodes.NOT_FOUND,+ 405: APIErrorCodes.METHOD_NOT_ALLOWED,+ 409: APIErrorCodes.CONFLICT,+ 410: APIErrorCodes.GONE,+ 500: APIErrorCodes.INTERNAL_SERVER_ERROR,+ 501: APIErrorCodes.NOT_IMPLEMENTED,+ 502: APIErrorCodes.BAD_GATEWAY,+ 503: APIErrorCodes.SERVICE_UNAVAILABLE,+ 504: APIErrorCodes.GATEWAY_TIMEOUT,+};++export function getApiErrorCodeForStatus(status: number): string {+ return HTTP_STATUS_TO_ERROR_CODE[status] ?? APIErrorCodes.GENERAL_ERROR;+}+function isRecord(value: unknown): value is Record<string, unknown> {return typeof value === 'object' && value !== null;}@@ -25,11 +43,6 @@ export function resolveApiErrorCode(err: unknown): string | null {if (err instanceof FluxerError) {return err.code;}- if (err instanceof HTTPException && 'code' in err && typeof err.code === 'string') {- if (isApiErrorCode(err.code)) {- return err.code;- }- }const record = getErrorRecord(err);if (!record) {return null;@@ -55,29 +68,14 @@ export function resolveErrorStatus(err: unknown): number | null {}export function resolveErrorData(err: unknown): Record<string, unknown> | undefined {- if (err instanceof HTTPException && 'data' in err && isRecord(err.data)) {- return err.data;- }const record = getErrorRecord(err);if (!record) {return undefined;}- if (isRecord(record.data)) {- return record.data;- }- return undefined;+ return isRecord(record.data) ? record.data : undefined;}export function resolveErrorHeaders(err: unknown): Record<string, string> | undefined {- if (err instanceof HTTPException && 'headers' in err && isRecord(err.headers)) {- const headers: Record<string, string> = {};- for (const [key, value] of Object.entries(err.headers)) {- if (typeof value === 'string') {- headers[key] = value;- }- }- return Object.keys(headers).length > 0 ? headers : undefined;- }const record = getErrorRecord(err);if (!record || !isRecord(record.headers)) {return undefined;@@ -92,9 +90,6 @@ export function resolveErrorHeaders(err: unknown): Record<string, string> | unde}export function resolveMessageVariables(err: unknown): Record<string, unknown> | undefined {- if (err instanceof HTTPException && 'messageVariables' in err && isRecord(err.messageVariables)) {- return err.messageVariables;- }const record = getErrorRecord(err);if (!record) {return undefined;diff --git a/packages/errors/src/error_handling/ErrorResponse.ts b/packages/errors/src/error_handling/ErrorResponse.tsindex fac14db4f..58ccbaa40 100644--- a/packages/errors/src/error_handling/ErrorResponse.ts+++ b/packages/errors/src/error_handling/ErrorResponse.ts@@ -2,12 +2,6 @@import {MimeType} from '@fluxer/constants/src/HttpConstants';-interface JsonResponseOptions {- status: number;- payload: Record<string, unknown>;- headers?: Record<string, string>;-}-interface JsonErrorResponseOptions {status: number;code: string;@@ -16,26 +10,21 @@ interface JsonErrorResponseOptions {headers?: Record<string, string>;}-function createJsonResponse(options: JsonResponseOptions): Response {- return new Response(JSON.stringify(options.payload), {- status: options.status,- headers: {- 'Content-Type': MimeType.JSON,- ...(options.headers ?? {}),- },- });-}-export function createJsonErrorResponse(options: JsonErrorResponseOptions): Response {- return createJsonResponse({- status: options.status,- payload: {+ return new Response(+ JSON.stringify({code: options.code,message: options.message,...(options.data ?? {}),+ }),+ {+ status: options.status,+ headers: {+ 'Content-Type': MimeType.JSON,+ ...(options.headers ?? {}),+ },},- headers: options.headers,- });+ );}export function createXmlErrorResponse(status: number, code: string, message: string): Response {diff --git a/packages/errors/src/i18n/ErrorCodeMappings.ts b/packages/errors/src/i18n/ErrorCodeMappings.tsindex ae47f9e52..75514995b 100644--- a/packages/errors/src/i18n/ErrorCodeMappings.ts+++ b/packages/errors/src/i18n/ErrorCodeMappings.ts@@ -28,9 +28,7 @@ export const ErrorCodeToI18nKey = {[APIErrorCodes.BAD_GATEWAY]: 'http.bad_gateway',[APIErrorCodes.BAD_REQUEST]: 'http.bad_request',[APIErrorCodes.BLUESKY_OAUTH_AUTHORIZATION_FAILED]: 'connections.bluesky_oauth_authorization_failed',- [APIErrorCodes.BLUESKY_OAUTH_CALLBACK_FAILED]: 'connections.bluesky_oauth_callback_failed',[APIErrorCodes.BLUESKY_OAUTH_NOT_ENABLED]: 'connections.bluesky_oauth_not_enabled',- [APIErrorCodes.BLUESKY_OAUTH_STATE_INVALID]: 'connections.bluesky_oauth_state_invalid',[APIErrorCodes.BOT_ALREADY_IN_GUILD]: 'auth_and_oauth.bot_already_in_guild',[APIErrorCodes.BOT_IS_PRIVATE]: 'bots.bot_is_private',[APIErrorCodes.BOT_USER_AUTH_ENDPOINT_ACCESS_DENIED]: 'auth_and_oauth.bot_users_cannot_use_auth_endpoints',diff --git a/packages/errors/src/i18n/ErrorI18nMessages.ts b/packages/errors/src/i18n/ErrorI18nMessages.tsindex d0b851733..d481ef63e 100644--- a/packages/errors/src/i18n/ErrorI18nMessages.ts+++ b/packages/errors/src/i18n/ErrorI18nMessages.ts@@ -228,9 +228,7 @@ export const ERROR_I18N_MESSAGES = {'connections.already_exists': 'A connection of this type with this identifier already exists.','connections.bluesky_oauth_authorization_failed':"We couldn't resolve that Bluesky handle. Please check it and try again.",- 'connections.bluesky_oauth_callback_failed': "We couldn't complete the Bluesky connection. Please try again.",'connections.bluesky_oauth_not_enabled': 'Bluesky connections are not enabled on this instance.',- 'connections.bluesky_oauth_state_invalid': 'The authorization request has expired or is invalid. Please try again.','connections.initiation_token_invalid': 'The connection initiation token is invalid or has expired.','connections.invalid_type': 'The connection type is not supported.','connections.limit_reached': "You've reached the maximum number of connections ({limit}).",diff --git a/packages/errors/src/i18n/locales/ar.ts b/packages/errors/src/i18n/locales/ar.tsindex e6e28f017..223c2320c 100644--- a/packages/errors/src/i18n/locales/ar.ts+++ b/packages/errors/src/i18n/locales/ar.ts@@ -193,9 +193,7 @@ const ERROR_I18N_AR_MESSAGES = defineErrorI18nLocaleMessages({"colors.color_value_too_low": "يجب أن لا تقل قيمة اللون عن 0x000000.","connections.already_exists": "يوجد بالفعل اتصال من هذا النوع بهذا المعرف.","connections.bluesky_oauth_authorization_failed": "لم نتمكن من حل معرّف Bluesky هذا. يُرجى التأكد منه والمحاولة مرة أخرى.",- "connections.bluesky_oauth_callback_failed": "لم نتمكن من إكمال الاتصال بـ Bluesky. يُرجى المحاولة مرة أخرى.","connections.bluesky_oauth_not_enabled": "ميزة الاتصال بـ Bluesky غير ممكّنة في هذا المثيل.",- "connections.bluesky_oauth_state_invalid": "انتهت صلاحية طلب التفويض أو غير صالح. يُرجى المحاولة مرة أخرى.","connections.initiation_token_invalid": "رمز بدء الاتصال غير صالح أو انتهت صلاحيته.","connections.invalid_type": "نوع الاتصال غير مدعوم.","connections.limit_reached": "وصلت إلى الحد الأقصى لعدد الاتصالات ({limit}).",diff --git a/packages/errors/src/i18n/locales/bg.ts b/packages/errors/src/i18n/locales/bg.tsindex c7d48acb9..f47bc0b25 100644--- a/packages/errors/src/i18n/locales/bg.ts+++ b/packages/errors/src/i18n/locales/bg.ts@@ -193,9 +193,7 @@ const ERROR_I18N_BG_MESSAGES = defineErrorI18nLocaleMessages({"colors.color_value_too_low": "Стойността на цвета трябва да е поне 0x000000.","connections.already_exists": "Връзка от този тип с този идентификатор вече съществува.","connections.bluesky_oauth_authorization_failed": "Не успяхме да намерим този Bluesky идентификатор. Моля, провери го и опитай пак.",- "connections.bluesky_oauth_callback_failed": "Не успяхме да установим връзката с Bluesky. Моля, опитай пак.","connections.bluesky_oauth_not_enabled": "Връзките с Bluesky не са активирани на тази инстанция.",- "connections.bluesky_oauth_state_invalid": "Заявката за оторизация е изтекла или е невалидна. Моля, опитай пак.","connections.initiation_token_invalid": "Токенът за иницииране на връзка е невалиден или е изтекъл.","connections.invalid_type": "Типът на връзката не се поддържа.","connections.limit_reached": "Достигнал си максималния брой връзки ({limit}).",diff --git a/packages/errors/src/i18n/locales/cs.ts b/packages/errors/src/i18n/locales/cs.tsindex fb134f784..e5bfe8056 100644--- a/packages/errors/src/i18n/locales/cs.ts+++ b/packages/errors/src/i18n/locales/cs.ts@@ -193,9 +193,7 @@ const ERROR_I18N_CS_MESSAGES = defineErrorI18nLocaleMessages({"colors.color_value_too_low": "Hodnota barvy musí být minimálně 0x000000.","connections.already_exists": "Propojení tohoto typu s tímto ID již existuje.","connections.bluesky_oauth_authorization_failed": "Nepodařilo se najít toto uživatelské jméno Bluesky. Zkontroluj ho a zkus to znovu.",- "connections.bluesky_oauth_callback_failed": "Nepodařilo se dokončit propojení s Bluesky. Zkus to znovu.","connections.bluesky_oauth_not_enabled": "Na této instanci nejsou povolena propojení s Bluesky.",- "connections.bluesky_oauth_state_invalid": "Žádost o autorizaci vypršela nebo je neplatná. Zkus to znovu.","connections.initiation_token_invalid": "Token pro spuštění propojení je neplatný nebo vypršel.","connections.invalid_type": "Tento typ propojení není podporován.","connections.limit_reached": "Dosáhl jsi maximálního počtu propojení ({limit}).",diff --git a/packages/errors/src/i18n/locales/da.ts b/packages/errors/src/i18n/locales/da.tsindex c86a8d087..616086bbf 100644--- a/packages/errors/src/i18n/locales/da.ts+++ b/packages/errors/src/i18n/locales/da.ts@@ -193,9 +193,7 @@ const ERROR_I18N_DA_MESSAGES = defineErrorI18nLocaleMessages({"colors.color_value_too_low": "Farveværdien skal være mindst 0x000000.","connections.already_exists": "En forbindelse af denne type med denne identifikator eksisterer allerede.","connections.bluesky_oauth_authorization_failed": "Vi kunne ikke finde det Bluesky-handle. Tjek det, og prøv igen.",- "connections.bluesky_oauth_callback_failed": "Vi kunne ikke fuldføre Bluesky-forbindelsen. Prøv igen.","connections.bluesky_oauth_not_enabled": "Bluesky-forbindelser er ikke aktiveret på denne instans.",- "connections.bluesky_oauth_state_invalid": "Autorisationsanmodningen er udløbet eller ugyldig. Prøv igen.","connections.initiation_token_invalid": "Forbindelsestokenet er ugyldigt eller udløbet.","connections.invalid_type": "Forbindelsestypen understøttes ikke.","connections.limit_reached": "Du har nået det maksimale antal forbindelser ({limit}).",diff --git a/packages/errors/src/i18n/locales/de.ts b/packages/errors/src/i18n/locales/de.tsindex 73e6c97e7..ad98a35b7 100644--- a/packages/errors/src/i18n/locales/de.ts+++ b/packages/errors/src/i18n/locales/de.ts@@ -193,9 +193,7 @@ const ERROR_I18N_DE_MESSAGES = defineErrorI18nLocaleMessages({"colors.color_value_too_low": "Der Farbwert muss mindestens 0x000000 betragen.","connections.already_exists": "Eine Verbindung dieses Typs mit dieser ID besteht bereits.","connections.bluesky_oauth_authorization_failed": "Wir konnten den Bluesky-Handle nicht auflösen. Überprüfe ihn bitte und versuch es noch mal.",- "connections.bluesky_oauth_callback_failed": "Wir konnten die Bluesky-Verbindung nicht herstellen. Versuch es noch mal.","connections.bluesky_oauth_not_enabled": "Auf dieser Instanz sind Bluesky-Verbindungen nicht aktiviert.",- "connections.bluesky_oauth_state_invalid": "Die Autorisierungsanforderung ist abgelaufen oder ungültig. Versuch es noch mal.","connections.initiation_token_invalid": "Das Token zur Verbindungsherstellung ist ungültig oder abgelaufen.","connections.invalid_type": "Dieser Verbindungstyp wird nicht unterstützt.","connections.limit_reached": "Du hast die maximale Anzahl an Verbindungen ({limit}) erreicht.",diff --git a/packages/errors/src/i18n/locales/el.ts b/packages/errors/src/i18n/locales/el.tsindex 7d3ab313b..8efcda12c 100644--- a/packages/errors/src/i18n/locales/el.ts+++ b/packages/errors/src/i18n/locales/el.ts@@ -193,9 +193,7 @@ const ERROR_I18N_EL_MESSAGES = defineErrorI18nLocaleMessages({"colors.color_value_too_low": "Η τιμή χρώματος πρέπει να είναι τουλάχιστον 0x000000.","connections.already_exists": "Υπάρχει ήδη μια σύνδεση αυτού του τύπου με αυτό το αναγνωριστικό.","connections.bluesky_oauth_authorization_failed": "Δεν μπορέσαμε να επιλύσουμε το όνομα χρήστη Bluesky. Ελέγξτε το και δοκιμάστε ξανά.",- "connections.bluesky_oauth_callback_failed": "Αδυνατούμε να ολοκληρώσουμε τη σύνδεση Bluesky. Δοκιμάστε ξανά.","connections.bluesky_oauth_not_enabled": "Οι συνδέσεις Bluesky δεν είναι ενεργοποιημένες σε αυτήν την εγκατάσταση.",- "connections.bluesky_oauth_state_invalid": "Το αίτημα εξουσιοδότησης έχει λήξει ή είναι μη έγκυρο. Δοκιμάστε ξανά.","connections.initiation_token_invalid": "Το token έναρξης σύνδεσης είναι άκυρο ή έχει λήξει.","connections.invalid_type": "Ο τύπος σύνδεσης δεν υποστηρίζεται.","connections.limit_reached": "Έχεις φτάσει τον μέγιστο αριθμό συνδέσεων ({limit}).",diff --git a/packages/errors/src/i18n/locales/en-GB.ts b/packages/errors/src/i18n/locales/en-GB.tsindex a1bce0166..e7d4f3a78 100644--- a/packages/errors/src/i18n/locales/en-GB.ts+++ b/packages/errors/src/i18n/locales/en-GB.ts@@ -193,9 +193,7 @@ const ERROR_I18N_EN_GB_MESSAGES = defineErrorI18nLocaleMessages({"colors.color_value_too_low": "Colour value must be at least 0x000000.","connections.already_exists": "A connection of this type with this identifier already exists.","connections.bluesky_oauth_authorization_failed": "We couldn't resolve that Bluesky handle. Please check it and try again.",- "connections.bluesky_oauth_callback_failed": "We couldn't complete the Bluesky connection. Please try again.","connections.bluesky_oauth_not_enabled": "Bluesky connections are not enabled on this instance.",- "connections.bluesky_oauth_state_invalid": "The authorization request has expired or is invalid. Please try again.","connections.initiation_token_invalid": "The connection initiation token is invalid or has expired.","connections.invalid_type": "The connection type is not supported.","connections.limit_reached": "You've reached the maximum number of connections ({limit}).",diff --git a/packages/errors/src/i18n/locales/es-419.ts b/packages/errors/src/i18n/locales/es-419.tsindex ffe9283ee..98afdf603 100644--- a/packages/errors/src/i18n/locales/es-419.ts+++ b/packages/errors/src/i18n/locales/es-419.ts@@ -193,9 +193,7 @@ const ERROR_I18N_ES_419_MESSAGES = defineErrorI18nLocaleMessages({"colors.color_value_too_low": "El valor del color debe ser como mínimo 0x000000.","connections.already_exists": "Ya existe una conexión de este tipo con este identificador.","connections.bluesky_oauth_authorization_failed": "No pudimos resolver ese identificador de Bluesky. Verifícalo e inténtalo de nuevo.",- "connections.bluesky_oauth_callback_failed": "No pudimos completar la conexión de Bluesky. Inténtalo de nuevo.","connections.bluesky_oauth_not_enabled": "Las conexiones de Bluesky no están habilitadas en esta instancia.",- "connections.bluesky_oauth_state_invalid": "La solicitud de autorización ha expirado o es inválida. Inténtalo de nuevo.","connections.initiation_token_invalid": "El token de inicio de conexión es inválido o ha expirado.","connections.invalid_type": "El tipo de conexión no es compatible.","connections.limit_reached": "Has alcanzado el número máximo de conexiones ({limit}).",diff --git a/packages/errors/src/i18n/locales/es-ES.ts b/packages/errors/src/i18n/locales/es-ES.tsindex 8eff72eff..5969690d2 100644--- a/packages/errors/src/i18n/locales/es-ES.ts+++ b/packages/errors/src/i18n/locales/es-ES.ts@@ -193,9 +193,7 @@ const ERROR_I18N_ES_ES_MESSAGES = defineErrorI18nLocaleMessages({"colors.color_value_too_low": "El valor del color debe ser al menos 0x000000.","connections.already_exists": "Ya existe una conexión de este tipo y con este identificador.","connections.bluesky_oauth_authorization_failed": "No pudimos resolver ese usuario de Bluesky. Compruébalo e inténtalo de nuevo.",- "connections.bluesky_oauth_callback_failed": "No se pudo completar la conexión con Bluesky. Inténtalo de nuevo.","connections.bluesky_oauth_not_enabled": "Las conexiones de Bluesky no están habilitadas en esta instancia.",- "connections.bluesky_oauth_state_invalid": "La solicitud de autorización ha expirado o no es válida. Inténtalo de nuevo.","connections.initiation_token_invalid": "El token de inicio de conexión no es válido o ha expirado.","connections.invalid_type": "El tipo de conexión no es compatible.","connections.limit_reached": "Has alcanzado el número máximo de conexiones ({limit}).",diff --git a/packages/errors/src/i18n/locales/fi.ts b/packages/errors/src/i18n/locales/fi.tsindex 0e6c7bea7..6a31baaa1 100644--- a/packages/errors/src/i18n/locales/fi.ts+++ b/packages/errors/src/i18n/locales/fi.ts@@ -193,9 +193,7 @@ const ERROR_I18N_FI_MESSAGES = defineErrorI18nLocaleMessages({"colors.color_value_too_low": "Väriarvon täytyy olla vähintään 0x000000.","connections.already_exists": "Tämän tyyppinen yhteys tällä tunnisteella on jo olemassa.","connections.bluesky_oauth_authorization_failed": "Emme voineet selvittää Bluesky-tunnusta. Tarkista tunnus ja yritä uudelleen.",- "connections.bluesky_oauth_callback_failed": "Emme voineet muodostaa Bluesky-yhteyttä. Yritä uudelleen.","connections.bluesky_oauth_not_enabled": "Bluesky-yhteydet eivät ole käytössä tässä instanssissa.",- "connections.bluesky_oauth_state_invalid": "Valtuutuspyyntö on vanhentunut tai virheellinen. Yritä uudelleen.","connections.initiation_token_invalid": "Yhteyden aloitustunnus on virheellinen tai vanhentunut.","connections.invalid_type": "Yhteyden tyyppiä ei tueta.","connections.limit_reached": "Olet saavuttanut yhteyksien enimmäismäärän ({limit}).",diff --git a/packages/errors/src/i18n/locales/fr.ts b/packages/errors/src/i18n/locales/fr.tsindex e9cfeca34..a8df5b170 100644--- a/packages/errors/src/i18n/locales/fr.ts+++ b/packages/errors/src/i18n/locales/fr.ts@@ -193,9 +193,7 @@ const ERROR_I18N_FR_MESSAGES = defineErrorI18nLocaleMessages({"colors.color_value_too_low": "La valeur de couleur doit être au moins 0x000000.","connections.already_exists": "Une connexion de ce type avec cet identifiant existe déjà.","connections.bluesky_oauth_authorization_failed": "Nous n'avons pas pu résoudre ce pseudo Bluesky. Vérifie-le et réessaie.",- "connections.bluesky_oauth_callback_failed": "Nous n'avons pas pu établir la connexion Bluesky. Réessaie.","connections.bluesky_oauth_not_enabled": "Les connexions Bluesky ne sont pas activées sur cette instance.",- "connections.bluesky_oauth_state_invalid": "La demande d'autorisation a expiré ou est invalide. Réessaie.","connections.initiation_token_invalid": "Le jeton d'initialisation de la connexion est invalide ou a expiré.","connections.invalid_type": "Le type de connexion n'est pas pris en charge.","connections.limit_reached": "Tu as atteint le nombre maximum de connexions ({limit}).",diff --git a/packages/errors/src/i18n/locales/he.ts b/packages/errors/src/i18n/locales/he.tsindex 4f7fd1312..51211edb4 100644--- a/packages/errors/src/i18n/locales/he.ts+++ b/packages/errors/src/i18n/locales/he.ts@@ -193,9 +193,7 @@ const ERROR_I18N_HE_MESSAGES = defineErrorI18nLocaleMessages({"colors.color_value_too_low": "ערך הצבע יהיה 0x000000 לפחות.","connections.already_exists": "חיבור מסוג זה עם מזהה זה כבר קיים.","connections.bluesky_oauth_authorization_failed": "לא הצלחנו לאתר את כתובת ה-Bluesky. נא לבדוק ולנסות שוב.",- "connections.bluesky_oauth_callback_failed": "לא הצלחנו להשלים את חיבור ה-Bluesky. ניתן לנסות שוב.","connections.bluesky_oauth_not_enabled": "חיבורי Bluesky לא מופעלים במופע זה.",- "connections.bluesky_oauth_state_invalid": "תוקף בקשת ההרשאה פג או שהיא לא תקפה. יש לנסות שוב.","connections.initiation_token_invalid": "אסימון אתחול החיבור לא תקף או שתוקפו פג.","connections.invalid_type": "סוג החיבור הזה לא נתמך.","connections.limit_reached": "הגעת למספר החיבורים המרבי ({limit}).",diff --git a/packages/errors/src/i18n/locales/hi.ts b/packages/errors/src/i18n/locales/hi.tsindex ca471c456..f1b6e5187 100644--- a/packages/errors/src/i18n/locales/hi.ts+++ b/packages/errors/src/i18n/locales/hi.ts@@ -193,9 +193,7 @@ const ERROR_I18N_HI_MESSAGES = defineErrorI18nLocaleMessages({"colors.color_value_too_low": "कलर वैल्यू कम से कम 0x000000 होनी चाहिए।","connections.already_exists": "इस आइडेंटिफ़ायर के साथ इस प्रकार का कनेक्शन पहले से मौजूद है।","connections.bluesky_oauth_authorization_failed": "हम उस Bluesky हैंडल को सुलझा नहीं पाए। कृपया इसे चेक करें और फिर से कोशिश करें।",- "connections.bluesky_oauth_callback_failed": "हम Bluesky कनेक्शन पूरा नहीं कर सके। कृपया फिर से कोशिश करें।","connections.bluesky_oauth_not_enabled": "इस इंस्टेंस पर Bluesky कनेक्शन सक्षम नहीं हैं।",- "connections.bluesky_oauth_state_invalid": "ऑथराइज़ेशन रिक्वेस्ट एक्सपायर हो गई है या अमान्य है। कृपया फिर से कोशिश करें।","connections.initiation_token_invalid": "कनेक्शन इनिशिएशन टोकन अमान्य है या एक्सपायर हो गया है।","connections.invalid_type": "कनेक्शन टाइप समर्थित नहीं है।","connections.limit_reached": "आपकी अधिकतम कनेक्शन ({limit}) की सीमा पूरी हो गई है।",diff --git a/packages/errors/src/i18n/locales/hr.ts b/packages/errors/src/i18n/locales/hr.tsindex 40059302f..db2536d24 100644--- a/packages/errors/src/i18n/locales/hr.ts+++ b/packages/errors/src/i18n/locales/hr.ts@@ -193,9 +193,7 @@ const ERROR_I18N_HR_MESSAGES = defineErrorI18nLocaleMessages({"colors.color_value_too_low": "Vrijednost boje mora biti najmanje 0x000000.","connections.already_exists": "Već postoji veza ove vrste s ovim identifikatorom.","connections.bluesky_oauth_authorization_failed": "Nismo ti mogli razriješiti to Bluesky korisničko ime. Provjeri ga i pokušaj ponovno.",- "connections.bluesky_oauth_callback_failed": "Nismo ti mogli dovršiti Bluesky vezu. Pokušaj ponovno.","connections.bluesky_oauth_not_enabled": "Bluesky veze nisu omogućene na ovoj instanci.",- "connections.bluesky_oauth_state_invalid": "Zahtjev za autorizaciju je istekao ili je nevažeći. Pokušaj ponovno.","connections.initiation_token_invalid": "Token za uspostavu veze je nevažeći ili je istekao.","connections.invalid_type": "Ova vrsta veze nije podržana.","connections.limit_reached": "Dostigao si maksimalan broj veza ({limit}).",diff --git a/packages/errors/src/i18n/locales/hu.ts b/packages/errors/src/i18n/locales/hu.tsindex 73c6a9396..86c5403a0 100644--- a/packages/errors/src/i18n/locales/hu.ts+++ b/packages/errors/src/i18n/locales/hu.ts@@ -193,9 +193,7 @@ const ERROR_I18N_HU_MESSAGES = defineErrorI18nLocaleMessages({"colors.color_value_too_low": "A színértéknek legalább 0x000000 lehet.","connections.already_exists": "Ilyen típusú kapcsolat ezzel az azonosítóval már létezik.","connections.bluesky_oauth_authorization_failed": "Nem sikerült feloldani a Bluesky felhasználónevet. Ellenőrizd, majd próbáld újra.",- "connections.bluesky_oauth_callback_failed": "Nem sikerült létrehozni a Bluesky kapcsolatot. Próbáld újra.","connections.bluesky_oauth_not_enabled": "A Bluesky kapcsolatok nincsenek engedélyezve ezen a rendszeren.",- "connections.bluesky_oauth_state_invalid": "A hitelesítési kérelem lejárt vagy érvénytelen. Próbáld újra.","connections.initiation_token_invalid": "A kapcsolatindító token érvénytelen vagy lejárt.","connections.invalid_type": "A kapcsolattípus nem támogatott.","connections.limit_reached": "Elérted a maximális kapcsolatszámot ({limit}).",diff --git a/packages/errors/src/i18n/locales/id.ts b/packages/errors/src/i18n/locales/id.tsindex c468a749c..4ab61f76c 100644--- a/packages/errors/src/i18n/locales/id.ts+++ b/packages/errors/src/i18n/locales/id.ts@@ -193,9 +193,7 @@ const ERROR_I18N_ID_MESSAGES = defineErrorI18nLocaleMessages({"colors.color_value_too_low": "Nilai warna minimal 0x000000.","connections.already_exists": "Koneksi jenis ini dengan pengidentifikasi ini sudah ada.","connections.bluesky_oauth_authorization_failed": "Tidak bisa menyelesaikan handle Bluesky tersebut. Silakan periksa dan coba lagi.",- "connections.bluesky_oauth_callback_failed": "Tidak bisa menyelesaikan koneksi Bluesky. Silakan coba lagi.","connections.bluesky_oauth_not_enabled": "Koneksi Bluesky tidak diaktifkan pada instans ini.",- "connections.bluesky_oauth_state_invalid": "Permintaan otorisasi sudah kedaluwarsa atau tidak valid. Silakan coba lagi.","connections.initiation_token_invalid": "Token inisiasi koneksi tidak valid atau sudah kedaluwarsa.","connections.invalid_type": "Jenis koneksi tidak didukung.","connections.limit_reached": "Kamu telah mencapai jumlah koneksi maksimum ({limit}).",diff --git a/packages/errors/src/i18n/locales/it.ts b/packages/errors/src/i18n/locales/it.tsindex b4a325939..3d04ebab5 100644--- a/packages/errors/src/i18n/locales/it.ts+++ b/packages/errors/src/i18n/locales/it.ts@@ -193,9 +193,7 @@ const ERROR_I18N_IT_MESSAGES = defineErrorI18nLocaleMessages({"colors.color_value_too_low": "Il valore del colore deve essere almeno 0x000000.","connections.already_exists": "Una connessione di questo tipo con questo identificatore esiste già.","connections.bluesky_oauth_authorization_failed": "Non siamo riusciti a risolvere l'handle Bluesky. Controllalo e riprova.",- "connections.bluesky_oauth_callback_failed": "Impossibile completare la connessione Bluesky. Riprova.","connections.bluesky_oauth_not_enabled": "Le connessioni Bluesky non sono abilitate su questa istanza.",- "connections.bluesky_oauth_state_invalid": "La richiesta di autorizzazione è scaduta o non è valida. Riprova.","connections.initiation_token_invalid": "Il token di inizializzazione della connessione non è valido o è scaduto.","connections.invalid_type": "Il tipo di connessione non è supportato.","connections.limit_reached": "Hai raggiunto il limite massimo di connessioni ({limit}).",diff --git a/packages/errors/src/i18n/locales/ja.ts b/packages/errors/src/i18n/locales/ja.tsindex b89c074b1..ebc8cec7c 100644--- a/packages/errors/src/i18n/locales/ja.ts+++ b/packages/errors/src/i18n/locales/ja.ts@@ -193,9 +193,7 @@ const ERROR_I18N_JA_MESSAGES = defineErrorI18nLocaleMessages({"colors.color_value_too_low": "カラー値は最低でも0x000000である必要があります。","connections.already_exists": "この識別子を持つこのタイプの接続はすでに登録されています。","connections.bluesky_oauth_authorization_failed": "Blueskyハンドルが見つかりませんでした。確認してもう一度お試しください。",- "connections.bluesky_oauth_callback_failed": "Blueskyへの接続ができませんでした。もう一度お試しください。","connections.bluesky_oauth_not_enabled": "このインスタンスではBluesky接続は利用できません。",- "connections.bluesky_oauth_state_invalid": "認証リクエストは有効期限切れか無効です。もう一度お試しください。","connections.initiation_token_invalid": "接続開始トークンが無効であるか、有効期限が切れています。","connections.invalid_type": "この接続タイプはサポート対象外です。","connections.limit_reached": "接続数の上限である{limit}に達しました。",diff --git a/packages/errors/src/i18n/locales/ko.ts b/packages/errors/src/i18n/locales/ko.tsindex ebdf9ec9d..b0fcab83e 100644--- a/packages/errors/src/i18n/locales/ko.ts+++ b/packages/errors/src/i18n/locales/ko.ts@@ -193,9 +193,7 @@ const ERROR_I18N_KO_MESSAGES = defineErrorI18nLocaleMessages({"colors.color_value_too_low": "색상 값은 최소 0x000000이어야 해요.","connections.already_exists": "이 식별자를 가진 동일한 유형의 연결이 이미 존재해요.","connections.bluesky_oauth_authorization_failed": "Bluesky 핸들을 확인할 수 없었어요. 다시 확인하고 시도해 주세요.",- "connections.bluesky_oauth_callback_failed": "Bluesky 연결을 완료할 수 없었어요. 다시 시도해 주세요.","connections.bluesky_oauth_not_enabled": "이 인스턴스에서는 Bluesky 연결이 활성화되어 있지 않아요.",- "connections.bluesky_oauth_state_invalid": "인증 요청이 만료되었거나 유효하지 않아요. 다시 시도해 주세요.","connections.initiation_token_invalid": "연결 시작 토큰이 유효하지 않거나 만료되었어요.","connections.invalid_type": "연결 유형이 지원되지 않아요.","connections.limit_reached": "최대 연결 수({limit})에 도달했어요.",diff --git a/packages/errors/src/i18n/locales/lt.ts b/packages/errors/src/i18n/locales/lt.tsindex ee30e1976..bad2197d7 100644--- a/packages/errors/src/i18n/locales/lt.ts+++ b/packages/errors/src/i18n/locales/lt.ts@@ -193,9 +193,7 @@ const ERROR_I18N_LT_MESSAGES = defineErrorI18nLocaleMessages({"colors.color_value_too_low": "Spalvos vertė negali būti mažesnė nei 0x000000.","connections.already_exists": "Tokio tipo ryšys su šiuo identifikatoriumi jau yra.","connections.bluesky_oauth_authorization_failed": "Nepavyko rasti šio \"Bluesky\" slapyvardžio. Patikrink ir pabandyk dar kartą.",- "connections.bluesky_oauth_callback_failed": "Nepavyko užbaigti \"Bluesky\" ryšio. Pabandyk dar kartą.","connections.bluesky_oauth_not_enabled": "\"Bluesky\" ryšiai šioje sistemoje neįjungti.",- "connections.bluesky_oauth_state_invalid": "Autorizacijos užklausa baigėsi arba negalioja. Pabandyk dar kartą.","connections.initiation_token_invalid": "Ryšio inicijavimo žetonas yra negaliojantis arba nebegalioja.","connections.invalid_type": "Ryšio tipas nepalaikomas.","connections.limit_reached": "Pasiekei maksimalų ryšių skaičių ({limit}).",diff --git a/packages/errors/src/i18n/locales/nl.ts b/packages/errors/src/i18n/locales/nl.tsindex 1ee757af3..f6fc8fa25 100644--- a/packages/errors/src/i18n/locales/nl.ts+++ b/packages/errors/src/i18n/locales/nl.ts@@ -193,9 +193,7 @@ const ERROR_I18N_NL_MESSAGES = defineErrorI18nLocaleMessages({"colors.color_value_too_low": "Kleurwaarde moet minstens 0x000000 zijn.","connections.already_exists": "Een verbinding van dit type met deze identificatie bestaat al.","connections.bluesky_oauth_authorization_failed": "We konden die Bluesky-gebruikersnaam niet vinden. Controleer deze en probeer het opnieuw.",- "connections.bluesky_oauth_callback_failed": "We konden de Bluesky-verbinding niet voltooien. Probeer het opnieuw.","connections.bluesky_oauth_not_enabled": "Bluesky-verbindingen zijn niet ingeschakeld voor deze instantie.",- "connections.bluesky_oauth_state_invalid": "Het autorisatieverzoek is verlopen of ongeldig. Probeer het nog eens.","connections.initiation_token_invalid": "Het token voor verbinding is ongeldig of verlopen.","connections.invalid_type": "Het verbindingstype wordt niet ondersteund.","connections.limit_reached": "Je hebt het maximale aantal verbindingen bereikt ({limit}).",diff --git a/packages/errors/src/i18n/locales/no.ts b/packages/errors/src/i18n/locales/no.tsindex 8d3639d16..a8f3a42ab 100644--- a/packages/errors/src/i18n/locales/no.ts+++ b/packages/errors/src/i18n/locales/no.ts@@ -193,9 +193,7 @@ const ERROR_I18N_NO_MESSAGES = defineErrorI18nLocaleMessages({"colors.color_value_too_low": "Fargeverdien må være minst 0x000000.","connections.already_exists": "En tilkobling av denne typen med denne ID-en eksisterer allerede.","connections.bluesky_oauth_authorization_failed": "Vi kunne ikke løse Bluesky-brukernavnet. Sjekk det og prøv igjen.",- "connections.bluesky_oauth_callback_failed": "Vi kunne ikke fullføre Bluesky-tilkoblingen. Prøv igjen.","connections.bluesky_oauth_not_enabled": "Bluesky-tilkoblinger er ikke aktivert på denne instansen.",- "connections.bluesky_oauth_state_invalid": "Autorisasjonsforespørselen din har utløpt eller er ugyldig. Prøv igjen.","connections.initiation_token_invalid": "Tilkoblingstokenet er ugyldig eller har utløpt.","connections.invalid_type": "Tilkoblingstypen er ikke støttet.","connections.limit_reached": "Du har nådd maksimalt antall tilkoblinger ({limit}).",diff --git a/packages/errors/src/i18n/locales/pl.ts b/packages/errors/src/i18n/locales/pl.tsindex b69e8e7c6..cd3fd49e6 100644--- a/packages/errors/src/i18n/locales/pl.ts+++ b/packages/errors/src/i18n/locales/pl.ts@@ -193,9 +193,7 @@ const ERROR_I18N_PL_MESSAGES = defineErrorI18nLocaleMessages({"colors.color_value_too_low": "Wartość koloru musi wynosić co najmniej 0x000000.","connections.already_exists": "Połączenie tego typu z tym identyfikatorem już istnieje.","connections.bluesky_oauth_authorization_failed": "Nie udało się rozpoznać tego identyfikatora Bluesky. Sprawdź i spróbuj ponownie.",- "connections.bluesky_oauth_callback_failed": "Nie udało się nawiązać połączenia z Bluesky. Spróbuj ponownie.","connections.bluesky_oauth_not_enabled": "Połączenia Bluesky nie są włączone na tej instancji.",- "connections.bluesky_oauth_state_invalid": "Żądanie autoryzacji wygasło lub jest niepoprawne. Spróbuj ponownie.","connections.initiation_token_invalid": "Token inicjujący połączenie jest nieprawidłowy lub wygasł.","connections.invalid_type": "Typ połączenia jest nieobsługiwany.","connections.limit_reached": "Osiągnięto maksymalną liczbę połączeń ({limit}).",diff --git a/packages/errors/src/i18n/locales/pt-BR.ts b/packages/errors/src/i18n/locales/pt-BR.tsindex eaa07e4d8..f9077fda1 100644--- a/packages/errors/src/i18n/locales/pt-BR.ts+++ b/packages/errors/src/i18n/locales/pt-BR.ts@@ -193,9 +193,7 @@ const ERROR_I18N_PT_BR_MESSAGES = defineErrorI18nLocaleMessages({"colors.color_value_too_low": "O valor da cor deve ser pelo menos 0x000000.","connections.already_exists": "Já existe uma conexão deste tipo com este identificador.","connections.bluesky_oauth_authorization_failed": "Não conseguimos resolver esse nome de usuário do Bluesky. Por favor, verifique e tente novamente.",- "connections.bluesky_oauth_callback_failed": "Não foi possível finalizar a conexão com o Bluesky. Por favor, tente novamente.","connections.bluesky_oauth_not_enabled": "As conexões do Bluesky não estão habilitadas nesta instância.",- "connections.bluesky_oauth_state_invalid": "A solicitação de autorização expirou ou é inválida. Por favor, tente novamente.","connections.initiation_token_invalid": "O token de conexão é inválido ou expirou.","connections.invalid_type": "O tipo de conexão não é suportado.","connections.limit_reached": "Você atingiu o número máximo de conexões ({limit}).",diff --git a/packages/errors/src/i18n/locales/ro.ts b/packages/errors/src/i18n/locales/ro.tsindex 92797222f..571a338f0 100644--- a/packages/errors/src/i18n/locales/ro.ts+++ b/packages/errors/src/i18n/locales/ro.ts@@ -193,9 +193,7 @@ const ERROR_I18N_RO_MESSAGES = defineErrorI18nLocaleMessages({"colors.color_value_too_low": "Valoarea culorii trebuie să fie cel puțin 0x000000.","connections.already_exists": "Există deja o conexiune de acest tip cu acest identificator.","connections.bluesky_oauth_authorization_failed": "Nu s-a putut rezolva contul Bluesky. Te rugăm să-l verifici și să încerci din nou.",- "connections.bluesky_oauth_callback_failed": "Nu am putut finaliza conexiunea Bluesky. Te rugăm să încerci din nou.","connections.bluesky_oauth_not_enabled": "Conexiunile Bluesky nu sunt activate pentru această instanță.",- "connections.bluesky_oauth_state_invalid": "Cererea de autorizare a expirat sau este nevalidă. Te rugăm să încerci din nou.","connections.initiation_token_invalid": "Tokenul de inițiere a conexiunii este nevalid sau a expirat.","connections.invalid_type": "Tipul de conexiune nu este acceptat.","connections.limit_reached": "Ai atins limita maximă de conexiuni ({limit}).",diff --git a/packages/errors/src/i18n/locales/ru.ts b/packages/errors/src/i18n/locales/ru.tsindex 16b19fdb3..5ce91513a 100644--- a/packages/errors/src/i18n/locales/ru.ts+++ b/packages/errors/src/i18n/locales/ru.ts@@ -193,9 +193,7 @@ const ERROR_I18N_RU_MESSAGES = defineErrorI18nLocaleMessages({"colors.color_value_too_low": "Значение цвета должно быть не менее 0x000000.","connections.already_exists": "Уже существует подключение такого типа с этим идентификатором.","connections.bluesky_oauth_authorization_failed": "Не удалось найти этот ник в Bluesky. Проверь его и попробуй ещё раз.",- "connections.bluesky_oauth_callback_failed": "Не удалось завершить подключение к Bluesky. Попробуй ещё раз.","connections.bluesky_oauth_not_enabled": "На этом экземпляре не включены подключения Bluesky.",- "connections.bluesky_oauth_state_invalid": "Истёк или недействителен запрос авторизации. Попробуй ещё раз.","connections.initiation_token_invalid": "Недействителен или истёк токен для начала подключения.","connections.invalid_type": "Этот тип подключения не поддерживается.","connections.limit_reached": "Ты достиг лимита подключений ({limit}).",diff --git a/packages/errors/src/i18n/locales/sv-SE.ts b/packages/errors/src/i18n/locales/sv-SE.tsindex a6ff6e30e..138e52e57 100644--- a/packages/errors/src/i18n/locales/sv-SE.ts+++ b/packages/errors/src/i18n/locales/sv-SE.ts@@ -193,9 +193,7 @@ const ERROR_I18N_SV_SE_MESSAGES = defineErrorI18nLocaleMessages({"colors.color_value_too_low": "Färgvärdet måste vara minst 0x000000.","connections.already_exists": "En anslutning av denna typ med denna identifierare finns redan.","connections.bluesky_oauth_authorization_failed": "Vi kunde inte lösa Bluesky-handtaget. Kontrollera det och försök igen.",- "connections.bluesky_oauth_callback_failed": "Vi kunde inte slutföra anslutningen till Bluesky. Försök igen.","connections.bluesky_oauth_not_enabled": "Bluesky-anslutningar är inte aktiverade på den här instansen.",- "connections.bluesky_oauth_state_invalid": "Auktoriseringen har gått ut eller är ogiltig. Försök igen.","connections.initiation_token_invalid": "Anslutningens starttoken är ogiltig eller har gått ut.","connections.invalid_type": "Anslutningstypen stöds inte.","connections.limit_reached": "Du har nått maxantalet anslutningar ({limit}).",diff --git a/packages/errors/src/i18n/locales/th.ts b/packages/errors/src/i18n/locales/th.tsindex 251f99d7b..05853d7f5 100644--- a/packages/errors/src/i18n/locales/th.ts+++ b/packages/errors/src/i18n/locales/th.ts@@ -193,9 +193,7 @@ const ERROR_I18N_TH_MESSAGES = defineErrorI18nLocaleMessages({"colors.color_value_too_low": "ค่าสีต้องมีอย่างน้อย 0x000000","connections.already_exists": "มีการเชื่อมต่อประเภทนี้พร้อมตัวระบุนี้อยู่แล้ว","connections.bluesky_oauth_authorization_failed": "ไม่สามารถระบุ Bluesky handle นั้นได้ โปรดตรวจสอบและลองอีกครั้ง",- "connections.bluesky_oauth_callback_failed": "ไม่สามารถเชื่อมต่อ Bluesky ได้ โปรดลองอีกครั้ง","connections.bluesky_oauth_not_enabled": "การเชื่อมต่อ Bluesky ไม่ได้เปิดใช้งานบนอินสแตนซ์นี้",- "connections.bluesky_oauth_state_invalid": "คำขออนุญาตหมดอายุหรือใช้ไม่ได้ โปรดลองอีกครั้ง","connections.initiation_token_invalid": "โทเค็นการเริ่มต้นการเชื่อมต่อไม่ถูกต้องหรือหมดอายุแล้ว","connections.invalid_type": "ไม่รองรับประเภทการเชื่อมต่อ","connections.limit_reached": "ถึงขีดจำกัดการเชื่อมต่อแล้ว ({limit})",diff --git a/packages/errors/src/i18n/locales/tr.ts b/packages/errors/src/i18n/locales/tr.tsindex b541351ac..fc6c78177 100644--- a/packages/errors/src/i18n/locales/tr.ts+++ b/packages/errors/src/i18n/locales/tr.ts@@ -193,9 +193,7 @@ const ERROR_I18N_TR_MESSAGES = defineErrorI18nLocaleMessages({"colors.color_value_too_low": "Renk değeri en az 0x000000 olmalıdır.","connections.already_exists": "Bu tanımlayıcıya sahip bu türde bir bağlantı zaten mevcut.","connections.bluesky_oauth_authorization_failed": "Bu Bluesky kullanıcı adını çözümleyemedik. Lütfen kontrol et ve tekrar dene.",- "connections.bluesky_oauth_callback_failed": "Bluesky bağlantısını tamamlayamadık. Lütfen tekrar dene.","connections.bluesky_oauth_not_enabled": "Bu kurulumda Bluesky bağlantıları etkin değil.",- "connections.bluesky_oauth_state_invalid": "Yetkilendirme isteğinin süresi doldu veya geçersiz. Lütfen tekrar dene.","connections.initiation_token_invalid": "Bağlantı başlatma jetonu geçersiz veya süresi doldu.","connections.invalid_type": "Bağlantı türü desteklenmiyor.","connections.limit_reached": "Maksimum bağlantı sayısına ulaştın ({limit}).",diff --git a/packages/errors/src/i18n/locales/uk.ts b/packages/errors/src/i18n/locales/uk.tsindex 26af2a251..53932ab29 100644--- a/packages/errors/src/i18n/locales/uk.ts+++ b/packages/errors/src/i18n/locales/uk.ts@@ -193,9 +193,7 @@ const ERROR_I18N_UK_MESSAGES = defineErrorI18nLocaleMessages({"colors.color_value_too_low": "Значення кольору має бути не менше 0x000000.","connections.already_exists": "З'єднання такого типу з цим ідентифікатором вже існує.","connections.bluesky_oauth_authorization_failed": "Не вдалося розпізнати цей ідентифікатор Bluesky. Перевір його та спробуй ще раз.",- "connections.bluesky_oauth_callback_failed": "Не вдалося завершити підключення до Bluesky. Спробуй ще раз.","connections.bluesky_oauth_not_enabled": "Підключення до Bluesky не ввімкнено у цій інсталяції.",- "connections.bluesky_oauth_state_invalid": "Термін дії запиту на авторизацію закінчився або є недійсним. Спробуй ще раз.","connections.initiation_token_invalid": "Токен ініціації з'єднання недійсний або термін дії закінчився.","connections.invalid_type": "Тип з'єднання не підтримується.","connections.limit_reached": "Досягнуто максимальної кількості з'єднань ({limit}).",diff --git a/packages/errors/src/i18n/locales/vi.ts b/packages/errors/src/i18n/locales/vi.tsindex 6abed2cd8..c8e0e11e0 100644--- a/packages/errors/src/i18n/locales/vi.ts+++ b/packages/errors/src/i18n/locales/vi.ts@@ -193,9 +193,7 @@ const ERROR_I18N_VI_MESSAGES = defineErrorI18nLocaleMessages({"colors.color_value_too_low": "Giá trị màu phải tối thiểu là 0x000000.","connections.already_exists": "Kết nối loại này với mã định danh này đã tồn tại.","connections.bluesky_oauth_authorization_failed": "Chúng tôi không thể tìm thấy tài khoản Bluesky đó. Vui lòng kiểm tra lại và thử lại.",- "connections.bluesky_oauth_callback_failed": "Chúng tôi không thể hoàn tất kết nối Bluesky. Vui lòng thử lại.","connections.bluesky_oauth_not_enabled": "Kết nối Bluesky không được bật trên phiên bản này.",- "connections.bluesky_oauth_state_invalid": "Yêu cầu ủy quyền đã hết hạn hoặc không hợp lệ. Thử lại.","connections.initiation_token_invalid": "Token khởi tạo kết nối không hợp lệ hoặc đã hết hạn.","connections.invalid_type": "Loại kết nối không được hỗ trợ.","connections.limit_reached": "Bạn đã đạt số lượng kết nối tối đa ({limit}).",diff --git a/packages/errors/src/i18n/locales/zh-CN.ts b/packages/errors/src/i18n/locales/zh-CN.tsindex 0a3b4d121..fb0cd29e5 100644--- a/packages/errors/src/i18n/locales/zh-CN.ts+++ b/packages/errors/src/i18n/locales/zh-CN.ts@@ -193,9 +193,7 @@ const ERROR_I18N_ZH_CN_MESSAGES = defineErrorI18nLocaleMessages({"colors.color_value_too_low": "颜色值必须至少为 0x000000。","connections.already_exists": "已存在此类型且标识符相同的连接。","connections.bluesky_oauth_authorization_failed": "我们无法解析该 Bluesky 账号。请检查并重试。",- "connections.bluesky_oauth_callback_failed": "我们无法完成 Bluesky 连接。请重试。","connections.bluesky_oauth_not_enabled": "此实例未启用 Bluesky 连接。",- "connections.bluesky_oauth_state_invalid": "授权请求已过期或失效。请重试。","connections.initiation_token_invalid": "连接初始化令牌无效或已过期。","connections.invalid_type": "不支持的连接类型。","connections.limit_reached": "你已达到最大连接数 ({limit})。",diff --git a/packages/errors/src/i18n/locales/zh-TW.ts b/packages/errors/src/i18n/locales/zh-TW.tsindex f7c6017e6..9ebd6bab0 100644--- a/packages/errors/src/i18n/locales/zh-TW.ts+++ b/packages/errors/src/i18n/locales/zh-TW.ts@@ -193,9 +193,7 @@ const ERROR_I18N_ZH_TW_MESSAGES = defineErrorI18nLocaleMessages({"colors.color_value_too_low": "顏色值至少須為 0x000000。","connections.already_exists": "此類型與此識別碼的連線已存在。","connections.bluesky_oauth_authorization_failed": "我們無法解析該 Bluesky 帳號。請檢查並再試一次。",- "connections.bluesky_oauth_callback_failed": "我們無法完成 Bluesky 連線。請再試一次。","connections.bluesky_oauth_not_enabled": "此實例未啟用 Bluesky 連線。",- "connections.bluesky_oauth_state_invalid": "授權請求已過期或無效。請再試。","connections.initiation_token_invalid": "連線權杖無效或已過期。","connections.invalid_type": "不支援此連線類型。","connections.limit_reached": "你已達到最大連線數 ({limit})。",diff --git a/packages/errors/src/i18n/weblate/locales/ar.json b/packages/errors/src/i18n/weblate/locales/ar.jsonindex ffb0d30a9..b59ca577d 100644--- a/packages/errors/src/i18n/weblate/locales/ar.json+++ b/packages/errors/src/i18n/weblate/locales/ar.json@@ -189,9 +189,7 @@"colors.color_value_too_low": "يجب أن لا تقل قيمة اللون عن 0x000000.","connections.already_exists": "يوجد بالفعل اتصال من هذا النوع بهذا المعرف.","connections.bluesky_oauth_authorization_failed": "لم نتمكن من حل معرّف Bluesky هذا. يُرجى التأكد منه والمحاولة مرة أخرى.",- "connections.bluesky_oauth_callback_failed": "لم نتمكن من إكمال الاتصال بـ Bluesky. يُرجى المحاولة مرة أخرى.","connections.bluesky_oauth_not_enabled": "ميزة الاتصال بـ Bluesky غير ممكّنة في هذا المثيل.",- "connections.bluesky_oauth_state_invalid": "انتهت صلاحية طلب التفويض أو غير صالح. يُرجى المحاولة مرة أخرى.","connections.initiation_token_invalid": "رمز بدء الاتصال غير صالح أو انتهت صلاحيته.","connections.invalid_type": "نوع الاتصال غير مدعوم.","connections.limit_reached": "وصلت إلى الحد الأقصى لعدد الاتصالات ({limit}).",diff --git a/packages/errors/src/i18n/weblate/locales/bg.json b/packages/errors/src/i18n/weblate/locales/bg.jsonindex dd2d85af6..67b4b70cc 100644--- a/packages/errors/src/i18n/weblate/locales/bg.json+++ b/packages/errors/src/i18n/weblate/locales/bg.json@@ -189,9 +189,7 @@"colors.color_value_too_low": "Стойността на цвета трябва да е поне 0x000000.","connections.already_exists": "Връзка от този тип с този идентификатор вече съществува.","connections.bluesky_oauth_authorization_failed": "Не успяхме да намерим този Bluesky идентификатор. Моля, провери го и опитай пак.",- "connections.bluesky_oauth_callback_failed": "Не успяхме да установим връзката с Bluesky. Моля, опитай пак.","connections.bluesky_oauth_not_enabled": "Връзките с Bluesky не са активирани на тази инстанция.",- "connections.bluesky_oauth_state_invalid": "Заявката за оторизация е изтекла или е невалидна. Моля, опитай пак.","connections.initiation_token_invalid": "Токенът за иницииране на връзка е невалиден или е изтекъл.","connections.invalid_type": "Типът на връзката не се поддържа.","connections.limit_reached": "Достигнал си максималния брой връзки ({limit}).",diff --git a/packages/errors/src/i18n/weblate/locales/cs.json b/packages/errors/src/i18n/weblate/locales/cs.jsonindex 1f6e64b18..3c8659009 100644--- a/packages/errors/src/i18n/weblate/locales/cs.json+++ b/packages/errors/src/i18n/weblate/locales/cs.json@@ -189,9 +189,7 @@"colors.color_value_too_low": "Hodnota barvy musí být minimálně 0x000000.","connections.already_exists": "Propojení tohoto typu s tímto ID již existuje.","connections.bluesky_oauth_authorization_failed": "Nepodařilo se najít toto uživatelské jméno Bluesky. Zkontroluj ho a zkus to znovu.",- "connections.bluesky_oauth_callback_failed": "Nepodařilo se dokončit propojení s Bluesky. Zkus to znovu.","connections.bluesky_oauth_not_enabled": "Na této instanci nejsou povolena propojení s Bluesky.",- "connections.bluesky_oauth_state_invalid": "Žádost o autorizaci vypršela nebo je neplatná. Zkus to znovu.","connections.initiation_token_invalid": "Token pro spuštění propojení je neplatný nebo vypršel.","connections.invalid_type": "Tento typ propojení není podporován.","connections.limit_reached": "Dosáhl jsi maximálního počtu propojení ({limit}).",diff --git a/packages/errors/src/i18n/weblate/locales/da.json b/packages/errors/src/i18n/weblate/locales/da.jsonindex d7aaeced8..da06ce3f8 100644--- a/packages/errors/src/i18n/weblate/locales/da.json+++ b/packages/errors/src/i18n/weblate/locales/da.json@@ -189,9 +189,7 @@"colors.color_value_too_low": "Farveværdien skal være mindst 0x000000.","connections.already_exists": "En forbindelse af denne type med denne identifikator eksisterer allerede.","connections.bluesky_oauth_authorization_failed": "Vi kunne ikke finde det Bluesky-handle. Tjek det, og prøv igen.",- "connections.bluesky_oauth_callback_failed": "Vi kunne ikke fuldføre Bluesky-forbindelsen. Prøv igen.","connections.bluesky_oauth_not_enabled": "Bluesky-forbindelser er ikke aktiveret på denne instans.",- "connections.bluesky_oauth_state_invalid": "Autorisationsanmodningen er udløbet eller ugyldig. Prøv igen.","connections.initiation_token_invalid": "Forbindelsestokenet er ugyldigt eller udløbet.","connections.invalid_type": "Forbindelsestypen understøttes ikke.","connections.limit_reached": "Du har nået det maksimale antal forbindelser ({limit}).",diff --git a/packages/errors/src/i18n/weblate/locales/de.json b/packages/errors/src/i18n/weblate/locales/de.jsonindex 0659fae98..f27444953 100644--- a/packages/errors/src/i18n/weblate/locales/de.json+++ b/packages/errors/src/i18n/weblate/locales/de.json@@ -189,9 +189,7 @@"colors.color_value_too_low": "Der Farbwert muss mindestens 0x000000 betragen.","connections.already_exists": "Eine Verbindung dieses Typs mit dieser ID besteht bereits.","connections.bluesky_oauth_authorization_failed": "Wir konnten den Bluesky-Handle nicht auflösen. Überprüfe ihn bitte und versuch es noch mal.",- "connections.bluesky_oauth_callback_failed": "Wir konnten die Bluesky-Verbindung nicht herstellen. Versuch es noch mal.","connections.bluesky_oauth_not_enabled": "Auf dieser Instanz sind Bluesky-Verbindungen nicht aktiviert.",- "connections.bluesky_oauth_state_invalid": "Die Autorisierungsanforderung ist abgelaufen oder ungültig. Versuch es noch mal.","connections.initiation_token_invalid": "Das Token zur Verbindungsherstellung ist ungültig oder abgelaufen.","connections.invalid_type": "Dieser Verbindungstyp wird nicht unterstützt.","connections.limit_reached": "Du hast die maximale Anzahl an Verbindungen ({limit}) erreicht.",diff --git a/packages/errors/src/i18n/weblate/locales/el.json b/packages/errors/src/i18n/weblate/locales/el.jsonindex 6134b1769..9688b1013 100644--- a/packages/errors/src/i18n/weblate/locales/el.json+++ b/packages/errors/src/i18n/weblate/locales/el.json@@ -189,9 +189,7 @@"colors.color_value_too_low": "Η τιμή χρώματος πρέπει να είναι τουλάχιστον 0x000000.","connections.already_exists": "Υπάρχει ήδη μια σύνδεση αυτού του τύπου με αυτό το αναγνωριστικό.","connections.bluesky_oauth_authorization_failed": "Δεν μπορέσαμε να επιλύσουμε το όνομα χρήστη Bluesky. Ελέγξτε το και δοκιμάστε ξανά.",- "connections.bluesky_oauth_callback_failed": "Αδυνατούμε να ολοκληρώσουμε τη σύνδεση Bluesky. Δοκιμάστε ξανά.","connections.bluesky_oauth_not_enabled": "Οι συνδέσεις Bluesky δεν είναι ενεργοποιημένες σε αυτήν την εγκατάσταση.",- "connections.bluesky_oauth_state_invalid": "Το αίτημα εξουσιοδότησης έχει λήξει ή είναι μη έγκυρο. Δοκιμάστε ξανά.","connections.initiation_token_invalid": "Το token έναρξης σύνδεσης είναι άκυρο ή έχει λήξει.","connections.invalid_type": "Ο τύπος σύνδεσης δεν υποστηρίζεται.","connections.limit_reached": "Έχεις φτάσει τον μέγιστο αριθμό συνδέσεων ({limit}).",diff --git a/packages/errors/src/i18n/weblate/locales/en-GB.json b/packages/errors/src/i18n/weblate/locales/en-GB.jsonindex ddabd1b66..6fd201ced 100644--- a/packages/errors/src/i18n/weblate/locales/en-GB.json+++ b/packages/errors/src/i18n/weblate/locales/en-GB.json@@ -189,9 +189,7 @@"colors.color_value_too_low": "Colour value must be at least 0x000000.","connections.already_exists": "A connection of this type with this identifier already exists.","connections.bluesky_oauth_authorization_failed": "We couldn't resolve that Bluesky handle. Please check it and try again.",- "connections.bluesky_oauth_callback_failed": "We couldn't complete the Bluesky connection. Please try again.","connections.bluesky_oauth_not_enabled": "Bluesky connections are not enabled on this instance.",- "connections.bluesky_oauth_state_invalid": "The authorization request has expired or is invalid. Please try again.","connections.initiation_token_invalid": "The connection initiation token is invalid or has expired.","connections.invalid_type": "The connection type is not supported.","connections.limit_reached": "You've reached the maximum number of connections ({limit}).",diff --git a/packages/errors/src/i18n/weblate/locales/es-419.json b/packages/errors/src/i18n/weblate/locales/es-419.jsonindex 2385ef971..e09804f99 100644--- a/packages/errors/src/i18n/weblate/locales/es-419.json+++ b/packages/errors/src/i18n/weblate/locales/es-419.json@@ -189,9 +189,7 @@"colors.color_value_too_low": "El valor del color debe ser como mínimo 0x000000.","connections.already_exists": "Ya existe una conexión de este tipo con este identificador.","connections.bluesky_oauth_authorization_failed": "No pudimos resolver ese identificador de Bluesky. Verifícalo e inténtalo de nuevo.",- "connections.bluesky_oauth_callback_failed": "No pudimos completar la conexión de Bluesky. Inténtalo de nuevo.","connections.bluesky_oauth_not_enabled": "Las conexiones de Bluesky no están habilitadas en esta instancia.",- "connections.bluesky_oauth_state_invalid": "La solicitud de autorización ha expirado o es inválida. Inténtalo de nuevo.","connections.initiation_token_invalid": "El token de inicio de conexión es inválido o ha expirado.","connections.invalid_type": "El tipo de conexión no es compatible.","connections.limit_reached": "Has alcanzado el número máximo de conexiones ({limit}).",diff --git a/packages/errors/src/i18n/weblate/locales/es-ES.json b/packages/errors/src/i18n/weblate/locales/es-ES.jsonindex d277af743..51ef24c80 100644--- a/packages/errors/src/i18n/weblate/locales/es-ES.json+++ b/packages/errors/src/i18n/weblate/locales/es-ES.json@@ -189,9 +189,7 @@"colors.color_value_too_low": "El valor del color debe ser al menos 0x000000.","connections.already_exists": "Ya existe una conexión de este tipo y con este identificador.","connections.bluesky_oauth_authorization_failed": "No pudimos resolver ese usuario de Bluesky. Compruébalo e inténtalo de nuevo.",- "connections.bluesky_oauth_callback_failed": "No se pudo completar la conexión con Bluesky. Inténtalo de nuevo.","connections.bluesky_oauth_not_enabled": "Las conexiones de Bluesky no están habilitadas en esta instancia.",- "connections.bluesky_oauth_state_invalid": "La solicitud de autorización ha expirado o no es válida. Inténtalo de nuevo.","connections.initiation_token_invalid": "El token de inicio de conexión no es válido o ha expirado.","connections.invalid_type": "El tipo de conexión no es compatible.","connections.limit_reached": "Has alcanzado el número máximo de conexiones ({limit}).",diff --git a/packages/errors/src/i18n/weblate/locales/fi.json b/packages/errors/src/i18n/weblate/locales/fi.jsonindex a0e0a6945..a845d36e8 100644--- a/packages/errors/src/i18n/weblate/locales/fi.json+++ b/packages/errors/src/i18n/weblate/locales/fi.json@@ -189,9 +189,7 @@"colors.color_value_too_low": "Väriarvon täytyy olla vähintään 0x000000.","connections.already_exists": "Tämän tyyppinen yhteys tällä tunnisteella on jo olemassa.","connections.bluesky_oauth_authorization_failed": "Emme voineet selvittää Bluesky-tunnusta. Tarkista tunnus ja yritä uudelleen.",- "connections.bluesky_oauth_callback_failed": "Emme voineet muodostaa Bluesky-yhteyttä. Yritä uudelleen.","connections.bluesky_oauth_not_enabled": "Bluesky-yhteydet eivät ole käytössä tässä instanssissa.",- "connections.bluesky_oauth_state_invalid": "Valtuutuspyyntö on vanhentunut tai virheellinen. Yritä uudelleen.","connections.initiation_token_invalid": "Yhteyden aloitustunnus on virheellinen tai vanhentunut.","connections.invalid_type": "Yhteyden tyyppiä ei tueta.","connections.limit_reached": "Olet saavuttanut yhteyksien enimmäismäärän ({limit}).",diff --git a/packages/errors/src/i18n/weblate/locales/fr.json b/packages/errors/src/i18n/weblate/locales/fr.jsonindex ca949fae1..776207259 100644--- a/packages/errors/src/i18n/weblate/locales/fr.json+++ b/packages/errors/src/i18n/weblate/locales/fr.json@@ -189,9 +189,7 @@"colors.color_value_too_low": "La valeur de couleur doit être au moins 0x000000.","connections.already_exists": "Une connexion de ce type avec cet identifiant existe déjà.","connections.bluesky_oauth_authorization_failed": "Nous n'avons pas pu résoudre ce pseudo Bluesky. Vérifie-le et réessaie.",- "connections.bluesky_oauth_callback_failed": "Nous n'avons pas pu établir la connexion Bluesky. Réessaie.","connections.bluesky_oauth_not_enabled": "Les connexions Bluesky ne sont pas activées sur cette instance.",- "connections.bluesky_oauth_state_invalid": "La demande d'autorisation a expiré ou est invalide. Réessaie.","connections.initiation_token_invalid": "Le jeton d'initialisation de la connexion est invalide ou a expiré.","connections.invalid_type": "Le type de connexion n'est pas pris en charge.","connections.limit_reached": "Tu as atteint le nombre maximum de connexions ({limit}).",diff --git a/packages/errors/src/i18n/weblate/locales/he.json b/packages/errors/src/i18n/weblate/locales/he.jsonindex a1764c540..371cd6f36 100644--- a/packages/errors/src/i18n/weblate/locales/he.json+++ b/packages/errors/src/i18n/weblate/locales/he.json@@ -189,9 +189,7 @@"colors.color_value_too_low": "ערך הצבע יהיה 0x000000 לפחות.","connections.already_exists": "חיבור מסוג זה עם מזהה זה כבר קיים.","connections.bluesky_oauth_authorization_failed": "לא הצלחנו לאתר את כתובת ה-Bluesky. נא לבדוק ולנסות שוב.",- "connections.bluesky_oauth_callback_failed": "לא הצלחנו להשלים את חיבור ה-Bluesky. ניתן לנסות שוב.","connections.bluesky_oauth_not_enabled": "חיבורי Bluesky לא מופעלים במופע זה.",- "connections.bluesky_oauth_state_invalid": "תוקף בקשת ההרשאה פג או שהיא לא תקפה. יש לנסות שוב.","connections.initiation_token_invalid": "אסימון אתחול החיבור לא תקף או שתוקפו פג.","connections.invalid_type": "סוג החיבור הזה לא נתמך.","connections.limit_reached": "הגעת למספר החיבורים המרבי ({limit}).",diff --git a/packages/errors/src/i18n/weblate/locales/hi.json b/packages/errors/src/i18n/weblate/locales/hi.jsonindex 30e98ddd1..30d9880eb 100644--- a/packages/errors/src/i18n/weblate/locales/hi.json+++ b/packages/errors/src/i18n/weblate/locales/hi.json@@ -189,9 +189,7 @@"colors.color_value_too_low": "कलर वैल्यू कम से कम 0x000000 होनी चाहिए।","connections.already_exists": "इस आइडेंटिफ़ायर के साथ इस प्रकार का कनेक्शन पहले से मौजूद है।","connections.bluesky_oauth_authorization_failed": "हम उस Bluesky हैंडल को सुलझा नहीं पाए। कृपया इसे चेक करें और फिर से कोशिश करें।",- "connections.bluesky_oauth_callback_failed": "हम Bluesky कनेक्शन पूरा नहीं कर सके। कृपया फिर से कोशिश करें।","connections.bluesky_oauth_not_enabled": "इस इंस्टेंस पर Bluesky कनेक्शन सक्षम नहीं हैं।",- "connections.bluesky_oauth_state_invalid": "ऑथराइज़ेशन रिक्वेस्ट एक्सपायर हो गई है या अमान्य है। कृपया फिर से कोशिश करें।","connections.initiation_token_invalid": "कनेक्शन इनिशिएशन टोकन अमान्य है या एक्सपायर हो गया है।","connections.invalid_type": "कनेक्शन टाइप समर्थित नहीं है।","connections.limit_reached": "आपकी अधिकतम कनेक्शन ({limit}) की सीमा पूरी हो गई है।",diff --git a/packages/errors/src/i18n/weblate/locales/hr.json b/packages/errors/src/i18n/weblate/locales/hr.jsonindex 930df8beb..206f30bc6 100644--- a/packages/errors/src/i18n/weblate/locales/hr.json+++ b/packages/errors/src/i18n/weblate/locales/hr.json@@ -189,9 +189,7 @@"colors.color_value_too_low": "Vrijednost boje mora biti najmanje 0x000000.","connections.already_exists": "Već postoji veza ove vrste s ovim identifikatorom.","connections.bluesky_oauth_authorization_failed": "Nismo ti mogli razriješiti to Bluesky korisničko ime. Provjeri ga i pokušaj ponovno.",- "connections.bluesky_oauth_callback_failed": "Nismo ti mogli dovršiti Bluesky vezu. Pokušaj ponovno.","connections.bluesky_oauth_not_enabled": "Bluesky veze nisu omogućene na ovoj instanci.",- "connections.bluesky_oauth_state_invalid": "Zahtjev za autorizaciju je istekao ili je nevažeći. Pokušaj ponovno.","connections.initiation_token_invalid": "Token za uspostavu veze je nevažeći ili je istekao.","connections.invalid_type": "Ova vrsta veze nije podržana.","connections.limit_reached": "Dostigao si maksimalan broj veza ({limit}).",diff --git a/packages/errors/src/i18n/weblate/locales/hu.json b/packages/errors/src/i18n/weblate/locales/hu.jsonindex b98c6e3fc..aa0431d31 100644--- a/packages/errors/src/i18n/weblate/locales/hu.json+++ b/packages/errors/src/i18n/weblate/locales/hu.json@@ -189,9 +189,7 @@"colors.color_value_too_low": "A színértéknek legalább 0x000000 lehet.","connections.already_exists": "Ilyen típusú kapcsolat ezzel az azonosítóval már létezik.","connections.bluesky_oauth_authorization_failed": "Nem sikerült feloldani a Bluesky felhasználónevet. Ellenőrizd, majd próbáld újra.",- "connections.bluesky_oauth_callback_failed": "Nem sikerült létrehozni a Bluesky kapcsolatot. Próbáld újra.","connections.bluesky_oauth_not_enabled": "A Bluesky kapcsolatok nincsenek engedélyezve ezen a rendszeren.",- "connections.bluesky_oauth_state_invalid": "A hitelesítési kérelem lejárt vagy érvénytelen. Próbáld újra.","connections.initiation_token_invalid": "A kapcsolatindító token érvénytelen vagy lejárt.","connections.invalid_type": "A kapcsolattípus nem támogatott.","connections.limit_reached": "Elérted a maximális kapcsolatszámot ({limit}).",diff --git a/packages/errors/src/i18n/weblate/locales/id.json b/packages/errors/src/i18n/weblate/locales/id.jsonindex d0f3b1945..079ad33f6 100644--- a/packages/errors/src/i18n/weblate/locales/id.json+++ b/packages/errors/src/i18n/weblate/locales/id.json@@ -189,9 +189,7 @@"colors.color_value_too_low": "Nilai warna minimal 0x000000.","connections.already_exists": "Koneksi jenis ini dengan pengidentifikasi ini sudah ada.","connections.bluesky_oauth_authorization_failed": "Tidak bisa menyelesaikan handle Bluesky tersebut. Silakan periksa dan coba lagi.",- "connections.bluesky_oauth_callback_failed": "Tidak bisa menyelesaikan koneksi Bluesky. Silakan coba lagi.","connections.bluesky_oauth_not_enabled": "Koneksi Bluesky tidak diaktifkan pada instans ini.",- "connections.bluesky_oauth_state_invalid": "Permintaan otorisasi sudah kedaluwarsa atau tidak valid. Silakan coba lagi.","connections.initiation_token_invalid": "Token inisiasi koneksi tidak valid atau sudah kedaluwarsa.","connections.invalid_type": "Jenis koneksi tidak didukung.","connections.limit_reached": "Kamu telah mencapai jumlah koneksi maksimum ({limit}).",diff --git a/packages/errors/src/i18n/weblate/locales/it.json b/packages/errors/src/i18n/weblate/locales/it.jsonindex 2fceee470..5a590add5 100644--- a/packages/errors/src/i18n/weblate/locales/it.json+++ b/packages/errors/src/i18n/weblate/locales/it.json@@ -189,9 +189,7 @@"colors.color_value_too_low": "Il valore del colore deve essere almeno 0x000000.","connections.already_exists": "Una connessione di questo tipo con questo identificatore esiste già.","connections.bluesky_oauth_authorization_failed": "Non siamo riusciti a risolvere l'handle Bluesky. Controllalo e riprova.",- "connections.bluesky_oauth_callback_failed": "Impossibile completare la connessione Bluesky. Riprova.","connections.bluesky_oauth_not_enabled": "Le connessioni Bluesky non sono abilitate su questa istanza.",- "connections.bluesky_oauth_state_invalid": "La richiesta di autorizzazione è scaduta o non è valida. Riprova.","connections.initiation_token_invalid": "Il token di inizializzazione della connessione non è valido o è scaduto.","connections.invalid_type": "Il tipo di connessione non è supportato.","connections.limit_reached": "Hai raggiunto il limite massimo di connessioni ({limit}).",diff --git a/packages/errors/src/i18n/weblate/locales/ja.json b/packages/errors/src/i18n/weblate/locales/ja.jsonindex 1ed728225..4f908f760 100644--- a/packages/errors/src/i18n/weblate/locales/ja.json+++ b/packages/errors/src/i18n/weblate/locales/ja.json@@ -189,9 +189,7 @@"colors.color_value_too_low": "カラー値は最低でも0x000000である必要があります。","connections.already_exists": "この識別子を持つこのタイプの接続はすでに登録されています。","connections.bluesky_oauth_authorization_failed": "Blueskyハンドルが見つかりませんでした。確認してもう一度お試しください。",- "connections.bluesky_oauth_callback_failed": "Blueskyへの接続ができませんでした。もう一度お試しください。","connections.bluesky_oauth_not_enabled": "このインスタンスではBluesky接続は利用できません。",- "connections.bluesky_oauth_state_invalid": "認証リクエストは有効期限切れか無効です。もう一度お試しください。","connections.initiation_token_invalid": "接続開始トークンが無効であるか、有効期限が切れています。","connections.invalid_type": "この接続タイプはサポート対象外です。","connections.limit_reached": "接続数の上限である{limit}に達しました。",diff --git a/packages/errors/src/i18n/weblate/locales/ko.json b/packages/errors/src/i18n/weblate/locales/ko.jsonindex 738940015..c336a9faf 100644--- a/packages/errors/src/i18n/weblate/locales/ko.json+++ b/packages/errors/src/i18n/weblate/locales/ko.json@@ -189,9 +189,7 @@"colors.color_value_too_low": "색상 값은 최소 0x000000이어야 해요.","connections.already_exists": "이 식별자를 가진 동일한 유형의 연결이 이미 존재해요.","connections.bluesky_oauth_authorization_failed": "Bluesky 핸들을 확인할 수 없었어요. 다시 확인하고 시도해 주세요.",- "connections.bluesky_oauth_callback_failed": "Bluesky 연결을 완료할 수 없었어요. 다시 시도해 주세요.","connections.bluesky_oauth_not_enabled": "이 인스턴스에서는 Bluesky 연결이 활성화되어 있지 않아요.",- "connections.bluesky_oauth_state_invalid": "인증 요청이 만료되었거나 유효하지 않아요. 다시 시도해 주세요.","connections.initiation_token_invalid": "연결 시작 토큰이 유효하지 않거나 만료되었어요.","connections.invalid_type": "연결 유형이 지원되지 않아요.","connections.limit_reached": "최대 연결 수({limit})에 도달했어요.",diff --git a/packages/errors/src/i18n/weblate/locales/lt.json b/packages/errors/src/i18n/weblate/locales/lt.jsonindex 3beef4b10..e96e95410 100644--- a/packages/errors/src/i18n/weblate/locales/lt.json+++ b/packages/errors/src/i18n/weblate/locales/lt.json@@ -189,9 +189,7 @@"colors.color_value_too_low": "Spalvos vertė negali būti mažesnė nei 0x000000.","connections.already_exists": "Tokio tipo ryšys su šiuo identifikatoriumi jau yra.","connections.bluesky_oauth_authorization_failed": "Nepavyko rasti šio \"Bluesky\" slapyvardžio. Patikrink ir pabandyk dar kartą.",- "connections.bluesky_oauth_callback_failed": "Nepavyko užbaigti \"Bluesky\" ryšio. Pabandyk dar kartą.","connections.bluesky_oauth_not_enabled": "\"Bluesky\" ryšiai šioje sistemoje neįjungti.",- "connections.bluesky_oauth_state_invalid": "Autorizacijos užklausa baigėsi arba negalioja. Pabandyk dar kartą.","connections.initiation_token_invalid": "Ryšio inicijavimo žetonas yra negaliojantis arba nebegalioja.","connections.invalid_type": "Ryšio tipas nepalaikomas.","connections.limit_reached": "Pasiekei maksimalų ryšių skaičių ({limit}).",diff --git a/packages/errors/src/i18n/weblate/locales/nl.json b/packages/errors/src/i18n/weblate/locales/nl.jsonindex 95e3fadbd..695abec51 100644--- a/packages/errors/src/i18n/weblate/locales/nl.json+++ b/packages/errors/src/i18n/weblate/locales/nl.json@@ -189,9 +189,7 @@"colors.color_value_too_low": "Kleurwaarde moet minstens 0x000000 zijn.","connections.already_exists": "Een verbinding van dit type met deze identificatie bestaat al.","connections.bluesky_oauth_authorization_failed": "We konden die Bluesky-gebruikersnaam niet vinden. Controleer deze en probeer het opnieuw.",- "connections.bluesky_oauth_callback_failed": "We konden de Bluesky-verbinding niet voltooien. Probeer het opnieuw.","connections.bluesky_oauth_not_enabled": "Bluesky-verbindingen zijn niet ingeschakeld voor deze instantie.",- "connections.bluesky_oauth_state_invalid": "Het autorisatieverzoek is verlopen of ongeldig. Probeer het nog eens.","connections.initiation_token_invalid": "Het token voor verbinding is ongeldig of verlopen.","connections.invalid_type": "Het verbindingstype wordt niet ondersteund.","connections.limit_reached": "Je hebt het maximale aantal verbindingen bereikt ({limit}).",diff --git a/packages/errors/src/i18n/weblate/locales/no.json b/packages/errors/src/i18n/weblate/locales/no.jsonindex 36653fddf..611889a34 100644--- a/packages/errors/src/i18n/weblate/locales/no.json+++ b/packages/errors/src/i18n/weblate/locales/no.json@@ -189,9 +189,7 @@"colors.color_value_too_low": "Fargeverdien må være minst 0x000000.","connections.already_exists": "En tilkobling av denne typen med denne ID-en eksisterer allerede.","connections.bluesky_oauth_authorization_failed": "Vi kunne ikke løse Bluesky-brukernavnet. Sjekk det og prøv igjen.",- "connections.bluesky_oauth_callback_failed": "Vi kunne ikke fullføre Bluesky-tilkoblingen. Prøv igjen.","connections.bluesky_oauth_not_enabled": "Bluesky-tilkoblinger er ikke aktivert på denne instansen.",- "connections.bluesky_oauth_state_invalid": "Autorisasjonsforespørselen din har utløpt eller er ugyldig. Prøv igjen.","connections.initiation_token_invalid": "Tilkoblingstokenet er ugyldig eller har utløpt.","connections.invalid_type": "Tilkoblingstypen er ikke støttet.","connections.limit_reached": "Du har nådd maksimalt antall tilkoblinger ({limit}).",diff --git a/packages/errors/src/i18n/weblate/locales/pl.json b/packages/errors/src/i18n/weblate/locales/pl.jsonindex a3877dcb8..d19a82991 100644--- a/packages/errors/src/i18n/weblate/locales/pl.json+++ b/packages/errors/src/i18n/weblate/locales/pl.json@@ -189,9 +189,7 @@"colors.color_value_too_low": "Wartość koloru musi wynosić co najmniej 0x000000.","connections.already_exists": "Połączenie tego typu z tym identyfikatorem już istnieje.","connections.bluesky_oauth_authorization_failed": "Nie udało się rozpoznać tego identyfikatora Bluesky. Sprawdź i spróbuj ponownie.",- "connections.bluesky_oauth_callback_failed": "Nie udało się nawiązać połączenia z Bluesky. Spróbuj ponownie.","connections.bluesky_oauth_not_enabled": "Połączenia Bluesky nie są włączone na tej instancji.",- "connections.bluesky_oauth_state_invalid": "Żądanie autoryzacji wygasło lub jest niepoprawne. Spróbuj ponownie.","connections.initiation_token_invalid": "Token inicjujący połączenie jest nieprawidłowy lub wygasł.","connections.invalid_type": "Typ połączenia jest nieobsługiwany.","connections.limit_reached": "Osiągnięto maksymalną liczbę połączeń ({limit}).",diff --git a/packages/errors/src/i18n/weblate/locales/pt-BR.json b/packages/errors/src/i18n/weblate/locales/pt-BR.jsonindex 2bd5511da..d91e841ca 100644--- a/packages/errors/src/i18n/weblate/locales/pt-BR.json+++ b/packages/errors/src/i18n/weblate/locales/pt-BR.json@@ -189,9 +189,7 @@"colors.color_value_too_low": "O valor da cor deve ser pelo menos 0x000000.","connections.already_exists": "Já existe uma conexão deste tipo com este identificador.","connections.bluesky_oauth_authorization_failed": "Não conseguimos resolver esse nome de usuário do Bluesky. Por favor, verifique e tente novamente.",- "connections.bluesky_oauth_callback_failed": "Não foi possível finalizar a conexão com o Bluesky. Por favor, tente novamente.","connections.bluesky_oauth_not_enabled": "As conexões do Bluesky não estão habilitadas nesta instância.",- "connections.bluesky_oauth_state_invalid": "A solicitação de autorização expirou ou é inválida. Por favor, tente novamente.","connections.initiation_token_invalid": "O token de conexão é inválido ou expirou.","connections.invalid_type": "O tipo de conexão não é suportado.","connections.limit_reached": "Você atingiu o número máximo de conexões ({limit}).",diff --git a/packages/errors/src/i18n/weblate/locales/ro.json b/packages/errors/src/i18n/weblate/locales/ro.jsonindex 35aceeebe..ac29df27c 100644--- a/packages/errors/src/i18n/weblate/locales/ro.json+++ b/packages/errors/src/i18n/weblate/locales/ro.json@@ -189,9 +189,7 @@"colors.color_value_too_low": "Valoarea culorii trebuie să fie cel puțin 0x000000.","connections.already_exists": "Există deja o conexiune de acest tip cu acest identificator.","connections.bluesky_oauth_authorization_failed": "Nu s-a putut rezolva contul Bluesky. Te rugăm să-l verifici și să încerci din nou.",- "connections.bluesky_oauth_callback_failed": "Nu am putut finaliza conexiunea Bluesky. Te rugăm să încerci din nou.","connections.bluesky_oauth_not_enabled": "Conexiunile Bluesky nu sunt activate pentru această instanță.",- "connections.bluesky_oauth_state_invalid": "Cererea de autorizare a expirat sau este nevalidă. Te rugăm să încerci din nou.","connections.initiation_token_invalid": "Tokenul de inițiere a conexiunii este nevalid sau a expirat.","connections.invalid_type": "Tipul de conexiune nu este acceptat.","connections.limit_reached": "Ai atins limita maximă de conexiuni ({limit}).",diff --git a/packages/errors/src/i18n/weblate/locales/ru.json b/packages/errors/src/i18n/weblate/locales/ru.jsonindex 0d86a8a79..20a21061e 100644--- a/packages/errors/src/i18n/weblate/locales/ru.json+++ b/packages/errors/src/i18n/weblate/locales/ru.json@@ -189,9 +189,7 @@"colors.color_value_too_low": "Значение цвета должно быть не менее 0x000000.","connections.already_exists": "Уже существует подключение такого типа с этим идентификатором.","connections.bluesky_oauth_authorization_failed": "Не удалось найти этот ник в Bluesky. Проверь его и попробуй ещё раз.",- "connections.bluesky_oauth_callback_failed": "Не удалось завершить подключение к Bluesky. Попробуй ещё раз.","connections.bluesky_oauth_not_enabled": "На этом экземпляре не включены подключения Bluesky.",- "connections.bluesky_oauth_state_invalid": "Истёк или недействителен запрос авторизации. Попробуй ещё раз.","connections.initiation_token_invalid": "Недействителен или истёк токен для начала подключения.","connections.invalid_type": "Этот тип подключения не поддерживается.","connections.limit_reached": "Ты достиг лимита подключений ({limit}).",diff --git a/packages/errors/src/i18n/weblate/locales/sv-SE.json b/packages/errors/src/i18n/weblate/locales/sv-SE.jsonindex 706198cbd..62df8d408 100644--- a/packages/errors/src/i18n/weblate/locales/sv-SE.json+++ b/packages/errors/src/i18n/weblate/locales/sv-SE.json@@ -189,9 +189,7 @@"colors.color_value_too_low": "Färgvärdet måste vara minst 0x000000.","connections.already_exists": "En anslutning av denna typ med denna identifierare finns redan.","connections.bluesky_oauth_authorization_failed": "Vi kunde inte lösa Bluesky-handtaget. Kontrollera det och försök igen.",- "connections.bluesky_oauth_callback_failed": "Vi kunde inte slutföra anslutningen till Bluesky. Försök igen.","connections.bluesky_oauth_not_enabled": "Bluesky-anslutningar är inte aktiverade på den här instansen.",- "connections.bluesky_oauth_state_invalid": "Auktoriseringen har gått ut eller är ogiltig. Försök igen.","connections.initiation_token_invalid": "Anslutningens starttoken är ogiltig eller har gått ut.","connections.invalid_type": "Anslutningstypen stöds inte.","connections.limit_reached": "Du har nått maxantalet anslutningar ({limit}).",diff --git a/packages/errors/src/i18n/weblate/locales/th.json b/packages/errors/src/i18n/weblate/locales/th.jsonindex 4dfa131c1..389fe758c 100644--- a/packages/errors/src/i18n/weblate/locales/th.json+++ b/packages/errors/src/i18n/weblate/locales/th.json@@ -189,9 +189,7 @@"colors.color_value_too_low": "ค่าสีต้องมีอย่างน้อย 0x000000","connections.already_exists": "มีการเชื่อมต่อประเภทนี้พร้อมตัวระบุนี้อยู่แล้ว","connections.bluesky_oauth_authorization_failed": "ไม่สามารถระบุ Bluesky handle นั้นได้ โปรดตรวจสอบและลองอีกครั้ง",- "connections.bluesky_oauth_callback_failed": "ไม่สามารถเชื่อมต่อ Bluesky ได้ โปรดลองอีกครั้ง","connections.bluesky_oauth_not_enabled": "การเชื่อมต่อ Bluesky ไม่ได้เปิดใช้งานบนอินสแตนซ์นี้",- "connections.bluesky_oauth_state_invalid": "คำขออนุญาตหมดอายุหรือใช้ไม่ได้ โปรดลองอีกครั้ง","connections.initiation_token_invalid": "โทเค็นการเริ่มต้นการเชื่อมต่อไม่ถูกต้องหรือหมดอายุแล้ว","connections.invalid_type": "ไม่รองรับประเภทการเชื่อมต่อ","connections.limit_reached": "ถึงขีดจำกัดการเชื่อมต่อแล้ว ({limit})",diff --git a/packages/errors/src/i18n/weblate/locales/tr.json b/packages/errors/src/i18n/weblate/locales/tr.jsonindex ea2f86467..4a8c80b0b 100644--- a/packages/errors/src/i18n/weblate/locales/tr.json+++ b/packages/errors/src/i18n/weblate/locales/tr.json@@ -189,9 +189,7 @@"colors.color_value_too_low": "Renk değeri en az 0x000000 olmalıdır.","connections.already_exists": "Bu tanımlayıcıya sahip bu türde bir bağlantı zaten mevcut.","connections.bluesky_oauth_authorization_failed": "Bu Bluesky kullanıcı adını çözümleyemedik. Lütfen kontrol et ve tekrar dene.",- "connections.bluesky_oauth_callback_failed": "Bluesky bağlantısını tamamlayamadık. Lütfen tekrar dene.","connections.bluesky_oauth_not_enabled": "Bu kurulumda Bluesky bağlantıları etkin değil.",- "connections.bluesky_oauth_state_invalid": "Yetkilendirme isteğinin süresi doldu veya geçersiz. Lütfen tekrar dene.","connections.initiation_token_invalid": "Bağlantı başlatma jetonu geçersiz veya süresi doldu.","connections.invalid_type": "Bağlantı türü desteklenmiyor.","connections.limit_reached": "Maksimum bağlantı sayısına ulaştın ({limit}).",diff --git a/packages/errors/src/i18n/weblate/locales/uk.json b/packages/errors/src/i18n/weblate/locales/uk.jsonindex f049f94bb..27e3cd4c3 100644--- a/packages/errors/src/i18n/weblate/locales/uk.json+++ b/packages/errors/src/i18n/weblate/locales/uk.json@@ -189,9 +189,7 @@"colors.color_value_too_low": "Значення кольору має бути не менше 0x000000.","connections.already_exists": "З'єднання такого типу з цим ідентифікатором вже існує.","connections.bluesky_oauth_authorization_failed": "Не вдалося розпізнати цей ідентифікатор Bluesky. Перевір його та спробуй ще раз.",- "connections.bluesky_oauth_callback_failed": "Не вдалося завершити підключення до Bluesky. Спробуй ще раз.","connections.bluesky_oauth_not_enabled": "Підключення до Bluesky не ввімкнено у цій інсталяції.",- "connections.bluesky_oauth_state_invalid": "Термін дії запиту на авторизацію закінчився або є недійсним. Спробуй ще раз.","connections.initiation_token_invalid": "Токен ініціації з'єднання недійсний або термін дії закінчився.","connections.invalid_type": "Тип з'єднання не підтримується.","connections.limit_reached": "Досягнуто максимальної кількості з'єднань ({limit}).",diff --git a/packages/errors/src/i18n/weblate/locales/vi.json b/packages/errors/src/i18n/weblate/locales/vi.jsonindex d1d68673c..37147d1b3 100644--- a/packages/errors/src/i18n/weblate/locales/vi.json+++ b/packages/errors/src/i18n/weblate/locales/vi.json@@ -189,9 +189,7 @@"colors.color_value_too_low": "Giá trị màu phải tối thiểu là 0x000000.","connections.already_exists": "Kết nối loại này với mã định danh này đã tồn tại.","connections.bluesky_oauth_authorization_failed": "Chúng tôi không thể tìm thấy tài khoản Bluesky đó. Vui lòng kiểm tra lại và thử lại.",- "connections.bluesky_oauth_callback_failed": "Chúng tôi không thể hoàn tất kết nối Bluesky. Vui lòng thử lại.","connections.bluesky_oauth_not_enabled": "Kết nối Bluesky không được bật trên phiên bản này.",- "connections.bluesky_oauth_state_invalid": "Yêu cầu ủy quyền đã hết hạn hoặc không hợp lệ. Thử lại.","connections.initiation_token_invalid": "Token khởi tạo kết nối không hợp lệ hoặc đã hết hạn.","connections.invalid_type": "Loại kết nối không được hỗ trợ.","connections.limit_reached": "Bạn đã đạt số lượng kết nối tối đa ({limit}).",diff --git a/packages/errors/src/i18n/weblate/locales/zh-CN.json b/packages/errors/src/i18n/weblate/locales/zh-CN.jsonindex 43d1727e0..bccdf3250 100644--- a/packages/errors/src/i18n/weblate/locales/zh-CN.json+++ b/packages/errors/src/i18n/weblate/locales/zh-CN.json@@ -189,9 +189,7 @@"colors.color_value_too_low": "颜色值必须至少为 0x000000。","connections.already_exists": "已存在此类型且标识符相同的连接。","connections.bluesky_oauth_authorization_failed": "我们无法解析该 Bluesky 账号。请检查并重试。",- "connections.bluesky_oauth_callback_failed": "我们无法完成 Bluesky 连接。请重试。","connections.bluesky_oauth_not_enabled": "此实例未启用 Bluesky 连接。",- "connections.bluesky_oauth_state_invalid": "授权请求已过期或失效。请重试。","connections.initiation_token_invalid": "连接初始化令牌无效或已过期。","connections.invalid_type": "不支持的连接类型。","connections.limit_reached": "你已达到最大连接数 ({limit})。",diff --git a/packages/errors/src/i18n/weblate/locales/zh-TW.json b/packages/errors/src/i18n/weblate/locales/zh-TW.jsonindex 1220fc4d1..777873002 100644--- a/packages/errors/src/i18n/weblate/locales/zh-TW.json+++ b/packages/errors/src/i18n/weblate/locales/zh-TW.json@@ -189,9 +189,7 @@"colors.color_value_too_low": "顏色值至少須為 0x000000。","connections.already_exists": "此類型與此識別碼的連線已存在。","connections.bluesky_oauth_authorization_failed": "我們無法解析該 Bluesky 帳號。請檢查並再試一次。",- "connections.bluesky_oauth_callback_failed": "我們無法完成 Bluesky 連線。請再試一次。","connections.bluesky_oauth_not_enabled": "此實例未啟用 Bluesky 連線。",- "connections.bluesky_oauth_state_invalid": "授權請求已過期或無效。請再試。","connections.initiation_token_invalid": "連線權杖無效或已過期。","connections.invalid_type": "不支援此連線類型。","connections.limit_reached": "你已達到最大連線數 ({limit})。",diff --git a/packages/errors/src/i18n/weblate/messages.json b/packages/errors/src/i18n/weblate/messages.jsonindex afe812da1..865bb47d4 100644--- a/packages/errors/src/i18n/weblate/messages.json+++ b/packages/errors/src/i18n/weblate/messages.json@@ -189,9 +189,7 @@"colors.color_value_too_low": "Color value must be at least 0x000000.","connections.already_exists": "A connection of this type with this identifier already exists.","connections.bluesky_oauth_authorization_failed": "We couldn't resolve that Bluesky handle. Please check it and try again.",- "connections.bluesky_oauth_callback_failed": "We couldn't complete the Bluesky connection. Please try again.","connections.bluesky_oauth_not_enabled": "Bluesky connections are not enabled on this instance.",- "connections.bluesky_oauth_state_invalid": "The authorization request has expired or is invalid. Please try again.","connections.initiation_token_invalid": "The connection initiation token is invalid or has expired.","connections.invalid_type": "The connection type is not supported.","connections.limit_reached": "You've reached the maximum number of connections ({limit}).",diff --git a/packages/hono/src/middleware/Cors.ts b/packages/hono/src/middleware/Cors.tsindex 4214f6fa2..a97eadbbf 100644--- a/packages/hono/src/middleware/Cors.ts+++ b/packages/hono/src/middleware/Cors.ts@@ -1,6 +1,6 @@// SPDX-License-Identifier: AGPL-3.0-or-later-import type {MiddlewareHandler} from 'hono';+import type {Context, MiddlewareHandler} from 'hono';export interface CorsOptions {enabled?: boolean;@@ -15,6 +15,14 @@ export interface CorsOptions {const DEFAULT_METHODS = ['GET', 'HEAD', 'PUT', 'PATCH', 'POST', 'DELETE', 'OPTIONS'];const DEFAULT_HEADERS = ['Content-Type', 'Authorization', 'X-Requested-With', 'Accept-Language', 'X-Request-ID'];+function appendOriginVary(c: Context): void {+ const vary = c.res.headers.get('Vary');+ const fields = vary?.split(',').map((field) => field.trim().toLowerCase()) ?? [];+ if (!fields.includes('*') && !fields.includes('origin')) {+ c.header('Vary', 'Origin', {append: Boolean(vary)});+ }+}+export function cors(options: CorsOptions = {}): MiddlewareHandler {const {enabled = true,@@ -36,7 +44,6 @@ export function cors(options: CorsOptions = {}): MiddlewareHandler {c.header('Access-Control-Allow-Origin', '*');} else if (Array.isArray(origins) && requestOrigin && origins.includes(requestOrigin)) {c.header('Access-Control-Allow-Origin', requestOrigin);- c.header('Vary', 'Origin');}if (credentials) {c.header('Access-Control-Allow-Credentials', 'true');@@ -52,10 +59,16 @@ export function cors(options: CorsOptions = {}): MiddlewareHandler {if (maxAge !== undefined) {c.header('Access-Control-Max-Age', maxAge.toString());}+ if (origins !== '*') {+ appendOriginVary(c);+ }return c.body(null, 204);}await next();applyCorsHeaders();+ if (origins !== '*') {+ appendOriginVary(c);+ }return;};}diff --git a/packages/hono/src/middleware/Metrics.ts b/packages/hono/src/middleware/Metrics.tsindex 502a9f84e..13ae8cf97 100644--- a/packages/hono/src/middleware/Metrics.ts+++ b/packages/hono/src/middleware/Metrics.ts@@ -75,10 +75,8 @@ class Histogram {const lines: Array<string> = [];lines.push(`# HELP ${name} ${help}`);lines.push(`# TYPE ${name} histogram`);- let cumulative = 0;for (let i = 0; i < this.buckets.length; i++) {- cumulative += this.counts[i];- lines.push(`${name}_bucket{le="${this.buckets[i]}"} ${cumulative}`);+ lines.push(`${name}_bucket{le="${this.buckets[i]}"} ${this.counts[i]}`);}lines.push(`${name}_bucket{le="+Inf"} ${this.count}`);lines.push(`${name}_sum ${this.sum}`);@@ -118,12 +116,12 @@ interface MetricsResult {export function createMetricsMiddleware(serviceName: string): MetricsResult {const prefix = `fluxer_${serviceName}`;- const startTime = Date.now();+ const startTime = performance.now();const requestsTotal = new Counter();const errorsTotal = new Counter();const requestDuration = new Histogram(DEFAULT_BUCKETS);- const uptime = new Gauge(() => (Date.now() - startTime) / 1000);+ const uptime = new Gauge(() => (performance.now() - startTime) / 1000);const state: MetricsState = {requestsTotal, errorsTotal, requestDuration, uptime};diff --git a/packages/hono/src/middleware/tests/Cors.test.ts b/packages/hono/src/middleware/tests/Cors.test.tsindex 3e122d6b4..bd8aa7640 100644--- a/packages/hono/src/middleware/tests/Cors.test.ts+++ b/packages/hono/src/middleware/tests/Cors.test.ts@@ -47,6 +47,7 @@ describe('CORS Middleware', () => {});expect(response.status).toBe(200);expect(response.headers.get('Access-Control-Allow-Origin')).toBeNull();+ expect(response.headers.get('Vary')).toBe('Origin');});test('does not set origin header when no origin header in request', async () => {const app = new Hono();diff --git a/packages/hono/src/security/OutboundEndpoint.ts b/packages/hono/src/security/OutboundEndpoint.tsindex ae43273e9..16db51bc5 100644--- a/packages/hono/src/security/OutboundEndpoint.ts+++ b/packages/hono/src/security/OutboundEndpoint.ts@@ -1,6 +1,7 @@// SPDX-License-Identifier: AGPL-3.0-or-later-import {isIP} from 'node:net';+import {isIPv4} from 'node:net';+import {getIpNetworkKey} from '@fluxer/ip_utils/src/IpAddress';interface ValidateOutboundEndpointOptions {name: string;@@ -65,14 +66,14 @@ function isLocalhostHostname(hostname: string): boolean {}function isPrivateOrSpecialIpLiteral(hostname: string): boolean {- const ipVersion = isIP(hostname);- if (!ipVersion) {+ const address = getIpNetworkKey(hostname, {ipv4PrefixLength: 'exact', ipv6PrefixLength: 'exact'});+ if (address === null) {return false;}- if (ipVersion === 4) {- return isPrivateOrSpecialIPv4(hostname);+ if (isIPv4(address)) {+ return isPrivateOrSpecialIPv4(address);}- return isPrivateOrSpecialIPv6(hostname);+ return isPrivateOrSpecialIPv6(address);}function isPrivateOrSpecialIPv4(hostname: string): boolean {@@ -91,17 +92,10 @@ function isPrivateOrSpecialIPv4(hostname: string): boolean {return false;}-function isPrivateOrSpecialIPv6(hostname: string): boolean {- const lower = hostname.toLowerCase();- if (lower === '::' || lower === '::1') {+function isPrivateOrSpecialIPv6(address: string): boolean {+ if (address === '::' || address === '::1') {return true;}- if (lower.startsWith('::ffff:')) {- const mapped = lower.slice('::ffff:'.length);- return isPrivateOrSpecialIPv4(mapped);- }- if (lower.startsWith('fe80:')) return true;- if (lower.startsWith('fc') || lower.startsWith('fd')) return true;- if (lower.startsWith('ff')) return true;- return false;+ const firstGroup = Number.parseInt(address.split(':', 1)[0] || '0', 16);+ return (firstGroup & 0xffc0) === 0xfe80 || (firstGroup & 0xfe00) === 0xfc00 || (firstGroup & 0xff00) === 0xff00;}diff --git a/packages/i18n/src/runtime/CompileTemplate.ts b/packages/i18n/src/runtime/CompileTemplate.tsdeleted file mode 100644index 1f625969f..000000000--- a/packages/i18n/src/runtime/CompileTemplate.ts+++ /dev/null@@ -1,13 +0,0 @@-// SPDX-License-Identifier: AGPL-3.0-or-later--import type {TemplateCompiler} from '@fluxer/i18n/src/runtime/I18nTypes';-import type MessageFormat from '@messageformat/core';--export function compileTemplate<TValue, TVariables>(- compiler: TemplateCompiler<TValue, TVariables>,- template: TValue,- variables: TVariables,- mf: MessageFormat,-): TValue {- return compiler(template, variables, mf);-}diff --git a/packages/i18n/src/runtime/CreateStaticI18n.ts b/packages/i18n/src/runtime/CreateStaticI18n.tsindex dec384aa9..5fe01d7ae 100644--- a/packages/i18n/src/runtime/CreateStaticI18n.ts+++ b/packages/i18n/src/runtime/CreateStaticI18n.ts@@ -1,8 +1,9 @@// SPDX-License-Identifier: AGPL-3.0-or-laterimport type {I18nResult, TemplateCompiler} from '@fluxer/i18n/src/runtime/I18nTypes';-import {getEffectiveStaticLocale} from '@fluxer/i18n/src/runtime/StaticLocale';-import MessageFormat from '@messageformat/core';+import {renderTemplate} from '@fluxer/i18n/src/runtime/RenderTemplate';+import {getEffectiveStaticLocale, hasStaticLocale} from '@fluxer/i18n/src/runtime/StaticLocale';+import type MessageFormat from '@messageformat/core';export type StaticLocaleMessages<TKey extends string, TValue> = Partial<Record<TKey, TValue>>;@@ -28,20 +29,11 @@ export function createStaticI18n<TKey extends string, TValue, TVariables>(): StaticI18nModule<TKey, TValue, TVariables> {const loadedLocales = new Set<string>([config.defaultLocale]);const messageFormatCache = new Map<string, MessageFormat>();- function getMessageFormat(locale: string): MessageFormat {- const cached = messageFormatCache.get(locale);- if (cached) {- return cached;- }- const messageFormat = new MessageFormat(locale);- messageFormatCache.set(locale, messageFormat);- return messageFormat;- }return {getTemplate(key: TKey, locale: string | null, variables: TVariables): I18nResult<TKey, TValue> {const effectiveLocale = getEffectiveStaticLocale(config, locale);loadedLocales.add(effectiveLocale);- const sourceTemplate = config.defaultMessages[key];+ const sourceTemplate = Object.hasOwn(config.defaultMessages, key) ? config.defaultMessages[key] : undefined;if (sourceTemplate === undefined) {return {ok: false,@@ -53,7 +45,11 @@ export function createStaticI18n<TKey extends string, TValue, TVariables>(locale: effectiveLocale,};}- const translatedTemplate = config.localeMessages[effectiveLocale]?.[key];+ const localeMessages = Object.hasOwn(config.localeMessages, effectiveLocale)+ ? config.localeMessages[effectiveLocale]+ : undefined;+ const translatedTemplate =+ localeMessages != null && Object.hasOwn(localeMessages, key) ? localeMessages[key] : undefined;const template = translatedTemplate ?? sourceTemplate;const validationError = config.validateVariables?.(key, template, variables);if (validationError) {@@ -67,27 +63,18 @@ export function createStaticI18n<TKey extends string, TValue, TVariables>(locale: effectiveLocale,};}- try {- return {- ok: true,- value: compile(template, variables, getMessageFormat(effectiveLocale)),- locale: effectiveLocale,- };- } catch (error) {- return {- ok: false,- error: {- kind: 'compile-failed',- key,- message: error instanceof Error ? error.message : 'Failed to compile template',- },- locale: effectiveLocale,- };- }+ return renderTemplate({+ key,+ locale: effectiveLocale,+ template,+ variables,+ compile,+ messageFormatCache,+ });},hasLocale(locale: string): boolean {const normalizedLocale = config.normalizeLocale?.(locale) ?? locale;- return normalizedLocale === config.defaultLocale || config.localeMessages[normalizedLocale] !== undefined;+ return hasStaticLocale(config, normalizedLocale);},getLoadedLocales(): Set<string> {return new Set(loadedLocales);diff --git a/packages/i18n/src/runtime/GetTemplate.ts b/packages/i18n/src/runtime/GetTemplate.tsindex fbec3f42c..1f24a7c4d 100644--- a/packages/i18n/src/runtime/GetTemplate.ts+++ b/packages/i18n/src/runtime/GetTemplate.ts@@ -1,10 +1,9 @@// SPDX-License-Identifier: AGPL-3.0-or-later-import {compileTemplate} from '@fluxer/i18n/src/runtime/CompileTemplate';import {getEffectiveLocale} from '@fluxer/i18n/src/runtime/GetEffectiveLocale';import type {I18nResult, I18nState, TemplateCompiler} from '@fluxer/i18n/src/runtime/I18nTypes';import {loadLocaleIfNotLoaded} from '@fluxer/i18n/src/runtime/LoadLocale';-import MessageFormat from '@messageformat/core';+import {renderTemplate} from '@fluxer/i18n/src/runtime/RenderTemplate';export function getTemplate<TKey extends string, TValue, TVariables>(state: I18nState<TKey, TValue, TVariables>,@@ -41,31 +40,12 @@ export function getTemplate<TKey extends string, TValue, TVariables>(locale: effectiveLocale,};}- try {- const compiled = compileTemplate(compile, template, variables, getMessageFormat(state, effectiveLocale));- return {ok: true, value: compiled, locale: effectiveLocale};- } catch (error) {- return {- ok: false,- error: {- kind: 'compile-failed',- key,- message: error instanceof Error ? error.message : 'Failed to compile template',- },- locale: effectiveLocale,- };- }-}--function getMessageFormat<TKey extends string, TValue, TVariables>(- state: I18nState<TKey, TValue, TVariables>,- locale: string,-): MessageFormat {- const cached = state.messageFormatCache.get(locale);- if (cached) {- return cached;- }- const mf = new MessageFormat(locale);- state.messageFormatCache.set(locale, mf);- return mf;+ return renderTemplate({+ key,+ locale: effectiveLocale,+ template,+ variables,+ compile,+ messageFormatCache: state.messageFormatCache,+ });}diff --git a/packages/i18n/src/runtime/RenderTemplate.ts b/packages/i18n/src/runtime/RenderTemplate.tsnew file mode 100644index 000000000..9966ed8ad--- /dev/null+++ b/packages/i18n/src/runtime/RenderTemplate.ts@@ -0,0 +1,45 @@+// SPDX-License-Identifier: AGPL-3.0-or-later++import type {I18nResult, TemplateCompiler} from '@fluxer/i18n/src/runtime/I18nTypes';+import MessageFormat from '@messageformat/core';++interface TemplateRenderOptions<TKey extends string, TValue, TVariables> {+ key: TKey;+ locale: string;+ template: TValue;+ variables: TVariables;+ compile: TemplateCompiler<TValue, TVariables>;+ messageFormatCache: Map<string, MessageFormat>;+}++export function renderTemplate<TKey extends string, TValue, TVariables>({+ key,+ locale,+ template,+ variables,+ compile,+ messageFormatCache,+}: TemplateRenderOptions<TKey, TValue, TVariables>): I18nResult<TKey, TValue> {+ try {+ let messageFormat = messageFormatCache.get(locale);+ if (!messageFormat) {+ messageFormat = new MessageFormat(locale);+ messageFormatCache.set(locale, messageFormat);+ }+ return {+ ok: true,+ value: compile(template, variables, messageFormat),+ locale,+ };+ } catch (error) {+ return {+ ok: false,+ error: {+ kind: 'compile-failed',+ key,+ message: error instanceof Error ? error.message : 'Failed to compile template',+ },+ locale,+ };+ }+}diff --git a/packages/i18n/src/runtime/StaticLocale.ts b/packages/i18n/src/runtime/StaticLocale.tsindex 6719bb7b0..8da2b5c8b 100644--- a/packages/i18n/src/runtime/StaticLocale.ts+++ b/packages/i18n/src/runtime/StaticLocale.ts@@ -2,6 +2,16 @@import type {StaticI18nConfig} from '@fluxer/i18n/src/runtime/CreateStaticI18n';+export function hasStaticLocale<TKey extends string, TValue, TVariables>(+ config: StaticI18nConfig<TKey, TValue, TVariables>,+ normalizedLocale: string,+): boolean {+ return (+ normalizedLocale === config.defaultLocale ||+ (Object.hasOwn(config.localeMessages, normalizedLocale) && config.localeMessages[normalizedLocale] !== undefined)+ );+}+export function getEffectiveStaticLocale<TKey extends string, TValue, TVariables>(config: StaticI18nConfig<TKey, TValue, TVariables>,locale: string | null | undefined,@@ -10,10 +20,7 @@ export function getEffectiveStaticLocale<TKey extends string, TValue, TVariablesreturn config.defaultLocale;}const normalizedLocale = config.normalizeLocale?.(locale) ?? locale;- if (normalizedLocale === config.defaultLocale) {- return config.defaultLocale;- }- if (config.localeMessages[normalizedLocale] === undefined) {+ if (!hasStaticLocale(config, normalizedLocale)) {config.onWarning?.(`Unsupported locale, falling back to ${config.defaultLocale}: ${locale}`);return config.defaultLocale;}diff --git a/packages/ip_utils/src/ClientIp.ts b/packages/ip_utils/src/ClientIp.tsindex b7c3871df..09d9c21f4 100644--- a/packages/ip_utils/src/ClientIp.ts+++ b/packages/ip_utils/src/ClientIp.ts@@ -52,31 +52,11 @@ function toStringHeaderValue(value: string | Array<string> | null | undefined):return typeof value === 'string' ? value : null;}-function parseSingleIpValue(value: string): ParsedIpAddress | null {- const trimmed = value.trim();- if (!trimmed) {- return null;- }- return parseIpAddress(trimmed);-}-function parseClientIpHeaderValue(value: string | null): ParsedIpAddress | null {if (value === null) {return null;}- const [firstHop] = value.split(',');- if (firstHop === undefined) {- return null;- }- return parseSingleIpValue(firstHop);-}--function createRequestHeaderReader(request: Request): HeaderReader {- return {- get: (name: string): string | null => {- return request.headers.get(name);- },- };+ return parseIpAddress(value.split(',', 1)[0]);}function getHeaderValue(headers: HeadersLike, name: string): string | null {@@ -121,7 +101,7 @@ function extractClientIpDetailsFromReader(}export function extractClientIpDetails(req: Request, options?: ClientIpExtractionOptions): ExtractedClientIp | null {- return extractClientIpDetailsFromReader(createRequestHeaderReader(req), options);+ return extractClientIpDetailsFromReader(req.headers, options);}export function extractClientIp(req: Request, options?: ClientIpExtractionOptions): string | null {diff --git a/packages/ip_utils/src/IpAddress.ts b/packages/ip_utils/src/IpAddress.tsindex 87be50517..163ba50b9 100644--- a/packages/ip_utils/src/IpAddress.ts+++ b/packages/ip_utils/src/IpAddress.ts@@ -21,6 +21,23 @@ const SAME_IP_DECISION_KEY_OPTIONS: Readonly<IpNetworkKeyOptions> = {ipv6PrefixLength: 64,};+const RESERVED_IPV4_RANGES: ReadonlyArray<readonly [base: number, prefixLength: number]> = [+ [0x00000000, 8],+ [0x0a000000, 8],+ [0x64400000, 10],+ [0x7f000000, 8],+ [0xa9fe0000, 16],+ [0xac100000, 12],+ [0xc0000000, 24],+ [0xc0000200, 24],+ [0xc0a80000, 16],+ [0xc6120000, 15],+ [0xc6336400, 24],+ [0xcb007100, 24],+ [0xe0000000, 4],+ [0xf0000000, 4],+];+function stripIpv6Brackets(value: string): string {if (value.startsWith('[') && value.endsWith(']')) {return value.slice(1, -1);@@ -112,7 +129,7 @@ function expandIpv6ToGroups(address: string): Array<string> {return address.split(':').map((g) => g.padStart(4, '0'));}-function isIpv4MappedIpv6Groups(groups: Array<string>): boolean {+function isIpv4MappedIpv6Groups(groups: ReadonlyArray<string>): boolean {return (groups[0] === '0000' &&groups[1] === '0000' &&@@ -123,7 +140,7 @@ function isIpv4MappedIpv6Groups(groups: Array<string>): boolean {);}-function ipv4FromMappedIpv6Groups(groups: Array<string>): string {+function ipv4FromMappedIpv6Groups(groups: ReadonlyArray<string>): string {const hi = parseInt(groups[6], 16);const lo = parseInt(groups[7], 16);const a = (hi >> 8) & 0xff;@@ -237,72 +254,28 @@ function isPublicIpv4Address(address: string): boolean {if (!octets) {return false;}- const reservedRanges: Array<[base: number, prefixLength: number]> = [- [0x00000000, 8],- [0x0a000000, 8],- [0x64400000, 10],- [0x7f000000, 8],- [0xa9fe0000, 16],- [0xac100000, 12],- [0xc0000000, 24],- [0xc0000200, 24],- [0xc0a80000, 16],- [0xc6120000, 15],- [0xc6336400, 24],- [0xcb007100, 24],- [0xe0000000, 4],- [0xf0000000, 4],- ];- return !reservedRanges.some(([base, prefixLength]) => isIpv4InCidr(octets, base, prefixLength));+ return !RESERVED_IPV4_RANGES.some(([base, prefixLength]) => isIpv4InCidr(octets, base, prefixLength));}-function getIpv4MappedIpv6(address: string): string | null {- const groups = expandIpv6ToGroups(address);+function getIpv4MappedIpv6(groups: ReadonlyArray<string>): string | null {if (!isIpv4MappedIpv6Groups(groups)) {return null;}return ipv4FromMappedIpv6Groups(groups);}-function ipv6GroupValue(group: string): number {- return Number.parseInt(group, 16);-}-function isPublicIpv6Address(address: string): boolean {- const mappedIpv4 = getIpv4MappedIpv6(address);+ const groups = expandIpv6ToGroups(address);+ const mappedIpv4 = getIpv4MappedIpv6(groups);if (mappedIpv4) {return isPublicIpv4Address(mappedIpv4);}- const groups = expandIpv6ToGroups(address);- const first = ipv6GroupValue(groups[0]);- const second = ipv6GroupValue(groups[1]);- const last = ipv6GroupValue(groups[7]);- const isUnspecifiedOrLoopback = groups.slice(0, 7).every((group) => group === '0000') && (last === 0 || last === 1);- if (isUnspecifiedOrLoopback) {- return false;- }+ const first = Number.parseInt(groups[0], 16);+ const second = Number.parseInt(groups[1], 16);if ((first & 0xe000) !== 0x2000) {return false;}- if ((first & 0xffc0) === 0xfe80) {- return false;- }- if ((first & 0xfe00) === 0xfc00) {- return false;- }- if ((first & 0xff00) === 0xff00) {- return false;- }- if (first === 0x2001 && second === 0x0db8) {- return false;- }- if (first === 0x0064 && second === 0xff9b) {- return false;- }- if (first === 0x0100 && second === 0x0000) {- return false;- }- return true;+ return first !== 0x2001 || second !== 0x0db8;}export function isPublicIpAddress(ip: string): boolean {@@ -332,11 +305,11 @@ export function isLoopbackIpAddress(ip: string): boolean {if (parsed.family === 'ipv4') {return isLoopbackIpv4Address(parsed.normalized);}- const mappedIpv4 = getIpv4MappedIpv6(parsed.normalized);+ const groups = expandIpv6ToGroups(parsed.normalized);+ const mappedIpv4 = getIpv4MappedIpv6(groups);if (mappedIpv4) {return isLoopbackIpv4Address(mappedIpv4);}- const groups = expandIpv6ToGroups(parsed.normalized);return groups.length === 8 && groups.slice(0, 7).every((group) => group === '0000') && groups[7] === '0001';}diff --git a/packages/logger/src/Logger.ts b/packages/logger/src/Logger.tsindex 8f6f4f694..0a0bfcc23 100644--- a/packages/logger/src/Logger.ts+++ b/packages/logger/src/Logger.ts@@ -6,20 +6,9 @@ import pino, {type Logger as PinoLogger} from 'pino';interface LoggerOptions {level?: pino.Level;environment?: string;- serviceVersion?: string;baseProperties?: Record<string, unknown>;}-interface PinoTransportOptions {- target: string;- options?: Record<string, unknown>;- caller?: Array<string>;- worker?: {- autoEnd?: boolean;- endTimeout?: number;- };-}-const PINO_LEVELS: ReadonlyArray<pino.Level> = ['fatal', 'error', 'warn', 'info', 'debug', 'trace'];function isDevelopment(environment: string): boolean {@@ -49,39 +38,29 @@ function createPinoLogger(serviceName: string, options: LoggerOptions = {}): Pinconst environment = resolveEnvironment(options);const isDev = isDevelopment(environment);const level = resolveLevel(options, isDev);- const streams: Array<pino.StreamEntry> = [];+ let destination: pino.DestinationStream;if (isDev) {try {const require = createRequire(import.meta.url);const pinoPrettyTarget = require.resolve('pino-pretty');- streams.push({- level: 'trace',- stream: pino.transport({- target: pinoPrettyTarget,- options: {- colorize: true,- translateTime: 'HH:MM:ss.l',- ignore: 'pid,hostname',- messageFormat: '{msg}',- },- sync: true,- } as PinoTransportOptions),- });+ const transportOptions: pino.TransportSingleOptions & {sync: boolean} = {+ target: pinoPrettyTarget,+ options: {+ colorize: true,+ translateTime: 'HH:MM:ss.l',+ ignore: 'pid,hostname',+ messageFormat: '{msg}',+ },+ sync: true,+ };+ destination = pino.transport(transportOptions);} catch (error) {console.warn('pino-pretty not available, falling back to stdout', error);- streams.push({- level: 'trace',- stream: pino.destination({dest: 1, sync: true}),- });+ destination = pino.destination({dest: 1, sync: true});}} else {- streams.push({- level: 'trace',- stream: pino.destination({dest: 1, sync: false}),- });+ destination = pino.destination({dest: 1, sync: false});}- const destination =- streams.length === 1 && streams[0] ? streams[0].stream : pino.multistream(streams, {dedupe: true});const pinoOptions: pino.LoggerOptions = {level,formatters: {@@ -135,72 +114,46 @@ export class Logger {trace(obj: Record<string, unknown>, msg?: string): void;trace(msg: string): void;trace(objOrMsg: Record<string, unknown> | string, msg?: string): void {- if (typeof objOrMsg === 'string') {- this.logger.trace(objOrMsg);- } else if (msg) {- this.logger.trace(objOrMsg, msg);- } else {- this.logger.trace(objOrMsg);- }+ this.log('trace', objOrMsg, msg);}debug(obj: Record<string, unknown>, msg?: string): void;debug(msg: string): void;debug(objOrMsg: Record<string, unknown> | string, msg?: string): void {- if (typeof objOrMsg === 'string') {- this.logger.debug(objOrMsg);- } else if (msg) {- this.logger.debug(objOrMsg, msg);- } else {- this.logger.debug(objOrMsg);- }+ this.log('debug', objOrMsg, msg);}info(obj: Record<string, unknown>, msg?: string): void;info(msg: string): void;info(objOrMsg: Record<string, unknown> | string, msg?: string): void {- if (typeof objOrMsg === 'string') {- this.logger.info(objOrMsg);- } else if (msg) {- this.logger.info(objOrMsg, msg);- } else {- this.logger.info(objOrMsg);- }+ this.log('info', objOrMsg, msg);}warn(obj: Record<string, unknown>, msg?: string): void;warn(msg: string): void;warn(objOrMsg: Record<string, unknown> | string, msg?: string): void {- if (typeof objOrMsg === 'string') {- this.logger.warn(objOrMsg);- } else if (msg) {- this.logger.warn(objOrMsg, msg);- } else {- this.logger.warn(objOrMsg);- }+ this.log('warn', objOrMsg, msg);}error(obj: Record<string, unknown>, msg?: string): void;error(msg: string): void;error(objOrMsg: Record<string, unknown> | string, msg?: string): void {- if (typeof objOrMsg === 'string') {- this.logger.error(objOrMsg);- } else if (msg) {- this.logger.error(objOrMsg, msg);- } else {- this.logger.error(objOrMsg);- }+ this.log('error', objOrMsg, msg);}fatal(obj: Record<string, unknown>, msg?: string): void;fatal(msg: string): void;fatal(objOrMsg: Record<string, unknown> | string, msg?: string): void {+ this.log('fatal', objOrMsg, msg);+ }++ private log(level: pino.Level, objOrMsg: Record<string, unknown> | string, msg?: string): void {if (typeof objOrMsg === 'string') {- this.logger.fatal(objOrMsg);+ this.logger[level](objOrMsg);} else if (msg) {- this.logger.fatal(objOrMsg, msg);+ this.logger[level](objOrMsg, msg);} else {- this.logger.fatal(objOrMsg);+ this.logger[level](objOrMsg);}}diff --git a/packages/openapi/src/OpenAPIComponentRef.ts b/packages/openapi/src/OpenAPIComponentRef.tsnew file mode 100644index 000000000..2339859be--- /dev/null+++ b/packages/openapi/src/OpenAPIComponentRef.ts@@ -0,0 +1,12 @@+import type {OpenAPIRef} from '@fluxer/openapi/src/OpenAPITypes';++export function validateOpenAPIComponentName(name: string): void {+ if (!/^[A-Za-z0-9._-]+$/.test(name)) {+ throw new Error(`Invalid OpenAPI schema name: ${name}`);+ }+}++export function createOpenAPIComponentRef(name: string): OpenAPIRef {+ validateOpenAPIComponentName(name);+ return {$ref: `#/components/schemas/${name}`};+}diff --git a/packages/openapi/src/OpenAPIGenerator.ts b/packages/openapi/src/OpenAPIGenerator.tsindex d05d7acd3..e78b3d70a 100644--- a/packages/openapi/src/OpenAPIGenerator.ts+++ b/packages/openapi/src/OpenAPIGenerator.ts@@ -1,5 +1,6 @@// SPDX-License-Identifier: AGPL-3.0-or-later+import assert from 'node:assert/strict';import {convertPathToOpenAPI} from '@fluxer/openapi/src/extractors/PathParameters';import {discoverControllerFiles, extractRoutesFromControllers} from '@fluxer/openapi/src/extractors/RouteExtractor';import {isExcludedRoutePath, OpenAPIGeneratorCatalog} from '@fluxer/openapi/src/generator/OpenAPIGeneratorCatalog';@@ -170,13 +171,12 @@ export class OpenAPIGenerator {allSchemas: Record<string, OpenAPISchema>,referencedSchemas: Set<string>,): Record<string, OpenAPISchema> {- const publishedSchemas: Record<string, OpenAPISchema> = {};+ const publishedSchemas = new Map<string, OpenAPISchema>();for (const name of referencedSchemas) {- if (allSchemas[name]) {- publishedSchemas[name] = allSchemas[name];- }+ assert(Object.hasOwn(allSchemas, name), `Referenced OpenAPI schema is missing: ${name}`);+ publishedSchemas.set(name, allSchemas[name]);}- return publishedSchemas;+ return Object.fromEntries(publishedSchemas);}private buildTags(routes: Array<ExtractedRoute>): Array<{name: string;diff --git a/packages/openapi/src/converters/ZodToOpenAPI.ts b/packages/openapi/src/converters/ZodToOpenAPI.tsindex d797f8cce..5011a13d8 100644--- a/packages/openapi/src/converters/ZodToOpenAPI.ts+++ b/packages/openapi/src/converters/ZodToOpenAPI.ts@@ -1,5 +1,6 @@// SPDX-License-Identifier: AGPL-3.0-or-laterimport {isDeepStrictEqual} from 'node:util';+import {createOpenAPIComponentRef, validateOpenAPIComponentName} from '@fluxer/openapi/src/OpenAPIComponentRef';import type {OpenAPISchemaTarget} from '@fluxer/openapi/src/OpenAPIGenerationTypes';import {visitOpenAPISchemaObjects} from '@fluxer/openapi/src/OpenAPISchemaVisitor';import type {OpenAPIDocument, OpenAPIRef, OpenAPISchema} from '@fluxer/openapi/src/OpenAPITypes';@@ -15,16 +16,10 @@ interface PendingSchema {}function componentName(name: string, io: SchemaIO): string {- if (!/^[A-Za-z0-9._-]+$/.test(name)) {- throw new Error(`Invalid OpenAPI schema name: ${name}`);- }+ validateOpenAPIComponentName(name);return io === 'input' ? `${name}Input` : name;}-function componentRef(name: string): OpenAPIRef {- return {$ref: `#/components/schemas/${name}`};-}-function replaceSchema(target: OpenAPISchema, replacement: OpenAPISchema): void {for (const key of Object.keys(target)) delete target[key];Object.assign(target, replacement);@@ -41,32 +36,31 @@ function applyMetadata(schema: core.$ZodType, json: OpenAPISchema): void {if (!metadata) return;if (metadata.format) json.format = metadata.format;if (metadata.bitflagValues) json['x-bitflagValues'] = metadata.bitflagValues;- if (metadata.enumEntries) {- const entries = metadata.enumEntries;- json['x-enumNames'] = entries.map((entry) => entry.name);- const descriptions = entries.map((entry) => entry.description ?? null);- if (descriptions.some((description) => description !== null)) {- json['x-enumDescriptions'] = descriptions;- }- delete json.anyOf;- delete json.oneOf;- if (metadata.openEnum) {- json.type = 'string';- const knownValues = entries.map((entry) => String(entry.value)).join(', ');- json.description = `${json.description ? `${json.description} ` : ''}Known values: ${knownValues} (other values allowed)`;- } else {- delete json.const;- json.enum = entries.map((entry) => entry.value);- json.type = entries.every((entry) => typeof entry.value === 'string') ? 'string' : 'integer';- }+ const entries = metadata.enumEntries;+ if (!entries) return;+ json['x-enumNames'] = entries.map((entry) => entry.name);+ const descriptions = entries.map((entry) => entry.description ?? null);+ if (descriptions.some((description) => description !== null)) {+ json['x-enumDescriptions'] = descriptions;+ }+ delete json.anyOf;+ delete json.oneOf;+ if (metadata.openEnum) {+ json.type = 'string';+ const knownValues = entries.map((entry) => String(entry.value)).join(', ');+ json.description = `${json.description ? `${json.description} ` : ''}Known values: ${knownValues} (other values allowed)`;+ } else {+ delete json.const;+ json.enum = entries.map((entry) => entry.value);+ json.type = entries.every((entry) => typeof entry.value === 'string') ? 'string' : 'integer';}}function relocateLocalRefs(value: unknown, name: string): void {visitOpenAPISchemaObjects(value, (schema) => {- if (schema.$ref === '#') schema.$ref = componentRef(name).$ref;+ if (schema.$ref === '#') schema.$ref = createOpenAPIComponentRef(name).$ref;else if (schema.$ref?.startsWith('#/$defs/') || schema.$ref?.startsWith('#/definitions/')) {- schema.$ref = `${componentRef(name).$ref}${schema.$ref.slice(1)}`;+ schema.$ref = `${createOpenAPIComponentRef(name).$ref}${schema.$ref.slice(1)}`;}});}@@ -87,10 +81,12 @@ function removeRedundantReferenceProperties(value: unknown, schemas: Record<striconst refs = [schema.$ref, ...(schema.allOf ?? []).map((branch) => branch.$ref)];for (const ref of refs) {if (typeof ref !== 'string' || !ref.startsWith('#/components/schemas/')) continue;- const referenced = schemas[ref.slice('#/components/schemas/'.length)];- if (!referenced) continue;- for (const [key, property] of Object.entries(schema)) {- if (key !== '$ref' && key !== 'allOf' && isDeepStrictEqual(property, referenced[key])) delete schema[key];+ const name = ref.slice('#/components/schemas/'.length);+ if (!Object.hasOwn(schemas, name)) continue;+ const referenced = schemas[name];+ if (referenced === schema) continue;+ for (const key of Object.keys(schema)) {+ if (key !== '$ref' && key !== 'allOf' && isDeepStrictEqual(schema[key], referenced[key])) delete schema[key];}}});@@ -106,6 +102,7 @@ export class ZodOpenAPIConverter {constructor(private readonly target: OpenAPISchemaTarget) {}register(name: string, schema: core.$ZodType): void {+ validateOpenAPIComponentName(name);if (!this.names.has(schema)) this.names.set(schema, name);}@@ -121,7 +118,7 @@ export class ZodOpenAPIConverter {else this.pending.set(key, [pending]);this.worklist.push(pending);}- return componentRef(key);+ return createOpenAPIComponentRef(key);}getSchema(name: string, schema: core.$ZodType, io: SchemaIO): OpenAPISchema {@@ -147,19 +144,21 @@ export class ZodOpenAPIConverter {while (remaining.size > 0) {const renames = new Map<string, string>();for (const [inputName, outputName] of remaining) {- const output = document.components.schemas[outputName];+ const output = Object.hasOwn(document.components.schemas, outputName)+ ? document.components.schemas[outputName]+ : undefined;if (!output || schemasHaveSameContract(document.components.schemas[inputName], output)) {renames.set(inputName, outputName);}}if (renames.size === 0) break;renameComponentRefs(document, renames);- const schemas: Record<string, OpenAPISchema> = {};+ const schemas = new Map<string, OpenAPISchema>();for (const [name, schema] of Object.entries(document.components.schemas)) {const renamed = renames.get(name) ?? name;- if (!Object.hasOwn(schemas, renamed) || name === renamed) schemas[renamed] = schema;+ if (!schemas.has(renamed) || name === renamed) schemas.set(renamed, schema);}- document.components.schemas = schemas;+ document.components.schemas = Object.fromEntries(schemas);for (const name of renames.keys()) remaining.delete(name);}removeRedundantReferenceProperties(document, document.components.schemas);@@ -189,7 +188,7 @@ export class ZodOpenAPIConverter {const name =this.names.get(zodSchema) ??(schemaMetadata.has(zodSchema) ? schemaMetadata.get(zodSchema)?.name : undefined);- if (name) {+ if (name !== undefined) {const description = jsonSchema.description;const ref = this.getRef(name, zodSchema, io);replaceSchema(jsonSchema, description ? {...ref, description} : ref);diff --git a/packages/openapi/src/converters/__tests__/ZodToOpenAPI.test.ts b/packages/openapi/src/converters/__tests__/ZodToOpenAPI.test.tsindex d143095b1..9f2263588 100644--- a/packages/openapi/src/converters/__tests__/ZodToOpenAPI.test.ts+++ b/packages/openapi/src/converters/__tests__/ZodToOpenAPI.test.ts@@ -82,6 +82,20 @@ describe('native Zod conversion', () => {});});+ it('drops the inlined expansion beside a reference for OpenAPI 3.0', () => {+ const child = z.union([z.string(), z.number()]).describe('Shared value');+ const converter = new ZodOpenAPIConverter('openapi-3.0');+ converter.register('Child', child);+ converter.getRef('Parent', z.object({child: child.describe('Field value')}), 'input');+ const document = documentFor(converter);+ document.openapi = '3.0.3';+ converter.normalizeComponents(document);+ expect(document.components.schemas.Parent.properties?.child).toEqual({+ description: 'Field value',+ allOf: [{$ref: '#/components/schemas/Child'}],+ });+ });+it.each(['openapi-3.0', 'draft-2020-12'] as const)('converts binary archive responses for %s', (target) => {const converter = new ZodOpenAPIConverter(target);const schema = converter.getSchema('HarvestArchiveResponse', HarvestArchiveResponse, 'output');diff --git a/packages/openapi/src/extractors/RouteExtractor.ts b/packages/openapi/src/extractors/RouteExtractor.tsindex 1d0ffb34f..17f939f2a 100644--- a/packages/openapi/src/extractors/RouteExtractor.ts+++ b/packages/openapi/src/extractors/RouteExtractor.ts@@ -1,6 +1,7 @@// SPDX-License-Identifier: AGPL-3.0-or-laterimport {EMPTY_SCOPE,+ getIdentifierDeclarations,type Scope,StaticPathResolver,type StaticValue,@@ -21,8 +22,40 @@ import {Project,type SourceFile,} from 'ts-morph';+import {z} from 'zod';const HTTP_METHODS: ReadonlySet<string> = new Set(['get', 'post', 'put', 'patch', 'delete']);+const SCHEMA_METADATA_FIELDS: ReadonlySet<string> = new Set(['responseSchema', 'requestSchema', 'requestFormSchema']);+const MetadataStringList = z+ .union([z.string(), z.array(z.string())])+ .transform((value) => (typeof value === 'string' ? [value] : value));+const MetadataStatusCode = z.int().min(100).max(599);+const MetadataSecurityScheme = z.enum(['botToken', 'oauth2Token', 'bearerToken', 'sessionToken', 'adminApiKey']);+const RouteMetadata = z.strictObject({+ operationId: z.string().regex(/^[a-z][a-z0-9_]*$/),+ summary: z.string().min(1),+ description: z.string(),+ responseSchema: z.string().min(1).nullable(),+ responseContentType: z.string().optional(),+ requestSchema: z.string().min(1).optional(),+ requestFormSchema: z.string().min(1).optional(),+ requestBodyRequired: z.boolean().optional(),+ statusCode: z+ .union([MetadataStatusCode, z.array(MetadataStatusCode)])+ .transform((value) => (typeof value === 'number' ? [value] : value))+ .optional(),+ bodylessStatusCodes: z.array(MetadataStatusCode).optional(),+ security: z+ .union([MetadataSecurityScheme, z.array(MetadataSecurityScheme)])+ .transform((value) => (typeof value === 'string' ? [value] : value))+ .optional(),+ tags: MetadataStringList,+ deprecated: z.boolean().optional(),+ externalDocs: z.strictObject({url: z.string(), description: z.string().optional()}).optional(),+});+const RouteOptionsMetadata = RouteMetadata.pick({description: true, responseContentType: true}).extend({+ description: z.string().min(1),+});function isHttpMethod(method: string): method is HttpMethod {return HTTP_METHODS.has(method);}@@ -38,25 +71,8 @@ function extractStringLiteral(node: Node): string | null {}return null;}-function extractNumberArray(value: unknown): Array<number> | null {- if (typeof value === 'number') return [value];- if (Array.isArray(value)) {- if (!value.every((entry): entry is number => typeof entry === 'number')) {- throw new Error('OpenAPI status-list metadata must contain only numbers');- }- return value;- }- return null;-}-function extractStringArray(value: unknown): Array<string> | null {- if (typeof value === 'string') return [value];- if (Array.isArray(value)) {- if (!value.every((entry): entry is string => typeof entry === 'string')) {- throw new Error('OpenAPI string-list metadata must contain only strings');- }- return value;- }- return null;+function isHttpStatusCode(value: unknown): value is number {+ return typeof value === 'number' && Number.isInteger(value) && value >= 100 && value <= 599;}function extractOAuth2ScopeArgs(args: ReadonlyArray<Node>): Array<string> | null {const scopes: Array<string> = [];@@ -73,70 +89,44 @@ interface MetadataContext {readonly resolver: StaticPathResolver;readonly scope: Scope;}-function resolveMetadataText(node: Node, context: MetadataContext): string | null {+function resolveMetadataValue(node: Node, context: MetadataContext): StaticValue {const value = context.resolver.resolve(node, context.scope);- return typeof value === 'string' ? value : null;+ if (value === UNRESOLVED) throw new Error(`Unresolved OpenAPI metadata expression: ${node.getText()}`);+ return value;}-function extractObjectLiteralValue(node: Node, context: MetadataContext): unknown {- if (Node.isStringLiteral(node) || Node.isNoSubstitutionTemplateLiteral(node)) {- return node.getLiteralValue();- }- if (Node.isTemplateExpression(node) || Node.isConditionalExpression(node)) {- return resolveMetadataText(node, context);- }- if (Node.isNumericLiteral(node)) {- return Number.parseFloat(node.getText());- }- if (Node.isTrueLiteral(node)) {- return true;- }- if (Node.isFalseLiteral(node)) {- return false;- }- if (Node.isNullLiteral(node)) {- return null;- }- if (Node.isIdentifier(node)) {- return node.getText();- }- if (Node.isPropertyAccessExpression(node)) {- return resolveMetadataText(node, context) ?? node.getText();- }- if (Node.isCallExpression(node)) {- return node.getText();- }- if (Node.isArrayLiteralExpression(node)) {- const values: Array<unknown> = [];- for (const element of node.getElements()) {- if (Node.isSpreadElement(element)) {- const spread = context.resolver.resolve(element.getExpression(), context.scope);- if (spread == null || spread === UNRESOLVED || !Array.isArray(spread)) {- values.push(null);- continue;- }- values.push(...spread);- continue;- }- values.push(extractObjectLiteralValue(element, context));- }- return values;- }- if (Node.isObjectLiteralExpression(node)) {- return parseObjectLiteralMetadata(node, context);- }- return null;+function extractSchemaName(node: Node, context: MetadataContext): string | null {+ const value = context.resolver.resolve(node, context.scope);+ if (value === null) return null;+ if (value === UNRESOLVED && Node.isIdentifier(node)) return node.getText();+ throw new Error(`OpenAPI schemas must use a named schema export: ${node.getText()}`);}function parseObjectLiteralMetadata(objLiteral: ObjectLiteralExpression,context: MetadataContext,): Record<string, unknown> {- const metadata: Record<string, unknown> = {};+ const metadata = new Map<string, unknown>();for (const property of objLiteral.getProperties()) {- if (!Node.isPropertyAssignment(property)) continue;- const initializer = property.getInitializer();- if (initializer) metadata[property.getName()] = extractObjectLiteralValue(initializer, context);+ if (!Node.isPropertyAssignment(property) && !Node.isShorthandPropertyAssignment(property)) {+ throw new Error(`Unsupported OpenAPI metadata property: ${property.getText()}`);+ }+ const name = context.resolver.resolvePropertyName(property.getNameNode(), context.scope);+ if (name === null) throw new Error(`Unresolved OpenAPI metadata key: ${property.getName()}`);+ if (+ Node.isPropertyAssignment(property) &&+ name === '__proto__' &&+ !Node.isComputedPropertyName(property.getNameNode())+ ) {+ throw new Error('OpenAPI metadata cannot set an object prototype');+ }+ const initializer = Node.isPropertyAssignment(property) ? property.getInitializerOrThrow() : property.getNameNode();+ metadata.set(+ name,+ SCHEMA_METADATA_FIELDS.has(name)+ ? extractSchemaName(initializer, context)+ : resolveMetadataValue(initializer, context),+ );}- return metadata;+ return Object.fromEntries(metadata);}function extractValidatorInfo(callExpr: CallExpression): ExtractedValidator | null {const expression = callExpr.getExpression();@@ -172,43 +162,43 @@ interface MiddlewareInfo {explicitDeprecated?: boolean;explicitExternalDocs?: OpenAPIExternalDocs;}-function metadataString(value: unknown): string | undefined {- return typeof value === 'string' ? value : undefined;-}-function extractExternalDocs(value: unknown): OpenAPIExternalDocs | undefined {- if (!value || typeof value !== 'object' || !('url' in value) || typeof value.url !== 'string') return undefined;- return {url: value.url, description: 'description' in value ? metadataString(value.description) : undefined};-}function extractOpenAPIMetadata(args: ReadonlyArray<Node>, context: MetadataContext): MiddlewareInfo {const [first, summary, responseSchema, options] = args;if (!first) throw new Error('OpenAPI requires route metadata');- const metadata = Node.isObjectLiteralExpression(first)+ if (options !== undefined && !Node.isObjectLiteralExpression(options)) {+ throw new Error(`OpenAPI options must be an object literal: ${options.getText()}`);+ }+ const value = Node.isObjectLiteralExpression(first)? parseObjectLiteralMetadata(first, context): {- ...(options && Node.isObjectLiteralExpression(options) ? parseObjectLiteralMetadata(options, context) : {}),- operationId: extractStringLiteral(first),- summary: summary ? extractStringLiteral(summary) : undefined,- responseSchema: responseSchema?.getText(),+ ...(options ? RouteOptionsMetadata.parse(parseObjectLiteralMetadata(options, context)) : {}),+ operationId: resolveMetadataValue(first, context),+ summary: summary ? resolveMetadataValue(summary, context) : undefined,+ responseSchema: responseSchema ? extractSchemaName(responseSchema, context) : undefined,+ tags: [],};- const schemaName = metadataString(metadata.responseSchema);+ const parsed = RouteMetadata.safeParse(value);+ if (!parsed.success) {+ throw new Error(`Invalid OpenAPI metadata at line ${first.getStartLineNumber()}`, {cause: parsed.error});+ }+ const metadata = parsed.data;return {middlewareName: 'OpenAPI',- responseSchemaName: schemaName,- hasNoContent: schemaName === undefined || schemaName === 'null',- bodylessStatusCodes: extractNumberArray(metadata.bodylessStatusCodes),- responseContentType: metadataString(metadata.responseContentType),- explicitRequestSchemaName: metadataString(metadata.requestSchema),- explicitRequestFormSchemaName: metadataString(metadata.requestFormSchema),- explicitRequestBodyRequired:- typeof metadata.requestBodyRequired === 'boolean' ? metadata.requestBodyRequired : undefined,- explicitSummary: metadataString(metadata.summary),- explicitOperationId: metadataString(metadata.operationId),- explicitDescription: metadataString(metadata.description),- explicitStatusCodes: extractNumberArray(metadata.statusCode),- explicitSecurity: extractStringArray(metadata.security),- explicitTags: extractStringArray(metadata.tags),- explicitDeprecated: metadata.deprecated === true,- explicitExternalDocs: extractExternalDocs(metadata.externalDocs),+ responseSchemaName: metadata.responseSchema ?? undefined,+ hasNoContent: metadata.responseSchema === null,+ bodylessStatusCodes: metadata.bodylessStatusCodes,+ responseContentType: metadata.responseContentType,+ explicitRequestSchemaName: metadata.requestSchema,+ explicitRequestFormSchemaName: metadata.requestFormSchema,+ explicitRequestBodyRequired: metadata.requestBodyRequired,+ explicitSummary: metadata.summary,+ explicitOperationId: metadata.operationId,+ explicitDescription: metadata.description,+ explicitStatusCodes: metadata.statusCode,+ explicitSecurity: metadata.security,+ explicitTags: metadata.tags,+ explicitDeprecated: metadata.deprecated,+ explicitExternalDocs: metadata.externalDocs,};}function extractMiddlewareInfo(callExpr: CallExpression, context: MetadataContext): MiddlewareInfo | null {@@ -251,8 +241,8 @@ function extractSuccessStatusCodes(handler: Node): Array<number> {if (args.length < 2) return;const statusArg = args[1];if (!Node.isNumericLiteral(statusArg)) return;- const parsed = Number.parseInt(statusArg.getText(), 10);- if (!Number.isFinite(parsed)) return;+ const parsed = statusArg.getLiteralValue();+ if (!isHttpStatusCode(parsed)) throw new Error(`Invalid HTTP response status: ${statusArg.getText()}`);if (parsed >= 200 && parsed <= 299) {codes.add(parsed);}@@ -293,43 +283,24 @@ function methodsFromOnArgument(node: Node, resolver: StaticPathResolver, scope:}return methods.length > 0 ? methods : null;}-const HONO_TYPE_PATTERN = /\bHono(App|Env)?\b/u;function isHonoReceiver(receiver: Node): boolean {- if (!Node.isIdentifier(receiver)) {- return false;- }- const name = receiver.getText();- for (const ancestor of receiver.getAncestors()) {- if (- Node.isFunctionDeclaration(ancestor) ||- Node.isArrowFunction(ancestor) ||- Node.isFunctionExpression(ancestor) ||- Node.isMethodDeclaration(ancestor)- ) {- for (const parameter of ancestor.getParameters()) {- const nameNode = parameter.getNameNode();- if (Node.isIdentifier(nameNode) && nameNode.getText() === name) {- return HONO_TYPE_PATTERN.test(parameter.getTypeNode()?.getText() ?? '');- }- }- }- if (Node.isBlock(ancestor) || Node.isSourceFile(ancestor)) {- for (const statement of ancestor.getStatements()) {- if (!Node.isVariableStatement(statement)) {- continue;- }- for (const declaration of statement.getDeclarations()) {- const nameNode = declaration.getNameNode();- if (Node.isIdentifier(nameNode) && nameNode.getText() === name) {- const annotation = declaration.getTypeNode()?.getText() ?? '';- const initializer = declaration.getInitializer()?.getText() ?? '';- return HONO_TYPE_PATTERN.test(`${annotation} ${initializer}`);- }- }- }- }- }- return false;+ if (!Node.isIdentifier(receiver)) return false;+ const declarations = getIdentifierDeclarations(receiver);+ if (declarations.length !== 1) return false;+ const declaration = declarations[0];+ if (!Node.isParameterDeclaration(declaration) && !Node.isVariableDeclaration(declaration)) return false;+ const typeNode = declaration.getTypeNode();+ if (typeNode !== undefined && Node.isTypeReference(typeNode)) {+ const typeName = typeNode.getTypeName();+ if (Node.isIdentifier(typeName) && (typeName.getText() === 'HonoApp' || typeName.getText() === 'Hono')) {+ return true;+ }+ }+ if (!Node.isVariableDeclaration(declaration)) return false;+ const initializer = declaration.getInitializer();+ if (initializer === undefined || !Node.isNewExpression(initializer)) return false;+ const constructorExpression = initializer.getExpression();+ return Node.isIdentifier(constructorExpression) && constructorExpression.getText() === 'Hono';}function isRegistrationCall(callExpr: CallExpression): boolean {const expression = callExpr.getExpression();@@ -498,8 +469,14 @@ function bindParameters(callerScope: Scope,resolver: StaticPathResolver,): Scope {- const scope = new Map<string, StaticValue>();+ const scope = new Map(callerScope);+ for (const declaration of scope.keys()) {+ if (declaration.getAncestors().includes(fn)) scope.delete(declaration);+ }+ const firstSpreadIndex = args.findIndex(Node.isSpreadElement);fn.getParameters().forEach((parameter, index) => {+ if (parameter.isRestParameter()) return;+ if (firstSpreadIndex !== -1 && index >= firstSpreadIndex) return;const arg = args[index];if (arg == null) {return;@@ -510,15 +487,16 @@ function bindParameters(}const nameNode = parameter.getNameNode();if (Node.isIdentifier(nameNode)) {- scope.set(nameNode.getText(), value);+ scope.set(parameter, value);return;}if (Node.isObjectBindingPattern(nameNode) && typeof value === 'object' && value !== null && !Array.isArray(value)) {const record = value as {readonly [key: string]: StaticValue};for (const element of nameNode.getElements()) {- const key = element.getPropertyNameNode()?.getText() ?? element.getName();- if (key in record) {- scope.set(element.getName(), record[key]);+ if (element.getDotDotDotToken() !== undefined) continue;+ const key = resolver.resolvePropertyName(element.getPropertyNameNode() ?? element.getNameNode(), scope);+ if (key !== null && Object.hasOwn(record, key)) {+ scope.set(element, record[key]);}}}@@ -531,11 +509,7 @@ function scopesForFunction(resolver: StaticPathResolver,visiting: Set<FunctionDeclaration>,): Array<Scope> {- if (visiting.has(fn)) {- return [EMPTY_SCOPE];- }- const name = fn.getName();- if (name == null) {+ if (visiting.has(fn) || fn.getName() === undefined) {return [EMPTY_SCOPE];}visiting.add(fn);@@ -546,7 +520,7 @@ function scopesForFunction(return;}const callee = node.getExpression();- if (!Node.isIdentifier(callee) || callee.getText() !== name) {+ if (!Node.isIdentifier(callee) || !getIdentifierDeclarations(callee).includes(fn)) {return;}const enclosing = owningFunction(node);@@ -586,7 +560,7 @@ function expandLoops(continue;}const initializer = loop.getInitializer();- if (!Node.isVariableDeclarationList(initializer)) {+ if (!Node.isVariableDeclarationList(initializer) || initializer.getDeclarationKind() !== 'const') {return scopes;}const declaration = initializer.getDeclarations()[0];@@ -602,7 +576,7 @@ function expandLoops(}for (const element of iterated) {const next = new Map(scope);- next.set(nameNode.getText(), element);+ next.set(declaration, element);expanded.push(next);}}@@ -678,17 +652,18 @@ export function extractRoutesFromControllers(controllerPaths: Array<string>): Arconst project = new Project({skipAddingFilesFromTsConfig: true,skipFileDependencyResolution: true,+ compilerOptions: {noResolve: true, noLib: true, types: []},});const resolver = new StaticPathResolver(project);const routes: Array<ExtractedRoute> = [];const unresolved: Array<UnresolvedRegistration> = [];- for (const controllerPath of controllerPaths) {+ const sourceFiles = controllerPaths.map((controllerPath) => project.addSourceFileAtPath(controllerPath));+ for (const sourceFile of sourceFiles) {try {- const sourceFile = project.addSourceFileAtPath(controllerPath);const fileRoutes = findRoutesInSourceFile(sourceFile, resolver, unresolved);routes.push(...fileRoutes);} catch (error) {- throw new Error(`Could not extract routes from ${controllerPath}`, {cause: error});+ throw new Error(`Could not extract routes from ${sourceFile.getFilePath()}`, {cause: error});}}if (unresolved.length > 0) {diff --git a/packages/openapi/src/extractors/StaticPathResolver.ts b/packages/openapi/src/extractors/StaticPathResolver.tsindex c2718cf2a..88c794ff6 100644--- a/packages/openapi/src/extractors/StaticPathResolver.ts+++ b/packages/openapi/src/extractors/StaticPathResolver.ts@@ -4,26 +4,28 @@ import {type BinaryExpression, type Identifier, Node, type Project, type SourceFexport const UNRESOLVED = Symbol('unresolved');+type StaticPrimitive = string | number | boolean | null;+export type StaticValue =- | string- | number- | boolean- | null+ | StaticPrimitive| ReadonlyArray<StaticValue>- | {readonly [key: string]: StaticValue};--type Resolved = StaticValue | typeof UNRESOLVED;+ | {readonly [key: string]: StaticValue}+ | typeof UNRESOLVED;-export type Scope = ReadonlyMap<string, StaticValue>;+export type Scope = ReadonlyMap<Node, StaticValue>;-export const EMPTY_SCOPE: Scope = new Map<string, StaticValue>();+export const EMPTY_SCOPE: Scope = new Map<Node, StaticValue>();const MAX_DEPTH = 48;-function isPlainObject(value: Resolved): value is {readonly [key: string]: StaticValue} {+function isPlainObject(value: StaticValue): value is {readonly [key: string]: StaticValue} {return typeof value === 'object' && value !== null && !Array.isArray(value);}+function isPrimitive(value: StaticValue): value is StaticPrimitive {+ return value === null || typeof value === 'string' || typeof value === 'number' || typeof value === 'boolean';+}+function unwrap(node: Node): Node {let current = node;while (@@ -38,13 +40,21 @@ function unwrap(node: Node): Node {return current;}+export function getIdentifierDeclarations(node: Identifier): ReadonlyArray<Node> {+ const parent = node.getParent();+ const symbol =+ Node.isShorthandPropertyAssignment(parent) && parent.getNameNode() === node+ ? parent.getValueSymbol()+ : node.getSymbol();+ return symbol?.getDeclarations() ?? [];+}+export class StaticPathResolver {- private readonly moduleConstants = new Map<SourceFile, Map<string, Node>>();private readonly inFlight = new Set<Node>();constructor(private readonly project: Project) {}- public resolve(node: Node, scope: Scope): Resolved {+ public resolve(node: Node, scope: Scope): StaticValue {return this.evaluate(node, scope, 0);}@@ -53,7 +63,19 @@ export class StaticPathResolver {return typeof value === 'string' ? value : null;}- private evaluate(rawNode: Node, scope: Scope, depth: number): Resolved {+ public resolvePropertyName(node: Node, scope: Scope): string | null {+ const name = this.evaluatePropertyName(node, scope, 0);+ return name === UNRESOLVED ? null : name;+ }++ private evaluatePropertyName(node: Node, scope: Scope, depth: number): string | typeof UNRESOLVED {+ if (Node.isIdentifier(node)) return node.getText();+ const expression = Node.isComputedPropertyName(node) ? node.getExpression() : node;+ const value = this.evaluate(expression, scope, depth + 1);+ return isPrimitive(value) ? String(value) : UNRESOLVED;+ }++ private evaluate(rawNode: Node, scope: Scope, depth: number): StaticValue {if (depth > MAX_DEPTH) {return UNRESOLVED;}@@ -77,7 +99,7 @@ export class StaticPathResolver {let text = node.getHead().getLiteralText();for (const span of node.getTemplateSpans()) {const value = this.evaluate(span.getExpression(), scope, depth + 1);- if (value === UNRESOLVED || Array.isArray(value) || isPlainObject(value)) {+ if (!isPrimitive(value)) {return UNRESOLVED;}text += String(value);@@ -94,7 +116,7 @@ export class StaticPathResolver {return UNRESOLVED;}const name = node.getName();- return name in target ? target[name] : UNRESOLVED;+ return Object.hasOwn(target, name) ? target[name] : UNRESOLVED;}if (Node.isElementAccessExpression(node)) {const target = this.evaluate(node.getExpression(), scope, depth + 1);@@ -113,50 +135,45 @@ export class StaticPathResolver {}if (isPlainObject(target)) {const name = String(key);- return name in target ? target[name] : UNRESOLVED;+ return Object.hasOwn(target, name) ? target[name] : UNRESOLVED;}return UNRESOLVED;}if (Node.isArrayLiteralExpression(node)) {const values: Array<StaticValue> = [];for (const element of node.getElements()) {- if (Node.isSpreadElement(element)) {- return UNRESOLVED;- }- const value = this.evaluate(element, scope, depth + 1);+ const value = this.evaluate(+ Node.isSpreadElement(element) ? element.getExpression() : element,+ scope,+ depth + 1,+ );if (value === UNRESOLVED) {return UNRESOLVED;}- values.push(value);+ if (Node.isSpreadElement(element)) {+ if (!Array.isArray(value)) return UNRESOLVED;+ values.push(...value);+ } else {+ values.push(value);+ }}return values;}if (Node.isObjectLiteralExpression(node)) {- const result: Record<string, StaticValue> = {};+ const properties = new Map<string, StaticValue>();for (const property of node.getProperties()) {- if (Node.isPropertyAssignment(property)) {- const initializer = property.getInitializer();- if (initializer == null) {- return UNRESOLVED;- }- const value = this.evaluate(initializer, scope, depth + 1);- if (value === UNRESOLVED) {- continue;- }- result[property.getName()] = value;- continue;- }- if (Node.isShorthandPropertyAssignment(property)) {- const value = this.evaluate(property.getNameNode(), scope, depth + 1);- if (value === UNRESOLVED) {- continue;- }- result[property.getName()] = value;- continue;+ if (!Node.isPropertyAssignment(property) && !Node.isShorthandPropertyAssignment(property)) return UNRESOLVED;+ const nameNode = property.getNameNode();+ const name = this.evaluatePropertyName(nameNode, scope, depth + 1);+ if (name === UNRESOLVED) return UNRESOLVED;+ if (Node.isPropertyAssignment(property) && name === '__proto__' && !Node.isComputedPropertyName(nameNode)) {+ return UNRESOLVED;}- return UNRESOLVED;+ const initializer = Node.isPropertyAssignment(property) ? property.getInitializer() : nameNode;+ if (initializer === undefined) return UNRESOLVED;+ properties.set(name, this.evaluate(initializer, scope, depth + 1));}- return result;+ return Object.fromEntries(properties);}if (Node.isConditionalExpression(node)) {const condition = this.evaluate(node.getCondition(), scope, depth + 1);@@ -178,7 +195,7 @@ export class StaticPathResolver {return UNRESOLVED;}- private evaluateBinary(node: BinaryExpression, scope: Scope, depth: number): Resolved {+ private evaluateBinary(node: BinaryExpression, scope: Scope, depth: number): StaticValue {const operator = node.getOperatorToken().getText();const left = this.evaluate(node.getLeft(), scope, depth + 1);if (left === UNRESOLVED) {@@ -197,86 +214,53 @@ export class StaticPathResolver {if (right === UNRESOLVED) {return UNRESOLVED;}- if (operator === '+') {- if (typeof left === 'string' && (typeof right === 'string' || typeof right === 'number')) {- return left + String(right);- }- if (typeof left === 'number' && typeof right === 'number') {- return left + right;+ if (!isPrimitive(left) || !isPrimitive(right)) return UNRESOLVED;+ switch (operator) {+ case '+':+ return typeof left === 'string' || typeof right === 'string'+ ? String(left) + String(right)+ : Number(left) + Number(right);+ case '===':+ return left === right;+ case '!==':+ return left !== right;+ case '==':+ case '!=': {+ const equal =+ typeof left === typeof right || left === null || right === null+ ? left === right+ : Number(left) === Number(right);+ return operator === '==' ? equal : !equal;}- return UNRESOLVED;- }- const comparable =- (typeof left === 'string' || typeof left === 'number' || typeof left === 'boolean' || left === null) &&- (typeof right === 'string' || typeof right === 'number' || typeof right === 'boolean' || right === null);- if (!comparable) {- return UNRESOLVED;- }- if (operator === '===' || operator === '==') {- return left === right;- }- if (operator === '!==' || operator === '!=') {- return left !== right;- }- return UNRESOLVED;- }-- private evaluateIdentifier(node: Identifier, scope: Scope, depth: number): Resolved {- const name = node.getText();- if (name === 'undefined') {- return UNRESOLVED;- }- const bound = scope.get(name);- if (bound !== undefined) {- return bound;- }- const local = this.findBindingInScopeChain(node, name);- if (local != null) {- return this.evaluateBinding(local, scope, depth);+ default:+ return UNRESOLVED;}- return this.evaluateImportedConstant(node.getSourceFile(), name, depth);}- private findBindingInScopeChain(from: Node, name: string): Node | null {- for (const ancestor of from.getAncestors()) {- if (!Node.isBlock(ancestor) && !Node.isSourceFile(ancestor) && !Node.isCaseClause(ancestor)) {- continue;- }- for (const statement of ancestor.getStatements()) {- if (!Node.isVariableStatement(statement)) {- continue;- }- if (statement.getDeclarationKind() !== 'const') {- continue;- }- for (const declaration of statement.getDeclarations()) {- const nameNode = declaration.getNameNode();- if (Node.isIdentifier(nameNode)) {- if (nameNode.getText() === name) {- return declaration;- }- continue;- }- if (Node.isObjectBindingPattern(nameNode) || Node.isArrayBindingPattern(nameNode)) {- for (const element of nameNode.getElements()) {- if (Node.isBindingElement(element) && element.getName() === name) {- return element;- }- }- }- }- }- }- return null;+ private evaluateIdentifier(node: Identifier, scope: Scope, depth: number): StaticValue {+ const declarations = getIdentifierDeclarations(node);+ if (declarations.length !== 1) return UNRESOLVED;+ const declaration = declarations[0];+ const bound = scope.get(declaration);+ if (bound !== undefined) return bound;+ if (Node.isImportSpecifier(declaration)) {+ if (declaration.isTypeOnly() || declaration.getImportDeclaration().isTypeOnly()) return UNRESOLVED;+ return this.evaluateImportedConstant(node.getSourceFile(), node.getText(), depth);+ }+ return this.evaluateBinding(declaration, scope, depth);}- private evaluateBinding(binding: Node, scope: Scope, depth: number): Resolved {+ private evaluateBinding(binding: Node, scope: Scope, depth: number): StaticValue {if (this.inFlight.has(binding)) {return UNRESOLVED;}this.inFlight.add(binding);try {if (Node.isVariableDeclaration(binding)) {+ const declarationList = binding.getParent();+ if (!Node.isVariableDeclarationList(declarationList) || declarationList.getDeclarationKind() !== 'const') {+ return UNRESOLVED;+ }const initializer = binding.getInitializer();return initializer == null ? UNRESOLVED : this.evaluate(initializer, scope, depth + 1);}@@ -291,6 +275,10 @@ export class StaticPathResolver {if (!Node.isVariableDeclaration(declaration)) {return UNRESOLVED;}+ const declarationList = declaration.getParent();+ if (!Node.isVariableDeclarationList(declarationList) || declarationList.getDeclarationKind() !== 'const') {+ return UNRESOLVED;+ }const initializer = declaration.getInitializer();if (initializer == null) {return UNRESOLVED;@@ -303,8 +291,8 @@ export class StaticPathResolver {if (!isPlainObject(source)) {return UNRESOLVED;}- const key = binding.getPropertyNameNode()?.getText() ?? binding.getName();- return key in source ? source[key] : UNRESOLVED;+ const key = this.evaluatePropertyName(binding.getPropertyNameNode() ?? binding.getNameNode(), scope, depth + 1);+ return key !== UNRESOLVED && Object.hasOwn(source, key) ? source[key] : UNRESOLVED;}if (Node.isArrayBindingPattern(pattern)) {if (!Array.isArray(source)) {@@ -319,17 +307,15 @@ export class StaticPathResolver {}}- private evaluateImportedConstant(sourceFile: SourceFile, name: string, depth: number): Resolved {+ private evaluateImportedConstant(sourceFile: SourceFile, name: string, depth: number): StaticValue {const target = this.resolveImportTarget(sourceFile, name);if (target == null) {return UNRESOLVED;}- const constants = this.constantsOf(target.sourceFile);- const initializer = constants.get(target.exportedName);- if (initializer == null) {- return UNRESOLVED;- }- return this.evaluate(initializer, EMPTY_SCOPE, depth + 1);+ const exported = target.sourceFile.getExportSymbols().find((symbol) => symbol.getName() === target.exportedName);+ const declarations = (exported?.getAliasedSymbol() ?? exported)?.getDeclarations();+ if (declarations?.length !== 1) return UNRESOLVED;+ return this.evaluateBinding(declarations[0], EMPTY_SCOPE, depth + 1);}private resolveImportTarget(@@ -369,26 +355,4 @@ export class StaticPathResolver {}return null;}-- private constantsOf(sourceFile: SourceFile): Map<string, Node> {- const cached = this.moduleConstants.get(sourceFile);- if (cached != null) {- return cached;- }- const constants = new Map<string, Node>();- for (const statement of sourceFile.getVariableStatements()) {- if (statement.getDeclarationKind() !== 'const') {- continue;- }- for (const declaration of statement.getDeclarations()) {- const nameNode = declaration.getNameNode();- const initializer = declaration.getInitializer();- if (Node.isIdentifier(nameNode) && initializer != null) {- constants.set(nameNode.getText(), initializer);- }- }- }- this.moduleConstants.set(sourceFile, constants);- return constants;- }}diff --git a/packages/openapi/src/registry/SchemaRegistry.ts b/packages/openapi/src/registry/SchemaRegistry.tsindex 1e35eecdf..0d9a622bb 100644--- a/packages/openapi/src/registry/SchemaRegistry.ts+++ b/packages/openapi/src/registry/SchemaRegistry.ts@@ -1,6 +1,7 @@// SPDX-License-Identifier: AGPL-3.0-or-laterimport {isDeepStrictEqual} from 'node:util';import {type SchemaIO, ZodOpenAPIConverter} from '@fluxer/openapi/src/converters/ZodToOpenAPI';+import {createOpenAPIComponentRef, validateOpenAPIComponentName} from '@fluxer/openapi/src/OpenAPIComponentRef';import type {OpenAPISchemaTarget} from '@fluxer/openapi/src/OpenAPIGenerationTypes';import type {OpenAPIDocument, OpenAPIRef, OpenAPISchema} from '@fluxer/openapi/src/OpenAPITypes';import {core} from 'zod';@@ -16,6 +17,7 @@ export class SchemaRegistry {}register(name: string, schema: OpenAPISchema): void {+ validateOpenAPIComponentName(name);if (this.zodSchemas.has(name)) throw new Error(`OpenAPI schema also has a Zod definition: ${name}`);const existing = this.schemas.get(name);if (existing && !isDeepStrictEqual(existing, schema)) throw new Error(`Conflicting OpenAPI schemas: ${name}`);@@ -23,6 +25,7 @@ export class SchemaRegistry {}registerZod(name: string, schema: core.$ZodType): void {+ validateOpenAPIComponentName(name);if (this.schemas.has(name)) throw new Error(`Zod schema also has an OpenAPI definition: ${name}`);const existing = this.zodSchemas.get(name);if (existing && existing !== schema) throw new Error(`Duplicate Zod schema export: ${name}`);@@ -34,7 +37,7 @@ export class SchemaRegistry {const schema = this.zodSchemas.get(name);if (schema) return this.converter.getRef(name, schema, io);if (!this.schemas.has(name)) throw new Error(`Unknown OpenAPI schema: ${name}`);- return {$ref: `#/components/schemas/${name}`};+ return createOpenAPIComponentRef(name);}get(name: string, io: SchemaIO = 'input'): OpenAPISchema | undefined {@@ -43,7 +46,7 @@ export class SchemaRegistry {}get size(): number {- return new Set([...this.schemas.keys(), ...this.zodSchemas.keys()]).size;+ return this.schemas.size + this.zodSchemas.size;}acceptsEmptyObject(name: string): boolean {diff --git a/packages/schema/src/domains/admin/AdminSchemas.ts b/packages/schema/src/domains/admin/AdminSchemas.tsindex 5dcab9a2a..2ad8e84df 100644--- a/packages/schema/src/domains/admin/AdminSchemas.ts+++ b/packages/schema/src/domains/admin/AdminSchemas.ts@@ -413,6 +413,8 @@ export const GenerateGiftCodesRequest = z.object({export type GenerateGiftCodesRequest = z.infer<typeof GenerateGiftCodesRequest>;+const SsoAllowedDomainsSchema = z.array(z.string()).max(100);+const SsoConfigResponse = z.object({enabled: z.boolean(),enforced: z.boolean(),@@ -425,7 +427,7 @@ const SsoConfigResponse = z.object({client_id: z.string().nullable(),client_secret_set: z.boolean(),scope: z.string().nullable(),- allowed_domains: z.array(z.string()).max(100),+ allowed_domains: SsoAllowedDomainsSchema,auto_provision: z.boolean(),redirect_uri: z.string().nullable(),});@@ -448,6 +450,7 @@ const RegistrationUrlResponse = z.object({last_used_at: z.iso.datetime().nullable(),last_used_by_user_id: SnowflakeStringType.nullable(),});+export type RegistrationUrlResponse = z.infer<typeof RegistrationUrlResponse>;const PendingRegistrationResponse = z.object({user_id: SnowflakeStringType,@@ -459,6 +462,7 @@ const PendingRegistrationResponse = z.object({registration_url_id: createStringType(1, 128).nullable(),client_ip: z.string().nullable(),});+export type PendingRegistrationResponse = z.infer<typeof PendingRegistrationResponse>;const InstanceRegistrationResponse = InstanceRegistrationConfigResponse.extend({urls: z.array(RegistrationUrlResponse),@@ -636,6 +640,28 @@ export const InstanceConfigResponse = z.object({export type InstanceConfigResponse = z.infer<typeof InstanceConfigResponse>;+const InstancePolicyUpdateSchema = z.object({+ single_community_enabled: z.boolean().optional(),+ single_community_name: z.string().trim().min(1).max(100).optional(),+ direct_messages_disabled: z.boolean().optional(),+ direct_messages_locked: z.literal(false).optional(),+ premium_mode: z.enum(['mirror', 'everyone']).optional(),+ services: z+ .object({+ gif_enabled: z.boolean().nullish(),+ youtube_enabled: z.boolean().nullish(),+ bluesky_enabled: z.boolean().nullish(),+ })+ .nullish(),+ deferred_phone_gate: z+ .object({+ enabled: z.boolean().optional(),+ window_hours: z.number().positive().max(8760).optional(),+ member_threshold: z.number().int().positive().max(1_000_000).optional(),+ })+ .nullish(),+});+export const InstanceConfigUpdateRequest = z.object({gateway_rollout: GatewayRolloutConfigUpdateRequest.nullish(),voice_noise_suppression: VoiceNoiseSuppressionConfigUpdateRequest.nullish(),@@ -659,7 +685,7 @@ export const InstanceConfigUpdateRequest = z.object({client_id: z.string().nullish(),client_secret: z.string().nullish(),scope: z.string().nullish(),- allowed_domains: z.array(z.string()).max(100).optional(),+ allowed_domains: SsoAllowedDomainsSchema.optional(),auto_provision: z.boolean().optional(),}).nullish(),@@ -741,29 +767,7 @@ export const InstanceConfigUpdateRequest = z.object({.nullish(),}).nullish(),- policy: z- .object({- single_community_enabled: z.boolean().optional(),- single_community_name: z.string().trim().min(1).max(100).optional(),- direct_messages_disabled: z.boolean().optional(),- direct_messages_locked: z.literal(false).optional(),- premium_mode: z.enum(['mirror', 'everyone']).optional(),- services: z- .object({- gif_enabled: z.boolean().nullish(),- youtube_enabled: z.boolean().nullish(),- bluesky_enabled: z.boolean().nullish(),- })- .nullish(),- deferred_phone_gate: z- .object({- enabled: z.boolean().optional(),- window_hours: z.number().positive().max(8760).optional(),- member_threshold: z.number().int().positive().max(1_000_000).optional(),- })- .nullish(),- })- .nullish(),+ policy: InstancePolicyUpdateSchema.nullish(),});export type InstanceConfigUpdateRequest = z.infer<typeof InstanceConfigUpdateRequest>;diff --git a/packages/schema/src/domains/admin/GatewayRolloutSchemas.ts b/packages/schema/src/domains/admin/GatewayRolloutSchemas.tsindex a4a9ab1af..99162bcbe 100644--- a/packages/schema/src/domains/admin/GatewayRolloutSchemas.ts+++ b/packages/schema/src/domains/admin/GatewayRolloutSchemas.ts@@ -6,31 +6,33 @@ const GatewayRolloutModeEnum = z.enum(['modulo', 'random']);const VoiceE2EEScopeEnum = z.enum(['guild_feature_only', 'platform_wide']);+const gatewayRolloutFields = {+ session_rollout_percentage: z.number().min(0).max(100),+ session_rollout_mode: GatewayRolloutModeEnum,+ guild_rollout_percentage: z.number().min(0).max(100),+ rpc_request_timeout_ms: z.number().int().min(1000).max(60000),+ max_concurrent_session_starts: z.number().int().min(1).max(10000),+ max_concurrent_guild_starts: z.number().int().min(1).max(10000),+ gateway_dispatch_relay_shards: z.number().int().min(1).max(10000),+ gateway_dispatch_relay_max_queue: z.number().int().min(0).max(1000000),+ voice_e2ee_scope: VoiceE2EEScopeEnum,+};+export const GatewayRolloutConfigSchema = z.object({- session_rollout_percentage: z.number().min(0).max(100).default(100),- session_rollout_mode: GatewayRolloutModeEnum.default('modulo'),- guild_rollout_percentage: z.number().min(0).max(100).default(100),- rpc_request_timeout_ms: z.number().int().min(1000).max(60000).default(10000),- max_concurrent_session_starts: z.number().int().min(1).max(10000).default(512),- max_concurrent_guild_starts: z.number().int().min(1).max(10000).default(256),- gateway_dispatch_relay_shards: z.number().int().min(1).max(10000).default(32),- gateway_dispatch_relay_max_queue: z.number().int().min(0).max(1000000).default(50000),- voice_e2ee_scope: VoiceE2EEScopeEnum.default('guild_feature_only'),+ session_rollout_percentage: gatewayRolloutFields.session_rollout_percentage.default(100),+ session_rollout_mode: gatewayRolloutFields.session_rollout_mode.default('modulo'),+ guild_rollout_percentage: gatewayRolloutFields.guild_rollout_percentage.default(100),+ rpc_request_timeout_ms: gatewayRolloutFields.rpc_request_timeout_ms.default(10000),+ max_concurrent_session_starts: gatewayRolloutFields.max_concurrent_session_starts.default(512),+ max_concurrent_guild_starts: gatewayRolloutFields.max_concurrent_guild_starts.default(256),+ gateway_dispatch_relay_shards: gatewayRolloutFields.gateway_dispatch_relay_shards.default(32),+ gateway_dispatch_relay_max_queue: gatewayRolloutFields.gateway_dispatch_relay_max_queue.default(50000),+ voice_e2ee_scope: gatewayRolloutFields.voice_e2ee_scope.default('guild_feature_only'),});export type GatewayRolloutConfig = z.infer<typeof GatewayRolloutConfigSchema>;-export const GatewayRolloutConfigUpdateRequest = z.object({- session_rollout_percentage: z.number().min(0).max(100).optional(),- session_rollout_mode: GatewayRolloutModeEnum.optional(),- guild_rollout_percentage: z.number().min(0).max(100).optional(),- rpc_request_timeout_ms: z.number().int().min(1000).max(60000).optional(),- max_concurrent_session_starts: z.number().int().min(1).max(10000).optional(),- max_concurrent_guild_starts: z.number().int().min(1).max(10000).optional(),- gateway_dispatch_relay_shards: z.number().int().min(1).max(10000).optional(),- gateway_dispatch_relay_max_queue: z.number().int().min(0).max(1000000).optional(),- voice_e2ee_scope: VoiceE2EEScopeEnum.optional(),-});+export const GatewayRolloutConfigUpdateRequest = z.object(gatewayRolloutFields).partial();export type GatewayRolloutConfigUpdateRequest = z.infer<typeof GatewayRolloutConfigUpdateRequest>;diff --git a/packages/schema/src/domains/instance/InstanceSchemas.ts b/packages/schema/src/domains/instance/InstanceSchemas.tsindex 7a80c7a14..f3f88a825 100644--- a/packages/schema/src/domains/instance/InstanceSchemas.ts+++ b/packages/schema/src/domains/instance/InstanceSchemas.ts@@ -128,7 +128,6 @@ export const InstanceRegistrationModeSchema = createNamedStringLiteralUnion(],'Registration mode',);-export type InstanceRegistrationMode = z.infer<typeof InstanceRegistrationModeSchema>;export const InstanceRegistrationSchema = z.object({diff --git a/packages/schema/src/primitives/AuditLogValidators.ts b/packages/schema/src/primitives/AuditLogValidators.tsindex 3eab2eb44..18b059174 100644--- a/packages/schema/src/primitives/AuditLogValidators.ts+++ b/packages/schema/src/primitives/AuditLogValidators.ts@@ -1,49 +1,46 @@// SPDX-License-Identifier: AGPL-3.0-or-laterimport {AuditLogActionType} from '@fluxer/constants/src/AuditLogActionType';-import {createInt32EnumType, withOpenApiType} from '@fluxer/schema/src/primitives/SchemaPrimitives';+import {createInt32EnumType} from '@fluxer/schema/src/primitives/SchemaPrimitives';-export const AuditLogActionTypeSchema = withOpenApiType(- createInt32EnumType(- [- [AuditLogActionType.GUILD_UPDATE, 'GUILD_UPDATE', 'Guild settings were updated'],- [AuditLogActionType.CHANNEL_CREATE, 'CHANNEL_CREATE', 'Channel was created'],- [AuditLogActionType.CHANNEL_UPDATE, 'CHANNEL_UPDATE', 'Channel was updated'],- [AuditLogActionType.CHANNEL_DELETE, 'CHANNEL_DELETE', 'Channel was deleted'],- [AuditLogActionType.CHANNEL_OVERWRITE_CREATE, 'CHANNEL_OVERWRITE_CREATE', 'Permission overwrite was created'],- [AuditLogActionType.CHANNEL_OVERWRITE_UPDATE, 'CHANNEL_OVERWRITE_UPDATE', 'Permission overwrite was updated'],- [AuditLogActionType.CHANNEL_OVERWRITE_DELETE, 'CHANNEL_OVERWRITE_DELETE', 'Permission overwrite was deleted'],- [AuditLogActionType.MEMBER_KICK, 'MEMBER_KICK', 'Member was kicked'],- [AuditLogActionType.MEMBER_PRUNE, 'MEMBER_PRUNE', 'Members were pruned'],- [AuditLogActionType.MEMBER_BAN_ADD, 'MEMBER_BAN_ADD', 'Member was banned'],- [AuditLogActionType.MEMBER_BAN_REMOVE, 'MEMBER_BAN_REMOVE', 'Member ban was removed'],- [AuditLogActionType.MEMBER_UPDATE, 'MEMBER_UPDATE', 'Member was updated'],- [AuditLogActionType.MEMBER_ROLE_UPDATE, 'MEMBER_ROLE_UPDATE', 'Member roles were updated'],- [AuditLogActionType.MEMBER_MOVE, 'MEMBER_MOVE', 'Member was moved to a different voice channel'],- [AuditLogActionType.MEMBER_DISCONNECT, 'MEMBER_DISCONNECT', 'Member was disconnected from a voice channel'],- [AuditLogActionType.BOT_ADD, 'BOT_ADD', 'Bot was added to the guild'],- [AuditLogActionType.ROLE_CREATE, 'ROLE_CREATE', 'Role was created'],- [AuditLogActionType.ROLE_UPDATE, 'ROLE_UPDATE', 'Role was updated'],- [AuditLogActionType.ROLE_DELETE, 'ROLE_DELETE', 'Role was deleted'],- [AuditLogActionType.INVITE_CREATE, 'INVITE_CREATE', 'Invite was created'],- [AuditLogActionType.INVITE_UPDATE, 'INVITE_UPDATE', 'Invite was updated'],- [AuditLogActionType.INVITE_DELETE, 'INVITE_DELETE', 'Invite was deleted'],- [AuditLogActionType.WEBHOOK_CREATE, 'WEBHOOK_CREATE', 'Webhook was created'],- [AuditLogActionType.WEBHOOK_UPDATE, 'WEBHOOK_UPDATE', 'Webhook was updated'],- [AuditLogActionType.WEBHOOK_DELETE, 'WEBHOOK_DELETE', 'Webhook was deleted'],- [AuditLogActionType.EMOJI_CREATE, 'EMOJI_CREATE', 'Emoji was created'],- [AuditLogActionType.EMOJI_UPDATE, 'EMOJI_UPDATE', 'Emoji was updated'],- [AuditLogActionType.EMOJI_DELETE, 'EMOJI_DELETE', 'Emoji was deleted'],- [AuditLogActionType.STICKER_CREATE, 'STICKER_CREATE', 'Sticker was created'],- [AuditLogActionType.STICKER_UPDATE, 'STICKER_UPDATE', 'Sticker was updated'],- [AuditLogActionType.STICKER_DELETE, 'STICKER_DELETE', 'Sticker was deleted'],- [AuditLogActionType.MESSAGE_DELETE, 'MESSAGE_DELETE', 'Message was deleted'],- [AuditLogActionType.MESSAGE_BULK_DELETE, 'MESSAGE_BULK_DELETE', 'Messages were bulk deleted'],- [AuditLogActionType.MESSAGE_PIN, 'MESSAGE_PIN', 'Message was pinned'],- [AuditLogActionType.MESSAGE_UNPIN, 'MESSAGE_UNPIN', 'Message was unpinned'],- ],- 'The type of action that occurred',- 'AuditLogActionType',- ),+export const AuditLogActionTypeSchema = createInt32EnumType(+ [+ [AuditLogActionType.GUILD_UPDATE, 'GUILD_UPDATE', 'Guild settings were updated'],+ [AuditLogActionType.CHANNEL_CREATE, 'CHANNEL_CREATE', 'Channel was created'],+ [AuditLogActionType.CHANNEL_UPDATE, 'CHANNEL_UPDATE', 'Channel was updated'],+ [AuditLogActionType.CHANNEL_DELETE, 'CHANNEL_DELETE', 'Channel was deleted'],+ [AuditLogActionType.CHANNEL_OVERWRITE_CREATE, 'CHANNEL_OVERWRITE_CREATE', 'Permission overwrite was created'],+ [AuditLogActionType.CHANNEL_OVERWRITE_UPDATE, 'CHANNEL_OVERWRITE_UPDATE', 'Permission overwrite was updated'],+ [AuditLogActionType.CHANNEL_OVERWRITE_DELETE, 'CHANNEL_OVERWRITE_DELETE', 'Permission overwrite was deleted'],+ [AuditLogActionType.MEMBER_KICK, 'MEMBER_KICK', 'Member was kicked'],+ [AuditLogActionType.MEMBER_PRUNE, 'MEMBER_PRUNE', 'Members were pruned'],+ [AuditLogActionType.MEMBER_BAN_ADD, 'MEMBER_BAN_ADD', 'Member was banned'],+ [AuditLogActionType.MEMBER_BAN_REMOVE, 'MEMBER_BAN_REMOVE', 'Member ban was removed'],+ [AuditLogActionType.MEMBER_UPDATE, 'MEMBER_UPDATE', 'Member was updated'],+ [AuditLogActionType.MEMBER_ROLE_UPDATE, 'MEMBER_ROLE_UPDATE', 'Member roles were updated'],+ [AuditLogActionType.MEMBER_MOVE, 'MEMBER_MOVE', 'Member was moved to a different voice channel'],+ [AuditLogActionType.MEMBER_DISCONNECT, 'MEMBER_DISCONNECT', 'Member was disconnected from a voice channel'],+ [AuditLogActionType.BOT_ADD, 'BOT_ADD', 'Bot was added to the guild'],+ [AuditLogActionType.ROLE_CREATE, 'ROLE_CREATE', 'Role was created'],+ [AuditLogActionType.ROLE_UPDATE, 'ROLE_UPDATE', 'Role was updated'],+ [AuditLogActionType.ROLE_DELETE, 'ROLE_DELETE', 'Role was deleted'],+ [AuditLogActionType.INVITE_CREATE, 'INVITE_CREATE', 'Invite was created'],+ [AuditLogActionType.INVITE_UPDATE, 'INVITE_UPDATE', 'Invite was updated'],+ [AuditLogActionType.INVITE_DELETE, 'INVITE_DELETE', 'Invite was deleted'],+ [AuditLogActionType.WEBHOOK_CREATE, 'WEBHOOK_CREATE', 'Webhook was created'],+ [AuditLogActionType.WEBHOOK_UPDATE, 'WEBHOOK_UPDATE', 'Webhook was updated'],+ [AuditLogActionType.WEBHOOK_DELETE, 'WEBHOOK_DELETE', 'Webhook was deleted'],+ [AuditLogActionType.EMOJI_CREATE, 'EMOJI_CREATE', 'Emoji was created'],+ [AuditLogActionType.EMOJI_UPDATE, 'EMOJI_UPDATE', 'Emoji was updated'],+ [AuditLogActionType.EMOJI_DELETE, 'EMOJI_DELETE', 'Emoji was deleted'],+ [AuditLogActionType.STICKER_CREATE, 'STICKER_CREATE', 'Sticker was created'],+ [AuditLogActionType.STICKER_UPDATE, 'STICKER_UPDATE', 'Sticker was updated'],+ [AuditLogActionType.STICKER_DELETE, 'STICKER_DELETE', 'Sticker was deleted'],+ [AuditLogActionType.MESSAGE_DELETE, 'MESSAGE_DELETE', 'Message was deleted'],+ [AuditLogActionType.MESSAGE_BULK_DELETE, 'MESSAGE_BULK_DELETE', 'Messages were bulk deleted'],+ [AuditLogActionType.MESSAGE_PIN, 'MESSAGE_PIN', 'Message was pinned'],+ [AuditLogActionType.MESSAGE_UNPIN, 'MESSAGE_UNPIN', 'Message was unpinned'],+ ],+ 'The type of action that occurred','AuditLogActionType',);diff --git a/packages/schema/src/primitives/ChannelValidators.ts b/packages/schema/src/primitives/ChannelValidators.tsindex 6c52c7afd..074b785e1 100644--- a/packages/schema/src/primitives/ChannelValidators.ts+++ b/packages/schema/src/primitives/ChannelValidators.ts@@ -18,19 +18,17 @@ import {} from '@fluxer/schema/src/primitives/SchemaPrimitives';import {z} from 'zod';-export const ChannelTypeSchema = withOpenApiType(- createInt32EnumType(- [- [ChannelTypes.GUILD_TEXT, 'GUILD_TEXT', 'A text channel within a guild'],- [ChannelTypes.DM, 'DM', 'A direct message between users'],- [ChannelTypes.GUILD_VOICE, 'GUILD_VOICE', 'A voice channel within a guild'],- [ChannelTypes.GROUP_DM, 'GROUP_DM', 'A group direct message between users'],- [ChannelTypes.GUILD_CATEGORY, 'GUILD_CATEGORY', 'A category that contains channels'],- [ChannelTypes.GUILD_LINK, 'GUILD_LINK', 'A link channel for external resources'],- [ChannelTypes.DM_PERSONAL_NOTES, 'DM_PERSONAL_NOTES', 'Personal notes DM channel'],- ],- 'The type of the channel',- ),+export const ChannelTypeSchema = createInt32EnumType(+ [+ [ChannelTypes.GUILD_TEXT, 'GUILD_TEXT', 'A text channel within a guild'],+ [ChannelTypes.DM, 'DM', 'A direct message between users'],+ [ChannelTypes.GUILD_VOICE, 'GUILD_VOICE', 'A voice channel within a guild'],+ [ChannelTypes.GROUP_DM, 'GROUP_DM', 'A group direct message between users'],+ [ChannelTypes.GUILD_CATEGORY, 'GUILD_CATEGORY', 'A category that contains channels'],+ [ChannelTypes.GUILD_LINK, 'GUILD_LINK', 'A link channel for external resources'],+ [ChannelTypes.DM_PERSONAL_NOTES, 'DM_PERSONAL_NOTES', 'Personal notes DM channel'],+ ],+ 'The type of the channel','ChannelType',);export const ChannelOverwriteTypeSchema = withOpenApiType(diff --git a/packages/schema/src/primitives/GuildValidators.ts b/packages/schema/src/primitives/GuildValidators.tsindex 42bb96b0a..0d45ba2a0 100644--- a/packages/schema/src/primitives/GuildValidators.ts+++ b/packages/schema/src/primitives/GuildValidators.ts@@ -10,11 +10,7 @@ import {JoinSourceTypes,} from '@fluxer/constants/src/GuildConstants';import {MessageNotifications} from '@fluxer/constants/src/NotificationConstants';-import {- createInt32EnumType,- createNamedLiteralUnion,- withOpenApiType,-} from '@fluxer/schema/src/primitives/SchemaPrimitives';+import {createInt32EnumType, createNamedLiteralUnion} from '@fluxer/schema/src/primitives/SchemaPrimitives';export const GuildVerificationLevelSchema = createInt32EnumType([@@ -80,18 +76,15 @@ export const SplashCardAlignmentSchema = createNamedLiteralUnion(] as const,'Alignment of the guild splash card',);-export const JoinSourceTypeSchema = withOpenApiType(- createInt32EnumType(- [- [JoinSourceTypes.CREATOR, 'CREATOR', 'Member created the guild'],- [JoinSourceTypes.INSTANT_INVITE, 'INSTANT_INVITE', 'Member joined via an instant invite'],- [JoinSourceTypes.VANITY_URL, 'VANITY_URL', 'Member joined via the vanity URL'],- [JoinSourceTypes.BOT_INVITE, 'BOT_INVITE', 'Member was added via a bot invite'],- [JoinSourceTypes.ADMIN_FORCE_ADD, 'ADMIN_FORCE_ADD', 'Member was force-added by a platform administrator'],- [JoinSourceTypes.DISCOVERY, 'DISCOVERY', 'Member joined via guild discovery'],- ],- 'How the member joined the guild',- 'JoinSourceType',- ),+export const JoinSourceTypeSchema = createInt32EnumType(+ [+ [JoinSourceTypes.CREATOR, 'CREATOR', 'Member created the guild'],+ [JoinSourceTypes.INSTANT_INVITE, 'INSTANT_INVITE', 'Member joined via an instant invite'],+ [JoinSourceTypes.VANITY_URL, 'VANITY_URL', 'Member joined via the vanity URL'],+ [JoinSourceTypes.BOT_INVITE, 'BOT_INVITE', 'Member was added via a bot invite'],+ [JoinSourceTypes.ADMIN_FORCE_ADD, 'ADMIN_FORCE_ADD', 'Member was force-added by a platform administrator'],+ [JoinSourceTypes.DISCOVERY, 'DISCOVERY', 'Member joined via guild discovery'],+ ],+ 'How the member joined the guild','JoinSourceType',);diff --git a/packages/schema/src/primitives/MessageValidators.ts b/packages/schema/src/primitives/MessageValidators.tsindex 978b03be9..12a6b7053 100644--- a/packages/schema/src/primitives/MessageValidators.ts+++ b/packages/schema/src/primitives/MessageValidators.ts@@ -7,35 +7,25 @@ import {MessageReferenceTypesDescriptions,MessageTypes,} from '@fluxer/constants/src/ChannelConstants';-import {- createInt32EnumType,- createNamedStringLiteralUnion,- withOpenApiType,-} from '@fluxer/schema/src/primitives/SchemaPrimitives';+import {createInt32EnumType, createNamedStringLiteralUnion} from '@fluxer/schema/src/primitives/SchemaPrimitives';-export const MessageTypeSchema = withOpenApiType(- createInt32EnumType(+export const MessageTypeSchema = createInt32EnumType(+ [+ [MessageTypes.DEFAULT, 'DEFAULT', 'A regular message'],+ [MessageTypes.RECIPIENT_ADD, 'RECIPIENT_ADD', 'A system message indicating a user was added to the conversation'],[- [MessageTypes.DEFAULT, 'DEFAULT', 'A regular message'],- [MessageTypes.RECIPIENT_ADD, 'RECIPIENT_ADD', 'A system message indicating a user was added to the conversation'],- [- MessageTypes.RECIPIENT_REMOVE,- 'RECIPIENT_REMOVE',- 'A system message indicating a user was removed from the conversation',- ],- [MessageTypes.CALL, 'CALL', 'A message representing a call'],- [MessageTypes.CHANNEL_NAME_CHANGE, 'CHANNEL_NAME_CHANGE', 'A system message indicating the channel name changed'],- [MessageTypes.CHANNEL_ICON_CHANGE, 'CHANNEL_ICON_CHANGE', 'A system message indicating the channel icon changed'],- [- MessageTypes.CHANNEL_PINNED_MESSAGE,- 'CHANNEL_PINNED_MESSAGE',- 'A system message indicating a message was pinned',- ],- [MessageTypes.USER_JOIN, 'USER_JOIN', 'A system message indicating a user joined'],- [MessageTypes.REPLY, 'REPLY', 'A reply message'],+ MessageTypes.RECIPIENT_REMOVE,+ 'RECIPIENT_REMOVE',+ 'A system message indicating a user was removed from the conversation',],- 'The type of message',- ),+ [MessageTypes.CALL, 'CALL', 'A message representing a call'],+ [MessageTypes.CHANNEL_NAME_CHANGE, 'CHANNEL_NAME_CHANGE', 'A system message indicating the channel name changed'],+ [MessageTypes.CHANNEL_ICON_CHANGE, 'CHANNEL_ICON_CHANGE', 'A system message indicating the channel icon changed'],+ [MessageTypes.CHANNEL_PINNED_MESSAGE, 'CHANNEL_PINNED_MESSAGE', 'A system message indicating a message was pinned'],+ [MessageTypes.USER_JOIN, 'USER_JOIN', 'A system message indicating a user joined'],+ [MessageTypes.REPLY, 'REPLY', 'A reply message'],+ ],+ 'The type of message','MessageType',);export const MessageReferenceTypeSchema = createInt32EnumType(diff --git a/packages/schema/src/primitives/WebhookValidators.ts b/packages/schema/src/primitives/WebhookValidators.tsindex 0f5205cd0..636ca265f 100644--- a/packages/schema/src/primitives/WebhookValidators.ts+++ b/packages/schema/src/primitives/WebhookValidators.ts@@ -1,15 +1,12 @@// SPDX-License-Identifier: AGPL-3.0-or-later-import {createInt32EnumType, withOpenApiType} from '@fluxer/schema/src/primitives/SchemaPrimitives';+import {createInt32EnumType} from '@fluxer/schema/src/primitives/SchemaPrimitives';-export const WebhookTypeSchema = withOpenApiType(- createInt32EnumType(- [- [1, 'INCOMING', 'Incoming webhook'],- [2, 'CHANNEL_FOLLOWER', 'Channel follower webhook'],- ],- 'The type of webhook',- 'WebhookType',- ),+export const WebhookTypeSchema = createInt32EnumType(+ [+ [1, 'INCOMING', 'Incoming webhook'],+ [2, 'CHANNEL_FOLLOWER', 'Channel follower webhook'],+ ],+ 'The type of webhook','WebhookType',);diff --git a/packages/snowflake/src/Snowflake.ts b/packages/snowflake/src/Snowflake.tsindex f23cbec71..f14cefd35 100644--- a/packages/snowflake/src/Snowflake.ts+++ b/packages/snowflake/src/Snowflake.ts@@ -28,12 +28,6 @@ export interface SnowflakeParts {sequence: number;}-interface SnowflakeBitParts {- relativeTimestamp: bigint;- workerId: bigint;- sequence: bigint;-}-interface ResolvedSnowflakeGeneratorOptions {workerId: number;now: () => number;@@ -82,12 +76,16 @@ function assertValidSequence(sequence: number): bigint {return sequenceBigInt;}-function toRelativeTimestamp(timestamp: number | bigint): bigint {- const timestampBigInt = BigInt(timestamp);- const relativeTimestamp = timestampBigInt - FLUXER_EPOCH;+function assertValidRelativeTimestamp(relativeTimestamp: bigint): void {if (relativeTimestamp < 0n) {throw new Error('Timestamp must be on or after the Fluxer epoch');}+}++function toRelativeTimestamp(timestamp: number | bigint): bigint {+ const timestampBigInt = BigInt(timestamp);+ const relativeTimestamp = timestampBigInt - FLUXER_EPOCH;+ assertValidRelativeTimestamp(relativeTimestamp);return relativeTimestamp;}@@ -95,14 +93,6 @@ function toEpochTimestamp(relativeTimestamp: bigint): bigint {return relativeTimestamp + FLUXER_EPOCH;}-function toSnowflakeBitParts(snowflake: bigint): SnowflakeBitParts {- return {- relativeTimestamp: snowflake >> TIMESTAMP_SHIFT,- workerId: (snowflake >> WORKER_ID_SHIFT) & MAX_WORKER_ID,- sequence: snowflake & MAX_SEQUENCE,- };-}-function createSnowflakeBigInt(relativeTimestamp: bigint, workerId: bigint, sequence: bigint): bigint {return (relativeTimestamp << TIMESTAMP_SHIFT) | (workerId << WORKER_ID_SHIFT) | sequence;}@@ -128,16 +118,18 @@ export class SnowflakeGenerator {if (timestamp < this.lastTimestamp) {timestamp = this.lastTimestamp;}+ assertValidRelativeTimestamp(timestamp);+ let sequence = 0n;if (timestamp === this.lastTimestamp) {- this.sequence = (this.sequence + 1n) & MAX_SEQUENCE;- if (this.sequence === 0n) {+ sequence = (this.sequence + 1n) & MAX_SEQUENCE;+ if (sequence === 0n) {timestamp = this.waitUntilNextTimestamp();}- } else {- this.sequence = 0n;}+ const snowflake = createSnowflakeBigInt(timestamp, this.workerId, sequence);+ this.sequence = sequence;this.lastTimestamp = timestamp;- return createSnowflakeBigInt(timestamp, this.workerId, this.sequence);+ return snowflake;}getWorkerId(): number {@@ -189,16 +181,14 @@ export function createSnowflakeFromTimestamp(timestamp: number | bigint, workerI}export function snowflakeToDate(snowflake: bigint): Date {- const bitParts = toSnowflakeBitParts(snowflake);- return new Date(Number(toEpochTimestamp(bitParts.relativeTimestamp)));+ return new Date(Number(toEpochTimestamp(snowflake >> TIMESTAMP_SHIFT)));}export function parseSnowflake(snowflake: bigint): SnowflakeParts {- const bitParts = toSnowflakeBitParts(snowflake);return {- timestamp: new Date(Number(toEpochTimestamp(bitParts.relativeTimestamp))),- workerId: Number(bitParts.workerId),- sequence: Number(bitParts.sequence),+ timestamp: snowflakeToDate(snowflake),+ workerId: Number((snowflake >> WORKER_ID_SHIFT) & MAX_WORKER_ID),+ sequence: Number(snowflake & MAX_SEQUENCE),};}@@ -209,12 +199,8 @@ export function isValidSnowflake(value: unknown): value is bigint {if (value < 0n) {return false;}- const bitParts = toSnowflakeBitParts(value);- const timestamp = toEpochTimestamp(bitParts.relativeTimestamp);+ const timestamp = toEpochTimestamp(value >> TIMESTAMP_SHIFT);const timestampNumber = Number(timestamp);- if (timestampNumber < Number(FLUXER_EPOCH)) {- return false;- }if (timestampNumber > Date.now() + MAX_FUTURE_DRIFT_MS) {return false;}diff --git a/packages/snowflake/src/SnowflakeBuckets.ts b/packages/snowflake/src/SnowflakeBuckets.tsindex e42f8d510..7eef99c2c 100644--- a/packages/snowflake/src/SnowflakeBuckets.ts+++ b/packages/snowflake/src/SnowflakeBuckets.ts@@ -26,7 +26,7 @@ function createBucketRange(startBucket: number, endBucket: number): Array<numberexport function makeBucket(snowflake: bigint | null): number {const timestamp = getRelativeTimestampForBucket(snowflake);- return Math.floor(Number(timestamp / SNOWFLAKE_BUCKET_SIZE_MS));+ return Number(timestamp / SNOWFLAKE_BUCKET_SIZE_MS);}export function makeBucketString(snowflake: string | null): number {diff --git a/packages/snowflake/src/SnowflakeUtils.ts b/packages/snowflake/src/SnowflakeUtils.tsindex 79db6cdd3..79d4205f3 100644--- a/packages/snowflake/src/SnowflakeUtils.ts+++ b/packages/snowflake/src/SnowflakeUtils.ts@@ -41,11 +41,7 @@ function assertValidSequenceValue(sequence: number): void {}export function extractTimestamp(snowflake: string): number {- try {- return extractTimestampWithEpoch(BigInt(snowflake), FLUXER_EPOCH);- } catch (_error) {- return Number.NaN;- }+ return extractTimestampFromSnowflake(snowflake);}export function extractTimestampBigInt(snowflake: bigint): number {@@ -53,11 +49,7 @@ export function extractTimestampBigInt(snowflake: bigint): number {}export function fromTimestamp(timestamp: number): string {- const clampedTimestamp = toClampedTimestamp(timestamp);- if (clampedTimestamp === FLUXER_EPOCH_NUMBER) {- return '0';- }- return createSnowflake({timestamp: clampedTimestamp}).toString();+ return fromTimestampBigInt(timestamp).toString();}export function fromTimestampBigInt(timestamp: number): bigint {@@ -131,13 +123,7 @@ export function compareBigInt(snowflake1: bigint | null, snowflake2: bigint | nuif (snowflake1 == null) {return -1;}- if (snowflake1 > snowflake2) {- return 1;- }- if (snowflake1 < snowflake2) {- return -1;- }- return 0;+ return snowflake1 > snowflake2 ? 1 : -1;}export function isProbablyAValidSnowflake(value: string | null | undefined): boolean {@@ -178,9 +164,6 @@ export function age(snowflake: string): number {export function ageBigInt(snowflake: bigint): number {const timestamp = extractTimestampBigInt(snowflake);- if (Number.isNaN(timestamp)) {- return 0;- }return Date.now() - timestamp;}@@ -202,11 +185,7 @@ export function extractTimestampFromSnowflakeAsDate(snowflake: string, epoch?: s}export function extractTimestampFromSnowflakeAsDateBigInt(snowflake: bigint): Date {- const timestamp = extractTimestampBigInt(snowflake);- if (Number.isNaN(timestamp)) {- return new Date();- }- return new Date(timestamp);+ return new Date(extractTimestampBigInt(snowflake));}export interface SnowflakeSequenceOptions {