create-expo-updates-server 0.1.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 (117) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +19 -0
  3. package/bin/create-expo-updates-server.mjs +5 -0
  4. package/dist/template/.env.docker.example +15 -0
  5. package/dist/template/.env.example +35 -0
  6. package/dist/template/Dockerfile +42 -0
  7. package/dist/template/LICENSE +21 -0
  8. package/dist/template/README.md +665 -0
  9. package/dist/template/app/api/admin/access-tokens/[id]/route.ts +25 -0
  10. package/dist/template/app/api/admin/access-tokens/route.test.ts +73 -0
  11. package/dist/template/app/api/admin/access-tokens/route.ts +90 -0
  12. package/dist/template/app/api/admin/embedded-updates/[embeddedUpdateId]/route.ts +25 -0
  13. package/dist/template/app/api/admin/embedded-updates/route.test.ts +102 -0
  14. package/dist/template/app/api/admin/embedded-updates/route.ts +47 -0
  15. package/dist/template/app/api/admin/emergency-redirects/[id]/route.ts +62 -0
  16. package/dist/template/app/api/admin/emergency-redirects/route.test.ts +84 -0
  17. package/dist/template/app/api/admin/emergency-redirects/route.ts +56 -0
  18. package/dist/template/app/api/admin/login/route.test.ts +55 -0
  19. package/dist/template/app/api/admin/login/route.ts +52 -0
  20. package/dist/template/app/api/admin/logout/route.ts +20 -0
  21. package/dist/template/app/api/admin/session/route.ts +15 -0
  22. package/dist/template/app/api/admin/updates/[encodedKey]/deactivate/route.ts +33 -0
  23. package/dist/template/app/api/admin/updates/[encodedKey]/promote/route.ts +29 -0
  24. package/dist/template/app/api/admin/updates/[encodedKey]/rollback/route.ts +29 -0
  25. package/dist/template/app/api/admin/updates/[encodedKey]/route.ts +96 -0
  26. package/dist/template/app/api/admin/updates/route.test.ts +142 -0
  27. package/dist/template/app/api/admin/updates/route.ts +32 -0
  28. package/dist/template/app/api/assets/route.ts +6 -0
  29. package/dist/template/app/api/health/route.test.ts +26 -0
  30. package/dist/template/app/api/health/route.ts +42 -0
  31. package/dist/template/app/api/manifest/route.ts +6 -0
  32. package/dist/template/app/api/update-complete/route.ts +6 -0
  33. package/dist/template/app/favicon.ico +0 -0
  34. package/dist/template/app/globals.css +26 -0
  35. package/dist/template/app/layout.tsx +34 -0
  36. package/dist/template/app/login/page.tsx +77 -0
  37. package/dist/template/app/page.tsx +12 -0
  38. package/dist/template/app/updates/[encodedKey]/page.tsx +482 -0
  39. package/dist/template/app/updates/embedded/page.tsx +164 -0
  40. package/dist/template/app/updates/emergency-redirects/page.tsx +430 -0
  41. package/dist/template/app/updates/layout.tsx +14 -0
  42. package/dist/template/app/updates/page.tsx +281 -0
  43. package/dist/template/docker-compose.yml +100 -0
  44. package/dist/template/docs/expo-app-setup.md +497 -0
  45. package/dist/template/docs/getting-started.md +502 -0
  46. package/dist/template/docs/getting-started.ru.md +623 -0
  47. package/dist/template/docs/index.md +57 -0
  48. package/dist/template/docs/migrations/schema.sql +363 -0
  49. package/dist/template/docs/npm-installer.md +83 -0
  50. package/dist/template/docs/operations-guide.md +270 -0
  51. package/dist/template/docs/ota-emergency-recovery.md +109 -0
  52. package/dist/template/docs/supabase-setup.md +133 -0
  53. package/dist/template/eslint.config.mjs +30 -0
  54. package/dist/template/gitignore.template +58 -0
  55. package/dist/template/next.config.ts +7 -0
  56. package/dist/template/package-lock.json +12156 -0
  57. package/dist/template/package.json +50 -0
  58. package/dist/template/postcss.config.mjs +7 -0
  59. package/dist/template/public/file.svg +1 -0
  60. package/dist/template/public/globe.svg +1 -0
  61. package/dist/template/public/next.svg +1 -0
  62. package/dist/template/public/vercel.svg +1 -0
  63. package/dist/template/public/window.svg +1 -0
  64. package/dist/template/scripts/configure-expo-app.mjs +145 -0
  65. package/dist/template/scripts/create-access-token.mjs +135 -0
  66. package/dist/template/scripts/create-admin.mjs +169 -0
  67. package/dist/template/scripts/import-emergency-redirects.mjs +126 -0
  68. package/dist/template/scripts/lib/embedded-update-registrar.test.ts +64 -0
  69. package/dist/template/scripts/lib/expo-app-configurator.mjs +666 -0
  70. package/dist/template/scripts/lib/expo-app-configurator.test.ts +463 -0
  71. package/dist/template/scripts/lib/expo-app-prompts.mjs +139 -0
  72. package/dist/template/scripts/lib/expo-app-prompts.test.ts +97 -0
  73. package/dist/template/scripts/lib/expo-export-command.test.ts +31 -0
  74. package/dist/template/scripts/lib/ota-publish-retry.test.ts +33 -0
  75. package/dist/template/scripts/manage-emergency-redirect.mjs +483 -0
  76. package/dist/template/scripts/sync-docker-database-password.sh +16 -0
  77. package/dist/template/src/client/admin-api.ts +174 -0
  78. package/dist/template/src/client/admin-types.ts +93 -0
  79. package/dist/template/src/client/logout-button.tsx +31 -0
  80. package/dist/template/src/server/controllers/assets.ts +216 -0
  81. package/dist/template/src/server/controllers/manifest.test.ts +403 -0
  82. package/dist/template/src/server/controllers/manifest.ts +626 -0
  83. package/dist/template/src/server/controllers/update-complete.ts +36 -0
  84. package/dist/template/src/server/lib/admin-access-tokens.ts +169 -0
  85. package/dist/template/src/server/lib/admin-api.ts +101 -0
  86. package/dist/template/src/server/lib/admin-auth.ts +208 -0
  87. package/dist/template/src/server/lib/admin-embedded-updates.ts +150 -0
  88. package/dist/template/src/server/lib/admin-updates.ts +1282 -0
  89. package/dist/template/src/server/lib/common.js +24 -0
  90. package/dist/template/src/server/lib/emergency-channel-redirects.ts +310 -0
  91. package/dist/template/src/server/lib/env.js +8 -0
  92. package/dist/template/src/server/lib/manifest-helpers.js +91 -0
  93. package/dist/template/src/server/lib/response.js +11 -0
  94. package/dist/template/src/server/lib/signing.js +55 -0
  95. package/dist/template/src/server/lib/supabase.js +763 -0
  96. package/dist/template/src/server/manifest/manifest-repository.ts +269 -0
  97. package/dist/template/src/server/manifest/manifest-request.ts +21 -0
  98. package/dist/template/src/server/manifest/manifest-response.ts +235 -0
  99. package/dist/template/src/server/manifest/manifest-values.ts +62 -0
  100. package/dist/template/templates/expo-app/.env.ota.example +18 -0
  101. package/dist/template/templates/expo-app/ci_scripts/ci_post_xcodebuild.sh +6 -0
  102. package/dist/template/templates/expo-app/ci_scripts/register-embedded-update.sh +36 -0
  103. package/dist/template/templates/expo-app/plugins/with-ota-embedded-registration.js +33 -0
  104. package/dist/template/templates/expo-app/scripts/ota-publish/api/database-client.mjs +87 -0
  105. package/dist/template/templates/expo-app/scripts/ota-publish/api/storage-client.mjs +57 -0
  106. package/dist/template/templates/expo-app/scripts/ota-publish/index.mjs +182 -0
  107. package/dist/template/templates/expo-app/scripts/ota-publish/lib/common.mjs +84 -0
  108. package/dist/template/templates/expo-app/scripts/ota-publish/lib/expo-export-command.mjs +24 -0
  109. package/dist/template/templates/expo-app/scripts/ota-publish/lib/retry.mjs +25 -0
  110. package/dist/template/templates/expo-app/scripts/ota-publish/shared/config.mjs +48 -0
  111. package/dist/template/templates/expo-app/scripts/ota-register-embedded/android-register-embedded-update.sh +18 -0
  112. package/dist/template/templates/expo-app/scripts/ota-register-embedded/index.mjs +275 -0
  113. package/dist/template/tsconfig.json +36 -0
  114. package/dist/template/vitest.config.mts +20 -0
  115. package/dist/template-manifest.json +564 -0
  116. package/lib/cli.mjs +549 -0
  117. package/package.json +41 -0
@@ -0,0 +1,626 @@
1
+ import NodeFormData from "form-data";
2
+ import { toPosixPath } from "../lib/manifest-helpers.js";
3
+ import { createSignatureHeaderIfRequested } from "../lib/signing.js";
4
+ import { buildRequestContext } from "../lib/common.js";
5
+ import { NextRequest } from "next/server.js";
6
+ import { resolveEmergencyChannelRedirect } from "../lib/emergency-channel-redirects";
7
+ import { getRequestedChannel } from "../manifest/manifest-request";
8
+ import {
9
+ buildAssetUrl,
10
+ createExpoClientConfig,
11
+ createMultipartResponse,
12
+ createNoUpdateResponse,
13
+ createSignatureRequest,
14
+ normalizeContentType,
15
+ normalizeFileExtension,
16
+ } from "../manifest/manifest-response";
17
+ import {
18
+ debugString,
19
+ isSameOrNewerDate,
20
+ latestExpoManifestDate,
21
+ normalizeExpoManifestDate,
22
+ normalizeId,
23
+ } from "../manifest/manifest-values";
24
+ import {
25
+ getChannelRow,
26
+ getLatestActiveUpdate,
27
+ getUpdateByUpdateId,
28
+ logServedManifest,
29
+ OtaUpdateRow,
30
+ resolveDeviceBaselineMeta,
31
+ resolveManifestId,
32
+ resolveUpdateIdFromServedManifestId,
33
+ } from "../manifest/manifest-repository";
34
+
35
+ type ManifestAsset = {
36
+ hash?: string;
37
+ key?: string;
38
+ path?: string;
39
+ fileExtension?: string;
40
+ contentType?: string;
41
+ };
42
+
43
+ type ManifestPayload = {
44
+ id?: string;
45
+ createdAt?: string;
46
+ runtimeVersion?: string;
47
+ assets?: ManifestAsset[];
48
+ launchAsset?: ManifestAsset;
49
+ fileMetadata?: Record<
50
+ string,
51
+ { assets?: Array<{ path?: string; ext?: string }> }
52
+ >;
53
+ extra?: { expoClient?: Record<string, unknown> };
54
+ expoClient?: Record<string, unknown>;
55
+ };
56
+
57
+
58
+ const manifestController = async (req: NextRequest) => {
59
+ if (req.method !== "GET") {
60
+ return Response.json({ error: "Expected GET." }, { status: 405 });
61
+ }
62
+
63
+ const protocolVersion = parseInt(
64
+ req.headers.get("expo-protocol-version") ?? "0",
65
+ 10,
66
+ );
67
+ const platform =
68
+ req.headers.get("expo-platform") ??
69
+ req.nextUrl.searchParams.get("platform");
70
+ const runtimeVersion =
71
+ req.headers.get("expo-runtime-version") ??
72
+ req.nextUrl.searchParams.get("runtime-version");
73
+ const rawCurrentUpdateId = req.headers.get("expo-current-update-id");
74
+ const rawEmbeddedUpdateId = req.headers.get("expo-embedded-update-id");
75
+ const embeddedUpdateId = normalizeId(rawEmbeddedUpdateId);
76
+ const requestedChannel = getRequestedChannel(req);
77
+ const emergencyRedirect = await resolveEmergencyChannelRedirect({
78
+ requestedChannel,
79
+ runtimeVersion,
80
+ platform,
81
+ embeddedUpdateId,
82
+ });
83
+ const channel = emergencyRedirect?.toChannel || requestedChannel;
84
+ const requestContext = buildRequestContext({
85
+ channel,
86
+ runtimeVersion,
87
+ platform,
88
+ });
89
+
90
+ if (channel !== requestedChannel) {
91
+ console.warn(
92
+ `[${new Date().toLocaleTimeString()}] 🚨 Emergency OTA channel redirect rule=${emergencyRedirect?.id || "unknown"} requestedChannel=${requestedChannel} effectiveChannel=${channel} platform=${debugString(
93
+ platform,
94
+ )} runtimeVersion=${debugString(runtimeVersion)} embeddedUpdateId=${debugString(
95
+ embeddedUpdateId,
96
+ )}`,
97
+ );
98
+ }
99
+
100
+ console.log(
101
+ `[${new Date().toLocaleTimeString()}] 🧾 Manifest request ${requestContext} protocol=${protocolVersion} deviceCurrentUpdateId=${debugString(
102
+ rawCurrentUpdateId,
103
+ )} deviceEmbeddedUpdateId=${debugString(rawEmbeddedUpdateId)} channelHeader=${debugString(
104
+ req.headers.get("expo-channel-name"),
105
+ )} requestedChannel=${requestedChannel} effectiveChannel=${channel}`,
106
+ );
107
+
108
+ if (platform !== "ios" && platform !== "android") {
109
+ return Response.json(
110
+ {
111
+ error: "Unsupported platform. Expected either ios or android.",
112
+ },
113
+ { status: 400 },
114
+ );
115
+ }
116
+
117
+ if (!runtimeVersion || typeof runtimeVersion !== "string") {
118
+ return Response.json(
119
+ { error: "No runtimeVersion provided." },
120
+ { status: 400 },
121
+ );
122
+ }
123
+
124
+ try {
125
+ const channelRow = await getChannelRow({
126
+ runtimeVersion,
127
+ channel,
128
+ platform,
129
+ });
130
+
131
+ console.log(
132
+ `[${new Date().toLocaleTimeString()}] 🗂️ Channel state ${requestContext} latestUpdateId=${debugString(
133
+ channelRow?.latest_update_id,
134
+ )} activeUpdateId=${debugString(
135
+ channelRow?.active_update_id,
136
+ )} activeChangedAt=${channelRow?.active_changed_at ? (normalizeExpoManifestDate(channelRow.active_changed_at) ?? "invalid") : "none"} servedManifestChangedAt=${channelRow?.served_manifest_changed_at ? (normalizeExpoManifestDate(channelRow.served_manifest_changed_at) ?? "invalid") : "none"}`,
137
+ );
138
+
139
+ const rollbackUpdateId =
140
+ channelRow?.active_update_id &&
141
+ channelRow.active_update_id !== channelRow.latest_update_id
142
+ ? channelRow.active_update_id
143
+ : null;
144
+
145
+ const rollbackMode = Boolean(rollbackUpdateId);
146
+
147
+ const selectedUpdateId =
148
+ rollbackUpdateId || channelRow?.latest_update_id || null;
149
+
150
+ console.log(
151
+ `[${new Date().toLocaleTimeString()}] 🎯 Channel selection ${requestContext} latestUpdateId=${debugString(
152
+ channelRow?.latest_update_id,
153
+ )} activeUpdateId=${debugString(
154
+ channelRow?.active_update_id,
155
+ )} selectedUpdateId=${debugString(selectedUpdateId)} rollbackMode=${rollbackMode}`,
156
+ );
157
+
158
+ if (!selectedUpdateId) {
159
+ console.log(
160
+ `[${new Date().toLocaleTimeString()}] ⏭️ Returning noUpdateAvailable ${requestContext} reason=no-selected-update-id`,
161
+ );
162
+ return createNoUpdateResponse(req, protocolVersion || 1);
163
+ }
164
+
165
+ let updateRow = await getUpdateByUpdateId(selectedUpdateId);
166
+ let latestActiveUpdateRow: OtaUpdateRow | null = null;
167
+
168
+ if (!updateRow || !updateRow.is_active) {
169
+ latestActiveUpdateRow = await getLatestActiveUpdate({
170
+ runtimeVersion,
171
+ channel,
172
+ platform,
173
+ });
174
+ }
175
+
176
+ if ((!updateRow || !updateRow.is_active) && rollbackUpdateId) {
177
+ updateRow = latestActiveUpdateRow;
178
+
179
+ console.log(
180
+ `[${new Date().toLocaleTimeString()}] 🔁 Rollback fallback attempted ${requestContext} rollbackUpdateId=${debugString(
181
+ rollbackUpdateId,
182
+ )} fallbackLatestActiveUpdateId=${debugString(latestActiveUpdateRow?.update_id)}`,
183
+ );
184
+ } else if (!rollbackMode && (!updateRow || !updateRow.is_active)) {
185
+ updateRow = latestActiveUpdateRow;
186
+
187
+ console.log(
188
+ `[${new Date().toLocaleTimeString()}] 🔁 Latest pointer fallback attempted ${requestContext} pointedLatestUpdateId=${debugString(
189
+ selectedUpdateId,
190
+ )} fallbackLatestActiveUpdateId=${debugString(latestActiveUpdateRow?.update_id)}`,
191
+ );
192
+ }
193
+
194
+ console.log(
195
+ `[${new Date().toLocaleTimeString()}] 📄 Selected update row ${requestContext} updateId=${debugString(
196
+ updateRow?.update_id,
197
+ )} createdAt=${normalizeExpoManifestDate(updateRow?.created_at) ?? "none"} platform=${debugString(
198
+ updateRow?.platform,
199
+ )} channel=${debugString(updateRow?.channel)} isActive=${Boolean(
200
+ updateRow?.is_active,
201
+ )}`,
202
+ );
203
+
204
+ if (!updateRow || !updateRow.is_active) {
205
+ console.log(
206
+ `[${new Date().toLocaleTimeString()}] ⏭️ Returning noUpdateAvailable ${requestContext} reason=missing-or-inactive-update-row`,
207
+ );
208
+ return createNoUpdateResponse(req, protocolVersion || 1);
209
+ }
210
+
211
+ if (
212
+ emergencyRedirect &&
213
+ emergencyRedirect.targetMode === "pinned" &&
214
+ updateRow.update_id.toLowerCase() !== emergencyRedirect.expectedUpdateId
215
+ ) {
216
+ console.error(
217
+ `[${new Date().toLocaleTimeString()}] 🚨 Emergency OTA redirect target mismatch rule=${emergencyRedirect.id} expectedUpdateId=${emergencyRedirect.expectedUpdateId} selectedUpdateId=${updateRow.update_id}`,
218
+ );
219
+ return createNoUpdateResponse(req, protocolVersion || 1);
220
+ }
221
+
222
+ const currentUpdateId = normalizeId(rawCurrentUpdateId);
223
+ const embeddedUpdateId = normalizeId(rawEmbeddedUpdateId);
224
+ const selectedUpdateIdNormalized = normalizeId(updateRow.update_id);
225
+ const selectedCreatedAt = normalizeExpoManifestDate(updateRow.created_at);
226
+ const currentInstalledUpdateMeta = currentUpdateId
227
+ ? await resolveDeviceBaselineMeta(currentUpdateId)
228
+ : null;
229
+
230
+ if (embeddedUpdateId && embeddedUpdateId === selectedUpdateIdNormalized) {
231
+ console.log(
232
+ `[${new Date().toLocaleTimeString()}] ⏭️ Returning noUpdateAvailable ${requestContext} reason=embedded-update-id-equals-selected-update-id embeddedUpdateId=${debugString(
233
+ embeddedUpdateId,
234
+ )} selectedUpdateId=${debugString(selectedUpdateIdNormalized)} rollbackMode=${rollbackMode}`,
235
+ );
236
+ return createNoUpdateResponse(req, protocolVersion || 1);
237
+ }
238
+
239
+ const embeddedUpdateMeta = embeddedUpdateId
240
+ ? await resolveDeviceBaselineMeta(embeddedUpdateId)
241
+ : null;
242
+
243
+ if (embeddedUpdateId && !embeddedUpdateMeta) {
244
+ console.log(
245
+ `[${new Date().toLocaleTimeString()}] ⚠️ Embedded update metadata not found ${requestContext} embeddedUpdateId=${debugString(
246
+ embeddedUpdateId,
247
+ )}`,
248
+ );
249
+ }
250
+
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
+
275
+ if (embeddedBlocksDowngrade || currentInstalledBlocksDowngrade) {
276
+ const downgradeBlockReason = embeddedBlocksDowngrade
277
+ ? "embedded-update-is-same-or-newer"
278
+ : "current-installed-update-is-same-or-newer";
279
+
280
+ console.log(
281
+ `[${new Date().toLocaleTimeString()}] ⏭️ Returning noUpdateAvailable ${requestContext} reason=${downgradeBlockReason} embeddedUpdateId=${debugString(
282
+ embeddedUpdateId,
283
+ )} embeddedCreatedAt=${debugString(
284
+ normalizeExpoManifestDate(embeddedUpdateMeta?.created_at),
285
+ )} currentInstalledUpdateId=${debugString(
286
+ currentInstalledUpdateMeta?.embedded_update_id,
287
+ )} currentInstalledCreatedAt=${debugString(
288
+ normalizeExpoManifestDate(currentInstalledUpdateMeta?.created_at),
289
+ )} selectedUpdateId=${debugString(
290
+ selectedUpdateIdNormalized,
291
+ )} selectedCreatedAt=${selectedCreatedAt ?? "none"} rollbackMode=${rollbackMode}`,
292
+ );
293
+ return createNoUpdateResponse(req, protocolVersion || 1);
294
+ }
295
+
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
+ const updateRef = {
304
+ runtimeVersion: updateRow.runtime_version,
305
+ platform: updateRow.platform,
306
+ channel: updateRow.channel,
307
+ createdAtPath: updateRow.created_at_path,
308
+ updateId: updateRow.update_id,
309
+ };
310
+
311
+ const platformExportMetadata =
312
+ updateInfo.fileMetadata &&
313
+ typeof updateInfo.fileMetadata === "object" &&
314
+ updateInfo.fileMetadata[platform]
315
+ ? updateInfo.fileMetadata[platform]
316
+ : null;
317
+
318
+ // served_manifest_id is a fresh UUID generated by DB trigger on every channel
319
+ // change (deploy, rollback, promote). Using it as manifest id ensures:
320
+ // 1. The update lands in SQLite with a fresh commit_time (active_changed_at),
321
+ // so LauncherSelectionPolicy always picks it over any stale phantom entries.
322
+ // 2. No PRIMARY KEY conflict — this UUID has never been in the client's SQLite.
323
+ //
324
+ // "noUpdate" matching checks BOTH served_manifest_id AND the raw update_id so
325
+ // that devices already running the target build are not offered a redundant update:
326
+ // - device received the update via a previous served_manifest_id → matches id
327
+ // - device received the update via its original update_id (e.g. first-time deploy
328
+ // where served_manifest_id happened to equal update_id, or legacy flow) → matches update_id
329
+ const manifestId = normalizeId(channelRow?.served_manifest_id);
330
+ const id = resolveManifestId(manifestId, updateRow.update_id);
331
+
332
+ // A normal deploy must remain newer than the embedded update, while a rollback
333
+ // needs the fresh served-manifest timestamp to bypass Expo downgrade protection.
334
+ const createdAt =
335
+ latestExpoManifestDate(
336
+ channelRow?.served_manifest_changed_at,
337
+ channelRow?.active_changed_at,
338
+ updateInfo.createdAt,
339
+ updateRow.created_at,
340
+ ) || new Date().toISOString();
341
+
342
+ // Resolve what real update_id the device's currentUpdateId represents.
343
+ // currentUpdateId is always a served_manifest_id (never the raw update_id
344
+ // unless the device was installed before this server was deployed).
345
+ // We look it up in ota_served_manifest_log to find the underlying update_id.
346
+ const resolvedCurrentUpdateId =
347
+ currentInstalledUpdateMeta?.embedded_update_id ||
348
+ (currentUpdateId
349
+ ? await resolveUpdateIdFromServedManifestId(currentUpdateId)
350
+ : null);
351
+
352
+ // Match if:
353
+ // 1. currentUpdateId IS the current served_manifest_id (fresh install / same channel state)
354
+ // 2. The resolved update_id equals the target — device already runs this build
355
+ // via a different served_manifest_id (e.g. rollback back to same version)
356
+ // 3. currentUpdateId IS the raw update_id (legacy / direct)
357
+ const matchesCurrentUpdate =
358
+ currentUpdateId !== null &&
359
+ (currentUpdateId === id ||
360
+ resolvedCurrentUpdateId === updateRow.update_id ||
361
+ currentUpdateId === updateRow.update_id);
362
+ const decisionReason = !currentUpdateId
363
+ ? "device-current-update-id-missing"
364
+ : matchesCurrentUpdate
365
+ ? "device-current-update-id-matches-target"
366
+ : "device-current-update-id-differs-from-target";
367
+
368
+ console.log(
369
+ `[${new Date().toLocaleTimeString()}] 🔎 OTA decision ${buildRequestContext(
370
+ {
371
+ channel,
372
+ runtimeVersion,
373
+ platform,
374
+ buildId: updateRef.updateId,
375
+ },
376
+ )} deviceCurrentUpdateId=${currentUpdateId || "none"} servedManifestId=${id || "none"} selectedUpdateId=${selectedUpdateIdNormalized || "none"} action=${
377
+ matchesCurrentUpdate ? "no-update" : "send-update"
378
+ } reason=${decisionReason} rollbackMode=${rollbackMode}`,
379
+ );
380
+
381
+ if (matchesCurrentUpdate) {
382
+ console.log(
383
+ `[${new Date().toLocaleTimeString()}] ⏭️ Returning noUpdateAvailable ${buildRequestContext(
384
+ {
385
+ channel,
386
+ runtimeVersion,
387
+ platform,
388
+ buildId: updateRef.updateId,
389
+ },
390
+ )} (current update id matches current channel target)`,
391
+ );
392
+ return createNoUpdateResponse(req, protocolVersion || 1);
393
+ }
394
+
395
+ console.log(
396
+ `[${new Date().toLocaleTimeString()}] 🆕 New OTA update found ${buildRequestContext(
397
+ {
398
+ channel,
399
+ runtimeVersion,
400
+ platform,
401
+ buildId: updateRef.updateId,
402
+ },
403
+ )} deviceCurrentUpdateId=${currentUpdateId || "none"} foundUpdateId=${updateRow.update_id} foundCreatedAt=${updateRow.created_at} foundPlatform=${updateRow.platform} foundChannel=${updateRow.channel} reason=${decisionReason}`,
404
+ );
405
+
406
+ const assets: Array<Record<string, unknown>> = [];
407
+ const extensionByAssetPath = new Map(
408
+ (platformExportMetadata?.assets || []).map((asset) => [
409
+ toPosixPath(asset.path),
410
+ asset.ext,
411
+ ]),
412
+ );
413
+
414
+ const updateAssets = Array.isArray(updateInfo.assets)
415
+ ? updateInfo.assets
416
+ : [];
417
+
418
+ for (const asset of updateAssets) {
419
+ const normalizedAssetPath = toPosixPath(asset.path);
420
+ const fileExtension = normalizeFileExtension(
421
+ asset.fileExtension,
422
+ extensionByAssetPath.get(normalizedAssetPath),
423
+ );
424
+
425
+ assets.push({
426
+ hash: asset.hash,
427
+ key: asset.key,
428
+ ...(fileExtension ? { fileExtension } : {}),
429
+ contentType: normalizeContentType(
430
+ asset.contentType,
431
+ fileExtension,
432
+ false,
433
+ ),
434
+ url: buildAssetUrl({
435
+ request: req,
436
+ runtimeVersion,
437
+ platform,
438
+ createdAtPath: updateRef.createdAtPath || "",
439
+ channel: updateRef.channel,
440
+ updateId: updateRef.updateId,
441
+ assetPath: normalizedAssetPath,
442
+ storageBasePath: updateRow.storage_base_path,
443
+ }),
444
+ });
445
+ }
446
+
447
+ console.log(
448
+ `[${new Date().toLocaleTimeString()}] 📦 Static assets prepared ${buildRequestContext(
449
+ {
450
+ channel,
451
+ runtimeVersion,
452
+ platform,
453
+ buildId: updateRef.updateId,
454
+ },
455
+ )} count=${assets.length}`,
456
+ );
457
+
458
+ const launchManifestAsset =
459
+ updateInfo.launchAsset && typeof updateInfo.launchAsset === "object"
460
+ ? updateInfo.launchAsset
461
+ : null;
462
+
463
+ if (!launchManifestAsset?.path) {
464
+ return createNoUpdateResponse(req, protocolVersion || 1);
465
+ }
466
+
467
+ const launchFileExtension = normalizeFileExtension(
468
+ launchManifestAsset.fileExtension,
469
+ "bundle",
470
+ );
471
+
472
+ const launchAsset = {
473
+ hash: launchManifestAsset.hash,
474
+ key: launchManifestAsset.key,
475
+ ...(launchFileExtension ? { fileExtension: launchFileExtension } : {}),
476
+ contentType: normalizeContentType(
477
+ launchManifestAsset.contentType,
478
+ launchFileExtension,
479
+ true,
480
+ ),
481
+ url: buildAssetUrl({
482
+ request: req,
483
+ runtimeVersion,
484
+ platform,
485
+ createdAtPath: updateRef.createdAtPath || "",
486
+ channel: updateRef.channel,
487
+ updateId: updateRef.updateId,
488
+ assetPath: launchManifestAsset.path,
489
+ storageBasePath: updateRow.storage_base_path,
490
+ }),
491
+ };
492
+
493
+ console.log(
494
+ `[${new Date().toLocaleTimeString()}] 🚀 Launch asset prepared ${buildRequestContext(
495
+ {
496
+ channel,
497
+ runtimeVersion,
498
+ platform,
499
+ buildId: updateRef.updateId,
500
+ },
501
+ )}`,
502
+ );
503
+
504
+ const manifest = {
505
+ id,
506
+ createdAt,
507
+ runtimeVersion: updateInfo.runtimeVersion || updateRow.runtime_version,
508
+ assets,
509
+ launchAsset,
510
+ metadata: {
511
+ channel,
512
+ },
513
+ extra: {
514
+ expoClient: createExpoClientConfig(
515
+ updateInfo.extra?.expoClient || updateInfo.expoClient,
516
+ ),
517
+ },
518
+ };
519
+
520
+ const manifestString = JSON.stringify(manifest);
521
+ let signature: string | null = null;
522
+ try {
523
+ console.log(
524
+ `[${new Date().toLocaleTimeString()}] 📤 Processing signature ${buildRequestContext(
525
+ {
526
+ channel,
527
+ runtimeVersion,
528
+ platform,
529
+ buildId: updateRef.updateId,
530
+ },
531
+ )}...`,
532
+ );
533
+ signature = await createSignatureHeaderIfRequested(
534
+ createSignatureRequest(req),
535
+ manifestString,
536
+ );
537
+ if (signature) {
538
+ console.log(
539
+ `[${new Date().toLocaleTimeString()}] ✅ Manifest will be signed ${buildRequestContext(
540
+ {
541
+ channel,
542
+ runtimeVersion,
543
+ platform,
544
+ buildId: updateRef.updateId,
545
+ },
546
+ )}`,
547
+ );
548
+ } else {
549
+ console.log(
550
+ `[${new Date().toLocaleTimeString()}] ⚪ Manifest will NOT be signed ${buildRequestContext(
551
+ {
552
+ channel,
553
+ runtimeVersion,
554
+ platform,
555
+ buildId: updateRef.updateId,
556
+ },
557
+ )} (no expect-signature header)`,
558
+ );
559
+ }
560
+ } catch (signatureError: unknown) {
561
+ return Response.json(
562
+ { error: (signatureError as Error).message },
563
+ { status: 400 },
564
+ );
565
+ }
566
+
567
+ const assetRequestHeaders: Record<string, Record<string, never>> = {};
568
+ [...assets, launchAsset].forEach((asset) => {
569
+ const key = typeof asset.key === "string" ? asset.key : null;
570
+ if (!key) {
571
+ return;
572
+ }
573
+ assetRequestHeaders[key] = {};
574
+ });
575
+
576
+ const form = new NodeFormData();
577
+ form.append("manifest", manifestString, {
578
+ contentType: "application/json",
579
+ header: {
580
+ "content-type": "application/json; charset=utf-8",
581
+ ...(signature ? { "expo-signature": signature } : {}),
582
+ },
583
+ });
584
+ form.append("extensions", JSON.stringify({ assetRequestHeaders }), {
585
+ contentType: "application/json",
586
+ });
587
+
588
+ const response = createMultipartResponse({
589
+ protocolVersion,
590
+ boundary: form.getBoundary(),
591
+ buffer: new Uint8Array(form.getBuffer()),
592
+ });
593
+
594
+ console.log(
595
+ `[${new Date().toLocaleTimeString()}] 📤 Manifest multipart sent ${buildRequestContext(
596
+ {
597
+ channel,
598
+ runtimeVersion,
599
+ platform,
600
+ buildId: updateRef.updateId,
601
+ },
602
+ )} id=${id} protocol=${protocolVersion}`,
603
+ );
604
+
605
+ // Log the mapping so future requests can resolve this served_manifest_id
606
+ // back to the real update_id (needed to detect "already on this version").
607
+ logServedManifest({
608
+ servedManifestId: id,
609
+ updateId: updateRow.update_id,
610
+ runtimeVersion,
611
+ channel,
612
+ platform,
613
+ reason: rollbackMode ? "rollback" : "deploy",
614
+ });
615
+
616
+ return response;
617
+ } catch (error: unknown) {
618
+ console.error(
619
+ `[${new Date().toLocaleTimeString()}] ❌ Manifest error ${requestContext}:`,
620
+ error,
621
+ );
622
+ return Response.json({ error: (error as Error).message }, { status: 500 });
623
+ }
624
+ };
625
+
626
+ export default manifestController;
@@ -0,0 +1,36 @@
1
+ import { NextRequest } from "next/server.js";
2
+
3
+ function getClientIp(req: NextRequest) {
4
+ const forwarded = req.headers.get("x-forwarded-for");
5
+ if (forwarded) {
6
+ const firstIp = forwarded.split(",")[0]?.trim();
7
+ if (firstIp) {
8
+ return firstIp;
9
+ }
10
+ }
11
+
12
+ return req.headers.get("x-real-ip") || "unknown";
13
+ }
14
+
15
+ const updateCompleteController = async (req: NextRequest) => {
16
+ if (req.method !== "POST") {
17
+ return Response.json({ error: "Expected POST." }, { status: 405 });
18
+ }
19
+
20
+ let runtimeVersion: string | null = null;
21
+ try {
22
+ const body = await req.json();
23
+ runtimeVersion =
24
+ typeof body?.runtimeVersion === "string" ? body.runtimeVersion : null;
25
+ } catch {
26
+ runtimeVersion = null;
27
+ }
28
+
29
+ const clientIp = getClientIp(req);
30
+ console.log(
31
+ `[${new Date().toLocaleTimeString()}] ✅ Update completed successfully (IP: ${clientIp}, Runtime: ${runtimeVersion || "unknown"})`,
32
+ );
33
+ return Response.json({ success: true });
34
+ };
35
+
36
+ export default updateCompleteController;