diff --git a/app/mcp/__tests__/oauthRoute.test.ts b/app/mcp/__tests__/oauthRoute.test.ts index cddf0536e..2596e5caf 100644 --- a/app/mcp/__tests__/oauthRoute.test.ts +++ b/app/mcp/__tests__/oauthRoute.test.ts @@ -82,6 +82,7 @@ it.each([false, true])( "list_artists", "open_recoup_workflows", "open_recoup_workflows_sidebar", + "recoup_skills", ]); const result = await client.callTool({ name: "get_tasks", arguments: {} }); expect(result.isError).not.toBe(true); @@ -185,6 +186,14 @@ it("advertises native skills and serves their manifests and files through authen expect(listing.result.cacheScope).toBe("private"); expect(listing.result.skills.map((skill: { uri: string }) => skill.uri)).toEqual([publicSkill]); + vi.stubEnv("OAUTH_ISSUER", ""); + vi.stubEnv("OAUTH_INDEX_KEY", ""); + const legacyCredential = await ( + await POST(modernRequest("tools/call", { name: "recoup_skills", arguments: {} })) + ).json(); + expect(legacyCredential.result.isError).toBeFalsy(); + expect(legacyCredential.result.content[0].text).toContain("recoup-public-test"); + const lookup = await (await POST(modernRequest("skills/get", { uri: publicSkill }))).json(); expect(lookup.result.skill).toEqual(listing.result.skills[0]); const uri = "skill://recoup-public-test/references/checklist.md"; @@ -206,8 +215,8 @@ it("advertises native skills and serves their manifests and files through authen isRecoupAdmin.mockResolvedValue(true); const staffOnMain = await (await POST(modernRequest("skills/get", { uri: staffSkill }))).json(); - expect(staffOnMain.error.code).toBe(-32602); - expect(isRecoupAdmin).not.toHaveBeenCalled(); + expect(staffOnMain.result.skill.uri).toBe(staffSkill); + expect(isRecoupAdmin).toHaveBeenCalledWith("member"); }); it("uses the same full OAuth tool restrictions and account binding on modern MCP", async () => { @@ -224,6 +233,7 @@ it("uses the same full OAuth tool restrictions and account binding on modern MCP "list_artists", "open_recoup_workflows", "open_recoup_workflows_sidebar", + "recoup_skills", ]); const called = await ( await POST(modernRequest("tools/call", { name: "get_tasks", arguments: {} })) @@ -243,10 +253,9 @@ it("serves public skills to limited OAuth grants without elevating their tool pe scopes: access.scopes, extra: { accountId: access.accountId, oauth: access }, }); - isRecoupAdmin.mockResolvedValue(true); + isRecoupAdmin.mockResolvedValue(false); const listing = await (await POST(modernRequest("skills/list"))).json(); expect(listing.result.skills.map((skill: { uri: string }) => skill.uri)).toEqual([publicSkill]); - expect(isRecoupAdmin).not.toHaveBeenCalled(); const write = await POST( modernRequest("tools/call", { name: "create_new_artist", arguments: { name: "Fixture" } }), ); @@ -352,3 +361,80 @@ it("grants staff skills to the exact configured account without requiring organi verify.mockResolvedValue({ ...auth, extra: { accountId: grantedAccount } }); expect((await staffPOST(request())).status).toBe(403); }); + +const checkFullOAuthRateLimit = vi.hoisted(() => vi.fn().mockResolvedValue(undefined)); +vi.mock("@/lib/mcp/oauth/checkFullOAuthRateLimit", () => ({ checkFullOAuthRateLimit })); + +const getVerifiedPrivyEmails = vi.hoisted(() => vi.fn()); +vi.mock("@/lib/privy/getVerifiedPrivyEmails", () => ({ getVerifiedPrivyEmails })); + +it("uses the signed-in identity for native skills and the ChatGPT tool on the same connection", async () => { + const subject = "did:privy:connector-staff"; + access.scopes = ["mcp:read"]; + verify.mockResolvedValue({ + token: "test", + clientId: access.clientId, + scopes: access.scopes, + extra: { accountId: access.accountId, oauth: { ...access, subject } }, + }); + isRecoupAdmin.mockResolvedValue(false); + const client = new Client({ name: "connector-fixture", version: "1" }); + await client.connect( + new StreamableHTTPClientTransport(new URL(access.resource), { + requestInit: { headers: { Authorization: "Bearer test" } }, + fetch: async (input, init) => POST(new Request(input, init)), + }), + ); + const tool = (args: Record) => + client.callTool({ name: "recoup_skills", arguments: args }); + try { + getVerifiedPrivyEmails.mockResolvedValue(["someone@recoupable.com.example"]); + const publicList = await tool({}); + expect(JSON.stringify(publicList)).toContain("recoup-public-test"); + expect(JSON.stringify(publicList)).not.toContain("recoup-internal-test"); + expect((await tool({ skill: "recoup-internal-test" })).isError).toBe(true); + expect((await tool({ file: "SKILL.md" })).isError).toBe(true); + expect((await tool({ skill: "recoup-public-test", query: "something" })).isError).toBe(true); + expect(checkFullOAuthRateLimit).toHaveBeenCalledWith("recoup_skills", access.accountId); + + checkFullOAuthRateLimit.mockRejectedValueOnce( + new Error("Tool rate limit reached; retry in 6 seconds"), + ); + const throttled = await tool({}); + expect(throttled.isError).toBe(true); + expect(JSON.stringify(throttled)).toContain("retry in 6 seconds"); + + getVerifiedPrivyEmails.mockResolvedValue(["staff@recoupable.com"]); + const staffList = await tool({}); + expect(JSON.stringify(staffList)).toContain("recoup-public-test"); + expect(JSON.stringify(staffList)).toContain("recoup-internal-test"); + expect(JSON.stringify(await tool({ skill: "recoup-internal-test" }))).toContain( + "name: recoup-internal-test", + ); + expect( + JSON.stringify(await tool({ skill: "recoup-public-test", file: "references/checklist.md" })), + ).toContain("Checklist"); + expect( + (await tool({ skill: "recoup-public-test", file: "../recoup-internal-test/SKILL.md" })) + .isError, + ).toBe(true); + expect(getVerifiedPrivyEmails).toHaveBeenCalledWith(subject); + + const native = await (await POST(modernRequest("skills/list"))).json(); + expect(native.result.skills.map((skill: { uri: string }) => skill.uri).sort()).toEqual( + [staffSkill, publicSkill].sort(), + ); + + checkFullOAuthRateLimit.mockRejectedValueOnce( + new Error("Tool rate limit reached; retry in 6 seconds"), + ); + expect((await POST(modernRequest("skills/list"))).status).toBe(500); + + getVerifiedPrivyEmails.mockResolvedValue([]); + expect((await tool({ skill: "recoup-internal-test" })).isError).toBe(true); + const revoked = await (await POST(modernRequest("resources/read", { uri: staffSkill }))).json(); + expect(revoked.error).toBeDefined(); + } finally { + await client.close(); + } +}); diff --git a/app/mcp/route.ts b/app/mcp/route.ts index 1ab6dd233..17d25f44b 100644 --- a/app/mcp/route.ts +++ b/app/mcp/route.ts @@ -7,6 +7,7 @@ import { setOAuthMcpHeaders } from "@/lib/mcp/oauth/setOAuthMcpHeaders"; import { registerAllTools } from "@/lib/mcp/tools"; import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; import { createModernRecoupHandler } from "@/lib/mcp/skills/createModernRecoupHandler"; +import { registerRecoupSkillsTool } from "@/lib/mcp/skills/registerRecoupSkillsTool"; import { createMcpHandler, withMcpAuth } from "mcp-handler"; import { verifyBearerToken } from "@/lib/mcp/verifyApiKey"; import { registerOAuthTools } from "@/lib/mcp/oauth/registerOAuthTools"; @@ -23,9 +24,13 @@ function createRecoupHandlers( version: string, withSkills = true, ) { + const registerConnection = (server: McpServer) => { + register(server); + if (withSkills) registerRecoupSkillsTool(server); + }; return { - legacy: createMcpHandler(register, { serverInfo: createRecoupServerInfo(version) }), - modern: createModernRecoupHandler(register, version, withSkills), + legacy: createMcpHandler(registerConnection, { serverInfo: createRecoupServerInfo(version) }), + modern: createModernRecoupHandler(registerConnection, version, withSkills), }; } diff --git a/docs/mcp-skills.md b/docs/mcp-skills.md index 380f4a17b..edd5f0acd 100644 --- a/docs/mcp-skills.md +++ b/docs/mcp-skills.md @@ -1,40 +1,35 @@ # Recoup Skills over MCP -Recoup serves the native Skills extension (`io.modelcontextprotocol/skills`) -to clients using MCP `2026-07-28`. - -## Claude Code setup - -Connect Recoup for customer-facing skills and tools. Recoup staff can add the -second connection for internal skills. Authorize Recoup Staff with the full -tools permission and a Recoup organization member account or a staff skills grant. - -```sh -claude mcp add --transport http recoup https://api.recoupable.dev/mcp -claude mcp add --transport http recoup-staff https://api.recoupable.dev/mcp/staff -``` - -Use `/skills` to find skills from both connections. For example, use -`/recoup:recoup-song-check-credits` or `/recoup-staff:recoup-internal-weekly-usage-review`. -Existing Recoup connections already use the first endpoint. Recoup Staff serves -skills and their resources. Recoup serves the tools those skills may need. -Selected Context grants retain their Context-only surface. - -Both catalogs fit within Claude Code's 100-skill limit per connection. -[Claude Code MCP skill limits](https://code.claude.com/docs/en/mcp#mcp-skill-limitations) +Use the Recoup connector at `https://api.recoupable.dev/mcp` and sign in to +Recoup. Signed-in accounts using the standard connector grant can use +customer-facing skills. The connector +also makes internal skills available to Recoup organization members, accounts +with a staff skills grant, and OAuth users whose Recoup sign-in identity has a +currently verified `@recoupable.com` email. These grants apply to skill +content. Recoup tool actions continue to enforce their existing permissions. + +In ChatGPT, ask the connected Recoup app to find or use a Recoup skill. The +`recoup_skills` tool searches the authorized catalog and reads skill +instructions and supporting files. ChatGPT's plugin listing shows the skills +included in the submitted plugin package. + +Clients with native Skills over MCP support can also use `skills/list`, +`skills/get`, and `resources/read` on the same connection. For Claude Code, +use `/skills` or ask Recoup to find a skill by name if its menu reaches the +client's display limit. Selected Context grants keep their workspace-only +tool surface. ## Granting staff skills access -Use the server-side `RECOUP_STAFF_SKILL_ACCOUNT_IDS` setting for accounts that -need access to staff skills without organization membership. Set it to a -comma-separated list of exact Recoup account IDs. This grants access only to -the staff skills connection. The account still needs full tools consent. +Use the server-side `RECOUP_STAFF_SKILL_ACCOUNT_IDS` setting for explicit +grants. Set it to a comma-separated list of exact Recoup account IDs. + +Use an account with customer-facing access when scanning or packaging the +public plugin so the submitted package contains only customer-facing skills. ## Updating the catalog The [Skills repository](https://github.com/recoupable/skills) owns the skill -source and supports the existing install paths. To release a catalog update, -bump the full Skills commit SHA in `scripts/mcp-skills/build.mjs` and run -`pnpm build:mcp-skills`. The build validates both catalogs and checks their -sizes against Claude Code's limit. Each deployment packages the same skill -definitions and supporting files until the next API release. +source. To release a catalog update, bump the Skills commit SHA in +`scripts/mcp-skills/build.mjs` and run `pnpm build:mcp-skills`. This validates +the catalog and packages the skill definitions and supporting files with the API. diff --git a/lib/mcp/skills/createModernRecoupHandler.ts b/lib/mcp/skills/createModernRecoupHandler.ts index 0e6398962..9b0be5d7e 100644 --- a/lib/mcp/skills/createModernRecoupHandler.ts +++ b/lib/mcp/skills/createModernRecoupHandler.ts @@ -5,6 +5,7 @@ import { z } from "zod"; import { createRecoupServerInfo } from "../createRecoupServerInfo"; import type { McpAuthInfo } from "../verifyApiKey"; import { getRecoupSkills } from "./getRecoupSkills"; +import { resolveRecoupSkillsAudience } from "./resolveRecoupSkillsAudience"; type LegacyTool = ( args: unknown, @@ -18,7 +19,7 @@ export function createModernRecoupHandler( withSkills = true, ) { return createMcpHandler( - async ({ authInfo }) => { + async ({ authInfo, requestInfo }) => { const auth = authInfo as McpAuthInfo | undefined; const server = new McpServer(createRecoupServerInfo(version)); @@ -55,7 +56,17 @@ export function createModernRecoupHandler( }; register(registration as unknown as LegacyServer); - if (withSkills) (await getRecoupSkills("public")).attach(server); + if (withSkills) { + const method = requestInfo?.headers.get("Mcp-Method"); + const skillRequest = + method === "skills/list" || + method === "skills/get" || + method === "resources/directory/read" || + (method === "resources/read" && + requestInfo?.headers.get("Mcp-Name") !== "ui://recoup/explore.html"); + const audience = skillRequest ? await resolveRecoupSkillsAudience(auth) : undefined; + (await getRecoupSkills(audience ?? "public")).attach(server); + } return server; }, { legacy: "reject" }, diff --git a/lib/mcp/skills/getRecoupSkills.ts b/lib/mcp/skills/getRecoupSkills.ts index 3216a8350..c7bc88310 100644 --- a/lib/mcp/skills/getRecoupSkills.ts +++ b/lib/mcp/skills/getRecoupSkills.ts @@ -1,11 +1,9 @@ -import { join } from "node:path"; import { SkillsExtension, type SkillCatalog } from "@modelcontextprotocol/server/ext/skills"; -import { nodeSkillFiles } from "@modelcontextprotocol/server/ext/skills/node"; import { isStaffSkill } from "./isStaffSkill.mjs"; +import { recoupSkillFiles } from "./recoupSkillFiles"; -type Audience = "public" | "staff"; +type Audience = "public" | "staff" | "all"; -const files = nodeSkillFiles(join(process.cwd(), ".mcp-skills/generated")); const catalogs = new Map>(); /** Build the catalog from the immutable deployment bundle once per audience. */ @@ -15,10 +13,10 @@ export function getRecoupSkills(audience: Audience): Promise { const catalog = SkillsExtension.load( { - read: path => files.read(path), + read: path => recoupSkillFiles.read(path), list: async path => { - const children = await files.list(path); - return path + const children = await recoupSkillFiles.list(path); + return path || audience === "all" ? children : children.filter(child => isStaffSkill(child.name) === (audience === "staff")); }, diff --git a/lib/mcp/skills/hasRecoupStaffSkills.ts b/lib/mcp/skills/hasRecoupStaffSkills.ts new file mode 100644 index 000000000..d9c85b4a2 --- /dev/null +++ b/lib/mcp/skills/hasRecoupStaffSkills.ts @@ -0,0 +1,23 @@ +import type { McpAuthInfo } from "../verifyApiKey"; + +/** Staff skills are a read entitlement independent of administrative and write permissions. */ +export async function hasRecoupStaffSkills( + accountId: string, + auth?: McpAuthInfo, +): Promise { + if (!accountId || auth?.extra.oauth?.selectedContext) return false; + if (process.env.RECOUP_STAFF_SKILL_ACCOUNT_IDS?.split(",").some(id => id.trim() === accountId)) + return true; + + try { + const { isRecoupAdmin } = await import("@/lib/organizations/isRecoupAdmin"); + if (await isRecoupAdmin(accountId)) return true; + const subject = auth?.extra.oauth?.subject; + if (!subject) return false; + const { getVerifiedPrivyEmails } = await import("@/lib/privy/getVerifiedPrivyEmails"); + const emails = await getVerifiedPrivyEmails(subject); + return emails.some(email => email.split("@").at(-1) === "recoupable.com"); + } catch { + return false; + } +} diff --git a/lib/mcp/skills/readRecoupSkillFile.ts b/lib/mcp/skills/readRecoupSkillFile.ts new file mode 100644 index 000000000..bacd3223f --- /dev/null +++ b/lib/mcp/skills/readRecoupSkillFile.ts @@ -0,0 +1,7 @@ +import { recoupSkillFiles } from "./recoupSkillFiles"; + +/** Read a file selected from an authorized catalog manifest. */ +export async function readRecoupSkillFile(uri: string) { + const url = new URL(uri); + return recoupSkillFiles.read(`${url.hostname}${decodeURIComponent(url.pathname)}`); +} diff --git a/lib/mcp/skills/recoupSkillFiles.ts b/lib/mcp/skills/recoupSkillFiles.ts new file mode 100644 index 000000000..1616f2e27 --- /dev/null +++ b/lib/mcp/skills/recoupSkillFiles.ts @@ -0,0 +1,4 @@ +import { join } from "node:path"; +import { nodeSkillFiles } from "@modelcontextprotocol/server/ext/skills/node"; + +export const recoupSkillFiles = nodeSkillFiles(join(process.cwd(), ".mcp-skills/generated")); diff --git a/lib/mcp/skills/recoupSkillsToolSchema.ts b/lib/mcp/skills/recoupSkillsToolSchema.ts new file mode 100644 index 000000000..48c647d80 --- /dev/null +++ b/lib/mcp/skills/recoupSkillsToolSchema.ts @@ -0,0 +1,29 @@ +import { z } from "zod"; + +export const recoupSkillsToolSchema = z + .object({ + query: z + .string() + .trim() + .max(200) + .optional() + .describe("Topic or words to find in skill names and descriptions"), + offset: z.number().int().min(0).optional().describe("Next offset from a previous search"), + skill: z + .string() + .regex(/^[a-z0-9-]{1,64}$/) + .optional() + .describe("Exact skill name to load"), + file: z + .string() + .min(1) + .max(1024) + .optional() + .describe("Skill-relative supporting file. Defaults to SKILL.md when a skill is selected"), + }) + .strict() + .refine( + ({ file, offset, query, skill }) => + skill ? query === undefined && offset === undefined : file === undefined, + "Provide a skill and optional file, or list skills with an optional query and offset.", + ); diff --git a/lib/mcp/skills/registerRecoupSkillsTool.ts b/lib/mcp/skills/registerRecoupSkillsTool.ts new file mode 100644 index 000000000..19b62e117 --- /dev/null +++ b/lib/mcp/skills/registerRecoupSkillsTool.ts @@ -0,0 +1,83 @@ +import type { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; +import type { CallToolResult } from "@modelcontextprotocol/sdk/types.js"; +import type { McpAuthInfo } from "../verifyApiKey"; +import { getRecoupSkills } from "./getRecoupSkills"; +import { readRecoupSkillFile } from "./readRecoupSkillFile"; +import { resolveRecoupSkillsAudience } from "./resolveRecoupSkillsAudience"; +import { recoupSkillsToolSchema } from "./recoupSkillsToolSchema"; + +const pageSize = 25; +const unavailable: CallToolResult = { + isError: true, + content: [{ type: "text", text: "This Recoup skill or file is unavailable." }], +}; + +/** Make the signed-in catalog available in clients that discover connector tools. */ +export function registerRecoupSkillsTool(server: McpServer) { + server.registerTool( + "recoup_skills", + { + title: "Recoup Skills", + description: + "Find and load Recoup workflows available to the connected account. Search by topic or list the catalog, then pass a matching skill name to load its instructions before running the workflow. Use file to load a supporting file referenced by those instructions.", + inputSchema: recoupSkillsToolSchema, + annotations: { readOnlyHint: true, destructiveHint: false, openWorldHint: false }, + }, + async ({ query, offset = 0, skill, file = "SKILL.md" }, extra): Promise => { + const authInfo = extra.authInfo as McpAuthInfo | undefined; + const audience = await resolveRecoupSkillsAudience(authInfo).catch((error: unknown) => { + if ( + error instanceof Error && + /^Tool rate limit reached; retry in \d+ seconds$/.test(error.message) + ) + throw error; + return undefined; + }); + if (!audience) return unavailable; + const catalog = await getRecoupSkills(audience); + if (!skill) { + const terms = query?.toLowerCase().split(/\s+/).filter(Boolean) ?? []; + const matches = catalog.entries + .map(({ frontmatter: { name, description } }) => ({ name, description })) + .filter(({ name, description }) => + terms.every(term => `${name} ${description}`.toLowerCase().includes(term)), + ); + const next = offset + pageSize; + return { + content: [ + { + type: "text", + text: JSON.stringify({ + skills: matches.slice(offset, next), + ...(next < matches.length ? { nextOffset: next } : {}), + }), + }, + ], + }; + } + + const entry = catalog.entries.find(entry => entry.frontmatter.name === skill); + if (!entry || entry.resources === "dynamic") return unavailable; + const resource = entry.resources.find( + ({ uri }) => decodeURIComponent(new URL(uri).pathname.slice(1)) === file, + ); + if (!resource) return unavailable; + + const { uri } = resource; + const bytes = await readRecoupSkillFile(uri); + try { + if (!bytes.includes(0)) { + const text = new TextDecoder("utf-8", { fatal: true, ignoreBOM: true }).decode(bytes); + return { content: [{ type: "text", text }] }; + } + } catch { + // Return non-text files as an embedded resource. + } + return { + content: [ + { type: "resource", resource: { uri, blob: Buffer.from(bytes).toString("base64") } }, + ], + }; + }, + ); +} diff --git a/lib/mcp/skills/resolveRecoupSkillsAudience.ts b/lib/mcp/skills/resolveRecoupSkillsAudience.ts new file mode 100644 index 000000000..4339c31e3 --- /dev/null +++ b/lib/mcp/skills/resolveRecoupSkillsAudience.ts @@ -0,0 +1,20 @@ +import type { McpAuthInfo } from "../verifyApiKey"; +import { hasRecoupStaffSkills } from "./hasRecoupStaffSkills"; + +/** Resolve the account and optional tool budget before loading a catalog. */ +export async function resolveRecoupSkillsAudience( + authInfo: McpAuthInfo | undefined, +): Promise<"all" | "public" | undefined> { + if (authInfo?.extra.oauth?.selectedContext) return undefined; + const { resolveAccountId } = await import("../resolveAccountId"); + const { accountId } = await resolveAccountId({ authInfo, accountIdOverride: undefined }); + if (!accountId) return undefined; + + // Legacy-only environments do not provision the OAuth-backed rate limiter. + const limiterConfigured = process.env.OAUTH_ISSUER && process.env.OAUTH_INDEX_KEY; + if (authInfo?.extra.oauth || limiterConfigured) { + const { checkFullOAuthRateLimit } = await import("../oauth/checkFullOAuthRateLimit"); + await checkFullOAuthRateLimit("recoup_skills", accountId); + } + return (await hasRecoupStaffSkills(accountId, authInfo)) ? "all" : "public"; +} diff --git a/lib/oauth/__tests__/resolveOAuthAccess.test.ts b/lib/oauth/__tests__/resolveOAuthAccess.test.ts index 74fa565db..f576a7a0a 100644 --- a/lib/oauth/__tests__/resolveOAuthAccess.test.ts +++ b/lib/oauth/__tests__/resolveOAuthAccess.test.ts @@ -130,3 +130,13 @@ it("preserves valid selected workspace attribution and rejects a different perso selectedContext.ownerId = "00000000-0000-4000-8000-000000000002"; expect(await resolveOAuthAccess(f.options, "secret")).toBeUndefined(); }); + +it("uses only the Privy subject recorded on the validated grant", async () => { + const f = fixture(); + Object.assign(f.attribution.extra, { subject: "did:privy:verified-staff" }); + expect(await resolveOAuthAccess(f.options, "secret")).toMatchObject({ + subject: "did:privy:verified-staff", + }); + Object.assign(f.attribution.extra, { subject: "staff@recoupable.com" }); + expect(await resolveOAuthAccess(f.options, "secret")).not.toHaveProperty("subject"); +}); diff --git a/lib/oauth/resolveOAuthAccess.ts b/lib/oauth/resolveOAuthAccess.ts index 61291eb65..d40c8349d 100644 --- a/lib/oauth/resolveOAuthAccess.ts +++ b/lib/oauth/resolveOAuthAccess.ts @@ -11,6 +11,7 @@ export type OAuthAccess = { resource: string; context: "personal"; selectedContext?: SelectedContext; + subject?: string; }; /** Check every authority binding, including the current grant, before accepting a bearer. */ @@ -64,6 +65,11 @@ export async function resolveOAuthAccess( return undefined; return { ...(selectedContext ? { selectedContext } : {}), + ...(typeof attribution.extra.subject === "string" && + attribution.extra.subject.startsWith("did:privy:") && + attribution.extra.subject.length <= 300 + ? { subject: attribution.extra.subject } + : {}), accountId: token.accountId, clientId: token.clientId, grantId: token.grantId, diff --git a/lib/privy/getVerifiedOAuthIdentity.ts b/lib/privy/getVerifiedOAuthIdentity.ts index 917b490e6..87e47aee2 100644 --- a/lib/privy/getVerifiedOAuthIdentity.ts +++ b/lib/privy/getVerifiedOAuthIdentity.ts @@ -2,13 +2,7 @@ import { z } from "zod"; import { InvalidAuthTokenError } from "@privy-io/node"; import privyClient from "./client"; import { OAuthIdentityError } from "./OAuthIdentityError"; - -const emailLink = z.object({ - type: z.literal("email"), - address: z.string().trim().toLowerCase().email().max(320), - // Do not treat imported/profile email attributes as proof of an authenticated email link. - latest_verified_at: z.number().int().positive(), -}); +import { getVerifiedPrivyEmails } from "./getVerifiedPrivyEmails"; /** Verify a Privy access token before fetching immutable subject and email-link evidence. */ export async function getVerifiedOAuthIdentity(authToken: string) { @@ -17,17 +11,7 @@ export async function getVerifiedOAuthIdentity(authToken: string) { if (!authToken || authToken.length > 16384) throw new OAuthIdentityError("invalid_token"); const verified = await privyClient.utils().auth().verifyAuthToken(authToken); const subject = z.string().startsWith("did:privy:").max(300).parse(verified?.user_id); - const account = await privyClient.users()._get(subject, { timeout: 10000, maxRetries: 1 }); - if (account.id !== subject || !Array.isArray(account.linked_accounts)) throw new Error(); - const verifiedEmails = [ - ...new Set( - account.linked_accounts.flatMap(link => { - const parsed = emailLink.safeParse(link); - return parsed.success ? [parsed.data.address] : []; - }), - ), - ]; - if (verifiedEmails.length > 20) throw new Error(); + const verifiedEmails = await getVerifiedPrivyEmails(subject); return { appId, subject, verifiedEmails }; } catch (error) { if (error instanceof OAuthIdentityError) throw error; diff --git a/lib/privy/getVerifiedPrivyEmails.ts b/lib/privy/getVerifiedPrivyEmails.ts new file mode 100644 index 000000000..2a6e16cd0 --- /dev/null +++ b/lib/privy/getVerifiedPrivyEmails.ts @@ -0,0 +1,24 @@ +import { z } from "zod"; +import privyClient from "./client"; + +const emailLink = z.object({ + type: z.literal("email"), + address: z.string().trim().toLowerCase().email().max(320), + latest_verified_at: z.number().int().positive(), +}); + +/** Read current proof of email ownership for a trusted Privy subject. */ +export async function getVerifiedPrivyEmails(subject: string): Promise { + const account = await privyClient.users()._get(subject, { timeout: 10000, maxRetries: 1 }); + if (account.id !== subject || !Array.isArray(account.linked_accounts)) throw new Error(); + const emails = [ + ...new Set( + account.linked_accounts.flatMap(link => { + const parsed = emailLink.safeParse(link); + return parsed.success ? [parsed.data.address] : []; + }), + ), + ]; + if (emails.length > 20) throw new Error(); + return emails; +}