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
@@ -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
@@ -372,9 +373,14 @@ npm run ota:build:android:apk
372
373
  ```
373
374
 
374
375
  Use `npm run ota:build:android:aab` for an App Bundle. After Gradle succeeds,
375
- the generated script finds `app.manifest` and registers the embedded update.
376
- For iOS, the configurator adds an Xcode Build Phase, so a Release/Archive build
377
- in Xcode performs registration automatically.
376
+ `scripts/ota-register-embedded/register-android.sh` finds `app.manifest` and
377
+ registers the embedded update. For iOS, the configurator adds an Xcode Build
378
+ Phase that invokes `scripts/ota-register-embedded/register-ios.sh`, so a
379
+ Release/Archive build in Xcode performs registration automatically.
380
+ The registrar uses an app version from the embedded manifest when available;
381
+ otherwise it falls back to the normalized `expo.version` in the project's
382
+ static `app.json`. A missing or invalid fallback remains `null` and does not
383
+ fail an otherwise valid registration.
378
384
 
379
385
  For remote CI or Xcode Cloud, do not provide PostgreSQL credentials. Create a
380
386
  dedicated token:
@@ -391,10 +397,10 @@ OTA_SERVER_URL=https://updates.example.com
391
397
  OTA_ACCESS_TOKEN=ota_...
392
398
  ```
393
399
 
394
- The configurator also creates `ci_scripts/ci_post_xcodebuild.sh`, which Xcode
395
- Cloud runs after a build. The token is shown only once and must never be
396
- committed or included in the mobile binary. Verify registered binaries at
397
- `/updates/embedded`.
400
+ The configurator also creates `ci_scripts/ci_post_xcodebuild.sh`, a thin Xcode
401
+ Cloud lifecycle adapter that invokes the same `register-ios.sh`. The token is
402
+ shown only once and must never be committed or included in the mobile binary.
403
+ Verify registered binaries at `/updates/embedded`.
398
404
 
399
405
  ## Step 1. Install Expo Updates
400
406
 
@@ -568,7 +574,9 @@ npm run create-admin
568
574
  Опционально:
569
575
 
570
576
  - `OTA_PUBLIC_BASE_URL` - публичный URL OTA сервера (для `/api/manifest` и `/api/assets`)
571
- - `OTA_CDN_BASE_URL` - публичный CDN URL для прямой раздачи ассетов (например `https://cdn.cogitize.tech`)
577
+ - `OTA_CDN_BASE_URL` - устаревшая совместимая настройка; новые manifest
578
+ намеренно игнорируют её и выдают gated `/api/assets` URL, чтобы глобальный
579
+ аварийный выключатель нельзя было обойти прямой загрузкой из CDN
572
580
  - `OTA_SIGNED_URL_TTL` - TTL signed URL в секундах (по умолчанию `3600`)
573
581
  - `R2_REGION` - регион для S3 клиента (по умолчанию `auto`)
574
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
+ }
@@ -2,6 +2,9 @@ import { beforeEach, describe, expect, it, vi } from "vitest";
2
2
  import { NextRequest } from "next/server";
3
3
 
4
4
  const requireAdminAccess = vi.hoisted(() => vi.fn());
5
+ const listEmbeddedUpdates = vi.hoisted(() =>
6
+ vi.fn(async (): Promise<Array<Record<string, unknown>>> => []),
7
+ );
5
8
  const registerEmbeddedUpdate = vi.hoisted(() =>
6
9
  vi.fn(async (input) => ({
7
10
  ...input,
@@ -22,7 +25,7 @@ vi.mock("@/src/server/lib/admin-embedded-updates", async (importOriginal) => {
22
25
  >();
23
26
  return {
24
27
  ...original,
25
- listEmbeddedUpdates: vi.fn(async () => []),
28
+ listEmbeddedUpdates,
26
29
  registerEmbeddedUpdate,
27
30
  };
28
31
  });
@@ -51,6 +54,7 @@ describe("POST /api/admin/embedded-updates", () => {
51
54
  },
52
55
  body: JSON.stringify({
53
56
  id: "55555555-5555-4555-8555-555555555555",
57
+ appVersion: " 2.4.1 ",
54
58
  createdAt: "2026-01-01T00:00:00Z",
55
59
  channel: "Production",
56
60
  platform: "ios",
@@ -66,12 +70,43 @@ describe("POST /api/admin/embedded-updates", () => {
66
70
  );
67
71
  expect(registerEmbeddedUpdate).toHaveBeenCalledWith({
68
72
  embeddedUpdateId: "55555555-5555-4555-8555-555555555555",
73
+ appVersion: "2.4.1",
69
74
  createdAt: "2026-01-01T00:00:00.000Z",
70
75
  channel: "production",
71
76
  platform: "ios",
72
77
  });
73
78
  });
74
79
 
80
+ it("lists appVersion as a nullable per-update value", async () => {
81
+ requireAdminAccess.mockResolvedValue({
82
+ type: "access-token",
83
+ id: "token-id",
84
+ name: "admin",
85
+ scopes: ["updates:read"],
86
+ });
87
+ listEmbeddedUpdates.mockResolvedValueOnce([
88
+ {
89
+ embeddedUpdateId: "55555555-5555-4555-8555-555555555555",
90
+ appVersion: null,
91
+ createdAt: "2026-01-01T00:00:00.000Z",
92
+ channel: "production",
93
+ platform: "ios",
94
+ isEmbedded: true,
95
+ insertedAt: "2026-01-01T00:00:00.000Z",
96
+ modifiedAt: "2026-01-01T00:00:00.000Z",
97
+ },
98
+ ]);
99
+ const { GET } = await import("./route");
100
+ const response = await GET(
101
+ new NextRequest(
102
+ "https://updates.example.com/api/admin/embedded-updates",
103
+ ),
104
+ );
105
+
106
+ expect(response.status).toBe(200);
107
+ expect((await response.json()).items[0].appVersion).toBeNull();
108
+ });
109
+
75
110
  it("rejects invalid registration payloads", async () => {
76
111
  requireAdminAccess.mockResolvedValue({
77
112
  type: "access-token",
@@ -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
+ }