@agentpress/sdk 0.2.113 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"file":"index.cjs","names":["verifySig"],"sources":["../src/errors.ts","../src/utils.ts","../src/webhooks/signing.ts","../src/actions/client.ts","../src/http.ts","../src/userApprovals/client.ts","../src/webhooks/client.ts","../src/client.ts"],"sourcesContent":["/**\n * Base error class for all SDK errors. Catch this to handle any error\n * thrown by the AgentPress SDK regardless of specific type.\n */\nexport class AgentPressError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"AgentPressError\";\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/**\n * Thrown at construction time when `AgentPressOptions` contains invalid values\n * (e.g., non-positive timeout, malformed `webhookSecret`).\n */\nexport class ConfigurationError extends AgentPressError {\n constructor(message: string) {\n super(message);\n this.name = \"ConfigurationError\";\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/**\n * Thrown when the API returns a non-2xx HTTP response.\n *\n * Properties:\n * - `statusCode` - HTTP status code (e.g., 401, 404, 500)\n * - `responseBody` - Raw response body text for debugging\n * - `url` - The full request URL that failed\n */\nexport class HttpError extends AgentPressError {\n public readonly statusCode: number;\n public readonly responseBody: string;\n public readonly url: string;\n\n constructor(statusCode: number, responseBody: string, url: string) {\n super(`HTTP ${statusCode} from ${url}`);\n this.name = \"HttpError\";\n this.statusCode = statusCode;\n this.responseBody = responseBody;\n this.url = url;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/** Thrown when a request exceeds the configured `timeout` (default 30s). */\nexport class TimeoutError extends AgentPressError {\n constructor(url: string, timeout: number) {\n super(`Request to ${url} timed out after ${timeout}ms`);\n this.name = \"TimeoutError\";\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/** Thrown by {@link WebhooksClient.verifyOrThrow} when an inbound webhook signature is invalid or expired. */\nexport class WebhookSignatureError extends AgentPressError {\n constructor(message: string) {\n super(message);\n this.name = \"WebhookSignatureError\";\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n","import { randomUUID } from \"node:crypto\";\n\nexport function randomMessageId(): string {\n return `msg_${randomUUID()}`;\n}\n","import { createHmac, timingSafeEqual } from \"node:crypto\";\n\nconst SIGNATURE_PREFIX = \"v1,\";\nconst DEFAULT_TOLERANCE_SECONDS = 5 * 60; // 5 minutes\n\n/**\n * Sign a webhook payload using Svix-compatible HMAC-SHA256.\n *\n * @param secret - The webhook secret (with \"whsec_\" prefix)\n * @param msgId - Unique message ID (e.g., \"msg_<uuid>\")\n * @param timestamp - Unix timestamp in seconds\n * @param body - JSON stringified payload\n * @returns Signature string in format \"v1,<base64>\"\n */\nexport function sign(\n secret: string,\n msgId: string,\n timestamp: number,\n body: string,\n): string {\n const secretBytes = Buffer.from(secret.replace(/^whsec_/, \"\"), \"base64\");\n const message = `${msgId}.${timestamp}.${body}`;\n const signature = createHmac(\"sha256\", secretBytes)\n .update(message)\n .digest(\"base64\");\n return `${SIGNATURE_PREFIX}${signature}`;\n}\n\n/**\n * Verify a Svix webhook signature.\n *\n * @param secret - The webhook secret (with \"whsec_\" prefix)\n * @param payload - Raw request body (string or Buffer)\n * @param headers - Svix headers object\n * @param toleranceSeconds - Max age of signature in seconds (default: 5 min)\n * @returns true if valid, false if invalid or expired\n */\nexport function verify(\n secret: string,\n payload: string | Buffer,\n headers: {\n \"svix-id\": string;\n \"svix-timestamp\": string;\n \"svix-signature\": string;\n },\n toleranceSeconds: number = DEFAULT_TOLERANCE_SECONDS,\n): boolean {\n const msgId = headers[\"svix-id\"];\n const timestampStr = headers[\"svix-timestamp\"];\n const signatureHeader = headers[\"svix-signature\"];\n\n const timestamp = parseInt(timestampStr, 10);\n if (Number.isNaN(timestamp)) return false;\n\n const now = Math.floor(Date.now() / 1000);\n if (Math.abs(now - timestamp) > toleranceSeconds) return false;\n\n const body =\n typeof payload === \"string\" ? payload : payload.toString(\"utf-8\");\n const expected = sign(secret, msgId, timestamp, body);\n\n const signatures = signatureHeader.split(\" \");\n const expectedBuf = Buffer.from(expected);\n\n for (const sig of signatures) {\n const sigBuf = Buffer.from(sig);\n if (\n sigBuf.length === expectedBuf.length &&\n timingSafeEqual(sigBuf, expectedBuf)\n ) {\n return true;\n }\n }\n\n return false;\n}\n","import { ConfigurationError } from \"../errors\";\nimport type { HttpClient } from \"../http\";\nimport type {\n ActionManageResponse,\n ApproveActionParams,\n RejectActionParams,\n ResolvedOptions,\n} from \"../types\";\nimport { randomMessageId } from \"../utils\";\nimport { sign } from \"../webhooks/signing\";\n\n/**\n * Client for programmatically approving or rejecting staged actions.\n * Uses HMAC-SHA256 signing (Svix-compatible), identical to {@link WebhooksClient}.\n *\n * @example\n * ```ts\n * const client = new AgentPress({ webhookSecret: \"whsec_...\", org: \"my-org\" });\n *\n * // Approve a staged action\n * await client.actions.approve(\"act_123\", {\n * action: \"my_webhook_action\",\n * });\n *\n * // Reject with a reason\n * await client.actions.reject(\"act_456\", {\n * action: \"my_webhook_action\",\n * reason: \"Insufficient data\",\n * });\n * ```\n */\nexport class ActionsClient {\n private readonly options: ResolvedOptions;\n private readonly http: HttpClient;\n\n constructor(options: ResolvedOptions, http: HttpClient) {\n this.options = options;\n this.http = http;\n }\n\n /**\n * Approve a staged action, optionally modifying the tool call.\n *\n * @throws ConfigurationError if webhookSecret is not configured\n * @throws HttpError on non-2xx response\n * @throws TimeoutError if request exceeds timeout\n */\n async approve(\n actionId: string,\n params: ApproveActionParams,\n ): Promise<ActionManageResponse> {\n const body: Record<string, unknown> = {};\n if (params.editedToolCall !== undefined) {\n body.editedToolCall = params.editedToolCall;\n }\n if (params.remember !== undefined) {\n body.remember = params.remember;\n }\n return this.manage(actionId, params.action, \"approve\", body);\n }\n\n /**\n * Reject a staged action.\n *\n * @throws ConfigurationError if webhookSecret is not configured\n * @throws HttpError on non-2xx response\n * @throws TimeoutError if request exceeds timeout\n */\n async reject(\n actionId: string,\n params: RejectActionParams,\n ): Promise<ActionManageResponse> {\n return this.manage(actionId, params.action, \"reject\", {\n reason: params.reason,\n });\n }\n\n private async manage(\n actionId: string,\n webhookAction: string,\n operation: \"approve\" | \"reject\",\n body: Record<string, unknown>,\n ): Promise<ActionManageResponse> {\n if (!this.options.webhookSecret) {\n throw new ConfigurationError(\n \"webhookSecret is required for action management operations\",\n );\n }\n\n const path = `/webhooks/actions/${this.options.org}/${webhookAction}/manage/${actionId}/${operation}`;\n const bodyStr = JSON.stringify(body);\n const msgId = randomMessageId();\n const timestamp = Math.floor(Date.now() / 1000);\n const signature = sign(\n this.options.webhookSecret,\n msgId,\n timestamp,\n bodyStr,\n );\n\n return this.http.request<ActionManageResponse>(path, {\n method: \"POST\",\n body: bodyStr,\n headers: {\n \"svix-id\": msgId,\n \"svix-timestamp\": String(timestamp),\n \"svix-signature\": signature,\n },\n });\n }\n}\n","import { AgentPressError, HttpError, TimeoutError } from \"./errors\";\nimport type { ResolvedOptions } from \"./types\";\n\n/**\n * Internal shared HTTP client. Not part of the public API -- used by\n * namespace clients (e.g., `WebhooksClient`) to make authenticated requests.\n * @internal\n */\nexport class HttpClient {\n private readonly baseUrl: string;\n private readonly timeout: number;\n private readonly onRequest?: ResolvedOptions[\"onRequest\"];\n private readonly onResponse?: ResolvedOptions[\"onResponse\"];\n\n constructor(options: ResolvedOptions) {\n this.baseUrl = options.baseUrl;\n this.timeout = options.timeout;\n this.onRequest = options.onRequest;\n this.onResponse = options.onResponse;\n }\n\n /**\n * Send an HTTP request to the API. Constructs the full URL from `baseUrl` + `path`,\n * applies the configured timeout via `AbortSignal`, fires `onRequest`/`onResponse`\n * hooks, and parses the JSON response.\n *\n * @throws {TimeoutError} If the request exceeds the configured timeout.\n * @throws {HttpError} If the API returns a non-2xx status code.\n * @throws {AgentPressError} On network failures or non-JSON responses.\n */\n async request<T>(path: string, init: RequestInit): Promise<T> {\n const url = `${this.baseUrl}${path}`;\n\n const headers = new Headers(init.headers);\n if (!headers.has(\"Content-Type\")) {\n headers.set(\"Content-Type\", \"application/json\");\n }\n\n const requestInit: RequestInit = {\n ...init,\n headers,\n signal: AbortSignal.timeout(this.timeout),\n };\n\n this.onRequest?.(url, requestInit);\n\n let response: Response;\n try {\n // biome-ignore lint/style/noRestrictedGlobals: SDK is a standalone package that uses raw fetch\n response = await fetch(url, requestInit);\n } catch (error: unknown) {\n if (\n error instanceof Error &&\n (error.name === \"TimeoutError\" || error.name === \"AbortError\")\n ) {\n throw new TimeoutError(url, this.timeout);\n }\n const message =\n error instanceof Error ? error.message : \"Unknown fetch error\";\n throw new AgentPressError(`Request to ${url} failed: ${message}`);\n }\n\n this.onResponse?.(url, response.clone());\n\n const text = await response.text();\n\n if (!response.ok) {\n throw new HttpError(response.status, text, url);\n }\n\n try {\n return JSON.parse(text) as T;\n } catch {\n throw new AgentPressError(\n `Expected JSON response from ${url} but received: ${text.slice(0, 200)}`,\n );\n }\n }\n}\n","import { ConfigurationError } from \"../errors\";\nimport type { HttpClient } from \"../http\";\nimport type {\n CreateUserApprovalParams,\n DeleteUserApprovalParams,\n ListUserApprovalsParams,\n ListUserApprovalsResponse,\n ResolvedOptions,\n UpdateUserApprovalParams,\n UserToolApproval,\n} from \"../types\";\nimport { randomMessageId } from \"../utils\";\nimport { sign } from \"../webhooks/signing\";\n\n/**\n * Client for managing per-user auto-approval rules — the SDK equivalent of the\n * console's `/account/auto-approvals` settings page. Uses HMAC-SHA256 signing\n * (Svix-compatible), identical to {@link ActionsClient.manage}.\n *\n * Each call is scoped to a single webhook (identified by `webhookIdentifier`),\n * which both selects the signing secret and scopes which approvals are visible.\n *\n * @example\n * ```ts\n * const client = new AgentPress({ webhookSecret: \"whsec_...\", org: \"my-org\" });\n *\n * // Provision consent so future \"sendEmail\" triggers skip the approval prompt\n * await client.userApprovals.create({\n * webhookIdentifier: \"reviews\",\n * userId: \"user-uuid\",\n * actionWebhookId: \"webhook-uuid\",\n * toolName: \"sendEmail\",\n * mode: \"always_allow\",\n * });\n *\n * // List rules (optionally filtered by userId)\n * const { approvals } = await client.userApprovals.list({\n * webhookIdentifier: \"reviews\",\n * });\n *\n * // Revoke\n * await client.userApprovals.delete(approvalId, { webhookIdentifier: \"reviews\" });\n * ```\n */\nexport class UserApprovalsClient {\n private readonly options: ResolvedOptions;\n private readonly http: HttpClient;\n\n constructor(options: ResolvedOptions, http: HttpClient) {\n this.options = options;\n this.http = http;\n }\n\n /**\n * List auto-approval rules for a webhook. Optionally filter by `userId`.\n *\n * @throws ConfigurationError if webhookSecret is not configured\n * @throws HttpError on non-2xx response\n * @throws TimeoutError if request exceeds timeout\n */\n async list(\n params: ListUserApprovalsParams,\n ): Promise<ListUserApprovalsResponse> {\n const body: Record<string, unknown> = {};\n if (params.userId !== undefined) body.userId = params.userId;\n if (params.authProvider !== undefined)\n body.authProvider = params.authProvider;\n return this.send<ListUserApprovalsResponse>(\n params.webhookIdentifier,\n \"list\",\n body,\n );\n }\n\n /**\n * Create (or upsert) an auto-approval rule. If a rule with the same\n * `(userId, actionWebhookId, toolName)` triple already exists, it is\n * updated in place.\n *\n * @throws ConfigurationError if webhookSecret is not configured\n * @throws HttpError on non-2xx response\n * @throws TimeoutError if request exceeds timeout\n */\n async create(params: CreateUserApprovalParams): Promise<UserToolApproval> {\n const body: Record<string, unknown> = {\n userId: params.userId,\n actionWebhookId: params.actionWebhookId,\n toolName: params.toolName,\n mode: params.mode ?? \"always_allow\",\n };\n if (params.authProvider !== undefined)\n body.authProvider = params.authProvider;\n if (params.expiresAt !== undefined) {\n body.expiresAt =\n params.expiresAt === null ? null : params.expiresAt.toISOString();\n }\n return this.send<UserToolApproval>(\n params.webhookIdentifier,\n \"create\",\n body,\n );\n }\n\n /**\n * Patch an existing auto-approval rule (change mode or expiry).\n *\n * @throws ConfigurationError if webhookSecret is not configured\n * @throws HttpError on non-2xx response (404 if the rule does not belong to this webhook)\n * @throws TimeoutError if request exceeds timeout\n */\n async update(\n id: string,\n params: UpdateUserApprovalParams,\n ): Promise<UserToolApproval> {\n const body: Record<string, unknown> = {};\n if (params.mode !== undefined) body.mode = params.mode;\n if (params.expiresAt !== undefined) {\n body.expiresAt =\n params.expiresAt === null ? null : params.expiresAt.toISOString();\n }\n return this.send<UserToolApproval>(\n params.webhookIdentifier,\n `update/${id}`,\n body,\n );\n }\n\n /**\n * Revoke an auto-approval rule. Future triggers of the corresponding\n * `(user, webhook, tool)` combination will once again stage for approval.\n *\n * @throws ConfigurationError if webhookSecret is not configured\n * @throws HttpError on non-2xx response (404 if the rule does not belong to this webhook)\n * @throws TimeoutError if request exceeds timeout\n */\n async delete(\n id: string,\n params: DeleteUserApprovalParams,\n ): Promise<{ success: boolean }> {\n return this.send<{ success: boolean }>(\n params.webhookIdentifier,\n `delete/${id}`,\n {},\n );\n }\n\n /** Internal: HMAC-sign and POST the body to the scoped path. */\n private async send<T>(\n webhookIdentifier: string,\n operation: string,\n body: Record<string, unknown>,\n ): Promise<T> {\n if (!this.options.webhookSecret) {\n throw new ConfigurationError(\n \"webhookSecret is required for user approval management operations\",\n );\n }\n\n const path = `/webhooks/user-approvals/${this.options.org}/${webhookIdentifier}/${operation}`;\n const bodyStr = JSON.stringify(body);\n const msgId = randomMessageId();\n const timestamp = Math.floor(Date.now() / 1000);\n const signature = sign(\n this.options.webhookSecret,\n msgId,\n timestamp,\n bodyStr,\n );\n\n return this.http.request<T>(path, {\n method: \"POST\",\n body: bodyStr,\n headers: {\n \"svix-id\": msgId,\n \"svix-timestamp\": String(timestamp),\n \"svix-signature\": signature,\n },\n });\n }\n}\n","import {\n AgentPressError,\n ConfigurationError,\n WebhookSignatureError,\n} from \"../errors\";\nimport type { HttpClient } from \"../http\";\nimport type {\n ActionCallbackPayload,\n ResolvedOptions,\n WebhookResponse,\n WebhookSendParams,\n WebhookVerifyParams,\n} from \"../types\";\nimport { randomMessageId } from \"../utils\";\nimport { sign, verify as verifySig } from \"./signing\";\n\nexport class WebhooksClient {\n private readonly options: ResolvedOptions;\n private readonly http: HttpClient;\n\n constructor(options: ResolvedOptions, http: HttpClient) {\n this.options = options;\n this.http = http;\n }\n\n /**\n * Send an arbitrary webhook payload to AgentPress.\n * Signs the payload with HMAC-SHA256 (Svix-compatible).\n *\n * @throws ConfigurationError if webhookSecret is not configured\n * @throws HttpError on non-2xx response\n * @throws TimeoutError if request exceeds timeout\n */\n async send(params: WebhookSendParams): Promise<WebhookResponse> {\n if (!this.options.webhookSecret) {\n throw new ConfigurationError(\n \"webhookSecret is required for webhook operations\",\n );\n }\n\n const path = `/webhooks/actions/${this.options.org}/${params.action}`;\n const body = JSON.stringify(params.payload);\n const msgId = randomMessageId();\n const timestamp = Math.floor(Date.now() / 1000);\n const signature = sign(this.options.webhookSecret, msgId, timestamp, body);\n\n return this.http.request<WebhookResponse>(path, {\n method: \"POST\",\n body,\n headers: {\n \"svix-id\": msgId,\n \"svix-timestamp\": String(timestamp),\n \"svix-signature\": signature,\n },\n });\n }\n\n /**\n * Verify an inbound Svix webhook signature.\n *\n * @returns true if valid, false if invalid or expired\n * @throws ConfigurationError if webhookSecret is not configured\n */\n verify(params: WebhookVerifyParams): boolean {\n if (!this.options.webhookSecret) {\n throw new ConfigurationError(\n \"webhookSecret is required for webhook verification\",\n );\n }\n\n return verifySig(\n this.options.webhookSecret,\n params.payload,\n params.headers,\n );\n }\n\n /**\n * Verify an inbound Svix webhook signature, throwing on failure.\n * Useful for middleware patterns where invalid signatures should halt processing.\n *\n * @throws WebhookSignatureError if signature is invalid or expired\n * @throws ConfigurationError if webhookSecret is not configured\n */\n verifyOrThrow(params: WebhookVerifyParams): void {\n if (!this.verify(params)) {\n throw new WebhookSignatureError(\"Invalid webhook signature\");\n }\n }\n\n /**\n * Verify and parse an inbound webhook from AgentPress.\n * Combines signature verification with JSON parsing and type casting.\n * This is the recommended way to handle incoming webhooks.\n *\n * @throws WebhookSignatureError if signature is invalid or expired\n * @throws ConfigurationError if webhookSecret is not configured\n * @throws AgentPressError if payload is not valid JSON\n */\n constructEvent(params: WebhookVerifyParams): ActionCallbackPayload {\n this.verifyOrThrow(params);\n const body =\n typeof params.payload === \"string\"\n ? params.payload\n : params.payload.toString(\"utf-8\");\n try {\n return JSON.parse(body) as ActionCallbackPayload;\n } catch {\n throw new AgentPressError(\"Webhook payload is not valid JSON\");\n }\n }\n}\n","import { ActionsClient } from \"./actions/client\";\nimport { ConfigurationError } from \"./errors\";\nimport { HttpClient } from \"./http\";\nimport type { AgentPressOptions, ResolvedOptions } from \"./types\";\nimport { UserApprovalsClient } from \"./userApprovals/client\";\nimport { WebhooksClient } from \"./webhooks/client\";\n\n/**\n * Main entry point for the AgentPress SDK. Provides namespaced access to API\n * resources (e.g., `client.webhooks.send()`, `client.actions.approve()`).\n * Validates all configuration options at construction time, so invalid config fails fast.\n *\n * @example\n * ```ts\n * const client = new AgentPress({\n * apiKey: \"ak_...\",\n * webhookSecret: \"whsec_...\",\n * });\n * await client.webhooks.send({ action: \"my_action\", payload: { ... } });\n * await client.actions.approve(\"act_123\", { action: \"my_action\" });\n * ```\n */\nexport class AgentPress {\n /** Webhook operations: send outbound webhooks and verify inbound signatures. */\n public readonly webhooks: WebhooksClient;\n /** Action management: approve or reject staged actions. */\n public readonly actions: ActionsClient;\n /** Per-user auto-approval rules (read / create / update / delete). */\n public readonly userApprovals: UserApprovalsClient;\n\n /**\n * @param options - SDK configuration. All fields are optional with sensible defaults.\n * @throws {ConfigurationError} If `timeout` is non-positive or `webhookSecret` has an invalid prefix.\n */\n constructor(options: AgentPressOptions = {}) {\n const resolved = resolveOptions(options);\n const http = new HttpClient(resolved);\n this.webhooks = new WebhooksClient(resolved, http);\n this.actions = new ActionsClient(resolved, http);\n this.userApprovals = new UserApprovalsClient(resolved, http);\n }\n}\n\nfunction resolveOptions(options: AgentPressOptions): ResolvedOptions {\n const baseUrl = (options.baseUrl ?? \"https://api.agent.press\").replace(\n /\\/+$/,\n \"\",\n );\n const timeout = options.timeout ?? 30_000;\n const org = options.org ?? \"default-org\";\n\n if (timeout <= 0 || !Number.isFinite(timeout)) {\n throw new ConfigurationError(\"timeout must be a positive number\");\n }\n\n if (\n options.webhookSecret !== undefined &&\n !options.webhookSecret.startsWith(\"whsec_\")\n ) {\n throw new ConfigurationError('webhookSecret must start with \"whsec_\"');\n }\n\n return {\n baseUrl,\n timeout,\n org,\n webhookSecret: options.webhookSecret,\n apiKey: options.apiKey,\n onRequest: options.onRequest,\n onResponse: options.onResponse,\n };\n}\n"],"mappings":";;;;;;;AAIA,IAAa,kBAAb,cAAqC,MAAM;CACzC,YAAY,SAAiB;AAC3B,QAAM,QAAQ;AACd,OAAK,OAAO;AACZ,SAAO,eAAe,MAAM,IAAI,OAAO,UAAU;;;;;;;AAQrD,IAAa,qBAAb,cAAwC,gBAAgB;CACtD,YAAY,SAAiB;AAC3B,QAAM,QAAQ;AACd,OAAK,OAAO;AACZ,SAAO,eAAe,MAAM,IAAI,OAAO,UAAU;;;;;;;;;;;AAYrD,IAAa,YAAb,cAA+B,gBAAgB;CAC7C;CACA;CACA;CAEA,YAAY,YAAoB,cAAsB,KAAa;AACjE,QAAM,QAAQ,WAAW,QAAQ,MAAM;AACvC,OAAK,OAAO;AACZ,OAAK,aAAa;AAClB,OAAK,eAAe;AACpB,OAAK,MAAM;AACX,SAAO,eAAe,MAAM,IAAI,OAAO,UAAU;;;;AAKrD,IAAa,eAAb,cAAkC,gBAAgB;CAChD,YAAY,KAAa,SAAiB;AACxC,QAAM,cAAc,IAAI,mBAAmB,QAAQ,IAAI;AACvD,OAAK,OAAO;AACZ,SAAO,eAAe,MAAM,IAAI,OAAO,UAAU;;;;AAKrD,IAAa,wBAAb,cAA2C,gBAAgB;CACzD,YAAY,SAAiB;AAC3B,QAAM,QAAQ;AACd,OAAK,OAAO;AACZ,SAAO,eAAe,MAAM,IAAI,OAAO,UAAU;;;;;AC3DrD,SAAgB,kBAA0B;AACxC,QAAO,QAAA,GAAA,YAAA,aAAmB;;;;ACD5B,MAAM,mBAAmB;AACzB,MAAM,4BAA4B;;;;;;;;;;AAWlC,S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GxE,QAAO;EACL;EACA;EACA;EACA,eAAe,QAAQ;EACvB,QAAQ,QAAQ;EAChB,WAAW,QAAQ;EACnB,YAAY,QAAQ;EACrB"}
1
+ {"version":3,"file":"index.cjs","names":["SIGNATURE_PREFIX","joseErrors","verifySig","verifyKeyRotationImpl"],"sources":["../src/errors.ts","../src/utils.ts","../src/webhooks/signing.ts","../src/actions/client.ts","../src/http.ts","../src/partners/client.ts","../src/userApprovals/client.ts","../src/webhooks/keyRotation.ts","../src/webhooks/client.ts","../src/client.ts"],"sourcesContent":["/**\n * Base error class for all SDK errors. Catch this to handle any error\n * thrown by the AgentPress SDK regardless of specific type.\n */\nexport class AgentPressError extends Error {\n constructor(message: string) {\n super(message);\n this.name = \"AgentPressError\";\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/**\n * Thrown at construction time when `AgentPressOptions` contains invalid values\n * (e.g., non-positive timeout, malformed `webhookSecret`).\n */\nexport class ConfigurationError extends AgentPressError {\n constructor(message: string) {\n super(message);\n this.name = \"ConfigurationError\";\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/**\n * Thrown when the API returns a non-2xx HTTP response.\n *\n * Properties:\n * - `statusCode` - HTTP status code (e.g., 401, 404, 500)\n * - `responseBody` - Raw response body text for debugging\n * - `url` - The full request URL that failed\n */\nexport class HttpError extends AgentPressError {\n public readonly statusCode: number;\n public readonly responseBody: string;\n public readonly url: string;\n\n constructor(statusCode: number, responseBody: string, url: string) {\n super(`HTTP ${statusCode} from ${url}`);\n this.name = \"HttpError\";\n this.statusCode = statusCode;\n this.responseBody = responseBody;\n this.url = url;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/** Thrown when a request exceeds the configured `timeout` (default 30s). */\nexport class TimeoutError extends AgentPressError {\n constructor(url: string, timeout: number) {\n super(`Request to ${url} timed out after ${timeout}ms`);\n this.name = \"TimeoutError\";\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/** Thrown by {@link WebhooksClient.verifyOrThrow} when an inbound webhook signature is invalid or expired. */\nexport class WebhookSignatureError extends AgentPressError {\n constructor(message: string) {\n super(message);\n this.name = \"WebhookSignatureError\";\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/** Reason codes for {@link PartnerTokenError}. Maps 1:1 to RFC 6750 `error_description` values. */\nexport type PartnerTokenErrorReason =\n | \"signature_invalid\"\n | \"issuer_mismatch\"\n | \"audience_mismatch\"\n | \"expired\"\n | \"not_yet_valid\"\n | \"missing_claim\"\n | \"ext_provider_mismatch\"\n | \"algorithm_not_allowed\"\n | \"kid_missing_or_unknown\"\n | \"malformed\";\n\n/**\n * Thrown by {@link PartnersClient.verifyToken} when a Partner MCP Spec v1 JWT\n * fails verification. Partners map `reason` to their RFC 6750 `WWW-Authenticate`\n * response (`401 invalid_token` for all reasons in this class).\n */\nexport class PartnerTokenError extends AgentPressError {\n public readonly reason: PartnerTokenErrorReason;\n\n constructor(reason: PartnerTokenErrorReason, message: string) {\n super(message);\n this.name = \"PartnerTokenError\";\n this.reason = reason;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n\n/** Reason codes for {@link KeyRotationVerifyError}. */\nexport type KeyRotationVerifyErrorReason =\n | \"invalid_signature\"\n | \"invalid_signature_format\"\n | \"timestamp_out_of_window\"\n | \"invalid_timestamp\"\n | \"payload_too_large\"\n | \"malformed_payload\";\n\n/**\n * Thrown by {@link WebhooksClient.verifyKeyRotation} when a `signing_key_rotation`\n * webhook fails HMAC / timestamp / payload validation.\n */\nexport class KeyRotationVerifyError extends AgentPressError {\n public readonly reason: KeyRotationVerifyErrorReason;\n\n constructor(reason: KeyRotationVerifyErrorReason, message: string) {\n super(message);\n this.name = \"KeyRotationVerifyError\";\n this.reason = reason;\n Object.setPrototypeOf(this, new.target.prototype);\n }\n}\n","import { randomUUID } from \"node:crypto\";\n\nexport function randomMessageId(): string {\n return `msg_${randomUUID()}`;\n}\n","import { createHmac, timingSafeEqual } from \"node:crypto\";\n\nconst SIGNATURE_PREFIX = \"v1,\";\nconst DEFAULT_TOLERANCE_SECONDS = 5 * 60; // 5 minutes\n\n/**\n * Sign a webhook payload using Svix-compatible HMAC-SHA256.\n *\n * @param secret - The webhook secret (with \"whsec_\" prefix)\n * @param msgId - Unique message ID (e.g., \"msg_<uuid>\")\n * @param timestamp - Unix timestamp in seconds\n * @param body - JSON stringified payload\n * @returns Signature string in format \"v1,<base64>\"\n */\nexport function sign(\n secret: string,\n msgId: string,\n timestamp: number,\n body: string,\n): string {\n const secretBytes = Buffer.from(secret.replace(/^whsec_/, \"\"), \"base64\");\n const message = `${msgId}.${timestamp}.${body}`;\n const signature = createHmac(\"sha256\", secretBytes)\n .update(message)\n .digest(\"base64\");\n return `${SIGNATURE_PREFIX}${signature}`;\n}\n\n/**\n * Verify a Svix webhook signature.\n *\n * @param secret - The webhook secret (with \"whsec_\" prefix)\n * @param payload - Raw request body (string or Buffer)\n * @param headers - Svix headers object\n * @param toleranceSeconds - Max age of signature in seconds (default: 5 min)\n * @returns true if valid, false if invalid or expired\n */\nexport function verify(\n secret: string,\n payload: string | Buffer,\n headers: {\n \"svix-id\": string;\n \"svix-timestamp\": string;\n \"svix-signature\": string;\n },\n toleranceSeconds: number = DEFAULT_TOLERANCE_SECONDS,\n): boolean {\n const msgId = headers[\"svix-id\"];\n const timestampStr = headers[\"svix-timestamp\"];\n const signatureHeader = headers[\"svix-signature\"];\n\n const timestamp = parseInt(timestampStr, 10);\n if (Number.isNaN(timestamp)) return false;\n\n const now = Math.floor(Date.now() / 1000);\n if (Math.abs(now - timestamp) > toleranceSeconds) return false;\n\n const body =\n typeof payload === \"string\" ? payload : payload.toString(\"utf-8\");\n const expected = sign(secret, msgId, timestamp, body);\n\n const signatures = signatureHeader.split(\" \");\n const expectedBuf = Buffer.from(expected);\n\n for (const sig of signatures) {\n const sigBuf = Buffer.from(sig);\n if (\n sigBuf.length === expectedBuf.length &&\n timingSafeEqual(sigBuf, expectedBuf)\n ) {\n return true;\n }\n }\n\n return false;\n}\n","import { ConfigurationError } from \"../errors\";\nimport type { HttpClient } from \"../http\";\nimport type {\n ActionManageResponse,\n ApproveActionParams,\n RejectActionParams,\n ResolvedOptions,\n} from \"../types\";\nimport { randomMessageId } from \"../utils\";\nimport { sign } from \"../webhooks/signing\";\n\n/**\n * Client for programmatically approving or rejecting staged actions.\n * Uses HMAC-SHA256 signing (Svix-compatible), identical to {@link WebhooksClient}.\n *\n * @example\n * ```ts\n * const client = new AgentPress({ webhookSecret: \"whsec_...\", org: \"my-org\" });\n *\n * // Approve a staged action\n * await client.actions.approve(\"act_123\", {\n * action: \"my_webhook_action\",\n * });\n *\n * // Reject with a reason\n * await client.actions.reject(\"act_456\", {\n * action: \"my_webhook_action\",\n * reason: \"Insufficient data\",\n * });\n * ```\n */\nexport class ActionsClient {\n private readonly options: ResolvedOptions;\n private readonly http: HttpClient;\n\n constructor(options: ResolvedOptions, http: HttpClient) {\n this.options = options;\n this.http = http;\n }\n\n /**\n * Approve a staged action, optionally modifying the tool call.\n *\n * @throws ConfigurationError if webhookSecret is not configured\n * @throws HttpError on non-2xx response\n * @throws TimeoutError if request exceeds timeout\n */\n async approve(\n actionId: string,\n params: ApproveActionParams,\n ): Promise<ActionManageResponse> {\n const body: Record<string, unknown> = {};\n if (params.editedToolCall !== undefined) {\n body.editedToolCall = params.editedToolCall;\n }\n if (params.remember !== undefined) {\n body.remember = params.remember;\n }\n return this.manage(actionId, params.action, \"approve\", body);\n }\n\n /**\n * Reject a staged action.\n *\n * @throws ConfigurationError if webhookSecret is not configured\n * @throws HttpError on non-2xx response\n * @throws TimeoutError if request exceeds timeout\n */\n async reject(\n actionId: string,\n params: RejectActionParams,\n ): Promise<ActionManageResponse> {\n return this.manage(actionId, params.action, \"reject\", {\n reason: params.reason,\n });\n }\n\n private async manage(\n actionId: string,\n webhookAction: string,\n operation: \"approve\" | \"reject\",\n body: Record<string, unknown>,\n ): Promise<ActionManageResponse> {\n if (!this.options.webhookSecret) {\n throw new ConfigurationError(\n \"webhookSecret is required for action management operations\",\n );\n }\n\n const path = `/webhooks/actions/${this.options.org}/${webhookAction}/manage/${actionId}/${operation}`;\n const bodyStr = JSON.stringify(body);\n const msgId = randomMessageId();\n const timestamp = Math.floor(Date.now() / 1000);\n const signature = sign(\n this.options.webhookSecret,\n msgId,\n timestamp,\n bodyStr,\n );\n\n return this.http.request<ActionManageResponse>(path, {\n method: \"POST\",\n body: bodyStr,\n headers: {\n \"svix-id\": msgId,\n \"svix-timestamp\": String(timestamp),\n \"svix-signature\": signature,\n },\n });\n }\n}\n","import { AgentPressError, HttpError, TimeoutError } from \"./errors\";\nimport type { ResolvedOptions } from \"./types\";\n\n/**\n * Internal shared HTTP client. Not part of the public API -- used by\n * namespace clients (e.g., `WebhooksClient`) to make authenticated requests.\n * @internal\n */\nexport class HttpClient {\n private readonly baseUrl: string;\n private readonly timeout: number;\n private readonly onRequest?: ResolvedOptions[\"onRequest\"];\n private readonly onResponse?: ResolvedOptions[\"onResponse\"];\n\n constructor(options: ResolvedOptions) {\n this.baseUrl = options.baseUrl;\n this.timeout = options.timeout;\n this.onRequest = options.onRequest;\n this.onResponse = options.onResponse;\n }\n\n /**\n * Send an HTTP request to the API. Constructs the full URL from `baseUrl` + `path`,\n * applies the configured timeout via `AbortSignal`, fires `onRequest`/`onResponse`\n * hooks, and parses the JSON response.\n *\n * @throws {TimeoutError} If the request exceeds the configured timeout.\n * @throws {HttpError} If the API returns a non-2xx status code.\n * @throws {AgentPressError} On network failures or non-JSON responses.\n */\n async request<T>(path: string, init: RequestInit): Promise<T> {\n const url = `${this.baseUrl}${path}`;\n\n const headers = new Headers(init.headers);\n if (!headers.has(\"Content-Type\")) {\n headers.set(\"Content-Type\", \"application/json\");\n }\n\n const requestInit: RequestInit = {\n ...init,\n headers,\n signal: AbortSignal.timeout(this.timeout),\n };\n\n this.onRequest?.(url, requestInit);\n\n let response: Response;\n try {\n // biome-ignore lint/style/noRestrictedGlobals: SDK is a standalone package that uses raw fetch\n response = await fetch(url, requestInit);\n } catch (error: unknown) {\n if (\n error instanceof Error &&\n (error.name === \"TimeoutError\" || error.name === \"AbortError\")\n ) {\n throw new TimeoutError(url, this.timeout);\n }\n const message =\n error instanceof Error ? error.message : \"Unknown fetch error\";\n throw new AgentPressError(`Request to ${url} failed: ${message}`);\n }\n\n this.onResponse?.(url, response.clone());\n\n const text = await response.text();\n\n if (!response.ok) {\n throw new HttpError(response.status, text, url);\n }\n\n try {\n return JSON.parse(text) as T;\n } catch {\n throw new AgentPressError(\n `Expected JSON response from ${url} but received: ${text.slice(0, 200)}`,\n );\n }\n }\n}\n","import {\n createRemoteJWKSet,\n type JWTVerifyGetKey,\n errors as joseErrors,\n jwtVerify,\n} from \"jose\";\n\nimport { ConfigurationError, PartnerTokenError } from \"../errors\";\nimport type {\n PartnerTokenClaims,\n ResolvedOptions,\n ResolvedPartnerMcpOptions,\n} from \"../types\";\n\nconst ALGORITHMS = [\"EdDSA\"] as const;\n\ntype RemoteJwks = ReturnType<typeof createRemoteJWKSet>;\n\n/**\n * Client for Partner MCP Spec v1 helpers. Created automatically when\n * {@link AgentPressOptions.partnerMcp} is provided.\n *\n * State (JWKS cache) is per-instance, NOT module-global, so staging and\n * production clients can run side-by-side without cross-talk.\n */\nexport class PartnersClient {\n private readonly options: ResolvedOptions;\n private readonly partnerMcp: ResolvedPartnerMcpOptions | undefined;\n private jwks: RemoteJwks | null = null;\n private jwksKeyFn: JWTVerifyGetKey | null = null;\n\n constructor(options: ResolvedOptions) {\n this.options = options;\n this.partnerMcp = options.partnerMcp;\n }\n\n /**\n * Verify an inbound Partner MCP Spec v1 JWT against AgentPress's JWKS.\n *\n * Enforces the full spec: `algorithms: [\"EdDSA\"]` pinned; `iss`, `aud`,\n * `ext_provider` validated; `sub`, `jti`, `scope` required and non-empty;\n * `kid` header required; `exp` / `iat` validated with ±30s skew (configurable).\n *\n * @param token - Bare JWT string (no `Bearer ` prefix).\n * @returns Typed {@link PartnerTokenClaims}.\n * @throws {PartnerTokenError} with a typed `reason` for RFC 6750 mapping.\n * @throws {ConfigurationError} if `partnerMcp` is not configured.\n */\n async verifyToken(token: string): Promise<PartnerTokenClaims> {\n const cfg = this.requireConfig();\n const jwks = this.getJwks();\n\n let payload: Record<string, unknown>;\n let protectedHeader: { alg?: string; kid?: string; typ?: string };\n\n try {\n const result = await jwtVerify(token, jwks, {\n algorithms: [...ALGORITHMS],\n issuer: cfg.issuer,\n audience: cfg.audience,\n clockTolerance: cfg.clockTolerance,\n });\n payload = result.payload as Record<string, unknown>;\n protectedHeader = result.protectedHeader as {\n alg?: string;\n kid?: string;\n typ?: string;\n };\n } catch (err) {\n throw mapJoseError(err);\n }\n\n // kid header required by spec. jose does not enforce this on its own\n // when the key is resolvable — we enforce it explicitly so forged\n // tokens that elide the kid header can't slip through on a single-key\n // JWKS.\n if (!protectedHeader.kid || typeof protectedHeader.kid !== \"string\") {\n throw new PartnerTokenError(\n \"kid_missing_or_unknown\",\n \"JWT header missing required 'kid'\",\n );\n }\n\n const claims = payload as PartnerTokenClaims & Record<string, unknown>;\n\n // jose's jwtVerify checks `exp` (with clockTolerance) but not `iat`\n // future-time unless `maxTokenAge` is set. The spec requires both sides\n // of the skew window, so enforce the future-iat check explicitly.\n if (typeof claims.iat !== \"number\" || !Number.isFinite(claims.iat)) {\n throw new PartnerTokenError(\n \"missing_claim\",\n \"'iat' claim must be a number\",\n );\n }\n const toleranceSeconds = toSeconds(cfg.clockTolerance);\n const nowSec = Math.floor(Date.now() / 1000);\n if (claims.iat - nowSec > toleranceSeconds) {\n throw new PartnerTokenError(\n \"not_yet_valid\",\n `'iat' is ${claims.iat - nowSec}s in the future, beyond ${toleranceSeconds}s tolerance`,\n );\n }\n\n if (typeof claims.sub !== \"string\" || claims.sub.length === 0) {\n throw new PartnerTokenError(\"missing_claim\", \"'sub' claim is required\");\n }\n if (typeof claims.jti !== \"string\" || claims.jti.length === 0) {\n throw new PartnerTokenError(\"missing_claim\", \"'jti' claim is required\");\n }\n if (typeof claims.scope !== \"string\") {\n throw new PartnerTokenError(\n \"missing_claim\",\n \"'scope' claim must be a string\",\n );\n }\n if (\n typeof claims.ext_provider !== \"string\" ||\n claims.ext_provider.length === 0\n ) {\n throw new PartnerTokenError(\n \"missing_claim\",\n \"'ext_provider' claim is required\",\n );\n }\n if (claims.ext_provider !== cfg.expectedExtProvider) {\n throw new PartnerTokenError(\n \"ext_provider_mismatch\",\n `ext_provider '${claims.ext_provider}' does not match expected '${cfg.expectedExtProvider}'`,\n );\n }\n\n return claims;\n }\n\n /**\n * Force the JWKS cache to refetch immediately. Call this from your\n * `signing_key_rotation` webhook handler after verifying the webhook —\n * otherwise the cache picks up new keys on the next `kid` miss (which\n * works, but with one failed verify latency penalty).\n */\n async refreshJwks(): Promise<void> {\n const jwks = this.getJwks();\n // jose's RemoteJWKSet exposes `.reload()` for exactly this use case.\n const anyJwks = jwks as unknown as { reload?: () => Promise<void> };\n if (typeof anyJwks.reload === \"function\") {\n await anyJwks.reload();\n }\n }\n\n private requireConfig(): ResolvedPartnerMcpOptions {\n if (!this.partnerMcp) {\n throw new ConfigurationError(\n \"partnerMcp options are required for partner token operations\",\n );\n }\n return this.partnerMcp;\n }\n\n private getJwks(): RemoteJwks {\n const cfg = this.requireConfig();\n if (!this.jwks) {\n this.jwks = createRemoteJWKSet(new URL(cfg.jwksUrl), {\n cacheMaxAge: cfg.jwksCacheMaxAgeMs,\n cooldownDuration: 30_000,\n });\n this.jwksKeyFn = this.jwks as unknown as JWTVerifyGetKey;\n }\n return this.jwks;\n }\n}\n\nfunction toSeconds(tolerance: string | number): number {\n if (typeof tolerance === \"number\") return tolerance;\n const match = tolerance.trim().match(/^(\\d+)\\s*(s|m|h)$/i);\n if (!match) return 30;\n const n = Number.parseInt(match[1] as string, 10);\n const unit = (match[2] as string).toLowerCase();\n if (unit === \"s\") return n;\n if (unit === \"m\") return n * 60;\n if (unit === \"h\") return n * 3600;\n return 30;\n}\n\nfunction mapJoseError(err: unknown): PartnerTokenError {\n if (err instanceof PartnerTokenError) return err;\n\n if (err instanceof joseErrors.JWSSignatureVerificationFailed) {\n return new PartnerTokenError(\n \"signature_invalid\",\n \"JWT signature verification failed\",\n );\n }\n if (err instanceof joseErrors.JWKSNoMatchingKey) {\n return new PartnerTokenError(\n \"kid_missing_or_unknown\",\n \"No JWKS key matches the JWT 'kid' header\",\n );\n }\n if (err instanceof joseErrors.JOSEAlgNotAllowed) {\n return new PartnerTokenError(\n \"algorithm_not_allowed\",\n \"JWT 'alg' is not EdDSA\",\n );\n }\n if (err instanceof joseErrors.JWTExpired) {\n return new PartnerTokenError(\"expired\", \"JWT has expired\");\n }\n if (err instanceof joseErrors.JWTClaimValidationFailed) {\n const claim = (err as { claim?: string }).claim;\n if (claim === \"iss\") {\n return new PartnerTokenError(\n \"issuer_mismatch\",\n \"JWT 'iss' does not match expected issuer\",\n );\n }\n if (claim === \"aud\") {\n return new PartnerTokenError(\n \"audience_mismatch\",\n \"JWT 'aud' does not match expected audience\",\n );\n }\n if (claim === \"iat\") {\n return new PartnerTokenError(\n \"not_yet_valid\",\n \"JWT 'iat' is in the future beyond clock tolerance\",\n );\n }\n return new PartnerTokenError(\n \"missing_claim\",\n err.message || \"Claim validation failed\",\n );\n }\n if (\n err instanceof joseErrors.JWTInvalid ||\n err instanceof joseErrors.JWSInvalid\n ) {\n return new PartnerTokenError(\"malformed\", err.message || \"Malformed JWT\");\n }\n if (err instanceof Error) {\n return new PartnerTokenError(\"malformed\", err.message);\n }\n return new PartnerTokenError(\"malformed\", String(err));\n}\n","import { ConfigurationError } from \"../errors\";\nimport type { HttpClient } from \"../http\";\nimport type {\n CreateUserApprovalParams,\n DeleteUserApprovalParams,\n ListUserApprovalsParams,\n ListUserApprovalsResponse,\n ResolvedOptions,\n UpdateUserApprovalParams,\n UserToolApproval,\n} from \"../types\";\nimport { randomMessageId } from \"../utils\";\nimport { sign } from \"../webhooks/signing\";\n\n/**\n * Client for managing per-user auto-approval rules — the SDK equivalent of the\n * console's `/account/auto-approvals` settings page. Uses HMAC-SHA256 signing\n * (Svix-compatible), identical to {@link ActionsClient.manage}.\n *\n * Each call is scoped to a single webhook (identified by `webhookIdentifier`),\n * which both selects the signing secret and scopes which approvals are visible.\n *\n * @example\n * ```ts\n * const client = new AgentPress({ webhookSecret: \"whsec_...\", org: \"my-org\" });\n *\n * // Provision consent so future \"sendEmail\" triggers skip the approval prompt\n * await client.userApprovals.create({\n * webhookIdentifier: \"reviews\",\n * userId: \"user-uuid\",\n * actionWebhookId: \"webhook-uuid\",\n * toolName: \"sendEmail\",\n * mode: \"always_allow\",\n * });\n *\n * // List rules (optionally filtered by userId)\n * const { approvals } = await client.userApprovals.list({\n * webhookIdentifier: \"reviews\",\n * });\n *\n * // Revoke\n * await client.userApprovals.delete(approvalId, { webhookIdentifier: \"reviews\" });\n * ```\n */\nexport class UserApprovalsClient {\n private readonly options: ResolvedOptions;\n private readonly http: HttpClient;\n\n constructor(options: ResolvedOptions, http: HttpClient) {\n this.options = options;\n this.http = http;\n }\n\n /**\n * List auto-approval rules for a webhook. Optionally filter by `userId`.\n *\n * @throws ConfigurationError if webhookSecret is not configured\n * @throws HttpError on non-2xx response\n * @throws TimeoutError if request exceeds timeout\n */\n async list(\n params: ListUserApprovalsParams,\n ): Promise<ListUserApprovalsResponse> {\n const body: Record<string, unknown> = {};\n if (params.userId !== undefined) body.userId = params.userId;\n if (params.authProvider !== undefined)\n body.authProvider = params.authProvider;\n return this.send<ListUserApprovalsResponse>(\n params.webhookIdentifier,\n \"list\",\n body,\n );\n }\n\n /**\n * Create (or upsert) an auto-approval rule. If a rule with the same\n * `(userId, actionWebhookId, toolName)` triple already exists, it is\n * updated in place.\n *\n * @throws ConfigurationError if webhookSecret is not configured\n * @throws HttpError on non-2xx response\n * @throws TimeoutError if request exceeds timeout\n */\n async create(params: CreateUserApprovalParams): Promise<UserToolApproval> {\n const body: Record<string, unknown> = {\n userId: params.userId,\n actionWebhookId: params.actionWebhookId,\n toolName: params.toolName,\n mode: params.mode ?? \"always_allow\",\n };\n if (params.authProvider !== undefined)\n body.authProvider = params.authProvider;\n if (params.expiresAt !== undefined) {\n body.expiresAt =\n params.expiresAt === null ? null : params.expiresAt.toISOString();\n }\n return this.send<UserToolApproval>(\n params.webhookIdentifier,\n \"create\",\n body,\n );\n }\n\n /**\n * Patch an existing auto-approval rule (change mode or expiry).\n *\n * @throws ConfigurationError if webhookSecret is not configured\n * @throws HttpError on non-2xx response (404 if the rule does not belong to this webhook)\n * @throws TimeoutError if request exceeds timeout\n */\n async update(\n id: string,\n params: UpdateUserApprovalParams,\n ): Promise<UserToolApproval> {\n const body: Record<string, unknown> = {};\n if (params.mode !== undefined) body.mode = params.mode;\n if (params.expiresAt !== undefined) {\n body.expiresAt =\n params.expiresAt === null ? null : params.expiresAt.toISOString();\n }\n return this.send<UserToolApproval>(\n params.webhookIdentifier,\n `update/${id}`,\n body,\n );\n }\n\n /**\n * Revoke an auto-approval rule. Future triggers of the corresponding\n * `(user, webhook, tool)` combination will once again stage for approval.\n *\n * @throws ConfigurationError if webhookSecret is not configured\n * @throws HttpError on non-2xx response (404 if the rule does not belong to this webhook)\n * @throws TimeoutError if request exceeds timeout\n */\n async delete(\n id: string,\n params: DeleteUserApprovalParams,\n ): Promise<{ success: boolean }> {\n return this.send<{ success: boolean }>(\n params.webhookIdentifier,\n `delete/${id}`,\n {},\n );\n }\n\n /** Internal: HMAC-sign and POST the body to the scoped path. */\n private async send<T>(\n webhookIdentifier: string,\n operation: string,\n body: Record<string, unknown>,\n ): Promise<T> {\n if (!this.options.webhookSecret) {\n throw new ConfigurationError(\n \"webhookSecret is required for user approval management operations\",\n );\n }\n\n const path = `/webhooks/user-approvals/${this.options.org}/${webhookIdentifier}/${operation}`;\n const bodyStr = JSON.stringify(body);\n const msgId = randomMessageId();\n const timestamp = Math.floor(Date.now() / 1000);\n const signature = sign(\n this.options.webhookSecret,\n msgId,\n timestamp,\n bodyStr,\n );\n\n return this.http.request<T>(path, {\n method: \"POST\",\n body: bodyStr,\n headers: {\n \"svix-id\": msgId,\n \"svix-timestamp\": String(timestamp),\n \"svix-signature\": signature,\n },\n });\n }\n}\n","import { createHmac, timingSafeEqual } from \"node:crypto\";\n\nimport { ConfigurationError, KeyRotationVerifyError } from \"../errors\";\nimport type { KeyRotationEvent, KeyRotationVerifyParams } from \"../types\";\n\nconst MAX_PAYLOAD_BYTES = 8 * 1024; // 8 KB\nconst TIMESTAMP_SKEW_SECONDS = 300; // 5 minutes\nconst SIGNATURE_PREFIX = \"sha256=\";\n\n/**\n * Verify a `signing_key_rotation` webhook signed by AgentPress with\n * HMAC-SHA256 over the raw request body. Returns the typed\n * {@link KeyRotationEvent} payload.\n *\n * @throws {KeyRotationVerifyError} with a typed `reason` for HTTP mapping.\n * @throws {ConfigurationError} if `webhookSecret` is not configured.\n */\nexport function verifyKeyRotation(\n secret: string | undefined,\n params: KeyRotationVerifyParams,\n): KeyRotationEvent {\n if (!secret) {\n throw new ConfigurationError(\n \"webhookSecret is required for key rotation webhook verification\",\n );\n }\n\n const body =\n typeof params.payload === \"string\"\n ? params.payload\n : params.payload.toString(\"utf-8\");\n\n const byteLength =\n typeof params.payload === \"string\"\n ? Buffer.byteLength(params.payload, \"utf-8\")\n : params.payload.length;\n if (byteLength > MAX_PAYLOAD_BYTES) {\n throw new KeyRotationVerifyError(\n \"payload_too_large\",\n `Payload exceeds ${MAX_PAYLOAD_BYTES} bytes`,\n );\n }\n\n const signatureHeader = readHeader(params.headers, \"x-agentpress-signature\");\n const timestampHeader = readHeader(params.headers, \"x-agentpress-timestamp\");\n\n if (!signatureHeader?.startsWith(SIGNATURE_PREFIX)) {\n throw new KeyRotationVerifyError(\n \"invalid_signature_format\",\n `Signature header missing or does not start with '${SIGNATURE_PREFIX}'`,\n );\n }\n const providedHex = signatureHeader\n .slice(SIGNATURE_PREFIX.length)\n .toLowerCase();\n if (!/^[0-9a-f]+$/.test(providedHex)) {\n throw new KeyRotationVerifyError(\n \"invalid_signature_format\",\n \"Signature is not a hex string\",\n );\n }\n\n if (!timestampHeader) {\n throw new KeyRotationVerifyError(\n \"invalid_timestamp\",\n \"x-agentpress-timestamp header is required\",\n );\n }\n const timestamp = Number.parseInt(timestampHeader, 10);\n if (\n !Number.isFinite(timestamp) ||\n String(timestamp) !== timestampHeader.trim()\n ) {\n throw new KeyRotationVerifyError(\n \"invalid_timestamp\",\n \"x-agentpress-timestamp is not a valid unix seconds integer\",\n );\n }\n const now = Math.floor(Date.now() / 1000);\n if (Math.abs(now - timestamp) > TIMESTAMP_SKEW_SECONDS) {\n throw new KeyRotationVerifyError(\n \"timestamp_out_of_window\",\n `Timestamp skew ${Math.abs(now - timestamp)}s exceeds ${TIMESTAMP_SKEW_SECONDS}s tolerance`,\n );\n }\n\n const expectedHex = createHmac(\"sha256\", secret).update(body).digest(\"hex\");\n const providedBuf = Buffer.from(providedHex, \"hex\");\n const expectedBuf = Buffer.from(expectedHex, \"hex\");\n if (\n providedBuf.length !== expectedBuf.length ||\n !timingSafeEqual(providedBuf, expectedBuf)\n ) {\n throw new KeyRotationVerifyError(\n \"invalid_signature\",\n \"HMAC signature mismatch\",\n );\n }\n\n let parsed: unknown;\n try {\n parsed = JSON.parse(body);\n } catch {\n throw new KeyRotationVerifyError(\n \"malformed_payload\",\n \"Payload is not valid JSON\",\n );\n }\n\n return validatePayload(parsed);\n}\n\nfunction readHeader(\n headers: Record<string, string | undefined>,\n name: string,\n): string | undefined {\n // Headers are case-insensitive; normalize without mutating the caller's object.\n const lowered = name.toLowerCase();\n for (const [k, v] of Object.entries(headers)) {\n if (k.toLowerCase() === lowered && typeof v === \"string\" && v.length > 0) {\n return v;\n }\n }\n return undefined;\n}\n\nfunction validatePayload(raw: unknown): KeyRotationEvent {\n if (!raw || typeof raw !== \"object\") {\n throw new KeyRotationVerifyError(\n \"malformed_payload\",\n \"Payload must be a JSON object\",\n );\n }\n const obj = raw as Record<string, unknown>;\n if (obj.event !== \"signing_key_rotation\") {\n throw new KeyRotationVerifyError(\n \"malformed_payload\",\n `Unexpected event '${String(obj.event)}'`,\n );\n }\n if (obj.type !== \"scheduled\" && obj.type !== \"emergency\") {\n throw new KeyRotationVerifyError(\n \"malformed_payload\",\n \"'type' must be 'scheduled' or 'emergency'\",\n );\n }\n for (const key of [\n \"retiredKid\",\n \"newCurrentKid\",\n \"retiredAt\",\n \"effectiveAt\",\n \"jwksUrl\",\n ]) {\n if (typeof obj[key] !== \"string\" || (obj[key] as string).length === 0) {\n throw new KeyRotationVerifyError(\n \"malformed_payload\",\n `'${key}' must be a non-empty string`,\n );\n }\n }\n if (obj.reason !== undefined && typeof obj.reason !== \"string\") {\n throw new KeyRotationVerifyError(\n \"malformed_payload\",\n \"'reason' must be a string when present\",\n );\n }\n\n const event: KeyRotationEvent = {\n event: \"signing_key_rotation\",\n type: obj.type as \"scheduled\" | \"emergency\",\n retiredKid: obj.retiredKid as string,\n newCurrentKid: obj.newCurrentKid as string,\n retiredAt: obj.retiredAt as string,\n effectiveAt: obj.effectiveAt as string,\n jwksUrl: obj.jwksUrl as string,\n };\n if (typeof obj.reason === \"string\") {\n event.reason = obj.reason;\n }\n return event;\n}\n","import {\n AgentPressError,\n ConfigurationError,\n WebhookSignatureError,\n} from \"../errors\";\nimport type { HttpClient } from \"../http\";\nimport type {\n ActionCallbackPayload,\n KeyRotationEvent,\n KeyRotationVerifyParams,\n ResolvedOptions,\n WebhookResponse,\n WebhookSendParams,\n WebhookVerifyParams,\n} from \"../types\";\nimport { randomMessageId } from \"../utils\";\nimport { verifyKeyRotation as verifyKeyRotationImpl } from \"./keyRotation\";\nimport { sign, verify as verifySig } from \"./signing\";\n\nexport class WebhooksClient {\n private readonly options: ResolvedOptions;\n private readonly http: HttpClient;\n\n constructor(options: ResolvedOptions, http: HttpClient) {\n this.options = options;\n this.http = http;\n }\n\n /**\n * Send an arbitrary webhook payload to AgentPress.\n * Signs the payload with HMAC-SHA256 (Svix-compatible).\n *\n * @throws ConfigurationError if webhookSecret is not configured\n * @throws HttpError on non-2xx response\n * @throws TimeoutError if request exceeds timeout\n */\n async send(params: WebhookSendParams): Promise<WebhookResponse> {\n if (!this.options.webhookSecret) {\n throw new ConfigurationError(\n \"webhookSecret is required for webhook operations\",\n );\n }\n\n const path = `/webhooks/actions/${this.options.org}/${params.action}`;\n const body = JSON.stringify(params.payload);\n const msgId = randomMessageId();\n const timestamp = Math.floor(Date.now() / 1000);\n const signature = sign(this.options.webhookSecret, msgId, timestamp, body);\n\n return this.http.request<WebhookResponse>(path, {\n method: \"POST\",\n body,\n headers: {\n \"svix-id\": msgId,\n \"svix-timestamp\": String(timestamp),\n \"svix-signature\": signature,\n },\n });\n }\n\n /**\n * Verify an inbound Svix webhook signature.\n *\n * @returns true if valid, false if invalid or expired\n * @throws ConfigurationError if webhookSecret is not configured\n */\n verify(params: WebhookVerifyParams): boolean {\n if (!this.options.webhookSecret) {\n throw new ConfigurationError(\n \"webhookSecret is required for webhook verification\",\n );\n }\n\n return verifySig(\n this.options.webhookSecret,\n params.payload,\n params.headers,\n );\n }\n\n /**\n * Verify an inbound Svix webhook signature, throwing on failure.\n * Useful for middleware patterns where invalid signatures should halt processing.\n *\n * @throws WebhookSignatureError if signature is invalid or expired\n * @throws ConfigurationError if webhookSecret is not configured\n */\n verifyOrThrow(params: WebhookVerifyParams): void {\n if (!this.verify(params)) {\n throw new WebhookSignatureError(\"Invalid webhook signature\");\n }\n }\n\n /**\n * Verify and parse an inbound webhook from AgentPress.\n * Combines signature verification with JSON parsing and type casting.\n * This is the recommended way to handle incoming webhooks.\n *\n * @throws WebhookSignatureError if signature is invalid or expired\n * @throws ConfigurationError if webhookSecret is not configured\n * @throws AgentPressError if payload is not valid JSON\n */\n constructEvent(params: WebhookVerifyParams): ActionCallbackPayload {\n this.verifyOrThrow(params);\n const body =\n typeof params.payload === \"string\"\n ? params.payload\n : params.payload.toString(\"utf-8\");\n try {\n return JSON.parse(body) as ActionCallbackPayload;\n } catch {\n throw new AgentPressError(\"Webhook payload is not valid JSON\");\n }\n }\n\n /**\n * Verify an inbound `signing_key_rotation` webhook (HMAC-SHA256 + timestamp\n * + typed payload) from AgentPress. See the Partner MCP Spec v1 for the\n * full contract.\n *\n * @throws {KeyRotationVerifyError} with a typed `reason` for HTTP mapping\n * (401 for signature errors, 400 for malformed payload, 413 for oversize).\n * @throws {ConfigurationError} if `webhookSecret` is not configured.\n */\n verifyKeyRotation(params: KeyRotationVerifyParams): KeyRotationEvent {\n return verifyKeyRotationImpl(this.options.webhookSecret, params);\n }\n}\n","import { ActionsClient } from \"./actions/client\";\nimport { ConfigurationError } from \"./errors\";\nimport { HttpClient } from \"./http\";\nimport { PartnersClient } from \"./partners/client\";\nimport type {\n AgentPressOptions,\n ResolvedOptions,\n ResolvedPartnerMcpOptions,\n} from \"./types\";\nimport { UserApprovalsClient } from \"./userApprovals/client\";\nimport { WebhooksClient } from \"./webhooks/client\";\n\n/**\n * Main entry point for the AgentPress SDK. Provides namespaced access to API\n * resources (e.g., `client.webhooks.send()`, `client.actions.approve()`).\n * Validates all configuration options at construction time, so invalid config fails fast.\n *\n * @example\n * ```ts\n * const client = new AgentPress({\n * apiKey: \"ak_...\",\n * webhookSecret: \"whsec_...\",\n * });\n * await client.webhooks.send({ action: \"my_action\", payload: { ... } });\n * await client.actions.approve(\"act_123\", { action: \"my_action\" });\n * ```\n */\nexport class AgentPress {\n /** Webhook operations: send outbound webhooks and verify inbound signatures. */\n public readonly webhooks: WebhooksClient;\n /** Action management: approve or reject staged actions. */\n public readonly actions: ActionsClient;\n /** Per-user auto-approval rules (read / create / update / delete). */\n public readonly userApprovals: UserApprovalsClient;\n /** Partner MCP Spec v1 helpers (inbound JWT verification, JWKS refresh). */\n public readonly partners: PartnersClient;\n\n /**\n * @param options - SDK configuration. All fields are optional with sensible defaults.\n * @throws {ConfigurationError} If `timeout` is non-positive or `webhookSecret` has an invalid prefix.\n */\n constructor(options: AgentPressOptions = {}) {\n const resolved = resolveOptions(options);\n const http = new HttpClient(resolved);\n this.webhooks = new WebhooksClient(resolved, http);\n this.actions = new ActionsClient(resolved, http);\n this.userApprovals = new UserApprovalsClient(resolved, http);\n this.partners = new PartnersClient(resolved);\n }\n}\n\nfunction resolveOptions(options: AgentPressOptions): ResolvedOptions {\n const baseUrl = (options.baseUrl ?? \"https://api.agent.press\").replace(\n /\\/+$/,\n \"\",\n );\n const timeout = options.timeout ?? 30_000;\n const org = options.org ?? \"default-org\";\n\n if (timeout <= 0 || !Number.isFinite(timeout)) {\n throw new ConfigurationError(\"timeout must be a positive number\");\n }\n\n if (\n options.webhookSecret !== undefined &&\n !options.webhookSecret.startsWith(\"whsec_\")\n ) {\n throw new ConfigurationError('webhookSecret must start with \"whsec_\"');\n }\n\n return {\n baseUrl,\n timeout,\n org,\n webhookSecret: options.webhookSecret,\n apiKey: options.apiKey,\n partnerMcp: resolvePartnerMcp(options.partnerMcp),\n onRequest: options.onRequest,\n onResponse: options.onResponse,\n };\n}\n\nfunction resolvePartnerMcp(\n options: AgentPressOptions[\"partnerMcp\"],\n): ResolvedPartnerMcpOptions | undefined {\n if (!options) return undefined;\n\n if (typeof options.jwksUrl !== \"string\" || options.jwksUrl.length === 0) {\n throw new ConfigurationError(\"partnerMcp.jwksUrl is required\");\n }\n try {\n // Validate early so a bad URL fails at construction, not on first verify.\n new URL(options.jwksUrl);\n } catch {\n throw new ConfigurationError(\"partnerMcp.jwksUrl must be a valid URL\");\n }\n if (typeof options.issuer !== \"string\" || options.issuer.length === 0) {\n throw new ConfigurationError(\"partnerMcp.issuer is required\");\n }\n if (typeof options.audience !== \"string\" || options.audience.length === 0) {\n throw new ConfigurationError(\"partnerMcp.audience is required\");\n }\n if (\n typeof options.expectedExtProvider !== \"string\" ||\n options.expectedExtProvider.length === 0\n ) {\n throw new ConfigurationError(\"partnerMcp.expectedExtProvider is required\");\n }\n\n const clockTolerance = options.clockTolerance ?? \"30s\";\n const jwksCacheMaxAgeMs = options.jwksCacheMaxAgeMs ?? 3_600_000;\n if (jwksCacheMaxAgeMs <= 0 || !Number.isFinite(jwksCacheMaxAgeMs)) {\n throw new ConfigurationError(\n \"partnerMcp.jwksCacheMaxAgeMs must be a positive number\",\n );\n }\n\n return {\n jwksUrl: options.jwksUrl,\n issuer: options.issuer,\n audience: options.audience,\n expectedExtProvider: options.expectedExtProvider,\n clockTolerance,\n jwksCacheMaxAgeMs,\n };\n}\n"],"mappings":";;;;;;;;AAIA,IAAa,kBAAb,cAAqC,MAAM;CACzC,YAAY,SAAiB;AAC3B,QAAM,QAAQ;AACd,OAAK,OAAO;AACZ,SAAO,eAAe,MAAM,IAAI,OAAO,UAAU;;;;;;;AAQrD,IAAa,qBAAb,cAAwC,gBAAgB;CACtD,YAAY,SAAiB;AAC3B,QAAM,QAAQ;AACd,OAAK,OAAO;AACZ,SAAO,eAAe,MAAM,IAAI,OAAO,UAAU;;;;;;;;;;;AAYrD,IAAa,YAAb,cAA+B,gBAAgB;CAC7C;CACA;CACA;CAEA,YAAY,YAAoB,cAAsB,KAAa;AACjE,QAAM,QAAQ,WAAW,QAAQ,MAAM;AACvC,OAAK,OAAO;AACZ,OAAK,aAAa;AAClB,OAAK,eAAe;AACpB,OAAK,MAAM;AACX,SAAO,eAAe,MAAM,IAAI,OAAO,UAAU;;;;AAKrD,IAAa,eAAb,cAAkC,gBAAgB;CAChD,YAAY,KAAa,SAAiB;AACxC,QAAM,cAAc,IAAI,mBAAmB,QAAQ,IAAI;AACvD,OAAK,OAAO;AACZ,SAAO,eAAe,MAAM,IAAI,OAAO,UAAU;;;;AAKrD,IAAa,wBAAb,cAA2C,gBAAgB;CACzD,YAAY,SAAiB;AAC3B,QAAM,QAAQ;AACd,OAAK,OAAO;AACZ,SAAO,eAAe,MAAM,IAAI,OAAO,UAAU;;;;;;;;AAsBrD,IAAa,oBAAb,cAAuC,gBAAgB;CACrD;CAEA,YAAY,QAAiC,SAAiB;AAC5D,QAAM,QAAQ;AACd,OAAK,OAAO;AACZ,OAAK,SAAS;AACd,SAAO,eAAe,MAAM,IA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ACuC;AACvC,KAAI,CAAC,QAAS,QAAO,KAAA;AAErB,KAAI,OAAO,QAAQ,YAAY,YAAY,QAAQ,QAAQ,WAAW,EACpE,OAAM,IAAI,mBAAmB,iCAAiC;AAEhE,KAAI;AAEF,MAAI,IAAI,QAAQ,QAAQ;SAClB;AACN,QAAM,IAAI,mBAAmB,yCAAyC;;AAExE,KAAI,OAAO,QAAQ,WAAW,YAAY,QAAQ,OAAO,WAAW,EAClE,OAAM,IAAI,mBAAmB,gCAAgC;AAE/D,KAAI,OAAO,QAAQ,aAAa,YAAY,QAAQ,SAAS,WAAW,EACtE,OAAM,IAAI,mBAAmB,kCAAkC;AAEjE,KACE,OAAO,QAAQ,wBAAwB,YACvC,QAAQ,oBAAoB,WAAW,EAEvC,OAAM,IAAI,mBAAmB,6CAA6C;CAG5E,MAAM,iBAAiB,QAAQ,kBAAkB;CACjD,MAAM,oBAAoB,QAAQ,qBAAqB;AACvD,KAAI,qBAAqB,KAAK,CAAC,OAAO,SAAS,kBAAkB,CAC/D,OAAM,IAAI,mBACR,yDACD;AAGH,QAAO;EACL,SAAS,QAAQ;EACjB,QAAQ,QAAQ;EAChB,UAAU,QAAQ;EAClB,qBAAqB,QAAQ;EAC7B;EACA;EACD"}
package/dist/index.d.cts CHANGED
@@ -11,11 +11,106 @@ interface AgentPressOptions {
11
11
  timeout?: number;
12
12
  /** Organization identifier sent with requests. @default "default-org" */
13
13
  org?: string;
14
+ /**
15
+ * Partner MCP Spec v1 configuration. Required only if you call
16
+ * {@link PartnersClient.verifyToken} or {@link WebhooksClient.verifyKeyRotation}.
17
+ *
18
+ * Each environment (staging / production) needs its own {@link AgentPress}
19
+ * instance with its own `partnerMcp` block — never share a client between
20
+ * environments. JWKS cache state is per-instance, so side-by-side staging
21
+ * and prod clients have no cross-talk.
22
+ */
23
+ partnerMcp?: PartnerMcpOptions;
14
24
  /** Hook called before every outbound HTTP request (useful for logging/tracing). */
15
25
  onRequest?: (url: string, init: RequestInit) => void;
16
26
  /** Hook called after every HTTP response is received. */
17
27
  onResponse?: (url: string, response: Response) => void;
18
28
  }
29
+ /** Partner MCP Spec v1 configuration. See {@link AgentPressOptions.partnerMcp}. */
30
+ interface PartnerMcpOptions {
31
+ /**
32
+ * Full URL to the issuing AgentPress org's JWKS.
33
+ * Per-org as of Partner MCP Spec v1 (per-org signing keys), e.g.
34
+ * `https://api.agent.press/orgs/<org-slug>/.well-known/jwks.json`.
35
+ * The org admin who registered you as a partner will give you the
36
+ * exact URL along with their `<org-slug>`.
37
+ */
38
+ jwksUrl: string;
39
+ /**
40
+ * Exact match for the JWT `iss` claim. Per-org scoped, e.g.
41
+ * `https://api.agent.press/orgs/<org-slug>`. The JWKS URL above is
42
+ * always `<issuer>/.well-known/jwks.json`.
43
+ */
44
+ issuer: string;
45
+ /** Exact match for the JWT `aud` claim — your partner MCP's stable URL. */
46
+ audience: string;
47
+ /** Required value for the `ext_provider` claim, e.g. `"localfalcon"`. */
48
+ expectedExtProvider: string;
49
+ /**
50
+ * Clock skew tolerance for `iat` / `exp` validation. Accepts a jose duration
51
+ * string (`"30s"`, `"1m"`) or a number of seconds.
52
+ * @default "30s"
53
+ */
54
+ clockTolerance?: string | number;
55
+ /**
56
+ * JWKS cache max age in milliseconds. Cache is per-instance, not module-global.
57
+ * @default 3_600_000 (1 hour)
58
+ */
59
+ jwksCacheMaxAgeMs?: number;
60
+ }
61
+ /** A verified Partner MCP Spec v1 JWT claim set. */
62
+ interface PartnerTokenClaims {
63
+ /** The external user id (verified non-empty). */
64
+ sub: string;
65
+ /** Space-separated scope string, per RFC 8693. May be empty but always present. */
66
+ scope: string;
67
+ /** External auth provider name; verified against {@link PartnerMcpOptions.expectedExtProvider}. */
68
+ ext_provider: string;
69
+ /** Unique token id. Non-empty. Partners build replay caches keyed by this. */
70
+ jti: string;
71
+ /** Already validated against {@link PartnerMcpOptions.issuer}; returned for audit logs. */
72
+ iss: string;
73
+ /** Already validated against {@link PartnerMcpOptions.audience}; returned for audit logs. */
74
+ aud: string;
75
+ /** Unix seconds. */
76
+ iat: number;
77
+ /** Unix seconds. */
78
+ exp: number;
79
+ /** AgentPress org identifier, optional. */
80
+ org_id?: string;
81
+ /** AgentPress thread identifier, optional. */
82
+ thread_id?: string;
83
+ /** Reserved for multi-tenant partner flows. */
84
+ settings_id?: string;
85
+ /** Forward-compat: any additional claims pass through. */
86
+ [key: string]: unknown;
87
+ }
88
+ /** Parameters for {@link WebhooksClient.verifyKeyRotation}. */
89
+ interface KeyRotationVerifyParams {
90
+ /** Raw request body (string or Buffer) — must not be parsed/modified. */
91
+ payload: string | Buffer;
92
+ /**
93
+ * Incoming HTTP headers. Accepts plain `Record<string, string | undefined>`
94
+ * so Hono / Fastify / Express / Fetch / Worker all work interchangeably.
95
+ * Must include `x-agentpress-signature` and `x-agentpress-timestamp`.
96
+ */
97
+ headers: Record<string, string | undefined>;
98
+ }
99
+ /** A verified `signing_key_rotation` webhook payload. */
100
+ interface KeyRotationEvent {
101
+ event: "signing_key_rotation";
102
+ type: "scheduled" | "emergency";
103
+ retiredKid: string;
104
+ newCurrentKid: string;
105
+ /** ISO 8601 timestamp. */
106
+ retiredAt: string;
107
+ /** ISO 8601 timestamp. */
108
+ effectiveAt: string;
109
+ /** Matches the configured partner JWKS URL. */
110
+ jwksUrl: string;
111
+ /** Present only on `type: "emergency"` rotations. */
112
+ reason?: string;
113
+ }
19
114
  /** Parameters for {@link WebhooksClient.send}. */
20
115
  interface WebhookSendParams {
21
116
  /** Webhook action name (matches an action rule on the server). */
@@ -219,9 +314,19 @@ interface ResolvedOptions {
219
314
  org: string;
220
315
  webhookSecret?: string;
221
316
  apiKey?: string;
317
+ partnerMcp?: ResolvedPartnerMcpOptions;
222
318
  onRequest?: AgentPressOptions["onRequest"];
223
319
  onResponse?: AgentPressOptions["onResponse"];
224
320
  }
321
+ /** @internal Resolved (validated, defaulted) partner MCP options. */
322
+ interface ResolvedPartnerMcpOptions {
323
+ jwksUrl: string;
324
+ issuer: string;
325
+ audience: string;
326
+ expectedExtProvider: string;
327
+ clockTolerance: string | number;
328
+ jwksCacheMaxAgeMs: number;
329
+ }
225
330
  //#endregion
226
331
  //#region src/http.d.ts
227
332
  /**
@@ -291,6 +396,44 @@ declare class ActionsClient {
291
396
  private manage;
292
397
  }
293
398
  //#endregion
399
+ //#region src/partners/client.d.ts
400
+ /**
401
+ * Client for Partner MCP Spec v1 helpers. Created automatically when
402
+ * {@link AgentPressOptions.partnerMcp} is provided.
403
+ *
404
+ * State (JWKS cache) is per-instance, NOT module-global, so staging and
405
+ * production clients can run side-by-side without cross-talk.
406
+ */
407
+ declare class PartnersClient {
408
+ private readonly options;
409
+ private readonly partnerMcp;
410
+ private jwks;
411
+ private jwksKeyFn;
412
+ constructor(options: ResolvedOptions);
413
+ /**
414
+ * Verify an inbound Partner MCP Spec v1 JWT against AgentPress's JWKS.
415
+ *
416
+ * Enforces the full spec: `algorithms: ["EdDSA"]` pinned; `iss`, `aud`,
417
+ * `ext_provider` validated; `sub`, `jti`, `scope` required and non-empty;
418
+ * `kid` header required; `exp` / `iat` validated with ±30s skew (configurable).
419
+ *
420
+ * @param token - Bare JWT string (no `Bearer ` prefix).
421
+ * @returns Typed {@link PartnerTokenClaims}.
422
+ * @throws {PartnerTokenError} with a typed `reason` for RFC 6750 mapping.
423
+ * @throws {ConfigurationError} if `partnerMcp` is not configured.
424
+ */
425
+ verifyToken(token: string): Promise<PartnerTokenClaims>;
426
+ /**
427
+ * Force the JWKS cache to refetch immediately. Call this from your
428
+ * `signing_key_rotation` webhook handler after verifying the webhook —
429
+ * otherwise the cache picks up new keys on the next `kid` miss (which
430
+ * works, but with one failed verify latency penalty).
431
+ */
432
+ refreshJwks(): Promise<void>;
433
+ private requireConfig;
434
+ private getJwks;
435
+ }
436
+ //#endregion
294
437
  //#region src/userApprovals/client.d.ts
295
438
  /**
296
439
  * Client for managing per-user auto-approval rules — the SDK equivalent of the
@@ -406,6 +549,16 @@ declare class WebhooksClient {
406
549
  * @throws AgentPressError if payload is not valid JSON
407
550
  */
408
551
  constructEvent(params: WebhookVerifyParams): ActionCallbackPayload;
552
+ /**
553
+ * Verify an inbound `signing_key_rotation` webhook (HMAC-SHA256 + timestamp
554
+ * + typed payload) from AgentPress. See the Partner MCP Spec v1 for the
555
+ * full contract.
556
+ *
557
+ * @throws {KeyRotationVerifyError} with a typed `reason` for HTTP mapping
558
+ * (401 for signature errors, 400 for malformed payload, 413 for oversize).
559
+ * @throws {ConfigurationError} if `webhookSecret` is not configured.
560
+ */
561
+ verifyKeyRotation(params: KeyRotationVerifyParams): KeyRotationEvent;
409
562
  }
410
563
  //#endregion
411
564
  //#region src/client.d.ts
@@ -431,6 +584,8 @@ declare class AgentPress {
431
584
  readonly actions: ActionsClient;
432
585
  /** Per-user auto-approval rules (read / create / update / delete). */
433
586
  readonly userApprovals: UserApprovalsClient;
587
+ /** Partner MCP Spec v1 helpers (inbound JWT verification, JWKS refresh). */
588
+ readonly partners: PartnersClient;
434
589
  /**
435
590
  * @param options - SDK configuration. All fields are optional with sensible defaults.
436
591
  * @throws {ConfigurationError} If `timeout` is non-positive or `webhookSecret` has an invalid prefix.
@@ -475,6 +630,27 @@ declare class TimeoutError extends AgentPressError {
475
630
  declare class WebhookSignatureError extends AgentPressError {
476
631
  constructor(message: string);
477
632
  }
633
+ /** Reason codes for {@link PartnerTokenError}. Maps 1:1 to RFC 6750 `error_description` values. */
634
+ type PartnerTokenErrorReason = "signature_invalid" | "issuer_mismatch" | "audience_mismatch" | "expired" | "not_yet_valid" | "missing_claim" | "ext_provider_mismatch" | "algorithm_not_allowed" | "kid_missing_or_unknown" | "malformed";
635
+ /**
636
+ * Thrown by {@link PartnersClient.verifyToken} when a Partner MCP Spec v1 JWT
637
+ * fails verification. Partners map `reason` to their RFC 6750 `WWW-Authenticate`
638
+ * response (`401 invalid_token` for all reasons in this class).
639
+ */
640
+ declare class PartnerTokenError extends AgentPressError {
641
+ readonly reason: PartnerTokenErrorReason;
642
+ constructor(reason: PartnerTokenErrorReason, message: string);
643
+ }
644
+ /** Reason codes for {@link KeyRotationVerifyError}. */
645
+ type KeyRotationVerifyErrorReason = "invalid_signature" | "invalid_signature_format" | "timestamp_out_of_window" | "invalid_timestamp" | "payload_too_large" | "malformed_payload";
646
+ /**
647
+ * Thrown by {@link WebhooksClient.verifyKeyRotation} when a `signing_key_rotation`
648
+ * webhook fails HMAC / timestamp / payload validation.
649
+ */
650
+ declare class KeyRotationVerifyError extends AgentPressError {
651
+ readonly reason: KeyRotationVerifyErrorReason;
652
+ constructor(reason: KeyRotationVerifyErrorReason, message: string);
653
+ }
478
654
  //#endregion
479
- export { type ActionCallbackPayload, type ActionEventType, type ActionManageResponse, type ActionStatus, ActionsClient, AgentPress, AgentPressError, type AgentPressOptions, type AgentResponse, type ApprovalMode, type ApproveActionParams, ConfigurationError, type CreateUserApprovalParams, type DeleteUserApprovalParams, HttpError, type ListUserApprovalsParams, type ListUserApprovalsResponse, type RejectActionParams, type StagedToolCall, TimeoutError, type ToolCallResult, type UpdateUserApprovalParams, UserApprovalsClient, type UserToolApproval, type WebhookResponse, type WebhookSendParams, WebhookSignatureError, type WebhookVerifyParams };
655
+ export { type ActionCallbackPayload, type ActionEventType, type ActionManageResponse, type ActionStatus, ActionsClient, AgentPress, AgentPressError, type AgentPressOptions, type AgentResponse, type ApprovalMode, type ApproveActionParams, ConfigurationError, type CreateUserApprovalParams, type DeleteUserApprovalParams, HttpError, type KeyRotationEvent, KeyRotationVerifyError, type KeyRotationVerifyErrorReason, type KeyRotationVerifyParams, type ListUserApprovalsParams, type ListUserApprovalsResponse, type PartnerMcpOptions, type PartnerTokenClaims, PartnerTokenError, type PartnerTokenErrorReason, PartnersClient, type RejectActionParams, type StagedToolCall, TimeoutError, type ToolCallResult, type UpdateUserApprovalParams, UserApprovalsClient, type UserToolApproval, type WebhookResponse, type WebhookSendParams, WebhookSignatureError, type WebhookVerifyParams, WebhooksClient };
480
656
  //# sourceMappingURL=index.d.cts.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.d.cts","names":[],"sources":["../src/types.ts","../src/http.ts","../src/actions/client.ts","../src/userApprovals/client.ts","../src/webhooks/client.ts","../src/client.ts","../src/errors.ts"],"mappings":";;UACiB,iBAAA;EAAiB;EAEhC,aAAA;EAY6C;EAV7C,MAAA;EAAA;EAEA,OAAA;EAEA;EAAA,OAAA;EAIA;EAFA,GAAA;EAEgC;EAAhC,SAAA,IAAa,GAAA,UAAa,IAAA,EAAM,WAAA;EAEhC;EAAA,UAAA,IAAc,GAAA,UAAa,QAAA,EAAU,QAAA;AAAA;;UAItB,iBAAA;EAJ8B;EAM7C,MAAA;EAFgC;EAIhC,OAAA,EAAS,MAAA;AAAA;;UAIM,mBAAA;EAJN;EAMT,OAAA,WAAkB,MAAA;EANH;EAQf,OAAA;IACE,SAAA;IACA,gBAAA;IACA,gBAAA;EAAA;AAAA;;UAKa,eAAA;EACf,OAAA;EANE;EAQF,QAAA;EARkB;EAUlB,aAAA;EACA,OAAA;EACA,IAAA,GAAO,MAAA;AAAA;;KAMG,eAAA;;UASK,cAAA;EACf,QAAA;EACA,UAAA;EACA,SAAA,EAAW,MAAA;AAAA;AAZb;AAAA,UAgBiB,mBAAA;;EAEf,MAAA;EAlByB;EAoBzB,cAAA;IACE,QAAA;IACA,SAAA,EAAW,MAAA;EAAA;EAZb;;;;;;AAMF;;EAgBE,QAAA;AAAA;;UAIe,kBAAA;EAfb;EAiBF,MAAA;EAhBa;EAkBb,MAAA;AAAA;;UAIe,oBAAA;EACf,OAAA;EACA,QAAA;EACA,MAAA,EAAQ,YAAA;AAAA;AAHV;AAAA,KASY,YAAA;;UAUK,cAAA;EACf,QAAA;EACA,SAAA,EAAW,MAAA;EACX,MAAA;AAAA;;UAIe,aAAA;EAjBL;EAmBV,IAAA;;EAEA,SAAA,EAAW,cAAA;AAAA;AAXb;;;;AAAA,UAkBiB,qBAAA;EACf,QAAA;EACA,MAAA,EAAQ,YAAA;EACR,UAAA;EAlBM;EAoBN,SAAA,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DY;;;;;;;;;EIwElC,cAAA,CAAe,MAAA,EAAQ,mBAAA,GAAsB,qBAAA;AAAA;;;;;;;;;;;;;;;;;;cC7ElC,UAAA;ELHI;EAAA,SKKC,QAAA,EAAU,cAAA;;WAEV,OAAA,EAAS,aAAA;ELLzB;EAAA,SKOgB,aAAA,EAAe,mBAAA;ELLtB;;;AAIX;cKOc,OAAA,GAAS,iBAAA;AAAA;;;;ALjCvB;;;cMGa,eAAA,SAAwB,KAAA;cACvB,OAAA;AAAA;;;;;cAWD,kBAAA,SAA2B,eAAA;cAC1B,OAAA;AAAA;;;;;;;ANEd;;cMaa,SAAA,SAAkB,eAAA;EAAA,SACb,UAAA;EAAA,SACA,YAAA;EAAA,SACA,GAAA;cAEJ,UAAA,UAAoB,YAAA,UAAsB,GAAA;AAAA;;cAW3C,YAAA,SAAqB,eAAA;cACpB,GAAA,UAAa,OAAA;AAAA;;cAQd,qBAAA,SAA8B,eAAA;cAC7B,OAAA;AAAA"}
1
+ {"version":3,"file":"index.d.cts","names":[],"sources":["../src/types.ts","../src/http.ts","../src/actions/client.ts","../src/partners/client.ts","../src/userApprovals/client.ts","../src/webhooks/client.ts","../src/client.ts","../src/errors.ts"],"mappings":";;UACiB,iBAAA;EAAiB;EAEhC,aAAA;EAkBa;EAhBb,MAAA;EAoBqC;EAlBrC,OAAA;EAkB6C;EAhB7C,OAAA;EAJA;EAMA,GAAA;EAFA;;;;;;;;;EAYA,UAAA,GAAa,iBAAA;EAIwB;EAFrC,SAAA,IAAa,GAAA,UAAa,IAAA,EAAM,WAAA;EAEa;EAA7C,UAAA,IAAc,GAAA,UAAa,QAAA,EAAU,QAAA;AAAA;;UAItB,iBAAA;EAAiB;;;;;;;EAQhC,OAAA;EAqBiB;AAInB;;;;EAnBE,MAAA;EAuBA;EArBA,QAAA;EAyBA;EAvBA,mBAAA;EA2BA;;;;;EArBA,cAAA;EAiCC;;;AAIH;EAhCE,iBAAA;AAAA;;UAIe,kBAAA;EA8BG;EA5BlB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