@marktiderman/genesis-supabase 0.10.1 → 0.12.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/README.md +88 -0
- package/dist/blocks.d.ts +9 -1
- package/dist/blocks.js +1 -1
- package/dist/{chunk-FWQGZT4S.js → chunk-34OBTZJQ.js} +15 -3
- package/dist/chunk-34OBTZJQ.js.map +1 -0
- package/dist/events.d.ts +108 -0
- package/dist/events.js +143 -0
- package/dist/events.js.map +1 -0
- package/dist/{index-CaYX9z8D.d.ts → index-UjHqJN2X.d.ts} +159 -2
- package/dist/index.d.ts +2 -2
- package/dist/index.js +129 -3
- package/dist/index.js.map +1 -1
- package/dist/native.d.ts +2 -2
- package/functions/genesis-apple-revoke/apple.ts +7 -2
- package/functions/genesis-support-intake/contract.ts +27 -27
- package/functions/genesis-support-intake/handler.ts +2 -0
- package/migrations/0018_genesis_events.sql +260 -0
- package/migrations/tests/0006_genesis_support.test.sql +1 -1
- package/migrations/tests/0018_genesis_events.test.sql +147 -0
- package/package.json +62 -3
- package/dist/chunk-FWQGZT4S.js.map +0 -1
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import '@supabase/supabase-js';
|
|
2
|
-
export { A as APPLE_REVOKE_FUNCTION, D as DeleteAccountClient,
|
|
3
|
-
export { accountBlock, featureMirrorBlock, jobsBlock, tenantFeaturesBlock } from './blocks.js';
|
|
2
|
+
export { A as APPLE_REVOKE_FUNCTION, c as AuthCallError, d as AuthCallResult, e as AuthFormSupabase, f as AuthFormSupabaseClient, g as AuthSettings, C as CreateAuthFormClientOptions, D as DeleteAccountClient, j as DeleteMyAccountOptions, E as ExpoCryptoLike, F as FeatureGateState, k as FeatureGateStateOptions, l as FeatureRegistryClient, m as FeatureRegistryDocument, n as FlagStateValue, o as FunctionsClient, G as GenesisSupabaseOptions, P as PostgrestErrorLike, p as SUPABASE_OAUTH_PROVIDERS, S as SessionStorage, q as SetTenantFeatureInput, r as StoreAppleTokenOptions, s as StoreAppleTokenResult, t as SupabaseQueryError, u as SyncFeatureRegistryOptions, T as TenantFeatureChange, v as TenantFeatureSetting, w as TenantFeatures, x as TenantFeaturesClient, y as createAuthFormClient, z as createGenesisSupabase, B as deleteMyAccount, H as featureGateState, I as fetchAuthSettings, J as must, K as requestAppleRevocation, L as setTenantFeature, M as storeAppleToken, N as syncFeatureRegistry, O as tenantFeatureHistory, Q as tenantFeatureSettings, R as tenantFeatures } from './index-UjHqJN2X.js';
|
|
3
|
+
export { accountBlock, eventsBlock, featureMirrorBlock, jobsBlock, tenantFeaturesBlock } from './blocks.js';
|
|
4
4
|
import '@marktiderman/genesis-features/blocks';
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { installWebCrypto, assertPkceCrypto, isDigestOnlyPolyfill, claimsViaServer } from './chunk-FAA2FTF4.js';
|
|
2
|
-
export { accountBlock, featureMirrorBlock, jobsBlock, tenantFeaturesBlock } from './chunk-
|
|
3
|
-
import { createClient, AuthInvalidJwtError } from '@supabase/supabase-js';
|
|
2
|
+
export { accountBlock, eventsBlock, featureMirrorBlock, jobsBlock, tenantFeaturesBlock } from './chunk-34OBTZJQ.js';
|
|
3
|
+
import { createClient, AuthInvalidJwtError, isAuthError } from '@supabase/supabase-js';
|
|
4
4
|
|
|
5
5
|
// src/apple-tokens.ts
|
|
6
6
|
var APPLE_REVOKE_FUNCTION = "genesis-apple-revoke";
|
|
@@ -107,6 +107,132 @@ async function syncFeatureRegistry(client, document, options) {
|
|
|
107
107
|
})
|
|
108
108
|
) === true;
|
|
109
109
|
}
|
|
110
|
+
function toResult(e) {
|
|
111
|
+
if (!e) return {};
|
|
112
|
+
const network = e.name === "AuthRetryableFetchError" || e.status === 0;
|
|
113
|
+
const missingSession = e.name === "AuthSessionMissingError";
|
|
114
|
+
const code = e.code ?? (missingSession ? "session_not_found" : network ? "network" : void 0);
|
|
115
|
+
return { error: { ...code ? { code } : {}, message: e.message } };
|
|
116
|
+
}
|
|
117
|
+
async function call(run) {
|
|
118
|
+
try {
|
|
119
|
+
return toResult((await run()).error);
|
|
120
|
+
} catch (e) {
|
|
121
|
+
if (isAuthError(e)) return toResult(e);
|
|
122
|
+
return { error: { code: "network", message: e instanceof Error ? e.message : "The request failed" } };
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
function createAuthFormClient(supabase, options = {}) {
|
|
126
|
+
const { url, publishableKey, redirectTo, resetRedirectTo = redirectTo } = options;
|
|
127
|
+
const auth = supabase.auth;
|
|
128
|
+
const otp = (email, createUser) => call(
|
|
129
|
+
() => auth.signInWithOtp({ email, options: { shouldCreateUser: createUser, ...redirectTo ? { emailRedirectTo: redirectTo } : {} } })
|
|
130
|
+
);
|
|
131
|
+
const client = {
|
|
132
|
+
signInWithPassword: ({ email, password }) => call(() => auth.signInWithPassword({ email, password })),
|
|
133
|
+
sendMagicLink: ({ email, createUser }) => otp(email, createUser),
|
|
134
|
+
sendEmailCode: ({ email, createUser }) => otp(email, createUser),
|
|
135
|
+
verifyEmailCode: ({ email, code }) => call(() => auth.verifyOtp({ email, token: code, type: "email" })),
|
|
136
|
+
signUp: async ({ email, password }) => {
|
|
137
|
+
let confirmEmail = false;
|
|
138
|
+
const result = await call(async () => {
|
|
139
|
+
const r = await auth.signUp({ email, password, ...redirectTo ? { options: { emailRedirectTo: redirectTo } } : {} });
|
|
140
|
+
confirmEmail = !r.error && !r.data.session;
|
|
141
|
+
return r;
|
|
142
|
+
});
|
|
143
|
+
return confirmEmail ? { ...result, confirmEmail } : result;
|
|
144
|
+
},
|
|
145
|
+
sendPasswordReset: ({ email }) => call(() => auth.resetPasswordForEmail(email, resetRedirectTo ? { redirectTo: resetRedirectTo } : void 0)),
|
|
146
|
+
updatePassword: ({ password }) => call(() => auth.updateUser({ password })),
|
|
147
|
+
signInWithProvider: (provider) => call(
|
|
148
|
+
() => auth.signInWithOAuth({
|
|
149
|
+
provider,
|
|
150
|
+
...redirectTo ? { options: { redirectTo } } : {}
|
|
151
|
+
})
|
|
152
|
+
)
|
|
153
|
+
};
|
|
154
|
+
if (url && publishableKey) {
|
|
155
|
+
let providers;
|
|
156
|
+
client.providers = () => {
|
|
157
|
+
providers ??= fetchAuthSettings({ url, publishableKey, ...options.fetch ? { fetch: options.fetch } : {} }).then(
|
|
158
|
+
(settings) => settings.providers,
|
|
159
|
+
(e) => {
|
|
160
|
+
providers = void 0;
|
|
161
|
+
throw e;
|
|
162
|
+
}
|
|
163
|
+
);
|
|
164
|
+
return providers;
|
|
165
|
+
};
|
|
166
|
+
}
|
|
167
|
+
return client;
|
|
168
|
+
}
|
|
169
|
+
var SUPABASE_OAUTH_PROVIDERS = [
|
|
170
|
+
"apple",
|
|
171
|
+
"azure",
|
|
172
|
+
"bitbucket",
|
|
173
|
+
"discord",
|
|
174
|
+
"facebook",
|
|
175
|
+
"figma",
|
|
176
|
+
"github",
|
|
177
|
+
"gitlab",
|
|
178
|
+
"google",
|
|
179
|
+
"kakao",
|
|
180
|
+
"keycloak",
|
|
181
|
+
"linkedin_oidc",
|
|
182
|
+
"notion",
|
|
183
|
+
"slack_oidc",
|
|
184
|
+
"spotify",
|
|
185
|
+
"twitch",
|
|
186
|
+
"twitter",
|
|
187
|
+
"workos",
|
|
188
|
+
"zoom"
|
|
189
|
+
];
|
|
190
|
+
var OAUTH_PROVIDERS = new Set(SUPABASE_OAUTH_PROVIDERS);
|
|
191
|
+
var SETTINGS_TIMEOUT_MS = 5e3;
|
|
192
|
+
function withoutTrailingSlashes(url) {
|
|
193
|
+
let end = url.length;
|
|
194
|
+
while (end > 0 && url[end - 1] === "/") end--;
|
|
195
|
+
return url.slice(0, end);
|
|
196
|
+
}
|
|
197
|
+
async function fetchAuthSettings({
|
|
198
|
+
url,
|
|
199
|
+
publishableKey,
|
|
200
|
+
fetch: fetcher = globalThis.fetch,
|
|
201
|
+
signal
|
|
202
|
+
}) {
|
|
203
|
+
if (publishableKey.startsWith("sb_secret_")) {
|
|
204
|
+
throw new Error("fetchAuthSettings takes the publishable key, not a secret key (sb_secret_\u2026)");
|
|
205
|
+
}
|
|
206
|
+
const controller = new AbortController();
|
|
207
|
+
const timer = setTimeout(() => {
|
|
208
|
+
const timedOut = new Error("Supabase Auth settings: timed out");
|
|
209
|
+
timedOut.name = "TimeoutError";
|
|
210
|
+
controller.abort(timedOut);
|
|
211
|
+
}, SETTINGS_TIMEOUT_MS);
|
|
212
|
+
const onAbort = () => controller.abort(signal?.reason);
|
|
213
|
+
if (signal?.aborted) onAbort();
|
|
214
|
+
else signal?.addEventListener("abort", onAbort, { once: true });
|
|
215
|
+
let response;
|
|
216
|
+
try {
|
|
217
|
+
response = await fetcher(`${withoutTrailingSlashes(url)}/auth/v1/settings`, {
|
|
218
|
+
headers: { apikey: publishableKey },
|
|
219
|
+
signal: controller.signal
|
|
220
|
+
});
|
|
221
|
+
} finally {
|
|
222
|
+
clearTimeout(timer);
|
|
223
|
+
signal?.removeEventListener("abort", onAbort);
|
|
224
|
+
}
|
|
225
|
+
if (!response.ok) throw new Error(`Supabase Auth settings: ${response.status}`);
|
|
226
|
+
const body = await response.json();
|
|
227
|
+
const external = body.external ?? {};
|
|
228
|
+
return {
|
|
229
|
+
providers: Object.keys(external).filter((key) => external[key] === true && OAUTH_PROVIDERS.has(key)).sort(),
|
|
230
|
+
email: external.email === true,
|
|
231
|
+
phone: external.phone === true,
|
|
232
|
+
signUpDisabled: body.disable_signup === true,
|
|
233
|
+
autoConfirm: body.mailer_autoconfirm === true
|
|
234
|
+
};
|
|
235
|
+
}
|
|
110
236
|
|
|
111
237
|
// src/index.ts
|
|
112
238
|
function createGenesisSupabase({
|
|
@@ -160,6 +286,6 @@ async function deleteMyAccount(client, options = {}) {
|
|
|
160
286
|
await client.auth.signOut({ scope: "local" });
|
|
161
287
|
}
|
|
162
288
|
|
|
163
|
-
export { APPLE_REVOKE_FUNCTION, SupabaseQueryError, createGenesisSupabase, deleteMyAccount, featureGateState, must, requestAppleRevocation, setTenantFeature, storeAppleToken, syncFeatureRegistry, tenantFeatureHistory, tenantFeatureSettings, tenantFeatures };
|
|
289
|
+
export { APPLE_REVOKE_FUNCTION, SUPABASE_OAUTH_PROVIDERS, SupabaseQueryError, createAuthFormClient, createGenesisSupabase, deleteMyAccount, featureGateState, fetchAuthSettings, must, requestAppleRevocation, setTenantFeature, storeAppleToken, syncFeatureRegistry, tenantFeatureHistory, tenantFeatureSettings, tenantFeatures };
|
|
164
290
|
//# sourceMappingURL=index.js.map
|
|
165
291
|
//# sourceMappingURL=index.js.map
|
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/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,E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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 * 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, featureMirrorBlock, jobsBlock, tenantFeaturesBlock } from \"./blocks\";\n"]}
|
|
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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,IAAA,GAAO,oBAAA;AAAA,EACP,IAAA;AAAA,EACA,OAAA;AAAA,EACA,IAAA;AAAA,EACT,YAAY,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 * 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) 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/** The parts of a Supabase client {@link createAuthFormClient} uses. A `SupabaseClient` fits. */\nexport interface AuthFormSupabase {\n auth: Pick<\n SupabaseClient[\"auth\"],\n \"signInWithPassword\" | \"signInWithOtp\" | \"verifyOtp\" | \"signUp\" | \"resetPasswordForEmail\" | \"updateUser\" | \"signInWithOAuth\"\n >;\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 signUp(input: { email: string; password: string }): Promise<AuthCallResult>;\n sendPasswordReset(input: { email: string }): Promise<AuthCallResult>;\n updatePassword(input: { password: string }): Promise<AuthCallResult>;\n signInWithProvider(provider: string): Promise<AuthCallResult>;\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 password-reset link opens: the page that shows `mode=\"new-password\"`. Default `redirectTo`. */\n resetRedirectTo?: string;\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). 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).\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, resetRedirectTo = redirectTo } = 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, ...(redirectTo ? { emailRedirectTo: redirectTo } : {}) } }),\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 }) => {\n let confirmEmail = false;\n const result = await call(async () => {\n const r = await auth.signUp({ email, password, ...(redirectTo ? { options: { emailRedirectTo: redirectTo } } : {}) });\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 call(() =>\n auth.signInWithOAuth({\n provider: provider as Parameters<typeof auth.signInWithOAuth>[0][\"provider\"],\n ...(redirectTo ? { options: { redirectTo } } : {}),\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 } 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,5 +1,5 @@
|
|
|
1
|
-
import { S as SessionStorage } from './index-
|
|
2
|
-
export { E as ExpoCryptoLike, W as WebCryptoSource, a as assertPkceCrypto, h as hasPkceCrypto, i as installWebCrypto, b as isDigestOnlyPolyfill } from './index-
|
|
1
|
+
import { S as SessionStorage } from './index-UjHqJN2X.js';
|
|
2
|
+
export { E as ExpoCryptoLike, W as WebCryptoSource, a as assertPkceCrypto, h as hasPkceCrypto, i as installWebCrypto, b as isDigestOnlyPolyfill } from './index-UjHqJN2X.js';
|
|
3
3
|
import { Session, SupabaseClient, User } from '@supabase/supabase-js';
|
|
4
4
|
import './blocks.js';
|
|
5
5
|
import '@marktiderman/genesis-features/blocks';
|
|
@@ -39,6 +39,11 @@ export interface AppleConfig {
|
|
|
39
39
|
|
|
40
40
|
const TEN_CHARS = /^[A-Z0-9]{10}$/;
|
|
41
41
|
const CLIENT_ID = /^[A-Za-z0-9][A-Za-z0-9.-]{0,254}$/;
|
|
42
|
+
// The PKCS#8 PEM armour, with the dashes counted (`-{5}`) rather than written out: the literal
|
|
43
|
+
// header is what secret scanners (gitleaks' private-key rule) look for, and every app that installs
|
|
44
|
+
// this function scans it.
|
|
45
|
+
const PEM_KEY = /-{5}BEGIN PRIVATE KEY-{5}[\s\S]+-{5}END PRIVATE KEY-{5}/;
|
|
46
|
+
const PEM_MARKER = /-{5}(?:BEGIN|END) PRIVATE KEY-{5}/g;
|
|
42
47
|
|
|
43
48
|
/**
|
|
44
49
|
* Reads the Apple settings from the environment. Returns the names that are
|
|
@@ -55,7 +60,7 @@ export function readAppleConfig(env: (name: string) => string | undefined): { co
|
|
|
55
60
|
.filter(Boolean);
|
|
56
61
|
if (!TEN_CHARS.test(teamId)) problems.push("APPLE_TEAM_ID (10 capital letters or digits)");
|
|
57
62
|
if (!TEN_CHARS.test(keyId)) problems.push("APPLE_KEY_ID (10 capital letters or digits)");
|
|
58
|
-
if (
|
|
63
|
+
if (!PEM_KEY.test(privateKey)) problems.push("APPLE_PRIVATE_KEY (the .p8 file's PEM text)");
|
|
59
64
|
if (clientIds.length === 0 || !clientIds.every((id) => CLIENT_ID.test(id))) problems.push("APPLE_CLIENT_IDS (comma-separated bundle ids or Services IDs)");
|
|
60
65
|
return problems.length ? { problems } : { config: { teamId, keyId, privateKey, clientIds } };
|
|
61
66
|
}
|
|
@@ -85,7 +90,7 @@ const keyCache = new Map<string, Promise<CryptoKey>>();
|
|
|
85
90
|
function signingKey(pem: string): Promise<CryptoKey> {
|
|
86
91
|
let key = keyCache.get(pem);
|
|
87
92
|
if (!key) {
|
|
88
|
-
const body = pem.replace(
|
|
93
|
+
const body = pem.replace(PEM_MARKER, "").replace(/\s+/g, "");
|
|
89
94
|
const der = Uint8Array.from(atob(body), (c) => c.charCodeAt(0));
|
|
90
95
|
key = crypto.subtle.importKey("pkcs8", der, { name: "ECDSA", namedCurve: "P-256" }, false, ["sign"]);
|
|
91
96
|
// A bad key must not stay cached as a rejected promise.
|
|
@@ -67,16 +67,16 @@ const SEVERITIES: readonly FindingSeverity[] = ["low", "medium", "high", "critic
|
|
|
67
67
|
|
|
68
68
|
/** Client to server: open a report. Screenshots go to storage, not in this body. */
|
|
69
69
|
export interface SubmitFeedbackInput {
|
|
70
|
-
type?: FeedbackReportType;
|
|
71
|
-
title?: string;
|
|
70
|
+
type?: FeedbackReportType | undefined;
|
|
71
|
+
title?: string | undefined;
|
|
72
72
|
body: string;
|
|
73
|
-
route?: string;
|
|
74
|
-
appVersion?: string;
|
|
75
|
-
envType?: string;
|
|
76
|
-
severity?: FindingSeverity;
|
|
77
|
-
tags?: string[];
|
|
73
|
+
route?: string | undefined;
|
|
74
|
+
appVersion?: string | undefined;
|
|
75
|
+
envType?: string | undefined;
|
|
76
|
+
severity?: FindingSeverity | undefined;
|
|
77
|
+
tags?: string[] | undefined;
|
|
78
78
|
/** Small, free-form context (breadcrumbs, a pin on the page). At most 16 KB as JSON. */
|
|
79
|
-
context?: Record<string, unknown
|
|
79
|
+
context?: Record<string, unknown> | undefined;
|
|
80
80
|
}
|
|
81
81
|
|
|
82
82
|
/** Server to client: the report created. `findingId` is the report's id (one finding per report here). */
|
|
@@ -163,31 +163,31 @@ export function validateSubmitInput(raw: unknown): SubmitValidation {
|
|
|
163
163
|
const known = new Set(["type", "title", "body", "route", "appVersion", "envType", "severity", "tags", "context"]);
|
|
164
164
|
for (const key of Object.keys(input)) if (!known.has(key)) return { ok: false, error: "invalid_args", field: key };
|
|
165
165
|
const optionalString = (key: string, max: number): boolean => input[key] == null || (typeof input[key] === "string" && (input[key] as string).length <= max);
|
|
166
|
-
if (typeof input
|
|
167
|
-
if (input
|
|
168
|
-
if (input
|
|
169
|
-
if (input
|
|
166
|
+
if (typeof input["body"] !== "string" || !input["body"].trim()) return { ok: false, error: "invalid_args", field: "body" };
|
|
167
|
+
if (input["body"].length > LIMITS.body) return { ok: false, error: "payload_too_large", field: "body" };
|
|
168
|
+
if (input["type"] != null && !FEEDBACK_REPORT_TYPES.includes(input["type"] as FeedbackReportType)) return { ok: false, error: "invalid_args", field: "type" };
|
|
169
|
+
if (input["severity"] != null && !SEVERITIES.includes(input["severity"] as FindingSeverity)) return { ok: false, error: "invalid_args", field: "severity" };
|
|
170
170
|
if (!optionalString("title", LIMITS.title)) return { ok: false, error: "invalid_args", field: "title" };
|
|
171
171
|
if (!optionalString("route", LIMITS.route)) return { ok: false, error: "invalid_args", field: "route" };
|
|
172
172
|
if (!optionalString("appVersion", LIMITS.appVersion)) return { ok: false, error: "invalid_args", field: "appVersion" };
|
|
173
173
|
if (!optionalString("envType", 60)) return { ok: false, error: "invalid_args", field: "envType" };
|
|
174
|
-
if (input
|
|
175
|
-
if (!Array.isArray(input
|
|
176
|
-
if (!input
|
|
174
|
+
if (input["tags"] != null) {
|
|
175
|
+
if (!Array.isArray(input["tags"]) || input["tags"].length > LIMITS.tags) return { ok: false, error: "invalid_args", field: "tags" };
|
|
176
|
+
if (!input["tags"].every((t) => typeof t === "string" && t.length <= LIMITS.tag)) return { ok: false, error: "invalid_args", field: "tags" };
|
|
177
177
|
}
|
|
178
|
-
if (input
|
|
179
|
-
if (typeof input
|
|
180
|
-
if (byteLength(JSON.stringify(input
|
|
178
|
+
if (input["context"] != null) {
|
|
179
|
+
if (typeof input["context"] !== "object" || Array.isArray(input["context"])) return { ok: false, error: "invalid_args", field: "context" };
|
|
180
|
+
if (byteLength(JSON.stringify(input["context"])) > LIMITS.contextBytes) return { ok: false, error: "payload_too_large", field: "context" };
|
|
181
181
|
}
|
|
182
|
-
const value: SubmitFeedbackInput = { body: input
|
|
183
|
-
if (input
|
|
184
|
-
if (input
|
|
185
|
-
const route = cleanRoute(input
|
|
182
|
+
const value: SubmitFeedbackInput = { body: input["body"] };
|
|
183
|
+
if (input["type"] != null) value.type = input["type"] as FeedbackReportType;
|
|
184
|
+
if (input["title"] != null) value.title = input["title"] as string;
|
|
185
|
+
const route = cleanRoute(input["route"] as string | undefined);
|
|
186
186
|
if (route) value.route = route;
|
|
187
|
-
if (input
|
|
188
|
-
if (input
|
|
189
|
-
if (input
|
|
190
|
-
if (input
|
|
191
|
-
if (input
|
|
187
|
+
if (input["appVersion"] != null) value.appVersion = input["appVersion"] as string;
|
|
188
|
+
if (input["envType"] != null) value.envType = input["envType"] as string;
|
|
189
|
+
if (input["severity"] != null) value.severity = input["severity"] as FindingSeverity;
|
|
190
|
+
if (input["tags"] != null) value.tags = input["tags"] as string[];
|
|
191
|
+
if (input["context"] != null) value.context = input["context"] as Record<string, unknown>;
|
|
192
192
|
return { ok: true, value };
|
|
193
193
|
}
|
|
@@ -132,6 +132,8 @@ export async function handle(req: Request, deps: IntakeDeps): Promise<Response>
|
|
|
132
132
|
message: a.body,
|
|
133
133
|
route: a.route ?? null,
|
|
134
134
|
app_version: a.appVersion ?? null,
|
|
135
|
+
// Also its own column when GENESIS_SUPPORT_SEVERITY_COLUMN=true says migration 0003 added it.
|
|
136
|
+
...(a.severity && deps.env("GENESIS_SUPPORT_SEVERITY_COLUMN") === "true" ? { severity: a.severity } : {}),
|
|
135
137
|
context,
|
|
136
138
|
});
|
|
137
139
|
if ("error" in created) return refusal(created.error, cors, deps);
|