@marktiderman/genesis-supabase 0.11.0 → 0.13.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 +86 -0
- package/dist/{index-CaYX9z8D.d.ts → index-CKloeGaz.d.ts} +195 -2
- package/dist/index.d.ts +1 -1
- package/dist/index.js +146 -2
- 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/tests/0006_genesis_support.test.sql +1 -1
- package/migrations/tests/0018_genesis_events.test.sql +1 -1
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -179,6 +179,86 @@ if (res.type === "success") {
|
|
|
179
179
|
it. That's harmless because of PKCE: a code is useless without the verifier, which never leaves
|
|
180
180
|
this device. The implicit flow would hand tokens to whoever owns the scheme.
|
|
181
181
|
|
|
182
|
+
### On the web: `AuthForm`
|
|
183
|
+
|
|
184
|
+
genesis-ui's `AuthForm` (inside `AuthPage`) is the web sign-in form; `createAuthFormClient` is its
|
|
185
|
+
client on Supabase Auth. The form never calls `supabase.auth` itself, and `createAuthFormClient`
|
|
186
|
+
makes no client of its own: pass it the app's, from `createGenesisSupabase()`.
|
|
187
|
+
|
|
188
|
+
```ts
|
|
189
|
+
import { createAuthFormClient } from "@marktiderman/genesis-supabase";
|
|
190
|
+
|
|
191
|
+
const client = createAuthFormClient(supabase, {
|
|
192
|
+
url: SUPABASE_URL,
|
|
193
|
+
publishableKey: SUPABASE_PUBLISHABLE_KEY,
|
|
194
|
+
redirectTo: `${location.origin}/auth/callback`,
|
|
195
|
+
resetRedirectTo: `${location.origin}/auth/new-password`,
|
|
196
|
+
});
|
|
197
|
+
// <AuthForm client={client} methods={["password", "email-code"]} onSuccess={…} />
|
|
198
|
+
```
|
|
199
|
+
|
|
200
|
+
| The form's call | Supabase Auth |
|
|
201
|
+
| --- | --- |
|
|
202
|
+
| `signInWithPassword` | `signInWithPassword` |
|
|
203
|
+
| `sendMagicLink`, `sendEmailCode` | `signInWithOtp` (`shouldCreateUser` follows the form's `allowSignUp`; without sign-up, an unknown email is answered as sent) |
|
|
204
|
+
| `verifyEmailCode` | `verifyOtp({ email, token, type: "email" })` |
|
|
205
|
+
| `signUp` | `signUp`, with the form's `signUpFields` as `options.data` (the user's metadata); `confirmEmail` when no session came back |
|
|
206
|
+
| `sendPasswordReset` | `resetPasswordForEmail` to `resetRedirectTo` |
|
|
207
|
+
| `updatePassword` | `updateUser({ password })`, on the session the reset link opened (`session_not_found` without one) |
|
|
208
|
+
| `signInWithProvider` | `signInWithOAuth` to `providerRedirectTo`, with `providerQueryParams` (leaves the page for the provider) |
|
|
209
|
+
| `sendPhoneCode`, `verifyPhoneCode` | `signInWithOtp({ phone })`, then `verifyOtp({ phone, token, type: "sms" })`: the form's `"phone-code"` method |
|
|
210
|
+
| `currentEmail` | `getSession()`: the signed-in email, which the new-password form gives the password manager (no request) |
|
|
211
|
+
| `providers` | `fetchAuthSettings`: `GET /auth/v1/settings`, the OAuth providers turned on (asked once per client) |
|
|
212
|
+
|
|
213
|
+
**Where each link comes back to.** `redirectTo` is the default for all of them. `emailRedirectTo`
|
|
214
|
+
overrides it for the emailed links (a magic link, the sign-up confirmation), `resetRedirectTo` for
|
|
215
|
+
the reset link (default `emailRedirectTo`), and `providerRedirectTo` for the providers: a string,
|
|
216
|
+
or a function of the provider's id that returns `undefined` for the default. `providerQueryParams`
|
|
217
|
+
adds parameters to the provider's authorize URL, for every provider or per provider:
|
|
218
|
+
|
|
219
|
+
```ts
|
|
220
|
+
const client = createAuthFormClient(supabase, {
|
|
221
|
+
redirectTo: `${location.origin}/auth/callback`,
|
|
222
|
+
providerRedirectTo: (provider) => (provider === "apple" ? `${location.origin}/auth/apple` : undefined),
|
|
223
|
+
providerQueryParams: (provider) => (provider === "google" ? { access_type: "offline", prompt: "consent" } : undefined),
|
|
224
|
+
});
|
|
225
|
+
```
|
|
226
|
+
|
|
227
|
+
There's no need to override `signInWithProvider` for either.
|
|
228
|
+
|
|
229
|
+
Every failure resolves as `{ error: { code, message } }` with Auth's code (`network` for a request
|
|
230
|
+
that got no answer, `session_not_found` for `AuthSessionMissingError`), also on a client made with
|
|
231
|
+
`throwOnError: true`. The form shows fixed copy for the code; Auth's `message` is never shown, only
|
|
232
|
+
sent to `reportError` when the form has no copy for the code.
|
|
233
|
+
|
|
234
|
+
- **Codes need the template.** Supabase sends the Magic Link email for a link and for a code alike,
|
|
235
|
+
and the default template has only the link: put `{{ .Token }}` in it to offer `"email-code"`.
|
|
236
|
+
With `offerCodeOnConfirm` the form also offers the code after sign-up, so put it in the Confirm
|
|
237
|
+
signup template too (`verifyOtp` with `type: "email"` confirms the account).
|
|
238
|
+
- **The code's length is the project's.** The form's `codeLength` (default 6) must match the
|
|
239
|
+
project's `otp_length` (Auth settings, "Email OTP length"). `/auth/v1/settings` doesn't report
|
|
240
|
+
it, so nothing can check it for you: with a mismatch no code can be entered whole, and code sign-in fails.
|
|
241
|
+
- **A texted code** (`"phone-code"`) needs a phone provider (Twilio, MessageBird…) turned on in
|
|
242
|
+
the project's Auth settings; its code length is the project's SMS OTP length, and the form's
|
|
243
|
+
`codeLength` must match it as for email.
|
|
244
|
+
- **The redirects** (`redirectTo`, `emailRedirectTo`, `resetRedirectTo`, `providerRedirectTo`) must be in the project's redirect allow list.
|
|
245
|
+
`createGenesisSupabase()` uses the PKCE flow (a plain `createClient` from supabase-js defaults to
|
|
246
|
+
the implicit flow), and its callback page needs nothing more on the web (`detectSessionInUrl`).
|
|
247
|
+
A PKCE link only works in the browser that asked for it, where the code verifier is stored: a
|
|
248
|
+
link opened on another device or in another browser fails.
|
|
249
|
+
- **The new-password page** shows `mode="new-password"` only after the `PASSWORD_RECOVERY` event
|
|
250
|
+
(`supabase.auth.onAuthStateChange`). Shown without the session the reset link opened, saving
|
|
251
|
+
fails with `session_not_found`.
|
|
252
|
+
- **No account enumeration without sign-up.** With `allowSignUp={false}` a magic link or code for an
|
|
253
|
+
email with no account is answered as sent, and the form's copy is neutral ("If … has an account").
|
|
254
|
+
- **Sign-up with auto-confirm does reveal accounts**: when the project confirms emails without a
|
|
255
|
+
link, signing up with an email that has an account answers `user_already_exists`. That is the
|
|
256
|
+
trade-off of auto-confirm; turn confirmation on if account existence must stay private.
|
|
257
|
+
- `fetchAuthSettings({ url, publishableKey, signal })` also says whether sign-up is closed
|
|
258
|
+
(`signUpDisabled`): pass `allowSignUp={!settings.signUpDisabled}`. It gives up after 5 seconds,
|
|
259
|
+
refuses a secret key (`sb_secret_…`), and reports only the OAuth providers in
|
|
260
|
+
`SUPABASE_OAUTH_PROVIDERS` (no `web3_*`, `saml` or `phone`).
|
|
261
|
+
|
|
182
262
|
### Deleting the account
|
|
183
263
|
|
|
184
264
|
The database half is a migration this package ships:
|
|
@@ -358,6 +438,8 @@ which isn't verified here).
|
|
|
358
438
|
no real Sign in with Apple key has been through the exchange and revocation yet (setup step 7).
|
|
359
439
|
That Apple answers `invalid_client` (not `invalid_grant`) to a live token with wrong secrets is
|
|
360
440
|
expected, not observed.
|
|
441
|
+
- **Branded auth emails.** The confirm, magic link (with the code) and reset templates are still
|
|
442
|
+
Supabase's own, set by hand in the dashboard.
|
|
361
443
|
- **Sign in with Apple on the web** (Services ID and redirect) isn't wired: the function accepts a
|
|
362
444
|
Services ID in `APPLE_CLIENT_IDS`, but exchanges codes without a `redirect_uri`, as a native
|
|
363
445
|
sign-in needs.
|
|
@@ -514,6 +596,10 @@ Functions (templates; copy the folder into `supabase/functions/`):
|
|
|
514
596
|
|
|
515
597
|
All three deploy with `verify_jwt = false` (each checks its caller or secret itself).
|
|
516
598
|
|
|
599
|
+
The intake function keeps a report's severity in its `context`. With genesis-support's migration
|
|
600
|
+
`0003_genesis_support_findings.sql` applied, set `GENESIS_SUPPORT_SEVERITY_COLUMN=true` and it also
|
|
601
|
+
writes the `severity` column.
|
|
602
|
+
|
|
517
603
|
### Not covered yet
|
|
518
604
|
|
|
519
605
|
- Not applied to a hosted project yet: the SQL is pgTAP-tested on a local database and the
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import {
|
|
1
|
+
import { SupabaseClient, SupabaseClientOptions } from '@supabase/supabase-js';
|
|
2
2
|
import './blocks.js';
|
|
3
3
|
|
|
4
4
|
/**
|
|
@@ -270,6 +270,199 @@ interface SyncFeatureRegistryOptions {
|
|
|
270
270
|
*/
|
|
271
271
|
declare function syncFeatureRegistry(client: FeatureRegistryClient, document: FeatureRegistryDocument, options: SyncFeatureRegistryOptions): Promise<boolean>;
|
|
272
272
|
|
|
273
|
+
/**
|
|
274
|
+
* Web sign-in on Supabase Auth, for genesis-ui's `AuthForm`: the calls each
|
|
275
|
+
* of its modes makes (password, magic link, emailed code, sign-up, reset, new
|
|
276
|
+
* password, providers, a texted code) and the provider list read from the project's
|
|
277
|
+
* `/auth/v1/settings`. Platform-neutral; native sign-in is on `/native`.
|
|
278
|
+
*/
|
|
279
|
+
|
|
280
|
+
/**
|
|
281
|
+
* The parts of a Supabase client {@link createAuthFormClient} uses. A `SupabaseClient` fits.
|
|
282
|
+
* `getSession`, when there, gives the new-password form the signed-in email (`currentEmail`).
|
|
283
|
+
*/
|
|
284
|
+
interface AuthFormSupabase {
|
|
285
|
+
auth: Pick<SupabaseClient["auth"], "signInWithPassword" | "signInWithOtp" | "verifyOtp" | "signUp" | "resetPasswordForEmail" | "updateUser" | "signInWithOAuth"> & Partial<Pick<SupabaseClient["auth"], "getSession">>;
|
|
286
|
+
}
|
|
287
|
+
/**
|
|
288
|
+
* Why a call failed: Supabase Auth's error `code` (`invalid_credentials`,
|
|
289
|
+
* `otp_expired`, `over_email_send_rate_limit`…), `session_not_found` when
|
|
290
|
+
* there is no session (`AuthSessionMissingError`), or `network` when the
|
|
291
|
+
* request never got an answer. The shape genesis-ui's `AuthFormError` reads.
|
|
292
|
+
* `message` is the server's text: the form never shows it (it is not marked
|
|
293
|
+
* `displayable`), only reports it for a code it has no copy for.
|
|
294
|
+
*/
|
|
295
|
+
interface AuthCallError {
|
|
296
|
+
code?: string;
|
|
297
|
+
message?: string;
|
|
298
|
+
}
|
|
299
|
+
/** What each call resolves with. Never throws. */
|
|
300
|
+
interface AuthCallResult {
|
|
301
|
+
error?: AuthCallError | null;
|
|
302
|
+
/** From `signUp`: the account waits for its email to be confirmed. */
|
|
303
|
+
confirmEmail?: boolean;
|
|
304
|
+
}
|
|
305
|
+
/**
|
|
306
|
+
* The calls genesis-ui's `AuthForm` makes (its `AuthFormClient`), on Supabase Auth.
|
|
307
|
+
*
|
|
308
|
+
* @stability Beta
|
|
309
|
+
*/
|
|
310
|
+
interface AuthFormSupabaseClient {
|
|
311
|
+
signInWithPassword(input: {
|
|
312
|
+
email: string;
|
|
313
|
+
password: string;
|
|
314
|
+
}): Promise<AuthCallResult>;
|
|
315
|
+
sendMagicLink(input: {
|
|
316
|
+
email: string;
|
|
317
|
+
createUser: boolean;
|
|
318
|
+
}): Promise<AuthCallResult>;
|
|
319
|
+
sendEmailCode(input: {
|
|
320
|
+
email: string;
|
|
321
|
+
createUser: boolean;
|
|
322
|
+
}): Promise<AuthCallResult>;
|
|
323
|
+
verifyEmailCode(input: {
|
|
324
|
+
email: string;
|
|
325
|
+
code: string;
|
|
326
|
+
}): Promise<AuthCallResult>;
|
|
327
|
+
/** `data`: the new user's metadata (`options.data`, `raw_user_meta_data`), such as `full_name`. */
|
|
328
|
+
signUp(input: {
|
|
329
|
+
email: string;
|
|
330
|
+
password: string;
|
|
331
|
+
data?: Record<string, unknown>;
|
|
332
|
+
}): Promise<AuthCallResult>;
|
|
333
|
+
sendPasswordReset(input: {
|
|
334
|
+
email: string;
|
|
335
|
+
}): Promise<AuthCallResult>;
|
|
336
|
+
updatePassword(input: {
|
|
337
|
+
password: string;
|
|
338
|
+
}): Promise<AuthCallResult>;
|
|
339
|
+
signInWithProvider(provider: string): Promise<AuthCallResult>;
|
|
340
|
+
/** A code by text message (`signInWithOtp({ phone })`). Needs a phone provider in the project's Auth settings. */
|
|
341
|
+
sendPhoneCode(input: {
|
|
342
|
+
phone: string;
|
|
343
|
+
createUser: boolean;
|
|
344
|
+
}): Promise<AuthCallResult>;
|
|
345
|
+
/** Checks a texted code (`verifyOtp({ phone, token, type: "sms" })`). */
|
|
346
|
+
verifyPhoneCode(input: {
|
|
347
|
+
phone: string;
|
|
348
|
+
code: string;
|
|
349
|
+
}): Promise<AuthCallResult>;
|
|
350
|
+
/** The signed-in user's email, from the session the client holds (no request); null without one. Present when the Supabase client has `getSession`. */
|
|
351
|
+
currentEmail?(): Promise<string | null>;
|
|
352
|
+
/** Present when `url` and `publishableKey` were given. */
|
|
353
|
+
providers?(): Promise<string[]>;
|
|
354
|
+
}
|
|
355
|
+
/** @stability Beta */
|
|
356
|
+
interface CreateAuthFormClientOptions {
|
|
357
|
+
/** The project URL, with `publishableKey`: lets the form discover its providers. */
|
|
358
|
+
url?: string;
|
|
359
|
+
/** The publishable (anon) key. */
|
|
360
|
+
publishableKey?: string;
|
|
361
|
+
/**
|
|
362
|
+
* Where a magic link, a sign-up confirmation and a provider come back to:
|
|
363
|
+
* the app's callback route (`${origin}/auth/callback`). It must be in the
|
|
364
|
+
* project's redirect allow list. Left out: the project's Site URL.
|
|
365
|
+
*/
|
|
366
|
+
redirectTo?: string;
|
|
367
|
+
/** Where the emailed links come back to (a magic link, the sign-up confirmation): overrides `redirectTo` for them. Default `redirectTo`. */
|
|
368
|
+
emailRedirectTo?: string;
|
|
369
|
+
/** Where the password-reset link opens: the page that shows `mode="new-password"`. Default `emailRedirectTo`, then `redirectTo`. */
|
|
370
|
+
resetRedirectTo?: string;
|
|
371
|
+
/**
|
|
372
|
+
* Where a provider sends the person back to, for every provider or per provider (a function of
|
|
373
|
+
* its id, `undefined` for the default): overrides `redirectTo` for providers. It must be in the
|
|
374
|
+
* project's redirect allow list. Default `redirectTo`.
|
|
375
|
+
*/
|
|
376
|
+
providerRedirectTo?: string | ((provider: string) => string | undefined);
|
|
377
|
+
/**
|
|
378
|
+
* Extra query parameters for the provider's authorize URL (`signInWithOAuth`'s
|
|
379
|
+
* `options.queryParams`): Google's `{ access_type: "offline", prompt: "consent" }`, say. One
|
|
380
|
+
* record for every provider, or a function of the provider's id. Default none.
|
|
381
|
+
*/
|
|
382
|
+
providerQueryParams?: Record<string, string> | ((provider: string) => Record<string, string> | undefined);
|
|
383
|
+
/** For the settings request. Default the global `fetch`. */
|
|
384
|
+
fetch?: typeof fetch;
|
|
385
|
+
}
|
|
386
|
+
/**
|
|
387
|
+
* genesis-ui's `AuthForm` client on Supabase Auth: password sign-in, magic
|
|
388
|
+
* link and emailed code (`signInWithOtp`, the code checked with `verifyOtp`),
|
|
389
|
+
* sign-up (`confirmEmail` when the project confirms emails), the reset email,
|
|
390
|
+
* the new password (`updateUser`, on the session the reset link opened), and
|
|
391
|
+
* OAuth providers (`signInWithOAuth`, which leaves the page; `providerRedirectTo` and
|
|
392
|
+
* `providerQueryParams` shape where it goes), and a code by text message
|
|
393
|
+
* (`signInWithOtp({ phone })`, checked with `verifyOtp` type `"sms"`). Every failure is
|
|
394
|
+
* `{ error: { code, message } }`, never a throw, also on a client made with
|
|
395
|
+
* `throwOnError: true`.
|
|
396
|
+
*
|
|
397
|
+
* It takes the app's client (from `createGenesisSupabase()`) and makes no
|
|
398
|
+
* client of its own.
|
|
399
|
+
*
|
|
400
|
+
* Without sign-up (`createUser: false`), an email with no account is answered
|
|
401
|
+
* like one with an account: the link or code is "sent". Saying otherwise would
|
|
402
|
+
* tell anyone which emails have accounts.
|
|
403
|
+
*
|
|
404
|
+
* The new-password page: show `mode="new-password"` only after the client's
|
|
405
|
+
* `PASSWORD_RECOVERY` event (`supabase.auth.onAuthStateChange`). Without the
|
|
406
|
+
* session the reset link opened, `updatePassword` fails with
|
|
407
|
+
* `session_not_found`.
|
|
408
|
+
*
|
|
409
|
+
* One email template serves the link and the code: Supabase sends the Magic
|
|
410
|
+
* Link template for both, so a form offering `"email-code"` needs
|
|
411
|
+
* `{{ .Token }}` in it (the default template has only the link). The form's
|
|
412
|
+
* `codeLength` must match the project's `otp_length`, which
|
|
413
|
+
* `/auth/v1/settings` doesn't report: with a mismatch no code can be entered
|
|
414
|
+
* whole, and code sign-in fails.
|
|
415
|
+
*
|
|
416
|
+
* ```ts
|
|
417
|
+
* const client = createAuthFormClient(supabase, {
|
|
418
|
+
* url: import.meta.env.VITE_SUPABASE_URL,
|
|
419
|
+
* publishableKey: import.meta.env.VITE_SUPABASE_PUBLISHABLE_KEY,
|
|
420
|
+
* redirectTo: `${location.origin}/auth/callback`,
|
|
421
|
+
* resetRedirectTo: `${location.origin}/auth/new-password`,
|
|
422
|
+
* });
|
|
423
|
+
* ```
|
|
424
|
+
*
|
|
425
|
+
* @stability Beta
|
|
426
|
+
*/
|
|
427
|
+
declare function createAuthFormClient(supabase: AuthFormSupabase, options?: CreateAuthFormClientOptions): AuthFormSupabaseClient;
|
|
428
|
+
/** What a project's Auth allows, from `/auth/v1/settings`. */
|
|
429
|
+
interface AuthSettings {
|
|
430
|
+
/** The OAuth providers turned on, as `signInWithOAuth` names them (`"google"`, `"apple"`…), sorted. */
|
|
431
|
+
providers: string[];
|
|
432
|
+
/** Email sign-in (password, link or code) is on. */
|
|
433
|
+
email: boolean;
|
|
434
|
+
/** Phone sign-in is on. */
|
|
435
|
+
phone: boolean;
|
|
436
|
+
/** New accounts are refused. */
|
|
437
|
+
signUpDisabled: boolean;
|
|
438
|
+
/** Emails are confirmed without a link. */
|
|
439
|
+
autoConfirm: boolean;
|
|
440
|
+
}
|
|
441
|
+
/**
|
|
442
|
+
* The OAuth providers `fetchAuthSettings` reports: the ones `signInWithOAuth`
|
|
443
|
+
* takes and genesis-ui's `AUTH_PROVIDER_NAMES` names. Any other key of the
|
|
444
|
+
* settings' `external` (`email`, `phone`, `saml`, `web3_*`…) isn't a button.
|
|
445
|
+
*
|
|
446
|
+
* @stability Beta
|
|
447
|
+
*/
|
|
448
|
+
declare const SUPABASE_OAUTH_PROVIDERS: readonly string[];
|
|
449
|
+
/**
|
|
450
|
+
* Reads a project's public Auth settings (`GET <url>/auth/v1/settings` with
|
|
451
|
+
* the publishable key): which OAuth providers are on, whether email and phone
|
|
452
|
+
* sign-in are, and whether sign-up is closed. Throws when the request fails,
|
|
453
|
+
* takes over 5 seconds or `signal` aborts it, and refuses a secret key
|
|
454
|
+
* (`sb_secret_…`), which must never reach a browser.
|
|
455
|
+
*
|
|
456
|
+
* @stability Beta
|
|
457
|
+
*/
|
|
458
|
+
declare function fetchAuthSettings({ url, publishableKey, fetch: fetcher, signal, }: {
|
|
459
|
+
url: string;
|
|
460
|
+
publishableKey: string;
|
|
461
|
+
fetch?: typeof fetch;
|
|
462
|
+
/** Cancels the request (an unmounting form, say). */
|
|
463
|
+
signal?: AbortSignal;
|
|
464
|
+
}): Promise<AuthSettings>;
|
|
465
|
+
|
|
273
466
|
/**
|
|
274
467
|
* Supabase for Genesis apps. Platform-neutral: web, React Native and the
|
|
275
468
|
* server import it. Native-only helpers (Keychain storage, foreground
|
|
@@ -399,4 +592,4 @@ interface DeleteMyAccountOptions {
|
|
|
399
592
|
*/
|
|
400
593
|
declare function deleteMyAccount(client: DeleteAccountClient, options?: DeleteMyAccountOptions): Promise<void>;
|
|
401
594
|
|
|
402
|
-
export { APPLE_REVOKE_FUNCTION as A,
|
|
595
|
+
export { APPLE_REVOKE_FUNCTION as A, deleteMyAccount as B, type CreateAuthFormClientOptions as C, type DeleteAccountClient as D, type ExpoCryptoLike as E, type FeatureGateState as F, type GenesisSupabaseOptions as G, featureGateState as H, fetchAuthSettings as I, must as J, requestAppleRevocation as K, setTenantFeature as L, storeAppleToken as M, syncFeatureRegistry as N, tenantFeatureHistory as O, type PostgrestErrorLike as P, tenantFeatureSettings as Q, tenantFeatures as R, type SessionStorage as S, type TenantFeatureChange as T, type WebCryptoSource as W, assertPkceCrypto as a, isDigestOnlyPolyfill as b, type AuthCallError as c, type AuthCallResult as d, type AuthFormSupabase as e, type AuthFormSupabaseClient as f, type AuthSettings as g, hasPkceCrypto as h, installWebCrypto as i, type DeleteMyAccountOptions as j, type FeatureGateStateOptions as k, type FeatureRegistryClient as l, type FeatureRegistryDocument as m, type FlagStateValue as n, type FunctionsClient as o, SUPABASE_OAUTH_PROVIDERS as p, type SetTenantFeatureInput as q, type StoreAppleTokenOptions as r, type StoreAppleTokenResult as s, SupabaseQueryError as t, type SyncFeatureRegistryOptions as u, type TenantFeatureSetting as v, type TenantFeatures as w, type TenantFeaturesClient as x, createAuthFormClient as y, createGenesisSupabase as z };
|
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,
|
|
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-CKloeGaz.js';
|
|
3
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
2
|
export { accountBlock, eventsBlock, featureMirrorBlock, jobsBlock, tenantFeaturesBlock } from './chunk-34OBTZJQ.js';
|
|
3
|
-
import { createClient, AuthInvalidJwtError } from '@supabase/supabase-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,150 @@ 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, emailRedirectTo = redirectTo, resetRedirectTo = emailRedirectTo, providerRedirectTo, providerQueryParams } = options;
|
|
127
|
+
const auth = supabase.auth;
|
|
128
|
+
const otp = (email, createUser) => call(
|
|
129
|
+
() => auth.signInWithOtp({ email, options: { shouldCreateUser: createUser, ...emailRedirectTo ? { emailRedirectTo } : {} } })
|
|
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, data }) => {
|
|
137
|
+
let confirmEmail = false;
|
|
138
|
+
const signUpOptions = { ...emailRedirectTo ? { emailRedirectTo } : {}, ...data ? { data } : {} };
|
|
139
|
+
const result = await call(async () => {
|
|
140
|
+
const r = await auth.signUp({ email, password, ...Object.keys(signUpOptions).length ? { options: signUpOptions } : {} });
|
|
141
|
+
confirmEmail = !r.error && !r.data.session;
|
|
142
|
+
return r;
|
|
143
|
+
});
|
|
144
|
+
return confirmEmail ? { ...result, confirmEmail } : result;
|
|
145
|
+
},
|
|
146
|
+
sendPasswordReset: ({ email }) => call(() => auth.resetPasswordForEmail(email, resetRedirectTo ? { redirectTo: resetRedirectTo } : void 0)),
|
|
147
|
+
updatePassword: ({ password }) => call(() => auth.updateUser({ password })),
|
|
148
|
+
signInWithProvider: (provider) => {
|
|
149
|
+
const back = (typeof providerRedirectTo === "function" ? providerRedirectTo(provider) : providerRedirectTo) ?? redirectTo;
|
|
150
|
+
const queryParams = typeof providerQueryParams === "function" ? providerQueryParams(provider) : providerQueryParams;
|
|
151
|
+
const oauthOptions = { ...back ? { redirectTo: back } : {}, ...queryParams && Object.keys(queryParams).length ? { queryParams } : {} };
|
|
152
|
+
return call(
|
|
153
|
+
() => auth.signInWithOAuth({
|
|
154
|
+
provider,
|
|
155
|
+
...Object.keys(oauthOptions).length ? { options: oauthOptions } : {}
|
|
156
|
+
})
|
|
157
|
+
);
|
|
158
|
+
},
|
|
159
|
+
sendPhoneCode: ({ phone, createUser }) => call(() => auth.signInWithOtp({ phone, options: { shouldCreateUser: createUser } })),
|
|
160
|
+
verifyPhoneCode: ({ phone, code }) => call(() => auth.verifyOtp({ phone, token: code, type: "sms" }))
|
|
161
|
+
};
|
|
162
|
+
const getSession = auth.getSession?.bind(auth);
|
|
163
|
+
if (getSession) {
|
|
164
|
+
client.currentEmail = async () => {
|
|
165
|
+
try {
|
|
166
|
+
return (await getSession()).data.session?.user.email ?? null;
|
|
167
|
+
} catch {
|
|
168
|
+
return null;
|
|
169
|
+
}
|
|
170
|
+
};
|
|
171
|
+
}
|
|
172
|
+
if (url && publishableKey) {
|
|
173
|
+
let providers;
|
|
174
|
+
client.providers = () => {
|
|
175
|
+
providers ??= fetchAuthSettings({ url, publishableKey, ...options.fetch ? { fetch: options.fetch } : {} }).then(
|
|
176
|
+
(settings) => settings.providers,
|
|
177
|
+
(e) => {
|
|
178
|
+
providers = void 0;
|
|
179
|
+
throw e;
|
|
180
|
+
}
|
|
181
|
+
);
|
|
182
|
+
return providers;
|
|
183
|
+
};
|
|
184
|
+
}
|
|
185
|
+
return client;
|
|
186
|
+
}
|
|
187
|
+
var SUPABASE_OAUTH_PROVIDERS = [
|
|
188
|
+
"apple",
|
|
189
|
+
"azure",
|
|
190
|
+
"bitbucket",
|
|
191
|
+
"discord",
|
|
192
|
+
"facebook",
|
|
193
|
+
"figma",
|
|
194
|
+
"github",
|
|
195
|
+
"gitlab",
|
|
196
|
+
"google",
|
|
197
|
+
"kakao",
|
|
198
|
+
"keycloak",
|
|
199
|
+
"linkedin_oidc",
|
|
200
|
+
"notion",
|
|
201
|
+
"slack_oidc",
|
|
202
|
+
"spotify",
|
|
203
|
+
"twitch",
|
|
204
|
+
"twitter",
|
|
205
|
+
"workos",
|
|
206
|
+
"zoom"
|
|
207
|
+
];
|
|
208
|
+
var OAUTH_PROVIDERS = new Set(SUPABASE_OAUTH_PROVIDERS);
|
|
209
|
+
var SETTINGS_TIMEOUT_MS = 5e3;
|
|
210
|
+
function withoutTrailingSlashes(url) {
|
|
211
|
+
let end = url.length;
|
|
212
|
+
while (end > 0 && url[end - 1] === "/") end--;
|
|
213
|
+
return url.slice(0, end);
|
|
214
|
+
}
|
|
215
|
+
async function fetchAuthSettings({
|
|
216
|
+
url,
|
|
217
|
+
publishableKey,
|
|
218
|
+
fetch: fetcher = globalThis.fetch,
|
|
219
|
+
signal
|
|
220
|
+
}) {
|
|
221
|
+
if (publishableKey.startsWith("sb_secret_")) {
|
|
222
|
+
throw new Error("fetchAuthSettings takes the publishable key, not a secret key (sb_secret_\u2026)");
|
|
223
|
+
}
|
|
224
|
+
const controller = new AbortController();
|
|
225
|
+
const timer = setTimeout(() => {
|
|
226
|
+
const timedOut = new Error("Supabase Auth settings: timed out");
|
|
227
|
+
timedOut.name = "TimeoutError";
|
|
228
|
+
controller.abort(timedOut);
|
|
229
|
+
}, SETTINGS_TIMEOUT_MS);
|
|
230
|
+
const onAbort = () => controller.abort(signal?.reason);
|
|
231
|
+
if (signal?.aborted) onAbort();
|
|
232
|
+
else signal?.addEventListener("abort", onAbort, { once: true });
|
|
233
|
+
let response;
|
|
234
|
+
try {
|
|
235
|
+
response = await fetcher(`${withoutTrailingSlashes(url)}/auth/v1/settings`, {
|
|
236
|
+
headers: { apikey: publishableKey },
|
|
237
|
+
signal: controller.signal
|
|
238
|
+
});
|
|
239
|
+
} finally {
|
|
240
|
+
clearTimeout(timer);
|
|
241
|
+
signal?.removeEventListener("abort", onAbort);
|
|
242
|
+
}
|
|
243
|
+
if (!response.ok) throw new Error(`Supabase Auth settings: ${response.status}`);
|
|
244
|
+
const body = await response.json();
|
|
245
|
+
const external = body.external ?? {};
|
|
246
|
+
return {
|
|
247
|
+
providers: Object.keys(external).filter((key) => external[key] === true && OAUTH_PROVIDERS.has(key)).sort(),
|
|
248
|
+
email: external.email === true,
|
|
249
|
+
phone: external.phone === true,
|
|
250
|
+
signUpDisabled: body.disable_signup === true,
|
|
251
|
+
autoConfirm: body.mailer_autoconfirm === true
|
|
252
|
+
};
|
|
253
|
+
}
|
|
110
254
|
|
|
111
255
|
// src/index.ts
|
|
112
256
|
function createGenesisSupabase({
|
|
@@ -160,6 +304,6 @@ async function deleteMyAccount(client, options = {}) {
|
|
|
160
304
|
await client.auth.signOut({ scope: "local" });
|
|
161
305
|
}
|
|
162
306
|
|
|
163
|
-
export { APPLE_REVOKE_FUNCTION, SupabaseQueryError, createGenesisSupabase, deleteMyAccount, featureGateState, must, requestAppleRevocation, setTenantFeature, storeAppleToken, syncFeatureRegistry, tenantFeatureHistory, tenantFeatureSettings, tenantFeatures };
|
|
307
|
+
export { APPLE_REVOKE_FUNCTION, SUPABASE_OAUTH_PROVIDERS, SupabaseQueryError, createAuthFormClient, createGenesisSupabase, deleteMyAccount, featureGateState, fetchAuthSettings, must, requestAppleRevocation, setTenantFeature, storeAppleToken, syncFeatureRegistry, tenantFeatureHistory, tenantFeatureSettings, tenantFeatures };
|
|
164
308
|
//# sourceMappingURL=index.js.map
|
|
165
309
|
//# 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;A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B,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 * 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\";\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,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AS,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 } 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-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';
|
|
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);
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
-- @feat:support-feedback
|
|
1
|
+
-- @feat:support-feedback
|
|
2
2
|
-- pgTAP test for 0006_genesis_support.sql.
|
|
3
3
|
-- Copy into your app's `supabase/tests/database/` and run `supabase test db`.
|
|
4
4
|
-- It writes only its own users, reports, ideas and storage rows and rolls everything back.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
-- @feat:
|
|
1
|
+
-- @feat:events
|
|
2
2
|
-- pgTAP test for 0018_genesis_events.sql (needs 0016).
|
|
3
3
|
-- Copy into your app's `supabase/tests/database/` and run `supabase test db`.
|
|
4
4
|
-- It writes only its own users, hook and events and rolls everything back. If your app already has
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@marktiderman/genesis-supabase",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.13.0",
|
|
4
4
|
"private": false,
|
|
5
5
|
"type": "module",
|
|
6
6
|
"sideEffects": false,
|
|
@@ -82,7 +82,7 @@
|
|
|
82
82
|
"README.md"
|
|
83
83
|
],
|
|
84
84
|
"dependencies": {
|
|
85
|
-
"@marktiderman/genesis-features": "^0.8.
|
|
85
|
+
"@marktiderman/genesis-features": "^0.8.1"
|
|
86
86
|
},
|
|
87
87
|
"peerDependencies": {
|
|
88
88
|
"@supabase/supabase-js": "^2.118.0",
|