Open source Loom alternative. Beautiful, shareable screen recordings.
Rust appcapcossloommacnextjsnextjs15open-sourceossreactrecordrustscreen-capturescreen-recorderscreenshotsolidjstauritauri-apptypescriptvite
test(web): add developer platform unit tests
Richie McIlroy933075b5746f
diff --git a/apps/web/__tests__/unit/developer-actions.test.ts b/apps/web/__tests__/unit/developer-actions.test.tsnew file mode 100644index 000000000..56a013e7b--- /dev/null+++ b/apps/web/__tests__/unit/developer-actions.test.ts@@ -0,0 +1,763 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++vi.mock("@cap/database", () => {+ const mockDb = {+ select: vi.fn(() => mockDb),+ insert: vi.fn(() => mockDb),+ update: vi.fn(() => mockDb),+ delete: vi.fn(() => mockDb),+ from: vi.fn(() => mockDb),+ set: vi.fn(() => mockDb),+ where: vi.fn(() => mockDb),+ limit: vi.fn(() => Promise.resolve([])),+ values: vi.fn(() => Promise.resolve()),+ transaction: vi.fn((fn) => fn(mockDb)),+ leftJoin: vi.fn(() => mockDb),+ orderBy: vi.fn(() => mockDb),+ offset: vi.fn(() => mockDb),+ };+ return {+ db: () => mockDb,+ __mockDb: mockDb,+ };+});++vi.mock("@cap/database/auth/session", () => ({+ getCurrentUser: vi.fn(),+}));++vi.mock("@cap/database/helpers", () => ({+ nanoId: vi.fn(() => "test-nano-id"),+ nanoIdLong: vi.fn(() => "test-nano-id-long-value"),+}));++vi.mock("@cap/database/schema", () => ({+ developerApps: {+ id: "id",+ ownerId: "ownerId",+ deletedAt: "deletedAt",+ },+ developerApiKeys: {+ id: "id",+ appId: "appId",+ keyType: "keyType",+ keyPrefix: "keyPrefix",+ keyHash: "keyHash",+ encryptedKey: "encryptedKey",+ revokedAt: "revokedAt",+ },+ developerAppDomains: {+ id: "id",+ appId: "appId",+ domain: "domain",+ },+ developerVideos: {+ id: "id",+ appId: "appId",+ deletedAt: "deletedAt",+ },+ developerCreditAccounts: {+ id: "id",+ appId: "appId",+ balanceMicroCredits: "balanceMicroCredits",+ autoTopUpEnabled: "autoTopUpEnabled",+ autoTopUpThresholdMicroCredits: "autoTopUpThresholdMicroCredits",+ autoTopUpAmountCents: "autoTopUpAmountCents",+ },+ developerCreditTransactions: {},+}));++vi.mock("@/lib/developer-key-hash", () => ({+ hashKey: vi.fn(() => Promise.resolve("mocked-hash-value")),+}));++vi.mock("next/cache", () => ({+ revalidatePath: vi.fn(),+}));++vi.mock("drizzle-orm", () => ({+ and: vi.fn((...args: unknown[]) => args),+ eq: vi.fn((field: unknown, value: unknown) => ({ field, value })),+ isNull: vi.fn((field: unknown) => ({ isNull: field })),+ sql: vi.fn(),+}));++import { __mockDb } from "@cap/database";+import { getCurrentUser } from "@cap/database/auth/session";++const mockGetCurrentUser = getCurrentUser as ReturnType<typeof vi.fn>;+const mockDb = __mockDb as Record<string, ReturnType<typeof vi.fn>>;++const mockUser = { id: "user-123", email: "[email protected]" };+const mockApp = {+ id: "app-456",+ ownerId: "user-123",+ name: "Test App",+ environment: "development",+ deletedAt: null,+};++function resetMockDb() {+ for (const key of Object.keys(mockDb)) {+ if (typeof mockDb[key]?.mockClear === "function") {+ mockDb[key].mockClear();+ }+ }+ mockDb.select.mockReturnValue(mockDb);+ mockDb.insert.mockReturnValue(mockDb);+ mockDb.update.mockReturnValue(mockDb);+ mockDb.delete.mockReturnValue(mockDb);+ mockDb.from.mockReturnValue(mockDb);+ mockDb.set.mockReturnValue(mockDb);+ mockDb.where.mockReturnValue(mockDb);+ mockDb.limit.mockReturnValue(Promise.resolve([]));+ mockDb.values.mockReturnValue(Promise.resolve());+ mockDb.leftJoin.mockReturnValue(mockDb);+ mockDb.orderBy.mockReturnValue(mockDb);+ mockDb.offset.mockReturnValue(mockDb);+ mockDb.transaction.mockImplementation((fn) => fn(mockDb));+}++describe("createDeveloperApp", () => {+ let createDeveloperApp: typeof import("@/actions/developers/create-app").createDeveloperApp;++ beforeEach(async () => {+ vi.clearAllMocks();+ resetMockDb();+ const mod = await import("@/actions/developers/create-app");+ createDeveloperApp = mod.createDeveloperApp;+ });++ it("throws Unauthorized when no user", async () => {+ mockGetCurrentUser.mockResolvedValue(null);+ await expect(+ createDeveloperApp({ name: "Test", environment: "development" }),+ ).rejects.toThrow("Unauthorized");+ });++ it("throws App name is required when empty name", async () => {+ mockGetCurrentUser.mockResolvedValue(mockUser);+ await expect(+ createDeveloperApp({ name: "", environment: "development" }),+ ).rejects.toThrow("App name is required");+ });++ it("throws App name is required when whitespace-only name", async () => {+ mockGetCurrentUser.mockResolvedValue(mockUser);+ await expect(+ createDeveloperApp({ name: " ", environment: "development" }),+ ).rejects.toThrow("App name is required");+ });++ it("creates app with trimmed name", async () => {+ mockGetCurrentUser.mockResolvedValue(mockUser);+ await createDeveloperApp({+ name: " My App ",+ environment: "production",+ });++ expect(mockDb.insert).toHaveBeenCalled();+ const firstValuesCall = mockDb.values.mock.calls[0][0];+ expect(firstValuesCall).toMatchObject({+ name: "My App",+ environment: "production",+ ownerId: "user-123",+ });+ });++ it("creates public key with cpk_ prefix", async () => {+ mockGetCurrentUser.mockResolvedValue(mockUser);+ const result = await createDeveloperApp({+ name: "Test",+ environment: "development",+ });+ expect(result.publicKey).toMatch(/^cpk_/);+ });++ it("creates secret key with csk_ prefix", async () => {+ mockGetCurrentUser.mockResolvedValue(mockUser);+ const result = await createDeveloperApp({+ name: "Test",+ environment: "development",+ });+ expect(result.secretKey).toMatch(/^csk_/);+ });++ it("creates credit account alongside app", async () => {+ mockGetCurrentUser.mockResolvedValue(mockUser);+ await createDeveloperApp({+ name: "Test",+ environment: "development",+ });++ expect(mockDb.insert).toHaveBeenCalledTimes(3);+ });++ it("returns appId, publicKey, secretKey", async () => {+ mockGetCurrentUser.mockResolvedValue(mockUser);+ const result = await createDeveloperApp({+ name: "Test",+ environment: "development",+ });++ expect(result).toHaveProperty("appId");+ expect(result).toHaveProperty("publicKey");+ expect(result).toHaveProperty("secretKey");+ expect(result.appId).toBe("test-nano-id");+ });++ it("public key prefix is first 12 chars", async () => {+ mockGetCurrentUser.mockResolvedValue(mockUser);+ const result = await createDeveloperApp({+ name: "Test",+ environment: "development",+ });++ const expectedPrefix = result.publicKey.slice(0, 12);+ const keysValuesCall = mockDb.values.mock.calls[1][0];+ const publicKeyEntry = keysValuesCall.find(+ (entry: Record<string, unknown>) => entry.keyType === "public",+ );+ expect(publicKeyEntry.keyPrefix).toBe(expectedPrefix);+ });+});++describe("deleteDeveloperApp", () => {+ let deleteDeveloperApp: typeof import("@/actions/developers/delete-app").deleteDeveloperApp;++ beforeEach(async () => {+ vi.clearAllMocks();+ resetMockDb();+ const mod = await import("@/actions/developers/delete-app");+ deleteDeveloperApp = mod.deleteDeveloperApp;+ });++ it("throws Unauthorized when no user", async () => {+ mockGetCurrentUser.mockResolvedValue(null);+ await expect(deleteDeveloperApp("app-456")).rejects.toThrow("Unauthorized");+ });++ it("throws App not found when app does not exist", async () => {+ mockGetCurrentUser.mockResolvedValue(mockUser);+ mockDb.limit.mockResolvedValue([]);+ await expect(deleteDeveloperApp("app-456")).rejects.toThrow(+ "App not found",+ );+ });++ it("soft deletes by setting deletedAt", async () => {+ mockGetCurrentUser.mockResolvedValue(mockUser);+ mockDb.limit.mockResolvedValueOnce([mockApp]);+ await deleteDeveloperApp("app-456");++ expect(mockDb.update).toHaveBeenCalled();+ expect(mockDb.set).toHaveBeenCalledWith(+ expect.objectContaining({ deletedAt: expect.any(Date) }),+ );+ });++ it("returns success true", async () => {+ mockGetCurrentUser.mockResolvedValue(mockUser);+ mockDb.limit.mockResolvedValueOnce([mockApp]);+ const result = await deleteDeveloperApp("app-456");+ expect(result).toEqual({ success: true });+ });+});++describe("updateDeveloperApp", () => {+ let updateDeveloperApp: typeof import("@/actions/developers/update-app").updateDeveloperApp;++ beforeEach(async () => {+ vi.clearAllMocks();+ resetMockDb();+ const mod = await import("@/actions/developers/update-app");+ updateDeveloperApp = mod.updateDeveloperApp;+ });++ it("throws Unauthorized when no user", async () => {+ mockGetCurrentUser.mockResolvedValue(null);+ await expect(+ updateDeveloperApp({ appId: "app-456", name: "New" }),+ ).rejects.toThrow("Unauthorized");+ });++ it("throws App not found when app does not exist", async () => {+ mockGetCurrentUser.mockResolvedValue(mockUser);+ mockDb.limit.mockResolvedValue([]);+ await expect(+ updateDeveloperApp({ appId: "app-456", name: "New" }),+ ).rejects.toThrow("App not found");+ });++ it("updates name when provided", async () => {+ mockGetCurrentUser.mockResolvedValue(mockUser);+ mockDb.limit.mockResolvedValueOnce([mockApp]);+ await updateDeveloperApp({ appId: "app-456", name: "Updated Name" });++ expect(mockDb.set).toHaveBeenCalledWith(+ expect.objectContaining({ name: "Updated Name" }),+ );+ });++ it("updates environment when provided", async () => {+ mockGetCurrentUser.mockResolvedValue(mockUser);+ mockDb.limit.mockResolvedValueOnce([mockApp]);+ await updateDeveloperApp({+ appId: "app-456",+ environment: "production",+ });++ expect(mockDb.set).toHaveBeenCalledWith(+ expect.objectContaining({ environment: "production" }),+ );+ });++ it("trims name before saving", async () => {+ mockGetCurrentUser.mockResolvedValue(mockUser);+ mockDb.limit.mockResolvedValueOnce([mockApp]);+ await updateDeveloperApp({ appId: "app-456", name: " Trimmed " });++ expect(mockDb.set).toHaveBeenCalledWith(+ expect.objectContaining({ name: "Trimmed" }),+ );+ });++ it("skips update when no fields provided", async () => {+ mockGetCurrentUser.mockResolvedValue(mockUser);+ mockDb.limit.mockResolvedValueOnce([mockApp]);+ await updateDeveloperApp({ appId: "app-456" });++ expect(mockDb.update).not.toHaveBeenCalled();+ });++ it("returns success true", async () => {+ mockGetCurrentUser.mockResolvedValue(mockUser);+ mockDb.limit.mockResolvedValueOnce([mockApp]);+ const result = await updateDeveloperApp({+ appId: "app-456",+ name: "New",+ });+ expect(result).toEqual({ success: true });+ });+});++describe("addDeveloperDomain", () => {+ let addDeveloperDomain: typeof import("@/actions/developers/add-domain").addDeveloperDomain;++ beforeEach(async () => {+ vi.clearAllMocks();+ resetMockDb();+ const mod = await import("@/actions/developers/add-domain");+ addDeveloperDomain = mod.addDeveloperDomain;+ });++ it("throws Unauthorized when no user", async () => {+ mockGetCurrentUser.mockResolvedValue(null);+ await expect(+ addDeveloperDomain("app-456", "https://example.com"),+ ).rejects.toThrow("Unauthorized");+ });++ it("throws Domain is required when empty", async () => {+ mockGetCurrentUser.mockResolvedValue(mockUser);+ await expect(addDeveloperDomain("app-456", "")).rejects.toThrow(+ "Domain is required",+ );+ });++ it("throws Domain is required when whitespace only", async () => {+ mockGetCurrentUser.mockResolvedValue(mockUser);+ await expect(addDeveloperDomain("app-456", " ")).rejects.toThrow(+ "Domain is required",+ );+ });++ it("validates domain format with regex", async () => {+ mockGetCurrentUser.mockResolvedValue(mockUser);+ await expect(addDeveloperDomain("app-456", "not-a-url")).rejects.toThrow(+ "Domain must be a valid origin (e.g. https://myapp.com)",+ );+ });++ it("accepts https://example.com", async () => {+ mockGetCurrentUser.mockResolvedValue(mockUser);+ mockDb.limit.mockResolvedValueOnce([mockApp]);+ const result = await addDeveloperDomain("app-456", "https://example.com");+ expect(result).toEqual({ success: true });+ });++ it("accepts http://localhost:3000", async () => {+ mockGetCurrentUser.mockResolvedValue(mockUser);+ mockDb.limit.mockResolvedValueOnce([mockApp]);+ const result = await addDeveloperDomain("app-456", "http://localhost:3000");+ expect(result).toEqual({ success: true });+ });++ it("rejects invalid domains without protocol", async () => {+ mockGetCurrentUser.mockResolvedValue(mockUser);+ await expect(addDeveloperDomain("app-456", "example.com")).rejects.toThrow(+ "Domain must be a valid origin (e.g. https://myapp.com)",+ );+ });++ it("rejects bare hostnames", async () => {+ mockGetCurrentUser.mockResolvedValue(mockUser);+ await expect(+ addDeveloperDomain("app-456", "just-hostname"),+ ).rejects.toThrow("Domain must be a valid origin (e.g. https://myapp.com)");+ });++ it("normalizes to lowercase", async () => {+ mockGetCurrentUser.mockResolvedValue(mockUser);+ mockDb.limit.mockResolvedValueOnce([mockApp]);+ await addDeveloperDomain("app-456", "HTTPS://EXAMPLE.COM");++ expect(mockDb.values).toHaveBeenCalledWith(+ expect.objectContaining({ domain: "https://example.com" }),+ );+ });++ it("returns success true", async () => {+ mockGetCurrentUser.mockResolvedValue(mockUser);+ mockDb.limit.mockResolvedValueOnce([mockApp]);+ const result = await addDeveloperDomain("app-456", "https://example.com");+ expect(result).toEqual({ success: true });+ });+});++describe("removeDeveloperDomain", () => {+ let removeDeveloperDomain: typeof import("@/actions/developers/remove-domain").removeDeveloperDomain;++ beforeEach(async () => {+ vi.clearAllMocks();+ resetMockDb();+ const mod = await import("@/actions/developers/remove-domain");+ removeDeveloperDomain = mod.removeDeveloperDomain;+ });++ it("throws Unauthorized when no user", async () => {+ mockGetCurrentUser.mockResolvedValue(null);+ await expect(+ removeDeveloperDomain("app-456", "domain-789"),+ ).rejects.toThrow("Unauthorized");+ });++ it("throws App not found when app does not exist", async () => {+ mockGetCurrentUser.mockResolvedValue(mockUser);+ mockDb.limit.mockResolvedValue([]);+ await expect(+ removeDeveloperDomain("app-456", "domain-789"),+ ).rejects.toThrow("App not found");+ });++ it("deletes domain record", async () => {+ mockGetCurrentUser.mockResolvedValue(mockUser);+ mockDb.limit.mockResolvedValueOnce([mockApp]);+ await removeDeveloperDomain("app-456", "domain-789");++ expect(mockDb.delete).toHaveBeenCalled();+ });++ it("returns success true", async () => {+ mockGetCurrentUser.mockResolvedValue(mockUser);+ mockDb.limit.mockResolvedValueOnce([mockApp]);+ const result = await removeDeveloperDomain("app-456", "domain-789");+ expect(result).toEqual({ success: true });+ });+});++describe("regenerateDeveloperKeys", () => {+ let regenerateDeveloperKeys: typeof import("@/actions/developers/regenerate-keys").regenerateDeveloperKeys;++ beforeEach(async () => {+ vi.clearAllMocks();+ resetMockDb();+ const mod = await import("@/actions/developers/regenerate-keys");+ regenerateDeveloperKeys = mod.regenerateDeveloperKeys;+ });++ it("throws Unauthorized when no user", async () => {+ mockGetCurrentUser.mockResolvedValue(null);+ await expect(regenerateDeveloperKeys("app-456")).rejects.toThrow(+ "Unauthorized",+ );+ });++ it("throws App not found when app does not exist", async () => {+ mockGetCurrentUser.mockResolvedValue(mockUser);+ mockDb.limit.mockResolvedValue([]);+ await expect(regenerateDeveloperKeys("app-456")).rejects.toThrow(+ "App not found",+ );+ });++ it("revokes all existing active keys", async () => {+ mockGetCurrentUser.mockResolvedValue(mockUser);+ mockDb.limit.mockResolvedValueOnce([mockApp]);+ await regenerateDeveloperKeys("app-456");++ expect(mockDb.update).toHaveBeenCalled();+ expect(mockDb.set).toHaveBeenCalledWith(+ expect.objectContaining({ revokedAt: expect.any(Date) }),+ );+ });++ it("creates new public and secret keys", async () => {+ mockGetCurrentUser.mockResolvedValue(mockUser);+ mockDb.limit.mockResolvedValueOnce([mockApp]);+ const result = await regenerateDeveloperKeys("app-456");++ expect(result.publicKey).toMatch(/^cpk_/);+ expect(result.secretKey).toMatch(/^csk_/);+ });++ it("returns new publicKey and secretKey", async () => {+ mockGetCurrentUser.mockResolvedValue(mockUser);+ mockDb.limit.mockResolvedValueOnce([mockApp]);+ const result = await regenerateDeveloperKeys("app-456");++ expect(result).toHaveProperty("publicKey");+ expect(result).toHaveProperty("secretKey");+ expect(typeof result.publicKey).toBe("string");+ expect(typeof result.secretKey).toBe("string");+ });+});++describe("addCreditsToAccount", () => {+ let addCreditsToAccount: typeof import("@/actions/developers/purchase-credits").addCreditsToAccount;++ beforeEach(async () => {+ vi.clearAllMocks();+ resetMockDb();+ const mod = await import("@/actions/developers/purchase-credits");+ addCreditsToAccount = mod.addCreditsToAccount;+ });++ it("correctly calculates micro-credits from cents", async () => {+ mockDb.transaction.mockImplementation(async (fn) => {+ const txDb = { ...mockDb };+ txDb.select = vi.fn(() => txDb) as unknown as ReturnType<typeof vi.fn>;+ txDb.from = vi.fn(() => txDb) as unknown as ReturnType<typeof vi.fn>;+ txDb.where = vi.fn(() => txDb) as unknown as ReturnType<typeof vi.fn>;+ txDb.update = vi.fn(() => txDb) as unknown as ReturnType<typeof vi.fn>;+ txDb.set = vi.fn(() => txDb) as unknown as ReturnType<typeof vi.fn>;+ txDb.insert = vi.fn(() => txDb) as unknown as ReturnType<typeof vi.fn>;+ txDb.values = vi.fn(() => Promise.resolve()) as unknown as ReturnType<+ typeof vi.fn+ >;+ txDb.limit = vi.fn(() =>+ Promise.resolve([{ balanceMicroCredits: 1000000 }]),+ ) as unknown as ReturnType<typeof vi.fn>;+ return fn(txDb);+ });++ const result = await addCreditsToAccount({+ accountId: "account-001",+ amountCents: 1000,+ });+ expect(result).toBe(1000000);+ });++ it("creates topup transaction record with referenceType", async () => {+ let capturedValues: Record<string, unknown> | null = null;+ mockDb.transaction.mockImplementation(async (fn) => {+ const txDb = { ...mockDb };+ txDb.select = vi.fn(() => txDb) as unknown as ReturnType<typeof vi.fn>;+ txDb.from = vi.fn(() => txDb) as unknown as ReturnType<typeof vi.fn>;+ txDb.where = vi.fn(() => txDb) as unknown as ReturnType<typeof vi.fn>;+ txDb.update = vi.fn(() => txDb) as unknown as ReturnType<typeof vi.fn>;+ txDb.set = vi.fn(() => txDb) as unknown as ReturnType<typeof vi.fn>;+ txDb.insert = vi.fn(() => txDb) as unknown as ReturnType<typeof vi.fn>;+ txDb.values = vi.fn((vals: Record<string, unknown>) => {+ capturedValues = vals;+ return Promise.resolve();+ }) as unknown as ReturnType<typeof vi.fn>;+ txDb.limit = vi.fn(() =>+ Promise.resolve([{ balanceMicroCredits: 500000 }]),+ ) as unknown as ReturnType<typeof vi.fn>;+ return fn(txDb);+ });++ await addCreditsToAccount({+ accountId: "account-001",+ amountCents: 500,+ referenceId: "pi_test123",+ referenceType: "stripe_payment_intent",+ });+ expect(capturedValues).toMatchObject({+ type: "topup",+ referenceId: "pi_test123",+ referenceType: "stripe_payment_intent",+ });+ });++ it("returns the new balance", async () => {+ mockDb.transaction.mockImplementation(async (fn) => {+ const txDb = { ...mockDb };+ txDb.select = vi.fn(() => txDb) as unknown as ReturnType<typeof vi.fn>;+ txDb.from = vi.fn(() => txDb) as unknown as ReturnType<typeof vi.fn>;+ txDb.where = vi.fn(() => txDb) as unknown as ReturnType<typeof vi.fn>;+ txDb.update = vi.fn(() => txDb) as unknown as ReturnType<typeof vi.fn>;+ txDb.set = vi.fn(() => txDb) as unknown as ReturnType<typeof vi.fn>;+ txDb.insert = vi.fn(() => txDb) as unknown as ReturnType<typeof vi.fn>;+ txDb.values = vi.fn(() => Promise.resolve()) as unknown as ReturnType<+ typeof vi.fn+ >;+ txDb.limit = vi.fn(() =>+ Promise.resolve([{ balanceMicroCredits: 750000 }]),+ ) as unknown as ReturnType<typeof vi.fn>;+ return fn(txDb);+ });++ const result = await addCreditsToAccount({+ accountId: "account-001",+ amountCents: 750,+ });+ expect(result).toBe(750000);+ });+});++describe("updateDeveloperAutoTopUp", () => {+ let updateDeveloperAutoTopUp: typeof import("@/actions/developers/update-auto-topup").updateDeveloperAutoTopUp;++ beforeEach(async () => {+ vi.clearAllMocks();+ resetMockDb();+ const mod = await import("@/actions/developers/update-auto-topup");+ updateDeveloperAutoTopUp = mod.updateDeveloperAutoTopUp;+ });++ it("throws Unauthorized when no user", async () => {+ mockGetCurrentUser.mockResolvedValue(null);+ await expect(+ updateDeveloperAutoTopUp({ appId: "app-456", enabled: true }),+ ).rejects.toThrow("Unauthorized");+ });++ it("throws App not found when app does not exist", async () => {+ mockGetCurrentUser.mockResolvedValue(mockUser);+ mockDb.limit.mockResolvedValue([]);+ await expect(+ updateDeveloperAutoTopUp({ appId: "app-456", enabled: true }),+ ).rejects.toThrow("App not found");+ });++ it("throws Threshold must be non-negative for negative threshold", async () => {+ mockGetCurrentUser.mockResolvedValue(mockUser);+ mockDb.limit.mockResolvedValueOnce([mockApp]);+ await expect(+ updateDeveloperAutoTopUp({+ appId: "app-456",+ enabled: true,+ thresholdMicroCredits: -100,+ }),+ ).rejects.toThrow("Threshold must be non-negative");+ });++ it("throws Top-up amount must be positive for zero amount", async () => {+ mockGetCurrentUser.mockResolvedValue(mockUser);+ mockDb.limit.mockResolvedValueOnce([mockApp]);+ await expect(+ updateDeveloperAutoTopUp({+ appId: "app-456",+ enabled: true,+ amountCents: 0,+ }),+ ).rejects.toThrow("Top-up amount must be positive");+ });++ it("throws Top-up amount must be positive for negative amount", async () => {+ mockGetCurrentUser.mockResolvedValue(mockUser);+ mockDb.limit.mockResolvedValueOnce([mockApp]);+ await expect(+ updateDeveloperAutoTopUp({+ appId: "app-456",+ enabled: true,+ amountCents: -50,+ }),+ ).rejects.toThrow("Top-up amount must be positive");+ });++ it("updates enabled flag", async () => {+ mockGetCurrentUser.mockResolvedValue(mockUser);+ mockDb.limit.mockResolvedValueOnce([mockApp]);+ await updateDeveloperAutoTopUp({ appId: "app-456", enabled: false });++ expect(mockDb.set).toHaveBeenCalledWith(+ expect.objectContaining({ autoTopUpEnabled: false }),+ );+ });++ it("conditionally updates threshold and amount", async () => {+ mockGetCurrentUser.mockResolvedValue(mockUser);+ mockDb.limit.mockResolvedValueOnce([mockApp]);+ await updateDeveloperAutoTopUp({+ appId: "app-456",+ enabled: true,+ thresholdMicroCredits: 50000,+ amountCents: 1000,+ });++ expect(mockDb.set).toHaveBeenCalledWith(+ expect.objectContaining({+ autoTopUpEnabled: true,+ autoTopUpThresholdMicroCredits: 50000,+ autoTopUpAmountCents: 1000,+ }),+ );+ });++ it("returns success true", async () => {+ mockGetCurrentUser.mockResolvedValue(mockUser);+ mockDb.limit.mockResolvedValueOnce([mockApp]);+ const result = await updateDeveloperAutoTopUp({+ appId: "app-456",+ enabled: true,+ });+ expect(result).toEqual({ success: true });+ });+});++describe("deleteDeveloperVideo", () => {+ let deleteDeveloperVideo: typeof import("@/actions/developers/delete-video").deleteDeveloperVideo;++ beforeEach(async () => {+ vi.clearAllMocks();+ resetMockDb();+ const mod = await import("@/actions/developers/delete-video");+ deleteDeveloperVideo = mod.deleteDeveloperVideo;+ });++ it("throws Unauthorized when no user", async () => {+ mockGetCurrentUser.mockResolvedValue(null);+ await expect(deleteDeveloperVideo("app-456", "video-001")).rejects.toThrow(+ "Unauthorized",+ );+ });++ it("throws App not found when app does not exist", async () => {+ mockGetCurrentUser.mockResolvedValue(mockUser);+ mockDb.limit.mockResolvedValue([]);+ await expect(deleteDeveloperVideo("app-456", "video-001")).rejects.toThrow(+ "App not found",+ );+ });++ it("soft deletes video", async () => {+ mockGetCurrentUser.mockResolvedValue(mockUser);+ mockDb.limit.mockResolvedValueOnce([mockApp]);+ await deleteDeveloperVideo("app-456", "video-001");++ expect(mockDb.update).toHaveBeenCalled();+ expect(mockDb.set).toHaveBeenCalledWith(+ expect.objectContaining({ deletedAt: expect.any(Date) }),+ );+ });++ it("returns success true", async () => {+ mockGetCurrentUser.mockResolvedValue(mockUser);+ mockDb.limit.mockResolvedValueOnce([mockApp]);+ const result = await deleteDeveloperVideo("app-456", "video-001");+ expect(result).toEqual({ success: true });+ });+});diff --git a/apps/web/__tests__/unit/developer-api-auth.test.ts b/apps/web/__tests__/unit/developer-api-auth.test.tsnew file mode 100644index 000000000..51bfbffe9--- /dev/null+++ b/apps/web/__tests__/unit/developer-api-auth.test.ts@@ -0,0 +1,533 @@+import { describe, expect, it, vi } from "vitest";++vi.mock("@cap/database", () => {+ const mockDb = {+ select: vi.fn(() => mockDb),+ insert: vi.fn(() => mockDb),+ update: vi.fn(() => mockDb),+ delete: vi.fn(() => mockDb),+ from: vi.fn(() => mockDb),+ set: vi.fn(() => mockDb),+ where: vi.fn(() => mockDb),+ limit: vi.fn(() => Promise.resolve([])),+ values: vi.fn(() => Promise.resolve()),+ leftJoin: vi.fn(() => mockDb),+ };+ return { db: () => mockDb, __mockDb: mockDb };+});++vi.mock("@cap/database/auth/session", () => ({+ getCurrentUser: vi.fn(),+}));++vi.mock("@cap/database/schema", () => ({+ developerApiKeys: {+ appId: "appId",+ keyHash: "keyHash",+ keyType: "keyType",+ revokedAt: "revokedAt",+ lastUsedAt: "lastUsedAt",+ },+ developerApps: { id: "id", deletedAt: "deletedAt" },+ developerAppDomains: { appId: "appId", domain: "domain" },+ authApiKeys: { id: "id", userId: "userId" },+ users: { id: "id" },+}));++vi.mock("@cap/env", () => ({+ buildEnv: { NEXT_PUBLIC_WEB_URL: "https://cap.so" },+}));++vi.mock("@/lib/developer-key-hash", () => ({+ hashKey: vi.fn(() => Promise.resolve("mocked-hash")),+}));++vi.mock("next/headers", () => ({+ cookies: vi.fn(() => Promise.resolve({ set: vi.fn() })),+}));++vi.mock("drizzle-orm", () => ({+ and: vi.fn((...args: unknown[]) => args),+ eq: vi.fn((a: unknown, b: unknown) => ({ eq: [a, b] })),+ isNull: vi.fn((a: unknown) => ({ isNull: a })),+}));++describe("developer API auth - key format validation", () => {+ describe("public key format (cpk_ prefix)", () => {+ it("accepts a key starting with cpk_", () => {+ const key = "cpk_abc123";+ expect(key.startsWith("cpk_")).toBe(true);+ });++ it("rejects a secret key for public auth", () => {+ const key = "csk_abc123";+ expect(key.startsWith("cpk_")).toBe(false);+ });++ it("rejects a key with no recognized prefix", () => {+ const key = "abc123";+ expect(key.startsWith("cpk_")).toBe(false);+ });++ it("rejects an empty string", () => {+ const key = "";+ expect(key.startsWith("cpk_")).toBe(false);+ });++ it("rejects undefined via optional chaining", () => {+ const key: string | undefined = undefined;+ expect(key?.startsWith("cpk_")).toBeFalsy();+ });++ it("rejects cpk prefix without trailing underscore", () => {+ const key = "cpkabc123";+ expect(key.startsWith("cpk_")).toBe(false);+ });+ });++ describe("secret key format (csk_ prefix)", () => {+ it("accepts a key starting with csk_", () => {+ const key = "csk_abc123";+ expect(key.startsWith("csk_")).toBe(true);+ });++ it("rejects a public key for secret auth", () => {+ const key = "cpk_abc123";+ expect(key.startsWith("csk_")).toBe(false);+ });++ it("rejects a key with no recognized prefix", () => {+ const key = "abc123";+ expect(key.startsWith("csk_")).toBe(false);+ });++ it("rejects an empty string", () => {+ const key = "";+ expect(key.startsWith("csk_")).toBe(false);+ });++ it("rejects undefined via optional chaining", () => {+ const key: string | undefined = undefined;+ expect(key?.startsWith("csk_")).toBeFalsy();+ });++ it("rejects csk prefix without trailing underscore", () => {+ const key = "cskabc123";+ expect(key.startsWith("csk_")).toBe(false);+ });+ });+});++describe("developer API auth - bearer token extraction", () => {+ it("extracts the token from a valid Bearer header", () => {+ const header = "Bearer cpk_test123";+ const token = header.split(" ")[1];+ expect(token).toBe("cpk_test123");+ });++ it("returns empty string when Bearer has no token", () => {+ const header = "Bearer ";+ const token = header.split(" ")[1];+ expect(token).toBe("");+ });++ it("returns undefined when authorization header is missing", () => {+ const header: string | undefined = undefined;+ const token = header?.split(" ")[1];+ expect(token).toBeUndefined();+ });++ it("extracts only the first token segment after Bearer", () => {+ const header = "Bearer cpk_test123 extra_stuff";+ const token = header.split(" ")[1];+ expect(token).toBe("cpk_test123");+ });++ it("returns the raw scheme when no space is present", () => {+ const header = "cpk_test123";+ const token = header.split(" ")[1];+ expect(token).toBeUndefined();+ });++ it("handles lowercase bearer prefix (non-standard)", () => {+ const header = "bearer cpk_test123";+ const token = header.split(" ")[1];+ expect(token).toBe("cpk_test123");+ });+});++describe("developer API auth - key revocation check", () => {+ it("treats a key with null revokedAt as active", () => {+ const keyRow = { appId: "app-1", revokedAt: null };+ const isRevoked = keyRow.revokedAt !== null;+ expect(isRevoked).toBe(false);+ });++ it("treats a key with a revokedAt date as revoked", () => {+ const keyRow = {+ appId: "app-1",+ revokedAt: new Date("2025-01-15T00:00:00Z"),+ };+ const isRevoked = keyRow.revokedAt !== null;+ expect(isRevoked).toBe(true);+ });++ it("middleware returns 401 when no key row is found", () => {+ const keyRows: unknown[] = [];+ const keyRow = keyRows[0];+ expect(keyRow).toBeUndefined();+ expect(!keyRow).toBe(true);+ });+});++describe("developer API auth - app deletion check", () => {+ it("treats an app with null deletedAt as active", () => {+ const app = { id: "app-1", environment: "production", deletedAt: null };+ const isDeleted = app.deletedAt !== null;+ expect(isDeleted).toBe(false);+ });++ it("treats an app with a deletedAt date as deleted", () => {+ const app = {+ id: "app-1",+ environment: "production",+ deletedAt: new Date("2025-06-01T00:00:00Z"),+ };+ const isDeleted = app.deletedAt !== null;+ expect(isDeleted).toBe(true);+ });++ it("middleware returns 401 when no app is found", () => {+ const apps: unknown[] = [];+ const app = apps[0];+ expect(app).toBeUndefined();+ expect(!app).toBe(true);+ });+});++describe("developer API auth - origin validation for production apps", () => {+ function validateOrigin(+ environment: string,+ origin: string | undefined,+ allowedDomains: string[],+ ): { allowed: boolean; status?: number; error?: string } {+ if (environment === "production") {+ if (!origin) {+ return {+ allowed: false,+ status: 403,+ error: "Origin header required for production apps",+ };+ }+ const match = allowedDomains.find((d) => d === origin);+ if (!match) {+ return { allowed: false, status: 403, error: "Origin not allowed" };+ }+ }+ return { allowed: true };+ }++ it("allows a production app when origin matches an allowed domain", () => {+ const result = validateOrigin("production", "https://myapp.com", [+ "https://myapp.com",+ "https://other.com",+ ]);+ expect(result.allowed).toBe(true);+ });++ it("denies a production app when origin does not match any allowed domain", () => {+ const result = validateOrigin("production", "https://evil.com", [+ "https://myapp.com",+ ]);+ expect(result.allowed).toBe(false);+ expect(result.status).toBe(403);+ expect(result.error).toBe("Origin not allowed");+ });++ it("denies a production app when no origin header is present", () => {+ const result = validateOrigin("production", undefined, [+ "https://myapp.com",+ ]);+ expect(result.allowed).toBe(false);+ expect(result.status).toBe(403);+ expect(result.error).toBe("Origin header required for production apps");+ });++ it("allows a development app with any origin", () => {+ const result = validateOrigin("development", "https://anything.com", []);+ expect(result.allowed).toBe(true);+ });++ it("allows a development app with no origin", () => {+ const result = validateOrigin("development", undefined, []);+ expect(result.allowed).toBe(true);+ });++ it("allows a production app when origin matches one of many domains", () => {+ const result = validateOrigin("production", "https://second.com", [+ "https://first.com",+ "https://second.com",+ "https://third.com",+ ]);+ expect(result.allowed).toBe(true);+ });++ it("performs exact match - no partial domain matching", () => {+ const result = validateOrigin("production", "https://myapp.com.evil.com", [+ "https://myapp.com",+ ]);+ expect(result.allowed).toBe(false);+ expect(result.status).toBe(403);+ });++ it("performs exact match - scheme matters", () => {+ const result = validateOrigin("production", "http://myapp.com", [+ "https://myapp.com",+ ]);+ expect(result.allowed).toBe(false);+ expect(result.status).toBe(403);+ });++ it("denies a production app with empty string origin", () => {+ const result = validateOrigin("production", "", ["https://myapp.com"]);+ expect(result.allowed).toBe(false);+ expect(result.status).toBe(403);+ expect(result.error).toBe("Origin header required for production apps");+ });++ it("denies a production app when allowed domains list is empty", () => {+ const result = validateOrigin("production", "https://myapp.com", []);+ expect(result.allowed).toBe(false);+ expect(result.status).toBe(403);+ expect(result.error).toBe("Origin not allowed");+ });+});++describe("developer API auth - full public auth flow simulation", () => {+ function simulatePublicAuth(params: {+ authHeader: string | undefined;+ keyRow: { appId: string } | undefined;+ app:+ | { id: string; environment: string; deletedAt: Date | null }+ | undefined;+ origin: string | undefined;+ allowedDomains: string[];+ }): { status: number; error?: string; appId?: string } {+ if (!params.authHeader?.startsWith("cpk_")) {+ return { status: 401, error: "Invalid public key" };+ }++ if (!params.keyRow) {+ return { status: 401, error: "Invalid or revoked public key" };+ }++ if (!params.app) {+ return { status: 401, error: "App not found" };+ }++ if (params.app.environment === "production") {+ if (!params.origin) {+ return {+ status: 403,+ error: "Origin header required for production apps",+ };+ }+ const match = params.allowedDomains.find((d) => d === params.origin);+ if (!match) {+ return { status: 403, error: "Origin not allowed" };+ }+ }++ return { status: 200, appId: params.app.id };+ }++ it("succeeds with valid public key, active app, and matching origin", () => {+ const result = simulatePublicAuth({+ authHeader: "cpk_live_key123",+ keyRow: { appId: "app-1" },+ app: { id: "app-1", environment: "production", deletedAt: null },+ origin: "https://myapp.com",+ allowedDomains: ["https://myapp.com"],+ });+ expect(result.status).toBe(200);+ expect(result.appId).toBe("app-1");+ });++ it("fails with 401 when no auth header is provided", () => {+ const result = simulatePublicAuth({+ authHeader: undefined,+ keyRow: undefined,+ app: undefined,+ origin: undefined,+ allowedDomains: [],+ });+ expect(result.status).toBe(401);+ expect(result.error).toBe("Invalid public key");+ });++ it("fails with 401 when key uses wrong prefix", () => {+ const result = simulatePublicAuth({+ authHeader: "csk_secret_key",+ keyRow: undefined,+ app: undefined,+ origin: undefined,+ allowedDomains: [],+ });+ expect(result.status).toBe(401);+ expect(result.error).toBe("Invalid public key");+ });++ it("fails with 401 when key is revoked (no key row returned)", () => {+ const result = simulatePublicAuth({+ authHeader: "cpk_revoked_key",+ keyRow: undefined,+ app: undefined,+ origin: undefined,+ allowedDomains: [],+ });+ expect(result.status).toBe(401);+ expect(result.error).toBe("Invalid or revoked public key");+ });++ it("fails with 401 when app is deleted (no app returned)", () => {+ const result = simulatePublicAuth({+ authHeader: "cpk_live_key123",+ keyRow: { appId: "app-1" },+ app: undefined,+ origin: undefined,+ allowedDomains: [],+ });+ expect(result.status).toBe(401);+ expect(result.error).toBe("App not found");+ });++ it("fails with 403 when production app has no origin", () => {+ const result = simulatePublicAuth({+ authHeader: "cpk_live_key123",+ keyRow: { appId: "app-1" },+ app: { id: "app-1", environment: "production", deletedAt: null },+ origin: undefined,+ allowedDomains: ["https://myapp.com"],+ });+ expect(result.status).toBe(403);+ expect(result.error).toBe("Origin header required for production apps");+ });++ it("fails with 403 when production app origin is not in allowed list", () => {+ const result = simulatePublicAuth({+ authHeader: "cpk_live_key123",+ keyRow: { appId: "app-1" },+ app: { id: "app-1", environment: "production", deletedAt: null },+ origin: "https://evil.com",+ allowedDomains: ["https://myapp.com"],+ });+ expect(result.status).toBe(403);+ expect(result.error).toBe("Origin not allowed");+ });++ it("succeeds for development app without origin validation", () => {+ const result = simulatePublicAuth({+ authHeader: "cpk_dev_key456",+ keyRow: { appId: "app-2" },+ app: { id: "app-2", environment: "development", deletedAt: null },+ origin: undefined,+ allowedDomains: [],+ });+ expect(result.status).toBe(200);+ expect(result.appId).toBe("app-2");+ });+});++describe("developer API auth - full secret auth flow simulation", () => {+ function simulateSecretAuth(params: {+ authHeader: string | undefined;+ keyRow: { appId: string } | undefined;+ app:+ | { id: string; environment: string; deletedAt: Date | null }+ | undefined;+ }): { status: number; error?: string; appId?: string } {+ if (!params.authHeader?.startsWith("csk_")) {+ return { status: 401, error: "Invalid secret key" };+ }++ if (!params.keyRow) {+ return { status: 401, error: "Invalid or revoked secret key" };+ }++ if (!params.app) {+ return { status: 401, error: "App not found" };+ }++ return { status: 200, appId: params.app.id };+ }++ it("succeeds with valid secret key and active app", () => {+ const result = simulateSecretAuth({+ authHeader: "csk_live_secret789",+ keyRow: { appId: "app-1" },+ app: { id: "app-1", environment: "production", deletedAt: null },+ });+ expect(result.status).toBe(200);+ expect(result.appId).toBe("app-1");+ });++ it("fails with 401 when no auth header is provided", () => {+ const result = simulateSecretAuth({+ authHeader: undefined,+ keyRow: undefined,+ app: undefined,+ });+ expect(result.status).toBe(401);+ expect(result.error).toBe("Invalid secret key");+ });++ it("fails with 401 when key uses public prefix", () => {+ const result = simulateSecretAuth({+ authHeader: "cpk_public_key",+ keyRow: undefined,+ app: undefined,+ });+ expect(result.status).toBe(401);+ expect(result.error).toBe("Invalid secret key");+ });++ it("fails with 401 when key is revoked (no key row returned)", () => {+ const result = simulateSecretAuth({+ authHeader: "csk_revoked_key",+ keyRow: undefined,+ app: undefined,+ });+ expect(result.status).toBe(401);+ expect(result.error).toBe("Invalid or revoked secret key");+ });++ it("fails with 401 when app is deleted (no app returned)", () => {+ const result = simulateSecretAuth({+ authHeader: "csk_live_secret789",+ keyRow: { appId: "app-1" },+ app: undefined,+ });+ expect(result.status).toBe(401);+ expect(result.error).toBe("App not found");+ });++ it("does not perform origin validation even for production apps", () => {+ const result = simulateSecretAuth({+ authHeader: "csk_live_secret789",+ keyRow: { appId: "app-1" },+ app: { id: "app-1", environment: "production", deletedAt: null },+ });+ expect(result.status).toBe(200);+ expect(result.appId).toBe("app-1");+ });++ it("succeeds for development app without any extra checks", () => {+ const result = simulateSecretAuth({+ authHeader: "csk_dev_secret456",+ keyRow: { appId: "app-2" },+ app: { id: "app-2", environment: "development", deletedAt: null },+ });+ expect(result.status).toBe(200);+ expect(result.appId).toBe("app-2");+ });+});diff --git a/apps/web/__tests__/unit/developer-credit-math.test.ts b/apps/web/__tests__/unit/developer-credit-math.test.tsnew file mode 100644index 000000000..e065b5eb9--- /dev/null+++ b/apps/web/__tests__/unit/developer-credit-math.test.ts@@ -0,0 +1,177 @@+const MICRO_CREDITS_PER_DOLLAR = 100_000;+const MICRO_CREDITS_PER_MINUTE = 5_000;+const MICRO_CREDITS_PER_MINUTE_PER_DAY = 3.33;+const MIN_BALANCE_MICRO_CREDITS = 5_000;++function purchaseCreditsFormula(amountCents: number): number {+ return Math.floor((amountCents / 100) * MICRO_CREDITS_PER_DOLLAR);+}++function videoRecordingCost(durationMinutes: number): number {+ return Math.floor(durationMinutes * MICRO_CREDITS_PER_MINUTE);+}++function dailyStorageCost(totalMinutes: number): number {+ return Math.floor(totalMinutes * MICRO_CREDITS_PER_MINUTE_PER_DAY);+}++function balanceDollars(balanceMicroCredits: number): string {+ return (balanceMicroCredits / 100_000).toFixed(2);+}++function balanceAfterCharge(balance: number, charge: number): number {+ return Math.max(0, balance - charge);+}++describe("Purchase Credits Conversion", () => {+ it("converts $5.00 (500 cents) to 500,000 micro-credits", () => {+ expect(purchaseCreditsFormula(500)).toBe(500_000);+ });++ it("converts $10.00 (1000 cents) to 1,000,000 micro-credits", () => {+ expect(purchaseCreditsFormula(1000)).toBe(1_000_000);+ });++ it("converts $25.00 (2500 cents) to 2,500,000 micro-credits", () => {+ expect(purchaseCreditsFormula(2500)).toBe(2_500_000);+ });++ it("converts $50.00 (5000 cents) to 5,000,000 micro-credits", () => {+ expect(purchaseCreditsFormula(5000)).toBe(5_000_000);+ });++ it("converts $0.01 (1 cent) to 1,000 micro-credits", () => {+ expect(purchaseCreditsFormula(1)).toBe(1_000);+ });++ it("converts $5.99 (599 cents) to 599,000 micro-credits using Math.floor", () => {+ expect(purchaseCreditsFormula(599)).toBe(+ Math.floor(5.99 * 100_000),+ );+ expect(purchaseCreditsFormula(599)).toBe(599_000);+ });++ it("rejects purchases below $5.00 minimum (amountCents < 500)", () => {+ expect(499 < 500).toBe(true);+ expect(500 < 500).toBe(false);+ expect(0 < 500).toBe(true);+ });+});++describe("Video Recording Cost", () => {+ it("charges 5,000 micro-credits for 1 minute video", () => {+ expect(videoRecordingCost(1)).toBe(5_000);+ });++ it("charges 25,000 micro-credits for 5 minute video", () => {+ expect(videoRecordingCost(5)).toBe(25_000);+ });++ it("charges 50,000 micro-credits for 10 minute video", () => {+ expect(videoRecordingCost(10)).toBe(50_000);+ });++ it("charges 2,500 micro-credits for 30 second video (0.5 min)", () => {+ expect(videoRecordingCost(0.5)).toBe(2_500);+ });++ it("charges 7,500 micro-credits for 90 second video (1.5 min)", () => {+ expect(videoRecordingCost(1.5)).toBe(7_500);+ });++ it("charges 0 micro-credits for 0 duration", () => {+ expect(videoRecordingCost(0)).toBe(0);+ });++ it("charges 83 micro-credits for 1 second video (1/60 min)", () => {+ const oneSecondInMinutes = 1 / 60;+ expect(videoRecordingCost(oneSecondInMinutes)).toBe(+ Math.floor(0.016666666666666666 * 5_000),+ );+ expect(videoRecordingCost(oneSecondInMinutes)).toBe(83);+ });+});++describe("Daily Storage Cost", () => {+ it("charges 3 micro-credits for 1 minute stored", () => {+ expect(dailyStorageCost(1)).toBe(Math.floor(1 * 3.33));+ expect(dailyStorageCost(1)).toBe(3);+ });++ it("charges 33 micro-credits for 10 minutes stored", () => {+ expect(dailyStorageCost(10)).toBe(Math.floor(10 * 3.33));+ expect(dailyStorageCost(10)).toBe(33);+ });++ it("charges 333 micro-credits for 100 minutes stored", () => {+ expect(dailyStorageCost(100)).toBe(Math.floor(100 * 3.33));+ expect(dailyStorageCost(100)).toBe(333);+ });++ it("charges 3330 micro-credits for 1000 minutes stored", () => {+ expect(dailyStorageCost(1000)).toBe(Math.floor(1000 * 3.33));+ expect(dailyStorageCost(1000)).toBe(3330);+ });++ it("charges 0 micro-credits for 0 minutes stored", () => {+ expect(dailyStorageCost(0)).toBe(0);+ });+});++describe("Balance Conversions", () => {+ it("converts 0 micro-credits to $0.00", () => {+ expect(balanceDollars(0)).toBe("0.00");+ });++ it("converts 100,000 micro-credits to $1.00", () => {+ expect(balanceDollars(100_000)).toBe("1.00");+ });++ it("converts 500,000 micro-credits to $5.00", () => {+ expect(balanceDollars(500_000)).toBe("5.00");+ });++ it("converts 1 micro-credit to $0.00 (rounds down)", () => {+ expect(balanceDollars(1)).toBe("0.00");+ });++ it("converts 99,999 micro-credits to $1.00 (rounds up)", () => {+ expect(balanceDollars(99_999)).toBe("1.00");+ });++ it("converts 50,000 micro-credits to $0.50", () => {+ expect(balanceDollars(50_000)).toBe("0.50");+ });+});++describe("Balance Protection (GREATEST(0, balance - charge))", () => {+ it("prevents negative balance: 1000 - 5000 = 0", () => {+ expect(balanceAfterCharge(1000, 5000)).toBe(0);+ });++ it("subtracts normally: 10000 - 5000 = 5000", () => {+ expect(balanceAfterCharge(10000, 5000)).toBe(5000);+ });++ it("handles exact depletion: 5000 - 5000 = 0", () => {+ expect(balanceAfterCharge(5000, 5000)).toBe(0);+ });+});++describe("Minimum Balance Check", () => {+ it("4,999 micro-credits is insufficient", () => {+ expect(4_999 < MIN_BALANCE_MICRO_CREDITS).toBe(true);+ });++ it("5,000 micro-credits is sufficient", () => {+ expect(5_000 < MIN_BALANCE_MICRO_CREDITS).toBe(false);+ });++ it("5,001 micro-credits is sufficient", () => {+ expect(5_001 < MIN_BALANCE_MICRO_CREDITS).toBe(false);+ });++ it("0 micro-credits is insufficient", () => {+ expect(0 < MIN_BALANCE_MICRO_CREDITS).toBe(true);+ });+});diff --git a/apps/web/__tests__/unit/developer-credits-checkout.test.ts b/apps/web/__tests__/unit/developer-credits-checkout.test.tsnew file mode 100644index 000000000..895e346cc--- /dev/null+++ b/apps/web/__tests__/unit/developer-credits-checkout.test.ts@@ -0,0 +1,367 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++const mockDb = {+ select: vi.fn(),+ insert: vi.fn(),+ update: vi.fn(),+ from: vi.fn(),+ set: vi.fn(),+ where: vi.fn(),+ limit: vi.fn(),+ values: vi.fn(),+};++function resetMockDb() {+ for (const key of Object.keys(mockDb)) {+ const fn = mockDb[key as keyof typeof mockDb];+ if (typeof fn?.mockClear === "function") {+ fn.mockClear();+ }+ }+ mockDb.select.mockReturnValue(mockDb);+ mockDb.insert.mockReturnValue(mockDb);+ mockDb.update.mockReturnValue(mockDb);+ mockDb.from.mockReturnValue(mockDb);+ mockDb.set.mockReturnValue(mockDb);+ mockDb.where.mockReturnValue(mockDb);+ mockDb.limit.mockReturnValue(Promise.resolve([]));+ mockDb.values.mockReturnValue(Promise.resolve());+}++vi.mock("@cap/database", () => ({+ db: () => mockDb,+}));++vi.mock("@cap/database/auth/session", () => ({+ getCurrentUser: vi.fn(),+}));++vi.mock("@cap/database/schema", () => ({+ developerApps: {+ id: "id",+ ownerId: "ownerId",+ deletedAt: "deletedAt",+ },+ developerCreditAccounts: {+ id: "id",+ appId: "appId",+ stripeCustomerId: "stripeCustomerId",+ },+ users: { id: "id" },+}));++vi.mock("@cap/env", () => ({+ serverEnv: () => ({+ WEB_URL: "https://cap.test",+ }),+}));++const mockStripe = {+ customers: {+ list: vi.fn(),+ create: vi.fn(),+ update: vi.fn(),+ },+ checkout: {+ sessions: {+ create: vi.fn(),+ },+ },+};++vi.mock("@cap/utils", () => ({+ stripe: () => mockStripe,+}));++vi.mock("drizzle-orm", () => ({+ and: vi.fn((...args: unknown[]) => args),+ eq: vi.fn((a: unknown, b: unknown) => ({ eq: [a, b] })),+ isNull: vi.fn((a: unknown) => ({ isNull: a })),+}));++import { getCurrentUser } from "@cap/database/auth/session";++const mockGetCurrentUser = getCurrentUser as ReturnType<typeof vi.fn>;++const mockUser = {+ id: "user-123",+ email: "[email protected]",+ stripeCustomerId: null,+};++const mockApp = {+ id: "app-456",+ ownerId: "user-123",+ name: "Test App",+ deletedAt: null,+};++const mockAccount = {+ id: "account-001",+ appId: "app-456",+ stripeCustomerId: null,+};++function makeRequest(body: Record<string, unknown>) {+ return new Request("https://cap.test/api/developer/credits/checkout", {+ method: "POST",+ headers: { "Content-Type": "application/json" },+ body: JSON.stringify(body),+ }) as unknown as import("next/server").NextRequest;+}++describe("POST /api/developer/credits/checkout", () => {+ let POST: typeof import("@/app/api/developer/credits/checkout/route").POST;++ beforeEach(async () => {+ vi.clearAllMocks();+ resetMockDb();+ const mod = await import("@/app/api/developer/credits/checkout/route");+ POST = mod.POST;+ });++ it("returns 401 when user is not authenticated", async () => {+ mockGetCurrentUser.mockResolvedValue(null);+ const res = await POST(+ makeRequest({ appId: "app-456", amountCents: 1000 }),+ );+ expect(res.status).toBe(401);+ const body = await res.json();+ expect(body.error).toBe("Unauthorized");+ });++ it("returns 400 when appId is missing", async () => {+ mockGetCurrentUser.mockResolvedValue(mockUser);+ const res = await POST(makeRequest({ amountCents: 1000 }));+ expect(res.status).toBe(400);+ });++ it("returns 400 when amountCents is below minimum", async () => {+ mockGetCurrentUser.mockResolvedValue(mockUser);+ const res = await POST(makeRequest({ appId: "app-456", amountCents: 499 }));+ expect(res.status).toBe(400);+ });++ it("returns 400 when amountCents is not an integer", async () => {+ mockGetCurrentUser.mockResolvedValue(mockUser);+ const res = await POST(+ makeRequest({ appId: "app-456", amountCents: 500.5 }),+ );+ expect(res.status).toBe(400);+ });++ it("returns 400 when amountCents is not a number", async () => {+ mockGetCurrentUser.mockResolvedValue(mockUser);+ const res = await POST(+ makeRequest({ appId: "app-456", amountCents: "1000" }),+ );+ expect(res.status).toBe(400);+ });++ it("returns 404 when app is not found", async () => {+ mockGetCurrentUser.mockResolvedValue(mockUser);+ mockDb.limit.mockResolvedValueOnce([]);+ const res = await POST(+ makeRequest({ appId: "app-456", amountCents: 1000 }),+ );+ expect(res.status).toBe(404);+ const body = await res.json();+ expect(body.error).toBe("App not found");+ });++ it("returns 404 when credit account is not found", async () => {+ mockGetCurrentUser.mockResolvedValue(mockUser);+ mockDb.limit.mockResolvedValueOnce([mockApp]).mockResolvedValueOnce([]);+ const res = await POST(+ makeRequest({ appId: "app-456", amountCents: 1000 }),+ );+ expect(res.status).toBe(404);+ const body = await res.json();+ expect(body.error).toBe("Credit account not found");+ });++ it("creates a new Stripe customer when none exists", async () => {+ mockGetCurrentUser.mockResolvedValue(mockUser);+ mockDb.limit+ .mockResolvedValueOnce([mockApp])+ .mockResolvedValueOnce([mockAccount]);++ const newCustomer = { id: "cus_new123", metadata: {} };+ mockStripe.customers.list.mockResolvedValue({ data: [] });+ mockStripe.customers.create.mockResolvedValue(newCustomer);+ mockStripe.checkout.sessions.create.mockResolvedValue({+ url: "https://checkout.stripe.com/test",+ });++ const res = await POST(+ makeRequest({ appId: "app-456", amountCents: 1000 }),+ );+ expect(res.status).toBe(200);+ expect(mockStripe.customers.create).toHaveBeenCalledWith({+ email: "[email protected]",+ metadata: { userId: "user-123" },+ });+ });++ it("reuses existing Stripe customer found by email", async () => {+ mockGetCurrentUser.mockResolvedValue(mockUser);+ mockDb.limit+ .mockResolvedValueOnce([mockApp])+ .mockResolvedValueOnce([mockAccount]);++ const existingCustomer = {+ id: "cus_existing",+ metadata: { otherKey: "val" },+ };+ mockStripe.customers.list.mockResolvedValue({+ data: [existingCustomer],+ });+ mockStripe.customers.update.mockResolvedValue(existingCustomer);+ mockStripe.checkout.sessions.create.mockResolvedValue({+ url: "https://checkout.stripe.com/test",+ });++ const res = await POST(+ makeRequest({ appId: "app-456", amountCents: 1000 }),+ );+ expect(res.status).toBe(200);+ expect(mockStripe.customers.update).toHaveBeenCalledWith(+ "cus_existing",+ expect.objectContaining({+ metadata: expect.objectContaining({ userId: "user-123" }),+ }),+ );+ expect(mockStripe.customers.create).not.toHaveBeenCalled();+ });++ it("skips customer creation when account already has stripeCustomerId", async () => {+ mockGetCurrentUser.mockResolvedValue(mockUser);+ const accountWithStripe = { ...mockAccount, stripeCustomerId: "cus_acct" };+ mockDb.limit+ .mockResolvedValueOnce([mockApp])+ .mockResolvedValueOnce([accountWithStripe]);++ mockStripe.checkout.sessions.create.mockResolvedValue({+ url: "https://checkout.stripe.com/test",+ });++ const res = await POST(+ makeRequest({ appId: "app-456", amountCents: 2500 }),+ );+ expect(res.status).toBe(200);+ expect(mockStripe.customers.list).not.toHaveBeenCalled();+ expect(mockStripe.customers.create).not.toHaveBeenCalled();+ });++ it("creates checkout session with correct metadata", async () => {+ mockGetCurrentUser.mockResolvedValue({+ ...mockUser,+ stripeCustomerId: "cus_exist",+ });+ const accountWithStripe = { ...mockAccount, stripeCustomerId: "cus_exist" };+ mockDb.limit+ .mockResolvedValueOnce([mockApp])+ .mockResolvedValueOnce([accountWithStripe]);++ mockStripe.checkout.sessions.create.mockResolvedValue({+ url: "https://checkout.stripe.com/test",+ });++ await POST(makeRequest({ appId: "app-456", amountCents: 2500 }));++ expect(mockStripe.checkout.sessions.create).toHaveBeenCalledWith(+ expect.objectContaining({+ mode: "payment",+ metadata: {+ type: "developer_credits",+ appId: "app-456",+ accountId: "account-001",+ amountCents: "2500",+ userId: "user-123",+ },+ }),+ );+ });++ it("returns checkout URL on success", async () => {+ mockGetCurrentUser.mockResolvedValue({+ ...mockUser,+ stripeCustomerId: "cus_exist",+ });+ const accountWithStripe = { ...mockAccount, stripeCustomerId: "cus_exist" };+ mockDb.limit+ .mockResolvedValueOnce([mockApp])+ .mockResolvedValueOnce([accountWithStripe]);++ mockStripe.checkout.sessions.create.mockResolvedValue({+ url: "https://checkout.stripe.com/session_abc",+ });++ const res = await POST(+ makeRequest({ appId: "app-456", amountCents: 1000 }),+ );+ expect(res.status).toBe(200);+ const body = await res.json();+ expect(body.url).toBe("https://checkout.stripe.com/session_abc");+ });++ it("returns 500 when checkout session has no URL", async () => {+ mockGetCurrentUser.mockResolvedValue({+ ...mockUser,+ stripeCustomerId: "cus_exist",+ });+ const accountWithStripe = { ...mockAccount, stripeCustomerId: "cus_exist" };+ mockDb.limit+ .mockResolvedValueOnce([mockApp])+ .mockResolvedValueOnce([accountWithStripe]);++ mockStripe.checkout.sessions.create.mockResolvedValue({ url: null });++ const res = await POST(+ makeRequest({ appId: "app-456", amountCents: 1000 }),+ );+ expect(res.status).toBe(500);+ });++ it("returns 500 when Stripe throws", async () => {+ mockGetCurrentUser.mockResolvedValue({+ ...mockUser,+ stripeCustomerId: "cus_exist",+ });+ const accountWithStripe = { ...mockAccount, stripeCustomerId: "cus_exist" };+ mockDb.limit+ .mockResolvedValueOnce([mockApp])+ .mockResolvedValueOnce([accountWithStripe]);++ mockStripe.checkout.sessions.create.mockRejectedValue(+ new Error("Stripe error"),+ );++ const res = await POST(+ makeRequest({ appId: "app-456", amountCents: 1000 }),+ );+ expect(res.status).toBe(500);+ });++ it("sets line_items with correct unit_amount", async () => {+ mockGetCurrentUser.mockResolvedValue({+ ...mockUser,+ stripeCustomerId: "cus_exist",+ });+ const accountWithStripe = { ...mockAccount, stripeCustomerId: "cus_exist" };+ mockDb.limit+ .mockResolvedValueOnce([mockApp])+ .mockResolvedValueOnce([accountWithStripe]);++ mockStripe.checkout.sessions.create.mockResolvedValue({+ url: "https://checkout.stripe.com/test",+ });++ await POST(makeRequest({ appId: "app-456", amountCents: 5000 }));++ const call = mockStripe.checkout.sessions.create.mock.calls[0]?.[0];+ expect(call.line_items[0].price_data.unit_amount).toBe(5000);+ expect(call.line_items[0].price_data.currency).toBe("usd");+ expect(call.line_items[0].quantity).toBe(1);+ });+});diff --git a/apps/web/__tests__/unit/developer-credits-webhook.test.ts b/apps/web/__tests__/unit/developer-credits-webhook.test.tsnew file mode 100644index 000000000..a16244c43--- /dev/null+++ b/apps/web/__tests__/unit/developer-credits-webhook.test.ts@@ -0,0 +1,272 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++const mockDbChain = {+ select: vi.fn(),+ from: vi.fn(),+ where: vi.fn(),+ limit: vi.fn(),+ insert: vi.fn(),+ update: vi.fn(),+ set: vi.fn(),+ values: vi.fn(),+};++function resetDbChain() {+ for (const key of Object.keys(mockDbChain)) {+ const fn = mockDbChain[key as keyof typeof mockDbChain];+ fn.mockClear();+ }+ mockDbChain.select.mockReturnValue(mockDbChain);+ mockDbChain.from.mockReturnValue(mockDbChain);+ mockDbChain.where.mockReturnValue(mockDbChain);+ mockDbChain.limit.mockReturnValue(Promise.resolve([]));+ mockDbChain.insert.mockReturnValue(mockDbChain);+ mockDbChain.update.mockReturnValue(mockDbChain);+ mockDbChain.set.mockReturnValue(mockDbChain);+ mockDbChain.values.mockReturnValue(Promise.resolve());+}++vi.mock("@cap/database", () => ({+ db: () => mockDbChain,+}));++vi.mock("@cap/database/helpers", () => ({+ nanoId: vi.fn(() => "test-nano-id"),+}));++vi.mock("@cap/database/schema", () => ({+ developerCreditTransactions: {+ id: "id",+ accountId: "accountId",+ referenceId: "referenceId",+ referenceType: "referenceType",+ },+ users: { id: "id", email: "email" },+}));++vi.mock("@cap/env", () => ({+ buildEnv: {+ NEXT_PUBLIC_POSTHOG_KEY: "",+ NEXT_PUBLIC_POSTHOG_HOST: "",+ },+ serverEnv: () => ({+ STRIPE_WEBHOOK_SECRET: "whsec_test",+ }),+}));++const mockAddCredits = vi.fn();+vi.mock("@/actions/developers/purchase-credits", () => ({+ addCreditsToAccount: (...args: unknown[]) => mockAddCredits(...args),+}));++vi.mock("@cap/web-domain", () => ({+ Organisation: { OrganisationId: { make: (v: string) => v } },+ User: { UserId: { make: (v: string) => v } },+}));++const mockStripe = {+ webhooks: {+ constructEvent: vi.fn(),+ },+ customers: {+ retrieve: vi.fn(),+ },+ subscriptions: {+ retrieve: vi.fn(),+ list: vi.fn(),+ },+};++vi.mock("@cap/utils", () => ({+ stripe: () => mockStripe,+}));++vi.mock("drizzle-orm", () => ({+ and: vi.fn((...args: unknown[]) => args),+ eq: vi.fn((a: unknown, b: unknown) => ({ eq: [a, b] })),+}));++vi.mock("posthog-node", () => ({+ PostHog: vi.fn().mockImplementation(() => ({+ capture: vi.fn(),+ shutdown: vi.fn().mockResolvedValue(undefined),+ })),+}));++function makeWebhookRequest(body = "{}") {+ return new Request("https://cap.test/api/webhooks/stripe", {+ method: "POST",+ headers: {+ "Content-Type": "application/json",+ "Stripe-Signature": "sig_test",+ },+ body,+ });+}++function makeCheckoutSession(overrides: Record<string, unknown> = {}) {+ return {+ id: "cs_test_123",+ customer: "cus_test",+ subscription: null,+ payment_intent: "pi_test_abc",+ metadata: {+ type: "developer_credits",+ appId: "app-456",+ accountId: "account-001",+ amountCents: "2500",+ userId: "user-123",+ },+ customer_details: { email: "[email protected]" },+ ...overrides,+ };+}++describe("Stripe webhook — developer credits", () => {+ let POST: typeof import("@/app/api/webhooks/stripe/route").POST;++ beforeEach(async () => {+ vi.clearAllMocks();+ resetDbChain();+ mockAddCredits.mockResolvedValue(250000);+ const mod = await import("@/app/api/webhooks/stripe/route");+ POST = mod.POST;+ });++ it("returns 400 when signature is missing", async () => {+ const req = new Request("https://cap.test/api/webhooks/stripe", {+ method: "POST",+ body: "{}",+ });+ const res = await POST(req);+ expect(res.status).toBe(400);+ });++ it("returns 400 when constructEvent throws", async () => {+ mockStripe.webhooks.constructEvent.mockImplementation(() => {+ throw new Error("Invalid signature");+ });+ const res = await POST(makeWebhookRequest());+ expect(res.status).toBe(400);+ const text = await res.text();+ expect(text).toContain("Invalid signature");+ });++ it("adds credits on valid developer_credits checkout", async () => {+ const session = makeCheckoutSession();+ mockStripe.webhooks.constructEvent.mockReturnValue({+ type: "checkout.session.completed",+ data: { object: session },+ });+ mockDbChain.limit.mockResolvedValueOnce([]);++ const res = await POST(makeWebhookRequest());+ expect(res.status).toBe(200);+ expect(mockAddCredits).toHaveBeenCalledWith({+ accountId: "account-001",+ amountCents: 2500,+ referenceId: "pi_test_abc",+ referenceType: "stripe_payment_intent",+ metadata: {+ amountCents: 2500,+ stripeSessionId: "cs_test_123",+ },+ });+ });++ it("converts amountCents from string to number", async () => {+ const session = makeCheckoutSession({+ metadata: {+ type: "developer_credits",+ appId: "app-456",+ accountId: "account-001",+ amountCents: "5000",+ userId: "user-123",+ },+ });+ mockStripe.webhooks.constructEvent.mockReturnValue({+ type: "checkout.session.completed",+ data: { object: session },+ });+ mockDbChain.limit.mockResolvedValueOnce([]);++ await POST(makeWebhookRequest());+ expect(mockAddCredits).toHaveBeenCalledWith(+ expect.objectContaining({ amountCents: 5000 }),+ );+ });++ it("skips duplicate webhook delivery (idempotency)", async () => {+ const session = makeCheckoutSession();+ mockStripe.webhooks.constructEvent.mockReturnValue({+ type: "checkout.session.completed",+ data: { object: session },+ });+ mockDbChain.limit.mockResolvedValueOnce([{ id: "existing-txn-id" }]);++ const res = await POST(makeWebhookRequest());+ expect(res.status).toBe(200);+ expect(mockAddCredits).not.toHaveBeenCalled();+ });++ it("returns 400 when payment_intent is missing", async () => {+ const session = makeCheckoutSession({ payment_intent: null });+ mockStripe.webhooks.constructEvent.mockReturnValue({+ type: "checkout.session.completed",+ data: { object: session },+ });++ const res = await POST(makeWebhookRequest());+ expect(res.status).toBe(400);+ expect(mockAddCredits).not.toHaveBeenCalled();+ });++ it("returns 400 when accountId is missing from metadata", async () => {+ const session = makeCheckoutSession({+ metadata: {+ type: "developer_credits",+ amountCents: "1000",+ userId: "user-123",+ },+ });+ mockStripe.webhooks.constructEvent.mockReturnValue({+ type: "checkout.session.completed",+ data: { object: session },+ });++ const res = await POST(makeWebhookRequest());+ expect(res.status).toBe(400);+ expect(mockAddCredits).not.toHaveBeenCalled();+ });++ it("returns 400 when amountCents is missing from metadata", async () => {+ const session = makeCheckoutSession({+ metadata: {+ type: "developer_credits",+ accountId: "account-001",+ userId: "user-123",+ },+ });+ mockStripe.webhooks.constructEvent.mockReturnValue({+ type: "checkout.session.completed",+ data: { object: session },+ });++ const res = await POST(makeWebhookRequest());+ expect(res.status).toBe(400);+ expect(mockAddCredits).not.toHaveBeenCalled();+ });++ it("does not fall through to subscription logic for developer_credits", async () => {+ const session = makeCheckoutSession();+ mockStripe.webhooks.constructEvent.mockReturnValue({+ type: "checkout.session.completed",+ data: { object: session },+ });+ mockDbChain.limit.mockResolvedValueOnce([]);++ await POST(makeWebhookRequest());+ expect(mockStripe.customers.retrieve).not.toHaveBeenCalled();+ expect(mockStripe.subscriptions.retrieve).not.toHaveBeenCalled();+ });+});diff --git a/apps/web/__tests__/unit/developer-cron-storage.test.ts b/apps/web/__tests__/unit/developer-cron-storage.test.tsnew file mode 100644index 000000000..8a09ee24c--- /dev/null+++ b/apps/web/__tests__/unit/developer-cron-storage.test.ts@@ -0,0 +1,320 @@+import { beforeEach, describe, expect, it, vi } from "vitest";++const mockDb = vi.fn();++vi.mock("@cap/database", () => ({+ db: mockDb,+}));++vi.mock("@cap/database/helpers", () => ({+ nanoId: vi.fn(() => "test-nano-id"),+}));++vi.mock("@cap/database/schema", () => ({+ developerApps: { id: "id", deletedAt: "deletedAt" },+ developerCreditAccounts: {+ id: "id",+ appId: "appId",+ balanceMicroCredits: "balanceMicroCredits",+ },+ developerCreditTransactions: {},+ developerDailyStorageSnapshots: {+ appId: "appId",+ snapshotDate: "snapshotDate",+ id: "id",+ processedAt: "processedAt",+ },+ developerVideos: {+ appId: "appId",+ deletedAt: "deletedAt",+ duration: "duration",+ },+}));++vi.mock("drizzle-orm", () => ({+ and: vi.fn((...args: any[]) => args),+ eq: vi.fn((a: any, b: any) => ({ eq: [a, b] })),+ isNull: vi.fn((a: any) => ({ isNull: a })),+ sql: vi.fn(),+}));++let capturedJsonBody: any = null;+let capturedStatus: number | undefined = undefined;++vi.mock("next/server", () => ({+ NextResponse: {+ json: vi.fn((body: any, init?: any) => {+ capturedJsonBody = body;+ capturedStatus = init?.status;+ return { body, status: init?.status ?? 200 };+ }),+ },+}));++const CRON_SECRET = "test-cron-secret";++function makeChain(+ result: any[],+ options?: { onTransaction?: (tx: any) => void },+) {+ const chain: any = {+ select: vi.fn(() => chain),+ from: vi.fn(() => chain),+ where: vi.fn(() => chain),+ limit: vi.fn(() => Promise.resolve(result)),+ insert: vi.fn(() => chain),+ values: vi.fn(() => Promise.resolve()),+ update: vi.fn(() => chain),+ set: vi.fn(() => chain),+ transaction: vi.fn(async (cb: any) => {+ const txChain: any = {+ select: vi.fn(() => txChain),+ from: vi.fn(() => txChain),+ where: vi.fn(() => txChain),+ limit: vi.fn(() =>+ Promise.resolve([{ balanceMicroCredits: 0 }]),+ ),+ insert: vi.fn(() => txChain),+ values: vi.fn(() => Promise.resolve()),+ update: vi.fn(() => txChain),+ set: vi.fn(() => txChain),+ };+ if (options?.onTransaction) {+ options.onTransaction(txChain);+ }+ await cb(txChain);+ }),+ };+ chain.then = (resolve: any) => resolve(result);+ return chain;+}++function setupDbSequence(+ responses: any[][],+ txOptions?: { onTransaction?: (tx: any) => void },+) {+ let callIndex = 0;+ mockDb.mockImplementation(() => {+ const idx = callIndex++;+ const result = idx < responses.length ? responses[idx] : [];+ return makeChain(result, txOptions);+ });+}++beforeEach(() => {+ vi.clearAllMocks();+ capturedJsonBody = null;+ capturedStatus = undefined;+ process.env.CRON_SECRET = CRON_SECRET;+});++async function importGET() {+ const mod = await import("@/app/api/cron/developer-storage/route");+ return mod.GET;+}++function makeRequest(authHeader?: string): Request {+ const headers = new Headers();+ if (authHeader) {+ headers.set("authorization", authHeader);+ }+ return new Request("https://localhost/api/cron/developer-storage", {+ method: "GET",+ headers,+ });+}++describe("developer-storage cron job", () => {+ describe("authentication", () => {+ it("returns 401 when no auth header", async () => {+ const GET = await importGET();+ await GET(makeRequest());++ expect(capturedJsonBody).toEqual({ error: "Unauthorized" });+ expect(capturedStatus).toBe(401);+ });++ it("returns 401 when wrong bearer token", async () => {+ const GET = await importGET();+ await GET(makeRequest("Bearer wrong-secret"));++ expect(capturedJsonBody).toEqual({ error: "Unauthorized" });+ expect(capturedStatus).toBe(401);+ });+ });++ describe("processing apps", () => {+ it("processes apps with videos and charges correctly", async () => {+ const GET = await importGET();++ setupDbSequence([+ [{ id: "app-1" }],+ [],+ [{ totalDurationMinutes: 10, videoCount: 5 }],+ [{ id: "account-1", appId: "app-1", balanceMicroCredits: 1000 }],+ [],+ ]);++ await GET(makeRequest(`Bearer ${CRON_SECRET}`));++ expect(capturedJsonBody).toMatchObject({+ success: true,+ appsProcessed: 1,+ });+ expect(capturedJsonBody.date).toMatch(/^\d{4}-\d{2}-\d{2}$/);+ });++ it("skips already-processed apps", async () => {+ const GET = await importGET();++ setupDbSequence([+ [{ id: "app-1" }],+ [{ id: "snapshot-1", processedAt: new Date() }],+ ]);++ await GET(makeRequest(`Bearer ${CRON_SECRET}`));++ expect(capturedJsonBody).toMatchObject({+ success: true,+ appsProcessed: 0,+ });+ });++ it("skips apps with 0 total duration", async () => {+ const GET = await importGET();++ setupDbSequence([+ [{ id: "app-1" }],+ [],+ [{ totalDurationMinutes: 0, videoCount: 0 }],+ ]);++ await GET(makeRequest(`Bearer ${CRON_SECRET}`));++ expect(capturedJsonBody).toMatchObject({+ success: true,+ appsProcessed: 0,+ });+ });++ it("skips apps with no credit account", async () => {+ const GET = await importGET();++ setupDbSequence([+ [{ id: "app-1" }],+ [],+ [{ totalDurationMinutes: 10, videoCount: 5 }],+ [],+ ]);++ await GET(makeRequest(`Bearer ${CRON_SECRET}`));++ expect(capturedJsonBody).toMatchObject({+ success: true,+ appsProcessed: 0,+ });+ });+ });++ describe("transaction behavior", () => {+ it("creates negative transaction for storage_daily", async () => {+ const GET = await importGET();+ let insertValues: any = null;++ setupDbSequence(+ [+ [{ id: "app-1" }],+ [],+ [{ totalDurationMinutes: 10, videoCount: 5 }],+ [{ id: "account-1", appId: "app-1", balanceMicroCredits: 1000 }],+ [],+ ],+ {+ onTransaction: (tx) => {+ tx.values.mockImplementation((vals: any) => {+ if (vals?.type === "storage_daily") {+ insertValues = vals;+ }+ return Promise.resolve();+ });+ },+ },+ );++ await GET(makeRequest(`Bearer ${CRON_SECRET}`));++ expect(insertValues).not.toBeNull();+ expect(insertValues.type).toBe("storage_daily");+ expect(insertValues.amountMicroCredits).toBe(-33);+ });++ it("transaction amount is negative (debit)", async () => {+ const GET = await importGET();+ let capturedAmount: number | null = null;++ setupDbSequence(+ [+ [{ id: "app-1" }],+ [],+ [{ totalDurationMinutes: 10, videoCount: 3 }],+ [{ id: "account-1", appId: "app-1", balanceMicroCredits: 500 }],+ [],+ ],+ {+ onTransaction: (tx) => {+ tx.values.mockImplementation((vals: any) => {+ if (vals?.type === "storage_daily") {+ capturedAmount = vals.amountMicroCredits;+ }+ return Promise.resolve();+ });+ },+ },+ );++ await GET(makeRequest(`Bearer ${CRON_SECRET}`));++ expect(capturedAmount).toBeLessThan(0);+ });+ });++ describe("response format", () => {+ it("returns correct response format", async () => {+ const GET = await importGET();++ setupDbSequence([[]]);++ await GET(makeRequest(`Bearer ${CRON_SECRET}`));++ expect(capturedJsonBody).toHaveProperty("success", true);+ expect(capturedJsonBody).toHaveProperty("date");+ expect(capturedJsonBody).toHaveProperty("appsProcessed");+ expect(capturedJsonBody.date).toMatch(/^\d{4}-\d{2}-\d{2}$/);+ expect(typeof capturedJsonBody.appsProcessed).toBe("number");+ });+ });++ describe("storage rate calculations", () => {+ const MICRO_CREDITS_PER_MINUTE_PER_DAY = 3.33;++ it("1 minute -> 3 credits", () => {+ expect(Math.floor(1 * MICRO_CREDITS_PER_MINUTE_PER_DAY)).toBe(3);+ });++ it("10 minutes -> 33 credits", () => {+ expect(Math.floor(10 * MICRO_CREDITS_PER_MINUTE_PER_DAY)).toBe(33);+ });++ it("100 minutes -> 333 credits", () => {+ expect(Math.floor(100 * MICRO_CREDITS_PER_MINUTE_PER_DAY)).toBe(333);+ });++ it("1000 minutes -> 3330 credits", () => {+ expect(Math.floor(1000 * MICRO_CREDITS_PER_MINUTE_PER_DAY)).toBe(3330);+ });++ it("0.5 minutes -> 1 credit", () => {+ expect(Math.floor(0.5 * MICRO_CREDITS_PER_MINUTE_PER_DAY)).toBe(1);+ });+ });+});diff --git a/apps/web/__tests__/unit/developer-domain-validation.test.ts b/apps/web/__tests__/unit/developer-domain-validation.test.tsnew file mode 100644index 000000000..836499d62--- /dev/null+++ b/apps/web/__tests__/unit/developer-domain-validation.test.ts@@ -0,0 +1,92 @@+import { describe, expect, it } from "vitest";++const urlPattern = /^https?:\/\/[a-z0-9.-]+(:[0-9]+)?$/;++function normalizeDomain(input: string): string {+ return input.trim().toLowerCase();+}++describe("developer domain validation regex", () => {+ describe("valid domains", () => {+ const validDomains = [+ "https://example.com",+ "https://myapp.com",+ "http://localhost:3000",+ "http://localhost",+ "https://sub.domain.example.com",+ "https://api.my-site.io",+ "https://192.168.1.1",+ "https://192.168.1.1:8080",+ "http://localhost:8080",+ "https://my-app.vercel.app",+ "https://a.b.c.d.e.com",+ "https://example.com:443",+ "http://example.com:80",+ "https://0.0.0.0:3000",+ ];++ for (const domain of validDomains) {+ it(`matches ${domain}`, () => {+ expect(urlPattern.test(domain)).toBe(true);+ });+ }+ });++ describe("invalid domains", () => {+ const invalidDomains: [string, string][] = [+ ["example.com", "no protocol"],+ ["ftp://example.com", "wrong protocol"],+ ["https://example.com/", "trailing slash"],+ ["https://example.com/path", "has path"],+ ["https://example.com?query=1", "has query"],+ ["https://example.com#hash", "has hash"],+ ["https://", "no hostname"],+ ["https://EXAMPLE.COM", "uppercase"],+ ["https://example.com:", "port separator but no port"],+ ["https://example.com:abc", "non-numeric port"],+ ["https://exam ple.com", "space in hostname"],+ ["", "empty string"],+ ["javascript:alert(1)", "XSS attempt"],+ ["data:text/html,<script>alert(1)</script>", "data URI"],+ ];++ for (const [domain, reason] of invalidDomains) {+ it(`rejects ${domain || "(empty string)"} — ${reason}`, () => {+ expect(urlPattern.test(domain)).toBe(false);+ });+ }+ });++ describe("edge case: large port number", () => {+ it("matches https://example.com:99999 since regex only checks for digits", () => {+ expect(urlPattern.test("https://example.com:99999")).toBe(true);+ });+ });+});++describe("domain normalization", () => {+ it("trims whitespace and lowercases the input", () => {+ const raw = " https://Example.COM ";+ const normalized = normalizeDomain(raw);+ expect(normalized).toBe("https://example.com");+ });++ it("produces a value that passes the regex after normalization", () => {+ const raw = " https://Example.COM ";+ const normalized = normalizeDomain(raw);+ expect(urlPattern.test(normalized)).toBe(true);+ });++ it("lowercases mixed-case input before regex test", () => {+ const raw = "https://MyApp.Vercel.App";+ const normalized = normalizeDomain(raw);+ expect(normalized).toBe("https://myapp.vercel.app");+ expect(urlPattern.test(normalized)).toBe(true);+ });++ it("uppercase raw input fails regex directly but passes after normalization", () => {+ const raw = "https://EXAMPLE.COM";+ expect(urlPattern.test(raw)).toBe(false);+ expect(urlPattern.test(normalizeDomain(raw))).toBe(true);+ });+});diff --git a/apps/web/__tests__/unit/developer-key-hash.test.ts b/apps/web/__tests__/unit/developer-key-hash.test.tsnew file mode 100644index 000000000..669f0f766--- /dev/null+++ b/apps/web/__tests__/unit/developer-key-hash.test.ts@@ -0,0 +1,58 @@+import { hashKey } from "@/lib/developer-key-hash";+import { describe, expect, it, vi } from "vitest";++vi.mock("@cap/env", () => ({+ serverEnv: () => ({+ NEXTAUTH_SECRET: "test-hmac-secret-for-unit-tests",+ }),+}));++describe("hashKey", () => {+ it("produces different hashes for different keys", async () => {+ const hash1 = await hashKey("key-one");+ const hash2 = await hashKey("key-two");+ expect(hash1).not.toBe(hash2);+ });++ it("is deterministic - same key always produces same hash", async () => {+ const first = await hashKey("deterministic-test");+ const second = await hashKey("deterministic-test");+ const third = await hashKey("deterministic-test");+ expect(first).toBe(second);+ expect(second).toBe(third);+ });++ it("returns exactly 64 hex characters (256 bits)", async () => {+ const result = await hashKey("length-check");+ expect(result).toHaveLength(64);+ });++ it("returns lowercase hex only", async () => {+ const result = await hashKey("case-check");+ expect(result).toMatch(/^[0-9a-f]{64}$/);+ });++ it("produces valid hash for empty string", async () => {+ const result = await hashKey("");+ expect(result).toHaveLength(64);+ expect(result).toMatch(/^[0-9a-f]{64}$/);+ });++ it("hashes public key format (cpk_*) correctly", async () => {+ const result = await hashKey("cpk_live_abc123def456");+ expect(result).toHaveLength(64);+ expect(result).toMatch(/^[0-9a-f]{64}$/);+ });++ it("hashes secret key format (csk_*) correctly", async () => {+ const result = await hashKey("csk_live_secret789xyz");+ expect(result).toHaveLength(64);+ expect(result).toMatch(/^[0-9a-f]{64}$/);+ });++ it("hashes unicode characters correctly", async () => {+ const result = await hashKey("héllo wörld 🌍");+ expect(result).toHaveLength(64);+ expect(result).toMatch(/^[0-9a-f]{64}$/);+ });+});