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
@@ -0,0 +1,75 @@
1
+ import { deviceIdPattern } from "./audience";
2
+ import { jsonb, supabase } from "../lib/supabase.js";
3
+
4
+ const uuid = /^[0-9a-f]{8}-[0-9a-f]{4}-[1-8][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
5
+ export type Heartbeat = {
6
+ deviceId?: string;
7
+ installationId: string; eventId: string; sequence: number; observedAt: string;
8
+ platform: "ios" | "android"; channel: string; runtimeVersion: string;
9
+ updateId: string | null; nativeVersion: string | null; nativeBuild: string | null;
10
+ isEmbeddedLaunch: boolean; isEmergencyLaunch: boolean;
11
+ };
12
+ function shortString(value: unknown, max: number): value is string {
13
+ return typeof value === "string" && value.length > 0 && value.length <= max && value.trim() === value && !/[\x00-\x1f\x7f]/.test(value);
14
+ }
15
+ export function parseHeartbeat(value: unknown): Heartbeat {
16
+ if (!value || typeof value !== "object" || Array.isArray(value)) throw new Error("Invalid heartbeat");
17
+ const v = value as Record<string, unknown>;
18
+ if ((v.deviceId !== undefined && (typeof v.deviceId !== "string" || !deviceIdPattern.test(v.deviceId))) ||
19
+ typeof v.installationId !== "string" || !uuid.test(v.installationId) ||
20
+ typeof v.eventId !== "string" || !uuid.test(v.eventId) ||
21
+ !Number.isSafeInteger(v.sequence) || Number(v.sequence) < 1 ||
22
+ typeof v.observedAt !== "string" || !Number.isFinite(Date.parse(v.observedAt)) || new Date(v.observedAt).toISOString() !== v.observedAt ||
23
+ (v.platform !== "ios" && v.platform !== "android") ||
24
+ !shortString(v.channel, 64) || !/^[a-z0-9][a-z0-9._-]*$/.test(v.channel) ||
25
+ !shortString(v.runtimeVersion, 100) ||
26
+ !(v.updateId === null || (typeof v.updateId === "string" && uuid.test(v.updateId))) ||
27
+ !(v.nativeVersion === null || shortString(v.nativeVersion, 100)) ||
28
+ !(v.nativeBuild === null || shortString(v.nativeBuild, 100)) ||
29
+ typeof v.isEmbeddedLaunch !== "boolean" || typeof v.isEmergencyLaunch !== "boolean") throw new Error("Invalid heartbeat");
30
+ return {
31
+ ...(typeof v.deviceId === "string" ? { deviceId: v.deviceId } : {}),
32
+ installationId: v.installationId.toLowerCase(), eventId: v.eventId.toLowerCase(), sequence: Number(v.sequence), observedAt: v.observedAt,
33
+ platform: v.platform as Heartbeat["platform"], channel: v.channel, runtimeVersion: v.runtimeVersion,
34
+ updateId: typeof v.updateId === "string" ? v.updateId.toLowerCase() : null,
35
+ nativeVersion: v.nativeVersion as string | null, nativeBuild: v.nativeBuild as string | null,
36
+ isEmbeddedLaunch: v.isEmbeddedLaunch, isEmergencyLaunch: v.isEmergencyLaunch,
37
+ };
38
+ }
39
+ class BodyTooLarge extends Error {}
40
+ async function readBody(request: Request) {
41
+ const reader = request.body?.getReader();
42
+ if (!reader) throw new Error("Missing body");
43
+ const chunks: Uint8Array[] = [];
44
+ let size = 0;
45
+ try {
46
+ while (true) {
47
+ const { value, done } = await reader.read();
48
+ if (done) break;
49
+ size += value.byteLength;
50
+ if (size > 8192) { await reader.cancel(); throw new BodyTooLarge(); }
51
+ chunks.push(value);
52
+ }
53
+ } finally { reader.releaseLock(); }
54
+ return JSON.parse(Buffer.concat(chunks).toString("utf8"));
55
+ }
56
+ export async function recordHeartbeat(request: Request) {
57
+ if (request.headers.get("content-type")?.split(";")[0].trim() !== "application/json") {
58
+ return Response.json({ error: "Expected application/json" }, { status: 415 });
59
+ }
60
+ let event: Heartbeat;
61
+ try { event = parseHeartbeat(await readBody(request)); }
62
+ catch (error) { return Response.json({ error: "Invalid heartbeat" }, { status: error instanceof BodyTooLarge ? 413 : 400 }); }
63
+ try {
64
+ const { data, error } = await supabase.rpc("ota_record_heartbeat", { p_event: jsonb(event) });
65
+ if (error) {
66
+ if (error.message.includes("HEARTBEAT_SEQUENCE_CONFLICT")) return Response.json({ error: "Sequence conflict" }, { status: 409 });
67
+ throw new Error(error.message);
68
+ }
69
+ if (!["accepted", "duplicate", "stale"].includes(data?.[0]?.result)) throw new Error("Invalid heartbeat result");
70
+ return Response.json({ status: data[0].result }, { headers: { "Cache-Control": "no-store" } });
71
+ } catch (error) {
72
+ console.error("Heartbeat storage failed", error);
73
+ return Response.json({ error: "Heartbeat storage unavailable" }, { status: 503 });
74
+ }
75
+ }
@@ -0,0 +1,114 @@
1
+ export type DevicePlatform = "ios" | "android";
2
+ export type DeviceLaunchKind = "ota" | "embedded" | "unknown";
3
+ export type DeviceReportDays = 1 | 7 | 30;
4
+
5
+ export type DeviceReportFilters = {
6
+ days: DeviceReportDays;
7
+ platform: DevicePlatform | null;
8
+ channel: string | null;
9
+ runtime: string | null;
10
+ launchKind: DeviceLaunchKind | null;
11
+ search: string | null;
12
+ };
13
+
14
+ export type DeviceInstallation = {
15
+ device_id?: string | null;
16
+ installation_id: string;
17
+ platform: DevicePlatform;
18
+ runtime_version: string;
19
+ channel: string;
20
+ native_version: string | null;
21
+ native_build: string | null;
22
+ launch_kind: DeviceLaunchKind;
23
+ reported_update_id: string | null;
24
+ resolved_update_id: string | null;
25
+ update_label: string | null;
26
+ emergency_launch: boolean;
27
+ observed_at: string | null;
28
+ first_seen_at: string;
29
+ last_seen_at: string;
30
+ };
31
+
32
+ export type DeviceVersion = {
33
+ /** Published app version; null when artifact metadata is unavailable. */
34
+ app_version: string | null;
35
+ platform: DevicePlatform;
36
+ channel: string;
37
+ runtime_version: string;
38
+ native_version: string | null;
39
+ native_build: string | null;
40
+ launch_kind: DeviceLaunchKind;
41
+ update_id: string | null;
42
+ update_label: string | null;
43
+ installations: number;
44
+ };
45
+
46
+ export type DeviceActivityDay = {
47
+ date: string;
48
+ activeInstallations: number | null;
49
+ newInstallations: number | null;
50
+ coverage: "complete" | "partial" | "unavailable";
51
+ };
52
+
53
+ export type DeviceRetentionCell = {
54
+ day: 0 | 1 | 7 | 14 | 30;
55
+ eligibleInstallations: number;
56
+ retainedInstallations: number | null;
57
+ /** Fraction from 0 to 1; null means no fully observed eligible day yet. */
58
+ rate: number | null;
59
+ };
60
+
61
+ export type DeviceRetentionCohort = {
62
+ weekStart: string;
63
+ installations: number;
64
+ cells: DeviceRetentionCell[];
65
+ };
66
+
67
+ /** Current composition of the selected recently active population, not retention. */
68
+ export type DeviceAdoptionCohort = {
69
+ weekStart: string;
70
+ installations: number;
71
+ otaInstallations: number;
72
+ embeddedInstallations: number;
73
+ unknownInstallations: number;
74
+ };
75
+
76
+ export type DevicesReport = {
77
+ total: number;
78
+ pageSize: number;
79
+ offset: number;
80
+ devices: DeviceInstallation[];
81
+ versions: DeviceVersion[];
82
+ filters: DeviceReportFilters;
83
+ options: {
84
+ platforms: DevicePlatform[];
85
+ channels: string[];
86
+ runtimes: string[];
87
+ launchKinds: DeviceLaunchKind[];
88
+ };
89
+ summary: {
90
+ activeInstallations: number;
91
+ newInstallations: number;
92
+ otaInstallations: number;
93
+ embeddedInstallations: number;
94
+ unknownInstallations: number;
95
+ emergencyInstallations: number;
96
+ reportedVersions: number;
97
+ };
98
+ activity: DeviceActivityDay[];
99
+ adoptionCohorts: DeviceAdoptionCohort[];
100
+ cohorts: DeviceRetentionCohort[];
101
+ coverage: {
102
+ collectionStartedAt: string;
103
+ retainedFrom: string;
104
+ timezone: "UTC";
105
+ retentionDays: 90;
106
+ cohortWindowDays: 90;
107
+ activityBasis: "accepted-heartbeat-receipt";
108
+ cohortBasis: "first-recorded-heartbeat";
109
+ cohortFilters: "entry-state";
110
+ todayIsPartial: true;
111
+ generatedAt: string;
112
+ windowStartedAt: string;
113
+ };
114
+ };
@@ -0,0 +1,29 @@
1
+ import { beforeEach, describe, expect, it, vi } from "vitest";
2
+ const rpc = vi.hoisted(() => vi.fn());
3
+ vi.mock("../lib/supabase.js", () => ({ supabase: { rpc } }));
4
+ import { getDevicesReport, parseDeviceFilters } from "./report";
5
+
6
+ describe("device analytics filters", () => {
7
+ beforeEach(() => rpc.mockReset());
8
+
9
+ it("passes every validated filter to the versioned report RPC", async () => {
10
+ const filters = parseDeviceFilters(new URLSearchParams("days=30&platform=ios&channel=production&runtime=1.0&launchKind=ota&search=ABC123&offset=50"));
11
+ expect(filters).toEqual({ p_days: 30, p_platform: "ios", p_channel: "production", p_runtime: "1.0", p_offset: 50, p_launch_kind: "ota", p_search: "abc123" });
12
+ rpc.mockResolvedValue({ data: [{ report: { total: 3 } }] });
13
+ expect(await getDevicesReport(filters)).toEqual({ total: 3 });
14
+ expect(rpc).toHaveBeenCalledWith("ota_devices_report_v2", filters);
15
+ });
16
+
17
+ it.each(["days=7&days=30", "platform=ios&platform=android", "launchKind=all", "search=%25", "search=abcdef_", `search=${"a".repeat(37)}`, "search=%00", "runtime=%09", "offset=Infinity"])("rejects invalid or nonscalar filters: %s", (query) => {
18
+ expect(() => parseDeviceFilters(new URLSearchParams(query))).toThrow("Invalid filters");
19
+ });
20
+
21
+ it("keeps empty optional controls unfiltered", () => {
22
+ expect(parseDeviceFilters(new URLSearchParams("launchKind=&search=%20%20"))).toMatchObject({ p_launch_kind: null, p_search: null });
23
+ });
24
+
25
+ it.each([{ error: { message: "database unavailable" } }, { data: [] }])("fails if storage does not return an analytics report", async (result) => {
26
+ rpc.mockResolvedValue(result);
27
+ await expect(getDevicesReport(parseDeviceFilters(new URLSearchParams()))).rejects.toThrow();
28
+ });
29
+ });
@@ -0,0 +1,27 @@
1
+ import { supabase } from "../lib/supabase.js";
2
+ import type { DevicesReport } from "./report-types";
3
+
4
+ export function parseDeviceFilters(params: URLSearchParams) {
5
+ for (const name of ["days", "offset", "platform", "channel", "runtime", "launchKind", "search"]) {
6
+ if (params.getAll(name).length > 1) throw new Error("Invalid filters");
7
+ }
8
+ const days = Number(params.get("days") || 7);
9
+ const offset = Number(params.get("offset") || 0);
10
+ const platform = params.get("platform") || null;
11
+ const channel = params.get("channel") || null;
12
+ const runtime = params.get("runtime") || null;
13
+ const launchKind = params.get("launchKind") || null;
14
+ const search = params.get("search")?.trim().toLowerCase() || null;
15
+ if (![1, 7, 30].includes(days) || !Number.isSafeInteger(offset) || offset < 0 || offset > 1000000 ||
16
+ (platform !== null && !["ios", "android"].includes(platform)) ||
17
+ (channel !== null && (channel.length > 64 || !/^[a-z0-9][a-z0-9._-]*$/.test(channel))) ||
18
+ (runtime !== null && (runtime.length > 100 || runtime.trim() !== runtime || /[\x00-\x1f\x7f]/.test(runtime))) ||
19
+ (launchKind !== null && !["ota", "embedded", "unknown"].includes(launchKind)) ||
20
+ (search !== null && !/^[a-f0-9-]{1,36}$/.test(search))) throw new Error("Invalid filters");
21
+ return { p_days: days, p_platform: platform, p_channel: channel, p_runtime: runtime, p_offset: offset, p_launch_kind: launchKind, p_search: search };
22
+ }
23
+ export async function getDevicesReport(filters: ReturnType<typeof parseDeviceFilters>): Promise<DevicesReport> {
24
+ const { data, error } = await supabase.rpc("ota_devices_report_v2", filters);
25
+ if (error || !data?.[0]?.report) throw new Error(error?.message || "Missing report");
26
+ return data[0].report as DevicesReport;
27
+ }
@@ -0,0 +1,94 @@
1
+ import { beforeEach, expect, it, vi } from 'vitest';
2
+ type Row = Record<string, unknown>;
3
+ const db = vi.hoisted(() => ({ updates: [] as Row[], channels: [] as Row[], blocked: false }));
4
+ vi.mock('./distribution-control', () => ({ assertOtaDistributionAllowed: async () => undefined }));
5
+ vi.mock('./supabase.js', () => {
6
+ class Query {
7
+ filters: Array<(r: Row) => boolean> = [];
8
+ patch: Row | null = null;
9
+ limitCount = Infinity;
10
+ upsertRow: Row | null = null;
11
+ orderFields: string[] = [];
12
+ constructor(private table: string) {}
13
+ select() { return this; }
14
+ eq(k: string, v: unknown) { this.filters.push(r => r[k] === v); return this; }
15
+ neq(k: string, v: unknown) { this.filters.push(r => r[k] !== v); return this; }
16
+ not(k: string, op: string, v: unknown) { void op; this.filters.push(r => r[k] !== v); return this; }
17
+ order(k: string) { this.orderFields.push(k); return this; }
18
+ limit(n: number) { this.limitCount = n; return this; }
19
+ update(p: Row) { this.patch = p; return this; }
20
+ upsert(p: Row) { this.upsertRow = p; return this; }
21
+ async execute() {
22
+ const rows = this.table === 'ota_updates' ? db.updates : db.channels;
23
+ if (this.upsertRow) {
24
+ if (this.table === 'ota_update_channels' && db.blocked) return { data: [], error: { message: 'OTA_DISTRIBUTION_BLOCKED: INSERT guard runs before ON CONFLICT' } };
25
+ const row = rows.find(r => r.runtime_version === this.upsertRow!.runtime_version && r.channel === this.upsertRow!.channel && r.platform === this.upsertRow!.platform);
26
+ if (row) Object.assign(row, this.upsertRow); else rows.push(this.upsertRow);
27
+ return { data: [row || this.upsertRow], error: null };
28
+ }
29
+ let found = rows.filter(r => this.filters.every(f => f(r)));
30
+ if (this.orderFields.length) found = found.sort((a, b) => {
31
+ for (const field of this.orderFields) {
32
+ const compared = String(b[field]).localeCompare(String(a[field]));
33
+ if (compared) return compared;
34
+ }
35
+ return 0;
36
+ });
37
+ found = found.slice(0, this.limitCount);
38
+ if (this.patch) found.forEach(r => {
39
+ // Mirror the activation trigger here; its atomic/concurrent behavior is
40
+ // exercised against PostgreSQL by device-targeting-activation.mjs.
41
+ if (this.table === 'ota_updates' && this.patch!.is_active === true && r.audience_mode === 'all') {
42
+ rows.filter(other => other !== r && other.runtime_version === r.runtime_version && other.channel === r.channel && other.platform === r.platform)
43
+ .forEach(other => Object.assign(other, { is_active: false, disabled_at: 'now' }));
44
+ }
45
+ Object.assign(r, this.patch);
46
+ });
47
+ return { data: found, error: null };
48
+ }
49
+ async maybeSingle() { const r = await this.execute(); return { ...r, data: r.data[0] || null }; }
50
+ single() { return this.maybeSingle(); }
51
+ then(resolve: (r: unknown) => unknown, reject: (e: unknown) => unknown) { return this.execute().then(resolve, reject); }
52
+ }
53
+ return { supabase: { from: (table: string) => new Query(table) }, jsonb: (v: unknown) => v, SUPABASE_BUCKET: 'test' };
54
+ });
55
+ import { setUpdateDisabledByKey, promoteLatestByKey, rollbackToUpdateByKey } from './admin-updates';
56
+ const older = '11111111-1111-4111-8111-111111111111', newer = '22222222-2222-4222-8222-222222222222';
57
+ const scope = { runtime_version: 'r1', channel: 'test', platform: 'android' };
58
+ beforeEach(() => {
59
+ db.blocked = false;
60
+ db.updates = [
61
+ { ...scope, update_id: older, created_at: '2026-10-20', created_at_path: 'old', is_active: true, audience_mode: 'all' },
62
+ { ...scope, update_id: newer, created_at: '2026-10-21', created_at_path: 'new', is_active: false, audience_mode: 'devices' },
63
+ ];
64
+ db.channels = [{ ...scope, latest_update_id: newer, active_update_id: null, latest_created_at: '2026-10-21' }];
65
+ });
66
+ it('preserves public fallback on targeted activation and removes it on normal public activation', async () => {
67
+ await setUpdateDisabledByKey(newer, false);
68
+ expect(db.updates.map(r => r.is_active)).toEqual([true, true]);
69
+ db.updates[1].audience_mode = 'all';
70
+ await setUpdateDisabledByKey(newer, false);
71
+ expect(db.updates.map(r => r.is_active)).toEqual([false, true]);
72
+ });
73
+ it('promotes targeted latest out of rollback without disabling the public fallback', async () => {
74
+ db.channels[0].active_update_id = older;
75
+ await promoteLatestByKey(newer);
76
+ expect(db.updates.map(r => r.is_active)).toEqual([true, true]);
77
+ expect(db.channels[0].active_update_id).toBeNull();
78
+ });
79
+ it('keeps other audiences live when rolling back selected devices', async () => {
80
+ Object.assign(db.updates[0], { audience_mode: 'devices', is_active: false });
81
+ Object.assign(db.updates[1], { audience_mode: 'all', is_active: true });
82
+ await rollbackToUpdateByKey(older);
83
+ expect(db.updates.map(r => r.is_active)).toEqual([true, true]);
84
+ expect(db.channels[0].active_update_id).toBe(older);
85
+ });
86
+
87
+ it('repairs an existing channel with UPDATE when deactivating under the global stop', async () => {
88
+ db.updates[1].is_active = true;
89
+ db.blocked = true;
90
+ const result = await setUpdateDisabledByKey(newer, true);
91
+ expect(db.updates.map(r => r.is_active)).toEqual([true, false]);
92
+ expect(result.disabled).toBe(true);
93
+ expect(db.channels[0].latest_update_id).toBe(older);
94
+ });
@@ -9,86 +9,6 @@ import {
9
9
  import { getManifestAppVersion } from "../manifest/manifest-values";
10
10
  import { assertOtaDistributionAllowed } from "./distribution-control";
11
11
 
12
- let hasServedManifestLogTable: boolean | null = null;
13
-
14
- function isMissingServedManifestLogTableError(error: unknown): boolean {
15
- if (!error || typeof error !== "object") {
16
- return false;
17
- }
18
-
19
- const message =
20
- "message" in error && typeof error.message === "string"
21
- ? error.message.toLowerCase()
22
- : "";
23
-
24
- return (
25
- message.includes("ota_served_manifest_log") &&
26
- message.includes("does not exist")
27
- );
28
- }
29
-
30
- /**
31
- * Records served_manifest_id → update_id mapping so manifest controller can
32
- * resolve what real update a device is running from its currentUpdateId.
33
- * Fire-and-forget: errors are logged but never thrown.
34
- */
35
- function logServedManifestMapping({
36
- servedManifestId,
37
- updateId,
38
- runtimeVersion,
39
- channel,
40
- platform,
41
- reason,
42
- }: {
43
- servedManifestId: string;
44
- updateId: string;
45
- runtimeVersion: string;
46
- channel: string;
47
- platform: string;
48
- reason: string;
49
- }): void {
50
- if (hasServedManifestLogTable === false) {
51
- return;
52
- }
53
-
54
- supabase
55
- .from("ota_served_manifest_log")
56
- .upsert(
57
- {
58
- served_manifest_id: servedManifestId,
59
- update_id: updateId,
60
- runtime_version: runtimeVersion,
61
- channel,
62
- platform,
63
- reason,
64
- },
65
- { onConflict: "served_manifest_id" },
66
- )
67
- .then(({ error }) => {
68
- if (isMissingServedManifestLogTableError(error)) {
69
- hasServedManifestLogTable = false;
70
- return;
71
- }
72
-
73
- if (!error && hasServedManifestLogTable === null) {
74
- hasServedManifestLogTable = true;
75
- }
76
-
77
- if (
78
- error &&
79
- !error.message?.includes("duplicate") &&
80
- !error.message?.includes("unique")
81
- ) {
82
- console.warn(
83
- `[admin-updates] Failed to log served manifest mapping: ${error.message}`,
84
- );
85
- }
86
- })
87
- .catch(() => {
88
- /* ignore */
89
- });
90
- }
91
-
92
12
  type UpdateStatus = "active" | "disabled";
93
13
 
94
14
  type UpdateMetaState = {
@@ -110,6 +30,7 @@ export type OtaUpdateRow = {
110
30
  storage_bucket: string;
111
31
  storage_base_path: string;
112
32
  is_active: boolean;
33
+ audience_mode?: "all" | "devices";
113
34
  updated_at: string | null;
114
35
  disabled_at: string | null;
115
36
  assets_count: number;
@@ -159,6 +80,7 @@ export type UpdateRecord = {
159
80
  channelLatestPath: string;
160
81
  createdAt: string | null;
161
82
  status: UpdateStatus;
83
+ audienceMode: "all" | "devices";
162
84
  isLatest: boolean;
163
85
  isRollbackActive: boolean;
164
86
  autoDeliveryEnabled: boolean;
@@ -282,6 +204,7 @@ async function getNewestUpdateByScope(
282
204
  .eq("channel", scope.channel)
283
205
  .eq("platform", scope.platform)
284
206
  .order("created_at", { ascending: false })
207
+ .order("update_id", { ascending: false })
285
208
  .limit(1)
286
209
  .maybeSingle();
287
210
 
@@ -326,14 +249,14 @@ export function mapRowToRecord(
326
249
  channelLatestPath: `${row.runtime_version}/${row.platform}/channels/${row.channel}/latest.json`,
327
250
  createdAt: row.created_at,
328
251
  status,
252
+ audienceMode: row.audience_mode === "devices" ? "devices" : "all",
329
253
  isLatest,
330
254
  isRollbackActive,
331
255
  autoDeliveryEnabled: !rollbackActiveAtScope,
332
256
  isIgnoredByRollback,
333
257
  launchAssetPath: row.launch_asset_path,
334
258
  assetsCount: row.assets_count,
335
- deliveryMode:
336
- row.delivery_mode === "background" ? "background" : "manual",
259
+ deliveryMode: row.delivery_mode === "background" ? "background" : "manual",
337
260
  hasGuard:
338
261
  typeof row.guard_action === "string" && row.guard_action.length > 0,
339
262
  policyVersion:
@@ -382,9 +305,7 @@ function rowToPolicy(row: OtaUpdateRow): UpdatePolicyRecord {
382
305
  guard: row.guard_action
383
306
  ? {
384
307
  action: row.guard_action,
385
- ...(row.guard_payload !== null
386
- ? { payload: row.guard_payload }
387
- : {}),
308
+ ...(row.guard_payload !== null ? { payload: row.guard_payload } : {}),
388
309
  }
389
310
  : null,
390
311
  });
@@ -579,6 +500,22 @@ async function upsertChannelRow(
579
500
  scope: Scope,
580
501
  payload: Partial<OtaChannelRow>,
581
502
  ): Promise<OtaChannelRow> {
503
+ // INSERT ... ON CONFLICT runs INSERT guards before checking the conflict.
504
+ // Update an existing scope directly so incident deactivation cleanup can be
505
+ // validated against OLD pointers while the global switch is blocked.
506
+ const existing = await supabase
507
+ .from("ota_update_channels")
508
+ .update(payload)
509
+ .eq("runtime_version", scope.runtimeVersion)
510
+ .eq("channel", scope.channel)
511
+ .eq("platform", scope.platform)
512
+ .select("*")
513
+ .maybeSingle();
514
+ if (existing.error) {
515
+ throw new Error(`Failed to update ota_update_channels row: ${existing.error.message}`);
516
+ }
517
+ if (existing.data) return existing.data as OtaChannelRow;
518
+
582
519
  const { data, error } = await supabase
583
520
  .from("ota_update_channels")
584
521
  .upsert(
@@ -669,6 +606,7 @@ async function getUpdateRowsByScope(scope: Scope): Promise<OtaUpdateRow[]> {
669
606
  .eq("channel", scope.channel)
670
607
  .eq("platform", scope.platform)
671
608
  .order("created_at", { ascending: false })
609
+ .order("update_id", { ascending: false })
672
610
  .execute();
673
611
 
674
612
  if (error) {
@@ -804,6 +742,7 @@ export async function getUpdatesPage(options: ListOptions) {
804
742
  .from("ota_updates")
805
743
  .select("*")
806
744
  .order("created_at", { ascending: false })
745
+ .order("update_id", { ascending: false })
807
746
  .execute();
808
747
 
809
748
  if (error) {
@@ -909,6 +848,11 @@ export async function deleteUpdateByKey(
909
848
  const row = await getUpdateRowById(updateId);
910
849
  const scope = makeScopeFromRow(row);
911
850
 
851
+ // Repair serving pointers before FK cleanup erases the retired target. This
852
+ // also keeps deletion available during a global stop with a public fallback,
853
+ // and stops new manifests referencing assets that are about to be removed.
854
+ await setUpdateDisabledByKey(updateId, true);
855
+
912
856
  let removedFiles = 0;
913
857
  const bucket = row.storage_bucket || SUPABASE_BUCKET;
914
858
  const basePath = toPosixPath(row.storage_base_path || "");
@@ -1138,25 +1082,7 @@ export async function rollbackToUpdateByKey(
1138
1082
  );
1139
1083
  }
1140
1084
 
1141
- const { error: deactivateOthersError } = await supabase
1142
- .from("ota_updates")
1143
- .update({
1144
- is_active: false,
1145
- updated_at: now,
1146
- disabled_at: now,
1147
- })
1148
- .eq("runtime_version", scope.runtimeVersion)
1149
- .eq("channel", scope.channel)
1150
- .eq("platform", scope.platform)
1151
- .neq("update_id", updateId)
1152
- .eq("is_active", true)
1153
- .execute();
1154
-
1155
- if (deactivateOthersError) {
1156
- throw new Error(
1157
- `Failed to deactivate other active updates in scope: ${deactivateOthersError.message}`,
1158
- );
1159
- }
1085
+ // The database atomically applies audience-aware peer deactivation.
1160
1086
 
1161
1087
  const { error: activationError } = await supabase
1162
1088
  .from("ota_updates")
@@ -1203,19 +1129,6 @@ export async function rollbackToUpdateByKey(
1203
1129
  active_changed_at: now,
1204
1130
  });
1205
1131
 
1206
- // Pre-populate the mapping so the first device request after rollback
1207
- // can immediately resolve served_manifest_id → update_id without a cold miss.
1208
- if (channelRow.served_manifest_id) {
1209
- logServedManifestMapping({
1210
- servedManifestId: channelRow.served_manifest_id,
1211
- updateId: refreshed.update_id,
1212
- runtimeVersion: scope.runtimeVersion,
1213
- channel: scope.channel,
1214
- platform: scope.platform,
1215
- reason: "rollback",
1216
- });
1217
- }
1218
-
1219
1132
  return {
1220
1133
  ...buildLatestPayload(refreshed, options?.reason || "rollback"),
1221
1134
  activeChangedAt: channelRow.active_changed_at,
@@ -1251,25 +1164,7 @@ export async function promoteLatestByKey(key: string) {
1251
1164
 
1252
1165
  const promoteNow = new Date().toISOString();
1253
1166
 
1254
- const { error: deactivateOthersError } = await supabase
1255
- .from("ota_updates")
1256
- .update({
1257
- is_active: false,
1258
- updated_at: promoteNow,
1259
- disabled_at: promoteNow,
1260
- })
1261
- .eq("runtime_version", scope.runtimeVersion)
1262
- .eq("channel", scope.channel)
1263
- .eq("platform", scope.platform)
1264
- .neq("update_id", latestUpdateId)
1265
- .eq("is_active", true)
1266
- .execute();
1267
-
1268
- if (deactivateOthersError) {
1269
- throw new Error(
1270
- `Failed to deactivate active updates during promote: ${deactivateOthersError.message}`,
1271
- );
1272
- }
1167
+ // Keep audience selection and peer deactivation in the activation statement.
1273
1168
 
1274
1169
  const { error: activateLatestError } = await supabase
1275
1170
  .from("ota_updates")
@@ -1297,19 +1192,6 @@ export async function promoteLatestByKey(key: string) {
1297
1192
  active_changed_at: promoteNow,
1298
1193
  });
1299
1194
 
1300
- // Pre-populate the mapping so the first device request after promote
1301
- // can immediately resolve served_manifest_id → update_id without a cold miss.
1302
- if (updatedChannel.served_manifest_id && updatedChannel.latest_update_id) {
1303
- logServedManifestMapping({
1304
- servedManifestId: updatedChannel.served_manifest_id,
1305
- updateId: updatedChannel.latest_update_id,
1306
- runtimeVersion: scope.runtimeVersion,
1307
- channel: scope.channel,
1308
- platform: scope.platform,
1309
- reason: "promote",
1310
- });
1311
- }
1312
-
1313
1195
  return {
1314
1196
  promoted: true,
1315
1197
  latestUpdateId: updatedChannel.latest_update_id,
@@ -1347,25 +1229,7 @@ export async function setUpdateDisabledByKey(key: string, disabled: boolean) {
1347
1229
  );
1348
1230
  }
1349
1231
 
1350
- const { error: deactivateOthersError } = await supabase
1351
- .from("ota_updates")
1352
- .update({
1353
- is_active: false,
1354
- updated_at: now,
1355
- disabled_at: now,
1356
- })
1357
- .eq("runtime_version", scope.runtimeVersion)
1358
- .eq("channel", scope.channel)
1359
- .eq("platform", scope.platform)
1360
- .neq("update_id", updateId)
1361
- .eq("is_active", true)
1362
- .execute();
1363
-
1364
- if (deactivateOthersError) {
1365
- throw new Error(
1366
- `Failed to deactivate other active updates in scope: ${deactivateOthersError.message}`,
1367
- );
1368
- }
1232
+ // Peer deactivation is performed atomically by the database trigger.
1369
1233
  }
1370
1234
 
1371
1235
  const { error } = await supabase