create-expo-updates-server 0.1.5 → 0.2.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 (141) hide show
  1. package/dist/template/.dockerignore +16 -0
  2. package/dist/template/README.md +51 -660
  3. package/dist/template/app/api/admin/device-targets/route.test.ts +43 -0
  4. package/dist/template/app/api/admin/device-targets/route.ts +91 -0
  5. package/dist/template/app/api/admin/devices/route.test.ts +41 -0
  6. package/dist/template/app/api/admin/devices/route.ts +15 -0
  7. package/dist/template/app/api/admin/updates/[encodedKey]/audience/route.ts +75 -0
  8. package/dist/template/app/api/device-heartbeat/route.ts +2 -0
  9. package/dist/template/app/globals.css +114 -15
  10. package/dist/template/app/layout.tsx +12 -4
  11. package/dist/template/app/login/page.tsx +22 -18
  12. package/dist/template/app/updates/[encodedKey]/page.tsx +112 -88
  13. package/dist/template/app/updates/devices/page.tsx +264 -0
  14. package/dist/template/app/updates/embedded/page.tsx +102 -68
  15. package/dist/template/app/updates/emergency-redirects/page.tsx +144 -111
  16. package/dist/template/app/updates/layout.tsx +6 -1
  17. package/dist/template/app/updates/page.tsx +262 -212
  18. package/dist/template/components/admin/admin-shell.tsx +196 -0
  19. package/dist/template/components/admin/language-switcher.tsx +25 -0
  20. package/dist/template/components/admin/theme-provider.tsx +15 -0
  21. package/dist/template/components/ui/alert.tsx +65 -0
  22. package/dist/template/components/ui/badge.tsx +47 -0
  23. package/dist/template/components/ui/button.tsx +63 -0
  24. package/dist/template/components/ui/card.tsx +91 -0
  25. package/dist/template/components/ui/chart.tsx +373 -0
  26. package/dist/template/components/ui/checkbox.tsx +31 -0
  27. package/dist/template/components/ui/dialog.tsx +158 -0
  28. package/dist/template/components/ui/dropdown-menu.tsx +256 -0
  29. package/dist/template/components/ui/input.tsx +20 -0
  30. package/dist/template/components/ui/label.tsx +23 -0
  31. package/dist/template/components/ui/native-select.tsx +61 -0
  32. package/dist/template/components/ui/popover.tsx +88 -0
  33. package/dist/template/components/ui/scroll-area.tsx +57 -0
  34. package/dist/template/components/ui/select.tsx +189 -0
  35. package/dist/template/components/ui/separator.tsx +27 -0
  36. package/dist/template/components/ui/sheet.tsx +142 -0
  37. package/dist/template/components/ui/sidebar.tsx +736 -0
  38. package/dist/template/components/ui/skeleton.tsx +13 -0
  39. package/dist/template/components/ui/switch.tsx +34 -0
  40. package/dist/template/components/ui/table.tsx +115 -0
  41. package/dist/template/components/ui/tabs.tsx +90 -0
  42. package/dist/template/components/ui/textarea.tsx +17 -0
  43. package/dist/template/components/ui/tooltip.tsx +56 -0
  44. package/dist/template/components.json +22 -0
  45. package/dist/template/docs/admin-ui.md +35 -0
  46. package/dist/template/docs/device-targeting.md +129 -0
  47. package/dist/template/docs/doctor.md +137 -0
  48. package/dist/template/docs/expo-app-setup.md +174 -47
  49. package/dist/template/docs/getting-started.md +105 -146
  50. package/dist/template/docs/getting-started.ru.md +106 -191
  51. package/dist/template/docs/index.md +14 -33
  52. package/dist/template/docs/installation-telemetry.md +233 -0
  53. package/dist/template/docs/migrations/2026-10-16-manifest-identity.sql +89 -0
  54. package/dist/template/docs/migrations/2026-10-19-device-heartbeat.sql +131 -0
  55. package/dist/template/docs/migrations/2026-10-22-device-analytics.sql +264 -0
  56. package/dist/template/docs/migrations/2026-10-22-device-targeting-activation.sql +108 -0
  57. package/dist/template/docs/migrations/2026-10-22-device-targeting.sql +130 -0
  58. package/dist/template/docs/migrations/2026-10-22-device-version-metadata.sql +154 -0
  59. package/dist/template/docs/migrations/schema.sql +868 -6
  60. package/dist/template/docs/npm-installer.md +15 -30
  61. package/dist/template/docs/operations-guide.md +87 -0
  62. package/dist/template/docs/ota-client-lifecycle.md +263 -0
  63. package/dist/template/docs/ota-update-policy.md +36 -2
  64. package/dist/template/docs/supabase-setup.md +4 -0
  65. package/dist/template/hooks/use-mobile.ts +21 -0
  66. package/dist/template/lib/utils.ts +6 -0
  67. package/dist/template/package-lock.json +2325 -101
  68. package/dist/template/package.json +13 -3
  69. package/dist/template/scripts/configure-expo-app.mjs +11 -15
  70. package/dist/template/scripts/doctor.mjs +51 -0
  71. package/dist/template/scripts/ensure-test-bucket.mjs +21 -0
  72. package/dist/template/scripts/lib/device-identity.test.ts +29 -0
  73. package/dist/template/scripts/lib/doctor-probes.mjs +139 -0
  74. package/dist/template/scripts/lib/doctor.mjs +208 -0
  75. package/dist/template/scripts/lib/doctor.test.mjs +262 -0
  76. package/dist/template/scripts/lib/expo-app-configurator.mjs +14 -9
  77. package/dist/template/scripts/lib/expo-app-configurator.test.ts +3 -2
  78. package/dist/template/scripts/lib/ota-client-configurator.mjs +69 -0
  79. package/dist/template/scripts/lib/ota-client-configurator.test.ts +88 -0
  80. package/dist/template/scripts/lib/ota-client.test.ts +55 -0
  81. package/dist/template/scripts/lib/ota-root-hook-patcher.mjs +173 -0
  82. package/dist/template/scripts/lib/ota-root-hook-patcher.test.ts +123 -0
  83. package/dist/template/scripts/lib/ota-update-controller.test.ts +231 -0
  84. package/dist/template/scripts/tests/device-analytics-migrations.mjs +80 -0
  85. package/dist/template/scripts/tests/device-analytics.mjs +126 -0
  86. package/dist/template/scripts/tests/device-heartbeat.mjs +86 -0
  87. package/dist/template/scripts/tests/device-targeting-activation.mjs +111 -0
  88. package/dist/template/scripts/tests/device-targeting.mjs +39 -0
  89. package/dist/template/scripts/tests/device-version-metadata.mjs +31 -0
  90. package/dist/template/scripts/tests/manifest-identity-concurrency.mjs +106 -0
  91. package/dist/template/scripts/tests/manifest-identity.sql +204 -0
  92. package/dist/template/src/client/admin-types.ts +1 -0
  93. package/dist/template/src/client/devices/analytics.tsx +429 -0
  94. package/dist/template/src/client/devices/device-name.tsx +82 -0
  95. package/dist/template/src/client/devices/registry.tsx +399 -0
  96. package/dist/template/src/client/devices/use-devices-report.ts +108 -0
  97. package/dist/template/src/client/devices/version-adoption-chart.tsx +269 -0
  98. package/dist/template/src/client/devices/version-groups.test.ts +57 -0
  99. package/dist/template/src/client/devices/version-groups.ts +101 -0
  100. package/dist/template/src/client/distribution-control.tsx +135 -81
  101. package/dist/template/src/client/guard-action-combobox.tsx +13 -24
  102. package/dist/template/src/client/i18n/en.json +286 -0
  103. package/dist/template/src/client/i18n/messages.test.ts +42 -0
  104. package/dist/template/src/client/i18n/messages.ts +31 -0
  105. package/dist/template/src/client/i18n/provider.tsx +55 -0
  106. package/dist/template/src/client/i18n/use-formatters.ts +38 -0
  107. package/dist/template/src/client/logout-button.tsx +3 -1
  108. package/dist/template/src/client/update-audience-editor.tsx +285 -0
  109. package/dist/template/src/client/update-policy-editor.tsx +53 -41
  110. package/dist/template/src/server/controllers/manifest.test.ts +250 -7
  111. package/dist/template/src/server/controllers/manifest.ts +39 -31
  112. package/dist/template/src/server/devices/audience.test.ts +48 -0
  113. package/dist/template/src/server/devices/audience.ts +86 -0
  114. package/dist/template/src/server/devices/heartbeat.test.ts +39 -0
  115. package/dist/template/src/server/devices/heartbeat.ts +75 -0
  116. package/dist/template/src/server/devices/report-types.ts +114 -0
  117. package/dist/template/src/server/devices/report.test.ts +29 -0
  118. package/dist/template/src/server/devices/report.ts +27 -0
  119. package/dist/template/src/server/lib/admin-audience-activation.test.ts +94 -0
  120. package/dist/template/src/server/lib/admin-updates.ts +32 -168
  121. package/dist/template/src/server/lib/distribution-control.test.ts +23 -2
  122. package/dist/template/src/server/lib/distribution-control.ts +13 -4
  123. package/dist/template/src/server/lib/supabase.js +10 -10
  124. package/dist/template/src/server/lib/supabase.test.ts +11 -0
  125. package/dist/template/src/server/manifest/manifest-identity.test.ts +30 -0
  126. package/dist/template/src/server/manifest/manifest-identity.ts +24 -0
  127. package/dist/template/src/server/manifest/manifest-repository.ts +31 -102
  128. package/dist/template/src/server/manifest/manifest-response.ts +1 -1
  129. package/dist/template/templates/expo-app/ota-client/README.md +59 -0
  130. package/dist/template/templates/expo-app/ota-client/controller.js +60 -0
  131. package/dist/template/templates/expo-app/ota-client/device-identity.js +26 -0
  132. package/dist/template/templates/expo-app/ota-client/docs/update-lifecycle.md +52 -0
  133. package/dist/template/templates/expo-app/ota-client/index.d.ts +47 -0
  134. package/dist/template/templates/expo-app/ota-client/index.js +3 -0
  135. package/dist/template/templates/expo-app/ota-client/model/hooks/useOtaUpdates.js +48 -0
  136. package/dist/template/templates/expo-app/ota-client/model/update-controller.js +182 -0
  137. package/dist/template/templates/expo-app/ota-client/runtime.js +112 -0
  138. package/dist/template/templates/expo-app/ota-client/ui/ota-update-gate.js +56 -0
  139. package/dist/template-manifest.json +582 -77
  140. package/lib/cli.mjs +4 -6
  141. package/package.json +1 -1
@@ -1,5 +1,6 @@
1
1
  import { beforeEach, describe, expect, it, vi } from "vitest";
2
2
  import { NextRequest } from "next/server";
3
+ import { createServedManifestId } from "../manifest/manifest-identity";
3
4
 
4
5
  type Row = Record<string, unknown>;
5
6
 
@@ -9,6 +10,10 @@ const database = vi.hoisted(() => ({
9
10
  embeddedUpdates: [] as Row[],
10
11
  servedManifests: [] as Row[],
11
12
  emergencyRedirects: [] as Row[],
13
+ mappingError: null as string | null,
14
+ mappingReadError: null as string | null,
15
+ mappingWriteBarrier: null as Promise<void> | null,
16
+ mappingWriteStarted: false,
12
17
  }));
13
18
  const distributionControl = vi.hoisted(() => ({
14
19
  blocked: false,
@@ -53,13 +58,29 @@ vi.mock("../lib/supabase.js", () => {
53
58
  }
54
59
 
55
60
  upsert(row: Row) {
56
- if (this.table === "ota_served_manifest_log") {
57
- database.servedManifests.push(row);
58
- }
59
- return Promise.resolve({ data: row, error: null });
61
+ return {
62
+ execute: async () => {
63
+ if (this.table === "ota_served_manifest_log") {
64
+ database.mappingWriteStarted = true;
65
+ await database.mappingWriteBarrier;
66
+ if (database.mappingError) {
67
+ return { data: null, error: { message: database.mappingError } };
68
+ }
69
+ const existing = database.servedManifests.find(
70
+ (item) => item.served_manifest_id === row.served_manifest_id,
71
+ );
72
+ if (existing) Object.assign(existing, row);
73
+ else database.servedManifests.push(row);
74
+ }
75
+ return { data: row, error: null };
76
+ },
77
+ };
60
78
  }
61
79
 
62
80
  maybeSingle() {
81
+ if (this.table === "ota_served_manifest_log" && database.mappingReadError) {
82
+ return Promise.resolve({ data: null, error: { message: database.mappingReadError } });
83
+ }
63
84
  const rowsByTable: Record<string, Row[]> = {
64
85
  ota_update_channels: database.channels,
65
86
  ota_updates: database.updates,
@@ -78,6 +99,13 @@ vi.mock("../lib/supabase.js", () => {
78
99
 
79
100
  return {
80
101
  supabase: {
102
+ rpc: async (name: string, args: Record<string, string | null>) => {
103
+ if (name !== "ota_latest_eligible_update") throw new Error(name);
104
+ const rows = database.updates.filter((r) => r.runtime_version === args.p_runtime && r.channel === args.p_channel && r.platform === args.p_platform && r.is_active &&
105
+ (r.audience_mode === 'all' || (r.audience_mode === 'devices' && ((r.audience_installation_ids as string[] || []).includes(args.p_installation || '') || (r.audience_device_ids as string[] || []).includes(args.p_device || '')))));
106
+ rows.sort((a, b) => String(b.created_at).localeCompare(String(a.created_at)));
107
+ return { data: rows.slice(0, 1), error: null };
108
+ },
81
109
  from(table: string) {
82
110
  return new Query(table);
83
111
  },
@@ -101,6 +129,7 @@ function makeUpdate(overrides: Row = {}): Row {
101
129
  created_at_path: "2026-08-28T08-00-00.000Z",
102
130
  storage_base_path: "1.0.0/android/production/update",
103
131
  is_active: true,
132
+ audience_mode: "all",
104
133
  delivery_mode: "manual",
105
134
  guard_action: null,
106
135
  guard_payload: null,
@@ -153,6 +182,19 @@ async function requestManifest(request: NextRequest) {
153
182
  return manifestController(request);
154
183
  }
155
184
 
185
+ function seedCurrentUpdate() {
186
+ database.channels.push({
187
+ latest_update_id: selectedUpdateId,
188
+ active_update_id: null,
189
+ served_manifest_id: servedManifestId,
190
+ served_manifest_changed_at: "2026-08-28T09:00:00.000Z",
191
+ runtime_version: "1.0.0",
192
+ channel: "production",
193
+ platform: "android",
194
+ });
195
+ database.updates.push(makeUpdate());
196
+ }
197
+
156
198
  describe("GET /api/manifest", () => {
157
199
  beforeEach(() => {
158
200
  vi.resetModules();
@@ -161,10 +203,166 @@ describe("GET /api/manifest", () => {
161
203
  database.embeddedUpdates = [];
162
204
  database.servedManifests = [];
163
205
  database.emergencyRedirects = [];
206
+ database.mappingError = null;
207
+ database.mappingReadError = null;
208
+ database.mappingWriteBarrier = null;
209
+ database.mappingWriteStarted = false;
164
210
  distributionControl.blocked = false;
165
211
  distributionControl.error = null;
166
212
  });
167
213
 
214
+ it("does not reuse a fallback manifest ID when its draft target becomes active", async () => {
215
+ database.channels.push({
216
+ latest_update_id: selectedUpdateId,
217
+ active_update_id: null,
218
+ served_manifest_id: servedManifestId,
219
+ served_manifest_changed_at: "2026-08-28T09:00:00.000Z",
220
+ runtime_version: "1.0.0",
221
+ channel: "production",
222
+ platform: "android",
223
+ });
224
+ const draft = makeUpdate({ is_active: false });
225
+ const stable = makeUpdate({
226
+ update_id: previousUpdateId,
227
+ created_at: "2026-08-27T08:00:00.000Z",
228
+ });
229
+ database.updates.push(draft, stable);
230
+ // Warm the old implementation's table-detection cache with a known ID.
231
+ database.servedManifests.push({
232
+ served_manifest_id: previousServedManifestId,
233
+ update_id: previousUpdateId,
234
+ });
235
+ await requestManifest(makeRequest({
236
+ "expo-current-update-id": previousServedManifestId,
237
+ }));
238
+
239
+ const first = await requestManifest(makeRequest());
240
+ const fallbackId = (await first.text()).match(/"id":"([^"]+)"/)?.[1];
241
+ expect(fallbackId).toBeTruthy();
242
+ expect(database.servedManifests.find(
243
+ (row) => row.served_manifest_id === fallbackId,
244
+ )?.update_id).toBe(previousUpdateId);
245
+
246
+ // Even a stale channel snapshot must not give two artifacts the same ID.
247
+ draft.is_active = true;
248
+ stable.is_active = false;
249
+ const second = await requestManifest(makeRequest({
250
+ "expo-current-update-id": fallbackId!,
251
+ }));
252
+ const body = await second.text();
253
+ expect(body).toContain('"launchAsset"');
254
+ expect(body).not.toContain(`"id":"${fallbackId}"`);
255
+ expect(database.servedManifests.find(
256
+ (row) => row.served_manifest_id === fallbackId,
257
+ )?.update_id).toBe(previousUpdateId);
258
+ });
259
+
260
+ it("serves the same identity on cold workers and concurrent repeated requests", async () => {
261
+ seedCurrentUpdate();
262
+ const first = await (await requestManifest(makeRequest())).text();
263
+ const id = first.match(/"id":"([^"]+)"/)?.[1];
264
+ expect(id).toBeTruthy();
265
+ vi.resetModules();
266
+ const responses = await Promise.all([
267
+ requestManifest(makeRequest()),
268
+ requestManifest(makeRequest()),
269
+ ]);
270
+ for (const response of responses) {
271
+ expect(await response.text()).toContain(`"id":"${id}"`);
272
+ }
273
+ expect(database.servedManifests).toHaveLength(1);
274
+ });
275
+
276
+ it("waits for the mapping write before completing a manifest response", async () => {
277
+ seedCurrentUpdate();
278
+ let release!: () => void;
279
+ database.mappingWriteBarrier = new Promise<void>((resolve) => { release = resolve; });
280
+ let completed = false;
281
+ const pending = requestManifest(makeRequest()).then((response) => {
282
+ completed = true;
283
+ return response;
284
+ });
285
+ try {
286
+ await vi.waitFor(() => expect(database.mappingWriteStarted).toBe(true));
287
+ expect(completed).toBe(false);
288
+ expect(database.servedManifests).toHaveLength(0);
289
+ } finally {
290
+ release();
291
+ }
292
+ expect((await pending).status).toBe(200);
293
+ expect(database.servedManifests).toHaveLength(1);
294
+ });
295
+
296
+ it.each([
297
+ 'relation "ota_served_manifest_log" does not exist',
298
+ "database unavailable",
299
+ "OTA_MANIFEST_IDENTITY_CONFLICT",
300
+ ])("does not deliver a manifest if the mapping cannot be recorded: %s", async (error) => {
301
+ seedCurrentUpdate();
302
+ database.mappingError = error;
303
+ const response = await requestManifest(makeRequest());
304
+ expect(response.status).toBe(500);
305
+ expect(await response.text()).not.toContain('"launchAsset"');
306
+ expect(database.servedManifests).toHaveLength(0);
307
+ // A recovered database must be usable without restarting the worker.
308
+ database.mappingError = null;
309
+ expect((await requestManifest(makeRequest())).status).toBe(200);
310
+ });
311
+
312
+ it("fails the request on a mapping lookup error and recovers on the next request", async () => {
313
+ seedCurrentUpdate();
314
+ database.mappingReadError = "database unavailable";
315
+ const request = () => makeRequest({ "expo-current-update-id": previousServedManifestId });
316
+ const response = await requestManifest(request());
317
+ expect(response.status).toBe(500);
318
+ expect(await response.text()).not.toContain('"launchAsset"');
319
+ expect(database.mappingWriteStarted).toBe(false);
320
+ database.mappingReadError = null;
321
+ expect((await requestManifest(request())).status).toBe(200);
322
+ });
323
+
324
+ it("uses the newer activation epoch timestamp for the newly activated artifact", async () => {
325
+ seedCurrentUpdate();
326
+ const draft = database.updates[0];
327
+ draft.is_active = false;
328
+ const stable = makeUpdate({
329
+ update_id: previousUpdateId,
330
+ created_at: "2026-08-27T08:00:00.000Z",
331
+ });
332
+ database.updates.push(stable);
333
+ const fallback = await (await requestManifest(makeRequest())).text();
334
+ const fallbackId = fallback.match(/"id":"([^"]+)"/)?.[1];
335
+ const fallbackDate = fallback.match(/"createdAt":"([^"]+)"/)?.[1];
336
+ expect(fallbackId).toBeTruthy();
337
+ expect(fallbackDate).toBeTruthy();
338
+ draft.is_active = true;
339
+ stable.is_active = false;
340
+ // The SQL integration script separately exercises the activation trigger.
341
+ database.channels[0].served_manifest_id = previousServedManifestId;
342
+ database.channels[0].served_manifest_changed_at = "2026-08-28T09:00:00.001Z";
343
+ const activated = await (await requestManifest(makeRequest({
344
+ "expo-current-update-id": fallbackId!,
345
+ }))).text();
346
+ const activatedDate = activated.match(/"createdAt":"([^"]+)"/)?.[1];
347
+ expect(activated).toContain('"launchAsset"');
348
+ expect(Date.parse(activatedDate!)).toBeGreaterThan(Date.parse(fallbackDate!));
349
+ });
350
+
351
+ it.each([selectedUpdateId, previousServedManifestId])(
352
+ "does not redownload an artifact already running under legacy ID %s",
353
+ async (id) => {
354
+ seedCurrentUpdate();
355
+ database.servedManifests.push({
356
+ served_manifest_id: previousServedManifestId,
357
+ update_id: selectedUpdateId,
358
+ });
359
+ const response = await requestManifest(makeRequest({ "expo-current-update-id": id }));
360
+ expect(response.status).toBe(200);
361
+ expect(await response.text()).toContain('"type":"noUpdateAvailable"');
362
+ expect(database.mappingWriteStarted).toBe(false);
363
+ },
364
+ );
365
+
168
366
  it("returns signed noUpdateAvailable before redirect or update selection when globally blocked", async () => {
169
367
  distributionControl.blocked = true;
170
368
  vi.stubEnv(
@@ -265,8 +463,8 @@ describe("GET /api/manifest", () => {
265
463
  const body = await response.text();
266
464
 
267
465
  expect(response.status).toBe(200);
268
- expect(response.headers.get("cache-control")).toBe("private, max-age=0");
269
- expect(body).toContain(`"id":"${servedManifestId}"`);
466
+ expect(response.headers.get("cache-control")).toBe("private, no-store");
467
+ expect(body).toContain(`"id":"${createServedManifestId(servedManifestId, selectedUpdateId)}"`);
270
468
  expect(body).toContain('"createdAt":"2026-08-28T09:00:00.000Z"');
271
469
  expect(body).toContain('"runtimeVersion":"1.0.0"');
272
470
  expect(body).toContain(
@@ -661,7 +859,7 @@ describe("GET /api/manifest", () => {
661
859
  const body = await response.text();
662
860
 
663
861
  expect(response.status).toBe(200);
664
- expect(body).toContain(`"id":"${previousUpdateId}"`);
862
+ expect(body).toContain(`"id":"${createServedManifestId(servedManifestId, previousUpdateId)}"`);
665
863
  expect(body).toContain(`updateId=${previousUpdateId}`);
666
864
  expect(body).toContain('"launchAsset"');
667
865
  });
@@ -713,6 +911,7 @@ describe("GET /api/manifest", () => {
713
911
  expect(response.status).toBe(200);
714
912
  expect(body).toContain(`updateId=${recoveryUpdateId}`);
715
913
  expect(body).toContain("channel=production");
914
+ expect(body).toContain('"metadata":{"channel":"production"}');
716
915
  });
717
916
 
718
917
  it("applies an emergency redirect stored in the database", async () => {
@@ -763,6 +962,7 @@ describe("GET /api/manifest", () => {
763
962
  expect(response.status).toBe(200);
764
963
  expect(body).toContain(`updateId=${recoveryUpdateId}`);
765
964
  expect(body).toContain("channel=production");
965
+ expect(body).toContain('"metadata":{"channel":"production"}');
766
966
  });
767
967
 
768
968
  it("returns no update when a pinned redirect target does not match", async () => {
@@ -811,4 +1011,47 @@ describe("GET /api/manifest", () => {
811
1011
  expect(body).toContain('{"type":"noUpdateAvailable"}');
812
1012
  expect(body).not.toContain('"launchAsset"');
813
1013
  });
1014
+ it("serves a targeted release only to its device; anonymous and other devices receive public fallback", async () => {
1015
+ seedCurrentUpdate();
1016
+ Object.assign(database.updates[0], { audience_mode: 'devices', audience_device_ids: ['a'.repeat(64)], delivery_mode: 'background', guard_action: 'force-update' });
1017
+ database.updates.push(makeUpdate({ update_id: previousUpdateId, created_at: '2026-08-27T08:00:00Z' }));
1018
+ for (const extra of ['', 'device_id="' + 'b'.repeat(64) + '"', 'device_id=invalid']) {
1019
+ const response = await requestManifest(makeRequest({ 'expo-extra-params': extra }));
1020
+ expect(await response.text()).toContain(createServedManifestId(servedManifestId, previousUpdateId));
1021
+ expect(response.headers.get('cache-control')).toContain('no-store');
1022
+ }
1023
+ const response = await requestManifest(makeRequest({ 'expo-extra-params': 'device_id="' + 'a'.repeat(64) + '"' }));
1024
+ expect(await response.text()).toContain(createServedManifestId(servedManifestId, selectedUpdateId));
1025
+ });
1026
+ it("fails closed for a private-only release and accepts a matching installation", async () => {
1027
+ seedCurrentUpdate();
1028
+ Object.assign(database.updates[0], { audience_mode: 'devices', audience_installation_ids: [previousUpdateId] });
1029
+ expect(await (await requestManifest(makeRequest())).text()).toContain('noUpdateAvailable');
1030
+ expect(await (await requestManifest(makeRequest({ 'expo-extra-params': `installation_id="${previousUpdateId}"` }))).text()).toContain('"launchAsset"');
1031
+ });
1032
+ it("does not serve a cross-runtime pointed artifact even to a matching target", async () => {
1033
+ seedCurrentUpdate(); database.updates[0].runtime_version = 'another-runtime';
1034
+ expect(await (await requestManifest(makeRequest())).text()).toContain('noUpdateAvailable');
1035
+ });
1036
+ it("keeps an explicit public rollback ahead of newer targeted releases", async () => {
1037
+ seedCurrentUpdate();
1038
+ database.channels[0].active_update_id = previousUpdateId;
1039
+ database.updates.push(makeUpdate({ update_id: previousUpdateId, created_at: '2026-08-27T08:00:00Z' }));
1040
+ Object.assign(database.updates[0], { audience_mode: 'devices', audience_device_ids: ['a'.repeat(64)] });
1041
+ const body = await (await requestManifest(makeRequest({ 'expo-extra-params': 'device_id="' + 'a'.repeat(64) + '"' }))).text();
1042
+ expect(body).toContain(createServedManifestId(servedManifestId, previousUpdateId));
1043
+ });
1044
+
1045
+ it("does not grant rollback downgrade privileges to a device outside its audience", async () => {
1046
+ seedCurrentUpdate();
1047
+ database.channels[0].active_update_id = previousUpdateId;
1048
+ database.updates.push(makeUpdate({ update_id: previousUpdateId, created_at: '2026-08-27T08:00:00Z', audience_mode: 'devices', audience_device_ids: ['a'.repeat(64)] }));
1049
+ const current = '55555555-5555-4555-8555-555555555555';
1050
+ database.updates.push(makeUpdate({ update_id: current, created_at: '2026-08-29T08:00:00Z', is_active: false }));
1051
+ const outside = await requestManifest(makeRequest({ 'expo-current-update-id': current }));
1052
+ expect(await outside.text()).toContain('noUpdateAvailable');
1053
+ const selected = await requestManifest(makeRequest({ 'expo-current-update-id': current, 'expo-extra-params': 'device_id="' + 'a'.repeat(64) + '"' }));
1054
+ expect(await selected.text()).toContain(createServedManifestId(servedManifestId, previousUpdateId));
1055
+ });
1056
+
814
1057
  });
@@ -1,3 +1,4 @@
1
+ import { eligibleForAudience, readRequestIdentity } from "../devices/audience";
1
2
  import NodeFormData from "form-data";
2
3
  import { toPosixPath } from "../lib/manifest-helpers.js";
3
4
  import { createSignatureHeaderIfRequested } from "../lib/signing.js";
@@ -6,6 +7,7 @@ import { createManifestUpdatePolicy } from "../lib/update-policy";
6
7
  import { NextRequest } from "next/server.js";
7
8
  import { resolveEmergencyChannelRedirect } from "../lib/emergency-channel-redirects";
8
9
  import { getRequestedChannel } from "../manifest/manifest-request";
10
+ import { createServedManifestId } from "../manifest/manifest-identity";
9
11
  import {
10
12
  buildAssetUrl,
11
13
  createExpoClientConfig,
@@ -28,10 +30,9 @@ import {
28
30
  getChannelRow,
29
31
  getLatestActiveUpdate,
30
32
  getUpdateByUpdateId,
31
- logServedManifest,
33
+ recordServedManifest,
32
34
  OtaUpdateRow,
33
35
  resolveDeviceBaselineMeta,
34
- resolveManifestId,
35
36
  resolveUpdateIdFromServedManifestId,
36
37
  } from "../manifest/manifest-repository";
37
38
  import { isOtaDistributionBlocked } from "../lib/distribution-control";
@@ -138,6 +139,16 @@ const manifestController = async (req: NextRequest) => {
138
139
  }
139
140
 
140
141
  try {
142
+ const identity = readRequestIdentity(req.headers);
143
+ const inScopeAndEligible = (row: OtaUpdateRow | null) =>
144
+ Boolean(
145
+ row &&
146
+ row.is_active &&
147
+ row.runtime_version === runtimeVersion &&
148
+ row.channel === channel &&
149
+ row.platform === platform &&
150
+ eligibleForAudience(row, identity),
151
+ );
141
152
  const channelRow = await getChannelRow({
142
153
  runtimeVersion,
143
154
  channel,
@@ -158,7 +169,7 @@ const manifestController = async (req: NextRequest) => {
158
169
  ? channelRow.active_update_id
159
170
  : null;
160
171
 
161
- const rollbackMode = Boolean(rollbackUpdateId);
172
+ let rollbackMode = Boolean(rollbackUpdateId);
162
173
 
163
174
  const selectedUpdateId =
164
175
  rollbackUpdateId || channelRow?.latest_update_id || null;
@@ -181,15 +192,16 @@ const manifestController = async (req: NextRequest) => {
181
192
  let updateRow = await getUpdateByUpdateId(selectedUpdateId);
182
193
  let latestActiveUpdateRow: OtaUpdateRow | null = null;
183
194
 
184
- if (!updateRow || !updateRow.is_active) {
195
+ if (!inScopeAndEligible(updateRow)) {
185
196
  latestActiveUpdateRow = await getLatestActiveUpdate({
197
+ identity,
186
198
  runtimeVersion,
187
199
  channel,
188
200
  platform,
189
201
  });
190
202
  }
191
203
 
192
- if ((!updateRow || !updateRow.is_active) && rollbackUpdateId) {
204
+ if (!inScopeAndEligible(updateRow) && rollbackUpdateId) {
193
205
  updateRow = latestActiveUpdateRow;
194
206
 
195
207
  console.log(
@@ -197,7 +209,7 @@ const manifestController = async (req: NextRequest) => {
197
209
  rollbackUpdateId,
198
210
  )} fallbackLatestActiveUpdateId=${debugString(latestActiveUpdateRow?.update_id)}`,
199
211
  );
200
- } else if (!rollbackMode && (!updateRow || !updateRow.is_active)) {
212
+ } else if (!rollbackMode && !inScopeAndEligible(updateRow)) {
201
213
  updateRow = latestActiveUpdateRow;
202
214
 
203
215
  console.log(
@@ -207,6 +219,10 @@ const manifestController = async (req: NextRequest) => {
207
219
  );
208
220
  }
209
221
 
222
+ rollbackMode = Boolean(
223
+ rollbackUpdateId && updateRow?.update_id === rollbackUpdateId,
224
+ );
225
+
210
226
  console.log(
211
227
  `[${new Date().toLocaleTimeString()}] 📄 Selected update row ${requestContext} updateId=${debugString(
212
228
  updateRow?.update_id,
@@ -217,7 +233,7 @@ const manifestController = async (req: NextRequest) => {
217
233
  )}`,
218
234
  );
219
235
 
220
- if (!updateRow || !updateRow.is_active) {
236
+ if (!updateRow || !inScopeAndEligible(updateRow)) {
221
237
  console.log(
222
238
  `[${new Date().toLocaleTimeString()}] ⏭️ Returning noUpdateAvailable ${requestContext} reason=missing-or-inactive-update-row`,
223
239
  );
@@ -366,19 +382,12 @@ const manifestController = async (req: NextRequest) => {
366
382
  ? updateInfo.fileMetadata[platform]
367
383
  : null;
368
384
 
369
- // served_manifest_id is a fresh UUID generated by DB trigger on every channel
370
- // change (deploy, rollback, promote). Using it as manifest id ensures:
371
- // 1. The update lands in SQLite with a fresh commit_time (active_changed_at),
372
- // so LauncherSelectionPolicy always picks it over any stale phantom entries.
373
- // 2. No PRIMARY KEY conflict — this UUID has never been in the client's SQLite.
374
- //
375
- // "noUpdate" matching checks BOTH served_manifest_id AND the raw update_id so
376
- // that devices already running the target build are not offered a redundant update:
377
- // - device received the update via a previous served_manifest_id → matches id
378
- // - device received the update via its original update_id (e.g. first-time deploy
379
- // where served_manifest_id happened to equal update_id, or legacy flow) → matches update_id
380
- const manifestId = normalizeId(channelRow?.served_manifest_id);
381
- const id = resolveManifestId(manifestId, updateRow.update_id);
385
+ // A channel epoch may serve a fallback while its latest upload is a draft.
386
+ // Include the actual selected artifact so the two never share a manifest ID.
387
+ const id = createServedManifestId(
388
+ channelRow?.served_manifest_id,
389
+ updateRow.update_id,
390
+ );
382
391
 
383
392
  // A normal deploy must remain newer than the embedded update, while a rollback
384
393
  // needs the fresh served-manifest timestamp to bypass Expo downgrade protection.
@@ -656,6 +665,16 @@ const manifestController = async (req: NextRequest) => {
656
665
  buffer: new Uint8Array(form.getBuffer()),
657
666
  });
658
667
 
668
+ // Never send a manifest whose identity has not been durably recorded.
669
+ await recordServedManifest({
670
+ servedManifestId: id,
671
+ updateId: updateRow.update_id,
672
+ runtimeVersion,
673
+ channel,
674
+ platform,
675
+ reason: rollbackMode ? "rollback" : "deploy",
676
+ });
677
+
659
678
  console.log(
660
679
  `[${new Date().toLocaleTimeString()}] 📤 Manifest multipart sent ${buildRequestContext(
661
680
  {
@@ -667,17 +686,6 @@ const manifestController = async (req: NextRequest) => {
667
686
  )} id=${id} protocol=${protocolVersion}`,
668
687
  );
669
688
 
670
- // Log the mapping so future requests can resolve this served_manifest_id
671
- // back to the real update_id (needed to detect "already on this version").
672
- logServedManifest({
673
- servedManifestId: id,
674
- updateId: updateRow.update_id,
675
- runtimeVersion,
676
- channel,
677
- platform,
678
- reason: rollbackMode ? "rollback" : "deploy",
679
- });
680
-
681
689
  return response;
682
690
  } catch (error: unknown) {
683
691
  console.error(
@@ -0,0 +1,48 @@
1
+ import { describe, it, expect } from "vitest";
2
+ import {
3
+ readRequestIdentity,
4
+ parseAudience,
5
+ eligibleForAudience,
6
+ } from "./audience";
7
+ const id = "11111111-1111-4111-8111-111111111111";
8
+ describe("audience contract", () => {
9
+ it("reads Expo structured fields with unrelated parameters; ignores malformed identities", () => {
10
+ expect(
11
+ readRequestIdentity(
12
+ new Headers({
13
+ "expo-extra-params": `installation_id="${id}", device_id="${"a".repeat(64)}", other="escaped\\\"value"`,
14
+ }),
15
+ ),
16
+ ).toEqual({ installationId: id, deviceId: "a".repeat(64) });
17
+ expect(
18
+ readRequestIdentity(
19
+ new Headers({ "expo-extra-params": `installation_id=${id}` }),
20
+ ).installationId,
21
+ ).toBeNull();
22
+ expect(
23
+ readRequestIdentity(new Headers({ "expo-extra-params": 'broken="' }))
24
+ .deviceId,
25
+ ).toBeNull();
26
+ });
27
+ it("rejects empty selected audience and unknown mode; missing fields fail closed", () => {
28
+ const base = {
29
+ audience_mode: "devices",
30
+ audience_version: 1,
31
+ audience_installation_ids: [],
32
+ audience_device_ids: [],
33
+ };
34
+ expect(() => parseAudience(base)).toThrow("Select");
35
+ expect(() =>
36
+ parseAudience({ ...base, audience_mode: "surprise" }),
37
+ ).toThrow();
38
+ expect(
39
+ eligibleForAudience({}, { installationId: id, deviceId: null }),
40
+ ).toBe(false);
41
+ expect(
42
+ eligibleForAudience(
43
+ { ...base, audience_mode: "devices", audience_installation_ids: [id] },
44
+ { installationId: id, deviceId: null },
45
+ ),
46
+ ).toBe(true);
47
+ });
48
+ });
@@ -0,0 +1,86 @@
1
+ import { parseDictionary } from "structured-headers";
2
+
3
+ export const installationIdPattern =
4
+ /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
5
+ export const deviceIdPattern = /^[0-9a-f]{64}$/;
6
+ export type Audience = {
7
+ audience_mode: "all" | "devices";
8
+ audience_installation_ids: string[];
9
+ audience_device_ids: string[];
10
+ audience_version: number;
11
+ };
12
+ export type RequestIdentity = {
13
+ installationId: string | null;
14
+ deviceId: string | null;
15
+ };
16
+
17
+ export function readRequestIdentity(headers: Headers): RequestIdentity {
18
+ const anonymous = { installationId: null, deviceId: null };
19
+ const raw = headers.get("expo-extra-params");
20
+ if (!raw || raw.length > 8192) return anonymous;
21
+ try {
22
+ const params = parseDictionary(raw);
23
+ const installation = params.get("installation_id")?.[0];
24
+ const device = params.get("device_id")?.[0];
25
+ return {
26
+ installationId:
27
+ typeof installation === "string" &&
28
+ installationIdPattern.test(installation.toLowerCase())
29
+ ? installation.toLowerCase()
30
+ : null,
31
+ deviceId:
32
+ typeof device === "string" && deviceIdPattern.test(device)
33
+ ? device
34
+ : null,
35
+ };
36
+ } catch {
37
+ return anonymous;
38
+ }
39
+ }
40
+
41
+ export function eligibleForAudience(
42
+ row: Partial<Audience>,
43
+ identity: RequestIdentity,
44
+ ): boolean {
45
+ if (row.audience_mode === "all") return true;
46
+ if (row.audience_mode !== "devices") return false;
47
+ return Boolean(
48
+ (identity.installationId &&
49
+ row.audience_installation_ids?.includes(identity.installationId)) ||
50
+ (identity.deviceId && row.audience_device_ids?.includes(identity.deviceId)),
51
+ );
52
+ }
53
+
54
+ export function parseAudience(value: unknown): Audience {
55
+ if (!value || typeof value !== "object") throw new Error("Invalid audience");
56
+ const v = value as Record<string, unknown>;
57
+ const ids = (key: string, pattern: RegExp): string[] => {
58
+ const list = v[key];
59
+ if (
60
+ !Array.isArray(list) ||
61
+ list.length > 100 ||
62
+ list.some((id) => typeof id !== "string" || !pattern.test(id))
63
+ )
64
+ throw new Error("Invalid target IDs (maximum 100 per type)");
65
+ return [...new Set(list)];
66
+ };
67
+ const installations = ids("audience_installation_ids", installationIdPattern);
68
+ const devices = ids("audience_device_ids", deviceIdPattern);
69
+ if (
70
+ (v.audience_mode !== "all" && v.audience_mode !== "devices") ||
71
+ !Number.isSafeInteger(v.audience_version) ||
72
+ Number(v.audience_version) < 1
73
+ )
74
+ throw new Error("Invalid audience mode or version");
75
+ if (
76
+ v.audience_mode === "devices" &&
77
+ installations.length + devices.length === 0
78
+ )
79
+ throw new Error("Select at least one device or installation");
80
+ return {
81
+ audience_mode: v.audience_mode,
82
+ audience_installation_ids: installations,
83
+ audience_device_ids: devices,
84
+ audience_version: Number(v.audience_version),
85
+ };
86
+ }
@@ -0,0 +1,39 @@
1
+ import { beforeEach, describe, expect, it, vi } from 'vitest';
2
+ const rpc = vi.hoisted(() => vi.fn());
3
+ vi.mock('../lib/supabase.js', () => ({ supabase: { rpc }, jsonb: (v: unknown) => v }));
4
+ import { parseHeartbeat, recordHeartbeat } from './heartbeat';
5
+ import { parseDeviceFilters } from './report';
6
+ const event = { installationId: 'b1c01662-c4e1-41a0-8556-a6c2a9dee467', eventId: 'd28a640f-f4c3-47ae-9044-58a950ad6d38', sequence: 1, observedAt: '2026-10-19T12:00:00.000Z', platform: 'android', channel: 'test', runtimeVersion: 'v1', updateId: null, nativeVersion: '1.0', nativeBuild: '1', isEmbeddedLaunch: true, isEmergencyLaunch: false };
7
+ function request(body: unknown) { return new Request('http://test/api/device-heartbeat', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) }); }
8
+ describe('heartbeat boundary', () => {
9
+ beforeEach(() => { rpc.mockReset(); rpc.mockResolvedValue({ data: [{ result: 'accepted' }] }); });
10
+ it('normalizes IDs, strips unexpected keys and stores actual launch info', async () => {
11
+ const response = await recordHeartbeat(request({ ...event, installationId: event.installationId.toUpperCase(), token: 'not stored' }));
12
+ expect(response.status).toBe(200);
13
+ expect(rpc).toHaveBeenCalledWith('ota_record_heartbeat', { p_event: event });
14
+ });
15
+ it.each([{ sequence: 0 }, { sequence: 1.5 }, { sequence: Number.MAX_SAFE_INTEGER + 1 }, { installationId: 'bad' }, { platform: 'web' }, { platform: ['ios'] }, { nativeVersion: {} }, { isEmbeddedLaunch: 'true' }, { observedAt: 'yesterday' }, { channel: 'BAD' }, { updateId: 'bad' }])('rejects malformed input %j', async (patch) => {
16
+ expect((await recordHeartbeat(request({ ...event, ...patch }))).status).toBe(400);
17
+ expect(rpc).not.toHaveBeenCalled();
18
+ });
19
+ it('limits streamed bodies without a content length', async () => {
20
+ const stream = new ReadableStream({ start(c) { c.enqueue(new TextEncoder().encode(' '.repeat(9000))); c.close(); } });
21
+ const req = new Request('http://test', { method: 'POST', headers: { 'content-type': 'application/json' }, body: stream, duplex: 'half' } as RequestInit);
22
+ expect((await recordHeartbeat(req)).status).toBe(413); expect(rpc).not.toHaveBeenCalled();
23
+ });
24
+ it('rejects non JSON and sequence conflicts', async () => {
25
+ expect((await recordHeartbeat(new Request('http://test', { method: 'POST', body: '{}' }))).status).toBe(415);
26
+ rpc.mockResolvedValue({ error: { message: 'HEARTBEAT_SEQUENCE_CONFLICT' } });
27
+ expect((await recordHeartbeat(request(event))).status).toBe(409);
28
+ });
29
+ it.each([{ data: [] }, { data: [{ result: 'unexpected' }] }])('rejects malformed storage success %j', async ({ data }) => {
30
+ rpc.mockResolvedValue({ data });
31
+ const log = vi.spyOn(console, 'error').mockImplementation(() => {});
32
+ try { expect((await recordHeartbeat(request(event))).status).toBe(503); } finally { log.mockRestore(); }
33
+ });
34
+ it('accepts unknown update IDs without inventing a version', () => expect(parseHeartbeat(event).updateId).toBeNull());
35
+ it('validates report filters', () => {
36
+ expect(parseDeviceFilters(new URLSearchParams())).toMatchObject({ p_days: 7, p_offset: 0 });
37
+ for (const query of ['days=0', 'days=365', 'offset=-1', 'offset=1.5', 'platform=web', 'channel=BAD']) expect(() => parseDeviceFilters(new URLSearchParams(query))).toThrow();
38
+ });
39
+ });