Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
test(web): add agent API contract and handler tests
Richie McIlroy143c008e0470
diff --git a/apps/web/__tests__/unit/agent-api-contract.test.ts b/apps/web/__tests__/unit/agent-api-contract.test.tsnew file mode 100644index 000000000..68e9b184d--- /dev/null+++ b/apps/web/__tests__/unit/agent-api-contract.test.ts@@ -0,0 +1,496 @@+import { readFileSync } from "node:fs";+import { join } from "node:path";+import { Agent, Organisation, User, Video } from "@cap/web-domain";+import { Schema } from "effect";+import { describe, expect, it } from "vitest";++const capability = { allowed: true, reason: null } as const;++const status = {+ id: Video.VideoId.make("cap_synthetic_1"),+ overall: "ready" as const,+ upload: { status: "complete" as const, reason: null, retryable: false },+ transcript: { status: "complete" as const, reason: null, retryable: false },+ ai: { status: "complete" as const, reason: null, retryable: false },+ updatedAt: "2026-07-18T12:00:00.000Z",+};++describe("agent API contract", () => {+ it("verifies credentials online and rate limits authorization boundaries", () => {+ const contract = readFileSync(+ join(process.cwd(), "../../packages/web-domain/src/Agent.ts"),+ "utf8",+ );+ const route = readFileSync(+ join(process.cwd(), "app/api/v1/[...route]/route.ts"),+ "utf8",+ );+ const authorize = readFileSync(+ join(process.cwd(), "app/cli/authorize/page.tsx"),+ "utf8",+ );+ expect(contract).toContain('HttpApiEndpoint.get("getAuthStatus"');+ expect(route).toContain('.handle("getAuthStatus"');+ expect(route).toContain("RATE_LIMIT_IDS.AGENT_TOKEN_EXCHANGE");+ expect(authorize).toContain("RATE_LIMIT_IDS.AGENT_AUTHORIZATION");+ });++ it("keeps every GET handler free of processing and mutation entry points", () => {+ const source = readFileSync(+ join(process.cwd(), "app/api/v1/[...route]/route.ts"),+ "utf8",+ );+ const readImplementationSource = source.slice(+ source.indexOf("const getViewableCap"),+ source.indexOf("const unlockCap"),+ );+ const readHandlerSource = source.slice(+ source.indexOf('.handle("listCaps"'),+ source.indexOf('.handle("unlockCap"'),+ );+ for (const forbidden of [+ "startVideoProcessingWorkflow",+ "generate-ai",+ "generateAi",+ "Workflows",+ ".putObject(",+ ".insert(",+ ".update(",+ ".delete(",+ ]) {+ expect(readImplementationSource).not.toContain(forbidden);+ expect(readHandlerSource).not.toContain(forbidden);+ }+ expect(source).toContain("export const GET = handler");+ expect(source).toContain("export const OPTIONS = handler");+ expect(source).toContain("export const POST = handler");+ expect(source).toContain("export const PATCH = handler");+ expect(source).toContain("export const PUT = handler");+ expect(source).toContain("export const DELETE = handler");+ });++ it("pins list execution to two bounded query phases", () => {+ const source = readFileSync(+ join(process.cwd(), "app/api/v1/[...route]/route.ts"),+ "utf8",+ );+ const listSource = source.slice(+ source.indexOf("const listCaps"),+ source.indexOf("const readTranscript"),+ );++ expect(listSource.match(/database\.use/g)).toHaveLength(1);+ expect(listSource.match(/getSpaceRules/g)).toHaveLength(1);+ expect(listSource).toContain(+ "union(ownedCaps, organizationCaps, spaceCaps)",+ );+ expect(listSource).not.toContain("Effect.forEach");+ expect(listSource).not.toContain("getThumbnailURL");+ expect(listSource).not.toContain("getAnalytics");+ expect(listSource).not.toContain("getSignedObjectUrl");+ });++ it("checks viewing policy before reading password hashes", () => {+ const source = readFileSync(+ join(process.cwd(), "app/api/v1/[...route]/route.ts"),+ "utf8",+ );+ const unlockSource = source.slice(+ source.indexOf("const unlockCap"),+ source.indexOf("const requireAgentWrites"),+ );++ expect(unlockSource.indexOf("getViewableVideo(videoId)")).toBeGreaterThan(+ -1,+ );+ expect(unlockSource.indexOf("getViewableVideo(videoId)")).toBeLessThan(+ unlockSource.indexOf("Db.videos.password"),+ );+ });++ it("decodes lightweight cap summaries without heavy media fields", () => {+ const decoded = Schema.decodeUnknownSync(Agent.AgentCapSummary)({+ id: Video.VideoId.make("cap_synthetic_1"),+ shareUrl: "https://cap.so/s/cap_synthetic_1",+ title: "Synthetic roadmap review",+ aiTitle: "Roadmap review",+ createdAt: "2026-07-18T11:00:00.000Z",+ updatedAt: "2026-07-18T12:00:00.000Z",+ durationMs: 188_000,+ owner: {+ id: User.UserId.make("user_synthetic_owner"),+ name: "Synthetic Owner",+ },+ organizationId: Organisation.OrganisationId.make("org_synthetic"),+ folderId: null,+ access: "owned",+ sharing: { public: true, protected: false },+ counts: { comments: 2, reactions: 1 },+ status,+ capabilities: {+ view: capability,+ summary: capability,+ chapters: capability,+ transcript: capability,+ comments: capability,+ reactions: capability,+ download: capability,+ comment: capability,+ react: capability,+ editTitle: capability,+ editVisibility: capability,+ processTranscript: capability,+ processAi: capability,+ editTranscript: capability,+ editPassword: capability,+ duplicate: capability,+ delete: capability,+ },+ });++ expect(decoded.id).toBe("cap_synthetic_1");+ expect(decoded).not.toHaveProperty("thumbnailUrl");+ expect(decoded).not.toHaveProperty("transcript");+ expect(decoded).not.toHaveProperty("downloadUrl");+ });++ it("pins structured retry metadata on stable errors", () => {+ const decoded = Schema.decodeUnknownSync(Agent.AgentApiError)({+ _tag: "AgentNotReadyError",+ code: "NOT_READY",+ message: "Transcript is not ready",+ retryable: true,+ retryAfterMs: 2_000,+ requestId: "request_synthetic_1",+ });++ expect(decoded.code).toBe("NOT_READY");+ expect(decoded.retryAfterMs).toBe(2_000);+ });++ it("keeps transcript format vocabulary stable", () => {+ for (const format of ["text", "json", "vtt"] as const) {+ expect(+ Schema.decodeUnknownSync(Agent.AgentTranscriptParams)({ format })+ .format,+ ).toBe(format);+ }+ expect(() =>+ Schema.decodeUnknownSync(Agent.AgentTranscriptParams)({ format: "srt" }),+ ).toThrow();+ });++ it("pins asynchronous destructive operation state", () => {+ const operation = Schema.decodeUnknownSync(Agent.AgentOperationResponse)({+ id: "operation_123",+ kind: "delete_cap",+ state: "running",+ resourceId: Video.VideoId.make("cap_synthetic_1"),+ resultResourceId: null,+ result: null,+ error: null,+ createdAt: "2026-07-18T12:00:00.000Z",+ updatedAt: "2026-07-18T12:00:01.000Z",+ completedAt: null,+ requestId: "request_synthetic_1",+ });++ expect(operation.state).toBe("running");+ });++ it("keeps destructive storage work retry-safe and confirmation-gated", () => {+ const route = readFileSync(+ join(process.cwd(), "app/api/v1/[...route]/route.ts"),+ "utf8",+ );+ const workflow = readFileSync(+ join(process.cwd(), "workflows/agent-cap-operation.ts"),+ "utf8",+ );+ expect(route).toContain('request.headers["x-cap-confirmation"]');+ expect(route).toContain("requireUserConfirmedRequest");+ expect(workflow.indexOf("await deleteCapObjects")).toBeLessThan(+ workflow.indexOf("await deleteCapDatabase"),+ );+ expect(workflow.indexOf("await copyCapObjects")).toBeLessThan(+ workflow.indexOf("await createDuplicate"),+ );+ });++ it("keeps organization hierarchy enforcement in agent member mutations", () => {+ const source = readFileSync(+ join(process.cwd(), "app/api/v1/[...route]/route.ts"),+ "utf8",+ );+ const memberSource = source.slice(+ source.indexOf('.handle("updateOrganizationMember"'),+ source.indexOf('.handle("updateMe"'),+ );+ expect(memberSource).toContain("canChangeOrganizationMemberRole");+ expect(memberSource).toContain("canRemoveOrganizationMember");+ expect(memberSource).toContain("Db.spaceMembers");+ });++ it("stores only developer key identifiers in idempotency responses", () => {+ const source = readFileSync(+ join(process.cwd(), "app/api/v1/[...route]/route.ts"),+ "utf8",+ );+ const developerSource = source.slice(+ source.indexOf('.handle("createDeveloperApp"'),+ source.indexOf('.handle("getOperation"'),+ );+ expect(developerSource).toContain(+ "response: { appId, publicKeyId, secretKeyId }",+ );+ expect(developerSource).not.toContain(+ "response: { appId, publicKey: publicKeyRaw",+ );+ expect(developerSource).toContain("readDeveloperCredentials");+ });++ it("keeps image and S3 secret material out of idempotency records", () => {+ const source = readFileSync(+ join(process.cwd(), "app/api/v1/[...route]/route.ts"),+ "utf8",+ );+ const imageSource = source.slice(+ source.indexOf("const updateAgentImage"),+ source.indexOf("const queueAgentCapOperation"),+ );+ const s3Source = source.slice(+ source.indexOf('.handle("updateOrganizationS3"'),+ source.indexOf('.handle("removeOrganizationS3"'),+ );++ expect(imageSource).toContain('sha256: createHash("sha256")');+ expect(imageSource).not.toContain("data: input.payload.data");+ expect(s3Source).toContain("accessKeyIdHash");+ expect(s3Source).toContain("secretAccessKeyHash");+ expect(s3Source).not.toContain("accessKeyId: config.accessKeyId");+ expect(s3Source).not.toContain("secretAccessKey: config.secretAccessKey");+ });++ it("delivers organization invites with provider idempotency", () => {+ const source = readFileSync(+ join(process.cwd(), "app/api/v1/[...route]/route.ts"),+ "utf8",+ );+ const inviteSource = source.slice(+ source.indexOf('.handle("createOrganizationInvite"'),+ source.indexOf('.handle("deleteOrganizationInvite"'),+ );++ expect(inviteSource).toContain("payload.sendEmail ?? true");+ expect(inviteSource).toContain(+ 'operation: "send_organization_invite_email"',+ );+ expect(inviteSource).toContain("idempotencyKey: providerIdempotencyKey");+ expect(inviteSource).toContain('emailDelivery: "accepted"');+ });++ it("requires explicit confirmation for agent-authored activity and metadata", () => {+ const source = readFileSync(+ join(process.cwd(), "app/api/v1/[...route]/route.ts"),+ "utf8",+ );+ const mutationSource = source.slice(+ source.indexOf('.handle("createComment"'),+ source.indexOf("const AgentManagementHandlersLive"),+ );++ expect(mutationSource.match(/requireUserConfirmedRequest/g)).toHaveLength(+ 4,+ );+ });++ it("advertises granular dashboard-parity confirmations", () => {+ const source = readFileSync(+ join(process.cwd(), "lib/agent-management.ts"),+ "utf8",+ );++ expect(source).toContain("createOrganization: scopedAction");+ expect(source).toContain("configureS3: scopedRoleAction");+ expect(source).toContain('confirmation: "secure_input"');+ expect(source).toContain("connectGoogleDrive: scopedRoleAction");+ expect(source).toContain("purchaseCredits: scopedAction");+ expect(source).toContain("signOutAllDevices: scopedAction");+ expect(source).toContain("openReferrals: scopedAction");+ });++ it("keeps normal Google Drive callbacks while isolating CLI completion", () => {+ const source = readFileSync(+ join(process.cwd(), "app/api/desktop/[...route]/storage.ts"),+ "utf8",+ );++ expect(source).toContain(+ 'const orgRedirectUrl = "/dashboard/settings/organization/integrations"',+ );+ expect(source).toContain(+ 'const agentSuccessRedirectUrl = "/cli/complete?googleDrive=connected"',+ );+ expect(source).toContain(+ 'const agentCancelledRedirectUrl = "/cli/complete?googleDrive=cancelled"',+ );+ expect(source).toContain("? agentSuccessRedirectUrl");+ expect(source).toContain("? agentCancelledRedirectUrl");+ });++ it("keeps developer video inventory bounded and secret-free", () => {+ const source = readFileSync(+ join(process.cwd(), "../../packages/web-backend/src/AgentManagement.ts"),+ "utf8",+ );+ const listSource = source.slice(+ source.indexOf("listDeveloperVideos: Effect.fn"),+ source.indexOf("listDeveloperTransactions: Effect.fn"),+ );++ expect(listSource).toContain(".limit(limit + 1)");+ expect(listSource).not.toContain("s3Key:");+ expect(listSource).not.toContain("metadata:");++ const decoded = Schema.decodeUnknownSync(+ Agent.AgentDeveloperVideosResponse,+ )({+ videos: [+ {+ id: "video_synthetic",+ appId: "app_synthetic",+ externalUserId: "customer_synthetic",+ name: "Synthetic SDK video",+ durationSeconds: 30,+ width: 1920,+ height: 1080,+ fps: 30,+ transcriptionStatus: "COMPLETE",+ createdAt: "2026-07-18T12:00:00.000Z",+ updatedAt: "2026-07-18T12:01:00.000Z",+ capabilities: {},+ },+ ],+ nextCursor: null,+ requestId: "request_synthetic",+ });+ expect(decoded.videos[0]?.id).toBe("video_synthetic");+ });++ it("validates and atomically merges public collection customization", () => {+ const source = readFileSync(+ join(process.cwd(), "app/api/v1/[...route]/route.ts"),+ "utf8",+ );+ const updateSource = source.slice(+ source.indexOf("const updateAgentCollectionPublicPage"),+ source.indexOf("const queueAgentCapOperation"),+ );++ expect(updateSource).toContain("AgentCollectionPublicPageInput");+ expect(updateSource).toContain("JSON_MERGE_PATCH");+ expect(updateSource).toContain("Cap Pro is required");+ expect(updateSource).toContain("getFolderAccess");+ expect(updateSource).toContain("getSpaceAccess");++ expect(+ Schema.decodeUnknownSync(Agent.AgentCollectionPublicPageInput)({+ public: true,+ title: "Synthetic collection",+ layout: "grid",+ gridColumns: 4,+ }),+ ).toMatchObject({ public: true, gridColumns: 4 });+ expect(() =>+ Schema.decodeUnknownSync(Agent.AgentCollectionPublicPageInput)({+ gridColumns: 6,+ }),+ ).toThrow();++ const publicPage = {+ title: "Synthetic collection",+ layout: "grid" as const,+ gridColumns: 4 as const,+ };+ const folderResponse = Schema.decodeUnknownSync(Agent.AgentFoldersResponse)(+ {+ folders: [+ {+ id: "folder_synthetic",+ name: "Synthetic folder",+ color: "normal",+ public: true,+ organizationId: "org_synthetic",+ createdById: "user_synthetic",+ parentId: null,+ spaceId: null,+ settings: { publicPage },+ publicPage,+ createdAt: "2026-07-18T12:00:00.000Z",+ updatedAt: "2026-07-18T12:00:00.000Z",+ capabilities: {},+ },+ ],+ requestId: "request_synthetic",+ },+ );+ const spaceResponse = Schema.decodeUnknownSync(Agent.AgentSpacesResponse)({+ spaces: [+ {+ id: "space_synthetic",+ name: "Synthetic space",+ description: null,+ organizationId: "org_synthetic",+ createdById: "user_synthetic",+ primary: false,+ privacy: "Public",+ public: true,+ protected: false,+ icon: null,+ settings: {+ disableSummary: null,+ disableCaptions: null,+ disableChapters: null,+ disableReactions: null,+ disableTranscript: null,+ disableComments: null,+ defaultPlaybackSpeed: null,+ },+ publicPage,+ role: "admin",+ counts: { members: 1, caps: 2, folders: 3 },+ createdAt: "2026-07-18T12:00:00.000Z",+ updatedAt: "2026-07-18T12:00:00.000Z",+ capabilities: {},+ },+ ],+ requestId: "request_synthetic",+ });++ expect(folderResponse.folders[0]?.publicPage).toEqual(publicPage);+ expect(spaceResponse.spaces[0]?.publicPage).toEqual(publicPage);+ });++ it("queues Loom imports without persisting download URLs", () => {+ const route = readFileSync(+ join(process.cwd(), "app/api/v1/[...route]/route.ts"),+ "utf8",+ );+ const workflow = readFileSync(+ join(process.cwd(), "workflows/import-loom-video.ts"),+ "utf8",+ );+ const importSource = route.slice(+ route.indexOf("const queueAgentLoomImport"),+ route.indexOf("const normalizeTranscriptCues"),+ );++ expect(importSource).toContain('operation: "import_loom"');+ expect(importSource).toContain('kind: "import_loom"');+ expect(importSource).toContain("agentOperationId: operationId");+ expect(importSource).not.toContain("loomDownloadUrl:");+ expect(workflow).toContain("claimAgentImport");+ expect(workflow).toContain("completeAgentImport");+ expect(workflow).toContain("failAgentImport");+ });+});diff --git a/apps/web/__tests__/unit/agent-api-handler.test.ts b/apps/web/__tests__/unit/agent-api-handler.test.tsnew file mode 100644index 000000000..d63116e18--- /dev/null+++ b/apps/web/__tests__/unit/agent-api-handler.test.ts@@ -0,0 +1,263 @@+import { beforeAll, describe, expect, it, vi } from "vitest";++vi.mock("server-only", () => ({}));+const isRateLimited = vi.hoisted(() => vi.fn(async () => false));+vi.mock("@/lib/rate-limit", () => ({+ isRateLimited,+ RATE_LIMIT_IDS: {+ AGENT_TOKEN_EXCHANGE: "rl_agent_token_exchange",+ AGENT_AUTHORIZATION: "rl_agent_authorization",+ AGENT_UNLOCK: "rl_agent_unlock",+ AGENT_LOOM_IMPORT: "rl_loom_import_per_user",+ },+}));++describe("agent API handler", () => {+ let GET: typeof import("@/app/api/v1/[...route]/route").GET;+ let OPTIONS: typeof import("@/app/api/v1/[...route]/route").OPTIONS;+ let POST: typeof import("@/app/api/v1/[...route]/route").POST;+ let PATCH: typeof import("@/app/api/v1/[...route]/route").PATCH;+ let PUT: typeof import("@/app/api/v1/[...route]/route").PUT;+ let DELETE: typeof import("@/app/api/v1/[...route]/route").DELETE;++ beforeAll(async () => {+ Object.assign(process.env, {+ NEXT_PUBLIC_WEB_URL: "http://localhost",+ WEB_URL: "http://localhost",+ DATABASE_URL: "mysql://unused:[email protected]:3306/unused",+ NEXTAUTH_SECRET: "synthetic-test-secret-that-is-long-enough",+ NEXTAUTH_URL: "http://localhost",+ CAP_AWS_BUCKET: "synthetic",+ CAP_AWS_REGION: "us-east-1",+ CAP_AWS_ACCESS_KEY: "synthetic",+ CAP_AWS_SECRET_KEY: "synthetic",+ NODE_ENV: "test",+ });+ const route = await import("@/app/api/v1/[...route]/route");+ GET = route.GET;+ OPTIONS = route.OPTIONS;+ POST = route.POST;+ PATCH = route.PATCH;+ PUT = route.PUT;+ DELETE = route.DELETE;+ });++ it("handles CORS preflight without authentication", async () => {+ const response = await OPTIONS(+ new Request("http://localhost/api/v1/caps", {+ method: "OPTIONS",+ headers: {+ Origin: "http://localhost",+ "Access-Control-Request-Method": "GET",+ "Access-Control-Request-Headers": "x-cap-confirmation",+ },+ }),+ );+ expect(response.status).toBeLessThan(400);+ expect(response.headers.get("access-control-allow-headers")).toContain(+ "X-Cap-Confirmation",+ );+ });++ it("returns the stable authentication error without a credential", async () => {+ for (const path of ["/api/v1/caps", "/api/v1/auth/status"]) {+ const response = await GET(new Request(`http://localhost${path}`));+ const body = await response.json();++ expect(response.status).toBe(401);+ expect(body).toMatchObject({+ _tag: "AgentAuthenticationError",+ code: "AUTH_REQUIRED",+ retryable: false,+ retryAfterMs: null,+ });+ expect(body.requestId).toEqual(expect.any(String));+ }+ });++ it("rate limits unauthenticated authorization-code exchange before database access", async () => {+ isRateLimited.mockResolvedValueOnce(true);+ const response = await POST(+ new Request("http://localhost/api/v1/auth/token", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ code: "c".repeat(43),+ codeVerifier: "v".repeat(43),+ redirectUri: "http://127.0.0.1:49152/callback",+ }),+ }),+ );+ const body = await response.json();+ expect(response.status).toBe(429);+ expect(body).toMatchObject({+ code: "RATE_LIMITED",+ retryable: true,+ retryAfterMs: 60_000,+ });+ });++ it("authenticates unlocks and mutations before executing them", async () => {+ const requests = [+ POST(+ new Request("http://localhost/api/v1/caps/cap_synthetic/unlock", {+ method: "POST",+ headers: { "Content-Type": "text/plain" },+ body: "not-a-real-password",+ }),+ ),+ POST(+ new Request("http://localhost/api/v1/caps/cap_synthetic/comments", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ content: "Synthetic comment" }),+ }),+ ),+ PATCH(+ new Request("http://localhost/api/v1/caps/cap_synthetic", {+ method: "PATCH",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ title: "Synthetic title" }),+ }),+ ),+ PUT(+ new Request("http://localhost/api/v1/caps/cap_synthetic/password", {+ method: "PUT",+ headers: { "Content-Type": "text/plain" },+ body: "not-a-real-password",+ }),+ ),+ DELETE(+ new Request("http://localhost/api/v1/caps/cap_synthetic", {+ method: "DELETE",+ }),+ ),+ PUT(+ new Request("http://localhost/api/v1/me/image", {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ data: "c3ludGhldGlj",+ contentType: "image/png",+ fileName: "synthetic.png",+ }),+ }),+ ),+ POST(+ new Request("http://localhost/api/v1/me/sign-out-all", {+ method: "POST",+ }),+ ),+ POST(+ new Request("http://localhost/api/v1/me/referrals", {+ method: "POST",+ }),+ ),+ POST(+ new Request("http://localhost/api/v1/organizations", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ name: "Synthetic organization" }),+ }),+ ),+ POST(+ new Request(+ "http://localhost/api/v1/organizations/org_synthetic/billing/checkout",+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ interval: "yearly" }),+ },+ ),+ ),+ PUT(+ new Request(+ "http://localhost/api/v1/organizations/org_synthetic/storage/s3",+ {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ provider: "aws",+ accessKeyId: "synthetic",+ secretAccessKey: "synthetic",+ endpoint: "https://s3.amazonaws.com",+ bucketName: "synthetic",+ region: "us-east-1",+ }),+ },+ ),+ ),+ POST(+ new Request(+ "http://localhost/api/v1/organizations/org_synthetic/storage/google-drive/connect",+ { method: "POST" },+ ),+ ),+ POST(+ new Request(+ "http://localhost/api/v1/developer/apps/app_synthetic/credits/checkout",+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ amountCents: 1_000 }),+ },+ ),+ ),+ POST(+ new Request(+ "http://localhost/api/v1/organizations/org_synthetic/imports/loom",+ {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ loomUrl: "https://www.loom.com/share/synthetic",+ }),+ },+ ),+ ),+ GET(+ new Request(+ "http://localhost/api/v1/developer/apps/app_synthetic/videos",+ ),+ ),+ GET(+ new Request(+ "http://localhost/api/v1/developer/apps/app_synthetic/transactions",+ ),+ ),+ DELETE(+ new Request(+ "http://localhost/api/v1/developer/apps/app_synthetic/videos/video_synthetic",+ { method: "DELETE" },+ ),+ ),+ PATCH(+ new Request(+ "http://localhost/api/v1/folders/folder_synthetic/public-page",+ {+ method: "PATCH",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({ title: "Synthetic collection" }),+ },+ ),+ ),+ PUT(+ new Request("http://localhost/api/v1/spaces/space_synthetic/logo", {+ method: "PUT",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify({+ data: "c3ludGhldGlj",+ contentType: "image/png",+ fileName: "synthetic.png",+ }),+ }),+ ),+ ];+ for (const request of requests) {+ const response = await request;+ const body = await response.json();+ expect(response.status).toBe(401);+ expect(body.code).toBe("AUTH_REQUIRED");+ }+ });+});diff --git a/apps/web/__tests__/unit/agent-token-contract.test.ts b/apps/web/__tests__/unit/agent-token-contract.test.tsnew file mode 100644index 000000000..422e67142--- /dev/null+++ b/apps/web/__tests__/unit/agent-token-contract.test.ts@@ -0,0 +1,36 @@+import { readFileSync } from "node:fs";+import { join } from "node:path";+import { describe, expect, it } from "vitest";++describe("agent token storage contract", () => {+ const source = readFileSync(+ join(process.cwd(), "lib/agent-token.ts"),+ "utf8",+ );++ it("consumes authorization codes atomically before issuing a token", () => {+ expect(source).toContain("verifyAgentCodeChallenge");+ expect(source).toContain(+ "isNull(Db.agentApiAuthorizationCodes.consumedAt)",+ );+ expect(source).toContain(+ "gt(Db.agentApiAuthorizationCodes.expiresAt, now)",+ );+ expect(source).toContain("getAffectedRows(consumed) !== 1");+ expect(source.indexOf("getAffectedRows(consumed) !== 1")).toBeLessThan(+ source.indexOf("createAgentAccessToken()"),+ );+ });++ it("stores only hashes of grants and access tokens", () => {+ expect(source).toMatch(/codeHash,\s+hashAgentSecret\(payload\.code\)/);+ expect(source).toContain("tokenHash: hashAgentSecret(accessToken)");+ expect(source).not.toContain("accessToken: Db.agentApiKeys");+ expect(source).not.toContain("code: Db.agentApiAuthorizationCodes");+ });++ it("never revokes a legacy desktop credential", () => {+ expect(source).toContain('principal.tokenKind !== "agent"');+ expect(source).not.toContain("Db.authApiKeys");+ });+});diff --git a/apps/web/__tests__/unit/agent-write-contract.test.ts b/apps/web/__tests__/unit/agent-write-contract.test.tsnew file mode 100644index 000000000..c40c702e5--- /dev/null+++ b/apps/web/__tests__/unit/agent-write-contract.test.ts@@ -0,0 +1,62 @@+import { readFileSync } from "node:fs";+import { join } from "node:path";+import { describe, expect, it, vi } from "vitest";+import {+ isAgentIdempotencyKey,+ isAgentWriteAccessEnabled,+} from "@/lib/agent-write";++vi.mock("server-only", () => ({}));++describe("agent write safety", () => {+ it("requires a separate production write switch", () => {+ expect(+ isAgentWriteAccessEnabled({+ nodeEnv: "production",+ enabled: undefined,+ }),+ ).toBe(false);+ expect(+ isAgentWriteAccessEnabled({+ nodeEnv: "production",+ enabled: "true",+ }),+ ).toBe(true);+ expect(+ isAgentWriteAccessEnabled({ nodeEnv: "test", enabled: undefined }),+ ).toBe(true);+ });++ it("accepts bounded opaque idempotency keys", () => {+ expect(isAgentIdempotencyKey("0f64ed31-88d5-48bf-b364-a2af210dfa90")).toBe(+ true,+ );+ expect(isAgentIdempotencyKey("short")).toBe(false);+ expect(isAgentIdempotencyKey("contains a secret")).toBe(false);+ });++ it("completes the mutation and idempotency record in one transaction", () => {+ const source = readFileSync(+ join(process.cwd(), "lib/agent-write.ts"),+ "utf8",+ );+ expect(source).toContain('.for("update")');+ expect(source).toContain("completeIdempotency(tx");+ expect(source).toContain("releaseIdempotency(tx");+ expect(source).toContain('state: "complete"');+ expect(source).toContain("titleManuallyEdited: true");+ expect(source).not.toContain("console.log");+ });++ it("serializes external retries and releases failed attempts", () => {+ const source = readFileSync(+ join(process.cwd(), "lib/agent-write.ts"),+ "utf8",+ );+ expect(source).toContain('return { state: "pending" as const }');+ expect(source).toContain("Effect.tapErrorCause");+ expect(source).toContain(".delete(Db.agentApiIdempotency)");+ expect(source).toContain("record.expiresAt.getTime() <= Date.now()");+ expect(source).toContain('Schedule.exponential("25 millis")');+ });+});