@marktiderman/genesis-supabase 0.15.1 → 0.16.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/apple-tokens.ts","../src/tenant-features.ts","../src/feature-registry.ts","../src/auth-form-client.ts","../src/index.ts"],"names":[],"mappings":";;;;;AASO,IAAM,qBAAA,GAAwB;AAGrC,IAAM,gBAAA,GAAmB,GAAA;AAEzB,IAAM,iBAAA,GAAoB,GAAA;AAiC1B,eAAsB,gBAAgB,MAAA,EAAyB,EAAE,mBAAmB,QAAA,EAAU,YAAA,GAAe,uBAAsB,EAA2D;AAC5L,EAAA,IAAI;AACF,IAAA,MAAM,EAAE,KAAA,EAAM,GAAI,MAAM,MAAA,CAAO,UAAU,MAAA,CAAO,YAAA,EAAc,EAAE,IAAA,EAAM,EAAE,MAAA,EAAQ,SAAS,IAAA,EAAM,iBAAA,EAAmB,GAAI,QAAA,GAAW,EAAE,QAAA,EAAS,GAAI,EAAC,EAAG,EAAG,OAAA,EAAS,gBAAA,EAAkB,CAAA;AAClL,IAAA,IAAI,OAAO,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,OAAO,KAAA,YAAiB,KAAA,GAAQ,KAAA,GAAQ,IAAI,MAAM,MAAA,CAAQ,KAAA,CAAgC,OAAA,IAAW,KAAK,CAAC,CAAA,EAAE;AAC5I,IAAA,OAAO,EAAE,IAAI,IAAA,EAAK;AAAA,EACpB,SAAS,KAAA,EAAO;AACd,IAAA,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,KAAA,EAAO,KAAA,YAAiB,KAAA,GAAQ,KAAA,GAAQ,IAAI,KAAA,CAAM,MAAA,CAAO,KAAK,CAAC,CAAA,EAAE;AAAA,EACvF;AACF;AAQA,eAAsB,sBAAA,CAAuB,MAAA,EAAyB,YAAA,GAAe,qBAAA,EAAyC;AAC5H,EAAA,IAAI;AACF,IAAA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OAAO,KAAA,CAAM,IAAA;AAClB,IAAA,IAAA,CAAK,UAAU,KAAA,CAAM,OAAA;AACrB,IAAA,IAAA,CAAK,OAAO,KAAA,CAAM,IAAA;AAAA,EACpB;AACF;AASO,SAAS,KAAQ,MAAA,EAAiF;AACvG,EAAA,IAAI,OAAO,KAAA,EAAO,MAAM,IAAI,kBAAA,CAAmB,OAAO,KAAK,CAAA;AAC3D,EAAA,OAAO,MAAA,CAAO,IAAA;AAChB;AAwCA,eAAsB,eAAA,CAAgB,MAAA,EAA6B,OAAA,GAAkC,EAAC,EAAkB;AACtH,EAAA,IAAA,CAAM,MAAM,MAAA,CAAO,GAAA,CAAI,mBAAmB,CAAgF,CAAA;AAC1H,EAAA,MAAM,SAAS,OAAA,CAAQ,iBAAA;AAEvB,EAAA,IAAI,MAAA,IAAU,MAAA,CAAO,SAAA,EAAW,MAAM,uBAAuB,EAAE,SAAA,EAAW,MAAA,CAAO,SAAA,EAAU,EAAG,OAAO,MAAA,KAAW,QAAA,GAAW,SAAS,qBAAqB,CAAA;AAEzJ,EAAA,MAAM,OAAO,IAAA,CAAK,OAAA,CAAQ,EAAE,KAAA,EAAO,SAAS,CAAA;AAC9C","file":"index.js","sourcesContent":["/**\n * The app's side of Sign in with Apple token revocation: hand the sign-in's\n * authorization code to the `genesis-apple-revoke` Edge Function (it keeps\n * Apple's refresh token server-side), and ask it to revoke after the account\n * is deleted. The function and its migration ship in this package; see the\n * README (\"Revoking Apple's tokens\").\n */\n\n/** The Edge Function's default name, as shipped in `functions/genesis-apple-revoke`. */\nexport const APPLE_REVOKE_FUNCTION = \"genesis-apple-revoke\";\n\n/** The store call waits on Apple's token endpoint (10 s timeout in the function). */\nconst STORE_TIMEOUT_MS = 20_000;\n/** The function answers the revoke call at once and works in the background; don't hold the delete screen for longer. */\nconst REVOKE_TIMEOUT_MS = 5_000;\n\n/** The parts of a Supabase client these helpers use. A `SupabaseClient` fits. */\nexport interface FunctionsClient {\n functions: {\n // Loose on purpose, so any supabase-js version's `invoke` fits.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n invoke: (name: string, options?: any) => PromiseLike<{ data: unknown; error: unknown }>;\n };\n}\n\n/** @stability Beta */\nexport interface StoreAppleTokenOptions {\n /** `authorizationCode` from `signInWithApple`'s result. Single-use, valid for five minutes: send it straight after sign-in. */\n authorizationCode: string;\n /** The client id the code was issued for: your bundle id on iOS. Must be in the function's APPLE_CLIENT_IDS; default its first. */\n clientId?: string;\n /** The Edge Function's name. Default `genesis-apple-revoke`. */\n functionName?: string;\n}\n\n/** @stability Beta */\nexport type StoreAppleTokenResult = { ok: true } | { ok: false; error: Error };\n\n/**\n * After a Sign in with Apple, sends the authorization code to the Edge\n * Function, which exchanges it for Apple's refresh token and keeps it where\n * only the server reads it, so deleting the account can revoke it. Call it\n * with the session from that sign-in. Never throws: the person is signed in\n * either way, so log a failure rather than showing it.\n *\n * @stability Beta\n */\nexport async function storeAppleToken(client: FunctionsClient, { authorizationCode, clientId, functionName = APPLE_REVOKE_FUNCTION }: StoreAppleTokenOptions): Promise<StoreAppleTokenResult> {\n try {\n const { error } = await client.functions.invoke(functionName, { body: { action: \"store\", code: authorizationCode, ...(clientId ? { clientId } : {}) }, timeout: STORE_TIMEOUT_MS });\n if (error) return { ok: false, error: error instanceof Error ? error : new Error(String((error as { message?: unknown }).message ?? error)) };\n return { ok: true };\n } catch (error) {\n return { ok: false, error: error instanceof Error ? error : new Error(String(error)) };\n }\n}\n\n/**\n * Asks the Edge Function to revoke the tokens of deleted accounts now, rather\n * than at its next scheduled run. Never throws and never fails the caller:\n * the account is already gone and the queue keeps the token until a run\n * succeeds.\n */\nexport async function requestAppleRevocation(client: FunctionsClient, functionName = APPLE_REVOKE_FUNCTION): Promise<boolean> {\n try {\n const { error } = await client.functions.invoke(functionName, { body: { action: \"revoke\" }, timeout: REVOKE_TIMEOUT_MS });\n return !error;\n } catch {\n return false;\n }\n}\n","/**\n * Tenant features: the client half of `migrations/0004_genesis_tenant_features.sql`.\n * A tenant's admins turn a shipped feature off (or back on) for their tenant,\n * with a reason; its members read which ids are off and hide them.\n *\n * Exposure only: a switch hides a feature, it never grants or denies access\n * to data (that is RLS) and never sells it (that is an entitlement).\n */\n// A cycle with ./index, used only inside the functions.\nimport { must, type PostgrestErrorLike } from \"./index\";\n\n/** The parts of a Supabase client these helpers use. A `SupabaseClient` fits. */\nexport interface TenantFeaturesClient {\n // Loose on purpose: a client typed by an app's Database narrows `rpc`'s\n // function names, and the app's generated types may not list these yet.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n rpc: (fn: any, ...rest: any[]) => PromiseLike<{ data: unknown; error: PostgrestErrorLike | null }>;\n}\n\ntype RpcResult = { data: unknown; error: null } | { data: null; error: PostgrestErrorLike };\n\n/** Which features a tenant has turned off. A feature not in `off` is on. @stability Beta */\nexport interface TenantFeatures {\n readonly tenantId: string;\n readonly off: ReadonlySet<string>;\n isOn(featureId: string): boolean;\n}\n\n/**\n * The features `tenantId` has turned off, for one of its members (or\n * admins): `tenant_features_off`. Throws a `SupabaseQueryError` (`42501`)\n * for anyone else, so a refusal is never mistaken for \"everything on\".\n *\n * ```ts\n * const features = await tenantFeatures(supabase, teamId);\n * if (features.isOn(\"chat\")) showChatTab();\n * ```\n *\n * @stability Beta\n */\nexport async function tenantFeatures(client: TenantFeaturesClient, tenantId: string): Promise<TenantFeatures> {\n const data = must((await client.rpc(\"tenant_features_off\", { tenant: tenantId })) as RpcResult);\n const off = new Set(Array.isArray(data) ? data.filter((id): id is string => typeof id === \"string\") : []);\n return Object.freeze({ tenantId, off, isOn: (featureId: string) => !off.has(featureId) });\n}\n\n/** @stability Beta */\nexport interface SetTenantFeatureInput {\n tenantId: string;\n featureId: string;\n enabled: boolean;\n /** Why, in at most 500 characters. Required: it goes in the history. */\n reason: string;\n}\n\n/**\n * Turn a feature on or off for a tenant: `set_tenant_feature`. Only the\n * tenant's admins (the app's `private.genesis_tenant_admin` hook); throws a\n * `SupabaseQueryError` otherwise (`42501`), for a blank reason (`22023`) or\n * a malformed feature id (`23514`).\n *\n * @stability Beta\n */\nexport async function setTenantFeature(client: TenantFeaturesClient, input: SetTenantFeatureInput): Promise<void> {\n must(\n (await client.rpc(\"set_tenant_feature\", {\n tenant: input.tenantId,\n feature: input.featureId,\n enabled: input.enabled,\n reason: input.reason,\n })) as RpcResult,\n );\n}\n\n/** One switch a tenant has set. @stability Beta */\nexport interface TenantFeatureSetting {\n feature_id: string;\n enabled: boolean;\n reason: string;\n updated_by: string | null;\n updated_at: string;\n}\n\n/** Every switch a tenant has set, with its reason, for its admins: `tenant_feature_settings`. @stability Beta */\nexport async function tenantFeatureSettings(client: TenantFeaturesClient, tenantId: string): Promise<TenantFeatureSetting[]> {\n return (must((await client.rpc(\"tenant_feature_settings\", { tenant: tenantId })) as RpcResult) ?? []) as TenantFeatureSetting[];\n}\n\n/** One change to a tenant's switches. `enabled` is null when a switch row was deleted (back to on). @stability Beta */\nexport interface TenantFeatureChange {\n feature_id: string;\n enabled: boolean | null;\n reason: string | null;\n /** The person, or null for the service role, a migration, or a person since deleted. */\n changed_by: string | null;\n changed_role: string;\n changed_at: string;\n}\n\n/** A tenant's history of changes, newest first (at most `maxRows`, 1 to 1000, default 100), for its admins. @stability Beta */\nexport async function tenantFeatureHistory(\n client: TenantFeaturesClient,\n tenantId: string,\n options: { maxRows?: number } = {},\n): Promise<TenantFeatureChange[]> {\n const args = options.maxRows === undefined ? { tenant: tenantId } : { tenant: tenantId, max_rows: options.maxRows };\n return (must((await client.rpc(\"tenant_feature_history\", args)) as RpcResult) ?? []) as TenantFeatureChange[];\n}\n","/**\n * The feature registry in the database: the client half of\n * `migrations/0008_genesis_feature_registry.sql`. The server syncs the code\n * registry on deploy; anyone building the gate's snapshot reads a tenant's\n * runtime state in one call.\n */\n// A cycle with ./index, used only inside the functions.\nimport { must, type PostgrestErrorLike } from \"./index\";\n\n/** The parts of a Supabase client these helpers use. A `SupabaseClient` fits. */\nexport interface FeatureRegistryClient {\n // Loose on purpose, as in tenant-features: an app's generated types may not list these yet.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n rpc: (\n fn: any,\n ...rest: any[]\n ) => PromiseLike<{ data: unknown; error: PostgrestErrorLike | null }>;\n}\n\ntype RpcResult =\n { data: unknown; error: null } | { data: null; error: PostgrestErrorLike };\n\n/** A flag value as the database hands it out: the JSON an OpenFeature flag can hold. @stability Beta */\nexport type FlagStateValue = boolean | string | number | { readonly [key: string]: unknown };\n\n/**\n * A tenant's runtime state for the gate, shaped to spread into a\n * `GateContext`: `{ platform, ...await featureGateState(client, tenantId) }`.\n *\n * @stability Beta\n */\nexport interface FeatureGateState {\n /** Feature ids the tenant switched off. */\n off: string[];\n /** Feature ids with an active entitlement: the tenant's, plus the person's own (0017). */\n entitlements: string[];\n /** Flag values for the tenant (platform values applied), by flag name. */\n flags: Record<string, FlagStateValue>;\n}\n\nconst strings = (value: unknown): string[] =>\n Array.isArray(value)\n ? value.filter((v): v is string => typeof v === \"string\")\n : [];\n\n/** @stability Beta */\nexport interface FeatureGateStateOptions {\n /**\n * With the service key only: add this person's own entitlements (the app's person id, not a\n * login), for a snapshot built on the server. A signed-in person's client gets their own\n * without it, and is refused (`42501`) with it.\n */\n personId?: string;\n}\n\n/**\n * A tenant's switches, entitlements and flag values: `feature_gate_state`.\n * Works with a signed-in person's client (for tenants they belong to; their own\n * person entitlements are included) or the service key. Throws a\n * `SupabaseQueryError` (`42501`) for anyone else, so a refusal is never mistaken\n * for \"nothing set\".\n *\n * @stability Beta\n */\nexport async function featureGateState(\n client: FeatureRegistryClient,\n tenantId: string,\n options: FeatureGateStateOptions = {},\n): Promise<FeatureGateState> {\n const args = options.personId === undefined ? { tenant: tenantId } : { tenant: tenantId, person: options.personId };\n const data = must((await client.rpc(\"feature_gate_state\", args)) as RpcResult);\n // Anything but the expected shape is an error, never \"nothing set\": an empty answer would turn\n // switched-off features back on.\n if (!data || typeof data !== \"object\" || Array.isArray(data)) throw new TypeError(\"feature_gate_state returned no state\");\n const { off, entitled, flags } = data as Record<string, unknown>;\n if (!Array.isArray(off) || !Array.isArray(entitled) || !flags || typeof flags !== \"object\" || Array.isArray(flags)) {\n throw new TypeError(\"feature_gate_state returned an unexpected shape\");\n }\n const values: Record<string, FlagStateValue> = {};\n for (const [key, value] of Object.entries(flags as Record<string, unknown>)) {\n if (typeof value === \"boolean\" || typeof value === \"string\" || typeof value === \"number\") values[key] = value;\n else if (value && typeof value === \"object\" && !Array.isArray(value)) values[key] = value as { [key: string]: unknown };\n }\n return { off: strings(off), entitlements: strings(entitled), flags: values };\n}\n\n/** `features.json` as `genesis features build` writes it. @stability Beta */\nexport interface FeatureRegistryDocument {\n features: readonly ({ id: string } & Record<string, unknown>)[];\n flags?: Readonly<Record<string, Record<string, unknown>>>;\n}\n\n/** @stability Beta */\nexport interface SyncFeatureRegistryOptions {\n /**\n * This build's version: an increasing number such as the build time in milliseconds, so an old\n * production deployment (Vercel keeps VERCEL_ENV=production on every one) can't sync over a newer\n * one. Older versions than the last sync are refused.\n */\n version: number;\n /** Allow a registry that drops more than a fifth of the features (at least 3). Default false. */\n allowShrink?: boolean;\n}\n\n/** JSON with object keys sorted, so the hash doesn't depend on key order. */\nfunction canonical(value: unknown): string {\n if (Array.isArray(value)) return `[${value.map(canonical).join(\",\")}]`;\n if (value && typeof value === \"object\") {\n const entries = Object.entries(value as Record<string, unknown>).filter(\n ([, v]) => v !== undefined,\n );\n return `{${entries\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n .map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`)\n .join(\",\")}}`;\n }\n return JSON.stringify(value) ?? \"null\";\n}\n\nasync function sha256(text: string): Promise<string> {\n const digest = await globalThis.crypto.subtle.digest(\n \"SHA-256\",\n new TextEncoder().encode(text),\n );\n return Array.from(new Uint8Array(digest), (b) =>\n b.toString(16).padStart(2, \"0\"),\n ).join(\"\");\n}\n\n/**\n * Copy the registry into the database: `sync_feature_registry`. Call it with\n * the service key when a production deployment starts serving, never from a\n * preview. Returns false when the database already has this registry or a\n * newer one; throws (`22023`) for an empty registry or one that drops most\n * features, unless `allowShrink`.\n *\n * ```ts\n * import registry from \"../features.json\";\n * if (process.env.VERCEL_ENV === \"production\") await syncFeatureRegistry(admin, registry, { version: BUILD_TIME });\n * ```\n *\n * @stability Beta\n */\nexport async function syncFeatureRegistry(\n client: FeatureRegistryClient,\n document: FeatureRegistryDocument,\n options: SyncFeatureRegistryOptions,\n): Promise<boolean> {\n if (!Number.isSafeInteger(options.version) || options.version < 0) {\n throw new TypeError(\n \"syncFeatureRegistry: version must be a non-negative integer\",\n );\n }\n const features = [...document.features];\n const flags = Object.entries(document.flags ?? {}).map(([key, flag]) => ({\n key,\n ...flag,\n }));\n const hash = await sha256(canonical({ features, flags }));\n return (\n must(\n (await client.rpc(\"sync_feature_registry\", {\n version: options.version,\n hash,\n features,\n flags,\n allow_shrink: options.allowShrink ?? false,\n })) as RpcResult,\n ) === true\n );\n}\n","/**\n * Web sign-in on Supabase Auth, for genesis-ui's `AuthForm`: the calls each\n * of its modes makes (password, magic link, emailed code, sign-up, reset, new\n * password, providers, a texted code) and the provider list read from the project's\n * `/auth/v1/settings`. Platform-neutral; native sign-in is on `/native`.\n */\nimport { isAuthError, type SupabaseClient } from \"@supabase/supabase-js\";\n\n/**\n * The parts of a Supabase client {@link createAuthFormClient} uses. A `SupabaseClient` fits.\n * `getSession`, when there, gives the new-password form the signed-in email (`currentEmail`).\n */\nexport interface AuthFormSupabase {\n auth: Pick<\n SupabaseClient[\"auth\"],\n \"signInWithPassword\" | \"signInWithOtp\" | \"verifyOtp\" | \"signUp\" | \"resetPasswordForEmail\" | \"updateUser\" | \"signInWithOAuth\"\n > &\n Partial<Pick<SupabaseClient[\"auth\"], \"getSession\">>;\n}\n\n/**\n * Why a call failed: Supabase Auth's error `code` (`invalid_credentials`,\n * `otp_expired`, `over_email_send_rate_limit`…), `session_not_found` when\n * there is no session (`AuthSessionMissingError`), or `network` when the\n * request never got an answer. The shape genesis-ui's `AuthFormError` reads.\n * `message` is the server's text: the form never shows it (it is not marked\n * `displayable`), only reports it for a code it has no copy for.\n */\nexport interface AuthCallError {\n code?: string;\n message?: string;\n}\n\n/** What each call resolves with. Never throws. */\nexport interface AuthCallResult {\n error?: AuthCallError | null;\n /** From `signUp`: the account waits for its email to be confirmed. */\n confirmEmail?: boolean;\n}\n\n/**\n * The calls genesis-ui's `AuthForm` makes (its `AuthFormClient`), on Supabase Auth.\n *\n * @stability Beta\n */\nexport interface AuthFormSupabaseClient {\n signInWithPassword(input: { email: string; password: string }): Promise<AuthCallResult>;\n sendMagicLink(input: { email: string; createUser: boolean }): Promise<AuthCallResult>;\n sendEmailCode(input: { email: string; createUser: boolean }): Promise<AuthCallResult>;\n verifyEmailCode(input: { email: string; code: string }): Promise<AuthCallResult>;\n /** `data`: the new user's metadata (`options.data`, `raw_user_meta_data`), such as `full_name`. */\n signUp(input: { email: string; password: string; data?: Record<string, unknown> }): Promise<AuthCallResult>;\n sendPasswordReset(input: { email: string }): Promise<AuthCallResult>;\n updatePassword(input: { password: string }): Promise<AuthCallResult>;\n signInWithProvider(provider: string): Promise<AuthCallResult>;\n /** A code by text message (`signInWithOtp({ phone })`). Needs a phone provider in the project's Auth settings. */\n sendPhoneCode(input: { phone: string; createUser: boolean }): Promise<AuthCallResult>;\n /** Checks a texted code (`verifyOtp({ phone, token, type: \"sms\" })`). */\n verifyPhoneCode(input: { phone: string; code: string }): Promise<AuthCallResult>;\n /** The signed-in user's email, from the session the client holds (no request); null without one. Present when the Supabase client has `getSession`. */\n currentEmail?(): Promise<string | null>;\n /** Present when `url` and `publishableKey` were given. */\n providers?(): Promise<string[]>;\n}\n\n/** @stability Beta */\nexport interface CreateAuthFormClientOptions {\n /** The project URL, with `publishableKey`: lets the form discover its providers. */\n url?: string;\n /** The publishable (anon) key. */\n publishableKey?: string;\n /**\n * Where a magic link, a sign-up confirmation and a provider come back to:\n * the app's callback route (`${origin}/auth/callback`). It must be in the\n * project's redirect allow list. Left out: the project's Site URL.\n */\n redirectTo?: string;\n /** Where the emailed links come back to (a magic link, the sign-up confirmation): overrides `redirectTo` for them. Default `redirectTo`. */\n emailRedirectTo?: string;\n /** Where the password-reset link opens: the page that shows `mode=\"new-password\"`. Default `emailRedirectTo`, then `redirectTo`. */\n resetRedirectTo?: string;\n /**\n * Where a provider sends the person back to, for every provider or per provider (a function of\n * its id, `undefined` for the default): overrides `redirectTo` for providers. It must be in the\n * project's redirect allow list. Default `redirectTo`.\n */\n providerRedirectTo?: string | ((provider: string) => string | undefined);\n /**\n * Extra query parameters for the provider's authorize URL (`signInWithOAuth`'s\n * `options.queryParams`): Google's `{ access_type: \"offline\", prompt: \"consent\" }`, say. One\n * record for every provider, or a function of the provider's id. Default none.\n */\n providerQueryParams?: Record<string, string> | ((provider: string) => Record<string, string> | undefined);\n /** For the settings request. Default the global `fetch`. */\n fetch?: typeof fetch;\n}\n\ntype SupabaseAuthResult = { data?: unknown; error: { code?: string | undefined; message: string; name?: string; status?: number | undefined } | null };\n\ntype SupabaseAuthError = NonNullable<SupabaseAuthResult[\"error\"]>;\n\nfunction toResult(e: SupabaseAuthError | null): AuthCallResult {\n if (!e) return {};\n // supabase-js answers a request that never reached Auth with AuthRetryableFetchError, status 0.\n const network = e.name === \"AuthRetryableFetchError\" || e.status === 0;\n // updateUser with no session: AuthSessionMissingError, which has no code.\n const missingSession = e.name === \"AuthSessionMissingError\";\n const code = e.code ?? (missingSession ? \"session_not_found\" : network ? \"network\" : undefined);\n return { error: { ...(code ? { code } : {}), message: e.message } };\n}\n\nasync function call(run: () => Promise<SupabaseAuthResult>): Promise<AuthCallResult> {\n try {\n return toResult((await run()).error);\n } catch (e) {\n // A client made with `throwOnError: true` throws Auth's errors: read them like a returned one.\n if (isAuthError(e)) return toResult(e as SupabaseAuthError);\n return { error: { code: \"network\", message: e instanceof Error ? e.message : \"The request failed\" } };\n }\n}\n\n/**\n * genesis-ui's `AuthForm` client on Supabase Auth: password sign-in, magic\n * link and emailed code (`signInWithOtp`, the code checked with `verifyOtp`),\n * sign-up (`confirmEmail` when the project confirms emails), the reset email,\n * the new password (`updateUser`, on the session the reset link opened), and\n * OAuth providers (`signInWithOAuth`, which leaves the page; `providerRedirectTo` and\n * `providerQueryParams` shape where it goes), and a code by text message\n * (`signInWithOtp({ phone })`, checked with `verifyOtp` type `\"sms\"`). Every failure is\n * `{ error: { code, message } }`, never a throw, also on a client made with\n * `throwOnError: true`.\n *\n * It takes the app's client (from `createGenesisSupabase()`) and makes no\n * client of its own.\n *\n * Without sign-up (`createUser: false`), an email with no account is answered\n * like one with an account: the link or code is \"sent\". Saying otherwise would\n * tell anyone which emails have accounts.\n *\n * The new-password page: show `mode=\"new-password\"` only after the client's\n * `PASSWORD_RECOVERY` event (`supabase.auth.onAuthStateChange`). Without the\n * session the reset link opened, `updatePassword` fails with\n * `session_not_found`.\n *\n * One email template serves the link and the code: Supabase sends the Magic\n * Link template for both, so a form offering `\"email-code\"` needs\n * `{{ .Token }}` in it (the default template has only the link). The form's\n * `codeLength` must match the project's `otp_length`, which\n * `/auth/v1/settings` doesn't report: with a mismatch no code can be entered\n * whole, and code sign-in fails.\n *\n * ```ts\n * const client = createAuthFormClient(supabase, {\n * url: import.meta.env.VITE_SUPABASE_URL,\n * publishableKey: import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY,\n * redirectTo: `${location.origin}/auth/callback`,\n * resetRedirectTo: `${location.origin}/auth/new-password`,\n * });\n * ```\n *\n * @stability Beta\n */\nexport function createAuthFormClient(supabase: AuthFormSupabase, options: CreateAuthFormClientOptions = {}): AuthFormSupabaseClient {\n const { url, publishableKey, redirectTo, emailRedirectTo = redirectTo, resetRedirectTo = emailRedirectTo, providerRedirectTo, providerQueryParams } = options;\n const auth = supabase.auth;\n // Without sign-up, Auth refuses an unknown email with otp_disabled (\"Signups not allowed for otp\").\n // The client passes it on as it is; AuthForm answers it as sent, so it doesn't say which emails\n // have accounts (one place, for every client).\n const otp = (email: string, createUser: boolean): Promise<AuthCallResult> =>\n call(() =>\n auth.signInWithOtp({ email, options: { shouldCreateUser: createUser, ...(emailRedirectTo ? { emailRedirectTo } : {}) } }),\n );\n const client: AuthFormSupabaseClient = {\n signInWithPassword: ({ email, password }) => call(() => auth.signInWithPassword({ email, password })),\n sendMagicLink: ({ email, createUser }) => otp(email, createUser),\n sendEmailCode: ({ email, createUser }) => otp(email, createUser),\n verifyEmailCode: ({ email, code }) => call(() => auth.verifyOtp({ email, token: code, type: \"email\" })),\n signUp: async ({ email, password, data }) => {\n let confirmEmail = false;\n const signUpOptions = { ...(emailRedirectTo ? { emailRedirectTo } : {}), ...(data ? { data } : {}) };\n const result = await call(async () => {\n const r = await auth.signUp({ email, password, ...(Object.keys(signUpOptions).length ? { options: signUpOptions } : {}) });\n confirmEmail = !r.error && !r.data.session;\n return r;\n });\n return confirmEmail ? { ...result, confirmEmail } : result;\n },\n sendPasswordReset: ({ email }) =>\n call(() => auth.resetPasswordForEmail(email, resetRedirectTo ? { redirectTo: resetRedirectTo } : undefined)),\n updatePassword: ({ password }) => call(() => auth.updateUser({ password })),\n signInWithProvider: (provider) => {\n const back = (typeof providerRedirectTo === \"function\" ? providerRedirectTo(provider) : providerRedirectTo) ?? redirectTo;\n const queryParams = typeof providerQueryParams === \"function\" ? providerQueryParams(provider) : providerQueryParams;\n const oauthOptions = { ...(back ? { redirectTo: back } : {}), ...(queryParams && Object.keys(queryParams).length ? { queryParams } : {}) };\n return call(() =>\n auth.signInWithOAuth({\n provider: provider as Parameters<typeof auth.signInWithOAuth>[0][\"provider\"],\n ...(Object.keys(oauthOptions).length ? { options: oauthOptions } : {}),\n }),\n );\n },\n sendPhoneCode: ({ phone, createUser }) => call(() => auth.signInWithOtp({ phone, options: { shouldCreateUser: createUser } })),\n verifyPhoneCode: ({ phone, code }) => call(() => auth.verifyOtp({ phone, token: code, type: \"sms\" })),\n };\n const getSession = auth.getSession?.bind(auth);\n if (getSession) {\n client.currentEmail = async () => {\n try {\n return (await getSession()).data.session?.user.email ?? null;\n } catch {\n return null;\n }\n };\n }\n if (url && publishableKey) {\n // Asked once per client: the form may mount many times, the project's providers don't change.\n let providers: Promise<string[]> | undefined;\n client.providers = () => {\n providers ??= fetchAuthSettings({ url, publishableKey, ...(options.fetch ? { fetch: options.fetch } : {}) }).then(\n (settings) => settings.providers,\n (e: unknown) => {\n providers = undefined; // a failed lookup can be tried again\n throw e;\n },\n );\n return providers;\n };\n }\n return client;\n}\n\n/** What a project's Auth allows, from `/auth/v1/settings`. */\nexport interface AuthSettings {\n /** The OAuth providers turned on, as `signInWithOAuth` names them (`\"google\"`, `\"apple\"`…), sorted. */\n providers: string[];\n /** Email sign-in (password, link or code) is on. */\n email: boolean;\n /** Phone sign-in is on. */\n phone: boolean;\n /** New accounts are refused. */\n signUpDisabled: boolean;\n /** Emails are confirmed without a link. */\n autoConfirm: boolean;\n}\n\n/**\n * The OAuth providers `fetchAuthSettings` reports: the ones `signInWithOAuth`\n * takes and genesis-ui's `AUTH_PROVIDER_NAMES` names. Any other key of the\n * settings' `external` (`email`, `phone`, `saml`, `web3_*`…) isn't a button.\n *\n * @stability Beta\n */\nexport const SUPABASE_OAUTH_PROVIDERS: readonly string[] = [\n \"apple\",\n \"azure\",\n \"bitbucket\",\n \"discord\",\n \"facebook\",\n \"figma\",\n \"github\",\n \"gitlab\",\n \"google\",\n \"kakao\",\n \"keycloak\",\n \"linkedin_oidc\",\n \"notion\",\n \"slack_oidc\",\n \"spotify\",\n \"twitch\",\n \"twitter\",\n \"workos\",\n \"zoom\",\n];\nconst OAUTH_PROVIDERS = new Set(SUPABASE_OAUTH_PROVIDERS);\n\n/** How long the settings request may take. */\nconst SETTINGS_TIMEOUT_MS = 5000;\n\nfunction withoutTrailingSlashes(url: string): string {\n let end = url.length;\n while (end > 0 && url[end - 1] === \"/\") end--;\n return url.slice(0, end);\n}\n\n/**\n * Reads a project's public Auth settings (`GET <url>/auth/v1/settings` with\n * the publishable key): which OAuth providers are on, whether email and phone\n * sign-in are, and whether sign-up is closed. Throws when the request fails,\n * takes over 5 seconds or `signal` aborts it, and refuses a secret key\n * (`sb_secret_…`), which must never reach a browser.\n *\n * @stability Beta\n */\nexport async function fetchAuthSettings({\n url,\n publishableKey,\n fetch: fetcher = globalThis.fetch,\n signal,\n}: {\n url: string;\n publishableKey: string;\n fetch?: typeof fetch;\n /** Cancels the request (an unmounting form, say). */\n signal?: AbortSignal;\n}): Promise<AuthSettings> {\n if (publishableKey.startsWith(\"sb_secret_\")) {\n throw new Error(\"fetchAuthSettings takes the publishable key, not a secret key (sb_secret_…)\");\n }\n // A controller and a timer rather than AbortSignal.timeout/any, which older Safari and React\n // Native's Hermes lack.\n const controller = new AbortController();\n const timer = setTimeout(() => {\n const timedOut = new Error(\"Supabase Auth settings: timed out\");\n timedOut.name = \"TimeoutError\";\n controller.abort(timedOut);\n }, SETTINGS_TIMEOUT_MS);\n const onAbort = () => controller.abort(signal?.reason);\n if (signal?.aborted) onAbort();\n else signal?.addEventListener(\"abort\", onAbort, { once: true });\n let response: Response;\n try {\n response = await fetcher(`${withoutTrailingSlashes(url)}/auth/v1/settings`, {\n headers: { apikey: publishableKey },\n signal: controller.signal,\n });\n } finally {\n clearTimeout(timer);\n signal?.removeEventListener(\"abort\", onAbort);\n }\n if (!response.ok) throw new Error(`Supabase Auth settings: ${response.status}`);\n const body = (await response.json()) as {\n external?: Record<string, unknown>;\n disable_signup?: unknown;\n mailer_autoconfirm?: unknown;\n };\n const external = body.external ?? {};\n return {\n providers: Object.keys(external)\n .filter((key) => external[key] === true && OAUTH_PROVIDERS.has(key))\n .sort(),\n email: external.email === true,\n phone: external.phone === true,\n signUpDisabled: body.disable_signup === true,\n autoConfirm: body.mailer_autoconfirm === true,\n };\n}\n","/**\n * Supabase for Genesis apps. Platform-neutral: web, React Native and the\n * server import it. Native-only helpers (Keychain storage, foreground\n * refresh, reinstall wipe) are on `@marktiderman/genesis-supabase/native`.\n */\nimport { AuthInvalidJwtError, createClient, type SupabaseClient, type SupabaseClientOptions } from \"@supabase/supabase-js\";\nimport { APPLE_REVOKE_FUNCTION, requestAppleRevocation, type FunctionsClient } from \"./apple-tokens\";\nimport { assertPkceCrypto, claimsViaServer, installWebCrypto, isDigestOnlyPolyfill, type ExpoCryptoLike } from \"./web-crypto\";\n\nexport type { ExpoCryptoLike } from \"./web-crypto\";\nexport {\n APPLE_REVOKE_FUNCTION,\n requestAppleRevocation,\n storeAppleToken,\n type FunctionsClient,\n type StoreAppleTokenOptions,\n type StoreAppleTokenResult,\n} from \"./apple-tokens\";\n\n/** The async key-value store Supabase auth keeps its session in. */\nexport interface SessionStorage {\n getItem(key: string): Promise<string | null>;\n setItem(key: string, value: string): Promise<void>;\n removeItem(key: string): Promise<void>;\n}\n\n/** @stability Beta */\nexport interface GenesisSupabaseOptions {\n url: string;\n /** The publishable (anon) key. Never the secret key in an app. */\n publishableKey: string;\n /** Where the session lives. Native: `keychainStorage(SecureStore)`. Web: leave out for supabase-js's own default. */\n storage?: SessionStorage;\n /** `\"native\"` sets the React Native defaults (no session from the URL). Default `\"web\"`. */\n platform?: \"web\" | \"native\";\n /**\n * Read a session from the URL after an OAuth redirect. Default: `true` on\n * web, `false` on native, where the app hands the redirect URL to\n * `exchangeCodeForSession` itself.\n */\n detectSessionInUrl?: boolean;\n /**\n * `expo-crypto` (`import * as ExpoCrypto from \"expo-crypto\"`), on native.\n * Hermes has no `crypto.subtle`, and without it supabase-js sends the PKCE\n * challenge as \"plain\"; this installs `crypto.getRandomValues` and a SHA-256\n * `crypto.subtle.digest` from it (real WebCrypto is kept), so the challenge\n * is S256. A PKCE client made where there is neither throws in development\n * and logs an error in a release build. With the polyfill in place,\n * `auth.getClaims` always has the server check the token (`getUser`), as\n * supabase-js does where WebCrypto is missing: the polyfill can hash but\n * not verify a signature.\n */\n crypto?: ExpoCryptoLike;\n /** Anything else for supabase-js, merged last. */\n options?: SupabaseClientOptions<\"public\">;\n}\n\n/**\n * A Supabase client with Genesis's defaults: PKCE sign-in (the code flow, not\n * tokens in a redirect URL, with an S256 challenge: pass `crypto` on native),\n * a persisted session that refreshes itself, and\n * the session storage you pass.\n *\n * @stability Beta\n */\nexport function createGenesisSupabase<Database = unknown>({\n url,\n publishableKey,\n storage,\n platform = \"web\",\n detectSessionInUrl = platform === \"web\",\n crypto,\n options = {},\n}: GenesisSupabaseOptions): SupabaseClient<Database> {\n if (crypto) installWebCrypto(crypto);\n // The PKCE flow needs WebCrypto for an S256 challenge; never let it fall back to \"plain\" quietly.\n if ((options.auth?.flowType ?? \"pkce\") === \"pkce\") assertPkceCrypto();\n // supabase-js's generics over the schema don't survive being forwarded, so the\n // options are built untyped and the client is typed by the caller's Database.\n const client = createClient(url, publishableKey, {\n ...options,\n auth: {\n flowType: \"pkce\",\n persistSession: true,\n autoRefreshToken: true,\n detectSessionInUrl,\n ...(storage ? { storage } : {}),\n ...options.auth,\n },\n });\n if (isDigestOnlyPolyfill()) {\n const auth = client.auth;\n auth.getClaims = claimsViaServer(auth, (message) => new AuthInvalidJwtError(message)) as typeof auth.getClaims;\n }\n return client as unknown as SupabaseClient<Database>;\n}\n\n/** What a Supabase or PostgREST error carries. */\nexport interface PostgrestErrorLike {\n message: string;\n code?: string;\n details?: string | null;\n hint?: string | null;\n}\n\n/**\n * A failed query, with the database's `code` (`23505` unique violation,\n * `42501` permission denied, `PGRST116` no rows…), `details` and `hint`, so a\n * caller can tell an RLS refusal from a conflict. The original error is the\n * `cause`.\n *\n * @stability Beta\n */\nexport class SupabaseQueryError extends Error {\n override name = \"SupabaseQueryError\";\n readonly code?: string;\n readonly details?: string | null;\n readonly hint?: string | null;\n constructor(error: PostgrestErrorLike) {\n super(error.message, { cause: error });\n this.code = error.code;\n this.details = error.details;\n this.hint = error.hint;\n }\n}\n\n/**\n * The data, or a thrown {@link SupabaseQueryError}: for query results where an\n * error should fail the caller (a TanStack Query `queryFn`). The return type\n * keeps `null` when the query can return no row (`.maybeSingle()`).\n *\n * @stability Beta\n */\nexport function must<T>(result: { data: T; error: null } | { data: null; error: PostgrestErrorLike }): T {\n if (result.error) throw new SupabaseQueryError(result.error);\n return result.data as T;\n}\n\n/** The parts of a Supabase client {@link deleteMyAccount} uses. A `SupabaseClient` fits. */\nexport interface DeleteAccountClient {\n // Loose on purpose: a client typed by an app's Database narrows `rpc`'s\n // function names, and the app's generated types may not list this one yet.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n rpc: (fn: any, ...rest: any[]) => PromiseLike<{ data: unknown; error: PostgrestErrorLike | null }>;\n auth: { signOut(options?: { scope?: \"global\" | \"local\" | \"others\" }): Promise<unknown> };\n /** Needed only with `revokeAppleTokens`. */\n functions?: FunctionsClient[\"functions\"];\n}\n\n/** @stability Beta */\nexport interface DeleteMyAccountOptions {\n /**\n * After the delete, ask the `genesis-apple-revoke` Edge Function to revoke\n * the person's Sign in with Apple tokens now (`true`, or the function's\n * name). Best effort: the delete has already queued them and the\n * function's schedule retries, so a failure here never fails the call.\n */\n revokeAppleTokens?: boolean | string;\n}\n\n/**\n * In-app account deletion (App Store Review Guideline 5.1.1(v)), on web and\n * native: calls the `delete_my_account` RPC (this package's\n * `migrations/0001_genesis_account_deletion.sql`), which deletes the login\n * and, through the app's `on delete cascade` foreign keys, its data; then\n * clears the session on this device. Throws a {@link SupabaseQueryError} when\n * the database refuses (`42501`: not signed in) and keeps the session then.\n *\n * With Sign in with Apple, ship the `genesis-apple-revoke` function and\n * migration 0003 and pass `{ revokeAppleTokens: true }`: App Review requires\n * the person's Apple tokens to be revoked.\n *\n * Put it behind a confirmation; see the README.\n *\n * @stability Beta\n */\nexport async function deleteMyAccount(client: DeleteAccountClient, options: DeleteMyAccountOptions = {}): Promise<void> {\n must((await client.rpc(\"delete_my_account\")) as { data: unknown; error: null } | { data: null; error: PostgrestErrorLike });\n const revoke = options.revokeAppleTokens;\n // The function needs no login (it works through the queue the delete just filled), so this runs after it.\n if (revoke && client.functions) await requestAppleRevocation({ functions: client.functions }, typeof revoke === \"string\" ? revoke : APPLE_REVOKE_FUNCTION);\n // The login is gone and its refresh tokens with it: only this device's copy is left to clear.\n await client.auth.signOut({ scope: \"local\" });\n}\nexport {\n tenantFeatures,\n setTenantFeature,\n tenantFeatureSettings,\n tenantFeatureHistory,\n type SetTenantFeatureInput,\n type TenantFeatureChange,\n type TenantFeatureSetting,\n type TenantFeatures,\n type TenantFeaturesClient,\n} from \"./tenant-features\";\nexport {\n featureGateState,\n syncFeatureRegistry,\n type FeatureGateState,\n type FeatureGateStateOptions,\n type FlagStateValue,\n type FeatureRegistryClient,\n type FeatureRegistryDocument,\n type SyncFeatureRegistryOptions,\n} from \"./feature-registry\";\nexport { accountBlock, eventsBlock, featureMirrorBlock, jobsBlock, tenantFeaturesBlock, versionedWritesBlock } from \"./blocks\";\nexport {\n createAuthFormClient,\n fetchAuthSettings,\n SUPABASE_OAUTH_PROVIDERS,\n type AuthCallError,\n type AuthCallResult,\n type AuthFormSupabase,\n type AuthFormSupabaseClient,\n type AuthSettings,\n type CreateAuthFormClientOptions,\n} from \"./auth-form-client\";\n"]}
1
+ {"version":3,"sources":["../src/apple-tokens.ts","../src/settings.ts","../src/tenant-features.ts","../src/feature-registry.ts","../src/auth-form-client.ts","../src/index.ts"],"names":[],"mappings":";;;;;;AASO,IAAM,qBAAA,GAAwB;AAGrC,IAAM,gBAAA,GAAmB,GAAA;AAEzB,IAAM,iBAAA,GAAoB,GAAA;AAiC1B,eAAsB,gBAAgB,MAAA,EAAyB,EAAE,mBAAmB,QAAA,EAAU,YAAA,GAAe,uBAAsB,EAA2D;AAC5L,EAAA,IAAI;AACF,IAAA,MAAM,EAAE,KAAA,EAAM,GAAI,MAAM,MAAA,CAAO,UAAU,MAAA,CAAO,YAAA,EAAc,EAAE,IAAA,EAAM,EAAE,MAAA,EAAQ,SAAS,IAAA,EAAM,iBAAA,EAAmB,GAAI,QAAA,GAAW,EAAE,QAAA,EAAS,GAAI,EAAC,EAAG,EAAG,OAAA,EAAS,gBAAA,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Y,KAAA,EAA2B;AACrC,IAAA,KAAA,CAAM,KAAA,CAAM,OAAA,EAAS,EAAE,KAAA,EAAO,OAAO,CAAA;AACrC,IAAA,IAAA,CAAK,OAAO,KAAA,CAAM,IAAA;AAClB,IAAA,IAAA,CAAK,UAAU,KAAA,CAAM,OAAA;AACrB,IAAA,IAAA,CAAK,OAAO,KAAA,CAAM,IAAA;AAAA,EACpB;AACF;AASO,SAAS,KAAQ,MAAA,EAAiF;AACvG,EAAA,IAAI,OAAO,KAAA,EAAO,MAAM,IAAI,kBAAA,CAAmB,OAAO,KAAK,CAAA;AAC3D,EAAA,OAAO,MAAA,CAAO,IAAA;AAChB;AAwCA,eAAsB,eAAA,CAAgB,MAAA,EAA6B,OAAA,GAAkC,EAAC,EAAkB;AACtH,EAAA,IAAA,CAAM,MAAM,MAAA,CAAO,GAAA,CAAI,mBAAmB,CAAgF,CAAA;AAC1H,EAAA,MAAM,SAAS,OAAA,CAAQ,iBAAA;AAEvB,EAAA,IAAI,MAAA,IAAU,MAAA,CAAO,SAAA,EAAW,MAAM,uBAAuB,EAAE,SAAA,EAAW,MAAA,CAAO,SAAA,EAAU,EAAG,OAAO,MAAA,KAAW,QAAA,GAAW,SAAS,qBAAqB,CAAA;AAEzJ,EAAA,MAAM,OAAO,IAAA,CAAK,OAAA,CAAQ,EAAE,KAAA,EAAO,SAAS,CAAA;AAC9C","file":"index.js","sourcesContent":["/**\n * The app's side of Sign in with Apple token revocation: hand the sign-in's\n * authorization code to the `genesis-apple-revoke` Edge Function (it keeps\n * Apple's refresh token server-side), and ask it to revoke after the account\n * is deleted. The function and its migration ship in this package; see the\n * README (\"Revoking Apple's tokens\").\n */\n\n/** The Edge Function's default name, as shipped in `functions/genesis-apple-revoke`. */\nexport const APPLE_REVOKE_FUNCTION = \"genesis-apple-revoke\";\n\n/** The store call waits on Apple's token endpoint (10 s timeout in the function). */\nconst STORE_TIMEOUT_MS = 20_000;\n/** The function answers the revoke call at once and works in the background; don't hold the delete screen for longer. */\nconst REVOKE_TIMEOUT_MS = 5_000;\n\n/** The parts of a Supabase client these helpers use. A `SupabaseClient` fits. */\nexport interface FunctionsClient {\n functions: {\n // Loose on purpose, so any supabase-js version's `invoke` fits.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n invoke: (name: string, options?: any) => PromiseLike<{ data: unknown; error: unknown }>;\n };\n}\n\n/** @stability Beta */\nexport interface StoreAppleTokenOptions {\n /** `authorizationCode` from `signInWithApple`'s result. Single-use, valid for five minutes: send it straight after sign-in. */\n authorizationCode: string;\n /** The client id the code was issued for: your bundle id on iOS. Must be in the function's APPLE_CLIENT_IDS; default its first. */\n clientId?: string;\n /** The Edge Function's name. Default `genesis-apple-revoke`. */\n functionName?: string;\n}\n\n/** @stability Beta */\nexport type StoreAppleTokenResult = { ok: true } | { ok: false; error: Error };\n\n/**\n * After a Sign in with Apple, sends the authorization code to the Edge\n * Function, which exchanges it for Apple's refresh token and keeps it where\n * only the server reads it, so deleting the account can revoke it. Call it\n * with the session from that sign-in. Never throws: the person is signed in\n * either way, so log a failure rather than showing it.\n *\n * @stability Beta\n */\nexport async function storeAppleToken(client: FunctionsClient, { authorizationCode, clientId, functionName = APPLE_REVOKE_FUNCTION }: StoreAppleTokenOptions): Promise<StoreAppleTokenResult> {\n try {\n const { error } = await client.functions.invoke(functionName, { body: { action: \"store\", code: authorizationCode, ...(clientId ? { clientId } : {}) }, timeout: STORE_TIMEOUT_MS });\n if (error) return { ok: false, error: error instanceof Error ? error : new Error(String((error as { message?: unknown }).message ?? error)) };\n return { ok: true };\n } catch (error) {\n return { ok: false, error: error instanceof Error ? error : new Error(String(error)) };\n }\n}\n\n/**\n * Asks the Edge Function to revoke the tokens of deleted accounts now, rather\n * than at its next scheduled run. Never throws and never fails the caller:\n * the account is already gone and the queue keeps the token until a run\n * succeeds.\n */\nexport async function requestAppleRevocation(client: FunctionsClient, functionName = APPLE_REVOKE_FUNCTION): Promise<boolean> {\n try {\n const { error } = await client.functions.invoke(functionName, { body: { action: \"revoke\" }, timeout: REVOKE_TIMEOUT_MS });\n return !error;\n } catch {\n return false;\n }\n}\n","/**\n * Genesis settings: the client half of `migrations/0020_genesis_settings.sql`. Read the layers the\n * database holds and resolve them with genesis-config's `resolveSettings` (the one resolver, on\n * every platform); platform admins set, lock and clear runtime settings; the service role writes\n * the app manifest (with the catalogue the database checks values against) on deploy.\n */\nimport {\n catalogueManifest,\n resolveSettings,\n settingsLayerFromFile,\n type ResolvedSettings,\n type SettingsCatalogue,\n type SettingsLayerValues,\n type SettingsLayers,\n type SettingsPreset,\n} from \"@marktiderman/genesis-config/settings\";\n// A cycle with ./index, used only inside the functions.\nimport { must, type PostgrestErrorLike } from \"./index\";\n\n/** The parts of a Supabase client these helpers use. A `SupabaseClient` fits. */\nexport interface SettingsClient {\n // Loose on purpose: a client typed by an app's Database narrows `rpc`'s function names, and the\n // app's generated types may not list these yet.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n rpc: (fn: any, ...rest: any[]) => PromiseLike<{ data: unknown; error: PostgrestErrorLike | null }>;\n}\n\n/** The service-role client {@link writeAppManifest} writes with. */\nexport interface ManifestClient {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n from: (table: any) => { upsert: (row: any, options?: any) => PromiseLike<{ error: PostgrestErrorLike | null }> };\n}\n\ntype RpcResult = { data: unknown; error: null } | { data: null; error: PostgrestErrorLike };\n\n/**\n * What `genesis_settings_layers` returns: the layers to resolve (not resolved values): the preset,\n * the file's settings for every declared key (build-time keys too) and the database layer for runtime keys.\n *\n * @stability Beta\n */\nexport interface StoredSettingsLayers {\n preset: SettingsPreset;\n file: SettingsLayerValues;\n database: SettingsLayerValues;\n /** When the manifest was last written; null before the first deploy wrote it. */\n reportedAt: string | null;\n}\n\nconst PRESETS: readonly string[] = [\"max\", \"standard\", \"min\"];\n\nfunction isObject(v: unknown): v is Record<string, unknown> {\n return typeof v === \"object\" && v !== null && !Array.isArray(v);\n}\n\n/**\n * The preset, the file's settings and the database layer, for any signed-in person or server code:\n * `genesis_settings_layers`. Throws a `SupabaseQueryError` (`42501`) when nobody is signed in.\n *\n * @stability Beta\n */\nexport async function readSettingsLayers(client: SettingsClient): Promise<StoredSettingsLayers> {\n const data = must((await client.rpc(\"genesis_settings_layers\")) as RpcResult);\n const raw = isObject(data) ? data : {};\n const database: Record<string, { value: unknown; locked?: boolean }> = {};\n for (const [key, entry] of Object.entries(isObject(raw.database) ? raw.database : {})) {\n if (!isObject(entry) || !(\"value\" in entry)) continue;\n database[key] = entry.locked === true ? { value: entry.value, locked: true } : { value: entry.value };\n }\n return {\n preset: (typeof raw.preset === \"string\" && PRESETS.includes(raw.preset) ? raw.preset : \"max\") as SettingsPreset,\n file: settingsLayerFromFile(isObject(raw.file) ? raw.file : {}),\n database,\n reportedAt: typeof raw.reportedAt === \"string\" ? raw.reportedAt : null,\n };\n}\n\n/** @stability Beta */\nexport interface ResolveAppSettingsOptions {\n /** The tenant's values (keys declared `scope: \"tenant\"`), from wherever the app keeps them. */\n tenant?: SettingsLayerValues;\n /** The person's values (keys declared `scope: \"person\"`). */\n person?: SettingsLayerValues;\n /**\n * The layers the build itself carries (the preset and genesis.config.json `settings`); when given,\n * they replace the stored preset and file layer (the stored ones are what the last deploy wrote).\n */\n build?: Pick<SettingsLayers, \"preset\" | \"file\">;\n}\n\n/**\n * Read the stored layers and resolve them with the app's catalogue: values, where each came from,\n * and what was wrong.\n *\n * ```ts\n * const settings = await resolveAppSettings(supabase, catalogue, { person: myPreferences });\n * settings.values[\"support.messenger\"]; // true\n * ```\n *\n * @stability Beta\n */\nexport async function resolveAppSettings(client: SettingsClient, catalogue: SettingsCatalogue, options: ResolveAppSettingsOptions = {}): Promise<ResolvedSettings> {\n const stored = await readSettingsLayers(client);\n return resolveSettings(catalogue, {\n preset: options.build?.preset ?? stored.preset,\n file: options.build?.file ?? stored.file,\n database: stored.database,\n ...(options.tenant ? { tenant: options.tenant } : {}),\n ...(options.person ? { person: options.person } : {}),\n });\n}\n\n/** @stability Beta */\nexport interface SetGenesisSettingInput {\n /** `namespace.key`, a runtime key the catalogue declares. */\n key: string;\n /** The value; `null` for \"not set\". */\n value: unknown;\n /** Lock it, so tenant and person values can't change it. Default false. */\n locked?: boolean;\n}\n\n/**\n * Set a runtime setting in the database layer: `set_genesis_setting`. Only platform admins (the\n * app's `private.genesis_platform_admin` hook); throws a `SupabaseQueryError` otherwise (`42501`),\n * or for a value the synced catalogue refuses (`22023`: an unknown or build-time key, one\n * genesis.config.json locks, the wrong type, out of bounds, or `null` for a key with a default).\n *\n * @stability Beta\n */\nexport async function setGenesisSetting(client: SettingsClient, input: SetGenesisSettingInput): Promise<void> {\n must((await client.rpc(\"set_genesis_setting\", { key: input.key, value: input.value === undefined ? null : input.value, locked: input.locked ?? false })) as RpcResult);\n}\n\n/** Remove a setting from the database layer, so the file, preset or default applies again: `clear_genesis_setting`. Platform admins only. @stability Beta */\nexport async function clearGenesisSetting(client: SettingsClient, key: string): Promise<void> {\n must((await client.rpc(\"clear_genesis_setting\", { key })) as RpcResult);\n}\n\n/** One change to the database layer. A null `new_value` with `new_locked` null is a cleared setting. @stability Beta */\nexport interface GenesisSettingChange {\n key: string;\n old_value: unknown;\n new_value: unknown;\n old_locked: boolean | null;\n new_locked: boolean | null;\n /** The person, or null for the service role, a migration, or a person since deleted. */\n changed_by: string | null;\n changed_role: string;\n source: \"admin\" | \"wizard\" | \"cli\" | \"central\" | \"server\" | \"database\";\n changed_at: string;\n}\n\n/** The database layer's history, newest first (at most `maxRows`, 1 to 1000, default 100). Platform admins only. @stability Beta */\nexport async function genesisSettingHistory(client: SettingsClient, options: { maxRows?: number } = {}): Promise<GenesisSettingChange[]> {\n const args = options.maxRows === undefined ? {} : { max_rows: options.maxRows };\n return (must((await client.rpc(\"genesis_setting_history\", args)) as RpcResult) ?? []) as GenesisSettingChange[];\n}\n\n/** What this app runs, written on deploy and at app start. @stability Beta */\nexport interface AppManifestInput {\n /** The app's slug (`sample-app`). */\n appId: string;\n name?: string;\n /** Package → version, from genesis.lock.json. */\n packages?: Record<string, string>;\n preset?: SettingsPreset;\n configHash?: string;\n /** genesis.config.json `settings`, as written. */\n fileSettings?: Record<string, unknown>;\n /** The app's catalogue: the database checks platform admins' values against it. */\n catalogue: SettingsCatalogue;\n}\n\n/**\n * Write the app manifest (one row) with the service-role client, on deploy and at app start. It\n * carries the catalogue `set_genesis_setting` validates against: until it's written, no setting\n * can be changed. Server only: never with a browser's client.\n *\n * @stability Beta\n */\nexport async function writeAppManifest(admin: ManifestClient, input: AppManifestInput): Promise<void> {\n const row = {\n app_id: input.appId,\n name: input.name ?? null,\n packages: input.packages ?? {},\n preset: input.preset ?? \"max\",\n config_hash: input.configHash ?? null,\n file_settings: input.fileSettings ?? {},\n catalogue: catalogueManifest(input.catalogue),\n reported_at: new Date().toISOString(),\n };\n // One row: an app that changed its id replaces the old row (the `one` column is unique).\n const { error } = await admin.from(\"genesis_app_manifest\").upsert(row, { onConflict: \"one\" });\n must({ data: null, error } as RpcResult);\n}\n","/**\n * Tenant features: the client half of `migrations/0004_genesis_tenant_features.sql`.\n * A tenant's admins turn a shipped feature off (or back on) for their tenant,\n * with a reason; its members read which ids are off and hide them.\n *\n * Exposure only: a switch hides a feature, it never grants or denies access\n * to data (that is RLS) and never sells it (that is an entitlement).\n */\n// A cycle with ./index, used only inside the functions.\nimport { must, type PostgrestErrorLike } from \"./index\";\n\n/** The parts of a Supabase client these helpers use. A `SupabaseClient` fits. */\nexport interface TenantFeaturesClient {\n // Loose on purpose: a client typed by an app's Database narrows `rpc`'s\n // function names, and the app's generated types may not list these yet.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n rpc: (fn: any, ...rest: any[]) => PromiseLike<{ data: unknown; error: PostgrestErrorLike | null }>;\n}\n\ntype RpcResult = { data: unknown; error: null } | { data: null; error: PostgrestErrorLike };\n\n/** Which features a tenant has turned off. A feature not in `off` is on. @stability Beta */\nexport interface TenantFeatures {\n readonly tenantId: string;\n readonly off: ReadonlySet<string>;\n isOn(featureId: string): boolean;\n}\n\n/**\n * The features `tenantId` has turned off, for one of its members (or\n * admins): `tenant_features_off`. Throws a `SupabaseQueryError` (`42501`)\n * for anyone else, so a refusal is never mistaken for \"everything on\".\n *\n * ```ts\n * const features = await tenantFeatures(supabase, teamId);\n * if (features.isOn(\"chat\")) showChatTab();\n * ```\n *\n * @stability Beta\n */\nexport async function tenantFeatures(client: TenantFeaturesClient, tenantId: string): Promise<TenantFeatures> {\n const data = must((await client.rpc(\"tenant_features_off\", { tenant: tenantId })) as RpcResult);\n const off = new Set(Array.isArray(data) ? data.filter((id): id is string => typeof id === \"string\") : []);\n return Object.freeze({ tenantId, off, isOn: (featureId: string) => !off.has(featureId) });\n}\n\n/** @stability Beta */\nexport interface SetTenantFeatureInput {\n tenantId: string;\n featureId: string;\n enabled: boolean;\n /** Why, in at most 500 characters. Required: it goes in the history. */\n reason: string;\n}\n\n/**\n * Turn a feature on or off for a tenant: `set_tenant_feature`. Only the\n * tenant's admins (the app's `private.genesis_tenant_admin` hook); throws a\n * `SupabaseQueryError` otherwise (`42501`), for a blank reason (`22023`) or\n * a malformed feature id (`23514`).\n *\n * @stability Beta\n */\nexport async function setTenantFeature(client: TenantFeaturesClient, input: SetTenantFeatureInput): Promise<void> {\n must(\n (await client.rpc(\"set_tenant_feature\", {\n tenant: input.tenantId,\n feature: input.featureId,\n enabled: input.enabled,\n reason: input.reason,\n })) as RpcResult,\n );\n}\n\n/** One switch a tenant has set. @stability Beta */\nexport interface TenantFeatureSetting {\n feature_id: string;\n enabled: boolean;\n reason: string;\n updated_by: string | null;\n updated_at: string;\n}\n\n/** Every switch a tenant has set, with its reason, for its admins: `tenant_feature_settings`. @stability Beta */\nexport async function tenantFeatureSettings(client: TenantFeaturesClient, tenantId: string): Promise<TenantFeatureSetting[]> {\n return (must((await client.rpc(\"tenant_feature_settings\", { tenant: tenantId })) as RpcResult) ?? []) as TenantFeatureSetting[];\n}\n\n/** One change to a tenant's switches. `enabled` is null when a switch row was deleted (back to on). @stability Beta */\nexport interface TenantFeatureChange {\n feature_id: string;\n enabled: boolean | null;\n reason: string | null;\n /** The person, or null for the service role, a migration, or a person since deleted. */\n changed_by: string | null;\n changed_role: string;\n changed_at: string;\n}\n\n/** A tenant's history of changes, newest first (at most `maxRows`, 1 to 1000, default 100), for its admins. @stability Beta */\nexport async function tenantFeatureHistory(\n client: TenantFeaturesClient,\n tenantId: string,\n options: { maxRows?: number } = {},\n): Promise<TenantFeatureChange[]> {\n const args = options.maxRows === undefined ? { tenant: tenantId } : { tenant: tenantId, max_rows: options.maxRows };\n return (must((await client.rpc(\"tenant_feature_history\", args)) as RpcResult) ?? []) as TenantFeatureChange[];\n}\n","/**\n * The feature registry in the database: the client half of\n * `migrations/0008_genesis_feature_registry.sql`. The server syncs the code\n * registry on deploy; anyone building the gate's snapshot reads a tenant's\n * runtime state in one call.\n */\n// A cycle with ./index, used only inside the functions.\nimport { must, type PostgrestErrorLike } from \"./index\";\n\n/** The parts of a Supabase client these helpers use. A `SupabaseClient` fits. */\nexport interface FeatureRegistryClient {\n // Loose on purpose, as in tenant-features: an app's generated types may not list these yet.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n rpc: (\n fn: any,\n ...rest: any[]\n ) => PromiseLike<{ data: unknown; error: PostgrestErrorLike | null }>;\n}\n\ntype RpcResult =\n { data: unknown; error: null } | { data: null; error: PostgrestErrorLike };\n\n/** A flag value as the database hands it out: the JSON an OpenFeature flag can hold. @stability Beta */\nexport type FlagStateValue = boolean | string | number | { readonly [key: string]: unknown };\n\n/**\n * A tenant's runtime state for the gate, shaped to spread into a\n * `GateContext`: `{ platform, ...await featureGateState(client, tenantId) }`.\n *\n * @stability Beta\n */\nexport interface FeatureGateState {\n /** Feature ids the tenant switched off. */\n off: string[];\n /** Feature ids with an active entitlement: the tenant's, plus the person's own (0017). */\n entitlements: string[];\n /** Flag values for the tenant (platform values applied), by flag name. */\n flags: Record<string, FlagStateValue>;\n}\n\nconst strings = (value: unknown): string[] =>\n Array.isArray(value)\n ? value.filter((v): v is string => typeof v === \"string\")\n : [];\n\n/** @stability Beta */\nexport interface FeatureGateStateOptions {\n /**\n * With the service key only: add this person's own entitlements (the app's person id, not a\n * login), for a snapshot built on the server. A signed-in person's client gets their own\n * without it, and is refused (`42501`) with it.\n */\n personId?: string;\n}\n\n/**\n * A tenant's switches, entitlements and flag values: `feature_gate_state`.\n * Works with a signed-in person's client (for tenants they belong to; their own\n * person entitlements are included) or the service key. Throws a\n * `SupabaseQueryError` (`42501`) for anyone else, so a refusal is never mistaken\n * for \"nothing set\".\n *\n * @stability Beta\n */\nexport async function featureGateState(\n client: FeatureRegistryClient,\n tenantId: string,\n options: FeatureGateStateOptions = {},\n): Promise<FeatureGateState> {\n const args = options.personId === undefined ? { tenant: tenantId } : { tenant: tenantId, person: options.personId };\n const data = must((await client.rpc(\"feature_gate_state\", args)) as RpcResult);\n // Anything but the expected shape is an error, never \"nothing set\": an empty answer would turn\n // switched-off features back on.\n if (!data || typeof data !== \"object\" || Array.isArray(data)) throw new TypeError(\"feature_gate_state returned no state\");\n const { off, entitled, flags } = data as Record<string, unknown>;\n if (!Array.isArray(off) || !Array.isArray(entitled) || !flags || typeof flags !== \"object\" || Array.isArray(flags)) {\n throw new TypeError(\"feature_gate_state returned an unexpected shape\");\n }\n const values: Record<string, FlagStateValue> = {};\n for (const [key, value] of Object.entries(flags as Record<string, unknown>)) {\n if (typeof value === \"boolean\" || typeof value === \"string\" || typeof value === \"number\") values[key] = value;\n else if (value && typeof value === \"object\" && !Array.isArray(value)) values[key] = value as { [key: string]: unknown };\n }\n return { off: strings(off), entitlements: strings(entitled), flags: values };\n}\n\n/** `features.json` as `genesis features build` writes it. @stability Beta */\nexport interface FeatureRegistryDocument {\n features: readonly ({ id: string } & Record<string, unknown>)[];\n flags?: Readonly<Record<string, Record<string, unknown>>>;\n}\n\n/** @stability Beta */\nexport interface SyncFeatureRegistryOptions {\n /**\n * This build's version: an increasing number such as the build time in milliseconds, so an old\n * production deployment (Vercel keeps VERCEL_ENV=production on every one) can't sync over a newer\n * one. Older versions than the last sync are refused.\n */\n version: number;\n /** Allow a registry that drops more than a fifth of the features (at least 3). Default false. */\n allowShrink?: boolean;\n}\n\n/** JSON with object keys sorted, so the hash doesn't depend on key order. */\nfunction canonical(value: unknown): string {\n if (Array.isArray(value)) return `[${value.map(canonical).join(\",\")}]`;\n if (value && typeof value === \"object\") {\n const entries = Object.entries(value as Record<string, unknown>).filter(\n ([, v]) => v !== undefined,\n );\n return `{${entries\n .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))\n .map(([k, v]) => `${JSON.stringify(k)}:${canonical(v)}`)\n .join(\",\")}}`;\n }\n return JSON.stringify(value) ?? \"null\";\n}\n\nasync function sha256(text: string): Promise<string> {\n const digest = await globalThis.crypto.subtle.digest(\n \"SHA-256\",\n new TextEncoder().encode(text),\n );\n return Array.from(new Uint8Array(digest), (b) =>\n b.toString(16).padStart(2, \"0\"),\n ).join(\"\");\n}\n\n/**\n * Copy the registry into the database: `sync_feature_registry`. Call it with\n * the service key when a production deployment starts serving, never from a\n * preview. Returns false when the database already has this registry or a\n * newer one; throws (`22023`) for an empty registry or one that drops most\n * features, unless `allowShrink`.\n *\n * ```ts\n * import registry from \"../features.json\";\n * if (process.env.VERCEL_ENV === \"production\") await syncFeatureRegistry(admin, registry, { version: BUILD_TIME });\n * ```\n *\n * @stability Beta\n */\nexport async function syncFeatureRegistry(\n client: FeatureRegistryClient,\n document: FeatureRegistryDocument,\n options: SyncFeatureRegistryOptions,\n): Promise<boolean> {\n if (!Number.isSafeInteger(options.version) || options.version < 0) {\n throw new TypeError(\n \"syncFeatureRegistry: version must be a non-negative integer\",\n );\n }\n const features = [...document.features];\n const flags = Object.entries(document.flags ?? {}).map(([key, flag]) => ({\n key,\n ...flag,\n }));\n const hash = await sha256(canonical({ features, flags }));\n return (\n must(\n (await client.rpc(\"sync_feature_registry\", {\n version: options.version,\n hash,\n features,\n flags,\n allow_shrink: options.allowShrink ?? false,\n })) as RpcResult,\n ) === true\n );\n}\n","/**\n * Web sign-in on Supabase Auth, for genesis-ui's `AuthForm`: the calls each\n * of its modes makes (password, magic link, emailed code, sign-up, reset, new\n * password, providers, a texted code) and the provider list read from the project's\n * `/auth/v1/settings`. Platform-neutral; native sign-in is on `/native`.\n */\nimport { isAuthError, type SupabaseClient } from \"@supabase/supabase-js\";\n\n/**\n * The parts of a Supabase client {@link createAuthFormClient} uses. A `SupabaseClient` fits.\n * `getSession`, when there, gives the new-password form the signed-in email (`currentEmail`).\n */\nexport interface AuthFormSupabase {\n auth: Pick<\n SupabaseClient[\"auth\"],\n \"signInWithPassword\" | \"signInWithOtp\" | \"verifyOtp\" | \"signUp\" | \"resetPasswordForEmail\" | \"updateUser\" | \"signInWithOAuth\"\n > &\n Partial<Pick<SupabaseClient[\"auth\"], \"getSession\">>;\n}\n\n/**\n * Why a call failed: Supabase Auth's error `code` (`invalid_credentials`,\n * `otp_expired`, `over_email_send_rate_limit`…), `session_not_found` when\n * there is no session (`AuthSessionMissingError`), or `network` when the\n * request never got an answer. The shape genesis-ui's `AuthFormError` reads.\n * `message` is the server's text: the form never shows it (it is not marked\n * `displayable`), only reports it for a code it has no copy for.\n */\nexport interface AuthCallError {\n code?: string;\n message?: string;\n}\n\n/** What each call resolves with. Never throws. */\nexport interface AuthCallResult {\n error?: AuthCallError | null;\n /** From `signUp`: the account waits for its email to be confirmed. */\n confirmEmail?: boolean;\n}\n\n/**\n * The calls genesis-ui's `AuthForm` makes (its `AuthFormClient`), on Supabase Auth.\n *\n * @stability Beta\n */\nexport interface AuthFormSupabaseClient {\n signInWithPassword(input: { email: string; password: string }): Promise<AuthCallResult>;\n sendMagicLink(input: { email: string; createUser: boolean }): Promise<AuthCallResult>;\n sendEmailCode(input: { email: string; createUser: boolean }): Promise<AuthCallResult>;\n verifyEmailCode(input: { email: string; code: string }): Promise<AuthCallResult>;\n /** `data`: the new user's metadata (`options.data`, `raw_user_meta_data`), such as `full_name`. */\n signUp(input: { email: string; password: string; data?: Record<string, unknown> }): Promise<AuthCallResult>;\n sendPasswordReset(input: { email: string }): Promise<AuthCallResult>;\n updatePassword(input: { password: string }): Promise<AuthCallResult>;\n signInWithProvider(provider: string): Promise<AuthCallResult>;\n /** A code by text message (`signInWithOtp({ phone })`). Needs a phone provider in the project's Auth settings. */\n sendPhoneCode(input: { phone: string; createUser: boolean }): Promise<AuthCallResult>;\n /** Checks a texted code (`verifyOtp({ phone, token, type: \"sms\" })`). */\n verifyPhoneCode(input: { phone: string; code: string }): Promise<AuthCallResult>;\n /** The signed-in user's email, from the session the client holds (no request); null without one. Present when the Supabase client has `getSession`. */\n currentEmail?(): Promise<string | null>;\n /** Present when `url` and `publishableKey` were given. */\n providers?(): Promise<string[]>;\n}\n\n/** @stability Beta */\nexport interface CreateAuthFormClientOptions {\n /** The project URL, with `publishableKey`: lets the form discover its providers. */\n url?: string;\n /** The publishable (anon) key. */\n publishableKey?: string;\n /**\n * Where a magic link, a sign-up confirmation and a provider come back to:\n * the app's callback route (`${origin}/auth/callback`). It must be in the\n * project's redirect allow list. Left out: the project's Site URL.\n */\n redirectTo?: string;\n /** Where the emailed links come back to (a magic link, the sign-up confirmation): overrides `redirectTo` for them. Default `redirectTo`. */\n emailRedirectTo?: string;\n /** Where the password-reset link opens: the page that shows `mode=\"new-password\"`. Default `emailRedirectTo`, then `redirectTo`. */\n resetRedirectTo?: string;\n /**\n * Where a provider sends the person back to, for every provider or per provider (a function of\n * its id, `undefined` for the default): overrides `redirectTo` for providers. It must be in the\n * project's redirect allow list. Default `redirectTo`.\n */\n providerRedirectTo?: string | ((provider: string) => string | undefined);\n /**\n * Extra query parameters for the provider's authorize URL (`signInWithOAuth`'s\n * `options.queryParams`): Google's `{ access_type: \"offline\", prompt: \"consent\" }`, say. One\n * record for every provider, or a function of the provider's id. Default none.\n */\n providerQueryParams?: Record<string, string> | ((provider: string) => Record<string, string> | undefined);\n /** For the settings request. Default the global `fetch`. */\n fetch?: typeof fetch;\n}\n\ntype SupabaseAuthResult = { data?: unknown; error: { code?: string | undefined; message: string; name?: string; status?: number | undefined } | null };\n\ntype SupabaseAuthError = NonNullable<SupabaseAuthResult[\"error\"]>;\n\nfunction toResult(e: SupabaseAuthError | null): AuthCallResult {\n if (!e) return {};\n // supabase-js answers a request that never reached Auth with AuthRetryableFetchError, status 0.\n const network = e.name === \"AuthRetryableFetchError\" || e.status === 0;\n // updateUser with no session: AuthSessionMissingError, which has no code.\n const missingSession = e.name === \"AuthSessionMissingError\";\n const code = e.code ?? (missingSession ? \"session_not_found\" : network ? \"network\" : undefined);\n return { error: { ...(code ? { code } : {}), message: e.message } };\n}\n\nasync function call(run: () => Promise<SupabaseAuthResult>): Promise<AuthCallResult> {\n try {\n return toResult((await run()).error);\n } catch (e) {\n // A client made with `throwOnError: true` throws Auth's errors: read them like a returned one.\n if (isAuthError(e)) return toResult(e as SupabaseAuthError);\n return { error: { code: \"network\", message: e instanceof Error ? e.message : \"The request failed\" } };\n }\n}\n\n/**\n * genesis-ui's `AuthForm` client on Supabase Auth: password sign-in, magic\n * link and emailed code (`signInWithOtp`, the code checked with `verifyOtp`),\n * sign-up (`confirmEmail` when the project confirms emails), the reset email,\n * the new password (`updateUser`, on the session the reset link opened), and\n * OAuth providers (`signInWithOAuth`, which leaves the page; `providerRedirectTo` and\n * `providerQueryParams` shape where it goes), and a code by text message\n * (`signInWithOtp({ phone })`, checked with `verifyOtp` type `\"sms\"`). Every failure is\n * `{ error: { code, message } }`, never a throw, also on a client made with\n * `throwOnError: true`.\n *\n * It takes the app's client (from `createGenesisSupabase()`) and makes no\n * client of its own.\n *\n * Without sign-up (`createUser: false`), an email with no account is answered\n * like one with an account: the link or code is \"sent\". Saying otherwise would\n * tell anyone which emails have accounts.\n *\n * The new-password page: show `mode=\"new-password\"` only after the client's\n * `PASSWORD_RECOVERY` event (`supabase.auth.onAuthStateChange`). Without the\n * session the reset link opened, `updatePassword` fails with\n * `session_not_found`.\n *\n * One email template serves the link and the code: Supabase sends the Magic\n * Link template for both, so a form offering `\"email-code\"` needs\n * `{{ .Token }}` in it (the default template has only the link). The form's\n * `codeLength` must match the project's `otp_length`, which\n * `/auth/v1/settings` doesn't report: with a mismatch no code can be entered\n * whole, and code sign-in fails.\n *\n * ```ts\n * const client = createAuthFormClient(supabase, {\n * url: import.meta.env.VITE_SUPABASE_URL,\n * publishableKey: import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY,\n * redirectTo: `${location.origin}/auth/callback`,\n * resetRedirectTo: `${location.origin}/auth/new-password`,\n * });\n * ```\n *\n * @stability Beta\n */\nexport function createAuthFormClient(supabase: AuthFormSupabase, options: CreateAuthFormClientOptions = {}): AuthFormSupabaseClient {\n const { url, publishableKey, redirectTo, emailRedirectTo = redirectTo, resetRedirectTo = emailRedirectTo, providerRedirectTo, providerQueryParams } = options;\n const auth = supabase.auth;\n // Without sign-up, Auth refuses an unknown email with otp_disabled (\"Signups not allowed for otp\").\n // The client passes it on as it is; AuthForm answers it as sent, so it doesn't say which emails\n // have accounts (one place, for every client).\n const otp = (email: string, createUser: boolean): Promise<AuthCallResult> =>\n call(() =>\n auth.signInWithOtp({ email, options: { shouldCreateUser: createUser, ...(emailRedirectTo ? { emailRedirectTo } : {}) } }),\n );\n const client: AuthFormSupabaseClient = {\n signInWithPassword: ({ email, password }) => call(() => auth.signInWithPassword({ email, password })),\n sendMagicLink: ({ email, createUser }) => otp(email, createUser),\n sendEmailCode: ({ email, createUser }) => otp(email, createUser),\n verifyEmailCode: ({ email, code }) => call(() => auth.verifyOtp({ email, token: code, type: \"email\" })),\n signUp: async ({ email, password, data }) => {\n let confirmEmail = false;\n const signUpOptions = { ...(emailRedirectTo ? { emailRedirectTo } : {}), ...(data ? { data } : {}) };\n const result = await call(async () => {\n const r = await auth.signUp({ email, password, ...(Object.keys(signUpOptions).length ? { options: signUpOptions } : {}) });\n confirmEmail = !r.error && !r.data.session;\n return r;\n });\n return confirmEmail ? { ...result, confirmEmail } : result;\n },\n sendPasswordReset: ({ email }) =>\n call(() => auth.resetPasswordForEmail(email, resetRedirectTo ? { redirectTo: resetRedirectTo } : undefined)),\n updatePassword: ({ password }) => call(() => auth.updateUser({ password })),\n signInWithProvider: (provider) => {\n const back = (typeof providerRedirectTo === \"function\" ? providerRedirectTo(provider) : providerRedirectTo) ?? redirectTo;\n const queryParams = typeof providerQueryParams === \"function\" ? providerQueryParams(provider) : providerQueryParams;\n const oauthOptions = { ...(back ? { redirectTo: back } : {}), ...(queryParams && Object.keys(queryParams).length ? { queryParams } : {}) };\n return call(() =>\n auth.signInWithOAuth({\n provider: provider as Parameters<typeof auth.signInWithOAuth>[0][\"provider\"],\n ...(Object.keys(oauthOptions).length ? { options: oauthOptions } : {}),\n }),\n );\n },\n sendPhoneCode: ({ phone, createUser }) => call(() => auth.signInWithOtp({ phone, options: { shouldCreateUser: createUser } })),\n verifyPhoneCode: ({ phone, code }) => call(() => auth.verifyOtp({ phone, token: code, type: \"sms\" })),\n };\n const getSession = auth.getSession?.bind(auth);\n if (getSession) {\n client.currentEmail = async () => {\n try {\n return (await getSession()).data.session?.user.email ?? null;\n } catch {\n return null;\n }\n };\n }\n if (url && publishableKey) {\n // Asked once per client: the form may mount many times, the project's providers don't change.\n let providers: Promise<string[]> | undefined;\n client.providers = () => {\n providers ??= fetchAuthSettings({ url, publishableKey, ...(options.fetch ? { fetch: options.fetch } : {}) }).then(\n (settings) => settings.providers,\n (e: unknown) => {\n providers = undefined; // a failed lookup can be tried again\n throw e;\n },\n );\n return providers;\n };\n }\n return client;\n}\n\n/** What a project's Auth allows, from `/auth/v1/settings`. */\nexport interface AuthSettings {\n /** The OAuth providers turned on, as `signInWithOAuth` names them (`\"google\"`, `\"apple\"`…), sorted. */\n providers: string[];\n /** Email sign-in (password, link or code) is on. */\n email: boolean;\n /** Phone sign-in is on. */\n phone: boolean;\n /** New accounts are refused. */\n signUpDisabled: boolean;\n /** Emails are confirmed without a link. */\n autoConfirm: boolean;\n}\n\n/**\n * The OAuth providers `fetchAuthSettings` reports: the ones `signInWithOAuth`\n * takes and genesis-ui's `AUTH_PROVIDER_NAMES` names. Any other key of the\n * settings' `external` (`email`, `phone`, `saml`, `web3_*`…) isn't a button.\n *\n * @stability Beta\n */\nexport const SUPABASE_OAUTH_PROVIDERS: readonly string[] = [\n \"apple\",\n \"azure\",\n \"bitbucket\",\n \"discord\",\n \"facebook\",\n \"figma\",\n \"github\",\n \"gitlab\",\n \"google\",\n \"kakao\",\n \"keycloak\",\n \"linkedin_oidc\",\n \"notion\",\n \"slack_oidc\",\n \"spotify\",\n \"twitch\",\n \"twitter\",\n \"workos\",\n \"zoom\",\n];\nconst OAUTH_PROVIDERS = new Set(SUPABASE_OAUTH_PROVIDERS);\n\n/** How long the settings request may take. */\nconst SETTINGS_TIMEOUT_MS = 5000;\n\nfunction withoutTrailingSlashes(url: string): string {\n let end = url.length;\n while (end > 0 && url[end - 1] === \"/\") end--;\n return url.slice(0, end);\n}\n\n/**\n * Reads a project's public Auth settings (`GET <url>/auth/v1/settings` with\n * the publishable key): which OAuth providers are on, whether email and phone\n * sign-in are, and whether sign-up is closed. Throws when the request fails,\n * takes over 5 seconds or `signal` aborts it, and refuses a secret key\n * (`sb_secret_…`), which must never reach a browser.\n *\n * @stability Beta\n */\nexport async function fetchAuthSettings({\n url,\n publishableKey,\n fetch: fetcher = globalThis.fetch,\n signal,\n}: {\n url: string;\n publishableKey: string;\n fetch?: typeof fetch;\n /** Cancels the request (an unmounting form, say). */\n signal?: AbortSignal;\n}): Promise<AuthSettings> {\n if (publishableKey.startsWith(\"sb_secret_\")) {\n throw new Error(\"fetchAuthSettings takes the publishable key, not a secret key (sb_secret_…)\");\n }\n // A controller and a timer rather than AbortSignal.timeout/any, which older Safari and React\n // Native's Hermes lack.\n const controller = new AbortController();\n const timer = setTimeout(() => {\n const timedOut = new Error(\"Supabase Auth settings: timed out\");\n timedOut.name = \"TimeoutError\";\n controller.abort(timedOut);\n }, SETTINGS_TIMEOUT_MS);\n const onAbort = () => controller.abort(signal?.reason);\n if (signal?.aborted) onAbort();\n else signal?.addEventListener(\"abort\", onAbort, { once: true });\n let response: Response;\n try {\n response = await fetcher(`${withoutTrailingSlashes(url)}/auth/v1/settings`, {\n headers: { apikey: publishableKey },\n signal: controller.signal,\n });\n } finally {\n clearTimeout(timer);\n signal?.removeEventListener(\"abort\", onAbort);\n }\n if (!response.ok) throw new Error(`Supabase Auth settings: ${response.status}`);\n const body = (await response.json()) as {\n external?: Record<string, unknown>;\n disable_signup?: unknown;\n mailer_autoconfirm?: unknown;\n };\n const external = body.external ?? {};\n return {\n providers: Object.keys(external)\n .filter((key) => external[key] === true && OAUTH_PROVIDERS.has(key))\n .sort(),\n email: external.email === true,\n phone: external.phone === true,\n signUpDisabled: body.disable_signup === true,\n autoConfirm: body.mailer_autoconfirm === true,\n };\n}\n","/**\n * Supabase for Genesis apps. Platform-neutral: web, React Native and the\n * server import it. Native-only helpers (Keychain storage, foreground\n * refresh, reinstall wipe) are on `@marktiderman/genesis-supabase/native`.\n */\nimport { AuthInvalidJwtError, createClient, type SupabaseClient, type SupabaseClientOptions } from \"@supabase/supabase-js\";\nimport { APPLE_REVOKE_FUNCTION, requestAppleRevocation, type FunctionsClient } from \"./apple-tokens\";\nimport { assertPkceCrypto, claimsViaServer, installWebCrypto, isDigestOnlyPolyfill, type ExpoCryptoLike } from \"./web-crypto\";\n\nexport type { ExpoCryptoLike } from \"./web-crypto\";\nexport {\n APPLE_REVOKE_FUNCTION,\n requestAppleRevocation,\n storeAppleToken,\n type FunctionsClient,\n type StoreAppleTokenOptions,\n type StoreAppleTokenResult,\n} from \"./apple-tokens\";\n\n/** The async key-value store Supabase auth keeps its session in. */\nexport interface SessionStorage {\n getItem(key: string): Promise<string | null>;\n setItem(key: string, value: string): Promise<void>;\n removeItem(key: string): Promise<void>;\n}\n\n/** @stability Beta */\nexport interface GenesisSupabaseOptions {\n url: string;\n /** The publishable (anon) key. Never the secret key in an app. */\n publishableKey: string;\n /** Where the session lives. Native: `keychainStorage(SecureStore)`. Web: leave out for supabase-js's own default. */\n storage?: SessionStorage;\n /** `\"native\"` sets the React Native defaults (no session from the URL). Default `\"web\"`. */\n platform?: \"web\" | \"native\";\n /**\n * Read a session from the URL after an OAuth redirect. Default: `true` on\n * web, `false` on native, where the app hands the redirect URL to\n * `exchangeCodeForSession` itself.\n */\n detectSessionInUrl?: boolean;\n /**\n * `expo-crypto` (`import * as ExpoCrypto from \"expo-crypto\"`), on native.\n * Hermes has no `crypto.subtle`, and without it supabase-js sends the PKCE\n * challenge as \"plain\"; this installs `crypto.getRandomValues` and a SHA-256\n * `crypto.subtle.digest` from it (real WebCrypto is kept), so the challenge\n * is S256. A PKCE client made where there is neither throws in development\n * and logs an error in a release build. With the polyfill in place,\n * `auth.getClaims` always has the server check the token (`getUser`), as\n * supabase-js does where WebCrypto is missing: the polyfill can hash but\n * not verify a signature.\n */\n crypto?: ExpoCryptoLike;\n /** Anything else for supabase-js, merged last. */\n options?: SupabaseClientOptions<\"public\">;\n}\n\n/**\n * A Supabase client with Genesis's defaults: PKCE sign-in (the code flow, not\n * tokens in a redirect URL, with an S256 challenge: pass `crypto` on native),\n * a persisted session that refreshes itself, and\n * the session storage you pass.\n *\n * @stability Beta\n */\nexport function createGenesisSupabase<Database = unknown>({\n url,\n publishableKey,\n storage,\n platform = \"web\",\n detectSessionInUrl = platform === \"web\",\n crypto,\n options = {},\n}: GenesisSupabaseOptions): SupabaseClient<Database> {\n if (crypto) installWebCrypto(crypto);\n // The PKCE flow needs WebCrypto for an S256 challenge; never let it fall back to \"plain\" quietly.\n if ((options.auth?.flowType ?? \"pkce\") === \"pkce\") assertPkceCrypto();\n // supabase-js's generics over the schema don't survive being forwarded, so the\n // options are built untyped and the client is typed by the caller's Database.\n const client = createClient(url, publishableKey, {\n ...options,\n auth: {\n flowType: \"pkce\",\n persistSession: true,\n autoRefreshToken: true,\n detectSessionInUrl,\n ...(storage ? { storage } : {}),\n ...options.auth,\n },\n });\n if (isDigestOnlyPolyfill()) {\n const auth = client.auth;\n auth.getClaims = claimsViaServer(auth, (message) => new AuthInvalidJwtError(message)) as typeof auth.getClaims;\n }\n return client as unknown as SupabaseClient<Database>;\n}\n\n/** What a Supabase or PostgREST error carries. */\nexport interface PostgrestErrorLike {\n message: string;\n code?: string;\n details?: string | null;\n hint?: string | null;\n}\n\n/**\n * A failed query, with the database's `code` (`23505` unique violation,\n * `42501` permission denied, `PGRST116` no rows…), `details` and `hint`, so a\n * caller can tell an RLS refusal from a conflict. The original error is the\n * `cause`.\n *\n * @stability Beta\n */\nexport class SupabaseQueryError extends Error {\n override name = \"SupabaseQueryError\";\n readonly code?: string;\n readonly details?: string | null;\n readonly hint?: string | null;\n constructor(error: PostgrestErrorLike) {\n super(error.message, { cause: error });\n this.code = error.code;\n this.details = error.details;\n this.hint = error.hint;\n }\n}\n\n/**\n * The data, or a thrown {@link SupabaseQueryError}: for query results where an\n * error should fail the caller (a TanStack Query `queryFn`). The return type\n * keeps `null` when the query can return no row (`.maybeSingle()`).\n *\n * @stability Beta\n */\nexport function must<T>(result: { data: T; error: null } | { data: null; error: PostgrestErrorLike }): T {\n if (result.error) throw new SupabaseQueryError(result.error);\n return result.data as T;\n}\n\n/** The parts of a Supabase client {@link deleteMyAccount} uses. A `SupabaseClient` fits. */\nexport interface DeleteAccountClient {\n // Loose on purpose: a client typed by an app's Database narrows `rpc`'s\n // function names, and the app's generated types may not list this one yet.\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n rpc: (fn: any, ...rest: any[]) => PromiseLike<{ data: unknown; error: PostgrestErrorLike | null }>;\n auth: { signOut(options?: { scope?: \"global\" | \"local\" | \"others\" }): Promise<unknown> };\n /** Needed only with `revokeAppleTokens`. */\n functions?: FunctionsClient[\"functions\"];\n}\n\n/** @stability Beta */\nexport interface DeleteMyAccountOptions {\n /**\n * After the delete, ask the `genesis-apple-revoke` Edge Function to revoke\n * the person's Sign in with Apple tokens now (`true`, or the function's\n * name). Best effort: the delete has already queued them and the\n * function's schedule retries, so a failure here never fails the call.\n */\n revokeAppleTokens?: boolean | string;\n}\n\n/**\n * In-app account deletion (App Store Review Guideline 5.1.1(v)), on web and\n * native: calls the `delete_my_account` RPC (this package's\n * `migrations/0001_genesis_account_deletion.sql`), which deletes the login\n * and, through the app's `on delete cascade` foreign keys, its data; then\n * clears the session on this device. Throws a {@link SupabaseQueryError} when\n * the database refuses (`42501`: not signed in) and keeps the session then.\n *\n * With Sign in with Apple, ship the `genesis-apple-revoke` function and\n * migration 0003 and pass `{ revokeAppleTokens: true }`: App Review requires\n * the person's Apple tokens to be revoked.\n *\n * Put it behind a confirmation; see the README.\n *\n * @stability Beta\n */\nexport async function deleteMyAccount(client: DeleteAccountClient, options: DeleteMyAccountOptions = {}): Promise<void> {\n must((await client.rpc(\"delete_my_account\")) as { data: unknown; error: null } | { data: null; error: PostgrestErrorLike });\n const revoke = options.revokeAppleTokens;\n // The function needs no login (it works through the queue the delete just filled), so this runs after it.\n if (revoke && client.functions) await requestAppleRevocation({ functions: client.functions }, typeof revoke === \"string\" ? revoke : APPLE_REVOKE_FUNCTION);\n // The login is gone and its refresh tokens with it: only this device's copy is left to clear.\n await client.auth.signOut({ scope: \"local\" });\n}\nexport {\n clearGenesisSetting,\n genesisSettingHistory,\n readSettingsLayers,\n resolveAppSettings,\n setGenesisSetting,\n writeAppManifest,\n type AppManifestInput,\n type GenesisSettingChange,\n type ManifestClient,\n type ResolveAppSettingsOptions,\n type SetGenesisSettingInput,\n type SettingsClient,\n type StoredSettingsLayers,\n} from \"./settings\";\nexport {\n tenantFeatures,\n setTenantFeature,\n tenantFeatureSettings,\n tenantFeatureHistory,\n type SetTenantFeatureInput,\n type TenantFeatureChange,\n type TenantFeatureSetting,\n type TenantFeatures,\n type TenantFeaturesClient,\n} from \"./tenant-features\";\nexport {\n featureGateState,\n syncFeatureRegistry,\n type FeatureGateState,\n type FeatureGateStateOptions,\n type FlagStateValue,\n type FeatureRegistryClient,\n type FeatureRegistryDocument,\n type SyncFeatureRegistryOptions,\n} from \"./feature-registry\";\nexport { accountBlock, eventsBlock, featureMirrorBlock, jobsBlock, settingsBlock, tenantFeaturesBlock, versionedWritesBlock } from \"./blocks\";\nexport {\n createAuthFormClient,\n fetchAuthSettings,\n SUPABASE_OAUTH_PROVIDERS,\n type AuthCallError,\n type AuthCallResult,\n type AuthFormSupabase,\n type AuthFormSupabaseClient,\n type AuthSettings,\n type CreateAuthFormClientOptions,\n} from \"./auth-form-client\";\n"]}
package/dist/native.d.ts CHANGED
@@ -1,8 +1,9 @@
1
- import { S as SessionStorage } from './index-CKloeGaz.js';
2
- export { E as ExpoCryptoLike, W as WebCryptoSource, a as assertPkceCrypto, h as hasPkceCrypto, i as installWebCrypto, b as isDigestOnlyPolyfill } from './index-CKloeGaz.js';
1
+ import { S as SessionStorage } from './index-C2xP-igM.js';
2
+ export { E as ExpoCryptoLike, W as WebCryptoSource, a as assertPkceCrypto, h as hasPkceCrypto, i as installWebCrypto, b as isDigestOnlyPolyfill } from './index-C2xP-igM.js';
3
3
  import { Session, SupabaseClient, User } from '@supabase/supabase-js';
4
+ import '@marktiderman/genesis-config/settings';
4
5
  import './blocks.js';
5
- import '@marktiderman/genesis-features/blocks';
6
+ import '@marktiderman/genesis-config/blocks';
6
7
 
7
8
  /**
8
9
  * Native sign-in onto a Supabase session: finishing an OAuth redirect (PKCE),
@@ -10,6 +10,10 @@
10
10
  * is deleted) and the uploads no attachment ever named (older than a day,
11
11
  * `support_orphan_objects`). Supabase refuses direct deletes from
12
12
  * storage.objects, so this is the only way they go. A bounded batch per call.
13
+ *
14
+ * It also deletes context dumps older than GENESIS_SUPPORT_DIAGNOSTICS_RETENTION_DAYS (at least
15
+ * 1) where genesis-support's migration 0019 is applied. Without it, the database decides: the
16
+ * `diagnostics.retentionDays` setting with genesis-support 0020, else 90 days.
13
17
  */
14
18
 
15
19
  export interface PurgeRow {
@@ -28,6 +32,13 @@ export interface CleanupStore {
28
32
  remove(bucket: string, paths: string[]): Promise<string[]>;
29
33
  /** Forget purge rows whose object is gone. */
30
34
  forget(ids: number[]): Promise<void>;
35
+ /**
36
+ * Delete up to `DIAGNOSTICS_BATCH` context dumps past their retention (genesis-support
37
+ * 0019's `support_purge_diagnostics`); returns how many went. `null`: the database's own
38
+ * default (the `diagnostics.retentionDays` setting with genesis-support 0020, else 90 days).
39
+ * Left out, or the function missing (0019 not applied), dumps are left alone.
40
+ */
41
+ purgeDiagnostics?(retentionDays: number | null): Promise<number>;
31
42
  }
32
43
 
33
44
  export interface CleanupDeps {
@@ -38,6 +49,11 @@ export interface CleanupDeps {
38
49
 
39
50
  const BATCH = 100;
40
51
  const BUCKET = "genesis-support";
52
+ /** Days a context dump is kept when nothing says otherwise (genesis-support's DIAGNOSTICS_DEFAULTS.retentionDays). */
53
+ export const DIAGNOSTICS_RETENTION_DAYS = 90;
54
+ /** Dumps deleted per call of `support_purge_diagnostics`, and the most calls in one run. */
55
+ export const DIAGNOSTICS_BATCH = 1000;
56
+ export const DIAGNOSTICS_MAX_ROUNDS = 20;
41
57
 
42
58
  function json(status: number, body: Record<string, unknown>): Response {
43
59
  return new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json", "cache-control": "no-store" } });
@@ -72,7 +88,20 @@ export async function handle(req: Request, deps: CleanupDeps): Promise<Response>
72
88
  }
73
89
  const orphans = await deps.store.orphans(BATCH);
74
90
  const removed = orphans.length ? await deps.store.remove(BUCKET, orphans) : [];
75
- return json(200, { ok: true, purged, orphans: removed.length });
91
+ let diagnostics = 0;
92
+ if (deps.store.purgeDiagnostics) {
93
+ // The environment wins; without it (or with nonsense), the database's default: the setting.
94
+ const raw = deps.env("GENESIS_SUPPORT_DIAGNOSTICS_RETENTION_DAYS");
95
+ const days = raw === undefined || raw.trim() === "" ? NaN : Number(raw);
96
+ const keep = Number.isFinite(days) && days >= 1 ? Math.floor(days) : null;
97
+ // A batch at a time until a short one, so a backlog clears in one run, within a bound.
98
+ for (let round = 0; round < DIAGNOSTICS_MAX_ROUNDS; round++) {
99
+ const removed = await deps.store.purgeDiagnostics(keep);
100
+ diagnostics += removed;
101
+ if (removed < DIAGNOSTICS_BATCH) break;
102
+ }
103
+ }
104
+ return json(200, { ok: true, purged, orphans: removed.length, diagnostics });
76
105
  } catch (error) {
77
106
  deps.log(`[genesis-support-cleanup] ${error instanceof Error ? error.message : String(error)}`);
78
107
  return json(500, { error: "cleanup_failed" });
@@ -1,6 +1,9 @@
1
1
  // genesis-support-cleanup: removes support screenshots whose report or account was
2
2
  // deleted, and uploads that were never attached, through the Storage API (Supabase
3
- // refuses direct deletes from storage.objects). Call it on a schedule. See handler.ts.
3
+ // refuses direct deletes from storage.objects), and context dumps past their retention
4
+ // (genesis-support 0019; GENESIS_SUPPORT_DIAGNOSTICS_RETENTION_DAYS, else the
5
+ // diagnostics.retentionDays setting, else 90). Call it
6
+ // on a schedule. See handler.ts.
4
7
  // A template from @marktiderman/genesis-supabase: copy this folder to your app's
5
8
  // `supabase/functions/`, beside migration 0006 (see the package README).
6
9
  //
@@ -8,7 +11,7 @@
8
11
  // `x-genesis-support-secret`). SUPABASE_URL and SUPABASE_SERVICE_ROLE_KEY are set by
9
12
  // Supabase. Deploy with `verify_jwt = false`: the secret is the check.
10
13
  import { createClient } from "npm:@supabase/supabase-js@2.118.0";
11
- import { handle, type CleanupStore, type PurgeRow } from "./handler.ts";
14
+ import { handle, DIAGNOSTICS_BATCH, type CleanupStore, type PurgeRow } from "./handler.ts";
12
15
 
13
16
  const admin = createClient(Deno.env.get("SUPABASE_URL") ?? "", Deno.env.get("SUPABASE_SERVICE_ROLE_KEY") ?? "", {
14
17
  auth: { persistSession: false, autoRefreshToken: false },
@@ -30,6 +33,14 @@ const store: CleanupStore = {
30
33
  if (error) throw new Error(`storage remove: ${error.message}`);
31
34
  return (data ?? []).map((object) => object.name);
32
35
  },
36
+ async purgeDiagnostics(retentionDays) {
37
+ // No age: the database's default (the diagnostics.retentionDays setting, else 90 days).
38
+ const { data, error } = await admin.rpc("support_purge_diagnostics", retentionDays === null ? { max_rows: DIAGNOSTICS_BATCH } : { older_than: `${retentionDays} days`, max_rows: DIAGNOSTICS_BATCH });
39
+ // PGRST202 / 42883: genesis-support's migration 0019 isn't applied, so there are no dumps.
40
+ if (error?.code === "PGRST202" || error?.code === "42883") return 0;
41
+ if (error) throw new Error(`support_purge_diagnostics: ${error.code ?? ""} ${error.message}`);
42
+ return typeof data === "number" ? data : 0;
43
+ },
33
44
  async forget(ids) {
34
45
  const { error } = await admin.from("support_attachment_purges").delete().in("id", ids);
35
46
  if (error) throw new Error(`support_attachment_purges: ${error.code ?? ""} ${error.message}`);
@@ -121,7 +121,12 @@ export const WIDGET_HEADERS = {
121
121
  /** Text limits, the same as the database's checks. */
122
122
  export const LIMITS = { title: 300, body: 20000, route: 2000, appVersion: 200, tag: 60, tags: 50, contextBytes: 16384 } as const;
123
123
 
124
- /** A path segment that names someone or something private: an email, a UUID, a number, a long token. */
124
+ /**
125
+ * A path segment that names someone or something private: an email, a UUID, a number, a phone
126
+ * number, a card or account number, a token or a short code. It is judged after percent-decoding,
127
+ * so `%20` and `+` separators don't hide a number. A name written as a slug (`jane-doe`) reads like
128
+ * any word and isn't caught: keep names out of paths.
129
+ */
125
130
  function privateSegment(segment: string): string | null {
126
131
  let s = segment;
127
132
  try {
@@ -129,24 +134,60 @@ function privateSegment(segment: string): string | null {
129
134
  } catch {
130
135
  // a malformed escape: judge it as written
131
136
  }
137
+ s = s.trim();
132
138
  if (s.includes("@")) return ":email";
133
139
  if (/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(s)) return ":id";
134
140
  if (/^\d+$/.test(s)) return ":id";
141
+ if (/^tel:/i.test(s)) return ":phone";
142
+ const digits = (s.match(/\d/g) ?? []).length;
143
+ // Digits and separators only: a phone number (`555-555-0101`, `(555) 555-0101`, `+44 20 7946
144
+ // 0958`), a card or account number in groups (`4111 1111 1111 1111`, `4111+1111+…`) or an SSN
145
+ // (`123-45-6789`). A date (`2024-11-19`) and short numbers (`1.4.0`) stay.
146
+ if (/^[\d().\s+-]+$/.test(s) && digits >= 7) {
147
+ if (/^\d{4}-\d{2}-\d{2}$/.test(s)) return null;
148
+ if (s.startsWith("+")) return ":phone";
149
+ return digits >= 13 ? ":token" : /^\d{3}-\d{2}-\d{4}$/.test(s) ? ":id" : ":phone";
150
+ }
151
+ // A short code (an invite, a coupon): 6 to 12 letters and digits with no separator, the two
152
+ // interleaved (`ab12cd`, `x7k9q2`). A slug that ends in a number (`round42`, `ios17-setup`,
153
+ // `top-10-tips-2024`) switches once or has separators, and stays.
154
+ if (/^[A-Za-z0-9]{6,12}$/.test(s) && (s.match(/[A-Za-z](?=\d)|\d(?=[A-Za-z])/g) ?? []).length >= 2) return ":token";
155
+ // A slug: words and numbers joined by `-` (`top-10-tips-2024`), each part all letters or all
156
+ // digits. A token's parts mix them. Three shapes look like slugs and aren't: 9 or more digits in
157
+ // all (`card-4111-1111-1111-1111`, `call-555-555-0101`: a card, an account, a phone; a date
158
+ // `release-2024-11-19` has 8), a long run of digits in one part (`acct-12345678`), and a grouped
159
+ // code, three or more parts of one length with both letters and digits (`ABCD-EFGH-1234-5678`).
160
+ if (/^[A-Za-z]+(?:-(?:[A-Za-z]+|\d+))+$/.test(s)) {
161
+ const parts = s.split("-");
162
+ if (digits >= 9 || parts.some((part) => /^\d{7,}$/.test(part))) return ":token";
163
+ const width = parts[0]?.length ?? 0;
164
+ const grouped = parts.length >= 3 && width >= 3 && parts.every((part) => part.length === width);
165
+ if (grouped && parts.some((part) => /^\d+$/.test(part))) return ":token";
166
+ return null;
167
+ }
168
+ // Letters and digits in spaced or `+`-joined groups: an IBAN (`DE89 3704 0044 0532 0130 00`).
169
+ if (/[\s+]/.test(s) && digits >= 9 && /^[A-Za-z0-9\s+.-]+$/.test(s)) return ":token";
170
+ // Base64 with its padding (`dG9rZW4xMjM0NQ==`).
171
+ if (/^[A-Za-z0-9+/_-]{8,}={1,2}$/.test(s)) return ":token";
135
172
  // A long run of letters and digits with a digit in it reads as a token or a code, not a word.
136
- if (s.length >= 16 && /\d/.test(s) && /^[A-Za-z0-9_.~-]+$/.test(s)) return ":token";
173
+ if (s.length >= 16 && /\d/.test(s) && /^[A-Za-z0-9_.~+=-]+$/.test(s)) return ":token";
137
174
  return null;
138
175
  }
139
176
 
177
+ /** Where the path ends: a `?` or `#`, written or percent-encoded (`%3F`, `%23`). */
178
+ const PATH_END = /[?#]|%3[fF]|%23/;
179
+
140
180
  /**
141
181
  * A route as a path only, safe to store and send: the query string and
142
- * fragment (tokens, codes, emails) are dropped, and path segments that look
143
- * private (an email, an id, a long token) become `:email`, `:id` or `:token`
182
+ * fragment (tokens, codes, emails), written or percent-encoded, are dropped, and path segments
183
+ * that look private (an email, an id, a phone or card number, a token or short code) become
184
+ * `:email`, `:id`, `:phone` or `:token`
144
185
  * (`/users/jane@x.test/reset/abc123…` → `/users/:email/reset/:token`).
145
186
  */
146
187
  export function cleanRoute(route: string | null | undefined): string | undefined {
147
188
  if (typeof route !== "string") return undefined;
148
- // A plain search, not a regex: `[?#].*$` retries at every `#` and goes quadratic on `###…`.
149
- const cut = route.search(/[?#]/);
189
+ // A plain search, not a regex over the rest: `[?#].*$` retries at every `#` and goes quadratic on `###…`.
190
+ const cut = route.search(PATH_END);
150
191
  const path = (cut === -1 ? route : route.slice(0, cut)).trim();
151
192
  if (!path) return undefined;
152
193
  const safe = path
@@ -2,9 +2,12 @@
2
2
  * The genesis-support-notify Edge Function's request handling, with its
3
3
  * dependencies passed in, so it is tested without Deno.
4
4
  *
5
- * A Supabase Database Webhook calls it on INSERT into public.support_reports
6
- * (Dashboard → Database → Webhooks, or `supabase_functions.http_request` in a
7
- * migration of your own), with the header `x-genesis-support-secret: <secret>`.
5
+ * A Supabase Database Webhook calls it on INSERT into public.tickets (Dashboard →
6
+ * Database → Webhooks, or `supabase_functions.http_request` in a migration of
7
+ * your own), with the header `x-genesis-support-secret: <secret>`. Since
8
+ * genesis-support's migration 0004 a report is a row in public.tickets;
9
+ * public.support_reports, the table before it, is still taken, for an app
10
+ * whose webhook was set up before that migration.
8
11
  * It forwards a summary to the sinks that are configured:
9
12
  *
10
13
  * - a GitHub issue per report: GITHUB_TOKEN (fine-grained, Issues: write on
@@ -49,6 +52,13 @@ export interface NotifyDeps {
49
52
 
50
53
  const MESSAGE_CAP = 2000;
51
54
 
55
+ /**
56
+ * The tables a new report lands in: `tickets` (genesis-support 0004 renamed the table), and
57
+ * `support_reports` for an app that hasn't applied 0004 yet. A webhook on the old name stops
58
+ * firing once it's renamed, so point the webhook at `tickets` after 0004.
59
+ */
60
+ export const REPORT_TABLES: ReadonlySet<string> = new Set(["tickets", "support_reports"]);
61
+
52
62
  /** The only fields a sink ever sees. */
53
63
  export function summarize(record: ReportRecord): ReportSummary {
54
64
  const message = String(record.message ?? "");
@@ -83,20 +93,34 @@ function json(status: number, body: Record<string, unknown>): Response {
83
93
  return new Response(JSON.stringify(body), { status, headers: { "content-type": "application/json", "cache-control": "no-store" } });
84
94
  }
85
95
 
86
- /** Markdown for the issue body; the person's text is fenced so it can't mention or link anyone. */
96
+ /** A fenced block the text can't break out of: the fence is longer than any run of backticks in it. */
97
+ export function fenced(text: string): string {
98
+ const longest = Math.max(0, ...(text.match(/`+/g) ?? []).map((run) => run.length));
99
+ const fence = "`".repeat(Math.max(4, longest + 1));
100
+ return [fence, text, fence].join("\n");
101
+ }
102
+
103
+ /** Text safe outside a fence (the issue title): nothing can form a mention, link, image or HTML. */
104
+ export function neutralise(text: string): string {
105
+ return text.replace(/[@#[!<`]/g, (c) => `${c}\u200b`);
106
+ }
107
+
108
+ /**
109
+ * Markdown for the issue body: everything in one fence, so neither the person's text nor the
110
+ * platform or route they sent can mention, link or embed anything.
111
+ */
87
112
  export function issueBody(s: ReportSummary): string {
88
- const fence = "````";
89
- return [
90
- `**${s.type}** from the app${s.platform ? ` (${s.platform})` : ""}`,
91
- "",
92
- fence,
93
- s.message.replaceAll(fence, "``` `"),
94
- fence,
95
- "",
96
- `- Route: ${s.route ? `\`${s.route.replaceAll("`", "")}\`` : "none"}`,
97
- `- Version: ${s.appVersion ? `\`${s.appVersion.replaceAll("`", "")}\`` : "unknown"}`,
98
- `- Report: \`${s.id}\``,
99
- ].join("\n");
113
+ return fenced(
114
+ [
115
+ `${s.type} from the app${s.platform ? ` (${s.platform})` : ""}`,
116
+ "",
117
+ s.message,
118
+ "",
119
+ `Route: ${s.route ?? "none"}`,
120
+ `Version: ${s.appVersion ?? "unknown"}`,
121
+ `Report: ${s.id}`,
122
+ ].join("\n"),
123
+ );
100
124
  }
101
125
 
102
126
  export async function handle(req: Request, deps: NotifyDeps): Promise<Response> {
@@ -114,7 +138,7 @@ export async function handle(req: Request, deps: NotifyDeps): Promise<Response>
114
138
  } catch {
115
139
  return json(400, { error: "invalid_json" });
116
140
  }
117
- if (payload.type !== "INSERT" || payload.table !== "support_reports" || !payload.record?.id) {
141
+ if (payload.type !== "INSERT" || !REPORT_TABLES.has(payload.table ?? "") || !payload.record?.id) {
118
142
  return json(200, { ok: true, skipped: true });
119
143
  }
120
144
  const summary = summarize(payload.record);
@@ -132,7 +156,7 @@ export async function handle(req: Request, deps: NotifyDeps): Promise<Response>
132
156
  const res = await deps.fetch(`https://api.github.com/repos/${repo}/issues`, {
133
157
  method: "POST",
134
158
  headers: { authorization: `Bearer ${token}`, accept: "application/vnd.github+json", "content-type": "application/json", "user-agent": "genesis-support-notify" },
135
- body: JSON.stringify({ title: `[${summary.type}] ${summary.title}`.slice(0, 256), body: issueBody(summary), labels: [...labels, summary.type] }),
159
+ body: JSON.stringify({ title: neutralise(`[${summary.type}] ${summary.title}`).slice(0, 256), body: issueBody(summary), labels: [...labels, summary.type] }),
136
160
  });
137
161
  if (res.ok) sent.push("github");
138
162
  else {
@@ -1,5 +1,6 @@
1
1
  // genesis-support-notify: an optional server-side sink for new support reports.
2
- // A Database Webhook on INSERT into public.support_reports calls it; it opens a
2
+ // A Database Webhook on INSERT into public.tickets (public.support_reports before
3
+ // genesis-support's migration 0004) calls it; it opens a
3
4
  // GitHub issue per report and/or posts a signed webhook, with a summary only
4
5
  // (no person id, email, device, context or screenshot). See handler.ts.
5
6
  // A template from @marktiderman/genesis-supabase: copy this folder to your app's