create-expo-updates-server 0.1.3 → 0.1.5

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (84) hide show
  1. package/dist/template/.env.docker.example +1 -0
  2. package/dist/template/.env.example +2 -0
  3. package/dist/template/README.md +16 -8
  4. package/dist/template/app/api/admin/distribution-control/route.test.ts +153 -0
  5. package/dist/template/app/api/admin/distribution-control/route.ts +111 -0
  6. package/dist/template/app/api/admin/embedded-updates/route.test.ts +36 -1
  7. package/dist/template/app/api/admin/guard-actions/[id]/route.test.ts +60 -0
  8. package/dist/template/app/api/admin/guard-actions/[id]/route.ts +32 -0
  9. package/dist/template/app/api/admin/guard-actions/route.test.ts +123 -0
  10. package/dist/template/app/api/admin/guard-actions/route.ts +66 -0
  11. package/dist/template/app/api/admin/updates/[encodedKey]/deactivate/route.ts +4 -1
  12. package/dist/template/app/api/admin/updates/[encodedKey]/policy/route.test.ts +171 -0
  13. package/dist/template/app/api/admin/updates/[encodedKey]/policy/route.ts +75 -0
  14. package/dist/template/app/api/admin/updates/[encodedKey]/promote/route.ts +4 -1
  15. package/dist/template/app/api/admin/updates/[encodedKey]/rollback/route.ts +4 -1
  16. package/dist/template/app/api/admin/updates/[encodedKey]/route.ts +4 -1
  17. package/dist/template/app/api/admin/updates/route.test.ts +29 -1
  18. package/dist/template/app/updates/[encodedKey]/page.tsx +74 -6
  19. package/dist/template/app/updates/embedded/page.tsx +6 -2
  20. package/dist/template/app/updates/page.tsx +28 -3
  21. package/dist/template/docs/expo-app-setup.md +14 -3
  22. package/dist/template/docs/getting-started.md +13 -7
  23. package/dist/template/docs/getting-started.ru.md +15 -7
  24. package/dist/template/docs/migrations/2026-09-01-app-version-columns.sql +23 -0
  25. package/dist/template/docs/migrations/2026-09-01-ota-update-policy.sql +108 -0
  26. package/dist/template/docs/migrations/2026-09-01-p1-guard-actions.sql +19 -0
  27. package/dist/template/docs/migrations/2026-09-01-p2-simplify-ota-guard-policy.sql +69 -0
  28. package/dist/template/docs/migrations/2026-09-01-policy-publication-correction.sql +44 -0
  29. package/dist/template/docs/migrations/2026-09-02-ota-distribution-control.sql +377 -0
  30. package/dist/template/docs/migrations/schema.sql +561 -2
  31. package/dist/template/docs/operations-guide.md +52 -1
  32. package/dist/template/docs/ota-emergency-recovery.md +22 -0
  33. package/dist/template/docs/ota-update-policy.md +89 -0
  34. package/dist/template/docs/supabase-setup.md +2 -1
  35. package/dist/template/package-lock.json +2 -2
  36. package/dist/template/package.json +1 -1
  37. package/dist/template/scripts/configure-expo-app.mjs +6 -0
  38. package/dist/template/scripts/lib/embedded-update-registrar.test.ts +383 -3
  39. package/dist/template/scripts/lib/expo-app-configurator.mjs +165 -9
  40. package/dist/template/scripts/lib/expo-app-configurator.test.ts +658 -9
  41. package/dist/template/src/client/admin-api.ts +80 -1
  42. package/dist/template/src/client/admin-types.ts +52 -2
  43. package/dist/template/src/client/distribution-control.tsx +231 -0
  44. package/dist/template/src/client/guard-action-combobox.test.ts +26 -0
  45. package/dist/template/src/client/guard-action-combobox.tsx +267 -0
  46. package/dist/template/src/client/guard-action-options.test.ts +62 -0
  47. package/dist/template/src/client/guard-action-options.ts +70 -0
  48. package/dist/template/src/client/update-policy-editor.test.ts +36 -0
  49. package/dist/template/src/client/update-policy-editor.tsx +436 -0
  50. package/dist/template/src/server/controllers/assets.test.ts +87 -0
  51. package/dist/template/src/server/controllers/assets.ts +26 -0
  52. package/dist/template/src/server/controllers/manifest.test.ts +413 -2
  53. package/dist/template/src/server/controllers/manifest.ts +103 -38
  54. package/dist/template/src/server/lib/admin-distribution-guard.test.ts +61 -0
  55. package/dist/template/src/server/lib/admin-embedded-updates.test.ts +57 -0
  56. package/dist/template/src/server/lib/admin-embedded-updates.ts +42 -25
  57. package/dist/template/src/server/lib/admin-update-policy.test.ts +176 -0
  58. package/dist/template/src/server/lib/admin-updates.test.ts +133 -0
  59. package/dist/template/src/server/lib/admin-updates.ts +174 -9
  60. package/dist/template/src/server/lib/distribution-control-migration.test.ts +94 -0
  61. package/dist/template/src/server/lib/distribution-control.test.ts +160 -0
  62. package/dist/template/src/server/lib/distribution-control.ts +250 -0
  63. package/dist/template/src/server/lib/guard-actions-migration.test.ts +56 -0
  64. package/dist/template/src/server/lib/guard-actions.test.ts +142 -0
  65. package/dist/template/src/server/lib/guard-actions.ts +106 -0
  66. package/dist/template/src/server/lib/ota-policy-migrations.test.ts +64 -0
  67. package/dist/template/src/server/lib/simple-policy-migration.test.ts +97 -0
  68. package/dist/template/src/server/lib/supabase.js +95 -8
  69. package/dist/template/src/server/lib/supabase.test.ts +194 -0
  70. package/dist/template/src/server/lib/update-policy.test.ts +98 -0
  71. package/dist/template/src/server/lib/update-policy.ts +171 -0
  72. package/dist/template/src/server/manifest/manifest-repository.ts +10 -1
  73. package/dist/template/src/server/manifest/manifest-response.ts +0 -16
  74. package/dist/template/src/server/manifest/manifest-values.test.ts +54 -0
  75. package/dist/template/src/server/manifest/manifest-values.ts +145 -0
  76. package/dist/template/templates/expo-app/ci_scripts/ci_post_xcodebuild.sh +23 -1
  77. package/dist/template/templates/expo-app/plugins/with-ota-embedded-registration.js +13 -4
  78. package/dist/template/templates/expo-app/scripts/ota-register-embedded/index.mjs +53 -7
  79. package/dist/template/templates/expo-app/scripts/ota-register-embedded/register-ios.sh +87 -0
  80. package/dist/template/tsconfig.json +4 -1
  81. package/dist/template-manifest.json +283 -88
  82. package/package.json +1 -1
  83. package/dist/template/templates/expo-app/ci_scripts/register-embedded-update.sh +0 -36
  84. /package/dist/template/templates/expo-app/scripts/ota-register-embedded/{android-register-embedded-update.sh → register-android.sh} +0 -0
@@ -0,0 +1,250 @@
1
+ import { jsonb, supabase } from "./supabase.js";
2
+
3
+ export const DISTRIBUTION_REASON_MAX_LENGTH = 500;
4
+
5
+ export type DistributionControlPrincipal = {
6
+ type: "session" | "access-token" | "system";
7
+ id: string;
8
+ label: string;
9
+ role?: string;
10
+ };
11
+
12
+ export type DistributionControlState = {
13
+ blocked: boolean;
14
+ version: number;
15
+ reason: string | null;
16
+ changedAt: string;
17
+ changedBy: DistributionControlPrincipal;
18
+ };
19
+
20
+ export class DistributionControlValidationError extends Error {
21
+ readonly status = 400;
22
+
23
+ constructor(message: string) {
24
+ super(message);
25
+ this.name = "DistributionControlValidationError";
26
+ }
27
+ }
28
+
29
+ export class DistributionControlConflictError extends Error {
30
+ readonly status = 409;
31
+
32
+ constructor() {
33
+ super("Distribution control version conflict. Refresh and try again.");
34
+ this.name = "DistributionControlConflictError";
35
+ }
36
+ }
37
+
38
+ export class OtaDistributionBlockedError extends Error {
39
+ readonly status = 409;
40
+
41
+ constructor() {
42
+ super(
43
+ "OTA distribution is globally blocked. Disable the emergency switch before starting distribution.",
44
+ );
45
+ this.name = "OtaDistributionBlockedError";
46
+ }
47
+ }
48
+
49
+ function isRecord(value: unknown): value is Record<string, unknown> {
50
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
51
+ }
52
+
53
+ function requiredString(
54
+ value: unknown,
55
+ field: string,
56
+ maxLength: number,
57
+ ): string {
58
+ if (typeof value !== "string") {
59
+ throw new Error(`Invalid OTA distribution control ${field}.`);
60
+ }
61
+ const normalized = value.trim();
62
+ if (!normalized || normalized.length > maxLength) {
63
+ throw new Error(`Invalid OTA distribution control ${field}.`);
64
+ }
65
+ return normalized;
66
+ }
67
+
68
+ function parsePrincipal(value: unknown): DistributionControlPrincipal {
69
+ if (!isRecord(value)) {
70
+ throw new Error("Invalid OTA distribution control changed_by.");
71
+ }
72
+
73
+ const type = value.type;
74
+ if (
75
+ type !== "session" &&
76
+ type !== "access-token" &&
77
+ type !== "system"
78
+ ) {
79
+ throw new Error("Invalid OTA distribution control principal type.");
80
+ }
81
+
82
+ const role =
83
+ typeof value.role === "string" && value.role.trim()
84
+ ? value.role.trim()
85
+ : undefined;
86
+
87
+ return {
88
+ type,
89
+ id: requiredString(value.id, "principal id", 200),
90
+ label: requiredString(value.label, "principal label", 200),
91
+ ...(role ? { role } : {}),
92
+ };
93
+ }
94
+
95
+ function parseStateRow(value: unknown): DistributionControlState {
96
+ if (!isRecord(value)) {
97
+ throw new Error("OTA distribution control state is missing.");
98
+ }
99
+
100
+ const version = Number(value.version);
101
+ if (
102
+ typeof value.blocked !== "boolean" ||
103
+ !Number.isSafeInteger(version) ||
104
+ version < 1
105
+ ) {
106
+ throw new Error("Invalid OTA distribution control state.");
107
+ }
108
+
109
+ const changedAt = requiredString(value.changed_at, "changed_at", 100);
110
+ if (Number.isNaN(Date.parse(changedAt))) {
111
+ throw new Error("Invalid OTA distribution control changed_at.");
112
+ }
113
+
114
+ const reason =
115
+ value.reason === null
116
+ ? null
117
+ : requiredString(
118
+ value.reason,
119
+ "reason",
120
+ DISTRIBUTION_REASON_MAX_LENGTH,
121
+ );
122
+ if (value.blocked && !reason) {
123
+ throw new Error("Blocked OTA distribution state has no reason.");
124
+ }
125
+ if (!value.blocked && reason !== null) {
126
+ throw new Error("Active OTA distribution state must not have a reason.");
127
+ }
128
+
129
+ return {
130
+ blocked: value.blocked,
131
+ version,
132
+ reason,
133
+ changedAt,
134
+ changedBy: parsePrincipal(value.changed_by),
135
+ };
136
+ }
137
+
138
+ function validateReason(blocked: boolean, reason: unknown): string | null {
139
+ if (!blocked) {
140
+ return null;
141
+ }
142
+ if (typeof reason !== "string") {
143
+ throw new DistributionControlValidationError(
144
+ "reason is required when OTA distribution is blocked.",
145
+ );
146
+ }
147
+ const normalized = reason.trim();
148
+ if (!normalized) {
149
+ throw new DistributionControlValidationError(
150
+ "reason is required when OTA distribution is blocked.",
151
+ );
152
+ }
153
+ if (
154
+ Array.from(normalized).length > DISTRIBUTION_REASON_MAX_LENGTH ||
155
+ /[\u0000-\u001f\u007f]/u.test(normalized)
156
+ ) {
157
+ throw new DistributionControlValidationError(
158
+ `reason must contain at most ${DISTRIBUTION_REASON_MAX_LENGTH} characters and no control characters.`,
159
+ );
160
+ }
161
+ return normalized;
162
+ }
163
+
164
+ function validatePrincipal(
165
+ principal: DistributionControlPrincipal,
166
+ ): DistributionControlPrincipal {
167
+ try {
168
+ return parsePrincipal(principal);
169
+ } catch {
170
+ throw new DistributionControlValidationError(
171
+ "principal metadata is invalid.",
172
+ );
173
+ }
174
+ }
175
+
176
+ export async function getDistributionControlState(): Promise<DistributionControlState> {
177
+ const { data, error } = await supabase
178
+ .from("ota_distribution_control")
179
+ .select("blocked,version,reason,changed_at,changed_by")
180
+ .eq("singleton_id", 1)
181
+ .maybeSingle();
182
+
183
+ if (error) {
184
+ throw new Error(
185
+ `Failed to read OTA distribution control: ${error.message}`,
186
+ );
187
+ }
188
+ return parseStateRow(data);
189
+ }
190
+
191
+ export async function isOtaDistributionBlocked(): Promise<boolean> {
192
+ return (await getDistributionControlState()).blocked;
193
+ }
194
+
195
+ export async function setDistributionControlState(input: {
196
+ blocked: unknown;
197
+ reason?: unknown;
198
+ expectedVersion: unknown;
199
+ principal: DistributionControlPrincipal;
200
+ }): Promise<DistributionControlState> {
201
+ if (typeof input.blocked !== "boolean") {
202
+ throw new DistributionControlValidationError(
203
+ "blocked must be a boolean.",
204
+ );
205
+ }
206
+ if (
207
+ typeof input.expectedVersion !== "number" ||
208
+ !Number.isSafeInteger(input.expectedVersion) ||
209
+ input.expectedVersion < 1
210
+ ) {
211
+ throw new DistributionControlValidationError(
212
+ "expectedVersion must be a positive integer.",
213
+ );
214
+ }
215
+
216
+ const reason = validateReason(input.blocked, input.reason);
217
+ const principal = validatePrincipal(input.principal);
218
+ const { data, error } = await supabase.rpc(
219
+ "set_ota_distribution_control",
220
+ {
221
+ p_blocked: input.blocked,
222
+ p_reason: reason,
223
+ p_expected_version: input.expectedVersion,
224
+ p_changed_by: jsonb(principal),
225
+ },
226
+ );
227
+
228
+ if (error) {
229
+ const message = String(error.message || "");
230
+ if (
231
+ message.toLowerCase().includes("version conflict") ||
232
+ message.includes("40001")
233
+ ) {
234
+ throw new DistributionControlConflictError();
235
+ }
236
+ throw new Error(`Failed to update OTA distribution control: ${message}`);
237
+ }
238
+
239
+ const row = Array.isArray(data) ? data[0] : data;
240
+ if (!row) {
241
+ throw new Error("OTA distribution control update returned no state.");
242
+ }
243
+ return parseStateRow(row);
244
+ }
245
+
246
+ export async function assertOtaDistributionAllowed(): Promise<void> {
247
+ if (await isOtaDistributionBlocked()) {
248
+ throw new OtaDistributionBlockedError();
249
+ }
250
+ }
@@ -0,0 +1,56 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { describe, expect, it } from "vitest";
3
+
4
+ const migration = readFileSync(
5
+ new URL(
6
+ "../../../docs/migrations/2026-09-01-p1-guard-actions.sql",
7
+ import.meta.url,
8
+ ),
9
+ "utf8",
10
+ );
11
+ const schema = readFileSync(
12
+ new URL("../../../docs/migrations/schema.sql", import.meta.url),
13
+ "utf8",
14
+ );
15
+
16
+ describe("guard action catalog migration", () => {
17
+ it.each([
18
+ ["migration", migration],
19
+ ["canonical schema", schema],
20
+ ])("defines the portable validated catalog in the %s", (_name, sql) => {
21
+ expect(sql).toMatch(
22
+ /create table if not exists public\.ota_guard_actions/i,
23
+ );
24
+ expect(sql).toMatch(/id uuid primary key default gen_random_uuid\(\)/i);
25
+ expect(sql).toMatch(/action_key = btrim\(action_key\)/i);
26
+ expect(sql).toMatch(/char_length\(action_key\) between 1 and 100/i);
27
+ expect(sql).toMatch(/action_key !~ '\[\[:cntrl:\]\]'/i);
28
+ expect(sql).toMatch(
29
+ /create unique index if not exists idx_ota_guard_actions_action_key/i,
30
+ );
31
+ expect(sql).toMatch(
32
+ /values \('ota-force-store-update'\)\s+on conflict \(action_key\) do nothing/i,
33
+ );
34
+ });
35
+
36
+ it("does not couple catalog entries to policy rules", () => {
37
+ const table = migration.slice(
38
+ migration.indexOf("create table"),
39
+ migration.indexOf("create unique index"),
40
+ );
41
+ expect(table).not.toMatch(/foreign key|references/i);
42
+ });
43
+
44
+ it("keeps the migration and canonical schema definitions identical", () => {
45
+ const catalogSql = (sql: string) => {
46
+ const start = sql.indexOf(
47
+ "create table if not exists public.ota_guard_actions",
48
+ );
49
+ const endMarker = "on conflict (action_key) do nothing;";
50
+ const end = sql.indexOf(endMarker, start) + endMarker.length;
51
+ return sql.slice(start, end);
52
+ };
53
+
54
+ expect(catalogSql(schema)).toBe(catalogSql(migration));
55
+ });
56
+ });
@@ -0,0 +1,142 @@
1
+ import { beforeEach, describe, expect, it, vi } from "vitest";
2
+
3
+ type Row = {
4
+ id: string;
5
+ action_key: string;
6
+ created_at: string;
7
+ };
8
+
9
+ const database = vi.hoisted(() => ({
10
+ rows: new Map<string, Row>(),
11
+ nextId: 1,
12
+ }));
13
+
14
+ vi.mock("./supabase.js", () => {
15
+ class Query {
16
+ private operation = "select";
17
+ private actionKey = "";
18
+ private id = "";
19
+
20
+ select() {
21
+ return this;
22
+ }
23
+
24
+ order() {
25
+ return this;
26
+ }
27
+
28
+ upsert(payload: { action_key: string }) {
29
+ this.operation = "upsert";
30
+ this.actionKey = payload.action_key;
31
+ if (!database.rows.has(this.actionKey)) {
32
+ const suffix = String(database.nextId++).padStart(12, "0");
33
+ database.rows.set(this.actionKey, {
34
+ id: `00000000-0000-4000-8000-${suffix}`,
35
+ action_key: this.actionKey,
36
+ created_at: "2026-09-01T00:00:00.000Z",
37
+ });
38
+ }
39
+ return this;
40
+ }
41
+
42
+ delete() {
43
+ this.operation = "delete";
44
+ return this;
45
+ }
46
+
47
+ eq(_column: string, value: string) {
48
+ this.id = value;
49
+ return this;
50
+ }
51
+
52
+ single() {
53
+ return Promise.resolve({
54
+ data: database.rows.get(this.actionKey),
55
+ error: null,
56
+ });
57
+ }
58
+
59
+ execute() {
60
+ if (this.operation === "delete") {
61
+ for (const [key, row] of database.rows) {
62
+ if (row.id === this.id) database.rows.delete(key);
63
+ }
64
+ return Promise.resolve({ data: null, error: null });
65
+ }
66
+ return Promise.resolve({
67
+ data: [...database.rows.values()].sort((left, right) =>
68
+ left.action_key.localeCompare(right.action_key),
69
+ ),
70
+ error: null,
71
+ });
72
+ }
73
+ }
74
+
75
+ return {
76
+ supabase: {
77
+ from(table: string) {
78
+ if (table !== "ota_guard_actions") {
79
+ throw new Error(`Unexpected table ${table}`);
80
+ }
81
+ return new Query();
82
+ },
83
+ },
84
+ };
85
+ });
86
+
87
+ describe("guard action catalog", () => {
88
+ beforeEach(() => {
89
+ database.rows.clear();
90
+ database.nextId = 1;
91
+ });
92
+
93
+ it("trims valid values and rejects length and control characters", async () => {
94
+ const { GuardActionValidationError, parseGuardActionInput } =
95
+ await import("./guard-actions");
96
+
97
+ expect(parseGuardActionInput({ actionKey: " store-update " })).toBe(
98
+ "store-update",
99
+ );
100
+ expect(() => parseGuardActionInput({ actionKey: "" })).toThrow(
101
+ GuardActionValidationError,
102
+ );
103
+ expect(() =>
104
+ parseGuardActionInput({ actionKey: "bad\nvalue" }),
105
+ ).toThrow(/control characters/);
106
+ expect(() =>
107
+ parseGuardActionInput({ actionKey: "x".repeat(101) }),
108
+ ).toThrow(/between 1 and 100/);
109
+ });
110
+
111
+ it("creates or gets one row across concurrent duplicate creates", async () => {
112
+ const { createGuardAction, listGuardActions } =
113
+ await import("./guard-actions");
114
+ const [first, second] = await Promise.all([
115
+ createGuardAction({ actionKey: "same-action" }),
116
+ createGuardAction({ actionKey: " same-action " }),
117
+ ]);
118
+
119
+ expect(first).toEqual(second);
120
+ await expect(listGuardActions()).resolves.toEqual([first]);
121
+ });
122
+
123
+ it("sorts results and deletes a UUID idempotently", async () => {
124
+ const { createGuardAction, deleteGuardAction, listGuardActions } =
125
+ await import("./guard-actions");
126
+ await createGuardAction({ actionKey: "zeta" });
127
+ const alpha = await createGuardAction({ actionKey: "alpha" });
128
+
129
+ expect((await listGuardActions()).map((item) => item.actionKey)).toEqual([
130
+ "alpha",
131
+ "zeta",
132
+ ]);
133
+ await deleteGuardAction(alpha.id);
134
+ await deleteGuardAction(alpha.id);
135
+ expect((await listGuardActions()).map((item) => item.actionKey)).toEqual([
136
+ "zeta",
137
+ ]);
138
+ await expect(deleteGuardAction("not-a-uuid")).rejects.toThrow(
139
+ /id must be a UUID/,
140
+ );
141
+ });
142
+ });
@@ -0,0 +1,106 @@
1
+ import { supabase } from "./supabase.js";
2
+
3
+ export type GuardAction = {
4
+ id: string;
5
+ actionKey: string;
6
+ createdAt: string;
7
+ };
8
+
9
+ type GuardActionRow = {
10
+ id: string;
11
+ action_key: string;
12
+ created_at: string;
13
+ };
14
+
15
+ const CONTROL_CHARACTER_PATTERN = /[\u0000-\u001f\u007f-\u009f]/;
16
+ const UUID_PATTERN =
17
+ /^[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/i;
18
+
19
+ export class GuardActionValidationError extends Error {}
20
+
21
+ export function parseGuardActionInput(value: unknown): string {
22
+ if (!value || typeof value !== "object" || Array.isArray(value)) {
23
+ throw new GuardActionValidationError(
24
+ "Guard action must be a JSON object",
25
+ );
26
+ }
27
+
28
+ const actionKey = (value as Record<string, unknown>).actionKey;
29
+ if (typeof actionKey !== "string") {
30
+ throw new GuardActionValidationError("actionKey must be a string");
31
+ }
32
+
33
+ const normalized = actionKey.trim();
34
+ if (normalized.length < 1 || normalized.length > 100) {
35
+ throw new GuardActionValidationError(
36
+ "actionKey must contain between 1 and 100 characters",
37
+ );
38
+ }
39
+ if (CONTROL_CHARACTER_PATTERN.test(normalized)) {
40
+ throw new GuardActionValidationError(
41
+ "actionKey must not contain control characters",
42
+ );
43
+ }
44
+
45
+ return normalized;
46
+ }
47
+
48
+ export function parseGuardActionId(value: string): string {
49
+ if (!UUID_PATTERN.test(value)) {
50
+ throw new GuardActionValidationError("id must be a UUID");
51
+ }
52
+ return value.toLowerCase();
53
+ }
54
+
55
+ function mapRow(row: GuardActionRow): GuardAction {
56
+ return {
57
+ id: row.id,
58
+ actionKey: row.action_key,
59
+ createdAt: row.created_at,
60
+ };
61
+ }
62
+
63
+ export async function listGuardActions(): Promise<GuardAction[]> {
64
+ const { data, error } = await supabase
65
+ .from("ota_guard_actions")
66
+ .select("id,action_key,created_at")
67
+ .order("action_key", { ascending: true })
68
+ .execute();
69
+
70
+ if (error) {
71
+ throw new Error(`Failed to list guard actions: ${error.message}`);
72
+ }
73
+
74
+ return ((data || []) as GuardActionRow[]).map(mapRow);
75
+ }
76
+
77
+ export async function createGuardAction(value: unknown): Promise<GuardAction> {
78
+ const actionKey = parseGuardActionInput(value);
79
+ const { data, error } = await supabase
80
+ .from("ota_guard_actions")
81
+ .upsert(
82
+ { action_key: actionKey },
83
+ { onConflict: "action_key" },
84
+ )
85
+ .select("id,action_key,created_at")
86
+ .single();
87
+
88
+ if (error || !data) {
89
+ throw new Error(`Failed to create guard action: ${error?.message}`);
90
+ }
91
+
92
+ return mapRow(data as GuardActionRow);
93
+ }
94
+
95
+ export async function deleteGuardAction(id: string): Promise<void> {
96
+ const normalizedId = parseGuardActionId(id);
97
+ const { error } = await supabase
98
+ .from("ota_guard_actions")
99
+ .delete()
100
+ .eq("id", normalizedId)
101
+ .execute();
102
+
103
+ if (error) {
104
+ throw new Error(`Failed to delete guard action: ${error.message}`);
105
+ }
106
+ }
@@ -0,0 +1,64 @@
1
+ import { readFileSync } from "node:fs";
2
+ import { describe, expect, it } from "vitest";
3
+
4
+ const correctiveMigration = readFileSync(
5
+ new URL(
6
+ "../../../docs/migrations/2026-09-01-policy-publication-correction.sql",
7
+ import.meta.url,
8
+ ),
9
+ "utf8",
10
+ );
11
+ const canonicalSchema = readFileSync(
12
+ new URL("../../../docs/migrations/schema.sql", import.meta.url),
13
+ "utf8",
14
+ );
15
+
16
+ function correctiveUpdate(sql: string): string {
17
+ const start = sql.indexOf("update public.ota_updates u\n");
18
+ const end = sql.indexOf(
19
+ "\n\ncreate trigger trg_ota_updates_lock_published_policy",
20
+ start,
21
+ );
22
+
23
+ expect(start).toBeGreaterThanOrEqual(0);
24
+ expect(end).toBeGreaterThan(start);
25
+ return sql.slice(start, end);
26
+ }
27
+
28
+ describe("OTA policy corrective migration", () => {
29
+ it("does not treat the latest upload pointer as publication evidence", () => {
30
+ expect(correctiveMigration).not.toMatch(
31
+ /where\s+c\.latest_update_id\s*=\s*u\.update_id/i,
32
+ );
33
+ });
34
+
35
+ it("preserves drafts with actual publication evidence", () => {
36
+ expect(correctiveMigration).toMatch(
37
+ /where\s+sml\.update_id\s*=\s*u\.update_id/i,
38
+ );
39
+ expect(correctiveMigration).toMatch(
40
+ /where\s+c\.active_update_id\s*=\s*u\.update_id/i,
41
+ );
42
+ });
43
+
44
+ it("requires simple Guard defaults before correcting a draft", () => {
45
+ expect(correctiveMigration).toMatch(/u\.guard_action is null/i);
46
+ expect(correctiveMigration).toMatch(/u\.guard_payload is null/i);
47
+ expect(correctiveMigration).not.toMatch(/guard_rules/i);
48
+ });
49
+
50
+ it("applies the same correction in schema.sql after the served log exists", () => {
51
+ const servedLogPosition = canonicalSchema.indexOf(
52
+ "create table if not exists public.ota_served_manifest_log",
53
+ );
54
+ const correctionPosition = canonicalSchema.indexOf(
55
+ "update public.ota_updates u\n",
56
+ );
57
+
58
+ expect(servedLogPosition).toBeGreaterThanOrEqual(0);
59
+ expect(correctionPosition).toBeGreaterThan(servedLogPosition);
60
+ expect(correctiveUpdate(canonicalSchema)).toBe(
61
+ correctiveUpdate(correctiveMigration),
62
+ );
63
+ });
64
+ });