Supercharge your AI agents with data from the web and beyond. Building the library for superintelligence. 🔥
TypeScript aiai-agentsai-crawlerai-scrapingai-searchcrawlerdata-extractionhtml-to-markdownllmmarkdownscraperscrapingweb-crawlerweb-dataweb-data-extractionweb-scraperweb-scrapingweb-searchwebscraping
Accept Vercel Marketplace OIDC resource tokens (Phase 1, dual auth) (#4874)
Erik Engervallee1a8c6eacb9
diff --git a/.github/workflows/test-server.yml b/.github/workflows/test-server.ymlindex 76f087043..0c6592a41 100644--- a/.github/workflows/test-server.yml+++ b/.github/workflows/test-server.yml@@ -326,6 +326,15 @@ jobs:--reporter=defaultworking-directory: apps/api+ - name: Run Vercel Marketplace OIDC auth regression tests+ if: matrix.engine == 'fetch' && matrix.proxy == 'no-proxy' && matrix.nuq == 'postgres'+ run: >-+ pnpm exec vitest run+ src/lib/__tests__/vercel-marketplace-oidc.test.ts+ src/controllers/__tests__/auth-vercel-oidc.test.ts+ --reporter=default+ working-directory: apps/api+- name: Run agent location regression testsif: matrix.engine == 'fetch' && matrix.proxy == 'no-proxy' && matrix.nuq == 'postgres'run: pnpm exec vitest run src/controllers/v2/__tests__/agent-location.test.ts --reporter=defaultdiff --git a/apps/api/.env.example b/apps/api/.env.exampleindex 9e5af838a..e62db1e10 100644--- a/apps/api/.env.example+++ b/apps/api/.env.example@@ -24,6 +24,9 @@ MCP_ACTION_LOG_SECRET=# Shared only between the hosted MCP signer and Core verifier. Use 32+ random# characters and do not reuse KEYLESS_PROXY_SECRET.MCP_DELEGATED_CREDENTIAL_SECRET=+# Vercel Marketplace integration id (oac_...). Enables Vercel OIDC resource+# tokens as bearer credentials. Not a secret; unset disables the branch.+VERCEL_MARKETPLACE_INTEGRATION_ID=# Keyless signup link keys: comma-separated base64 16-byte AES keys# (openssl rand -base64 16). The first encrypts the /k/<token> links in keyless# prompts; all are tried to decrypt. Set the same value in firecrawl-web.diff --git a/apps/api/src/config.ts b/apps/api/src/config.tsindex 242c5e6af..fb1f3ce94 100644--- a/apps/api/src/config.ts+++ b/apps/api/src/config.ts@@ -301,6 +301,13 @@ const configSchema = z.object({.nonnegative().default(10),+ // Vercel Marketplace integration id (oac_...). When set, Vercel OIDC resource+ // tokens (iss https://integrations.vercel.com/<id>) are accepted as bearer+ // credentials. Unset disables the branch. Not a secret.+ VERCEL_MARKETPLACE_INTEGRATION_ID: emptyStringAsUndefined(+ z.string().regex(/^oac_[A-Za-z0-9]+$/),+ ),+// OAuth token introspectionOAUTH_INTROSPECT_URL: z.string().optional(),OAUTH_INTROSPECT_SECRET: z.string().optional(),diff --git a/apps/api/src/controllers/__tests__/auth-vercel-oidc.test.ts b/apps/api/src/controllers/__tests__/auth-vercel-oidc.test.tsnew file mode 100644index 000000000..69c8ea408--- /dev/null+++ b/apps/api/src/controllers/__tests__/auth-vercel-oidc.test.ts@@ -0,0 +1,556 @@+import { vi } from "vitest";+import { exportJWK, generateKeyPair, SignJWT, type JWK } from "jose";+import { authenticateUser } from "../auth";+import { config } from "../../config";+import { RateLimiterMode } from "../../types";+import { authCreditUsageChunk } from "../../db/rpc";+import { getValue, setValue } from "../../services/redis";+import { getAutumnRateLimiter } from "../../services/rate-limiter";+import { autumnService } from "../../services/autumn/autumn.service";+import { logger } from "../../lib/logger";++const { rows, errors, dbChain } = vi.hoisted(() => {+ const rows = {+ replica: [] as unknown[],+ primary: [] as unknown[],+ };+ const errors = {+ replica: null as Error | null,+ primary: null as Error | null,+ };+ const dbChain = (which: "replica" | "primary") => {+ const chain = {+ select: vi.fn(() => chain),+ from: vi.fn(() => chain),+ leftJoin: vi.fn(() => chain),+ where: vi.fn(() => chain),+ limit: vi.fn(async () => {+ if (errors[which]) throw errors[which];+ return rows[which];+ }),+ };+ return chain;+ };+ return { rows, errors, dbChain };+});++vi.mock("../../db/connection", () => ({+ db: dbChain("primary"),+ dbRr: dbChain("replica"),+}));++vi.mock("../../services/queue-service", () => ({+ getRedisConnection: vi.fn(() => ({ sadd: vi.fn() })),+}));++vi.mock("../../services/redis", () => ({+ getValue: vi.fn(),+ setValue: vi.fn(),+ deleteKey: vi.fn(),+}));++vi.mock("../../services/redlock", () => ({+ redlock: { using: vi.fn() },+}));++vi.mock("../../db/rpc", () => ({+ authCreditUsageChunk: vi.fn(),+ authCreditUsageChunkFromTeam: vi.fn(),+}));++vi.mock("ioredis", () => ({ default: class {} }));++vi.mock("../../services/rate-limiter", async importOriginal => {+ const actual =+ await importOriginal<typeof import("../../services/rate-limiter")>();+ return {+ ...actual,+ getRateLimiter: vi.fn(),+ getAutumnRateLimiter: vi.fn(),+ };+});++vi.mock("../../lib/spur", () => ({+ isKeylessIpSuspicious: vi.fn().mockResolvedValue(false),+}));++vi.mock("../../services/autumn/autumn.service", () => ({+ DEFAULT_TEAM_LIMITS: {+ concurrency_limit: 2,+ rate_limit_multiplier: 1,+ is_paid_plan: false,+ },+ autumnService: { getTeamLimits: vi.fn() },+}));++vi.mock("../../services/agent-sponsor", () => ({+ getAgentSponsorStatus: vi.fn(),+}));++const INTEGRATION_ID = "oac_authtest";+const ISSUER = `https://integrations.vercel.com/${INTEGRATION_ID}`;+const API_KEY = "11111111-1111-4111-8111-111111111111";+const TEAM_ID = "22222222-2222-4222-8222-222222222222";++type KeyPair = Awaited<ReturnType<typeof generateKeyPair>>;+let signing: KeyPair;+let jwk: JWK;++beforeAll(async () => {+ signing = await generateKeyPair("RS256");+ jwk = { ...(await exportJWK(signing.publicKey)), kid: "k1", alg: "RS256" };+});++async function sign(+ overrides: {+ iss?: string;+ aud?: string;+ resource?: string;+ alg?: string;+ kid?: string;+ key?: KeyPair["privateKey"];+ expSecondsFromNow?: number;+ } = {},+) {+ const now = Math.floor(Date.now() / 1000);+ return new SignJWT({+ act: { sub: "owner:team_vercel:project:prj_1:environment:production" },+ environment: "production",+ })+ .setProtectedHeader({+ alg: overrides.alg ?? "RS256",+ kid: overrides.kid ?? "k1",+ })+ .setIssuer(overrides.iss ?? ISSUER)+ .setAudience(overrides.aud ?? "icfg_1")+ .setSubject(overrides.resource ?? "res_1")+ .setIssuedAt(now)+ .setNotBefore(now)+ .setExpirationTime(now + (overrides.expSecondsFromNow ?? 300))+ .sign(overrides.key ?? signing.privateKey);+}++function request(token: string) {+ return {+ headers: { authorization: `Bearer ${token}` },+ socket: { remoteAddress: "127.0.0.1" },+ };+}++const UNAUTHORIZED = {+ success: false,+ error: "Unauthorized: Invalid token",+ status: 401,+};++describe("authenticateUser with Vercel Marketplace OIDC tokens", () => {+ const originalUseDbAuth = config.USE_DB_AUTHENTICATION;+ const originalIntegrationId = config.VERCEL_MARKETPLACE_INTEGRATION_ID;+ let jwksFetch: ReturnType<typeof vi.fn>;++ beforeEach(() => {+ config.USE_DB_AUTHENTICATION = true;+ config.VERCEL_MARKETPLACE_INTEGRATION_ID = INTEGRATION_ID;+ errors.replica = null;+ errors.primary = null;+ rows.replica = [{ teamId: TEAM_ID, apiKey: API_KEY }];+ rows.primary = [];+ vi.mocked(getValue).mockResolvedValue(null);+ vi.mocked(setValue).mockResolvedValue(undefined as never);+ vi.mocked(autumnService.getTeamLimits).mockResolvedValue({+ concurrency_limit: 2,+ rate_limit_multiplier: 1,+ is_paid_plan: false,+ });+ vi.mocked(getAutumnRateLimiter).mockReturnValue({+ consume: vi.fn().mockResolvedValue(undefined),+ } as never);+ vi.mocked(authCreditUsageChunk).mockResolvedValue([+ {+ api_key: API_KEY,+ api_key_id: 7,+ team_id: TEAM_ID,+ org_id: "org-1",+ flags: null,+ },+ ] as never);+ jwksFetch = vi.fn(+ async () =>+ new Response(JSON.stringify({ keys: [jwk] }), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ }),+ );+ vi.stubGlobal("fetch", jwksFetch);+ vi.spyOn(logger, "warn").mockImplementation(() => logger);+ vi.spyOn(logger, "info").mockImplementation(() => logger);+ });++ afterEach(() => {+ config.USE_DB_AUTHENTICATION = originalUseDbAuth;+ config.VERCEL_MARKETPLACE_INTEGRATION_ID = originalIntegrationId;+ vi.useRealTimers();+ vi.unstubAllGlobals();+ vi.restoreAllMocks();+ vi.clearAllMocks();+ });++ it("resolves a valid token to the resource's API key and team", async () => {+ const auth = await authenticateUser(+ request(await sign()),+ {},+ RateLimiterMode.Scrape,+ );++ expect(auth).toEqual(+ expect.objectContaining({+ success: true,+ team_id: TEAM_ID,+ org_id: "org-1",+ chunk: expect.objectContaining({ api_key_id: 7, team_id: TEAM_ID }),+ }),+ );+ expect(jwksFetch).toHaveBeenCalledWith(+ `${ISSUER}/jwks.json`,+ expect.any(Object),+ );+ expect(authCreditUsageChunk).toHaveBeenCalledWith(+ expect.anything(),+ API_KEY,+ "general",+ );+ const cacheWrite = vi+ .mocked(setValue)+ .mock.calls.find(([key]) => key.startsWith("vercel_oidc_token:"));+ expect(cacheWrite).toBeDefined();+ expect(JSON.parse(cacheWrite![1])).toMatchObject({+ ok: true,+ apiKey: API_KEY,+ });+ expect(cacheWrite![2]).toBeGreaterThan(0);+ expect(cacheWrite![2]).toBeLessThanOrEqual(300);+ });++ it("serves a cached resolution without re-verifying or reading the database", async () => {+ vi.mocked(getValue).mockImplementation(async key =>+ key.startsWith("vercel_oidc_token:")+ ? JSON.stringify({+ ok: true,+ apiKey: API_KEY,+ teamId: TEAM_ID,+ installationId: "icfg_1",+ resourceId: "res_1",+ })+ : null,+ );+ rows.replica = [];++ const auth = await authenticateUser(+ request(await sign()),+ {},+ RateLimiterMode.Scrape,+ );++ expect(auth.success).toBe(true);+ expect(authCreditUsageChunk).toHaveBeenCalledWith(+ expect.anything(),+ API_KEY,+ "general",+ );+ });++ it("re-verifies a token when a cached rejection has no reason", async () => {+ const integrationId = "oac_malformed_cache";+ config.VERCEL_MARKETPLACE_INTEGRATION_ID = integrationId;+ vi.mocked(getValue).mockImplementation(async key =>+ key.startsWith("vercel_oidc_token:")+ ? JSON.stringify({ ok: false })+ : null,+ );++ const auth = await authenticateUser(+ request(+ await sign({+ iss: `https://integrations.vercel.com/${integrationId}`,+ }),+ ),+ {},+ RateLimiterMode.Scrape,+ );++ expect(auth.success).toBe(true);+ expect(jwksFetch).toHaveBeenCalledWith(+ `https://integrations.vercel.com/${integrationId}/jwks.json`,+ expect.any(Object),+ );+ });++ it("scopes cached resolutions to the configured integration", async () => {+ await authenticateUser(request(await sign()), {}, RateLimiterMode.Scrape);+ const cached = vi+ .mocked(setValue)+ .mock.calls.find(([key]) => key.startsWith("vercel_oidc_token:"));+ expect(cached).toBeDefined();+ vi.mocked(getValue).mockImplementation(async key =>+ key === cached?.[0] ? cached![1] : null,+ );+ config.VERCEL_MARKETPLACE_INTEGRATION_ID = "oac_other";++ const auth = await authenticateUser(+ request(await sign()),+ {},+ RateLimiterMode.Scrape,+ );++ expect(auth).toEqual(UNAUTHORIZED);+ expect(getValue).toHaveBeenCalledWith(+ expect.stringMatching(/^vercel_oidc_token:oac_other:/),+ );+ });++ it.each([+ [+ "another integration's issuer",+ { iss: "https://integrations.vercel.com/oac_other" },+ ],+ ["an expired token", { expSecondsFromNow: -120 }],+ ])("rejects %s with 401", async (_label, overrides) => {+ const auth = await authenticateUser(+ request(await sign(overrides)),+ {},+ RateLimiterMode.Scrape,+ );+ expect(auth).toEqual(UNAUTHORIZED);+ expect(logger.warn).toHaveBeenCalledWith(+ "Request denied",+ expect.objectContaining({+ canonicalLog: "auth/denied",+ reason: "invalid_vercel_oidc_token",+ status: 401,+ }),+ );+ expect(authCreditUsageChunk).not.toHaveBeenCalled();+ expect(+ vi+ .mocked(setValue)+ .mock.calls.some(([key]) => key.startsWith("vercel_oidc_token:")),+ ).toBe(false);+ });++ it("does not cache an unknown-kid rejection and accepts the key after a refetch", async () => {+ vi.useFakeTimers({ toFake: ["Date"], now: Date.now() });+ const integrationId = "oac_rotation";+ config.VERCEL_MARKETPLACE_INTEGRATION_ID = integrationId;+ const rotated = await generateKeyPair("RS256");+ const rotatedJwk = {+ ...(await exportJWK(rotated.publicKey)),+ kid: "k2",+ alg: "RS256",+ };+ const token = await sign({+ iss: `https://integrations.vercel.com/${integrationId}`,+ kid: "k2",+ key: rotated.privateKey,+ });++ expect(+ await authenticateUser(request(token), {}, RateLimiterMode.Scrape),+ ).toEqual(UNAUTHORIZED);+ expect(+ vi+ .mocked(setValue)+ .mock.calls.some(([key]) => key.startsWith("vercel_oidc_token:")),+ ).toBe(false);++ jwksFetch.mockImplementation(+ async () =>+ new Response(JSON.stringify({ keys: [jwk, rotatedJwk] }), {+ status: 200,+ headers: { "Content-Type": "application/json" },+ }),+ );+ vi.setSystemTime(Date.now() + 31_000);++ const auth = await authenticateUser(+ request(token),+ {},+ RateLimiterMode.Scrape,+ );+ expect(auth.success).toBe(true);+ expect(jwksFetch).toHaveBeenCalledTimes(2);+ });++ it("rejects a non-RS256 token with 401", async () => {+ const rs512 = await generateKeyPair("RS512");+ const auth = await authenticateUser(+ request(await sign({ alg: "RS512", key: rs512.privateKey })),+ {},+ RateLimiterMode.Scrape,+ );+ expect(auth).toEqual(UNAUTHORIZED);+ expect(authCreditUsageChunk).not.toHaveBeenCalled();+ });++ it("rejects an unknown installation or resource with 401 after checking the primary", async () => {+ rows.replica = [];+ rows.primary = [];++ const auth = await authenticateUser(+ request(await sign({ aud: "icfg_unknown", resource: "res_unknown" })),+ {},+ RateLimiterMode.Scrape,+ );++ expect(auth).toEqual(UNAUTHORIZED);+ expect(authCreditUsageChunk).not.toHaveBeenCalled();+ });++ it("accepts a resource the replica has not caught up on yet", async () => {+ rows.replica = [];+ rows.primary = [{ teamId: TEAM_ID, apiKey: API_KEY }];++ const auth = await authenticateUser(+ request(await sign()),+ {},+ RateLimiterMode.Scrape,+ );++ expect(auth.success).toBe(true);+ });++ it("falls back to the primary when the resource replica query fails", async () => {+ errors.replica = new Error("replica unavailable");+ rows.primary = [{ teamId: TEAM_ID, apiKey: API_KEY }];++ const auth = await authenticateUser(+ request(await sign()),+ {},+ RateLimiterMode.Scrape,+ );++ expect(auth.success).toBe(true);+ expect(logger.warn).toHaveBeenCalledWith(+ "Vercel OIDC resource replica lookup failed",+ expect.any(Object),+ );+ });++ it("falls back to the primary when the replica row has no team", async () => {+ rows.replica = [{ teamId: null, apiKey: API_KEY }];+ rows.primary = [{ teamId: TEAM_ID, apiKey: API_KEY }];++ const auth = await authenticateUser(+ request(await sign()),+ {},+ RateLimiterMode.Scrape,+ );++ expect(auth.success).toBe(true);+ });++ it("rejects a resource whose api_key_id is null with 401", async () => {+ rows.replica = [{ teamId: TEAM_ID, apiKey: null }];+ rows.primary = [{ teamId: TEAM_ID, apiKey: null }];++ const auth = await authenticateUser(+ request(await sign()),+ {},+ RateLimiterMode.Scrape,+ );++ expect(auth).toEqual(UNAUTHORIZED);+ expect(authCreditUsageChunk).not.toHaveBeenCalled();+ });++ it("rejects when the key's team differs from the resource's team", async () => {+ vi.mocked(authCreditUsageChunk).mockResolvedValue([+ {+ api_key: API_KEY,+ api_key_id: 7,+ team_id: "33333333-3333-4333-8333-333333333333",+ org_id: "org-2",+ flags: null,+ },+ ] as never);++ const auth = await authenticateUser(+ request(await sign()),+ {},+ RateLimiterMode.Scrape,+ );++ expect(auth).toEqual(UNAUTHORIZED);+ expect(logger.warn).toHaveBeenCalledWith(+ "Request denied",+ expect.objectContaining({+ canonicalLog: "auth/denied",+ reason: "vercel_oidc_team_mismatch",+ status: 401,+ }),+ );+ });++ it("returns 503 when no signing keys can be fetched", async () => {+ config.VERCEL_MARKETPLACE_INTEGRATION_ID = "oac_jwksdown";+ vi.spyOn(logger, "error").mockImplementation(() => logger);+ jwksFetch.mockImplementation(async () => new Response("", { status: 500 }));++ const auth = await authenticateUser(+ request(+ await sign({ iss: "https://integrations.vercel.com/oac_jwksdown" }),+ ),+ {},+ RateLimiterMode.Scrape,+ );++ expect(auth).toEqual({+ success: false,+ error: "Vercel authentication is temporarily unavailable",+ status: 503,+ });+ });++ it("leaves fc- API keys on the existing path", async () => {+ const auth = await authenticateUser(+ request("fc-11111111111141118111111111111111"),+ {},+ RateLimiterMode.Scrape,+ );++ expect(auth.success).toBe(true);+ expect(jwksFetch).not.toHaveBeenCalled();+ expect(authCreditUsageChunk).toHaveBeenCalledWith(+ expect.anything(),+ API_KEY,+ "general",+ );+ });++ it("treats JWTs as ordinary invalid keys when the integration is not configured", async () => {+ config.VERCEL_MARKETPLACE_INTEGRATION_ID = undefined;++ const auth = await authenticateUser(+ request(await sign()),+ {},+ RateLimiterMode.Scrape,+ );++ expect(auth).toEqual(UNAUTHORIZED);+ expect(jwksFetch).not.toHaveBeenCalled();+ expect(authCreditUsageChunk).not.toHaveBeenCalled();+ });++ it("does not enter the Marketplace auth path without DB authentication", async () => {+ config.USE_DB_AUTHENTICATION = false;++ const auth = await authenticateUser(+ request(await sign()),+ {},+ RateLimiterMode.Scrape,+ );++ expect(auth).toMatchObject({ success: true, team_id: "bypass" });+ expect(jwksFetch).not.toHaveBeenCalled();+ expect(authCreditUsageChunk).not.toHaveBeenCalled();+ });+});diff --git a/apps/api/src/controllers/auth.ts b/apps/api/src/controllers/auth.tsindex a615fc005..a06b054df 100644--- a/apps/api/src/controllers/auth.ts+++ b/apps/api/src/controllers/auth.ts@@ -51,6 +51,14 @@ import {} from "../services/oauth-token-introspection";import type { OAuthIntrospectionResponse } from "../services/oauth-token-introspection";import { verifyMcpDelegatedCredential } from "../lib/mcp-delegated-credential";+import {+ looksLikeJwt,+ VercelJwksUnavailableError,+} from "../lib/vercel-marketplace-oidc";+import {+ resolveVercelOidcToken,+ type VercelOidcResolution,+} from "../services/vercel-marketplace-oidc";import {autumnService,DEFAULT_TEAM_LIMITS,@@ -1033,6 +1041,71 @@ async function supaAuthenticateUser(mode,minRateMultiplier,);+ } else if (+ config.USE_DB_AUTHENTICATION === true &&+ config.VERCEL_MARKETPLACE_INTEGRATION_ID &&+ looksLikeJwt(token)+ ) {+ // Vercel Marketplace OIDC resource token. It resolves to the API key issued+ // for the resource, so per-key behavior and billing stay on the key path.+ let resolution: VercelOidcResolution;+ try {+ resolution = await resolveVercelOidcToken(+ token,+ config.VERCEL_MARKETPLACE_INTEGRATION_ID,+ );+ } catch (error) {+ if (error instanceof VercelJwksUnavailableError) {+ return {+ success: false,+ error: "Vercel authentication is temporarily unavailable",+ status: 503,+ };+ }+ throw error;+ }+ if (!resolution.ok) {+ return denied(req, "invalid_vercel_oidc_token", {+ success: false,+ error: "Unauthorized: Invalid token",+ status: 401,+ });+ }++ chunk = await getACUC(+ resolution.apiKey,+ false,+ true,+ RateLimiterMode.Scrape,+ "general",+ );+ if (chunk === null) {+ return denied(req, "unknown_key", {+ success: false,+ error: "Unauthorized: Invalid token",+ status: 401,+ });+ }+ if (chunk.team_id !== resolution.teamId) {+ return denied(+ req,+ "vercel_oidc_team_mismatch",+ {+ success: false,+ error: "Unauthorized: Invalid token",+ status: 401,+ },+ chunk,+ );+ }++ teamId = chunk.team_id;+ subscriptionData = { team_id: teamId };+ rateLimiter = await buildAuthenticatedRateLimiter(+ chunk,+ mode,+ minRateMultiplier,+ );} else {normalizedApi = parseApi(token);if (!normalizedApiIsUuid(normalizedApi)) {diff --git a/apps/api/src/db/schema/public.ts b/apps/api/src/db/schema/public.tsindex 43d20b846..e5040d016 100644--- a/apps/api/src/db/schema/public.ts+++ b/apps/api/src/db/schema/public.ts@@ -86,6 +86,42 @@ export const api_keys = pgTable(],);+// Vercel Marketplace installations (icfg_...) and the resources provisioned+// under them. Written by the integration webhooks outside this service; the+// API only reads them, to resolve a Vercel OIDC resource token to the key+// issued for that resource.+const vercel_marketplace_installations = pgTable(+ "vercel_marketplace_installations",+ {+ installation_id: text("installation_id").primaryKey(),+ team_id: uuid("team_id"),+ created_at: ts("created_at").notNull().defaultNow(),+ updated_at: ts("updated_at").notNull().defaultNow(),+ },+);++export const vercel_marketplace_resources = pgTable(+ "vercel_marketplace_resources",+ {+ installation_id: text("installation_id")+ .notNull()+ .references(() => vercel_marketplace_installations.installation_id, {+ onDelete: "cascade",+ }),+ resource_id: text("resource_id").notNull(),+ api_key_id: bigintNum("api_key_id").references(() => api_keys.id, {+ onDelete: "set null",+ }),+ team_id: uuid("team_id"),+ resource_name: text("resource_name"),+ created_at: ts("created_at").notNull().defaultNow(),+ updated_at: ts("updated_at").notNull().defaultNow(),+ },+ table => [+ primaryKey({ columns: [table.installation_id, table.resource_id] }),+ ],+);+export const blocklist = pgTable("blocklist", {id: bigintNum("id").notNull().generatedByDefaultAsIdentity(),data: jsonb("data").notNull(),diff --git a/apps/api/src/lib/__tests__/vercel-marketplace-oidc.test.ts b/apps/api/src/lib/__tests__/vercel-marketplace-oidc.test.tsnew file mode 100644index 000000000..8c49319d1--- /dev/null+++ b/apps/api/src/lib/__tests__/vercel-marketplace-oidc.test.ts@@ -0,0 +1,311 @@+import { beforeAll, describe, expect, it, vi } from "vitest";+import { exportJWK, generateKeyPair, SignJWT, type JWK } from "jose";+import {+ createVercelJwks,+ looksLikeJwt,+ VercelJwksUnavailableError,+ VercelOidcTokenInvalidError,+ verifyVercelOidcToken,+} from "../vercel-marketplace-oidc";+import { logger } from "../logger";++const INTEGRATION_ID = "oac_test123";+const ISSUER = `https://integrations.vercel.com/${INTEGRATION_ID}`;+const JWKS_URL = `${ISSUER}/jwks.json`;++type KeyPair = Awaited<ReturnType<typeof generateKeyPair>>;+let signing: KeyPair;+let other: KeyPair;+let signingJwk: JWK;+let otherJwk: JWK;++beforeAll(async () => {+ signing = await generateKeyPair("RS256");+ other = await generateKeyPair("RS256");+ signingJwk = {+ ...(await exportJWK(signing.publicKey)),+ kid: "k1",+ alg: "RS256",+ };+ otherJwk = { ...(await exportJWK(other.publicKey)), kid: "k2", alg: "RS256" };+});++function jwksResponse(keys: JWK[], cacheControl?: string) {+ return new Response(JSON.stringify({ keys }), {+ status: 200,+ headers: {+ "Content-Type": "application/json",+ ...(cacheControl ? { "Cache-Control": cacheControl } : {}),+ },+ });+}++async function sign(+ overrides: {+ claims?: Record<string, unknown>;+ aud?: string | string[];+ iss?: string;+ kid?: string;+ key?: KeyPair["privateKey"];+ alg?: string;+ expSecondsFromNow?: number;+ } = {},+) {+ const now = Math.floor(Date.now() / 1000);+ return new SignJWT({+ act: { sub: "owner:team_abc:project:prj_abc:environment:production" },+ environment: "production",+ ...overrides.claims,+ })+ .setProtectedHeader({+ alg: overrides.alg ?? "RS256",+ kid: overrides.kid ?? "k1",+ })+ .setIssuer(overrides.iss ?? ISSUER)+ .setAudience(overrides.aud ?? "icfg_1")+ .setSubject("res_1")+ .setIssuedAt(now)+ .setNotBefore(now)+ .setExpirationTime(now + (overrides.expSecondsFromNow ?? 300))+ .sign(overrides.key ?? signing.privateKey);+}++function staticJwks() {+ return createVercelJwks(JWKS_URL, {+ fetchFn: vi.fn().mockImplementation(async () => jwksResponse([signingJwk])),+ });+}++async function expectInvalid(token: string, getKey = staticJwks()) {+ await expect(+ verifyVercelOidcToken(token, { integrationId: INTEGRATION_ID, getKey }),+ ).rejects.toBeInstanceOf(VercelOidcTokenInvalidError);+}++describe("looksLikeJwt", () => {+ it("matches a three-segment token with a JSON header", async () => {+ expect(looksLikeJwt(await sign())).toBe(true);+ });++ it("does not match Firecrawl API keys or other bearer tokens", () => {+ expect(looksLikeJwt("fc-11111111111111118111111111111111")).toBe(false);+ expect(looksLikeJwt("11111111-1111-1111-8111-111111111111")).toBe(false);+ expect(looksLikeJwt("fco_access_token")).toBe(false);+ expect(looksLikeJwt("eyJhbGciOiJSUzI1NiJ9.onlytwo")).toBe(false);+ });+});++describe("verifyVercelOidcToken", () => {+ it("returns the claims of a valid resource token", async () => {+ const claims = await verifyVercelOidcToken(await sign(), {+ integrationId: INTEGRATION_ID,+ getKey: staticJwks(),+ });+ expect(claims).toMatchObject({+ iss: ISSUER,+ aud: "icfg_1",+ sub: "res_1",+ actor: "owner:team_abc:project:prj_abc:environment:production",+ environment: "production",+ });+ });++ it("rejects a token from another integration", async () => {+ await expectInvalid(+ await sign({ iss: "https://integrations.vercel.com/oac_other" }),+ );+ });++ it("rejects a non-RS256 algorithm", async () => {+ const rs512 = await generateKeyPair("RS512");+ const jwk = { ...(await exportJWK(rs512.publicKey)), kid: "k3" };+ const getKey = createVercelJwks(JWKS_URL, {+ fetchFn: vi.fn().mockImplementation(async () => jwksResponse([jwk])),+ });+ await expectInvalid(+ await sign({ alg: "RS512", kid: "k3", key: rs512.privateKey }),+ getKey,+ );+ });++ it("rejects a token signed by a key outside the JWKS", async () => {+ await expectInvalid(await sign({ key: other.privateKey }));+ });++ it("rejects an expired token beyond the clock tolerance", async () => {+ await expectInvalid(await sign({ expSecondsFromNow: -120 }));+ });++ it("accepts a token within the 60s clock tolerance", async () => {+ await expect(+ verifyVercelOidcToken(await sign({ expSecondsFromNow: -30 }), {+ integrationId: INTEGRATION_ID,+ getKey: staticJwks(),+ }),+ ).resolves.toMatchObject({ sub: "res_1" });+ });++ it("rejects an aud that is not a single string", async () => {+ await expectInvalid(await sign({ aud: ["icfg_1", "icfg_2"] }));+ });++ it("rejects a token without an act claim", async () => {+ await expectInvalid(await sign({ claims: { act: undefined } }));+ });++ it("accepts a resource claim that matches sub", async () => {+ await expect(+ verifyVercelOidcToken(await sign({ claims: { resource: "res_1" } }), {+ integrationId: INTEGRATION_ID,+ getKey: staticJwks(),+ }),+ ).resolves.toMatchObject({ sub: "res_1" });+ });++ it("rejects a token whose resource claim disagrees with sub", async () => {+ await expect(+ verifyVercelOidcToken(await sign({ claims: { resource: "res_2" } }), {+ integrationId: INTEGRATION_ID,+ getKey: staticJwks(),+ }),+ ).rejects.toMatchObject({ reason: "resource_sub_mismatch" });+ });+});++describe("createVercelJwks", () => {+ it("caches keys for the Cache-Control max-age", async () => {+ let now = 1_000_000;+ const fetchFn = vi+ .fn()+ .mockImplementation(async () =>+ jwksResponse([signingJwk], "public, max-age=3600"),+ );+ const getKey = createVercelJwks(JWKS_URL, { fetchFn, now: () => now });+ const token = await sign();++ await verifyVercelOidcToken(token, {+ integrationId: INTEGRATION_ID,+ getKey,+ });+ now += 3_599_000;+ await verifyVercelOidcToken(token, {+ integrationId: INTEGRATION_ID,+ getKey,+ });+ expect(fetchFn).toHaveBeenCalledTimes(1);++ now += 2_000;+ await verifyVercelOidcToken(token, {+ integrationId: INTEGRATION_ID,+ getKey,+ });+ expect(fetchFn).toHaveBeenCalledTimes(2);+ });++ it("refetches on an unknown kid, at most once per cooldown", async () => {+ let now = 1_000_000;+ const fetchFn = vi+ .fn()+ .mockImplementationOnce(async () => jwksResponse([signingJwk]))+ .mockImplementation(async () => jwksResponse([signingJwk, otherJwk]));+ const getKey = createVercelJwks(JWKS_URL, { fetchFn, now: () => now });++ await verifyVercelOidcToken(await sign(), {+ integrationId: INTEGRATION_ID,+ getKey,+ });+ const rotated = await sign({ kid: "k2", key: other.privateKey });++ // Inside the cooldown the unknown kid is rejected without a refetch.+ now += 10_000;+ await expectInvalid(rotated, getKey);+ expect(fetchFn).toHaveBeenCalledTimes(1);++ now += 30_000;+ await expect(+ verifyVercelOidcToken(rotated, { integrationId: INTEGRATION_ID, getKey }),+ ).resolves.toMatchObject({ sub: "res_1" });+ expect(fetchFn).toHaveBeenCalledTimes(2);+ });++ it("returns unavailable when a rotated key cannot be fetched", async () => {+ let now = 1_000_000;+ const error = vi.spyOn(logger, "error").mockImplementation(() => logger);+ const fetchFn = vi+ .fn()+ .mockImplementationOnce(async () => jwksResponse([signingJwk]))+ .mockImplementation(async () => new Response("down", { status: 503 }));+ const getKey = createVercelJwks(JWKS_URL, { fetchFn, now: () => now });++ await verifyVercelOidcToken(await sign(), {+ integrationId: INTEGRATION_ID,+ getKey,+ });+ now += 31_000;++ await expect(+ verifyVercelOidcToken(await sign({ kid: "k2", key: other.privateKey }), {+ integrationId: INTEGRATION_ID,+ getKey,+ }),+ ).rejects.toBeInstanceOf(VercelJwksUnavailableError);+ expect(fetchFn).toHaveBeenCalledTimes(2);+ error.mockRestore();+ });++ it("keeps using cached keys for up to 24h when a refresh fails", async () => {+ let now = 1_000_000;+ const error = vi.spyOn(logger, "error").mockImplementation(() => logger);+ const failedResponse = new Response("down", { status: 503 });+ const cancelBody = vi.spyOn(failedResponse.body!, "cancel");+ const fetchFn = vi+ .fn()+ .mockImplementationOnce(async () => jwksResponse([signingJwk]))+ .mockImplementation(async () => failedResponse);+ const getKey = createVercelJwks(JWKS_URL, { fetchFn, now: () => now });+ const token = await sign();++ await verifyVercelOidcToken(token, {+ integrationId: INTEGRATION_ID,+ getKey,+ });+ now += 2 * 60 * 60 * 1000;+ await expect(+ verifyVercelOidcToken(token, { integrationId: INTEGRATION_ID, getKey }),+ ).resolves.toMatchObject({ sub: "res_1" });+ expect(error).toHaveBeenCalledWith(+ "Vercel Marketplace JWKS refresh failed, using cached keys",+ expect.any(Object),+ );+ expect(fetchFn).toHaveBeenCalledTimes(2);+ expect(cancelBody).toHaveBeenCalledTimes(1);++ // The failed refresh is not retried on every request.+ now += 1_000;+ await verifyVercelOidcToken(token, {+ integrationId: INTEGRATION_ID,+ getKey,+ });+ expect(fetchFn).toHaveBeenCalledTimes(2);++ now += 23 * 60 * 60 * 1000;+ await expect(+ verifyVercelOidcToken(token, { integrationId: INTEGRATION_ID, getKey }),+ ).rejects.toBeInstanceOf(VercelJwksUnavailableError);+ error.mockRestore();+ });++ it("reports the JWKS unavailable when the first fetch fails", async () => {+ const error = vi.spyOn(logger, "error").mockImplementation(() => logger);+ const getKey = createVercelJwks(JWKS_URL, {+ fetchFn: vi.fn().mockRejectedValue(new Error("network")),+ });+ await expect(+ verifyVercelOidcToken(await sign(), {+ integrationId: INTEGRATION_ID,+ getKey,+ }),+ ).rejects.toBeInstanceOf(VercelJwksUnavailableError);+ error.mockRestore();+ });+});diff --git a/apps/api/src/lib/auth-denied-log.ts b/apps/api/src/lib/auth-denied-log.tsindex 72a094e47..a9c522bde 100644--- a/apps/api/src/lib/auth-denied-log.ts+++ b/apps/api/src/lib/auth-denied-log.ts@@ -13,6 +13,8 @@ export type AuthDenialReason =| "invalid_oauth_token"| "oauth_purpose_mismatch"| "oauth_team_mismatch"+ | "invalid_vercel_oidc_token"+ | "vercel_oidc_team_mismatch"| "team_banned"| "ip_restricted"| "endpoint_restricted"diff --git a/apps/api/src/lib/vercel-marketplace-oidc.ts b/apps/api/src/lib/vercel-marketplace-oidc.tsnew file mode 100644index 000000000..9d3ea9113--- /dev/null+++ b/apps/api/src/lib/vercel-marketplace-oidc.ts@@ -0,0 +1,240 @@+import {+ createLocalJWKSet,+ errors as joseErrors,+ jwtVerify,+ type JSONWebKeySet,+ type JWTVerifyGetKey,+} from "jose";+import { logger } from "./logger";++// Vercel Marketplace OIDC resource tokens. A customer's Vercel deployment mints+// a short-lived RS256 JWT for one of our resources and sends it as the bearer+// credential. We only verify it; Vercel hosts the mint endpoint.++const VERCEL_INTEGRATIONS_ORIGIN = "https://integrations.vercel.com";+// Vercel's contract sets the access token TTL to 15 minutes.+const CLOCK_TOLERANCE_SECONDS = 60;++const DEFAULT_JWKS_MAX_AGE_MS = 60 * 60 * 1000;+const MIN_JWKS_MAX_AGE_MS = 60 * 1000;+// Vercel's contract: keep serving cached keys for up to 24h when a refresh fails.+const JWKS_STALE_LIMIT_MS = 24 * 60 * 60 * 1000;+// Refetches (unknown kid, or retrying after a failure) are rate-limited to one+// per this window.+const JWKS_REFETCH_COOLDOWN_MS = 30 * 1000;+const JWKS_FETCH_TIMEOUT_MS = 5_000;++type Fetch = (+ input: string | URL | Request,+ init?: RequestInit,+) => Promise<Response>;++interface VercelOidcClaims {+ iss: string;+ aud: string;+ sub: string;+ actor: string;+ role?: string;+ environment?: string;+ exp: number;+ iat: number;+}++export class VercelJwksUnavailableError extends Error {+ constructor(message = "Vercel Marketplace JWKS is unavailable") {+ super(message);+ this.name = "VercelJwksUnavailableError";+ }+}++export class VercelOidcTokenInvalidError extends Error {+ constructor(readonly reason: string) {+ super(`Invalid Vercel Marketplace OIDC token: ${reason}`);+ this.name = "VercelOidcTokenInvalidError";+ }+}++/**+ * Cheap shape check: three base64url segments with a JSON header. Firecrawl+ * API keys (fc-..., bare uuids) never match, so they skip this branch.+ */+export function looksLikeJwt(token: string): boolean {+ return token.startsWith("eyJ") && /^[\w-]+\.[\w-]+\.[\w-]+$/.test(token);+}++export function vercelIssuer(integrationId: string): string {+ return `${VERCEL_INTEGRATIONS_ORIGIN}/${integrationId}`;+}++function maxAgeFromCacheControl(header: string | null): number {+ const match = header?.match(/(?:^|,)\s*max-age=(\d+)/i);+ if (!match) return DEFAULT_JWKS_MAX_AGE_MS;+ return Math.min(+ Math.max(Number(match[1]) * 1000, MIN_JWKS_MAX_AGE_MS),+ JWKS_STALE_LIMIT_MS,+ );+}++/**+ * Remote JWKS resolver following Vercel's key-rotation contract. jose's+ * createRemoteJWKSet ignores Cache-Control and fails closed when a refresh+ * fails, so this wraps createLocalJWKSet instead:+ * - keys are fresh for the response's Cache-Control max-age (default 1h),+ * - an unknown kid triggers at most one refetch per 30s cooldown,+ * - a failed refresh keeps the last good keys for up to 24h, logs an error,+ * and is retried at most once per cooldown.+ */+export function createVercelJwks(+ jwksUrl: string,+ options: { fetchFn?: Fetch; now?: () => number } = {},+): JWTVerifyGetKey {+ const fetchFn: Fetch =+ options.fetchFn ?? ((input, init) => fetch(input, init));+ const now = options.now ?? Date.now;+ let local: ReturnType<typeof createLocalJWKSet> | undefined;+ let fetchedAt = 0;+ let maxAgeMs = DEFAULT_JWKS_MAX_AGE_MS;+ let lastAttemptAt = Number.NEGATIVE_INFINITY;+ let lastRefreshFailed = false;+ let pending: Promise<void> | undefined;++ const fetchKeys = async (): Promise<void> => {+ lastAttemptAt = now();+ const response = await fetchFn(jwksUrl, {+ method: "GET",+ headers: { accept: "application/json" },+ redirect: "manual",+ signal: AbortSignal.timeout(JWKS_FETCH_TIMEOUT_MS),+ });+ if (response.status !== 200) {+ await response.body?.cancel();+ throw new Error(`JWKS fetch returned HTTP ${response.status}`);+ }+ const jwks = (await response.json()) as JSONWebKeySet;+ local = createLocalJWKSet(jwks);+ fetchedAt = now();+ maxAgeMs = maxAgeFromCacheControl(response.headers.get("cache-control"));+ };++ // Refreshes the key set, deduplicating concurrent callers. A failed refresh+ // is tolerated while the last good keys are under 24h old.+ const refresh = async (): Promise<boolean> => {+ pending ??= fetchKeys().finally(() => {+ pending = undefined;+ });+ try {+ await pending;+ lastRefreshFailed = false;+ return true;+ } catch (error) {+ if (local && now() - fetchedAt < JWKS_STALE_LIMIT_MS) {+ lastRefreshFailed = true;+ logger.error(+ "Vercel Marketplace JWKS refresh failed, using cached keys",+ {+ error,+ keysAgeMs: now() - fetchedAt,+ },+ );+ return false;+ }+ lastRefreshFailed = true;+ logger.error("Vercel Marketplace JWKS fetch failed, no usable keys", {+ error,+ });+ throw new VercelJwksUnavailableError();+ }+ };++ const coolingDown = () => now() - lastAttemptAt < JWKS_REFETCH_COOLDOWN_MS;++ const ensureKeys = async (): Promise<void> => {+ const age = now() - fetchedAt;+ if (local && age < maxAgeMs) return;+ if (pending || !coolingDown()) {+ await refresh();+ return;+ }+ // A refresh failed moments ago: serve cached keys inside the stale limit+ // rather than refetching on every request.+ if (!local || age >= JWKS_STALE_LIMIT_MS) {+ throw new VercelJwksUnavailableError();+ }+ };++ return async (protectedHeader, token) => {+ await ensureKeys();+ try {+ return await local!(protectedHeader, token);+ } catch (error) {+ if (error instanceof joseErrors.JWKSNoMatchingKey) {+ if (pending || !coolingDown()) {+ if (!(await refresh())) throw new VercelJwksUnavailableError();+ return local!(protectedHeader, token);+ }+ if (lastRefreshFailed) throw new VercelJwksUnavailableError();+ }+ throw error;+ }+ };+}++function optionalString(value: unknown): string | undefined {+ return typeof value === "string" ? value : undefined;+}++/**+ * Verifies a Vercel Marketplace OIDC resource token: RS256 only, exact issuer+ * for our integration, a single-string aud (the installation id), sub (our+ * resource id, matching `resource` when present) and act.sub. aud is not pinned here because it varies per+ * installation; the caller checks it against the stored installation.+ */+export async function verifyVercelOidcToken(+ token: string,+ options: {+ integrationId: string;+ getKey: JWTVerifyGetKey;+ },+): Promise<VercelOidcClaims> {+ let payload: Record<string, unknown>;+ try {+ ({ payload } = await jwtVerify(token, options.getKey, {+ issuer: vercelIssuer(options.integrationId),+ algorithms: ["RS256"],+ clockTolerance: CLOCK_TOLERANCE_SECONDS,+ requiredClaims: ["exp", "iat", "nbf", "aud", "sub", "act"],+ }));+ } catch (error) {+ if (error instanceof VercelJwksUnavailableError) throw error;+ const code =+ error instanceof joseErrors.JOSEError ? error.code : "ERR_UNKNOWN";+ throw new VercelOidcTokenInvalidError(code);+ }++ if (typeof payload.aud !== "string" || payload.aud.length === 0) {+ throw new VercelOidcTokenInvalidError("aud_not_single_string");+ }+ if (typeof payload.sub !== "string" || payload.sub.length === 0) {+ throw new VercelOidcTokenInvalidError("missing_sub");+ }+ // Vercel's earlier contract carried the resource id in `resource` and a role+ // in `sub`. A token where the two disagree is never bound to a resource.+ if (payload.resource !== undefined && payload.resource !== payload.sub) {+ throw new VercelOidcTokenInvalidError("resource_sub_mismatch");+ }+ const actor = optionalString((payload.act as { sub?: unknown } | null)?.sub);+ if (!actor) {+ throw new VercelOidcTokenInvalidError("missing_act");+ }++ return {+ iss: payload.iss as string,+ aud: payload.aud,+ sub: payload.sub,+ actor,+ role: optionalString(payload.role),+ environment: optionalString(payload.environment),+ exp: payload.exp as number,+ iat: payload.iat as number,+ };+}diff --git a/apps/api/src/services/vercel-marketplace-oidc.ts b/apps/api/src/services/vercel-marketplace-oidc.tsnew file mode 100644index 000000000..9b17d879a--- /dev/null+++ b/apps/api/src/services/vercel-marketplace-oidc.ts@@ -0,0 +1,199 @@+import { createHash } from "node:crypto";+import { and, eq } from "drizzle-orm";+import type { JWTVerifyGetKey } from "jose";+import { db, dbRr } from "../db/connection";+import * as schema from "../db/schema";+import { logger } from "../lib/logger";+import {+ createVercelJwks,+ VercelOidcTokenInvalidError,+ vercelIssuer,+ verifyVercelOidcToken,+} from "../lib/vercel-marketplace-oidc";+import { getValue, setValue } from "./redis";++const MAX_POSITIVE_CACHE_TTL_SECONDS = 300;+const NEGATIVE_CACHE_TTL_SECONDS = 60;++export type VercelOidcResolution =+ | {+ ok: true;+ // api_keys.key (uuid form), fed to the regular ACUC lookup.+ apiKey: string;+ // vercel_marketplace_resources.team_id; the caller checks it against the+ // key's team.+ teamId: string;+ installationId: string;+ resourceId: string;+ }+ | { ok: false; reason: string };++const jwksByIntegration = new Map<string, JWTVerifyGetKey>();++function jwksFor(integrationId: string): JWTVerifyGetKey {+ let getKey = jwksByIntegration.get(integrationId);+ if (!getKey) {+ getKey = createVercelJwks(`${vercelIssuer(integrationId)}/jwks.json`);+ jwksByIntegration.set(integrationId, getKey);+ }+ return getKey;+}++function cacheKey(integrationId: string, token: string): string {+ const hash = createHash("sha256").update(token).digest("hex");+ return `vercel_oidc_token:${integrationId}:${hash.slice(0, 32)}`;+}++async function readCache(key: string): Promise<VercelOidcResolution | null> {+ try {+ const cached = await getValue(key);+ if (cached === null) return null;+ const parsed = JSON.parse(cached) as VercelOidcResolution;+ if (+ parsed.ok === false &&+ typeof parsed.reason === "string" &&+ parsed.reason.length > 0+ ) {+ return parsed;+ }+ if (+ parsed.ok === true &&+ typeof parsed.apiKey === "string" &&+ typeof parsed.teamId === "string"+ ) {+ return parsed;+ }+ } catch (error) {+ // Redis and malformed entries are treated as misses; verification stays+ // authoritative.+ logger.warn("Vercel OIDC token cache read failed", { error });+ }+ return null;+}++async function writeCache(+ key: string,+ value: VercelOidcResolution,+ ttlSeconds: number,+): Promise<void> {+ if (ttlSeconds <= 0) return;+ try {+ await setValue(key, JSON.stringify(value), ttlSeconds);+ } catch (error) {+ logger.warn("Vercel OIDC token cache write failed", { error });+ }+}++async function lookupResource(installationId: string, resourceId: string) {+ const query = (database: typeof db) =>+ database+ .select({+ teamId: schema.vercel_marketplace_resources.team_id,+ apiKey: schema.api_keys.key,+ })+ .from(schema.vercel_marketplace_resources)+ .leftJoin(+ schema.api_keys,+ eq(schema.api_keys.id, schema.vercel_marketplace_resources.api_key_id),+ )+ .where(+ and(+ eq(+ schema.vercel_marketplace_resources.installation_id,+ installationId,+ ),+ eq(schema.vercel_marketplace_resources.resource_id, resourceId),+ ),+ )+ .limit(1);++ // The replica serves the steady state. A miss re-reads the primary so a+ // resource provisioned moments ago is not negatively cached through replica+ // lag.+ let replicaRow: Awaited<ReturnType<typeof query>>[number] | undefined;+ try {+ [replicaRow] = await query(dbRr);+ } catch (error) {+ logger.warn("Vercel OIDC resource replica lookup failed", { error });+ }+ if (replicaRow?.apiKey && replicaRow.teamId) return replicaRow;+ const [primaryRow] = await query(db);+ return primaryRow;+}++/**+ * Resolves a Vercel Marketplace OIDC resource token to the API key issued for+ * that resource. Verified resolutions are cached by token hash until the token+ * expires (at most 5 minutes). Unknown resources are cached for a minute;+ * signature and claim rejections are not cached, since they depend on the+ * pod's current signing keys.+ *+ * Throws VercelJwksUnavailableError when no usable signing keys are available.+ */+export async function resolveVercelOidcToken(+ token: string,+ integrationId: string,+): Promise<VercelOidcResolution> {+ const key = cacheKey(integrationId, token);+ const cached = await readCache(key);+ if (cached) return cached;++ let claims;+ try {+ claims = await verifyVercelOidcToken(token, {+ integrationId,+ getKey: jwksFor(integrationId),+ });+ } catch (error) {+ if (error instanceof VercelOidcTokenInvalidError) {+ logger.warn("Vercel OIDC token rejected", { reason: error.reason });+ return { ok: false, reason: error.reason };+ }+ throw error;+ }++ const audit = {+ installationId: claims.aud,+ resourceId: claims.sub,+ actor: claims.actor,+ role: claims.role,+ environment: claims.environment,+ };++ const row = await lookupResource(claims.aud, claims.sub);+ if (!row || !row.apiKey || !row.teamId) {+ const rejected = {+ ok: false as const,+ reason: !row+ ? "unknown_resource"+ : !row.apiKey+ ? "resource_has_no_key"+ : "resource_has_no_team",+ };+ logger.warn("Vercel OIDC token rejected", {+ ...audit,+ reason: rejected.reason,+ });+ await writeCache(key, rejected, NEGATIVE_CACHE_TTL_SECONDS);+ return rejected;+ }++ const resolution = {+ ok: true as const,+ apiKey: row.apiKey,+ teamId: row.teamId,+ installationId: claims.aud,+ resourceId: claims.sub,+ };+ logger.info("Vercel OIDC token verified", { ...audit, teamId: row.teamId });++ await writeCache(+ key,+ resolution,+ Math.min(+ claims.exp - Math.floor(Date.now() / 1000),+ MAX_POSITIVE_CACHE_TTL_SECONDS,+ ),+ );+ return resolution;+}