create-expo-updates-server 0.1.4 → 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 (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 +160 -0
  51. package/dist/template/src/server/lib/distribution-control.ts +250 -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
@@ -11,5 +11,6 @@ OTA_STORAGE_BUCKET=expo-updates
11
11
 
12
12
  OTA_HTTP_PORT=3000
13
13
  OTA_PUBLIC_BASE_URL=http://localhost:3000
14
+ # Deprecated/ignored for new manifests; assets are served through /api/assets.
14
15
  OTA_CDN_BASE_URL=
15
16
  CODE_SIGNING_PRIVATE_KEY=
@@ -21,6 +21,8 @@ R2_REGION="auto"
21
21
  OTA_STORAGE_BUCKET="expo-updates"
22
22
  OTA_SIGNED_URL_TTL="3600"
23
23
  OTA_PUBLIC_BASE_URL="https://updates.example.com"
24
+ # Deprecated compatibility setting. New manifests always use gated /api/assets
25
+ # URLs so the global OTA emergency switch cannot be bypassed.
24
26
  OTA_CDN_BASE_URL=""
25
27
 
26
28
  # Supabase provider
@@ -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
@@ -573,7 +574,9 @@ npm run create-admin
573
574
  Опционально:
574
575
 
575
576
  - `OTA_PUBLIC_BASE_URL` - публичный URL OTA сервера (для `/api/manifest` и `/api/assets`)
576
- - `OTA_CDN_BASE_URL` - публичный CDN URL для прямой раздачи ассетов (например `https://cdn.cogitize.tech`)
577
+ - `OTA_CDN_BASE_URL` - устаревшая совместимая настройка; новые manifest
578
+ намеренно игнорируют её и выдают gated `/api/assets` URL, чтобы глобальный
579
+ аварийный выключатель нельзя было обойти прямой загрузкой из CDN
577
580
  - `OTA_SIGNED_URL_TTL` - TTL signed URL в секундах (по умолчанию `3600`)
578
581
  - `R2_REGION` - регион для S3 клиента (по умолчанию `auto`)
579
582
 
@@ -0,0 +1,153 @@
1
+ import { beforeEach, describe, expect, it, vi } from "vitest";
2
+ import { NextRequest, NextResponse } from "next/server";
3
+
4
+ const requireAdminAccess = vi.hoisted(() => vi.fn());
5
+ const getState = vi.hoisted(() => vi.fn());
6
+ const setState = vi.hoisted(() => vi.fn());
7
+
8
+ vi.mock("@/src/server/lib/admin-api", () => ({
9
+ requireAdminAccess,
10
+ }));
11
+
12
+ vi.mock("@/src/server/lib/distribution-control", () => {
13
+ class DistributionControlValidationError extends Error {
14
+ readonly status = 400;
15
+ }
16
+ class DistributionControlConflictError extends Error {
17
+ readonly status = 409;
18
+ }
19
+ return {
20
+ DistributionControlValidationError,
21
+ DistributionControlConflictError,
22
+ getDistributionControlState: getState,
23
+ setDistributionControlState: setState,
24
+ };
25
+ });
26
+
27
+ const currentState = {
28
+ blocked: false,
29
+ version: 3,
30
+ reason: null,
31
+ changedAt: "2026-09-02T00:00:00.000Z",
32
+ changedBy: { type: "system", id: "migration", label: "Migration" },
33
+ };
34
+
35
+ describe("/api/admin/distribution-control", () => {
36
+ beforeEach(() => {
37
+ vi.clearAllMocks();
38
+ const principal = {
39
+ type: "session",
40
+ id: "operator-id",
41
+ username: "operator",
42
+ role: "operator",
43
+ };
44
+ requireAdminAccess.mockResolvedValue(principal);
45
+ getState.mockResolvedValue(currentState);
46
+ setState.mockResolvedValue({
47
+ ...currentState,
48
+ blocked: true,
49
+ version: 4,
50
+ reason: "INC-42",
51
+ });
52
+ });
53
+
54
+ it("requires updates:read and reports viewer write capability", async () => {
55
+ requireAdminAccess.mockResolvedValueOnce({
56
+ type: "session",
57
+ id: "viewer-id",
58
+ username: "viewer",
59
+ role: "viewer",
60
+ });
61
+ const { GET } = await import("./route");
62
+ const request = new NextRequest(
63
+ "https://updates.example.com/api/admin/distribution-control",
64
+ );
65
+
66
+ const response = await GET(request);
67
+
68
+ expect(response.status).toBe(200);
69
+ expect(await response.json()).toMatchObject({ canWrite: false });
70
+ expect(requireAdminAccess).toHaveBeenCalledWith(request, "updates:read");
71
+ });
72
+
73
+ it("requires updates:write and records session principal metadata", async () => {
74
+ const { PUT } = await import("./route");
75
+ const request = new NextRequest(
76
+ "https://updates.example.com/api/admin/distribution-control",
77
+ {
78
+ method: "PUT",
79
+ headers: { "content-type": "application/json" },
80
+ body: JSON.stringify({
81
+ blocked: true,
82
+ reason: "INC-42",
83
+ expectedVersion: 3,
84
+ }),
85
+ },
86
+ );
87
+
88
+ const response = await PUT(request);
89
+
90
+ expect(response.status).toBe(200);
91
+ expect(setState).toHaveBeenCalledWith({
92
+ blocked: true,
93
+ reason: "INC-42",
94
+ expectedVersion: 3,
95
+ principal: {
96
+ type: "session",
97
+ id: "operator-id",
98
+ label: "operator",
99
+ role: "operator",
100
+ },
101
+ });
102
+ expect(requireAdminAccess).toHaveBeenCalledWith(request, "updates:write");
103
+ });
104
+
105
+ it("returns auth responses and optimistic conflicts with correct status", async () => {
106
+ requireAdminAccess.mockResolvedValueOnce(
107
+ NextResponse.json({ error: "Forbidden" }, { status: 403 }),
108
+ );
109
+ const { GET, PUT } = await import("./route");
110
+ const forbidden = await GET(
111
+ new NextRequest(
112
+ "https://updates.example.com/api/admin/distribution-control",
113
+ ),
114
+ );
115
+ expect(forbidden.status).toBe(403);
116
+
117
+ const { DistributionControlConflictError } =
118
+ await import("@/src/server/lib/distribution-control");
119
+ setState.mockRejectedValueOnce(new DistributionControlConflictError());
120
+ const conflict = await PUT(
121
+ new NextRequest(
122
+ "https://updates.example.com/api/admin/distribution-control",
123
+ {
124
+ method: "PUT",
125
+ body: JSON.stringify({
126
+ blocked: false,
127
+ expectedVersion: 2,
128
+ }),
129
+ },
130
+ ),
131
+ );
132
+ expect(conflict.status).toBe(409);
133
+ });
134
+
135
+ it("returns 400 for malformed JSON and 500 for state read failures", async () => {
136
+ const { GET, PUT } = await import("./route");
137
+ const invalid = await PUT(
138
+ new NextRequest(
139
+ "https://updates.example.com/api/admin/distribution-control",
140
+ { method: "PUT", body: "{" },
141
+ ),
142
+ );
143
+ expect(invalid.status).toBe(400);
144
+
145
+ getState.mockRejectedValueOnce(new Error("database down"));
146
+ const failed = await GET(
147
+ new NextRequest(
148
+ "https://updates.example.com/api/admin/distribution-control",
149
+ ),
150
+ );
151
+ expect(failed.status).toBe(500);
152
+ });
153
+ });
@@ -0,0 +1,111 @@
1
+ import {
2
+ requireAdminAccess,
3
+ type AdminPrincipal,
4
+ } from "@/src/server/lib/admin-api";
5
+ import {
6
+ DistributionControlConflictError,
7
+ DistributionControlValidationError,
8
+ getDistributionControlState,
9
+ setDistributionControlState,
10
+ type DistributionControlPrincipal,
11
+ } from "@/src/server/lib/distribution-control";
12
+ import { NextRequest, NextResponse } from "next/server";
13
+
14
+ function toDistributionPrincipal(
15
+ principal: AdminPrincipal,
16
+ ): DistributionControlPrincipal {
17
+ if (principal.type === "session") {
18
+ return {
19
+ type: "session",
20
+ id: principal.id,
21
+ label: principal.username,
22
+ role: principal.role,
23
+ };
24
+ }
25
+
26
+ return {
27
+ type: "access-token",
28
+ id: principal.id,
29
+ label: principal.name,
30
+ };
31
+ }
32
+
33
+ function isRecord(value: unknown): value is Record<string, unknown> {
34
+ return Boolean(value) && typeof value === "object" && !Array.isArray(value);
35
+ }
36
+
37
+ function canWrite(principal: AdminPrincipal): boolean {
38
+ return principal.type === "session"
39
+ ? principal.role !== "viewer"
40
+ : principal.scopes.includes("updates:write");
41
+ }
42
+
43
+ export async function GET(request: NextRequest) {
44
+ const principal = await requireAdminAccess(request, "updates:read");
45
+ if (principal instanceof NextResponse) {
46
+ return principal;
47
+ }
48
+
49
+ try {
50
+ return NextResponse.json({
51
+ ...(await getDistributionControlState()),
52
+ canWrite: canWrite(principal),
53
+ });
54
+ } catch (error: unknown) {
55
+ console.error("Failed to read OTA distribution control:", error);
56
+ return NextResponse.json(
57
+ { error: "Failed to read OTA distribution control." },
58
+ { status: 500 },
59
+ );
60
+ }
61
+ }
62
+
63
+ export async function PUT(request: NextRequest) {
64
+ const principal = await requireAdminAccess(request, "updates:write");
65
+ if (principal instanceof NextResponse) {
66
+ return principal;
67
+ }
68
+
69
+ let body: unknown;
70
+ try {
71
+ body = await request.json();
72
+ } catch {
73
+ return NextResponse.json(
74
+ { error: "Invalid JSON request body." },
75
+ { status: 400 },
76
+ );
77
+ }
78
+
79
+ if (!isRecord(body)) {
80
+ return NextResponse.json(
81
+ { error: "Request body must be a JSON object." },
82
+ { status: 400 },
83
+ );
84
+ }
85
+
86
+ try {
87
+ return NextResponse.json(
88
+ await setDistributionControlState({
89
+ blocked: body.blocked,
90
+ reason: body.reason,
91
+ expectedVersion: body.expectedVersion,
92
+ principal: toDistributionPrincipal(principal),
93
+ }),
94
+ );
95
+ } catch (error: unknown) {
96
+ if (
97
+ error instanceof DistributionControlValidationError ||
98
+ error instanceof DistributionControlConflictError
99
+ ) {
100
+ return NextResponse.json(
101
+ { error: error.message },
102
+ { status: error.status },
103
+ );
104
+ }
105
+ console.error("Failed to update OTA distribution control:", error);
106
+ return NextResponse.json(
107
+ { error: "Failed to update OTA distribution control." },
108
+ { status: 500 },
109
+ );
110
+ }
111
+ }
@@ -0,0 +1,60 @@
1
+ import { beforeEach, describe, expect, it, vi } from "vitest";
2
+ import { NextRequest, NextResponse } from "next/server";
3
+
4
+ const requireAdminAccess = vi.hoisted(() => vi.fn());
5
+ const deleteGuardAction = vi.hoisted(() => vi.fn(async () => undefined));
6
+ const ValidationError = vi.hoisted(() => class extends Error {});
7
+
8
+ vi.mock("@/src/server/lib/admin-api", () => ({
9
+ requireAdminAccess,
10
+ }));
11
+ vi.mock("@/src/server/lib/guard-actions", () => ({
12
+ deleteGuardAction,
13
+ GuardActionValidationError: ValidationError,
14
+ }));
15
+
16
+ const request = new NextRequest(
17
+ "https://updates.example.com/api/admin/guard-actions/aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
18
+ { method: "DELETE" },
19
+ );
20
+ const context = {
21
+ params: Promise.resolve({
22
+ id: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
23
+ }),
24
+ };
25
+
26
+ describe("DELETE /api/admin/guard-actions/[id]", () => {
27
+ beforeEach(() => {
28
+ requireAdminAccess.mockReset();
29
+ deleteGuardAction.mockClear();
30
+ });
31
+
32
+ it("requires updates:write", async () => {
33
+ requireAdminAccess.mockResolvedValue(
34
+ NextResponse.json({ error: "Forbidden" }, { status: 403 }),
35
+ );
36
+ const { DELETE } = await import("./route");
37
+ expect((await DELETE(request, context)).status).toBe(403);
38
+ expect(deleteGuardAction).not.toHaveBeenCalled();
39
+ });
40
+
41
+ it("is idempotent and policy-independent", async () => {
42
+ requireAdminAccess.mockResolvedValue({
43
+ type: "session",
44
+ id: "operator-id",
45
+ username: "operator",
46
+ role: "operator",
47
+ });
48
+ const { DELETE } = await import("./route");
49
+ expect((await DELETE(request, context)).status).toBe(200);
50
+ expect((await DELETE(request, context)).status).toBe(200);
51
+ expect(deleteGuardAction).toHaveBeenCalledTimes(2);
52
+ expect(deleteGuardAction).toHaveBeenCalledWith(
53
+ "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
54
+ );
55
+ expect(requireAdminAccess).toHaveBeenLastCalledWith(
56
+ expect.any(NextRequest),
57
+ "updates:write",
58
+ );
59
+ });
60
+ });
@@ -0,0 +1,32 @@
1
+ import { requireAdminAccess } from "@/src/server/lib/admin-api";
2
+ import {
3
+ deleteGuardAction,
4
+ GuardActionValidationError,
5
+ } from "@/src/server/lib/guard-actions";
6
+ import { NextRequest, NextResponse } from "next/server";
7
+
8
+ type RouteContext = {
9
+ params: Promise<{ id: string }>;
10
+ };
11
+
12
+ export async function DELETE(request: NextRequest, context: RouteContext) {
13
+ const principal = await requireAdminAccess(request, "updates:write");
14
+ if (principal instanceof NextResponse) {
15
+ return principal;
16
+ }
17
+
18
+ try {
19
+ const { id } = await context.params;
20
+ await deleteGuardAction(id);
21
+ return NextResponse.json({ ok: true });
22
+ } catch (error: unknown) {
23
+ if (error instanceof GuardActionValidationError) {
24
+ return NextResponse.json({ error: error.message }, { status: 400 });
25
+ }
26
+ console.error("Failed to delete guard action:", error);
27
+ return NextResponse.json(
28
+ { error: "Failed to delete guard action" },
29
+ { status: 500 },
30
+ );
31
+ }
32
+ }
@@ -0,0 +1,123 @@
1
+ import { beforeEach, describe, expect, it, vi } from "vitest";
2
+ import { NextRequest, NextResponse } from "next/server";
3
+
4
+ const requireAdminAccess = vi.hoisted(() => vi.fn());
5
+ const listGuardActions = vi.hoisted(() =>
6
+ vi.fn(async () => [
7
+ {
8
+ id: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
9
+ actionKey: "alpha",
10
+ createdAt: "2026-09-01T00:00:00.000Z",
11
+ },
12
+ ]),
13
+ );
14
+ const createGuardAction = vi.hoisted(() => vi.fn());
15
+ const ValidationError = vi.hoisted(() => class extends Error {});
16
+
17
+ vi.mock("@/src/server/lib/admin-api", () => ({
18
+ requireAdminAccess,
19
+ }));
20
+ vi.mock("@/src/server/lib/guard-actions", () => ({
21
+ listGuardActions,
22
+ createGuardAction,
23
+ GuardActionValidationError: ValidationError,
24
+ }));
25
+
26
+ function request(method = "GET", body?: unknown) {
27
+ return new NextRequest(
28
+ "https://updates.example.com/api/admin/guard-actions",
29
+ {
30
+ method,
31
+ ...(body
32
+ ? {
33
+ headers: { "content-type": "application/json" },
34
+ body: JSON.stringify(body),
35
+ }
36
+ : {}),
37
+ },
38
+ );
39
+ }
40
+
41
+ describe("/api/admin/guard-actions", () => {
42
+ beforeEach(() => {
43
+ requireAdminAccess.mockReset();
44
+ createGuardAction.mockReset();
45
+ });
46
+
47
+ it("requires updates:read and reports viewer mutation authorization", async () => {
48
+ requireAdminAccess.mockResolvedValueOnce(
49
+ NextResponse.json({ error: "Forbidden" }, { status: 403 }),
50
+ );
51
+ const { GET } = await import("./route");
52
+ expect((await GET(request())).status).toBe(403);
53
+
54
+ requireAdminAccess.mockResolvedValueOnce({
55
+ type: "session",
56
+ id: "viewer-id",
57
+ username: "viewer",
58
+ role: "viewer",
59
+ });
60
+ const response = await GET(request());
61
+ expect(response.status).toBe(200);
62
+ await expect(response.json()).resolves.toEqual({
63
+ items: await listGuardActions(),
64
+ canWrite: false,
65
+ });
66
+ expect(requireAdminAccess).toHaveBeenLastCalledWith(
67
+ expect.any(NextRequest),
68
+ "updates:read",
69
+ );
70
+ });
71
+
72
+ it("reports token write scope independently of read authorization", async () => {
73
+ requireAdminAccess.mockResolvedValue({
74
+ type: "access-token",
75
+ id: "token-id",
76
+ name: "token",
77
+ scopes: ["updates:read", "updates:write"],
78
+ });
79
+ const { GET } = await import("./route");
80
+ await expect((await GET(request())).json()).resolves.toMatchObject({
81
+ canWrite: true,
82
+ });
83
+ });
84
+
85
+ it("requires updates:write and returns the create-or-get result", async () => {
86
+ const item = {
87
+ id: "aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
88
+ actionKey: "same-action",
89
+ createdAt: "2026-09-01T00:00:00.000Z",
90
+ };
91
+ requireAdminAccess.mockResolvedValue({
92
+ type: "session",
93
+ id: "operator-id",
94
+ username: "operator",
95
+ role: "operator",
96
+ });
97
+ createGuardAction.mockResolvedValue(item);
98
+ const { POST } = await import("./route");
99
+ const first = await POST(request("POST", { actionKey: "same-action" }));
100
+ const second = await POST(request("POST", { actionKey: "same-action" }));
101
+
102
+ expect(first.status).toBe(201);
103
+ expect(second.status).toBe(201);
104
+ await expect(first.json()).resolves.toEqual(item);
105
+ await expect(second.json()).resolves.toEqual(item);
106
+ expect(requireAdminAccess).toHaveBeenLastCalledWith(
107
+ expect.any(NextRequest),
108
+ "updates:write",
109
+ );
110
+ });
111
+
112
+ it("returns 400 for invalid catalog input", async () => {
113
+ requireAdminAccess.mockResolvedValue({
114
+ type: "session",
115
+ id: "operator-id",
116
+ username: "operator",
117
+ role: "operator",
118
+ });
119
+ createGuardAction.mockRejectedValue(new ValidationError("invalid"));
120
+ const { POST } = await import("./route");
121
+ expect((await POST(request("POST", { actionKey: "" }))).status).toBe(400);
122
+ });
123
+ });
@@ -0,0 +1,66 @@
1
+ import {
2
+ AdminPrincipal,
3
+ requireAdminAccess,
4
+ } from "@/src/server/lib/admin-api";
5
+ import {
6
+ createGuardAction,
7
+ GuardActionValidationError,
8
+ listGuardActions,
9
+ } from "@/src/server/lib/guard-actions";
10
+ import { NextRequest, NextResponse } from "next/server";
11
+
12
+ function canWrite(principal: AdminPrincipal): boolean {
13
+ return principal.type === "session"
14
+ ? principal.role !== "viewer"
15
+ : principal.scopes.includes("updates:write");
16
+ }
17
+
18
+ export async function GET(request: NextRequest) {
19
+ const principal = await requireAdminAccess(request, "updates:read");
20
+ if (principal instanceof NextResponse) {
21
+ return principal;
22
+ }
23
+
24
+ try {
25
+ return NextResponse.json({
26
+ items: await listGuardActions(),
27
+ canWrite: canWrite(principal),
28
+ });
29
+ } catch (error: unknown) {
30
+ console.error("Failed to list guard actions:", error);
31
+ return NextResponse.json(
32
+ { error: "Failed to list guard actions" },
33
+ { status: 500 },
34
+ );
35
+ }
36
+ }
37
+
38
+ export async function POST(request: NextRequest) {
39
+ const principal = await requireAdminAccess(request, "updates:write");
40
+ if (principal instanceof NextResponse) {
41
+ return principal;
42
+ }
43
+
44
+ let body: unknown;
45
+ try {
46
+ body = await request.json();
47
+ } catch {
48
+ return NextResponse.json(
49
+ { error: "Invalid JSON request body" },
50
+ { status: 400 },
51
+ );
52
+ }
53
+
54
+ try {
55
+ return NextResponse.json(await createGuardAction(body), { status: 201 });
56
+ } catch (error: unknown) {
57
+ if (error instanceof GuardActionValidationError) {
58
+ return NextResponse.json({ error: error.message }, { status: 400 });
59
+ }
60
+ console.error("Failed to create guard action:", error);
61
+ return NextResponse.json(
62
+ { error: "Failed to create guard action" },
63
+ { status: 500 },
64
+ );
65
+ }
66
+ }
@@ -4,6 +4,7 @@ import {
4
4
  setUpdateDisabledByKey,
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 }>;
@@ -27,7 +28,9 @@ export async function POST(request: NextRequest, context: RouteContext) {
27
28
  } catch (error: unknown) {
28
29
  return NextResponse.json(
29
30
  { error: (error as Error).message || "Failed to deactivate update" },
30
- { status: 500 },
31
+ {
32
+ status: error instanceof OtaDistributionBlockedError ? 409 : 500,
33
+ },
31
34
  );
32
35
  }
33
36
  }