create-expo-updates-server 0.1.6 → 0.2.1

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 (143) hide show
  1. package/dist/template/.dockerignore +16 -0
  2. package/dist/template/Dockerfile +5 -0
  3. package/dist/template/README.md +51 -660
  4. package/dist/template/app/api/admin/device-targets/route.test.ts +43 -0
  5. package/dist/template/app/api/admin/device-targets/route.ts +91 -0
  6. package/dist/template/app/api/admin/devices/route.test.ts +41 -0
  7. package/dist/template/app/api/admin/devices/route.ts +15 -0
  8. package/dist/template/app/api/admin/updates/[encodedKey]/audience/route.ts +75 -0
  9. package/dist/template/app/api/device-heartbeat/route.ts +2 -0
  10. package/dist/template/app/globals.css +114 -15
  11. package/dist/template/app/layout.tsx +12 -4
  12. package/dist/template/app/login/page.tsx +22 -18
  13. package/dist/template/app/updates/[encodedKey]/page.tsx +112 -88
  14. package/dist/template/app/updates/devices/page.tsx +264 -0
  15. package/dist/template/app/updates/embedded/page.tsx +102 -68
  16. package/dist/template/app/updates/emergency-redirects/page.tsx +144 -111
  17. package/dist/template/app/updates/layout.tsx +6 -1
  18. package/dist/template/app/updates/page.tsx +262 -212
  19. package/dist/template/components/admin/admin-shell.tsx +196 -0
  20. package/dist/template/components/admin/language-switcher.tsx +25 -0
  21. package/dist/template/components/admin/theme-provider.tsx +15 -0
  22. package/dist/template/components/ui/alert.tsx +65 -0
  23. package/dist/template/components/ui/badge.tsx +47 -0
  24. package/dist/template/components/ui/button.tsx +63 -0
  25. package/dist/template/components/ui/card.tsx +91 -0
  26. package/dist/template/components/ui/chart.tsx +373 -0
  27. package/dist/template/components/ui/checkbox.tsx +31 -0
  28. package/dist/template/components/ui/dialog.tsx +158 -0
  29. package/dist/template/components/ui/dropdown-menu.tsx +256 -0
  30. package/dist/template/components/ui/input.tsx +20 -0
  31. package/dist/template/components/ui/label.tsx +23 -0
  32. package/dist/template/components/ui/native-select.tsx +61 -0
  33. package/dist/template/components/ui/popover.tsx +88 -0
  34. package/dist/template/components/ui/scroll-area.tsx +57 -0
  35. package/dist/template/components/ui/select.tsx +189 -0
  36. package/dist/template/components/ui/separator.tsx +27 -0
  37. package/dist/template/components/ui/sheet.tsx +142 -0
  38. package/dist/template/components/ui/sidebar.tsx +736 -0
  39. package/dist/template/components/ui/skeleton.tsx +13 -0
  40. package/dist/template/components/ui/switch.tsx +34 -0
  41. package/dist/template/components/ui/table.tsx +115 -0
  42. package/dist/template/components/ui/tabs.tsx +90 -0
  43. package/dist/template/components/ui/textarea.tsx +17 -0
  44. package/dist/template/components/ui/tooltip.tsx +56 -0
  45. package/dist/template/components.json +22 -0
  46. package/dist/template/docker/minio.Dockerfile +11 -0
  47. package/dist/template/docker-compose.yml +7 -9
  48. package/dist/template/docs/admin-ui.md +35 -0
  49. package/dist/template/docs/device-targeting.md +129 -0
  50. package/dist/template/docs/doctor.md +137 -0
  51. package/dist/template/docs/expo-app-setup.md +174 -47
  52. package/dist/template/docs/getting-started.md +109 -146
  53. package/dist/template/docs/getting-started.ru.md +110 -193
  54. package/dist/template/docs/index.md +14 -33
  55. package/dist/template/docs/installation-telemetry.md +233 -0
  56. package/dist/template/docs/migrations/2026-10-16-manifest-identity.sql +89 -0
  57. package/dist/template/docs/migrations/2026-10-19-device-heartbeat.sql +131 -0
  58. package/dist/template/docs/migrations/2026-10-22-device-analytics.sql +264 -0
  59. package/dist/template/docs/migrations/2026-10-22-device-targeting-activation.sql +108 -0
  60. package/dist/template/docs/migrations/2026-10-22-device-targeting.sql +130 -0
  61. package/dist/template/docs/migrations/2026-10-22-device-version-metadata.sql +154 -0
  62. package/dist/template/docs/migrations/schema.sql +868 -6
  63. package/dist/template/docs/npm-installer.md +15 -30
  64. package/dist/template/docs/operations-guide.md +87 -0
  65. package/dist/template/docs/ota-client-lifecycle.md +263 -0
  66. package/dist/template/docs/ota-update-policy.md +36 -2
  67. package/dist/template/docs/supabase-setup.md +4 -0
  68. package/dist/template/hooks/use-mobile.ts +21 -0
  69. package/dist/template/lib/utils.ts +6 -0
  70. package/dist/template/package-lock.json +2325 -101
  71. package/dist/template/package.json +13 -3
  72. package/dist/template/scripts/configure-expo-app.mjs +11 -15
  73. package/dist/template/scripts/doctor.mjs +51 -0
  74. package/dist/template/scripts/ensure-storage-bucket.mjs +25 -0
  75. package/dist/template/scripts/ensure-test-bucket.mjs +21 -0
  76. package/dist/template/scripts/lib/device-identity.test.ts +29 -0
  77. package/dist/template/scripts/lib/doctor-probes.mjs +139 -0
  78. package/dist/template/scripts/lib/doctor.mjs +208 -0
  79. package/dist/template/scripts/lib/doctor.test.mjs +262 -0
  80. package/dist/template/scripts/lib/expo-app-configurator.mjs +14 -9
  81. package/dist/template/scripts/lib/expo-app-configurator.test.ts +3 -2
  82. package/dist/template/scripts/lib/ota-client-configurator.mjs +69 -0
  83. package/dist/template/scripts/lib/ota-client-configurator.test.ts +88 -0
  84. package/dist/template/scripts/lib/ota-client.test.ts +55 -0
  85. package/dist/template/scripts/lib/ota-root-hook-patcher.mjs +173 -0
  86. package/dist/template/scripts/lib/ota-root-hook-patcher.test.ts +123 -0
  87. package/dist/template/scripts/lib/ota-update-controller.test.ts +231 -0
  88. package/dist/template/scripts/tests/device-analytics-migrations.mjs +80 -0
  89. package/dist/template/scripts/tests/device-analytics.mjs +126 -0
  90. package/dist/template/scripts/tests/device-heartbeat.mjs +86 -0
  91. package/dist/template/scripts/tests/device-targeting-activation.mjs +111 -0
  92. package/dist/template/scripts/tests/device-targeting.mjs +39 -0
  93. package/dist/template/scripts/tests/device-version-metadata.mjs +31 -0
  94. package/dist/template/scripts/tests/manifest-identity-concurrency.mjs +106 -0
  95. package/dist/template/scripts/tests/manifest-identity.sql +204 -0
  96. package/dist/template/src/client/admin-types.ts +1 -0
  97. package/dist/template/src/client/devices/analytics.tsx +429 -0
  98. package/dist/template/src/client/devices/device-name.tsx +82 -0
  99. package/dist/template/src/client/devices/registry.tsx +399 -0
  100. package/dist/template/src/client/devices/use-devices-report.ts +108 -0
  101. package/dist/template/src/client/devices/version-adoption-chart.tsx +269 -0
  102. package/dist/template/src/client/devices/version-groups.test.ts +57 -0
  103. package/dist/template/src/client/devices/version-groups.ts +101 -0
  104. package/dist/template/src/client/distribution-control.tsx +135 -81
  105. package/dist/template/src/client/guard-action-combobox.tsx +13 -24
  106. package/dist/template/src/client/i18n/en.json +286 -0
  107. package/dist/template/src/client/i18n/messages.test.ts +42 -0
  108. package/dist/template/src/client/i18n/messages.ts +31 -0
  109. package/dist/template/src/client/i18n/provider.tsx +55 -0
  110. package/dist/template/src/client/i18n/use-formatters.ts +38 -0
  111. package/dist/template/src/client/logout-button.tsx +3 -1
  112. package/dist/template/src/client/update-audience-editor.tsx +285 -0
  113. package/dist/template/src/client/update-policy-editor.tsx +53 -41
  114. package/dist/template/src/server/controllers/manifest.test.ts +250 -7
  115. package/dist/template/src/server/controllers/manifest.ts +39 -31
  116. package/dist/template/src/server/devices/audience.test.ts +48 -0
  117. package/dist/template/src/server/devices/audience.ts +86 -0
  118. package/dist/template/src/server/devices/heartbeat.test.ts +39 -0
  119. package/dist/template/src/server/devices/heartbeat.ts +75 -0
  120. package/dist/template/src/server/devices/report-types.ts +114 -0
  121. package/dist/template/src/server/devices/report.test.ts +29 -0
  122. package/dist/template/src/server/devices/report.ts +27 -0
  123. package/dist/template/src/server/lib/admin-audience-activation.test.ts +94 -0
  124. package/dist/template/src/server/lib/admin-updates.ts +32 -168
  125. package/dist/template/src/server/lib/supabase.js +10 -10
  126. package/dist/template/src/server/lib/supabase.test.ts +11 -0
  127. package/dist/template/src/server/manifest/manifest-identity.test.ts +30 -0
  128. package/dist/template/src/server/manifest/manifest-identity.ts +24 -0
  129. package/dist/template/src/server/manifest/manifest-repository.ts +31 -102
  130. package/dist/template/src/server/manifest/manifest-response.ts +1 -1
  131. package/dist/template/templates/expo-app/ota-client/README.md +59 -0
  132. package/dist/template/templates/expo-app/ota-client/controller.js +60 -0
  133. package/dist/template/templates/expo-app/ota-client/device-identity.js +26 -0
  134. package/dist/template/templates/expo-app/ota-client/docs/update-lifecycle.md +52 -0
  135. package/dist/template/templates/expo-app/ota-client/index.d.ts +47 -0
  136. package/dist/template/templates/expo-app/ota-client/index.js +3 -0
  137. package/dist/template/templates/expo-app/ota-client/model/hooks/useOtaUpdates.js +48 -0
  138. package/dist/template/templates/expo-app/ota-client/model/update-controller.js +182 -0
  139. package/dist/template/templates/expo-app/ota-client/runtime.js +112 -0
  140. package/dist/template/templates/expo-app/ota-client/ui/ota-update-gate.js +56 -0
  141. package/dist/template-manifest.json +592 -77
  142. package/lib/cli.mjs +4 -6
  143. package/package.json +1 -1
@@ -199,7 +199,7 @@ class TableQuery {
199
199
  this.operation = "select";
200
200
  this.selectedColumns = "*";
201
201
  this.filters = [];
202
- this.orderBy = null;
202
+ this.orderBy = [];
203
203
  this.limitValue = null;
204
204
  this.updatePayload = null;
205
205
  this.upsertPayload = null;
@@ -233,11 +233,11 @@ class TableQuery {
233
233
  }
234
234
 
235
235
  order(column, options = {}) {
236
- this.orderBy = {
236
+ this.orderBy.push({
237
237
  column,
238
238
  ascending: options.ascending !== false,
239
239
  nullsFirst: options.nullsFirst === true,
240
- };
240
+ });
241
241
  return this;
242
242
  }
243
243
 
@@ -351,13 +351,13 @@ class TableQuery {
351
351
  }
352
352
 
353
353
  buildOrderClause() {
354
- if (!this.orderBy) {
355
- return "";
356
- }
357
-
358
- const direction = this.orderBy.ascending ? "ASC" : "DESC";
359
- const nulls = this.orderBy.nullsFirst ? "NULLS FIRST" : "NULLS LAST";
360
- return ` ORDER BY ${this.orderBy.column} ${direction} ${nulls}`;
354
+ if (!this.orderBy.length) return "";
355
+ const terms = this.orderBy.map(({ column, ascending, nullsFirst }) => {
356
+ const direction = ascending ? "ASC" : "DESC";
357
+ const nulls = nullsFirst ? "NULLS FIRST" : "NULLS LAST";
358
+ return `${column} ${direction} ${nulls}`;
359
+ });
360
+ return ` ORDER BY ${terms.join(", ")}`;
361
361
  }
362
362
 
363
363
  buildLimitClause(index) {
@@ -117,6 +117,17 @@ describe("common database abstraction", () => {
117
117
  );
118
118
  });
119
119
 
120
+ it("preserves primary ordering when a tie-breaker is chained", async () => {
121
+ const { supabase } = await import("./supabase.js");
122
+ await supabase.from("ota_updates").select("update_id")
123
+ .order("created_at", { ascending: false })
124
+ .order("update_id", { ascending: true, nullsFirst: true }).limit(1).execute();
125
+ expect(poolQuery).toHaveBeenCalledWith(
126
+ "SELECT update_id FROM ota_updates ORDER BY created_at DESC NULLS LAST, update_id ASC NULLS FIRST LIMIT $1",
127
+ [1],
128
+ );
129
+ });
130
+
120
131
  it("serializes wrapped JSONB payloads but preserves PostgreSQL arrays", async () => {
121
132
  const payload = { message: "Ready" };
122
133
  const { jsonb, supabase } = await import("./supabase.js");
@@ -0,0 +1,30 @@
1
+ import { describe, expect, it } from "vitest";
2
+ import { createServedManifestId } from "./manifest-identity";
3
+
4
+ const epoch = "33333333-3333-4333-8333-333333333333";
5
+ const artifact = "11111111-1111-4111-8111-111111111111";
6
+
7
+ describe("served manifest identity", () => {
8
+ it("matches UUID v5 independently computed with Python uuid.uuid5", () => {
9
+ expect(createServedManifestId(epoch, artifact)).toBe(
10
+ "07ca31ab-9fad-5b74-a12b-1b6ae48a17d8",
11
+ );
12
+ });
13
+
14
+ it("distinguishes artifacts and repeated publications of the same artifact", () => {
15
+ const id = createServedManifestId(epoch, artifact);
16
+ expect(createServedManifestId(epoch, "22222222-2222-4222-8222-222222222222")).not.toBe(id);
17
+ expect(createServedManifestId("44444444-4444-4444-8444-444444444444", artifact)).not.toBe(id);
18
+ });
19
+
20
+ it("normalizes UUID casing", () => {
21
+ const mixed = "abcdefab-abcd-4abc-8abc-abcdefabcdef";
22
+ expect(createServedManifestId(mixed.toUpperCase(), mixed.toUpperCase())).toBe(
23
+ createServedManifestId(mixed, mixed),
24
+ );
25
+ });
26
+
27
+ it.each([null, undefined, "", "invalid"])("rejects missing or corrupt epoch %s", (value) => {
28
+ expect(() => createServedManifestId(value, artifact)).toThrow("valid channel epoch");
29
+ });
30
+ });
@@ -0,0 +1,24 @@
1
+ import { createHash } from "node:crypto";
2
+
3
+ const UUID_PATTERN = /^[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}$/i;
4
+
5
+ /** UUID v5: the channel publication epoch is the namespace, the artifact is the name. */
6
+ export function createServedManifestId(
7
+ channelEpoch: string | null | undefined,
8
+ updateId: string,
9
+ ): string {
10
+ if (!channelEpoch || !UUID_PATTERN.test(channelEpoch) || !UUID_PATTERN.test(updateId)) {
11
+ throw new Error("A valid channel epoch and update UUID are required to serve a manifest.");
12
+ }
13
+
14
+ const namespace = Buffer.from(channelEpoch.replaceAll("-", ""), "hex");
15
+ const bytes = createHash("sha1")
16
+ .update(namespace)
17
+ .update(updateId.toLowerCase(), "utf8")
18
+ .digest()
19
+ .subarray(0, 16);
20
+ bytes[6] = (bytes[6] & 0x0f) | 0x50;
21
+ bytes[8] = (bytes[8] & 0x3f) | 0x80;
22
+ const hex = bytes.toString("hex");
23
+ return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(12, 16)}-${hex.slice(16, 20)}-${hex.slice(20)}`;
24
+ }
@@ -1,8 +1,9 @@
1
+ import { Audience, RequestIdentity } from "../devices/audience";
1
2
  import { supabase } from "../lib/supabase.js";
2
3
  import { UpdateDeliveryMode } from "../lib/update-policy";
3
4
  import { getManifestAppVersion } from "./manifest-values";
4
5
 
5
- export type OtaUpdateRow = {
6
+ export type OtaUpdateRow = Partial<Audience> & {
6
7
  update_id: string;
7
8
  build_id: string;
8
9
  runtime_version: string;
@@ -36,70 +37,22 @@ export type EmbeddedUpdateMeta = {
36
37
  app_version: string | null;
37
38
  };
38
39
 
39
- let hasServedManifestLogTable: boolean | null = null;
40
-
41
- function isMissingServedManifestLogTableError(error: unknown): boolean {
42
- if (!error || typeof error !== "object") {
43
- return false;
44
- }
45
-
46
- const message =
47
- "message" in error && typeof error.message === "string"
48
- ? error.message.toLowerCase()
49
- : "";
50
-
51
- return (
52
- message.includes("ota_served_manifest_log") &&
53
- message.includes("does not exist")
54
- );
55
- }
56
-
57
- export function resolveManifestId(
58
- servedManifestId: string | null,
59
- updateId: string,
60
- ): string {
61
- return hasServedManifestLogTable === true && servedManifestId
62
- ? servedManifestId
63
- : updateId;
64
- }
65
-
66
40
  export async function resolveUpdateIdFromServedManifestId(
67
41
  servedManifestId: string,
68
42
  ): Promise<string | null> {
69
- if (hasServedManifestLogTable === false) {
70
- return null;
71
- }
72
-
73
- try {
74
- const { data, error } = await supabase
75
- .from("ota_served_manifest_log")
76
- .select("update_id")
77
- .eq("served_manifest_id", servedManifestId)
78
- .maybeSingle();
79
-
80
- if (isMissingServedManifestLogTableError(error)) {
81
- hasServedManifestLogTable = false;
82
- return null;
83
- }
84
-
85
- if (error || !data) {
86
- if (hasServedManifestLogTable === null) {
87
- hasServedManifestLogTable = true;
88
- }
89
- return null;
90
- }
43
+ const { data, error } = await supabase
44
+ .from("ota_served_manifest_log")
45
+ .select("update_id")
46
+ .eq("served_manifest_id", servedManifestId)
47
+ .maybeSingle();
91
48
 
92
- hasServedManifestLogTable = true;
93
- return (data as { update_id: string }).update_id || null;
94
- } catch (error: unknown) {
95
- if (isMissingServedManifestLogTableError(error)) {
96
- hasServedManifestLogTable = false;
97
- }
98
- return null;
49
+ if (error) {
50
+ throw new Error(`Failed to resolve served manifest: ${error.message}`);
99
51
  }
52
+ return (data as { update_id: string } | null)?.update_id || null;
100
53
  }
101
54
 
102
- export function logServedManifest({
55
+ export async function recordServedManifest({
103
56
  servedManifestId,
104
57
  updateId,
105
58
  runtimeVersion,
@@ -113,12 +66,10 @@ export function logServedManifest({
113
66
  channel: string;
114
67
  platform: string;
115
68
  reason: string;
116
- }): void {
117
- if (hasServedManifestLogTable === false) {
118
- return;
119
- }
120
-
121
- supabase
69
+ }): Promise<void> {
70
+ // The database rejects reassignment of an existing ID to another update.
71
+ // Await this write before returning a manifest to a device.
72
+ const { error } = await supabase
122
73
  .from("ota_served_manifest_log")
123
74
  .upsert(
124
75
  {
@@ -131,27 +82,11 @@ export function logServedManifest({
131
82
  },
132
83
  { onConflict: "served_manifest_id" },
133
84
  )
134
- .then(({ error }) => {
135
- if (isMissingServedManifestLogTableError(error)) {
136
- hasServedManifestLogTable = false;
137
- return;
138
- }
85
+ .execute();
139
86
 
140
- if (!error && hasServedManifestLogTable === null) {
141
- hasServedManifestLogTable = true;
142
- }
143
-
144
- if (
145
- error &&
146
- !error.message?.includes("duplicate") &&
147
- !error.message?.includes("unique")
148
- ) {
149
- console.warn(
150
- `[${new Date().toLocaleTimeString()}] ⚠️ Failed to log served manifest: ${error.message}`,
151
- );
152
- }
153
- })
154
- .catch(() => undefined);
87
+ if (error) {
88
+ throw new Error(`Failed to record served manifest: ${error.message}`);
89
+ }
155
90
  }
156
91
 
157
92
  export async function getChannelRow({
@@ -252,27 +187,21 @@ export async function getLatestActiveUpdate({
252
187
  runtimeVersion,
253
188
  channel,
254
189
  platform,
190
+ identity,
255
191
  }: {
256
192
  runtimeVersion: string;
257
193
  channel: string;
258
194
  platform: "ios" | "android";
195
+ identity: RequestIdentity;
259
196
  }): Promise<OtaUpdateRow | null> {
260
- const { data, error } = await supabase
261
- .from("ota_updates")
262
- .select("*")
263
- .eq("runtime_version", runtimeVersion)
264
- .eq("channel", channel)
265
- .eq("platform", platform)
266
- .eq("is_active", true)
267
- .order("created_at", { ascending: false })
268
- .limit(1)
269
- .maybeSingle();
270
-
271
- if (error) {
272
- throw new Error(
273
- `Failed to load latest active update row: ${error.message}`,
274
- );
275
- }
276
-
277
- return (data as OtaUpdateRow | null) || null;
197
+ const { data, error } = await supabase.rpc("ota_latest_eligible_update", {
198
+ p_runtime: runtimeVersion,
199
+ p_channel: channel,
200
+ p_platform: platform,
201
+ p_installation: identity.installationId,
202
+ p_device: identity.deviceId,
203
+ });
204
+ if (error)
205
+ throw new Error(`Failed to load eligible update: ${error.message}`);
206
+ return data?.[0] || null;
278
207
  }
@@ -113,7 +113,7 @@ export function createMultipartResponse({
113
113
  headers: {
114
114
  "expo-protocol-version": String(protocolVersion),
115
115
  "expo-sfv-version": "0",
116
- "cache-control": "private, max-age=0",
116
+ "cache-control": "private, no-store",
117
117
  "content-type": `multipart/mixed; boundary=${boundary}`,
118
118
  },
119
119
  });
@@ -0,0 +1,59 @@
1
+ # Installation telemetry client
2
+
3
+ Generated by `configure-app`; update the server template and rerun configuration to upgrade it.
4
+ Build and install a new native binary when first adding this client: it requires
5
+ expo-updates, expo-application, expo-crypto, expo-secure-store and AsyncStorage. Do not deliver newly
6
+ required native modules to an older binary via OTA. Keep these native dependencies
7
+ in the same runtime compatibility boundary as the rest of your application.
8
+
9
+ `ota-entry.js` starts telemetry without waiting, then synchronously loads the original
10
+ entry saved in `ota-client-entry.json`. The configurator also patches the root layout with the update hook and gate. Development,
11
+ Expo Go, web and disabled-updates builds do not report. Original OTA check policy
12
+ remains under the application/configurator's control.
13
+
14
+ The public API exports `start()`, `getInstallationId()`, `checkForUpdateAsync()` and
15
+ `fetchUpdateAsync()`. The latter two wait for durable identity and the installation_id
16
+ Expo extra parameter. Direct Expo calls at module startup do not have this guarantee.
17
+ Telemetry failure never waits on network before returning identity.
18
+
19
+ State is a single AsyncStorage envelope: installation ID, increasing sequence and
20
+ one pending event. Writes/acks serialize; network requests have an 8-second timeout.
21
+ Startup and active foreground report the current launch; active timers refresh no
22
+ more often than once per minute. Failures retry with capped backoff (up to 5 minutes).
23
+ One latest pending snapshot bounds offline storage; it is not an exhaustive offline
24
+ transition history. Only accepted receipts refresh server last-seen time.
25
+
26
+ The ID identifies an installation, not a person or a permanent physical device.
27
+ Clearing app data/reinstallation may change it; OS backup/restore may copy it. Never
28
+ use this self-reported ID as authorization. No admin/database/storage secrets belong
29
+ in this directory. Heartbeat indicates JS startup, not successful smoke testing.
30
+
31
+ ## Device-targeted releases
32
+
33
+ The entry bootstrap also initializes a separate Device ID automatically. Android uses a
34
+ SHA-256 hash of app-scoped Android ID; iOS uses a random seed in SecureStore/Keychain.
35
+ Both are scoped to application ID and `config.json.identityNamespace`. Keep that namespace
36
+ stable when changing tunnel URLs. Runtime/channel changes do not change Device ID.
37
+ Installation ID still changes on reinstall and remains the unit of telemetry.
38
+
39
+ Device ID may survive reinstalls, but is not guaranteed across factory reset, signing key
40
+ changes or iOS Keychain deletion. Raw Android IDs never leave the device. If identity is
41
+ unavailable, the server only offers public or explicitly installation-targeted releases.
42
+
43
+ `getDeviceId()` is optional for displaying diagnostics. `start()` is already called by the
44
+ generated entry; telemetry works independently of the root hook. Custom check/download UI should use the
45
+ exports here, which await identity initialization before calling Expo. Direct Expo calls
46
+ made too early are anonymous. Rebuild the native app with a new runtime after adding
47
+ SecureStore; do not deliver this client to older binaries lacking the native dependency.
48
+
49
+ ## Update hook
50
+
51
+ `useOtaUpdates` shares identity, state and lifecycle actions across the application.
52
+ The configurator inserts it and `OtaUpdateGate` in the root layout automatically.
53
+ See [Update lifecycle](./docs/update-lifecycle.md) for manual/automatic/background
54
+ updates, force OTA versus store upgrades, custom guards and option defaults.
55
+
56
+ For a custom root that could not be patched, see the complete
57
+ [manual integration guide](https://tonichiga.github.io/expo-updates-server/ota-client-lifecycle#manual-integration)
58
+ (or `docs/ota-client-lifecycle.md` in the server repository). It covers both an
59
+ already generated client and copying/configuring the client without the generator.
@@ -0,0 +1,60 @@
1
+ // Pure controller: storage and network are injected so ordering is testable.
2
+ // One persisted envelope owns identity, sequence and the bounded outbox.
3
+ export function createInstallationClient({ read, write, uuid, snapshot, send, setIdentity, now = () => new Date().toISOString() }) {
4
+ let state;
5
+ let queue = Promise.resolve();
6
+ let flight;
7
+ const serial = (work) => {
8
+ const result = queue.then(work);
9
+ queue = result.catch(() => undefined);
10
+ return result;
11
+ };
12
+ async function initialize() {
13
+ if (state) return state;
14
+ const stored = await read();
15
+ if (stored) {
16
+ const parsed = JSON.parse(stored);
17
+ if (!parsed.installationId || !Number.isSafeInteger(parsed.sequence) || parsed.sequence < 0) throw new Error("Invalid OTA client state");
18
+ state = parsed;
19
+ } else {
20
+ const next = { installationId: uuid(), sequence: 0, pending: null };
21
+ await write(JSON.stringify(next));
22
+ state = next;
23
+ }
24
+ return state;
25
+ }
26
+ const ready = () => serial(async () => {
27
+ const current = await initialize();
28
+ await setIdentity(current.installationId);
29
+ return current.installationId;
30
+ });
31
+ async function flush() {
32
+ if (flight) return flight;
33
+ flight = (async () => {
34
+ const pending = await serial(async () => (await initialize()).pending);
35
+ if (!pending) return;
36
+ await send(pending);
37
+ await serial(async () => {
38
+ if (state.pending?.eventId !== pending.eventId) return;
39
+ const next = { ...state, pending: null };
40
+ await write(JSON.stringify(next));
41
+ state = next;
42
+ });
43
+ })();
44
+ try { await flight; } finally { flight = undefined; }
45
+ }
46
+ async function observe() {
47
+ await serial(async () => {
48
+ const current = await initialize();
49
+ await setIdentity(current.installationId);
50
+ if (current.sequence >= Number.MAX_SAFE_INTEGER) throw new Error("OTA sequence exhausted");
51
+ const sequence = current.sequence + 1;
52
+ const pending = { ...snapshot(), installationId: current.installationId, eventId: uuid(), sequence, observedAt: now() };
53
+ const next = { ...current, sequence, pending };
54
+ await write(JSON.stringify(next));
55
+ state = next;
56
+ });
57
+ await flush();
58
+ }
59
+ return { ready, observe, flush };
60
+ }
@@ -0,0 +1,26 @@
1
+ // Dependencies are injected so reinstall behaviour can be tested without native modules.
2
+ export function createDeviceIdentity({ platform, scope, androidId, readSecure, writeSecure, uuid, digest }) {
3
+ let flight;
4
+ async function resolve() {
5
+ const namespace = await digest(`ota-device-v1:${scope}`);
6
+ let seed;
7
+ if (platform === 'android') {
8
+ seed = androidId();
9
+ if (!seed) throw new Error('Android ID unavailable');
10
+ } else if (platform === 'ios') {
11
+ const key = `ota-device-v1.${namespace}`;
12
+ seed = await readSecure(key);
13
+ if (!seed) {
14
+ seed = uuid();
15
+ await writeSecure(key, seed);
16
+ }
17
+ } else {
18
+ return null;
19
+ }
20
+ return digest(`${namespace}:${platform}:${seed}`);
21
+ }
22
+ return () => {
23
+ if (!flight) flight = resolve().catch((error) => { flight = undefined; throw error; });
24
+ return flight;
25
+ };
26
+ }
@@ -0,0 +1,52 @@
1
+ # Update lifecycle
2
+
3
+ `configure-app` inserts `useOtaUpdates({ autoCheck: true, autoUpdate: false,
4
+ autoReload: false })` in the root layout/App and wraps its content in `OtaUpdateGate`.
5
+ All screens can call `useOtaUpdates()` to observe the same state and use `check()`,
6
+ `download()` and `reload()`. No provider is needed. Configure automation in one root;
7
+ additional consumers default to observation/manual actions. Multiple configured roots
8
+ combine boolean options with OR. Guard handlers should be stable references.
9
+
10
+ Identity is persisted and installed in Expo request parameters before any check/download.
11
+ Launch/foreground heartbeats report only the **running** bundle, never a downloaded
12
+ candidate. Network telemetry does not block app launch or update checks. Development,
13
+ Expo Go, web and disabled-updates builds leave automation off.
14
+
15
+ | Policy/options | Behavior |
16
+ | --- | --- |
17
+ | manual, default options | Check exposes candidate; caller downloads and reloads |
18
+ | autoCheck | Check on mount and foreground, minimum interval 60 seconds |
19
+ | autoUpdate | Also download eligible manual candidates |
20
+ | autoReload | Reload a pending non-background bundle while app is active |
21
+ | delivery=background | Download silently; apply on next cold launch or manual reload |
22
+ | guard=ota-force-update | Block with gate, download automatically; restart button when ready |
23
+ | guard=ota-force-store-update | Block with gate; open store, never download this candidate |
24
+ | custom/unknown guard | Block until guardHandlers[action] explicitly returns `allow` |
25
+
26
+ Store guard payload: `{ "androidUrl": "market://details?id=com.example.app",
27
+ "iosUrl": "https://apps.apple.com/app/id123" }`; `url` is a common fallback. Only
28
+ https, market and itms-apps URLs are accepted. Native upgrades still require a store
29
+ release; OTA cannot add native modules or change the installed runtime.
30
+
31
+ The built-in gate is a non-dismissable modal that preserves mounted navigation and providers.
32
+ It is customizable with `renderBlocked`. Keep the gate mounted around
33
+ the application; a hook alone exposes `blocked` but cannot prevent interaction with
34
+ your own screens. Unknown guards fail closed. Required checks are online policy,
35
+ not authentication or a tamper-proof access restriction. Offline check failure keeps
36
+ the running app usable unless a required candidate was already discovered or the running bundle requires a store/custom guard.
37
+
38
+ Calls are single-flight per action; a different action while busy rejects. Errors are
39
+ available in `error` and returned promises reject, so handle manual calls with try/catch.
40
+ Retry rechecks the server and reevaluates a pending candidate's custom guard.
41
+ Download reevaluates the fetched manifest's policy because it can differ from the
42
+ checked candidate. A pending bundle owns the gate until reload; checking another
43
+ candidate does not authorize an older cached bundle. Native rollback directives are
44
+ supported. Expo controls cold-start loading of already downloaded bundles; JS guards
45
+ cannot revoke that native cache. Store/custom guards are checked again from the running
46
+ manifest on the next launch; force OTA is already fulfilled by launching that bundle.
47
+ Do not mix direct expo-updates calls or native automatic
48
+ checks with hook orchestration: configure-app uses checkAutomatically=NEVER.
49
+
50
+ Legacy exports `checkForUpdateAsync`/`fetchUpdateAsync` remain identity-aware low-level
51
+ APIs for existing integrations. They intentionally do not implement hook policies.
52
+ No database/admin credentials are shipped: the server persists public heartbeat reports.
@@ -0,0 +1,47 @@
1
+ import type { ReactNode } from 'react';
2
+ import type * as Updates from 'expo-updates';
3
+
4
+ export declare function start(): void;
5
+ export declare function getInstallationId(): Promise<string | null>;
6
+ export declare function getDeviceId(): Promise<string | null>;
7
+ /** Low-level compatibility API; new screens should use the shared lifecycle hook. */
8
+ export declare const checkForUpdateAsync: typeof Updates.checkForUpdateAsync;
9
+ export declare const fetchUpdateAsync: typeof Updates.fetchUpdateAsync;
10
+
11
+ export interface OtaPolicy {
12
+ schemaVersion: number;
13
+ delivery: 'manual' | 'background';
14
+ guard?: { action: string; payload?: unknown };
15
+ }
16
+ export interface OtaOptions {
17
+ /** Check at startup/foreground, at most once per minute. Default false. */
18
+ autoCheck?: boolean;
19
+ /** Download eligible manual releases automatically. Default false. */
20
+ autoUpdate?: boolean;
21
+ /** Reload downloaded non-background releases while active. Default false. */
22
+ autoReload?: boolean;
23
+ guardHandlers?: Record<string, (context: { action: string; payload: unknown; manifest: unknown }) =>
24
+ 'allow' | 'block' | Promise<'allow' | 'block'>>;
25
+ }
26
+ export interface OtaController {
27
+ enabled: boolean;
28
+ status: 'idle' | 'checking' | 'downloading' | 'reloading' | 'opening-store';
29
+ installationId: string | null;
30
+ deviceId: string | null;
31
+ available: boolean;
32
+ pending: boolean;
33
+ candidate: { type: 'new' | 'rollback'; manifest: unknown } | null;
34
+ policy: OtaPolicy | null;
35
+ blocked: boolean;
36
+ blockReason: string | null;
37
+ error: Error | null;
38
+ isBusy: boolean;
39
+ check(): Promise<Updates.UpdateCheckResult>;
40
+ download(): Promise<Updates.UpdateFetchResult>;
41
+ reload(): Promise<void>;
42
+ retry(): Promise<Updates.UpdateCheckResult>;
43
+ openStore(): Promise<void>;
44
+ }
45
+ export declare function useOtaUpdates(options?: OtaOptions): OtaController;
46
+ export declare function OtaUpdateGate(props: { controller: OtaController; children?: ReactNode;
47
+ renderBlocked?: (controller: OtaController) => ReactNode }): ReactNode;
@@ -0,0 +1,3 @@
1
+ export { start, getInstallationId, getDeviceId, checkForUpdateAsync, fetchUpdateAsync } from './runtime';
2
+ export { useOtaUpdates } from './model/hooks/useOtaUpdates';
3
+ export { OtaUpdateGate } from './ui/ota-update-gate';
@@ -0,0 +1,48 @@
1
+ import { useEffect, useRef, useSyncExternalStore } from 'react';
2
+ import * as Updates from 'expo-updates';
3
+ import { AppState, Linking, Platform } from 'react-native';
4
+ import { enabled, start, getInstallationId, getDeviceId, checkForUpdateAsync, fetchUpdateAsync } from '../../runtime';
5
+ import { createUpdateController } from '../update-controller';
6
+
7
+ const controller = createUpdateController({
8
+ enabled, start,
9
+ identity: async () => ({ installationId: await getInstallationId(), deviceId: await getDeviceId() }),
10
+ check: checkForUpdateAsync,
11
+ fetch: fetchUpdateAsync,
12
+ runningCandidate: () => ({ type: 'new', manifest: Updates.manifest }),
13
+ reload: () => Updates.reloadAsync(),
14
+ isActive: () => AppState.currentState === 'active',
15
+ openStore: async (payload) => {
16
+ const url = payload?.[`${Platform.OS}Url`] || payload?.url;
17
+ if (typeof url !== 'string' || !/^(https:\/\/|market:\/\/|itms-apps:\/\/)/i.test(url)) {
18
+ throw new Error('The store update policy must provide a valid https/store URL');
19
+ }
20
+ await Linking.openURL(url);
21
+ },
22
+ });
23
+ const emptyOptions = Object.freeze({});
24
+
25
+ /** Configure once in the root; additional consumers share identity, state and actions. */
26
+ export function useOtaUpdates(options = emptyOptions) {
27
+ const owner = useRef(Symbol('ota-updates'));
28
+ const state = useSyncExternalStore(controller.subscribe, controller.getSnapshot, controller.getSnapshot);
29
+ const native = Updates.useUpdates();
30
+ const { autoCheck = false, autoUpdate = false, autoReload = false, guardHandlers } = options;
31
+ useEffect(() => {
32
+ const token = owner.current;
33
+ controller.configure(token, { autoCheck, autoUpdate, autoReload, guardHandlers });
34
+ void controller.initialize().catch(() => undefined);
35
+ controller.automaticCheck();
36
+ const subscription = AppState.addEventListener('change', (next) => {
37
+ if (next === 'active') controller.automaticCheck();
38
+ });
39
+ return () => { subscription.remove(); controller.removeOwner(token); };
40
+ }, [autoCheck, autoUpdate, autoReload, guardHandlers]);
41
+ const downloaded = native.downloadedUpdate;
42
+ useEffect(() => {
43
+ if (!enabled || !downloaded || !native.isUpdatePending) return;
44
+ void controller.syncPending({ type: downloaded.type, manifest: downloaded.manifest }).catch(() => undefined);
45
+ }, [downloaded, native.isUpdatePending]);
46
+ return { ...state, isBusy: state.status !== 'idle', check: controller.check,
47
+ download: controller.download, reload: controller.reload, retry: controller.retry, openStore: controller.openStore };
48
+ }