create-expo-updates-server 0.1.4 → 0.1.5

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 (67) hide show
  1. package/dist/template/.env.docker.example +1 -0
  2. package/dist/template/.env.example +2 -0
  3. package/dist/template/README.md +4 -1
  4. package/dist/template/app/api/admin/distribution-control/route.test.ts +153 -0
  5. package/dist/template/app/api/admin/distribution-control/route.ts +111 -0
  6. package/dist/template/app/api/admin/guard-actions/[id]/route.test.ts +60 -0
  7. package/dist/template/app/api/admin/guard-actions/[id]/route.ts +32 -0
  8. package/dist/template/app/api/admin/guard-actions/route.test.ts +123 -0
  9. package/dist/template/app/api/admin/guard-actions/route.ts +66 -0
  10. package/dist/template/app/api/admin/updates/[encodedKey]/deactivate/route.ts +4 -1
  11. package/dist/template/app/api/admin/updates/[encodedKey]/policy/route.test.ts +171 -0
  12. package/dist/template/app/api/admin/updates/[encodedKey]/policy/route.ts +75 -0
  13. package/dist/template/app/api/admin/updates/[encodedKey]/promote/route.ts +4 -1
  14. package/dist/template/app/api/admin/updates/[encodedKey]/rollback/route.ts +4 -1
  15. package/dist/template/app/api/admin/updates/[encodedKey]/route.ts +4 -1
  16. package/dist/template/app/updates/[encodedKey]/page.tsx +74 -6
  17. package/dist/template/app/updates/page.tsx +22 -1
  18. package/dist/template/docs/getting-started.md +1 -0
  19. package/dist/template/docs/getting-started.ru.md +2 -1
  20. package/dist/template/docs/migrations/2026-09-01-ota-update-policy.sql +108 -0
  21. package/dist/template/docs/migrations/2026-09-01-p1-guard-actions.sql +19 -0
  22. package/dist/template/docs/migrations/2026-09-01-p2-simplify-ota-guard-policy.sql +69 -0
  23. package/dist/template/docs/migrations/2026-09-01-policy-publication-correction.sql +44 -0
  24. package/dist/template/docs/migrations/2026-09-02-ota-distribution-control.sql +377 -0
  25. package/dist/template/docs/migrations/schema.sql +539 -2
  26. package/dist/template/docs/operations-guide.md +52 -1
  27. package/dist/template/docs/ota-emergency-recovery.md +22 -0
  28. package/dist/template/docs/ota-update-policy.md +89 -0
  29. package/dist/template/docs/supabase-setup.md +2 -1
  30. package/dist/template/package-lock.json +2 -2
  31. package/dist/template/package.json +1 -1
  32. package/dist/template/src/client/admin-api.ts +80 -1
  33. package/dist/template/src/client/admin-types.ts +50 -2
  34. package/dist/template/src/client/distribution-control.tsx +231 -0
  35. package/dist/template/src/client/guard-action-combobox.test.ts +26 -0
  36. package/dist/template/src/client/guard-action-combobox.tsx +267 -0
  37. package/dist/template/src/client/guard-action-options.test.ts +62 -0
  38. package/dist/template/src/client/guard-action-options.ts +70 -0
  39. package/dist/template/src/client/update-policy-editor.test.ts +36 -0
  40. package/dist/template/src/client/update-policy-editor.tsx +436 -0
  41. package/dist/template/src/server/controllers/assets.test.ts +87 -0
  42. package/dist/template/src/server/controllers/assets.ts +26 -0
  43. package/dist/template/src/server/controllers/manifest.test.ts +413 -2
  44. package/dist/template/src/server/controllers/manifest.ts +103 -38
  45. package/dist/template/src/server/lib/admin-distribution-guard.test.ts +61 -0
  46. package/dist/template/src/server/lib/admin-update-policy.test.ts +176 -0
  47. package/dist/template/src/server/lib/admin-updates.test.ts +72 -0
  48. package/dist/template/src/server/lib/admin-updates.ts +169 -24
  49. package/dist/template/src/server/lib/distribution-control-migration.test.ts +94 -0
  50. package/dist/template/src/server/lib/distribution-control.test.ts +160 -0
  51. package/dist/template/src/server/lib/distribution-control.ts +250 -0
  52. package/dist/template/src/server/lib/guard-actions-migration.test.ts +56 -0
  53. package/dist/template/src/server/lib/guard-actions.test.ts +142 -0
  54. package/dist/template/src/server/lib/guard-actions.ts +106 -0
  55. package/dist/template/src/server/lib/ota-policy-migrations.test.ts +64 -0
  56. package/dist/template/src/server/lib/simple-policy-migration.test.ts +97 -0
  57. package/dist/template/src/server/lib/supabase.js +95 -8
  58. package/dist/template/src/server/lib/supabase.test.ts +194 -0
  59. package/dist/template/src/server/lib/update-policy.test.ts +98 -0
  60. package/dist/template/src/server/lib/update-policy.ts +171 -0
  61. package/dist/template/src/server/manifest/manifest-repository.ts +10 -1
  62. package/dist/template/src/server/manifest/manifest-response.ts +0 -16
  63. package/dist/template/src/server/manifest/manifest-values.test.ts +54 -0
  64. package/dist/template/src/server/manifest/manifest-values.ts +145 -0
  65. package/dist/template/tsconfig.json +4 -1
  66. package/dist/template-manifest.json +239 -59
  67. package/package.json +1 -1
@@ -2,6 +2,7 @@ import NodeFormData from "form-data";
2
2
  import { toPosixPath } from "../lib/manifest-helpers.js";
3
3
  import { createSignatureHeaderIfRequested } from "../lib/signing.js";
4
4
  import { buildRequestContext } from "../lib/common.js";
5
+ import { createManifestUpdatePolicy } from "../lib/update-policy";
5
6
  import { NextRequest } from "next/server.js";
6
7
  import { resolveEmergencyChannelRedirect } from "../lib/emergency-channel-redirects";
7
8
  import { getRequestedChannel } from "../manifest/manifest-request";
@@ -15,7 +16,9 @@ import {
15
16
  normalizeFileExtension,
16
17
  } from "../manifest/manifest-response";
17
18
  import {
19
+ compareAppVersions,
18
20
  debugString,
21
+ getManifestAppVersion,
19
22
  isSameOrNewerDate,
20
23
  latestExpoManifestDate,
21
24
  normalizeExpoManifestDate,
@@ -31,6 +34,7 @@ import {
31
34
  resolveManifestId,
32
35
  resolveUpdateIdFromServedManifestId,
33
36
  } from "../manifest/manifest-repository";
37
+ import { isOtaDistributionBlocked } from "../lib/distribution-control";
34
38
 
35
39
  type ManifestAsset = {
36
40
  hash?: string;
@@ -54,7 +58,6 @@ type ManifestPayload = {
54
58
  expoClient?: Record<string, unknown>;
55
59
  };
56
60
 
57
-
58
61
  const manifestController = async (req: NextRequest) => {
59
62
  if (req.method !== "GET") {
60
63
  return Response.json({ error: "Expected GET." }, { status: 405 });
@@ -74,6 +77,19 @@ const manifestController = async (req: NextRequest) => {
74
77
  const rawEmbeddedUpdateId = req.headers.get("expo-embedded-update-id");
75
78
  const embeddedUpdateId = normalizeId(rawEmbeddedUpdateId);
76
79
  const requestedChannel = getRequestedChannel(req);
80
+
81
+ try {
82
+ if (await isOtaDistributionBlocked()) {
83
+ return createNoUpdateResponse(req, protocolVersion || 1);
84
+ }
85
+ } catch (error: unknown) {
86
+ console.error(
87
+ "Failed to read OTA distribution control; failing manifest closed:",
88
+ error,
89
+ );
90
+ return createNoUpdateResponse(req, protocolVersion || 1);
91
+ }
92
+
77
93
  const emergencyRedirect = await resolveEmergencyChannelRedirect({
78
94
  requestedChannel,
79
95
  runtimeVersion,
@@ -223,6 +239,13 @@ const manifestController = async (req: NextRequest) => {
223
239
  const embeddedUpdateId = normalizeId(rawEmbeddedUpdateId);
224
240
  const selectedUpdateIdNormalized = normalizeId(updateRow.update_id);
225
241
  const selectedCreatedAt = normalizeExpoManifestDate(updateRow.created_at);
242
+ const updateInfo =
243
+ updateRow.manifest &&
244
+ typeof updateRow.manifest === "object" &&
245
+ !Array.isArray(updateRow.manifest)
246
+ ? (updateRow.manifest as ManifestPayload)
247
+ : ({} as ManifestPayload);
248
+ const selectedAppVersion = getManifestAppVersion(updateInfo);
226
249
  const currentInstalledUpdateMeta = currentUpdateId
227
250
  ? await resolveDeviceBaselineMeta(currentUpdateId)
228
251
  : null;
@@ -248,58 +271,86 @@ const manifestController = async (req: NextRequest) => {
248
271
  );
249
272
  }
250
273
 
251
- const currentInstalledBlocksDowngrade =
252
- !rollbackMode &&
253
- Boolean(
254
- currentInstalledUpdateMeta &&
255
- currentInstalledUpdateMeta.platform === platform &&
256
- currentInstalledUpdateMeta.channel === channel &&
257
- isSameOrNewerDate(
258
- normalizeExpoManifestDate(currentInstalledUpdateMeta.created_at),
259
- selectedCreatedAt,
260
- ),
261
- );
262
-
263
- const embeddedBlocksDowngrade =
264
- !rollbackMode &&
265
- Boolean(
266
- embeddedUpdateMeta &&
267
- embeddedUpdateMeta.platform === platform &&
268
- embeddedUpdateMeta.channel === channel &&
269
- isSameOrNewerDate(
270
- normalizeExpoManifestDate(embeddedUpdateMeta.created_at),
271
- selectedCreatedAt,
272
- ),
273
- );
274
+ // Cached Expo/prebuild output can reuse an embedded update ID and createdAt
275
+ // across APK version bumps. Registration updates app_version on that same
276
+ // row, so a valid newer app version must override the stale timestamp.
277
+ const embeddedAppVersionComparison =
278
+ embeddedUpdateMeta?.platform === platform
279
+ ? compareAppVersions(embeddedUpdateMeta.app_version, selectedAppVersion)
280
+ : null;
281
+ const currentInstalledAppVersionComparison =
282
+ currentInstalledUpdateMeta?.platform === platform
283
+ ? compareAppVersions(
284
+ currentInstalledUpdateMeta.app_version,
285
+ selectedAppVersion,
286
+ )
287
+ : null;
288
+ const embeddedVersionBlocks = embeddedAppVersionComparison === 1;
289
+ const currentInstalledVersionBlocks =
290
+ currentInstalledAppVersionComparison === 1;
291
+
292
+ const embeddedTimestampBlocks = Boolean(
293
+ embeddedUpdateMeta &&
294
+ embeddedUpdateMeta.platform === platform &&
295
+ embeddedUpdateMeta.channel === channel &&
296
+ (embeddedAppVersionComparison === 0 ||
297
+ embeddedAppVersionComparison === null) &&
298
+ isSameOrNewerDate(
299
+ normalizeExpoManifestDate(embeddedUpdateMeta.created_at),
300
+ selectedCreatedAt,
301
+ ),
302
+ );
303
+ const currentInstalledTimestampBlocks = Boolean(
304
+ currentInstalledUpdateMeta &&
305
+ currentInstalledUpdateMeta.platform === platform &&
306
+ currentInstalledUpdateMeta.channel === channel &&
307
+ (currentInstalledAppVersionComparison === 0 ||
308
+ currentInstalledAppVersionComparison === null) &&
309
+ isSameOrNewerDate(
310
+ normalizeExpoManifestDate(currentInstalledUpdateMeta.created_at),
311
+ selectedCreatedAt,
312
+ ),
313
+ );
274
314
 
275
- if (embeddedBlocksDowngrade || currentInstalledBlocksDowngrade) {
276
- const downgradeBlockReason = embeddedBlocksDowngrade
277
- ? "embedded-update-is-same-or-newer"
278
- : "current-installed-update-is-same-or-newer";
315
+ const versionBlocksDowngrade =
316
+ embeddedVersionBlocks || currentInstalledVersionBlocks;
317
+ const timestampBlocksDowngrade =
318
+ embeddedTimestampBlocks || currentInstalledTimestampBlocks;
319
+
320
+ if (!rollbackMode && (versionBlocksDowngrade || timestampBlocksDowngrade)) {
321
+ const blockingBaseline = embeddedVersionBlocks
322
+ ? "embedded"
323
+ : currentInstalledVersionBlocks
324
+ ? "current-installed"
325
+ : embeddedTimestampBlocks
326
+ ? "embedded"
327
+ : "current-installed";
328
+ const downgradeBlockReason = versionBlocksDowngrade
329
+ ? "app-version"
330
+ : "timestamp";
279
331
 
280
332
  console.log(
281
- `[${new Date().toLocaleTimeString()}] ⏭️ Returning noUpdateAvailable ${requestContext} reason=${downgradeBlockReason} embeddedUpdateId=${debugString(
333
+ `[${new Date().toLocaleTimeString()}] ⏭️ Returning noUpdateAvailable ${requestContext} reason=downgrade-protection blockingReason=${downgradeBlockReason} baseline=${blockingBaseline} embeddedUpdateId=${debugString(
282
334
  embeddedUpdateId,
335
+ )} embeddedAppVersion=${debugString(
336
+ embeddedUpdateMeta?.app_version,
283
337
  )} embeddedCreatedAt=${debugString(
284
338
  normalizeExpoManifestDate(embeddedUpdateMeta?.created_at),
285
339
  )} currentInstalledUpdateId=${debugString(
286
340
  currentInstalledUpdateMeta?.embedded_update_id,
341
+ )} currentInstalledAppVersion=${debugString(
342
+ currentInstalledUpdateMeta?.app_version,
287
343
  )} currentInstalledCreatedAt=${debugString(
288
344
  normalizeExpoManifestDate(currentInstalledUpdateMeta?.created_at),
289
345
  )} selectedUpdateId=${debugString(
290
346
  selectedUpdateIdNormalized,
347
+ )} selectedAppVersion=${debugString(
348
+ selectedAppVersion,
291
349
  )} selectedCreatedAt=${selectedCreatedAt ?? "none"} rollbackMode=${rollbackMode}`,
292
350
  );
293
351
  return createNoUpdateResponse(req, protocolVersion || 1);
294
352
  }
295
353
 
296
- const updateInfo =
297
- updateRow.manifest &&
298
- typeof updateRow.manifest === "object" &&
299
- !Array.isArray(updateRow.manifest)
300
- ? (updateRow.manifest as ManifestPayload)
301
- : ({} as ManifestPayload);
302
-
303
354
  const updateRef = {
304
355
  runtimeVersion: updateRow.runtime_version,
305
356
  platform: updateRow.platform,
@@ -439,7 +490,6 @@ const manifestController = async (req: NextRequest) => {
439
490
  channel: updateRef.channel,
440
491
  updateId: updateRef.updateId,
441
492
  assetPath: normalizedAssetPath,
442
- storageBasePath: updateRow.storage_base_path,
443
493
  }),
444
494
  });
445
495
  }
@@ -486,7 +536,6 @@ const manifestController = async (req: NextRequest) => {
486
536
  channel: updateRef.channel,
487
537
  updateId: updateRef.updateId,
488
538
  assetPath: launchManifestAsset.path,
489
- storageBasePath: updateRow.storage_base_path,
490
539
  }),
491
540
  };
492
541
 
@@ -514,6 +563,22 @@ const manifestController = async (req: NextRequest) => {
514
563
  expoClient: createExpoClientConfig(
515
564
  updateInfo.extra?.expoClient || updateInfo.expoClient,
516
565
  ),
566
+ updatePolicy: createManifestUpdatePolicy({
567
+ delivery: updateRow.delivery_mode,
568
+ guard: updateRow.guard_action
569
+ ? {
570
+ action: updateRow.guard_action,
571
+ ...(updateRow.guard_payload !== null
572
+ ? { payload: updateRow.guard_payload }
573
+ : {}),
574
+ }
575
+ : null,
576
+ policyVersion: updateRow.policy_version,
577
+ onCorrupt: (policyError) =>
578
+ console.error(
579
+ `[${new Date().toLocaleTimeString()}] ⚠️ Corrupt OTA update policy; serving manual policy updateId=${updateRow.update_id}: ${policyError.message}`,
580
+ ),
581
+ }),
517
582
  },
518
583
  };
519
584
 
@@ -0,0 +1,61 @@
1
+ import { beforeEach, describe, expect, it, vi } from "vitest";
2
+
3
+ const assertAllowed = vi.hoisted(() => vi.fn());
4
+
5
+ vi.mock("./distribution-control", () => ({
6
+ assertOtaDistributionAllowed: assertAllowed,
7
+ }));
8
+
9
+ vi.mock("./supabase.js", () => ({
10
+ jsonb: (value: unknown) => value,
11
+ SUPABASE_BUCKET: "updates",
12
+ supabase: {
13
+ from: () => {
14
+ throw new Error("Database access must not happen after blocked guard.");
15
+ },
16
+ },
17
+ }));
18
+
19
+ import {
20
+ promoteLatestByKey,
21
+ rollbackToUpdateByKey,
22
+ setUpdateDisabledByKey,
23
+ updateJsonFileByKey,
24
+ } from "./admin-updates";
25
+
26
+ describe("admin OTA distribution guards", () => {
27
+ beforeEach(() => {
28
+ assertAllowed.mockReset();
29
+ assertAllowed.mockRejectedValue(new Error("blocked"));
30
+ });
31
+
32
+ it.each([
33
+ ["rollback", () => rollbackToUpdateByKey("invalid")],
34
+ ["promote", () => promoteLatestByKey("invalid")],
35
+ ["activation", () => setUpdateDisabledByKey("invalid", false)],
36
+ [
37
+ "channel latest",
38
+ () =>
39
+ updateJsonFileByKey("invalid", "channel-latest.json", {
40
+ updateId: "invalid",
41
+ }),
42
+ ],
43
+ [
44
+ "activating update meta",
45
+ () =>
46
+ updateJsonFileByKey("invalid", "update-meta.json", {
47
+ isActive: true,
48
+ }),
49
+ ],
50
+ ])("rejects %s before database mutation", async (_name, operation) => {
51
+ await expect(operation()).rejects.toThrow("blocked");
52
+ expect(assertAllowed).toHaveBeenCalledTimes(1);
53
+ });
54
+
55
+ it("does not apply the distribution guard to safe draft JSON changes", async () => {
56
+ await expect(
57
+ updateJsonFileByKey("invalid", "update-info.json", {}),
58
+ ).rejects.toThrow("Invalid update key format");
59
+ expect(assertAllowed).not.toHaveBeenCalled();
60
+ });
61
+ });
@@ -0,0 +1,176 @@
1
+ import { beforeEach, describe, expect, it, vi } from "vitest";
2
+
3
+ const policyDatabase = vi.hoisted(() => ({
4
+ row: null as Record<string, unknown> | null,
5
+ updateCalls: 0,
6
+ }));
7
+
8
+ vi.mock("./supabase.js", () => ({
9
+ jsonb: (value: unknown) => value,
10
+ SUPABASE_BUCKET: "updates",
11
+ supabase: {
12
+ from: () => {
13
+ let updatePayload: Record<string, unknown> | null = null;
14
+ const builder = {
15
+ select() {
16
+ return builder;
17
+ },
18
+ update(payload: Record<string, unknown>) {
19
+ updatePayload = payload;
20
+ policyDatabase.updateCalls += 1;
21
+ return builder;
22
+ },
23
+ eq() {
24
+ return builder;
25
+ },
26
+ is() {
27
+ return builder;
28
+ },
29
+ single() {
30
+ return Promise.resolve({
31
+ data: policyDatabase.row,
32
+ error: policyDatabase.row ? null : { message: "not found" },
33
+ });
34
+ },
35
+ maybeSingle() {
36
+ if (updatePayload && policyDatabase.row) {
37
+ policyDatabase.row = {
38
+ ...policyDatabase.row,
39
+ ...updatePayload,
40
+ };
41
+ }
42
+ return Promise.resolve({
43
+ data: policyDatabase.row,
44
+ error: null,
45
+ });
46
+ },
47
+ };
48
+ return builder;
49
+ },
50
+ },
51
+ }));
52
+
53
+ import {
54
+ getUpdatePolicyByKey,
55
+ replaceUpdatePolicyByKey,
56
+ UpdatePolicyPublishedError,
57
+ } from "./admin-updates";
58
+
59
+ const updateId = "22222222-2222-4222-8222-222222222222";
60
+
61
+ function makePolicyRow(overrides: Record<string, unknown> = {}) {
62
+ return {
63
+ id: "11111111-1111-4111-8111-111111111111",
64
+ update_id: updateId,
65
+ build_id: "33333333-3333-4333-8333-333333333333",
66
+ comment: null,
67
+ runtime_version: "runtime-1",
68
+ channel: "production",
69
+ platform: "ios",
70
+ created_at: "2026-01-01T00:00:00.000Z",
71
+ created_at_path: "2026/01/01/000000",
72
+ storage_bucket: "updates",
73
+ storage_base_path: "runtime-1/ios/update",
74
+ is_active: false,
75
+ updated_at: null,
76
+ disabled_at: "2026-01-01T00:00:00.000Z",
77
+ assets_count: 2,
78
+ launch_asset_path: "bundle.js",
79
+ rolled_back_from_update_id: null,
80
+ delivery_mode: "manual",
81
+ guard_action: null,
82
+ guard_payload: null,
83
+ policy_version: 1,
84
+ policy_published_at: null,
85
+ manifest: {},
86
+ inserted_at: "2026-01-01T00:00:00.000Z",
87
+ modified_at: "2026-01-01T00:00:00.000Z",
88
+ ...overrides,
89
+ };
90
+ }
91
+
92
+ describe("simple OTA update policy service publication lock", () => {
93
+ beforeEach(() => {
94
+ policyDatabase.row = makePolicyRow();
95
+ policyDatabase.updateCalls = 0;
96
+ });
97
+
98
+ it("edits delivery and an unconditional Guard on a draft", async () => {
99
+ expect(await getUpdatePolicyByKey(updateId)).toMatchObject({
100
+ delivery: "manual",
101
+ guard: null,
102
+ publishedAt: null,
103
+ editable: true,
104
+ });
105
+
106
+ const guard = {
107
+ action: "require-confirmation",
108
+ payload: { message: "Ready" },
109
+ };
110
+ const updated = await replaceUpdatePolicyByKey(
111
+ updateId,
112
+ { delivery: "background", guard },
113
+ 1,
114
+ );
115
+
116
+ expect(updated).toMatchObject({
117
+ delivery: "background",
118
+ guard,
119
+ policyVersion: 2,
120
+ publishedAt: null,
121
+ editable: true,
122
+ });
123
+ expect(policyDatabase.row).toMatchObject({
124
+ guard_action: guard.action,
125
+ guard_payload: guard.payload,
126
+ });
127
+ expect(policyDatabase.updateCalls).toBe(1);
128
+ });
129
+
130
+ it("clears both Guard columns when Guard is disabled", async () => {
131
+ policyDatabase.row = makePolicyRow({
132
+ guard_action: "existing",
133
+ guard_payload: { message: "old" },
134
+ });
135
+ const updated = await replaceUpdatePolicyByKey(
136
+ updateId,
137
+ { delivery: "manual", guard: null },
138
+ 1,
139
+ );
140
+
141
+ expect(updated.guard).toBeNull();
142
+ expect(policyDatabase.row).toMatchObject({
143
+ guard_action: null,
144
+ guard_payload: null,
145
+ });
146
+ });
147
+
148
+ it.each([
149
+ [
150
+ "active without a publication marker",
151
+ { is_active: true, disabled_at: null, policy_published_at: null },
152
+ ],
153
+ [
154
+ "inactive after publication",
155
+ {
156
+ is_active: false,
157
+ disabled_at: "2026-01-02T00:00:00.000Z",
158
+ policy_published_at: "2026-01-01T12:00:00.000Z",
159
+ },
160
+ ],
161
+ ])("locks an %s row", async (_case, overrides) => {
162
+ policyDatabase.row = makePolicyRow(overrides);
163
+
164
+ expect(await getUpdatePolicyByKey(updateId)).toMatchObject({
165
+ editable: false,
166
+ });
167
+ await expect(
168
+ replaceUpdatePolicyByKey(
169
+ updateId,
170
+ { delivery: "background", guard: null },
171
+ 1,
172
+ ),
173
+ ).rejects.toBeInstanceOf(UpdatePolicyPublishedError);
174
+ expect(policyDatabase.updateCalls).toBe(0);
175
+ });
176
+ });
@@ -1,8 +1,11 @@
1
1
  import { describe, expect, it } from "vitest";
2
2
  import {
3
+ assertExpectedPolicyVersion,
3
4
  mapRowToRecord,
4
5
  OtaUpdateRow,
6
+ UpdatePolicyConflictError,
5
7
  } from "./admin-updates";
8
+ import { UpdatePolicyValidationError } from "./update-policy";
6
9
 
7
10
  function makeRow(manifest: Record<string, unknown> = {}): OtaUpdateRow {
8
11
  return {
@@ -23,6 +26,11 @@ function makeRow(manifest: Record<string, unknown> = {}): OtaUpdateRow {
23
26
  assets_count: 2,
24
27
  launch_asset_path: "bundle.js",
25
28
  rolled_back_from_update_id: null,
29
+ delivery_mode: "manual",
30
+ guard_action: null,
31
+ guard_payload: null,
32
+ policy_version: 1,
33
+ policy_published_at: "2026-01-01T00:00:00.000Z",
26
34
  manifest,
27
35
  inserted_at: "2026-01-01T00:00:00.000Z",
28
36
  modified_at: "2026-01-01T00:00:00.000Z",
@@ -30,6 +38,58 @@ function makeRow(manifest: Record<string, unknown> = {}): OtaUpdateRow {
30
38
  }
31
39
 
32
40
  describe("OTA admin update mapping", () => {
41
+ it("requires expectedPolicyVersion at the service boundary", () => {
42
+ expect(() => assertExpectedPolicyVersion(undefined)).toThrow(
43
+ UpdatePolicyValidationError,
44
+ );
45
+ });
46
+
47
+ it("rejects a stale expectedPolicyVersion at the service boundary", () => {
48
+ expect(() => assertExpectedPolicyVersion(2, 3)).toThrow(
49
+ UpdatePolicyConflictError,
50
+ );
51
+ });
52
+
53
+ it("maps an inactive initial-disabled draft as policy-editable", () => {
54
+ const row = makeRow();
55
+ row.is_active = false;
56
+ row.disabled_at = row.created_at;
57
+ row.policy_published_at = null;
58
+
59
+ const item = mapRowToRecord(row, null);
60
+
61
+ expect(item.status).toBe("disabled");
62
+ expect(item.policyPublishedAt).toBeNull();
63
+ expect(item.policyEditable).toBe(true);
64
+ });
65
+
66
+ it("maps the simple Guard badge without rule counting", () => {
67
+ const row = makeRow();
68
+ row.guard_action = "require-confirmation";
69
+ expect(mapRowToRecord(row, null).hasGuard).toBe(true);
70
+ row.guard_action = null;
71
+ expect(mapRowToRecord(row, null).hasGuard).toBe(false);
72
+ });
73
+
74
+ it.each([
75
+ ["active without a marker", true, null],
76
+ [
77
+ "inactive after publication",
78
+ false,
79
+ "2026-01-01T00:00:00.000Z",
80
+ ],
81
+ ])("maps an %s update as locked", (_case, active, publishedAt) => {
82
+ const row = makeRow();
83
+ row.is_active = active;
84
+ row.disabled_at = active ? null : "2026-01-02T00:00:00.000Z";
85
+ row.policy_published_at = publishedAt;
86
+
87
+ const item = mapRowToRecord(row, null);
88
+
89
+ expect(item.policyPublishedAt).toBe(publishedAt);
90
+ expect(item.policyEditable).toBe(false);
91
+ });
92
+
33
93
  it("maps expoClient.version from the stored manifest", () => {
34
94
  const item = mapRowToRecord(
35
95
  makeRow({ expoClient: { version: "2.4.1" } }),
@@ -49,6 +109,18 @@ describe("OTA admin update mapping", () => {
49
109
  expect(item.appVersion).toBe("2.4.1");
50
110
  });
51
111
 
112
+ it("prefers extra.expoClient.version from uploaded manifests", () => {
113
+ const item = mapRowToRecord(
114
+ makeRow({
115
+ expoClient: { version: "1.0.0" },
116
+ extra: { expoClient: { version: "2.4.1" } },
117
+ }),
118
+ null,
119
+ );
120
+
121
+ expect(item.appVersion).toBe("2.4.1");
122
+ });
123
+
52
124
  it.each([
53
125
  ["missing expoClient", {}],
54
126
  ["missing version", { expoClient: {} }],