import { isUuid } from '@d3ro/core/guards' import { SUPABASE_ANON_KEY, SUPABASE_URL } from '@d3ro/core/supabase-config' import { assertRecordWith, parseBoundedStringWith, parseIsoTimestampWith, parseSafeIntegerWith, parseUuidWith, } from '../shared/service-guards' export const ADMIN_ROLES = ['user', 'manager', 'admin', 'super_admin'] as const export const ADMIN_TIERS = ['free', 'pro', 'pro_plus'] as const export const ADMIN_SUBSCRIPTION_STATUSES = ['active', 'canceled', 'past_due', 'expired'] as const export type AdminRole = typeof ADMIN_ROLES[number] export type AdminTier = typeof ADMIN_TIERS[number] export type AdminSubscriptionStatus = typeof ADMIN_SUBSCRIPTION_STATUSES[number] export type CurrentAdminRole = Exclude export type AdminServiceErrorCode = | 'auth' | 'forbidden' | 'not-found' | 'conflict' | 'validation' | 'network' | 'timeout' | 'unavailable' | 'server' export class AdminServiceError extends Error { constructor( readonly code: AdminServiceErrorCode, readonly status: number | null, readonly retryable: boolean, ) { super(code) this.name = 'AdminServiceError' } } export interface AdminProfileSummary { id: string name: string | null avatarUrl: string | null tier: AdminTier role: AdminRole createdAt: string } export interface AdminProfileDetail extends AdminProfileSummary { locale: string | null updatedAt: string } export interface AdminAccountDetail { id: string email: string | null createdAt: string lastSignInAt: string | null } export interface AdminSubscription { id: string userId: string tier: AdminTier status: AdminSubscriptionStatus provider: string paymentProvider: string currentPeriodStart: string | null currentPeriodEnd: string | null overageCredits: number adminNote: string | null cancelAt: string | null createdAt: string updatedAt: string profileName?: string | null profileAvatarUrl?: string | null } export interface AdminUserDetail { profile: AdminProfileDetail subscription: AdminSubscription | null account: AdminAccountDetail } export interface AdminAuditEntry { id: number adminId: string adminName: string | null action: string targetType: 'profile' | 'subscription' targetId: string memo: string | null createdAt: string } export interface AdminProviderEvent { provider: string eventType: string eventCreatedAt: string disposition: string receivedAt: string processedAt: string | null } export interface AdminProviderOperation { provider: string operationType: string requestedTier: AdminTier | null state: string errorCode: string | null expiresAt: string createdAt: string updatedAt: string } export interface AdminPaymentHistory { subscription: AdminSubscription | null auditLogs: AdminAuditEntry[] providerEvents: AdminProviderEvent[] providerOperations: AdminProviderOperation[] liveProviderHistoryAvailable: false } export interface AdminPage { entries: T[] total: number page: number limit: number } interface RequestOptions { accessToken: string method?: 'GET' | 'POST' | 'PATCH' | 'DELETE' body?: Record idempotencyKey?: string signal?: AbortSignal } const EMAIL_PATTERN = /^[^\s@]+@[^\s@]+\.[^\s@]+$/ const MAX_RESPONSE_BYTES = 1024 * 1024 const REQUEST_TIMEOUT_MS = 20_000 const ROLE_SET = new Set(ADMIN_ROLES) const TIER_SET = new Set(ADMIN_TIERS) const STATUS_SET = new Set(ADMIN_SUBSCRIPTION_STATUSES) function recordValue(value: unknown): Record { return assertRecordWith(value, invalidResponse) } function assertOnlyKeys(value: Record, allowed: readonly string[]): void { const allowedSet = new Set(allowed) if (Object.keys(value).some((key) => !allowedSet.has(key))) throw invalidResponse() } function requiredString(value: unknown, maximum = 2048): string { return parseBoundedStringWith(value, invalidResponse, { maxLength: maximum }) } function nullableString(value: unknown, maximum = 4096): string | null { if (value === null) return null return requiredString(value, maximum) } function uuid(value: unknown): string { return parseUuidWith(requiredString(value, 36), invalidResponse) } function isoDateTime(value: unknown): string { return parseIsoTimestampWith(requiredString(value, 40), invalidResponse, { maxLength: 40 }) } function nullableIsoDateTime(value: unknown): string | null { return value === null ? null : isoDateTime(value) } function nonNegativeInteger(value: unknown, maximum = 1_000_000): number { return parseSafeIntegerWith(value, invalidResponse, { min: 0, max: maximum }) } function positiveInteger(value: unknown, maximum = Number.MAX_SAFE_INTEGER): number { return parseSafeIntegerWith(value, invalidResponse, { min: 1, max: maximum }) } function role(value: unknown): AdminRole { const normalized = requiredString(value, 20) if (!ROLE_SET.has(normalized)) throw invalidResponse() return normalized as AdminRole } function tier(value: unknown): AdminTier { const normalized = requiredString(value, 20) if (!TIER_SET.has(normalized)) throw invalidResponse() return normalized as AdminTier } function nullableTier(value: unknown): AdminTier | null { return value === null ? null : tier(value) } function subscriptionStatus(value: unknown): AdminSubscriptionStatus { const normalized = requiredString(value, 20) if (!STATUS_SET.has(normalized)) throw invalidResponse() return normalized as AdminSubscriptionStatus } function invalidResponse(): AdminServiceError { return new AdminServiceError('server', 502, false) } function parseProfileSummary(value: unknown): AdminProfileSummary { const row = recordValue(value) assertOnlyKeys(row, ['id', 'name', 'avatar_url', 'tier', 'role', 'created_at']) return { id: uuid(row.id), name: nullableString(row.name, 200), avatarUrl: nullableString(row.avatar_url, 2048), tier: tier(row.tier), role: role(row.role), createdAt: isoDateTime(row.created_at), } } function parseProfileDetail(value: unknown): AdminProfileDetail { const row = recordValue(value) assertOnlyKeys(row, ['id', 'name', 'avatar_url', 'locale', 'tier', 'role', 'created_at', 'updated_at']) return { id: uuid(row.id), name: nullableString(row.name, 200), avatarUrl: nullableString(row.avatar_url, 2048), locale: nullableString(row.locale, 32), tier: tier(row.tier), role: role(row.role), createdAt: isoDateTime(row.created_at), updatedAt: isoDateTime(row.updated_at), } } function parseAccount(value: unknown): AdminAccountDetail { const row = recordValue(value) assertOnlyKeys(row, ['id', 'email', 'createdAt', 'lastSignInAt']) const email = nullableString(row.email, 320) if (email !== null && !EMAIL_PATTERN.test(email)) throw invalidResponse() return { id: uuid(row.id), email, createdAt: isoDateTime(row.createdAt), lastSignInAt: nullableIsoDateTime(row.lastSignInAt), } } const SUBSCRIPTION_KEYS = [ 'id', 'user_id', 'tier', 'status', 'provider', 'payment_provider', 'current_period_start', 'current_period_end', 'overage_credits', 'admin_note', 'cancel_at', 'created_at', 'updated_at', ] as const function parseSubscription(value: unknown): AdminSubscription { const row = recordValue(value) assertOnlyKeys(row, SUBSCRIPTION_KEYS) return { id: uuid(row.id), userId: uuid(row.user_id), tier: tier(row.tier), status: subscriptionStatus(row.status), provider: requiredString(row.provider, 64), paymentProvider: requiredString(row.payment_provider, 64), currentPeriodStart: nullableIsoDateTime(row.current_period_start), currentPeriodEnd: nullableIsoDateTime(row.current_period_end), overageCredits: nonNegativeInteger(row.overage_credits), adminNote: nullableString(row.admin_note, 2000), cancelAt: nullableIsoDateTime(row.cancel_at), createdAt: isoDateTime(row.created_at), updatedAt: isoDateTime(row.updated_at), } } function parseSubscriptionListRow(value: unknown): AdminSubscription { const row = recordValue(value) assertOnlyKeys(row, [...SUBSCRIPTION_KEYS, 'profiles']) const base: Record = {} for (const key of SUBSCRIPTION_KEYS) base[key] = row[key] const parsed = parseSubscription(base) if (row.profiles === null) return parsed const profile = recordValue(row.profiles) assertOnlyKeys(profile, ['name', 'avatar_url']) return { ...parsed, profileName: nullableString(profile.name, 200), profileAvatarUrl: nullableString(profile.avatar_url, 2048), } } function parseAudit(value: unknown, allowAdminName: boolean): AdminAuditEntry { const row = recordValue(value) const allowed = [ 'id', 'admin_id', 'action', 'target_type', 'target_id', 'before_data', 'after_data', 'memo', 'created_at', ...(allowAdminName ? ['admin_name'] : []), ] assertOnlyKeys(row, allowed) const targetType = requiredString(row.target_type, 32) if (targetType !== 'profile' && targetType !== 'subscription') throw invalidResponse() return { id: positiveInteger(row.id, 10_000_000_000), adminId: uuid(row.admin_id), adminName: allowAdminName ? nullableString(row.admin_name, 200) : null, action: requiredString(row.action, 100), targetType, targetId: uuid(row.target_id), memo: nullableString(row.memo, 1000), createdAt: isoDateTime(row.created_at), } } function parsePaymentAudit(value: unknown): AdminAuditEntry { const row = recordValue(value) assertOnlyKeys(row, ['id', 'admin_id', 'action', 'target_type', 'target_id', 'memo', 'created_at']) return parseAudit({ ...row, before_data: null, after_data: null }, false) } function parseProviderEvent(value: unknown): AdminProviderEvent { const row = recordValue(value) assertOnlyKeys(row, [ 'id', 'provider', 'event_type', 'event_created_at', 'disposition', 'received_at', 'processed_at', ]) requiredString(row.id, 256) return { provider: requiredString(row.provider, 64), eventType: requiredString(row.event_type, 128), eventCreatedAt: isoDateTime(row.event_created_at), disposition: requiredString(row.disposition, 64), receivedAt: isoDateTime(row.received_at), processedAt: nullableIsoDateTime(row.processed_at), } } function parseProviderOperation(value: unknown): AdminProviderOperation { const row = recordValue(value) assertOnlyKeys(row, [ 'id', 'provider', 'operation_type', 'requested_tier', 'state', 'error_code', 'expires_at', 'created_at', 'updated_at', ]) requiredString(row.id, 256) return { provider: requiredString(row.provider, 64), operationType: requiredString(row.operation_type, 128), requestedTier: nullableTier(row.requested_tier), state: requiredString(row.state, 64), errorCode: nullableString(row.error_code, 128), expiresAt: isoDateTime(row.expires_at), createdAt: isoDateTime(row.created_at), updatedAt: isoDateTime(row.updated_at), } } function publicErrorCode(value: unknown): string { if (typeof value !== 'string' || value.length < 1 || value.length > 128) return 'invalid_error_response' return value } function errorFromResponse(status: number, value: unknown): AdminServiceError { const body = typeof value === 'object' && value !== null && !Array.isArray(value) ? value as Record : {} const publicCode = publicErrorCode(body.error) if (status === 401) return new AdminServiceError('auth', status, false) if (status === 403) return new AdminServiceError('forbidden', status, false) if (status === 404) return new AdminServiceError('not-found', status, false) if (status === 409) return new AdminServiceError('conflict', status, publicCode === 'operation_in_progress') if (status === 400 || status === 413 || status === 415 || status === 422) { return new AdminServiceError('validation', status, false) } if (status === 501 || status === 503) return new AdminServiceError('unavailable', status, true) return new AdminServiceError('server', status, status >= 500) } function validatedToken(value: string): string { const token = value.trim() if (token.length < 20 || token.length > 16_384 || /\s/.test(token)) { throw new AdminServiceError('auth', null, false) } return token } async function requestAdmin(path: string, options: RequestOptions): Promise { const token = validatedToken(options.accessToken) const controller = new AbortController() let externallyAborted = false const abortFromCaller = (): void => { externallyAborted = true controller.abort() } options.signal?.addEventListener('abort', abortFromCaller, { once: true }) const timer = setTimeout(() => controller.abort(), REQUEST_TIMEOUT_MS) try { const response = await fetch(`${SUPABASE_URL}/functions/v1/${path}`, { method: options.method ?? 'GET', headers: { apikey: SUPABASE_ANON_KEY, Authorization: `Bearer ${token}`, Accept: 'application/json', ...(options.body === undefined ? {} : { 'Content-Type': 'application/json' }), ...(options.idempotencyKey === undefined ? {} : { 'idempotency-key': options.idempotencyKey }), }, body: options.body === undefined ? undefined : JSON.stringify(options.body), signal: controller.signal, }) const text = await response.text() if (new TextEncoder().encode(text).byteLength > MAX_RESPONSE_BYTES) throw invalidResponse() let payload: unknown = null if (text.length > 0) { try { payload = JSON.parse(text) as unknown } catch { throw invalidResponse() } } if (!response.ok) throw errorFromResponse(response.status, payload) return payload } catch (error) { if (error instanceof AdminServiceError) throw error if (controller.signal.aborted) { if (externallyAborted) throw new AdminServiceError('network', null, false) throw new AdminServiceError('timeout', null, true) } throw new AdminServiceError('network', null, true) } finally { clearTimeout(timer) options.signal?.removeEventListener('abort', abortFromCaller) } } function queryString(params: Record): string { const query = Object.entries(params) .filter((entry): entry is [string, string | number] => entry[1] !== undefined) .map(([key, value]) => `${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`) .join('&') return query.length === 0 ? '' : `?${query}` } function validatedPage(page: number, limit: number): void { if (!Number.isSafeInteger(page) || page < 1 || page > 1_000_000) { throw new AdminServiceError('validation', null, false) } if (!Number.isSafeInteger(limit) || limit < 1 || limit > 100) { throw new AdminServiceError('validation', null, false) } } function parsePageEnvelope( payload: unknown, listKey: string, parseEntry: (value: unknown) => T, ): AdminPage { const body = recordValue(payload) assertOnlyKeys(body, [listKey, 'total', 'page', 'limit']) if (!Array.isArray(body[listKey])) throw invalidResponse() return { entries: body[listKey].map(parseEntry), total: nonNegativeInteger(body.total, 1_000_000_000), page: positiveInteger(body.page, 1_000_000), limit: positiveInteger(body.limit, 100), } } export function currentAdminRole(metadata: unknown): CurrentAdminRole | null { if (typeof metadata !== 'object' || metadata === null || Array.isArray(metadata)) return null const candidate = (metadata as Record).role return candidate === 'manager' || candidate === 'admin' || candidate === 'super_admin' ? candidate : null } export async function listAdminUsers(options: { accessToken: string page?: number limit?: number search?: string role?: AdminRole signal?: AbortSignal }): Promise> { const page = options.page ?? 1 const limit = options.limit ?? 20 validatedPage(page, limit) const search = options.search?.trim() if (search !== undefined && (search.length < 1 || search.length > 100)) { throw new AdminServiceError('validation', null, false) } if (options.role !== undefined && !ROLE_SET.has(options.role)) { throw new AdminServiceError('validation', null, false) } const payload = await requestAdmin(`admin-users${queryString({ page, limit, search, role: options.role })}`, { accessToken: options.accessToken, signal: options.signal, }) return parsePageEnvelope(payload, 'profiles', parseProfileSummary) } export async function getAdminUser( accessToken: string, userId: string, signal?: AbortSignal, ): Promise { if (!isUuid(userId)) throw new AdminServiceError('validation', null, false) const payload = await requestAdmin(`admin-users${queryString({ userId })}`, { accessToken, signal }) const body = recordValue(payload) assertOnlyKeys(body, ['profile', 'subscription', 'account']) const profile = parseProfileDetail(body.profile) const account = parseAccount(body.account) const subscription = body.subscription === null ? null : parseSubscription(body.subscription) if (profile.id !== userId.toLowerCase() || account.id !== profile.id || (subscription !== null && subscription.userId !== profile.id)) throw invalidResponse() return { profile, account, subscription } } export async function listAdminSubscriptions(options: { accessToken: string page?: number limit?: number tier?: AdminTier status?: AdminSubscriptionStatus signal?: AbortSignal }): Promise> { const page = options.page ?? 1 const limit = options.limit ?? 20 validatedPage(page, limit) if (options.tier !== undefined && !TIER_SET.has(options.tier)) { throw new AdminServiceError('validation', null, false) } if (options.status !== undefined && !STATUS_SET.has(options.status)) { throw new AdminServiceError('validation', null, false) } const payload = await requestAdmin(`admin-subscriptions${queryString({ page, limit, tier: options.tier, status: options.status, })}`, { accessToken: options.accessToken, signal: options.signal }) return parsePageEnvelope(payload, 'subscriptions', parseSubscriptionListRow) } export async function listAdminAudit(options: { accessToken: string page?: number limit?: number targetType?: 'profile' | 'subscription' targetId?: string signal?: AbortSignal }): Promise> { const page = options.page ?? 1 const limit = options.limit ?? 20 validatedPage(page, limit) if (options.targetId !== undefined && !isUuid(options.targetId)) { throw new AdminServiceError('validation', null, false) } const payload = await requestAdmin(`admin-audit-log${queryString({ page, limit, target_type: options.targetType, target_id: options.targetId, })}`, { accessToken: options.accessToken, signal: options.signal }) return parsePageEnvelope(payload, 'logs', (value) => parseAudit(value, true)) } export async function getAdminPaymentHistory( accessToken: string, userId: string, signal?: AbortSignal, ): Promise { if (!isUuid(userId)) throw new AdminServiceError('validation', null, false) const payload = await requestAdmin(`admin-payments${queryString({ userId, source: 'db' })}`, { accessToken, signal, }) const body = recordValue(payload) assertOnlyKeys(body, [ 'subscription', 'auditLogs', 'providerEvents', 'providerOperations', 'liveProviderHistoryAvailable', ]) if (!Array.isArray(body.auditLogs) || !Array.isArray(body.providerEvents) || !Array.isArray(body.providerOperations) || body.liveProviderHistoryAvailable !== false) { throw invalidResponse() } const subscription = body.subscription === null ? null : parseSubscription(body.subscription) if (subscription !== null && subscription.userId !== userId.toLowerCase()) throw invalidResponse() return { subscription, auditLogs: body.auditLogs.map(parsePaymentAudit), providerEvents: body.providerEvents.map(parseProviderEvent), providerOperations: body.providerOperations.map(parseProviderOperation), liveProviderHistoryAvailable: false, } } function validatedIdempotencyKey(value: string): string { if (!isUuid(value)) throw new AdminServiceError('validation', null, false) return value.toLowerCase() } function validatedMemo(value: string): string { const memo = value.trim() if (memo.length < 3 || memo.length > 1000) throw new AdminServiceError('validation', null, false) return memo } export async function changeAdminUserRole(options: { accessToken: string idempotencyKey: string userId: string newRole: AdminRole memo: string signal?: AbortSignal }): Promise<{ userId: string; newRole: AdminRole }> { if (!isUuid(options.userId) || !ROLE_SET.has(options.newRole)) { throw new AdminServiceError('validation', null, false) } const idempotencyKey = validatedIdempotencyKey(options.idempotencyKey) const payload = await requestAdmin('admin-users', { accessToken: options.accessToken, method: 'PATCH', idempotencyKey, body: { userId: options.userId.toLowerCase(), newRole: options.newRole, memo: validatedMemo(options.memo), }, signal: options.signal, }) const body = recordValue(payload) assertOnlyKeys(body, ['success', 'userId', 'newRole']) if (body.success !== true || uuid(body.userId) !== options.userId.toLowerCase() || role(body.newRole) !== options.newRole) throw invalidResponse() return { userId: options.userId.toLowerCase(), newRole: options.newRole } } export type AdminSubscriptionMutation = { tier?: AdminTier status?: AdminSubscriptionStatus currentPeriodEnd?: string overageCredits?: number adminNote?: string memo: string } function normalizedSubscriptionMutation(value: AdminSubscriptionMutation): Record { const body: Record = { memo: validatedMemo(value.memo) } if (value.tier !== undefined) { if (!TIER_SET.has(value.tier)) throw new AdminServiceError('validation', null, false) body.tier = value.tier } if (value.status !== undefined) { if (!STATUS_SET.has(value.status)) throw new AdminServiceError('validation', null, false) body.status = value.status } if (value.currentPeriodEnd !== undefined) { if (!Number.isFinite(Date.parse(value.currentPeriodEnd))) { throw new AdminServiceError('validation', null, false) } body.currentPeriodEnd = new Date(Date.parse(value.currentPeriodEnd)).toISOString() } if (value.overageCredits !== undefined) { if (!Number.isSafeInteger(value.overageCredits) || value.overageCredits < 0 || value.overageCredits > 1_000_000) { throw new AdminServiceError('validation', null, false) } body.overageCredits = value.overageCredits } if (value.adminNote !== undefined) { if (value.adminNote.length > 2000) throw new AdminServiceError('validation', null, false) body.adminNote = value.adminNote } return body } async function mutateAdminSubscription( action: 'create' | 'update' | 'delete', options: { accessToken: string idempotencyKey: string userId: string mutation: AdminSubscriptionMutation signal?: AbortSignal }, ): Promise { if (!isUuid(options.userId)) throw new AdminServiceError('validation', null, false) const idempotencyKey = validatedIdempotencyKey(options.idempotencyKey) const body = action === 'delete' ? { memo: validatedMemo(options.mutation.memo) } : normalizedSubscriptionMutation(options.mutation) if (action === 'create') body.userId = options.userId.toLowerCase() if (action === 'create' && body.tier === undefined) { throw new AdminServiceError('validation', null, false) } const path = action === 'create' ? 'admin-subscriptions' : `admin-subscriptions${queryString({ userId: options.userId.toLowerCase() })}` const payload = await requestAdmin(path, { accessToken: options.accessToken, method: action === 'create' ? 'POST' : action === 'update' ? 'PATCH' : 'DELETE', idempotencyKey, body, signal: options.signal, }) const response = recordValue(payload) assertOnlyKeys(response, ['success', 'subscription']) if (response.success !== true) throw invalidResponse() const subscription = parseSubscription(response.subscription) if (subscription.userId !== options.userId.toLowerCase()) throw invalidResponse() return subscription } export function createAdminSubscription(options: { accessToken: string idempotencyKey: string userId: string mutation: AdminSubscriptionMutation & { tier: AdminTier } signal?: AbortSignal }): Promise { return mutateAdminSubscription('create', options) } export function updateAdminSubscription(options: { accessToken: string idempotencyKey: string userId: string mutation: AdminSubscriptionMutation signal?: AbortSignal }): Promise { return mutateAdminSubscription('update', options) } export function deleteAdminSubscription(options: { accessToken: string idempotencyKey: string userId: string memo: string signal?: AbortSignal }): Promise { return mutateAdminSubscription('delete', { ...options, mutation: { memo: options.memo }, }) }