@marktiderman/genesis-cli 1.5.0 → 1.7.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.
Files changed (139) hide show
  1. package/README.md +224 -3
  2. package/dist/cli.js +4602 -1549
  3. package/dist/cli.js.map +1 -1
  4. package/dist/{config-Ci-_Ue-1.d.ts → config-CrZbM3jD.d.ts} +73 -4
  5. package/dist/doctor.d.ts +31 -4
  6. package/dist/doctor.js +976 -30
  7. package/dist/doctor.js.map +1 -1
  8. package/dist/expo.d.ts +91 -8
  9. package/dist/expo.js +207 -14
  10. package/dist/expo.js.map +1 -1
  11. package/dist/genesis-catalog.json +502 -0
  12. package/dist/index.d.ts +1 -1
  13. package/dist/index.js +987 -38
  14. package/dist/index.js.map +1 -1
  15. package/dist/scaffolder.d.ts +1 -1
  16. package/dist/scaffolder.js +9 -6
  17. package/dist/scaffolder.js.map +1 -1
  18. package/dist/starter/.eas/scripts/rollout-health.mjs +85 -0
  19. package/dist/starter/.eas/workflows/deploy-production.yml +149 -0
  20. package/dist/starter/.eas/workflows/e2e.yml +77 -0
  21. package/dist/starter/.eas/workflows/pr-preview.yml +117 -0
  22. package/dist/starter/.eas/workflows/rollout.yml +120 -0
  23. package/dist/starter/.env.example +11 -0
  24. package/dist/starter/.fingerprintignore +7 -0
  25. package/dist/starter/.maestro/README.md +38 -0
  26. package/dist/starter/.maestro/config.yaml +5 -0
  27. package/dist/starter/.maestro/flows/deep-link.yaml +22 -0
  28. package/dist/starter/.maestro/flows/launch.yaml +17 -0
  29. package/dist/starter/.maestro/flows/settings-version.yaml +28 -0
  30. package/dist/starter/.maestro/flows/sign-in-screen.yaml +17 -0
  31. package/dist/starter/.maestro/subflows/sign-in.yaml +20 -0
  32. package/dist/starter/README.md +314 -0
  33. package/dist/starter/__tests__/app-config.test.ts +51 -0
  34. package/dist/starter/__tests__/check-in-photos.test.ts +57 -0
  35. package/dist/starter/__tests__/components/css-stub.js +2 -0
  36. package/dist/starter/__tests__/components/fake-supabase.ts +136 -0
  37. package/dist/starter/__tests__/components/links.test.ts +25 -0
  38. package/dist/starter/__tests__/components/render-app.ts +22 -0
  39. package/dist/starter/__tests__/components/reports.ts +10 -0
  40. package/dist/starter/__tests__/components/resolver.js +12 -0
  41. package/dist/starter/__tests__/components/root-layout.test.tsx +55 -0
  42. package/dist/starter/__tests__/components/session-storage.test.tsx +81 -0
  43. package/dist/starter/__tests__/components/settings.test.tsx +134 -0
  44. package/dist/starter/__tests__/components/setup.ts +69 -0
  45. package/dist/starter/__tests__/components/sign-in.test.tsx +90 -0
  46. package/dist/starter/__tests__/components/tabs-feature-off.test.tsx +19 -0
  47. package/dist/starter/__tests__/components/tabs.test.tsx +43 -0
  48. package/dist/starter/__tests__/components/tabs.ts +12 -0
  49. package/dist/starter/__tests__/entry.test.ts +28 -0
  50. package/dist/starter/__tests__/inline-copy.ts +59 -0
  51. package/dist/starter/__tests__/starter.test.ts +319 -0
  52. package/dist/starter/_gitignore +13 -0
  53. package/dist/starter/app.config.ts +44 -0
  54. package/dist/starter/babel.config.js +9 -0
  55. package/dist/starter/eas.json +47 -0
  56. package/dist/starter/eslint.config.js +5 -0
  57. package/dist/starter/genesis.config.json +12 -0
  58. package/dist/starter/global.css +3 -0
  59. package/dist/starter/index.ts +14 -0
  60. package/dist/starter/jest.config.js +36 -0
  61. package/dist/starter/metro.config.js +38 -0
  62. package/dist/starter/package.json +93 -0
  63. package/dist/starter/pnpm-workspace.yaml +73 -0
  64. package/dist/starter/src/app/(app)/(home)/_layout.tsx +6 -0
  65. package/dist/starter/src/app/(app)/(home)/check-in.tsx +41 -0
  66. package/dist/starter/src/app/(app)/(home)/index.tsx +34 -0
  67. package/dist/starter/src/app/(app)/_layout.tsx +27 -0
  68. package/dist/starter/src/app/(app)/notifications/_layout.tsx +6 -0
  69. package/dist/starter/src/app/(app)/notifications/index.tsx +36 -0
  70. package/dist/starter/src/app/(app)/settings/_layout.tsx +6 -0
  71. package/dist/starter/src/app/(app)/settings/index.tsx +96 -0
  72. package/dist/starter/src/app/(app)/settings/notifications.tsx +16 -0
  73. package/dist/starter/src/app/(app)/settings/support/[id].tsx +23 -0
  74. package/dist/starter/src/app/(app)/settings/support/ideas.tsx +20 -0
  75. package/dist/starter/src/app/(app)/settings/support/index.tsx +20 -0
  76. package/dist/starter/src/app/(app)/settings/support/new.tsx +35 -0
  77. package/dist/starter/src/app/(app)/settings/support/shipped.tsx +20 -0
  78. package/dist/starter/src/app/+native-intent.ts +11 -0
  79. package/dist/starter/src/app/_layout.tsx +20 -0
  80. package/dist/starter/src/app/sign-in.tsx +69 -0
  81. package/dist/starter/src/copy.ts +118 -0
  82. package/dist/starter/src/forms/check-in.json +121 -0
  83. package/dist/starter/src/lib/account.ts +42 -0
  84. package/dist/starter/src/lib/app.ts +52 -0
  85. package/dist/starter/src/lib/auth.ts +80 -0
  86. package/dist/starter/src/lib/check-in-photos.ts +66 -0
  87. package/dist/starter/src/lib/check-in.ts +85 -0
  88. package/dist/starter/src/lib/define-starter.ts +148 -0
  89. package/dist/starter/src/lib/devtools-overlay.ts +34 -0
  90. package/dist/starter/src/lib/devtools.ts +23 -0
  91. package/dist/starter/src/lib/env.ts +33 -0
  92. package/dist/starter/src/lib/google-signin.ts +23 -0
  93. package/dist/starter/src/lib/links.ts +40 -0
  94. package/dist/starter/src/lib/native-modules.ts +27 -0
  95. package/dist/starter/src/lib/notifications.ts +15 -0
  96. package/dist/starter/src/lib/observability.ts +45 -0
  97. package/dist/starter/src/lib/push.ts +49 -0
  98. package/dist/starter/src/lib/supabase.ts +65 -0
  99. package/dist/starter/src/lib/support.ts +44 -0
  100. package/dist/starter/src/lib/updates.ts +61 -0
  101. package/dist/starter/starter.config.ts +37 -0
  102. package/dist/starter/supabase/config.toml +26 -0
  103. package/dist/starter/supabase/functions/genesis-apple-revoke/apple.ts +237 -0
  104. package/dist/starter/supabase/functions/genesis-apple-revoke/handler.ts +227 -0
  105. package/dist/starter/supabase/functions/genesis-apple-revoke/index.ts +55 -0
  106. package/dist/starter/supabase/functions/genesis-push-send/expo.ts +117 -0
  107. package/dist/starter/supabase/functions/genesis-push-send/handler.ts +462 -0
  108. package/dist/starter/supabase/functions/genesis-push-send/index.ts +54 -0
  109. package/dist/starter/supabase/migrations/20261024000000_genesis_account_deletion.sql +133 -0
  110. package/dist/starter/supabase/migrations/20261024000100_genesis_app_release_policy.sql +82 -0
  111. package/dist/starter/supabase/migrations/20261024000200_genesis_apple_token_revocation.sql +205 -0
  112. package/dist/starter/supabase/migrations/20261024000400_genesis_push.sql +524 -0
  113. package/dist/starter/supabase/migrations/20261024000600_genesis_support.sql +846 -0
  114. package/dist/starter/supabase/tests/database/genesis_account_deletion.test.sql +138 -0
  115. package/dist/starter/supabase/tests/database/genesis_app_release_policy.test.sql +148 -0
  116. package/dist/starter/supabase/tests/database/genesis_apple_token_revocation.test.sql +230 -0
  117. package/dist/starter/supabase/tests/database/genesis_push.test.sql +407 -0
  118. package/dist/starter/supabase/tests/database/genesis_support.test.sql +552 -0
  119. package/dist/starter/tailwind.config.mjs +15 -0
  120. package/dist/starter/tsconfig.json +14 -0
  121. package/dist/starter/vitest.config.mts +7 -0
  122. package/dist/templates/ci/app-ci.yml +17 -0
  123. package/dist/templates/ci/genesis-upgrade.yml +21 -0
  124. package/dist/templates/ci/supabase-ci.yml +20 -0
  125. package/dist/templates/eas/eas.json +47 -0
  126. package/dist/templates/eas/scripts/rollout-health.mjs +85 -0
  127. package/dist/templates/eas/workflows/deploy-production.yml +149 -0
  128. package/dist/templates/eas/workflows/e2e.yml +77 -0
  129. package/dist/templates/eas/workflows/pr-preview.yml +117 -0
  130. package/dist/templates/eas/workflows/rollout.yml +120 -0
  131. package/dist/templates/maestro/config.yaml +5 -0
  132. package/dist/templates/maestro/flows/deep-link.yaml +22 -0
  133. package/dist/templates/maestro/flows/launch.yaml +17 -0
  134. package/dist/templates/maestro/flows/settings-version.yaml +28 -0
  135. package/dist/templates/maestro/flows/sign-in-screen.yaml +17 -0
  136. package/dist/templates/maestro/subflows/sign-in.yaml +20 -0
  137. package/dist/vite.js +975 -29
  138. package/dist/vite.js.map +1 -1
  139. package/package.json +4 -4
@@ -0,0 +1,227 @@
1
+ /**
2
+ * The genesis-apple-revoke Edge Function's request handling, with its
3
+ * dependencies passed in (index.ts wires the real ones), so it is tested
4
+ * without Deno, a database or Apple.
5
+ *
6
+ * POST { "action": "store", "code": "<authorizationCode>", "clientId"?: "<bundle id>" }
7
+ * Authorization: Bearer <the person's access token>
8
+ * Exchanges the code from a Sign in with Apple at /auth/token and keeps
9
+ * Apple's refresh token against the caller, server-side only.
10
+ *
11
+ * POST { "action": "revoke" }
12
+ * Revokes the tokens of deleted accounts that are due (queued by the
13
+ * delete trigger, retried with backoff). It needs no caller: it only
14
+ * works through the queue, a bounded batch at a time, and answers
15
+ * `{ ok: true }` (202, working in the background, when the runtime can)
16
+ * whatever was in it. The app calls it after `delete_my_account`; a
17
+ * schedule calls it to retry.
18
+ *
19
+ * Responses never carry a token, a secret, or Apple's response body: only an
20
+ * `error` code.
21
+ */
22
+ import { checkRefreshToken, exchangeAuthorizationCode, readAppleConfig, revokeRefreshToken, type AppleConfig } from "./apple.ts";
23
+
24
+ /** The signed-in caller, as the auth server reports it. */
25
+ export interface CallerUser {
26
+ id: string;
27
+ /** The `sub` of each Apple identity linked to this login (Apple's user id). */
28
+ appleUserIds: string[];
29
+ }
30
+
31
+ export interface DueRevocation {
32
+ id: number;
33
+ client_id: string;
34
+ refresh_token: string;
35
+ attempts: number;
36
+ }
37
+
38
+ /** The SQL functions from migration 0003, called with the service role. */
39
+ export interface TokenStore {
40
+ /** `genesis_apple_token_save`: "stored", or "queued" when the login is already gone. */
41
+ save(userId: string, clientId: string, refreshToken: string): Promise<"stored" | "queued">;
42
+ /** `genesis_apple_revocations_claim`: due rows, each leased until its next retry. */
43
+ claim(limit: number): Promise<DueRevocation[]>;
44
+ /** `genesis_apple_revocation_done`: forgets a revoked token. */
45
+ done(id: number): Promise<void>;
46
+ /** `genesis_apple_revocation_failed`: keeps the row for its next retry ("retry"), or drops its token after the last attempt ("gave_up"). */
47
+ failed(id: number, error: string): Promise<"retry" | "gave_up">;
48
+ }
49
+
50
+ export interface HandlerDeps {
51
+ env: (name: string) => string | undefined;
52
+ fetch: typeof fetch;
53
+ /** The user behind an access token (checked with the auth server), or null. */
54
+ getUser(accessToken: string): Promise<CallerUser | null>;
55
+ store: TokenStore;
56
+ log: (message: string) => void;
57
+ /** Keeps work running after the response (`EdgeRuntime.waitUntil`). Without it, the revoke action answers when the batch is done. */
58
+ background?: (work: Promise<unknown>) => void;
59
+ }
60
+
61
+ export const REVOKE_BATCH = 20;
62
+ const MAX_BODY_BYTES = 4096;
63
+ const MAX_REFRESH_TOKEN = 4096;
64
+ const CODE = /^[A-Za-z0-9._-]{1,1024}$/;
65
+
66
+ const CORS = {
67
+ "access-control-allow-origin": "*",
68
+ "access-control-allow-headers": "authorization, x-client-info, apikey, content-type",
69
+ "access-control-allow-methods": "POST, OPTIONS",
70
+ };
71
+
72
+ function json(status: number, body: Record<string, unknown>): Response {
73
+ return new Response(JSON.stringify(body), { status, headers: { ...CORS, "content-type": "application/json", "cache-control": "no-store" } });
74
+ }
75
+
76
+ async function readBody(req: Request): Promise<Record<string, unknown> | null> {
77
+ if (Number(req.headers.get("content-length") ?? 0) > MAX_BODY_BYTES) return null;
78
+ const text = await req.text().catch(() => null);
79
+ if (text === null || text.length > MAX_BODY_BYTES) return null;
80
+ try {
81
+ const body: unknown = JSON.parse(text);
82
+ return body && typeof body === "object" && !Array.isArray(body) ? (body as Record<string, unknown>) : null;
83
+ } catch {
84
+ return null;
85
+ }
86
+ }
87
+
88
+ function bearer(req: Request): string | null {
89
+ const match = /^Bearer\s+(\S+)$/i.exec(req.headers.get("authorization") ?? "");
90
+ return match?.[1] ?? null;
91
+ }
92
+
93
+ const describe = (error: unknown) => (error instanceof Error ? `${error.name}: ${error.message}` : "unknown error");
94
+
95
+ export async function handle(req: Request, deps: HandlerDeps): Promise<Response> {
96
+ try {
97
+ return await route(req, deps);
98
+ } catch (error) {
99
+ // e.g. APPLE_PRIVATE_KEY isn't a P-256 key, or the database is unreachable.
100
+ deps.log(`genesis-apple-revoke: failed: ${describe(error)}`);
101
+ return json(500, { error: "internal" });
102
+ }
103
+ }
104
+
105
+ async function route(req: Request, deps: HandlerDeps): Promise<Response> {
106
+ if (req.method === "OPTIONS") return new Response(null, { status: 204, headers: CORS });
107
+ if (req.method !== "POST") return json(405, { error: "method_not_allowed" });
108
+ const body = await readBody(req);
109
+ if (!body) return json(400, { error: "bad_request" });
110
+
111
+ const apple = readAppleConfig(deps.env);
112
+ if (!apple.config) {
113
+ // Loud in the logs, by name only: a missing secret must not pass for a revoked token.
114
+ deps.log(`genesis-apple-revoke: not configured; set ${apple.problems.join(", ")}`);
115
+ return json(500, { error: "not_configured" });
116
+ }
117
+
118
+ if (body.action === "store") return store(req, body, apple.config, deps);
119
+ if (body.action === "revoke") {
120
+ const work = revokeDue(apple.config, deps);
121
+ if (deps.background) {
122
+ // The app waits on this right after deleting the account: answer now, finish the batch after.
123
+ deps.background(work);
124
+ return json(202, { ok: true });
125
+ }
126
+ await work;
127
+ return json(200, { ok: true });
128
+ }
129
+ return json(400, { error: "bad_request" });
130
+ }
131
+
132
+ async function store(req: Request, body: Record<string, unknown>, config: AppleConfig, deps: HandlerDeps): Promise<Response> {
133
+ const token = bearer(req);
134
+ const user = token ? await deps.getUser(token).catch(() => null) : null;
135
+ if (!user) return json(401, { error: "not_signed_in" });
136
+
137
+ const code = body.code;
138
+ if (typeof code !== "string" || !CODE.test(code)) return json(400, { error: "bad_request" });
139
+ const clientId = body.clientId === undefined || body.clientId === null ? config.clientIds[0]! : body.clientId;
140
+ if (typeof clientId !== "string" || !config.clientIds.includes(clientId)) {
141
+ deps.log(`genesis-apple-revoke: a store named a client id outside APPLE_CLIENT_IDS; add every bundle id the app signs in with (each build variant too)`);
142
+ return json(400, { error: "unknown_client" });
143
+ }
144
+ if (user.appleUserIds.length === 0) return json(403, { error: "no_apple_identity" });
145
+
146
+ const exchanged = await exchangeAuthorizationCode(config, clientId, code, deps.fetch);
147
+ if (!exchanged.ok) {
148
+ deps.log(`genesis-apple-revoke: code exchange failed for ${clientId}: ${exchanged.error}${exchanged.status ? ` (HTTP ${exchanged.status})` : ""}`);
149
+ // Apple minted a token whose id token we refused: revoke it rather than drop it.
150
+ if (exchanged.mintedRefreshToken) await revokeMinted(config, clientId, exchanged.mintedRefreshToken, deps);
151
+ return json(502, { error: "exchange_failed", apple: exchanged.error });
152
+ }
153
+
154
+ // The code must belong to this login's Apple identity: otherwise someone
155
+ // could file another person's token under their own account.
156
+ if (!user.appleUserIds.includes(exchanged.appleUserId)) {
157
+ deps.log("genesis-apple-revoke: a code for another Apple account was refused");
158
+ await revokeMinted(config, clientId, exchanged.refreshToken, deps);
159
+ return json(403, { error: "apple_identity_mismatch" });
160
+ }
161
+ if (exchanged.refreshToken.length > MAX_REFRESH_TOKEN) {
162
+ // The column would refuse it (and a refused row's text can reach the database's log).
163
+ deps.log("genesis-apple-revoke: Apple's refresh token is longer than the table allows");
164
+ await revokeMinted(config, clientId, exchanged.refreshToken, deps);
165
+ return json(502, { error: "exchange_failed", apple: "bad_response" });
166
+ }
167
+
168
+ const saved = await deps.store.save(user.id, clientId, exchanged.refreshToken);
169
+ // The login was deleted while this ran: the token went to the queue, so revoke now.
170
+ if (saved === "queued") await revokeDue(config, deps);
171
+ return json(200, { ok: true });
172
+ }
173
+
174
+ /** Revokes a token this request minted and won't keep (it was just issued with these secrets, so a 200 is meaningful). */
175
+ async function revokeMinted(config: AppleConfig, clientId: string, refreshToken: string, deps: HandlerDeps): Promise<void> {
176
+ const revoked = await revokeRefreshToken(config, clientId, refreshToken, deps.fetch);
177
+ if (!revoked.ok) deps.log(`genesis-apple-revoke: couldn't revoke a token it refused to keep: ${revoked.error}`);
178
+ }
179
+
180
+ /**
181
+ * Works through due revocations. Each token is first checked at /auth/token
182
+ * (`checkRefreshToken`), because /auth/revoke's 200 proves nothing on its
183
+ * own: live → revoke, and only a 200 then forgets the row; already dead
184
+ * (`invalid_grant`) → nothing to revoke, forget it; anything else (wrong
185
+ * secrets, Apple down) → retry later. Returns the counts, for logs and tests.
186
+ */
187
+ export async function revokeDue(config: AppleConfig, deps: HandlerDeps): Promise<{ revoked: number; gone: number; failed: number }> {
188
+ const counts = { revoked: 0, gone: 0, failed: 0 };
189
+ let due: DueRevocation[];
190
+ try {
191
+ due = await deps.store.claim(REVOKE_BATCH);
192
+ } catch (error) {
193
+ deps.log(`genesis-apple-revoke: couldn't read the queue: ${describe(error)}`);
194
+ return counts;
195
+ }
196
+ for (const row of due) {
197
+ // One row's trouble never stops the rest; a row whose result wasn't
198
+ // recorded comes round again when its lease ends.
199
+ try {
200
+ const check = await checkRefreshToken(config, row.client_id, row.refresh_token, deps.fetch);
201
+ if (!check.ok && check.error === "invalid_grant") {
202
+ await deps.store.done(row.id);
203
+ counts.gone++;
204
+ continue;
205
+ }
206
+ const result = check.ok ? await revokeRefreshToken(config, row.client_id, row.refresh_token, deps.fetch) : check;
207
+ if (result.ok) {
208
+ await deps.store.done(row.id);
209
+ counts.revoked++;
210
+ continue;
211
+ }
212
+ const why = `${check.ok ? "revoke" : "check"}: ${result.error}${result.status ? ` (HTTP ${result.status})` : ""}`;
213
+ counts.failed++;
214
+ const next = await deps.store.failed(row.id, why);
215
+ deps.log(
216
+ next === "gave_up"
217
+ ? `genesis-apple-revoke: GAVE UP on revocation ${row.id} for ${row.client_id} after ${row.attempts} attempts (${why}); its token is dropped and the row kept as a record`
218
+ : `genesis-apple-revoke: revocation ${row.id} for ${row.client_id} failed (attempt ${row.attempts}): ${why}; it will be retried`,
219
+ );
220
+ } catch (error) {
221
+ counts.failed++;
222
+ deps.log(`genesis-apple-revoke: revocation ${row.id} couldn't be recorded: ${describe(error)}; it will be retried`);
223
+ }
224
+ }
225
+ if (due.length) deps.log(`genesis-apple-revoke: ${counts.revoked} revoked, ${counts.gone} already invalid, ${counts.failed} failed`);
226
+ return counts;
227
+ }
@@ -0,0 +1,55 @@
1
+ // genesis-apple-revoke: keeps Sign in with Apple refresh tokens server-side and
2
+ // revokes them when the account is deleted (App Store Review Guideline 5.1.1(v)).
3
+ // A template from @marktiderman/genesis-supabase: copy this folder to your app's
4
+ // `supabase/functions/`, beside migration 0003 (see the package README).
5
+ //
6
+ // Secrets (`supabase secrets set …`): APPLE_TEAM_ID, APPLE_KEY_ID,
7
+ // APPLE_PRIVATE_KEY (the .p8 file's text) and APPLE_CLIENT_IDS (your bundle ids,
8
+ // comma-separated). SUPABASE_URL and SUPABASE_SERVICE_ROLE_KEY are set by
9
+ // Supabase. Deploy with `--no-verify-jwt` (or `verify_jwt = false` in
10
+ // config.toml): the store action checks the caller itself, and the revoke
11
+ // action must run after the caller's login is gone.
12
+ import { createClient } from "npm:@supabase/supabase-js@2.118.0";
13
+ import { handle, type CallerUser, type DueRevocation, type TokenStore } from "./handler.ts";
14
+
15
+ const url = Deno.env.get("SUPABASE_URL") ?? "";
16
+ const serviceKey = Deno.env.get("SUPABASE_SERVICE_ROLE_KEY") ?? "";
17
+ const admin = createClient(url, serviceKey, { auth: { persistSession: false, autoRefreshToken: false } });
18
+
19
+ async function rpc<T>(fn: string, args: Record<string, unknown>): Promise<T> {
20
+ const { data, error } = await admin.rpc(fn, args);
21
+ if (error) throw new Error(`${fn}: ${error.code ?? ""} ${error.message}`);
22
+ return data as T;
23
+ }
24
+
25
+ const store: TokenStore = {
26
+ save: (userId, clientId, refreshToken) =>
27
+ rpc<"stored" | "queued">("genesis_apple_token_save", { p_user_id: userId, p_client_id: clientId, p_refresh_token: refreshToken }),
28
+ claim: (limit) => rpc<DueRevocation[]>("genesis_apple_revocations_claim", { p_limit: limit }),
29
+ done: (id) => rpc<void>("genesis_apple_revocation_done", { p_id: id }),
30
+ failed: (id, error) => rpc<"retry" | "gave_up">("genesis_apple_revocation_failed", { p_id: id, p_error: error }),
31
+ };
32
+
33
+ async function getUser(accessToken: string): Promise<CallerUser | null> {
34
+ const { data, error } = await admin.auth.getUser(accessToken);
35
+ if (error || !data.user) return null;
36
+ const appleUserIds = (data.user.identities ?? [])
37
+ .filter((i) => i.provider === "apple")
38
+ .map((i) => (typeof i.identity_data?.sub === "string" ? i.identity_data.sub : i.id))
39
+ .filter((sub): sub is string => typeof sub === "string" && sub.length > 0);
40
+ return { id: data.user.id, appleUserIds };
41
+ }
42
+
43
+ const runtime = (globalThis as { EdgeRuntime?: { waitUntil(work: Promise<unknown>): void } }).EdgeRuntime;
44
+
45
+ Deno.serve((req) =>
46
+ handle(req, {
47
+ env: (name) => Deno.env.get(name),
48
+ fetch,
49
+ getUser,
50
+ store,
51
+ log: (message) => console.error(message),
52
+ // Supabase's edge runtime keeps the worker alive for this after the response.
53
+ background: runtime?.waitUntil ? (work) => runtime.waitUntil(work) : undefined,
54
+ }),
55
+ );
@@ -0,0 +1,117 @@
1
+ /**
2
+ * Expo's push service, as the genesis-push-send function uses it:
3
+ * https://docs.expo.dev/push-notifications/sending-notifications/
4
+ *
5
+ * POST /--/api/v2/push/send up to 100 messages; one ticket each, in order
6
+ * POST /--/api/v2/push/getReceipts up to 1000 ticket ids; a receipt for each one ready
7
+ *
8
+ * Nothing here logs: a caller that logs uses `describeExpoError`, which
9
+ * names a status and Expo's error code, never a token or a message body.
10
+ */
11
+
12
+ export const EXPO_SEND_URL = "https://exp.host/--/api/v2/push/send";
13
+ export const EXPO_RECEIPTS_URL = "https://exp.host/--/api/v2/push/getReceipts";
14
+ /** Expo takes up to 100 messages per send request. */
15
+ export const EXPO_SEND_BATCH = 100;
16
+ /** And up to 1000 ticket ids per receipts request. */
17
+ export const EXPO_RECEIPTS_BATCH = 1000;
18
+ const CALL_TIMEOUT_MS = 15_000;
19
+
20
+ /** One message for Expo. `data` reaches the app (`notification.request.content.data`), not the screen. */
21
+ export interface ExpoMessage {
22
+ to: string;
23
+ title?: string;
24
+ subtitle?: string;
25
+ body?: string;
26
+ data?: Record<string, unknown>;
27
+ sound?: "default" | null;
28
+ badge?: number;
29
+ /** Android: the notification channel (the app creates one per category). */
30
+ channelId?: string;
31
+ /** Seconds Apple and Google keep trying an offline phone. */
32
+ ttl?: number;
33
+ priority?: "default" | "normal" | "high";
34
+ }
35
+
36
+ /** Expo's answer for one message. */
37
+ export type ExpoTicket =
38
+ | { status: "ok"; id: string }
39
+ | { status: "error"; message?: string; details?: { error?: string } };
40
+
41
+ /** Expo's later word on one ticket. */
42
+ export type ExpoReceipt = { status: "ok" } | { status: "error"; message?: string; details?: { error?: string } };
43
+
44
+ /** Expo answered a whole request with an error status. */
45
+ export class ExpoHttpError extends Error {
46
+ constructor(readonly status: number) {
47
+ super(`Expo push answered HTTP ${status}`);
48
+ this.name = "ExpoHttpError";
49
+ }
50
+ }
51
+
52
+ /**
53
+ * Expo refused the request itself (a 4xx other than 429), as it does for a
54
+ * batch that mixes projects. A timeout, a 429 or a 5xx may have been accepted
55
+ * or may recur, so those are never resent one by one.
56
+ */
57
+ export function refusedOutright(error: unknown): boolean {
58
+ return error instanceof ExpoHttpError && error.status >= 400 && error.status < 500 && error.status !== 429;
59
+ }
60
+
61
+ /** An Expo error code (`DeviceNotRegistered`), safe to store and log; anything else becomes `Unknown`. */
62
+ export function errorCode(value: { details?: { error?: string } } | undefined): string {
63
+ const code = value?.details?.error;
64
+ return typeof code === "string" && /^[A-Za-z_]{1,64}$/.test(code) ? code : "Unknown";
65
+ }
66
+
67
+ function headers(accessToken: string | undefined): Record<string, string> {
68
+ return {
69
+ accept: "application/json",
70
+ "content-type": "application/json",
71
+ ...(accessToken ? { authorization: `Bearer ${accessToken}` } : {}),
72
+ };
73
+ }
74
+
75
+ async function post(fetchFn: typeof fetch, url: string, body: unknown, accessToken: string | undefined): Promise<unknown> {
76
+ const response = await fetchFn(url, {
77
+ method: "POST",
78
+ headers: headers(accessToken),
79
+ body: JSON.stringify(body),
80
+ signal: AbortSignal.timeout(CALL_TIMEOUT_MS),
81
+ });
82
+ // The body of an error is never read: it can echo the request back.
83
+ if (!response.ok) {
84
+ await response.body?.cancel().catch(() => {});
85
+ throw new ExpoHttpError(response.status);
86
+ }
87
+ return response.json();
88
+ }
89
+
90
+ /** Sends one batch (at most 100) and returns a ticket per message, in order. */
91
+ export async function sendBatch(fetchFn: typeof fetch, messages: ExpoMessage[], accessToken?: string): Promise<ExpoTicket[]> {
92
+ if (messages.length > EXPO_SEND_BATCH) throw new Error(`sendBatch: at most ${EXPO_SEND_BATCH} messages`);
93
+ const json = (await post(fetchFn, EXPO_SEND_URL, messages, accessToken)) as { data?: unknown };
94
+ const tickets = Array.isArray(json?.data) ? (json.data as ExpoTicket[]) : [];
95
+ // A short or malformed answer: the messages without a ticket count as failed, never as sent.
96
+ return messages.map((_, i) => {
97
+ const ticket = tickets[i];
98
+ if (ticket && ticket.status === "ok" && typeof ticket.id === "string" && ticket.id.length > 0 && ticket.id.length <= 128) return ticket;
99
+ if (ticket && ticket.status === "error") return ticket;
100
+ return { status: "error", details: { error: "NoTicket" } };
101
+ });
102
+ }
103
+
104
+ /** Receipts for up to 1000 ticket ids; ids Expo has no receipt for yet are left out. */
105
+ export async function getReceipts(fetchFn: typeof fetch, ids: string[], accessToken?: string): Promise<Record<string, ExpoReceipt>> {
106
+ if (ids.length > EXPO_RECEIPTS_BATCH) throw new Error(`getReceipts: at most ${EXPO_RECEIPTS_BATCH} ids`);
107
+ const json = (await post(fetchFn, EXPO_RECEIPTS_URL, { ids }, accessToken)) as { data?: unknown };
108
+ const data = json?.data;
109
+ return data && typeof data === "object" && !Array.isArray(data) ? (data as Record<string, ExpoReceipt>) : {};
110
+ }
111
+
112
+ /** A failed call, for a log line: the status or the error's name, never the request. */
113
+ export function describeExpoError(error: unknown): string {
114
+ if (error instanceof ExpoHttpError) return `HTTP ${error.status}`;
115
+ if (error instanceof Error) return error.name === "TimeoutError" || error.name === "AbortError" ? "timeout" : error.name;
116
+ return "unknown error";
117
+ }