create-expo-updates-server 0.1.4 → 0.1.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (67) hide show
  1. package/dist/template/.env.docker.example +1 -0
  2. package/dist/template/.env.example +2 -0
  3. package/dist/template/README.md +4 -1
  4. package/dist/template/app/api/admin/distribution-control/route.test.ts +153 -0
  5. package/dist/template/app/api/admin/distribution-control/route.ts +111 -0
  6. package/dist/template/app/api/admin/guard-actions/[id]/route.test.ts +60 -0
  7. package/dist/template/app/api/admin/guard-actions/[id]/route.ts +32 -0
  8. package/dist/template/app/api/admin/guard-actions/route.test.ts +123 -0
  9. package/dist/template/app/api/admin/guard-actions/route.ts +66 -0
  10. package/dist/template/app/api/admin/updates/[encodedKey]/deactivate/route.ts +4 -1
  11. package/dist/template/app/api/admin/updates/[encodedKey]/policy/route.test.ts +171 -0
  12. package/dist/template/app/api/admin/updates/[encodedKey]/policy/route.ts +75 -0
  13. package/dist/template/app/api/admin/updates/[encodedKey]/promote/route.ts +4 -1
  14. package/dist/template/app/api/admin/updates/[encodedKey]/rollback/route.ts +4 -1
  15. package/dist/template/app/api/admin/updates/[encodedKey]/route.ts +4 -1
  16. package/dist/template/app/updates/[encodedKey]/page.tsx +74 -6
  17. package/dist/template/app/updates/page.tsx +22 -1
  18. package/dist/template/docs/getting-started.md +1 -0
  19. package/dist/template/docs/getting-started.ru.md +2 -1
  20. package/dist/template/docs/migrations/2026-09-01-ota-update-policy.sql +108 -0
  21. package/dist/template/docs/migrations/2026-09-01-p1-guard-actions.sql +19 -0
  22. package/dist/template/docs/migrations/2026-09-01-p2-simplify-ota-guard-policy.sql +69 -0
  23. package/dist/template/docs/migrations/2026-09-01-policy-publication-correction.sql +44 -0
  24. package/dist/template/docs/migrations/2026-09-02-ota-distribution-control.sql +377 -0
  25. package/dist/template/docs/migrations/schema.sql +539 -2
  26. package/dist/template/docs/operations-guide.md +52 -1
  27. package/dist/template/docs/ota-emergency-recovery.md +22 -0
  28. package/dist/template/docs/ota-update-policy.md +89 -0
  29. package/dist/template/docs/supabase-setup.md +2 -1
  30. package/dist/template/package-lock.json +2 -2
  31. package/dist/template/package.json +1 -1
  32. package/dist/template/src/client/admin-api.ts +80 -1
  33. package/dist/template/src/client/admin-types.ts +50 -2
  34. package/dist/template/src/client/distribution-control.tsx +231 -0
  35. package/dist/template/src/client/guard-action-combobox.test.ts +26 -0
  36. package/dist/template/src/client/guard-action-combobox.tsx +267 -0
  37. package/dist/template/src/client/guard-action-options.test.ts +62 -0
  38. package/dist/template/src/client/guard-action-options.ts +70 -0
  39. package/dist/template/src/client/update-policy-editor.test.ts +36 -0
  40. package/dist/template/src/client/update-policy-editor.tsx +436 -0
  41. package/dist/template/src/server/controllers/assets.test.ts +87 -0
  42. package/dist/template/src/server/controllers/assets.ts +26 -0
  43. package/dist/template/src/server/controllers/manifest.test.ts +413 -2
  44. package/dist/template/src/server/controllers/manifest.ts +103 -38
  45. package/dist/template/src/server/lib/admin-distribution-guard.test.ts +61 -0
  46. package/dist/template/src/server/lib/admin-update-policy.test.ts +176 -0
  47. package/dist/template/src/server/lib/admin-updates.test.ts +72 -0
  48. package/dist/template/src/server/lib/admin-updates.ts +169 -24
  49. package/dist/template/src/server/lib/distribution-control-migration.test.ts +94 -0
  50. package/dist/template/src/server/lib/distribution-control.test.ts +181 -0
  51. package/dist/template/src/server/lib/distribution-control.ts +259 -0
  52. package/dist/template/src/server/lib/guard-actions-migration.test.ts +56 -0
  53. package/dist/template/src/server/lib/guard-actions.test.ts +142 -0
  54. package/dist/template/src/server/lib/guard-actions.ts +106 -0
  55. package/dist/template/src/server/lib/ota-policy-migrations.test.ts +64 -0
  56. package/dist/template/src/server/lib/simple-policy-migration.test.ts +97 -0
  57. package/dist/template/src/server/lib/supabase.js +95 -8
  58. package/dist/template/src/server/lib/supabase.test.ts +194 -0
  59. package/dist/template/src/server/lib/update-policy.test.ts +98 -0
  60. package/dist/template/src/server/lib/update-policy.ts +171 -0
  61. package/dist/template/src/server/manifest/manifest-repository.ts +10 -1
  62. package/dist/template/src/server/manifest/manifest-response.ts +0 -16
  63. package/dist/template/src/server/manifest/manifest-values.test.ts +54 -0
  64. package/dist/template/src/server/manifest/manifest-values.ts +145 -0
  65. package/dist/template/tsconfig.json +4 -1
  66. package/dist/template-manifest.json +239 -59
  67. package/package.json +1 -1
@@ -0,0 +1,171 @@
1
+ import { beforeEach, describe, expect, it, vi } from "vitest";
2
+ import { NextRequest } from "next/server";
3
+
4
+ const auth = vi.hoisted(() => ({
5
+ scopes: [] as string[],
6
+ }));
7
+ const getPolicy = vi.hoisted(() =>
8
+ vi.fn(async () => ({
9
+ delivery: "manual",
10
+ guard: null,
11
+ policyVersion: 1,
12
+ publishedAt: null,
13
+ editable: true,
14
+ })),
15
+ );
16
+ const replacePolicy = vi.hoisted(() => vi.fn());
17
+
18
+ vi.mock("@/src/server/lib/admin-access-tokens", () => ({
19
+ authenticateAccessToken: vi.fn(async () => ({
20
+ id: "token",
21
+ name: "test",
22
+ scopes: auth.scopes,
23
+ })),
24
+ }));
25
+ vi.mock("@/src/server/lib/admin-auth", () => ({
26
+ getAdminSessionFromRequest: vi.fn(async () => null),
27
+ }));
28
+ vi.mock("@/src/server/lib/admin-updates", () => ({
29
+ decodeUpdateKey: (value: string) => value,
30
+ getUpdatePolicyByKey: getPolicy,
31
+ replaceUpdatePolicyByKey: replacePolicy,
32
+ UpdatePolicyConflictError: class UpdatePolicyConflictError extends Error {},
33
+ UpdatePolicyPublishedError: class UpdatePolicyPublishedError extends Error {},
34
+ }));
35
+
36
+ const context = {
37
+ params: Promise.resolve({ encodedKey: "encoded-update" }),
38
+ };
39
+ function request(method = "GET", body?: unknown) {
40
+ return new NextRequest(
41
+ "https://updates.example.com/api/admin/updates/encoded-update/policy",
42
+ {
43
+ method,
44
+ headers: {
45
+ authorization: "Bearer ota_test",
46
+ ...(body ? { "content-type": "application/json" } : {}),
47
+ },
48
+ ...(body ? { body: JSON.stringify(body) } : {}),
49
+ },
50
+ );
51
+ }
52
+
53
+ describe("update policy API", () => {
54
+ beforeEach(() => {
55
+ auth.scopes = [];
56
+ getPolicy.mockClear();
57
+ replacePolicy.mockReset();
58
+ });
59
+
60
+ it("requires updates:read for GET", async () => {
61
+ const { GET } = await import("./route");
62
+ expect((await GET(request(), context)).status).toBe(403);
63
+ expect(getPolicy).not.toHaveBeenCalled();
64
+
65
+ auth.scopes = ["updates:read"];
66
+ expect((await GET(request(), context)).status).toBe(200);
67
+ expect(getPolicy).toHaveBeenCalledWith("encoded-update");
68
+ });
69
+
70
+ it("requires updates:write for PUT", async () => {
71
+ auth.scopes = ["updates:read"];
72
+ const { PUT } = await import("./route");
73
+ const response = await PUT(
74
+ request("PUT", { delivery: "manual", guard: null }),
75
+ context,
76
+ );
77
+ expect(response.status).toBe(403);
78
+ expect(replacePolicy).not.toHaveBeenCalled();
79
+ });
80
+
81
+ it("performs complete replacement with optimistic policy version", async () => {
82
+ auth.scopes = ["updates:write"];
83
+ const guard = {
84
+ action: "require-confirmation",
85
+ payload: { message: "Ready" },
86
+ };
87
+ replacePolicy.mockResolvedValueOnce({
88
+ delivery: "background",
89
+ guard,
90
+ policyVersion: 4,
91
+ publishedAt: null,
92
+ editable: true,
93
+ });
94
+ const { PUT } = await import("./route");
95
+ const response = await PUT(
96
+ request("PUT", {
97
+ delivery: "background",
98
+ guard,
99
+ expectedPolicyVersion: 3,
100
+ }),
101
+ context,
102
+ );
103
+ expect(response.status).toBe(200);
104
+ expect(replacePolicy).toHaveBeenCalledWith(
105
+ "encoded-update",
106
+ { delivery: "background", guard },
107
+ 3,
108
+ );
109
+ });
110
+
111
+ it.each([
112
+ ["missing", undefined],
113
+ ["zero", 0],
114
+ ["fractional", 1.5],
115
+ ])("returns 400 for a %s expected policy version", async (_case, version) => {
116
+ auth.scopes = ["updates:write"];
117
+ const { PUT } = await import("./route");
118
+ const response = await PUT(
119
+ request("PUT", {
120
+ delivery: "manual",
121
+ guard: null,
122
+ ...(version === undefined
123
+ ? {}
124
+ : { expectedPolicyVersion: version }),
125
+ }),
126
+ context,
127
+ );
128
+
129
+ expect(response.status).toBe(400);
130
+ expect(replacePolicy).not.toHaveBeenCalled();
131
+ });
132
+
133
+ it("returns 409 for publication and stale version conflicts", async () => {
134
+ auth.scopes = ["updates:write"];
135
+ const { PUT } = await import("./route");
136
+ const { UpdatePolicyPublishedError, UpdatePolicyConflictError } =
137
+ await import("@/src/server/lib/admin-updates");
138
+
139
+ replacePolicy.mockRejectedValueOnce(
140
+ new UpdatePolicyPublishedError("published"),
141
+ );
142
+ expect(
143
+ (
144
+ await PUT(
145
+ request("PUT", {
146
+ delivery: "manual",
147
+ guard: null,
148
+ expectedPolicyVersion: 1,
149
+ }),
150
+ context,
151
+ )
152
+ ).status,
153
+ ).toBe(409);
154
+
155
+ replacePolicy.mockRejectedValueOnce(
156
+ new UpdatePolicyConflictError("conflict"),
157
+ );
158
+ expect(
159
+ (
160
+ await PUT(
161
+ request("PUT", {
162
+ delivery: "manual",
163
+ guard: null,
164
+ expectedPolicyVersion: 1,
165
+ }),
166
+ context,
167
+ )
168
+ ).status,
169
+ ).toBe(409);
170
+ });
171
+ });
@@ -0,0 +1,75 @@
1
+ import { requireAdminAccess } from "@/src/server/lib/admin-api";
2
+ import {
3
+ decodeUpdateKey,
4
+ getUpdatePolicyByKey,
5
+ replaceUpdatePolicyByKey,
6
+ UpdatePolicyConflictError,
7
+ UpdatePolicyPublishedError,
8
+ } from "@/src/server/lib/admin-updates";
9
+ import { UpdatePolicyValidationError } from "@/src/server/lib/update-policy";
10
+ import { NextRequest, NextResponse } from "next/server";
11
+
12
+ type RouteContext = {
13
+ params: Promise<{ encodedKey: string }>;
14
+ };
15
+
16
+ export async function GET(request: NextRequest, context: RouteContext) {
17
+ const session = await requireAdminAccess(request, "updates:read");
18
+ if (session instanceof NextResponse) {
19
+ return session;
20
+ }
21
+ try {
22
+ const { encodedKey } = await context.params;
23
+ return NextResponse.json(
24
+ await getUpdatePolicyByKey(decodeUpdateKey(encodedKey)),
25
+ );
26
+ } catch (error: unknown) {
27
+ return NextResponse.json(
28
+ { error: (error as Error).message || "Failed to fetch update policy" },
29
+ { status: 500 },
30
+ );
31
+ }
32
+ }
33
+
34
+ export async function PUT(request: NextRequest, context: RouteContext) {
35
+ const session = await requireAdminAccess(request, "updates:write");
36
+ if (session instanceof NextResponse) {
37
+ return session;
38
+ }
39
+ try {
40
+ const { encodedKey } = await context.params;
41
+ const body = await request.json();
42
+ if (
43
+ !Number.isInteger(body?.expectedPolicyVersion) ||
44
+ body.expectedPolicyVersion < 1
45
+ ) {
46
+ return NextResponse.json(
47
+ { error: "expectedPolicyVersion must be a positive integer." },
48
+ { status: 400 },
49
+ );
50
+ }
51
+ const policy = await replaceUpdatePolicyByKey(
52
+ decodeUpdateKey(encodedKey),
53
+ { delivery: body?.delivery, guard: body?.guard },
54
+ body?.expectedPolicyVersion,
55
+ );
56
+ return NextResponse.json(policy);
57
+ } catch (error: unknown) {
58
+ if (
59
+ error instanceof UpdatePolicyConflictError ||
60
+ error instanceof UpdatePolicyPublishedError
61
+ ) {
62
+ return NextResponse.json({ error: error.message }, { status: 409 });
63
+ }
64
+ if (
65
+ error instanceof UpdatePolicyValidationError ||
66
+ error instanceof SyntaxError
67
+ ) {
68
+ return NextResponse.json({ error: error.message }, { status: 400 });
69
+ }
70
+ return NextResponse.json(
71
+ { error: (error as Error).message || "Failed to update policy" },
72
+ { status: 500 },
73
+ );
74
+ }
75
+ }
@@ -4,6 +4,7 @@ import {
4
4
  promoteLatestByKey,
5
5
  } from "@/src/server/lib/admin-updates";
6
6
  import { NextRequest, NextResponse } from "next/server";
7
+ import { OtaDistributionBlockedError } from "@/src/server/lib/distribution-control";
7
8
 
8
9
  type RouteContext = {
9
10
  params: Promise<{ encodedKey: string }>;
@@ -23,7 +24,9 @@ export async function POST(request: NextRequest, context: RouteContext) {
23
24
  } catch (error: unknown) {
24
25
  return NextResponse.json(
25
26
  { error: (error as Error).message || "Failed to promote latest update" },
26
- { status: 500 },
27
+ {
28
+ status: error instanceof OtaDistributionBlockedError ? 409 : 500,
29
+ },
27
30
  );
28
31
  }
29
32
  }
@@ -4,6 +4,7 @@ import {
4
4
  rollbackToUpdateByKey,
5
5
  } from "@/src/server/lib/admin-updates";
6
6
  import { NextRequest, NextResponse } from "next/server";
7
+ import { OtaDistributionBlockedError } from "@/src/server/lib/distribution-control";
7
8
 
8
9
  type RouteContext = {
9
10
  params: Promise<{ encodedKey: string }>;
@@ -23,7 +24,9 @@ export async function POST(request: NextRequest, context: RouteContext) {
23
24
  } catch (error: unknown) {
24
25
  return NextResponse.json(
25
26
  { error: (error as Error).message || "Failed to rollback update" },
26
- { status: 500 },
27
+ {
28
+ status: error instanceof OtaDistributionBlockedError ? 409 : 500,
29
+ },
27
30
  );
28
31
  }
29
32
  }
@@ -6,6 +6,7 @@ import {
6
6
  updateJsonFileByKey,
7
7
  } from "@/src/server/lib/admin-updates";
8
8
  import { NextRequest, NextResponse } from "next/server";
9
+ import { OtaDistributionBlockedError } from "@/src/server/lib/distribution-control";
9
10
 
10
11
  type RouteContext = {
11
12
  params: Promise<{ encodedKey: string }>;
@@ -90,7 +91,9 @@ export async function PATCH(request: NextRequest, context: RouteContext) {
90
91
  } catch (error: unknown) {
91
92
  return NextResponse.json(
92
93
  { error: (error as Error).message || "Failed to update JSON" },
93
- { status: 500 },
94
+ {
95
+ status: error instanceof OtaDistributionBlockedError ? 409 : 500,
96
+ },
94
97
  );
95
98
  }
96
99
  }
@@ -10,9 +10,14 @@ import {
10
10
  } from "@/src/client/admin-api";
11
11
  import { UpdateDetail } from "@/src/client/admin-types";
12
12
  import LogoutButton from "@/src/client/logout-button";
13
+ import UpdatePolicyEditor from "@/src/client/update-policy-editor";
13
14
  import Link from "next/link";
14
15
  import { useParams, useRouter } from "next/navigation";
15
16
  import { useEffect, useMemo, useState } from "react";
17
+ import {
18
+ DistributionControlBanner,
19
+ useDistributionControlState,
20
+ } from "@/src/client/distribution-control";
16
21
 
17
22
  type EditableFile =
18
23
  | "update-info.json"
@@ -37,6 +42,13 @@ export default function UpdateDetailsPage() {
37
42
  const [selectedFile, setSelectedFile] =
38
43
  useState<EditableFile>("update-info.json");
39
44
  const [editorValue, setEditorValue] = useState("{}");
45
+ const distributionControl = useDistributionControlState();
46
+ const distributionUnavailable =
47
+ distributionControl.loading ||
48
+ Boolean(distributionControl.error) ||
49
+ !distributionControl.state;
50
+ const distributionBlocked =
51
+ distributionControl.state?.blocked === true || distributionUnavailable;
40
52
 
41
53
  const channelState = useMemo(() => {
42
54
  const latestUpdateId =
@@ -75,10 +87,13 @@ export default function UpdateDetailsPage() {
75
87
  }, [detail]);
76
88
 
77
89
  const canPromote = Boolean(
78
- channelState.isNewestInScope && channelState.rollbackActive,
90
+ !distributionBlocked &&
91
+ channelState.isNewestInScope &&
92
+ channelState.rollbackActive,
79
93
  );
80
94
  const canRollback = Boolean(
81
95
  detail &&
96
+ !distributionBlocked &&
82
97
  !channelState.isNewestInScope &&
83
98
  channelState.currentServedUpdateId &&
84
99
  detail.updateId !== channelState.currentServedUpdateId,
@@ -88,6 +103,7 @@ export default function UpdateDetailsPage() {
88
103
  );
89
104
  const canDirectActivate = Boolean(
90
105
  detail &&
106
+ !distributionBlocked &&
91
107
  detail.status === "disabled" &&
92
108
  channelState.isNewestInScope &&
93
109
  !channelState.rollbackActive,
@@ -98,7 +114,26 @@ export default function UpdateDetailsPage() {
98
114
  const showToggleDisabledButton = canDirectActivate || canDirectDeactivate;
99
115
  const canDelete = Boolean(detail && detail.status !== "active");
100
116
  const channelLatestLocked =
101
- selectedFile === "channel-latest.json" && channelState.rollbackActive;
117
+ selectedFile === "channel-latest.json" &&
118
+ (channelState.rollbackActive || distributionBlocked);
119
+
120
+ const updateMetaDistributionLocked = useMemo(() => {
121
+ if (selectedFile !== "update-meta.json" || !distributionBlocked) {
122
+ return false;
123
+ }
124
+ try {
125
+ const value: unknown = JSON.parse(editorValue);
126
+ return (
127
+ !value ||
128
+ typeof value !== "object" ||
129
+ Array.isArray(value) ||
130
+ !("isActive" in value) ||
131
+ value.isActive !== false
132
+ );
133
+ } catch {
134
+ return true;
135
+ }
136
+ }, [distributionBlocked, editorValue, selectedFile]);
102
137
 
103
138
  const fileContent = useMemo(() => {
104
139
  if (!detail) {
@@ -301,6 +336,12 @@ export default function UpdateDetailsPage() {
301
336
  </div>
302
337
  ) : null}
303
338
 
339
+ <DistributionControlBanner
340
+ state={distributionControl.state}
341
+ loading={distributionControl.loading}
342
+ error={distributionControl.error}
343
+ />
344
+
304
345
  {!loading && detail ? (
305
346
  <>
306
347
  {channelState.rollbackActive ? (
@@ -347,7 +388,18 @@ export default function UpdateDetailsPage() {
347
388
  />
348
389
  <Info
349
390
  label="Доставка"
350
- value={detail.isIgnoredByRollback ? "Ignored" : "Auto"}
391
+ value={
392
+ detail.isIgnoredByRollback
393
+ ? "Ignored by rollback"
394
+ : detail.deliveryMode === "background"
395
+ ? "Background"
396
+ : "Manual"
397
+ }
398
+ />
399
+ <Info label="Guard" value={detail.hasGuard ? "Yes" : "None"} />
400
+ <Info
401
+ label="Policy"
402
+ value={`v${detail.policyVersion} · ${detail.policyEditable ? "draft" : "published"}`}
351
403
  />
352
404
  <Info label="Assets" value={String(detail.assetsCount)} />
353
405
  <Info
@@ -367,6 +419,12 @@ export default function UpdateDetailsPage() {
367
419
  />
368
420
  </section>
369
421
 
422
+ <UpdatePolicyEditor
423
+ key={`${encodedKey}-${detail.policyVersion}-${detail.policyPublishedAt || "draft"}`}
424
+ encodedKey={encodedKey}
425
+ onSaved={reload}
426
+ />
427
+
370
428
  <section className="rounded-xl border border-zinc-200 bg-white p-4 dark:border-zinc-800 dark:bg-zinc-900">
371
429
  <div className="flex flex-wrap gap-2">
372
430
  {canRollback ? (
@@ -435,7 +493,11 @@ export default function UpdateDetailsPage() {
435
493
  <button
436
494
  type="button"
437
495
  onClick={handleSaveJson}
438
- disabled={saving || channelLatestLocked}
496
+ disabled={
497
+ saving ||
498
+ channelLatestLocked ||
499
+ updateMetaDistributionLocked
500
+ }
439
501
  className="rounded-md border border-zinc-300 px-4 py-4 text-sm hover:bg-zinc-100 disabled:cursor-not-allowed disabled:opacity-60 dark:border-zinc-700 dark:hover:bg-zinc-800"
440
502
  >
441
503
  Сохранить JSON
@@ -443,8 +505,14 @@ export default function UpdateDetailsPage() {
443
505
  </div>
444
506
  {channelLatestLocked ? (
445
507
  <p className="mt-2 text-xs text-orange-700 dark:text-orange-300">
446
- Редактирование channel latest.json заблокировано: rollback
447
- активен. Используйте Promote.
508
+ Редактирование channel latest.json заблокировано: активен
509
+ rollback или глобальный аварийный выключатель.
510
+ </p>
511
+ ) : null}
512
+ {updateMetaDistributionLocked ? (
513
+ <p className="mt-2 text-xs text-red-700 dark:text-red-300">
514
+ Активация через update-meta.json недоступна при глобальной
515
+ блокировке. Деактивация с isActive=false остаётся доступна.
448
516
  </p>
449
517
  ) : null}
450
518
  <textarea
@@ -3,6 +3,7 @@
3
3
  import { getUpdates } from "@/src/client/admin-api";
4
4
  import { UpdateItem } from "@/src/client/admin-types";
5
5
  import LogoutButton from "@/src/client/logout-button";
6
+ import DistributionControl from "@/src/client/distribution-control";
6
7
  import Link from "next/link";
7
8
  import { useCallback, useEffect, useState } from "react";
8
9
 
@@ -124,6 +125,8 @@ export default function UpdatesPage() {
124
125
  </div>
125
126
  </header>
126
127
 
128
+ <DistributionControl />
129
+
127
130
  {error ? (
128
131
  <div className="rounded-md border border-red-200 bg-red-50 p-3 text-sm text-red-700 dark:border-red-900 dark:bg-red-950/40 dark:text-red-300">
129
132
  {error}
@@ -220,6 +223,23 @@ export default function UpdatesPage() {
220
223
  <td className="px-4 py-4">{item.stage}</td>
221
224
  <td className="px-4 py-4">{item.status}</td>
222
225
  <td className="px-4 py-4">
226
+ <div className="flex flex-wrap gap-1">
227
+ <span
228
+ className={`rounded border px-2 py-0.5 text-xs ${
229
+ item.deliveryMode === "background"
230
+ ? "border-blue-300 text-blue-700 dark:border-blue-700 dark:text-blue-300"
231
+ : "border-zinc-300 text-zinc-700 dark:border-zinc-600 dark:text-zinc-300"
232
+ }`}
233
+ >
234
+ {item.deliveryMode === "background"
235
+ ? "Background"
236
+ : "Manual"}
237
+ </span>
238
+ {item.hasGuard ? (
239
+ <span className="rounded border border-violet-300 px-2 py-0.5 text-xs text-violet-700 dark:border-violet-700 dark:text-violet-300">
240
+ Guard
241
+ </span>
242
+ ) : null}
223
243
  {item.isRollbackActive ? (
224
244
  <span className="rounded border border-amber-300 px-2 py-0.5 text-xs text-amber-800 dark:border-amber-700 dark:text-amber-300">
225
245
  rollback
@@ -230,9 +250,10 @@ export default function UpdatesPage() {
230
250
  </span>
231
251
  ) : (
232
252
  <span className="rounded border border-emerald-300 px-2 py-0.5 text-xs text-emerald-700 dark:border-emerald-700 dark:text-emerald-300">
233
- auto
253
+ scope open
234
254
  </span>
235
255
  )}
256
+ </div>
236
257
  </td>
237
258
  <td className="px-4 py-4">
238
259
  {item.isLatest ? "Да" : "Нет"}
@@ -233,6 +233,7 @@ ota_device_state
233
233
  ota_device_transitions
234
234
  ota_embedded_updates
235
235
  ota_emergency_redirects
236
+ ota_guard_actions
236
237
  ota_served_manifest_log
237
238
  ota_update_channels
238
239
  ota_updates
@@ -282,7 +282,7 @@ OTA-сервер — приложение сервера всё равно ну
282
282
 
283
283
  ## Шаг 3. Проверьте таблицы
284
284
 
285
- Откройте слева **Table Editor**. Должны появиться 10 таблиц:
285
+ Откройте слева **Table Editor**. Должны появиться 11 таблиц:
286
286
 
287
287
  ```text
288
288
  ota_access_tokens
@@ -292,6 +292,7 @@ ota_device_state
292
292
  ota_device_transitions
293
293
  ota_embedded_updates
294
294
  ota_emergency_redirects
295
+ ota_guard_actions
295
296
  ota_served_manifest_log
296
297
  ota_update_channels
297
298
  ota_updates
@@ -0,0 +1,108 @@
1
+ alter table public.ota_updates
2
+ add column if not exists delivery_mode text not null default 'manual',
3
+ add column if not exists guard_action text null,
4
+ add column if not exists guard_payload jsonb null,
5
+ add column if not exists policy_version integer not null default 1,
6
+ add column if not exists policy_published_at timestamptz null;
7
+
8
+ drop trigger if exists trg_ota_updates_lock_published_policy
9
+ on public.ota_updates;
10
+
11
+ alter table public.ota_updates
12
+ drop constraint if exists ota_updates_delivery_mode_chk,
13
+ add constraint ota_updates_delivery_mode_chk
14
+ check (delivery_mode in ('manual', 'background')),
15
+ drop constraint if exists ota_updates_guard_rules_array_chk,
16
+ drop constraint if exists ota_updates_guard_action_chk,
17
+ add constraint ota_updates_guard_action_chk check (
18
+ guard_action is null
19
+ or (
20
+ guard_action = btrim(guard_action)
21
+ and char_length(guard_action) between 1 and 100
22
+ and guard_action !~ '[[:cntrl:]]'
23
+ )
24
+ ),
25
+ drop constraint if exists ota_updates_guard_payload_requires_action_chk,
26
+ add constraint ota_updates_guard_payload_requires_action_chk check (
27
+ guard_payload is null or guard_action is not null
28
+ ),
29
+ drop constraint if exists ota_updates_policy_version_chk,
30
+ add constraint ota_updates_policy_version_chk
31
+ check (policy_version > 0),
32
+ drop column if exists guard_rules;
33
+
34
+ -- Active rows, rows disabled after their initial draft marker, rollback
35
+ -- targets, explicitly pinned rows, and demonstrably served rows have
36
+ -- participated in delivery. Uploads start inactive with disabled_at equal to
37
+ -- created_at; that initial marker is not a publication event.
38
+ update public.ota_updates u
39
+ set policy_published_at = coalesce(
40
+ u.updated_at,
41
+ u.disabled_at,
42
+ u.created_at,
43
+ now()
44
+ )
45
+ where u.policy_published_at is null
46
+ and (
47
+ u.is_active
48
+ or (
49
+ u.disabled_at is not null
50
+ and u.disabled_at is distinct from u.created_at
51
+ and u.updated_at is not null
52
+ )
53
+ or u.rolled_back_from_update_id is not null
54
+ or exists (
55
+ select 1
56
+ from public.ota_update_channels c
57
+ where c.active_update_id = u.update_id
58
+ )
59
+ or exists (
60
+ select 1
61
+ from public.ota_served_manifest_log sml
62
+ where sml.update_id = u.update_id
63
+ )
64
+ );
65
+
66
+ create or replace function public.ota_updates_lock_published_policy()
67
+ returns trigger
68
+ language plpgsql
69
+ as $$
70
+ begin
71
+ if tg_op = 'INSERT' then
72
+ if new.is_active and new.policy_published_at is null then
73
+ new.policy_published_at := coalesce(
74
+ new.updated_at,
75
+ new.created_at,
76
+ now()
77
+ );
78
+ end if;
79
+ return new;
80
+ end if;
81
+
82
+ if new.is_active and not old.is_active
83
+ and new.policy_published_at is null then
84
+ new.policy_published_at := coalesce(
85
+ new.updated_at,
86
+ new.created_at,
87
+ now()
88
+ );
89
+ end if;
90
+
91
+ if old.policy_published_at is not null and (
92
+ new.delivery_mode is distinct from old.delivery_mode
93
+ or new.guard_action is distinct from old.guard_action
94
+ or new.guard_payload is distinct from old.guard_payload
95
+ or new.policy_version is distinct from old.policy_version
96
+ or new.policy_published_at is distinct from old.policy_published_at
97
+ ) then
98
+ raise exception 'OTA update policy is immutable after publication';
99
+ end if;
100
+ return new;
101
+ end;
102
+ $$;
103
+
104
+ drop trigger if exists trg_ota_updates_lock_published_policy
105
+ on public.ota_updates;
106
+ create trigger trg_ota_updates_lock_published_policy
107
+ before insert or update on public.ota_updates
108
+ for each row execute function public.ota_updates_lock_published_policy();
@@ -0,0 +1,19 @@
1
+ create extension if not exists pgcrypto;
2
+
3
+ create table if not exists public.ota_guard_actions (
4
+ id uuid primary key default gen_random_uuid(),
5
+ action_key text not null,
6
+ created_at timestamptz not null default now(),
7
+ constraint ota_guard_actions_action_key_chk check (
8
+ action_key = btrim(action_key)
9
+ and char_length(action_key) between 1 and 100
10
+ and action_key !~ '[[:cntrl:]]'
11
+ )
12
+ );
13
+
14
+ create unique index if not exists idx_ota_guard_actions_action_key
15
+ on public.ota_guard_actions (action_key);
16
+
17
+ insert into public.ota_guard_actions (action_key)
18
+ values ('ota-force-store-update')
19
+ on conflict (action_key) do nothing;