Skip to content

armgit / Cap

Public Imported from GitHub
0

Open source Loom alternative. Beautiful, shareable screen recordings.

test(web): add agent API fixtures and core unit tests

Richie McIlroy74e141c0d2c9
diff --git a/apps/web/__tests__/fixtures/agent-caps.ts b/apps/web/__tests__/fixtures/agent-caps.ts
new file mode 100644
index 000000000..87d689a63
--- /dev/null
+++ b/apps/web/__tests__/fixtures/agent-caps.ts
@@ -0,0 +1,86 @@
+export const syntheticAgentCaps = [
+ {
+ name: "owner-ready",
+ access: "owned",
+ public: true,
+ protected: false,
+ transcriptionStatus: "COMPLETE",
+ aiGenerationStatus: "COMPLETE",
+ durationMs: 188_000,
+ comments: 2,
+ reactions: 1,
+ },
+ {
+ name: "organization-share",
+ access: "shared",
+ public: false,
+ protected: false,
+ transcriptionStatus: "COMPLETE",
+ aiGenerationStatus: "COMPLETE",
+ durationMs: 420_000,
+ comments: 4,
+ reactions: 3,
+ },
+ {
+ name: "space-share",
+ access: "shared",
+ public: false,
+ protected: false,
+ transcriptionStatus: "PROCESSING",
+ aiGenerationStatus: "QUEUED",
+ durationMs: 94_000,
+ comments: 0,
+ reactions: 0,
+ },
+ {
+ name: "public-direct",
+ access: "shared",
+ public: true,
+ protected: false,
+ transcriptionStatus: "SKIPPED",
+ aiGenerationStatus: "SKIPPED",
+ durationMs: 42_000,
+ comments: 1,
+ reactions: 0,
+ },
+ {
+ name: "password-protected",
+ access: "shared",
+ public: true,
+ protected: true,
+ transcriptionStatus: "COMPLETE",
+ aiGenerationStatus: "COMPLETE",
+ durationMs: 610_000,
+ comments: 3,
+ reactions: 2,
+ },
+ {
+ name: "content-disabled",
+ access: "shared",
+ public: true,
+ protected: false,
+ transcriptionStatus: "COMPLETE",
+ aiGenerationStatus: "COMPLETE",
+ durationMs: 215_000,
+ comments: 0,
+ reactions: 0,
+ },
+ {
+ name: "processing-error",
+ access: "owned",
+ public: false,
+ protected: false,
+ transcriptionStatus: "ERROR",
+ aiGenerationStatus: "ERROR",
+ durationMs: 19_800_000,
+ comments: 0,
+ reactions: 0,
+ },
+] as const;
+
+export const makeSyntheticVtt = (targetBytes: number) => {
+ const header = "WEBVTT\n\n";
+ const cue =
+ "1\n00:00:00.000 --> 00:00:02.000\nSynthetic transcript content only.\n\n";
+ return `${header}${cue.repeat(Math.max(1, Math.ceil(targetBytes / cue.length)))}`;
+};
diff --git a/apps/web/__tests__/unit/agent-access-grant.test.ts b/apps/web/__tests__/unit/agent-access-grant.test.ts
new file mode 100644
index 000000000..2813ac20e
--- /dev/null
+++ b/apps/web/__tests__/unit/agent-access-grant.test.ts
@@ -0,0 +1,53 @@
+import { User, Video } from "@cap/web-domain";
+import { describe, expect, it, vi } from "vitest";
+import { validateAgentAccessGrantPayload } from "@/lib/agent-access-grant";
+
+vi.mock("server-only", () => ({}));
+
+const videoId = Video.VideoId.make("cap_synthetic_grant");
+const userId = User.UserId.make("user_synthetic_grant");
+
+describe("agent access grants", () => {
+ it("accepts only a live grant bound to the same user and Cap", () => {
+ const value = {
+ videoId,
+ userId,
+ passwordHash: "h".repeat(64),
+ expiresAt: "2026-07-18T18:30:00.000Z",
+ };
+ expect(
+ validateAgentAccessGrantPayload(
+ value,
+ videoId,
+ userId,
+ Date.parse("2026-07-18T18:20:00.000Z"),
+ ),
+ ).toMatchObject({ passwordHash: "h".repeat(64) });
+ expect(
+ validateAgentAccessGrantPayload(
+ value,
+ videoId,
+ User.UserId.make("different_user"),
+ Date.parse("2026-07-18T18:20:00.000Z"),
+ ),
+ ).toBeNull();
+ expect(
+ validateAgentAccessGrantPayload(
+ value,
+ videoId,
+ userId,
+ Date.parse("2026-07-18T18:31:00.000Z"),
+ ),
+ ).toBeNull();
+ });
+
+ it("rejects malformed payloads without exposing their contents", () => {
+ expect(
+ validateAgentAccessGrantPayload(
+ { videoId, userId, passwordHash: "short", expiresAt: "invalid" },
+ videoId,
+ userId,
+ ),
+ ).toBeNull();
+ });
+});
diff --git a/apps/web/__tests__/unit/agent-api.test.ts b/apps/web/__tests__/unit/agent-api.test.ts
new file mode 100644
index 000000000..ce3bebf23
--- /dev/null
+++ b/apps/web/__tests__/unit/agent-api.test.ts
@@ -0,0 +1,165 @@
+import { Agent, Video } from "@cap/web-domain";
+import { Schema } from "effect";
+import { describe, expect, it } from "vitest";
+import {
+ agentCapabilities,
+ agentStatus,
+ agentTranscriptRevision,
+ decodeAgentCursor,
+ encodeAgentCursor,
+ parseAgentDate,
+ parseAgentLimit,
+ parseAgentVtt,
+ renderAgentVtt,
+ safeDownloadFileName,
+ transcriptTextFromCues,
+} from "@/lib/agent-api";
+import { makeSyntheticVtt, syntheticAgentCaps } from "../fixtures/agent-caps";
+
+describe("agent API normalization", () => {
+ it("pins pagination defaults and opaque cursor round trips", () => {
+ expect(parseAgentLimit(undefined)).toBe(50);
+ expect(parseAgentLimit("250")).toBe(100);
+ expect(parseAgentLimit("0")).toBeNull();
+ expect(parseAgentLimit("nope")).toBeNull();
+
+ const cursor = {
+ updatedAt: "2026-07-18T12:00:00.000Z",
+ id: "cap_synthetic_1",
+ };
+ expect(decodeAgentCursor(encodeAgentCursor(cursor))).toEqual(cursor);
+ expect(decodeAgentCursor("not-a-cursor")).toBeUndefined();
+ expect(decodeAgentCursor("a".repeat(1_025))).toBeUndefined();
+ expect(
+ decodeAgentCursor(
+ Buffer.from(
+ JSON.stringify({ updatedAt: cursor.updatedAt, id: "bad id" }),
+ ).toString("base64url"),
+ ),
+ ).toBeUndefined();
+ });
+
+ it("accepts only valid ISO-compatible updated-after values", () => {
+ expect(parseAgentDate(undefined)).toBeNull();
+ expect(parseAgentDate("2026-07-18T12:00:00Z")?.toISOString()).toBe(
+ "2026-07-18T12:00:00.000Z",
+ );
+ expect(parseAgentDate("not-a-date")).toBeUndefined();
+ expect(parseAgentDate("2026-07-18T13:00:00+01:00")).toBeUndefined();
+ expect(parseAgentDate("2026-02-30T12:00:00Z")).toBeUndefined();
+ });
+
+ it("normalizes VTT into millisecond cues and text", () => {
+ const cues = parseAgentVtt(
+ "WEBVTT\r\n\r\n1\r\n00:00:01.250 --> 00:00:03.500 align:start\r\nHello <b>agent</b>\r\n\r\n2\r\n00:00:04,000 --> 00:00:05,125\r\nSecond line\r\n",
+ );
+
+ expect(cues).toEqual([
+ { startMs: 1_250, endMs: 3_500, text: "Hello agent" },
+ { startMs: 4_000, endMs: 5_125, text: "Second line" },
+ ]);
+ expect(transcriptTextFromCues(cues)).toBe("Hello agent\nSecond line");
+ const rendered = renderAgentVtt(cues);
+ expect(parseAgentVtt(rendered)).toEqual(cues);
+ expect(agentTranscriptRevision(rendered)).toMatch(/^[a-f0-9]{64}$/);
+ });
+
+ it("handles representative and large synthetic transcript shapes", () => {
+ for (const bytes of [10_000, 100_000, 500_000]) {
+ const vtt = makeSyntheticVtt(bytes);
+ expect(vtt.length).toBeGreaterThanOrEqual(bytes);
+ expect(parseAgentVtt(vtt).length).toBeGreaterThan(0);
+ }
+ });
+
+ it("reports content and mutation capabilities without inference", () => {
+ const capabilities = agentCapabilities({
+ isOwner: false,
+ hasReadScope: true,
+ hasCommentScope: true,
+ hasWriteScope: true,
+ hasProcessScope: true,
+ hasDeleteScope: true,
+ passwordRequired: false,
+ transcriptStatus: "COMPLETE",
+ hasSummary: true,
+ hasChapters: true,
+ settings: {
+ disableSummary: false,
+ disableChapters: false,
+ disableTranscript: true,
+ disableComments: false,
+ disableReactions: true,
+ },
+ });
+
+ expect(capabilities.transcript).toEqual({
+ allowed: false,
+ reason: "CONTENT_DISABLED",
+ });
+ expect(capabilities.editTitle).toEqual({
+ allowed: false,
+ reason: "OWNER_ONLY",
+ });
+ expect(capabilities.comment.allowed).toBe(true);
+ expect(capabilities.react.reason).toBe("CONTENT_DISABLED");
+ expect(
+ Schema.decodeUnknownSync(Agent.AgentCapabilities)(capabilities),
+ ).toEqual(capabilities);
+ });
+
+ it("locks every read and write surface for protected shared Caps", () => {
+ const capabilities = agentCapabilities({
+ isOwner: false,
+ hasReadScope: true,
+ hasCommentScope: true,
+ hasWriteScope: true,
+ hasProcessScope: true,
+ hasDeleteScope: true,
+ passwordRequired: true,
+ transcriptStatus: "COMPLETE",
+ hasSummary: true,
+ hasChapters: true,
+ settings: {
+ disableSummary: false,
+ disableChapters: false,
+ disableTranscript: false,
+ disableComments: false,
+ disableReactions: false,
+ },
+ });
+
+ for (const value of Object.values(capabilities)) {
+ expect(value).toEqual({
+ allowed: false,
+ reason: "PASSWORD_REQUIRED",
+ });
+ }
+ });
+
+ it("maps processing states without starting work", () => {
+ const fixture = syntheticAgentCaps.find(
+ (cap) => cap.name === "space-share",
+ );
+ expect(fixture).toBeDefined();
+ const status = agentStatus({
+ id: Video.VideoId.make("cap_synthetic_processing"),
+ updatedAt: new Date("2026-07-18T12:00:00.000Z"),
+ transcriptionStatus: fixture?.transcriptionStatus ?? null,
+ aiGenerationStatus: fixture?.aiGenerationStatus,
+ uploadPhase: "complete",
+ uploadError: null,
+ });
+
+ expect(status.overall).toBe("processing");
+ expect(status.transcript.status).toBe("processing");
+ expect(status.ai.status).toBe("queued");
+ });
+
+ it("creates portable download names", () => {
+ expect(safeDownloadFileName(" Q3: Roadmap / review? ")).toBe(
+ "Q3-Roadmap-review.mp4",
+ );
+ expect(safeDownloadFileName("🔥")).toBe("cap-recording.mp4");
+ });
+});
diff --git a/apps/web/__tests__/unit/agent-auth.test.ts b/apps/web/__tests__/unit/agent-auth.test.ts
new file mode 100644
index 000000000..9421241c5
--- /dev/null
+++ b/apps/web/__tests__/unit/agent-auth.test.ts
@@ -0,0 +1,157 @@
+import { createHash } from "node:crypto";
+import { isLegacyAgentKeySource } from "@cap/web-backend";
+import { describe, expect, it } from "vitest";
+import {
+ buildAgentCallbackUrl,
+ createAgentAccessToken,
+ hashAgentSecret,
+ isAgentCodeVerifier,
+ isAgentLoopbackRedirectUri,
+ isAgentReadAccessEnabled,
+ parseAgentAuthorizationRequest,
+ parseAgentScopes,
+ verifyAgentCodeChallenge,
+} from "@/lib/agent-auth";
+
+const state = "s".repeat(43);
+const verifier = "v".repeat(43);
+const challenge = createHash("sha256").update(verifier).digest("base64url");
+
+describe("agent browser authorization", () => {
+ it("only accepts explicit loopback callback URLs", () => {
+ expect(isAgentLoopbackRedirectUri("http://127.0.0.1:49152/callback")).toBe(
+ true,
+ );
+ expect(isAgentLoopbackRedirectUri("http://[::1]:49152/callback")).toBe(
+ true,
+ );
+ for (const value of [
+ "https://127.0.0.1:49152/callback",
+ "http://localhost:49152/callback",
+ "http://127.0.0.1/callback",
+ "http://127.0.0.1:49152/other",
+ "http://127.0.0.1:49152/callback?next=https://example.com",
+ "http://example.com:49152/callback",
+ ]) {
+ expect(isAgentLoopbackRedirectUri(value)).toBe(false);
+ }
+ });
+
+ it("requires PKCE S256, state, and known scopes", () => {
+ const request = parseAgentAuthorizationRequest({
+ client_id: "cap-cli",
+ redirect_uri: "http://127.0.0.1:49152/callback",
+ response_type: "code",
+ state,
+ code_challenge: challenge,
+ code_challenge_method: "S256",
+ scope: "caps:read caps:comment",
+ });
+ expect(request).toMatchObject({
+ clientId: "cap-cli",
+ scopes: ["caps:read", "caps:comment"],
+ });
+ expect(
+ parseAgentAuthorizationRequest({
+ client_id: "cap-cli",
+ redirect_uri: "http://127.0.0.1:49152/callback",
+ response_type: "code",
+ state,
+ code_challenge: challenge,
+ code_challenge_method: "plain",
+ scope: "caps:read",
+ }),
+ ).toBeNull();
+ expect(parseAgentScopes("caps:comment")).toBeNull();
+ expect(parseAgentScopes("caps:read unknown")).toBeNull();
+ expect(
+ parseAgentScopes(
+ "caps:read caps:upload library:write organizations:manage developer:secrets",
+ ),
+ ).toEqual([
+ "caps:read",
+ "caps:upload",
+ "library:write",
+ "organizations:manage",
+ "developer:secrets",
+ ]);
+ });
+
+ it("verifies the RFC 7636 challenge", () => {
+ expect(isAgentCodeVerifier(verifier)).toBe(true);
+ expect(verifyAgentCodeChallenge(verifier, challenge)).toBe(true);
+ expect(verifyAgentCodeChallenge("x".repeat(43), challenge)).toBe(false);
+ });
+
+ it("builds a callback without accepting an open redirect", () => {
+ const callback = buildAgentCallbackUrl("http://127.0.0.1:49152/callback", {
+ state,
+ code: "one-time-code",
+ });
+ expect(callback).toBe(
+ `http://127.0.0.1:49152/callback?state=${state}&code=one-time-code`,
+ );
+ expect(
+ buildAgentCallbackUrl("https://example.com/callback", {
+ state,
+ code: "code",
+ }),
+ ).toBeNull();
+ });
+
+ it("hashes credentials and never embeds the raw value", () => {
+ const token = createAgentAccessToken();
+ expect(token).toMatch(/^cap_cli_[A-Za-z0-9_-]{43}$/);
+ expect(hashAgentSecret(token)).toMatch(/^[a-f0-9]{64}$/);
+ expect(hashAgentSecret(token)).not.toContain(token);
+ });
+});
+
+describe("agent API dark launch", () => {
+ it("requires both the production switch and exact allowlist membership", () => {
+ expect(
+ isAgentReadAccessEnabled({
+ nodeEnv: "production",
+ enabled: "true",
+ allowlist: "[email protected]",
+ email: "[email protected]",
+ }),
+ ).toBe(true);
+ expect(
+ isAgentReadAccessEnabled({
+ nodeEnv: "production",
+ enabled: "false",
+ allowlist: "[email protected]",
+ email: "[email protected]",
+ }),
+ ).toBe(false);
+ expect(
+ isAgentReadAccessEnabled({
+ nodeEnv: "production",
+ enabled: "true",
+ allowlist: "[email protected]",
+ email: "[email protected]",
+ }),
+ ).toBe(false);
+ });
+
+ it("stays available in local and test environments", () => {
+ expect(
+ isAgentReadAccessEnabled({
+ nodeEnv: "test",
+ enabled: undefined,
+ allowlist: undefined,
+ email: "[email protected]",
+ }),
+ ).toBe(true);
+ });
+});
+
+describe("legacy agent credentials", () => {
+ it("accepts desktop-era keys without extending mobile or extension keys", () => {
+ expect(isLegacyAgentKeySource("desktop")).toBe(true);
+ expect(isLegacyAgentKeySource("unknown")).toBe(true);
+ expect(isLegacyAgentKeySource("mobile")).toBe(false);
+ expect(isLegacyAgentKeySource("extension")).toBe(false);
+ });
+});
diff --git a/apps/web/__tests__/unit/agent-management.test.ts b/apps/web/__tests__/unit/agent-management.test.ts
new file mode 100644
index 000000000..211a6e1c8
--- /dev/null
+++ b/apps/web/__tests__/unit/agent-management.test.ts
@@ -0,0 +1,88 @@
+import { describe, expect, it } from "vitest";
+import {
+ decodeNotificationCursor,
+ encodeNotificationCursor,
+ libraryCapabilities,
+ normalizeOrganization,
+ organizationCapabilities,
+ profileCapabilities,
+} from "@/lib/agent-management";
+
+describe("agent management capabilities", () => {
+ it("requires both scope and organization role", () => {
+ const scopes = new Set([
+ "organizations:read",
+ "organizations:manage",
+ "organizations:members",
+ "billing:write",
+ ] as const);
+ const member = organizationCapabilities("member", scopes);
+ expect(member.read.allowed).toBe(true);
+ expect(member.update).toMatchObject({
+ allowed: false,
+ reason: "ROLE_REQUIRED",
+ });
+ const owner = organizationCapabilities("owner", scopes);
+ expect(owner.update.allowed).toBe(true);
+ expect(owner.manageBilling).toMatchObject({
+ allowed: true,
+ confirmation: "browser",
+ sideEffect: "paid",
+ });
+ });
+
+ it("keeps read, write, and destructive metadata explicit", () => {
+ const scopes = new Set(["profile:read", "library:write"] as const);
+ expect(profileCapabilities(scopes).read).toMatchObject({
+ allowed: true,
+ sideEffect: "read",
+ idempotencyRequired: false,
+ });
+ expect(libraryCapabilities(true, scopes).delete).toMatchObject({
+ allowed: true,
+ confirmation: "user",
+ sideEffect: "destructive",
+ idempotencyRequired: true,
+ });
+ });
+
+ it("normalizes organization settings and billing without secrets", () => {
+ const result = normalizeOrganization(
+ {
+ id: "org_test" as never,
+ name: "Test",
+ ownerId: "user_test" as never,
+ role: "owner",
+ hasProSeat: true,
+ allowedEmailDomain: null,
+ customDomain: "caps.example.com",
+ domainVerifiedAt: new Date("2026-01-01T00:00:00.000Z"),
+ settings: { disableTranscript: true },
+ icon: null,
+ shareableLinkIcon: null,
+ ownerSubscriptionStatus: "active",
+ ownerThirdPartySubscriptionId: null,
+ createdAt: new Date("2025-01-01T00:00:00.000Z"),
+ updatedAt: new Date("2026-01-01T00:00:00.000Z"),
+ },
+ new Set(["organizations:read"]),
+ );
+ expect(result.billing).toEqual({ status: "active", plan: "pro" });
+ expect(result.settings.disableTranscript).toBe(true);
+ expect(JSON.stringify(result)).not.toContain("stripeCustomerId");
+ });
+});
+
+describe("notification cursor", () => {
+ it("round trips opaque cursors and rejects tampering", () => {
+ const cursor = {
+ createdAt: new Date("2026-01-01T00:00:00.000Z"),
+ id: "notification_1",
+ };
+ expect(decodeNotificationCursor(encodeNotificationCursor(cursor))).toEqual(
+ cursor,
+ );
+ expect(decodeNotificationCursor("not-a-cursor")).toBeUndefined();
+ expect(decodeNotificationCursor("a".repeat(1_025))).toBeUndefined();
+ });
+});