@zapier/policy-context 1.3.0-mr.6.c3a1f51e → 2.0.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.
package/dist/index.cjs CHANGED
@@ -44,6 +44,7 @@ __export(index_exports, {
44
44
  buildHttpRequestContext: () => buildHttpRequestContext,
45
45
  buildUrlString: () => buildUrlString,
46
46
  globSelectedApiVersion: () => globSelectedApiVersion,
47
+ isIgnoredHeader: () => isIgnoredHeader,
47
48
  isWriteRequest: () => isWriteRequest,
48
49
  parseActionResource: () => parseActionResource,
49
50
  parseUrl: () => parseUrl,
@@ -265,8 +266,15 @@ var IGNORED_HEADERS = /* @__PURE__ */ new Set([
265
266
  "x-real-ip",
266
267
  // Proxy internal — sdkapi-specific headers
267
268
  "x-is-interactive-session",
268
- "x-relay-callback-url"
269
+ "x-relay-callback-url",
270
+ // Subsumed by isIgnoredHeader's x-zapier- prefix rule; kept for byte-parity
271
+ // with the approvalsapi source and for consumers reading the set directly.
272
+ "x-zapier-approval-token"
269
273
  ]);
274
+ function isIgnoredHeader(name) {
275
+ const normalized = name.toLowerCase();
276
+ return IGNORED_HEADERS.has(normalized) || normalized.startsWith("zapier-") || normalized.startsWith("x-zapier-");
277
+ }
270
278
 
271
279
  // src/builders.ts
272
280
  var import_zod2 = require("zod");
@@ -306,7 +314,7 @@ function buildExactHttpConditions(context) {
306
314
  });
307
315
  }
308
316
  for (const [key, value] of Object.entries(context.headers)) {
309
- if (!IGNORED_HEADERS.has(key.toLowerCase()) && typeof value === "string") {
317
+ if (!isIgnoredHeader(key) && typeof value === "string") {
310
318
  conditions.push({
311
319
  path: ["headers", key.toLowerCase()],
312
320
  operator: "equals",
@@ -348,7 +356,7 @@ var BuildHttpRequestContextOptionsSchema = import_zod2.z.object({
348
356
  method: import_zod2.z.string(),
349
357
  /** Raw URL string. Will be normalized with https:// if no protocol present. */
350
358
  url: import_zod2.z.string(),
351
- /** Raw headers from the request. Will be filtered through IGNORED_HEADERS. */
359
+ /** Raw headers from the request. Will be filtered through isIgnoredHeader. */
352
360
  headers: import_zod2.z.record(
353
361
  import_zod2.z.string(),
354
362
  import_zod2.z.union([import_zod2.z.string(), import_zod2.z.array(import_zod2.z.string()), import_zod2.z.undefined()])
@@ -368,7 +376,7 @@ function buildHttpRequestContext(options) {
368
376
  if (parsed.headers) {
369
377
  for (const [key, value] of Object.entries(parsed.headers)) {
370
378
  const lowerKey = key.toLowerCase();
371
- if (!IGNORED_HEADERS.has(lowerKey) && typeof value === "string") {
379
+ if (!isIgnoredHeader(lowerKey) && typeof value === "string") {
372
380
  headers[lowerKey] = value;
373
381
  }
374
382
  }
@@ -391,7 +399,7 @@ function buildHttpRequestContext(options) {
391
399
  method: parsed.method.toUpperCase(),
392
400
  url,
393
401
  headers,
394
- body: parsed.body ?? null,
402
+ body: body_json === null ? parsed.body ?? null : null,
395
403
  body_json,
396
404
  connection_id: parsed.connection_id
397
405
  });
@@ -595,6 +603,7 @@ function buildConnectionlessPolicy(options) {
595
603
  buildHttpRequestContext,
596
604
  buildUrlString,
597
605
  globSelectedApiVersion,
606
+ isIgnoredHeader,
598
607
  isWriteRequest,
599
608
  parseActionResource,
600
609
  parseUrl,
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/types.ts","../src/constants.ts","../src/builders.ts","../src/conditions.ts","../src/policies.ts","../src/connection-policy.ts","../src/connectionless-policy.ts"],"sourcesContent":["// ABOUTME: Public API for @zapier/policy-context.\n// ABOUTME: Shared context types, builders, and condition generators for sdkapi + approvalsapi.\n\nexport {\n HttpRequestContextSchema,\n ActionRunContextSchema,\n ActionRunContextInputSchema,\n ActionTypeSchema,\n RequestContextSchema,\n ParsedUrlSchema,\n DEFAULT_PORTS,\n parseUrl,\n buildUrlString,\n parseActionResource,\n toAppKey,\n globSelectedApiVersion,\n type HttpRequestContext,\n type ActionRunContext,\n type ActionType,\n type RequestContext,\n type ParsedUrl,\n} from \"./types.ts\";\n\nexport { IGNORED_HEADERS } from \"./constants.ts\";\n\nexport {\n buildHttpRequestContext,\n buildActionRunContext,\n BuildHttpRequestContextOptionsSchema,\n BuildActionRunContextOptionsSchema,\n type BuildHttpRequestContextOptions,\n type BuildActionRunContextOptions,\n} from \"./builders.ts\";\n\nexport {\n buildExactHttpConditions,\n buildDomainHttpConditions,\n buildExactActionConditions,\n buildActionResource,\n buildBroadActionResource,\n} from \"./conditions.ts\";\n\nexport { toExactPolicy } from \"./policies.ts\";\n\nexport {\n buildConnectionPolicy,\n isWriteRequest,\n AccessLevelSchema,\n READ_ACTION_TYPES,\n READ_HTTP_METHODS,\n type AccessLevel,\n} from \"./connection-policy.ts\";\n\nexport { buildConnectionlessPolicy } from \"./connectionless-policy.ts\";\n","// ABOUTME: Canonical request context types shared between sdkapi and approvalsapi.\n// ABOUTME: These define the contract for how requests are described in approval flows and policy evaluation.\n\nimport { z } from \"zod\";\n\n/**\n * Parsed URL components for policy evaluation.\n * Matches the ParsedUrl shape from @zapier/policy-schema so that\n * evaluatePolicy condition paths like [\"url\", \"host\"] resolve correctly.\n */\nexport const ParsedUrlSchema = z\n .object({\n scheme: z.string().describe('URL scheme, e.g. \"https\"'),\n host: z.string().describe('Hostname, e.g. \"api.example.com\"'),\n port: z\n .number()\n .int()\n .describe(\"Port number (defaults to 443 for https, 80 for http)\"),\n path: z.string().describe('URL path, e.g. \"/v1/foo\"'),\n query: z\n .record(z.string(), z.array(z.string()))\n .describe(\"Query parameters as key to string array mapping\"),\n })\n .meta({\n id: \"ParsedUrl\",\n description: \"Parsed URL components for policy condition matching\",\n });\nexport type ParsedUrl = z.infer<typeof ParsedUrlSchema>;\n\n/** Default ports by scheme, used when URL has no explicit port. */\nexport const DEFAULT_PORTS: Record<string, number> = {\n http: 80,\n https: 443,\n};\n\n/**\n * Parse a raw URL string into a ParsedUrl.\n * Same logic as parseUrlForPolicyContext in @zapier/policy.\n */\nexport function parseUrl(raw: string): ParsedUrl {\n const url = new URL(raw);\n const scheme = url.protocol.slice(0, -1).toLowerCase();\n const host = url.hostname.toLowerCase();\n const port = url.port ? parseInt(url.port, 10) : (DEFAULT_PORTS[scheme] ?? 0);\n const path = url.pathname || \"/\";\n const query: Record<string, string[]> = {};\n for (const [key, value] of url.searchParams) {\n if (!query[key]) {\n query[key] = [];\n }\n query[key].push(value);\n }\n return { scheme, host, port, path, query };\n}\n\n/**\n * Reconstruct a URL string from a ParsedUrl.\n * Same logic as buildUrl in @zapier/policy.\n */\nexport function buildUrlString(parsed: ParsedUrl): string {\n const { scheme, host, port, path, query } = parsed;\n const defaultPort = DEFAULT_PORTS[scheme];\n const portString = port !== defaultPort ? `:${String(port)}` : \"\";\n const params = new URLSearchParams();\n for (const [key, values] of Object.entries(query)) {\n for (const value of values) {\n params.append(key, value);\n }\n }\n const queryString = params.toString();\n return `${scheme}://${host}${portString}${path}${queryString ? \"?\" + queryString : \"\"}`;\n}\n\n/**\n * HTTP request context for approval/policy flows.\n * Sent by sdkapi when a relay request is denied, stored by approvalsapi,\n * and used for both policy evaluation and building policy conditions.\n *\n * The url field is a ParsedUrl object (matching @zapier/policy-schema's ParsedUrl)\n * so that evaluatePolicy conditions like [\"url\", \"host\"] resolve correctly.\n */\nexport const HttpRequestContextSchema = z\n .object({\n request_type: z\n .literal(\"http_request\")\n .describe(\"Context type discriminator\"),\n method: z\n .string()\n .max(10)\n .transform((m) => m.toUpperCase())\n .describe(\"HTTP method\"),\n /** Parsed URL components for policy condition matching */\n url: ParsedUrlSchema,\n /** Filtered headers (IGNORED_HEADERS excluded, keys lowercased) */\n headers: z\n .record(z.string(), z.string())\n .describe(\"Filtered headers (IGNORED_HEADERS excluded, keys lowercased)\"),\n /** Raw body string */\n body: z.string().max(65536).nullable().describe(\"Raw body string\"),\n /**\n * Parsed JSON body. Authored as `z.unknown().pipe(z.json())` so\n * the OpenAPI generator sees the outer `z.unknown()` and emits a\n * permissive field (no recursive `$ref`, no type), while the inner\n * `z.json()` still rejects non-JSON values (`Date`, `undefined`,\n * functions) at parse time. Same inferred `JsonValue` type either way.\n */\n body_json: z\n .unknown()\n .pipe(z.json())\n .nullable()\n .describe(\"Parsed JSON body (if applicable)\"),\n /** Zapier connection ID used for this request */\n connection_id: z\n .string()\n .max(255)\n .optional()\n .describe(\"Zapier connection ID used for this request\"),\n /** Optional human-readable reason for the request */\n reason: z\n .string()\n .max(1024)\n .optional()\n .describe(\"Optional human-readable reason for the request\"),\n })\n .meta({ id: \"HttpRequestContext\" });\nexport type HttpRequestContext = z.infer<typeof HttpRequestContextSchema>;\n\n/**\n * Canonical Zapier action types.\n *\n * Mirrors the `action_type` enum in sdkapi's OpenAPI spec\n * (`packages/openapi-spec/openapi.d.ts` `action_type`). Single source of\n * truth for any code that branches on or filters by action_type — keeps\n * `ActionRunContextSchema`, `BuildActionRunContextOptionsSchema`, and the\n * `READ_ACTION_TYPES` allowlist in `connection-policy.ts` aligned.\n */\nexport const ActionTypeSchema = z\n .enum([\n \"filter\",\n \"read\",\n \"read_bulk\",\n \"run\",\n \"search\",\n \"search_and_write\",\n \"search_or_write\",\n \"write\",\n ])\n .meta({ id: \"action_type\", description: \"Canonical Zapier action type.\" });\nexport type ActionType = z.infer<typeof ActionTypeSchema>;\n\n/**\n * Allowed character set for the `selected_api` segment of an action\n * resource. Blocks `*`, `/`, `:`, whitespace, and other glob/path\n * metacharacters that would otherwise widen policy scope. Permits at\n * most one `@`, which `globSelectedApiVersion` treats as the\n * version separator.\n */\nexport const ACTION_RESOURCE_SEGMENT_PATTERN =\n /^[A-Za-z0-9._+-]+(?:@[A-Za-z0-9._+-]+)?$/;\n\n/**\n * Allowed character set for the `action_key` segment of an action\n * resource. More permissive than `ACTION_RESOURCE_SEGMENT_PATTERN`\n * because sdkapi emits keys like `ae:358405` and `core:123abc` that\n * carry a namespace prefix separated by `:`. Still blocks `*`, `/`,\n * whitespace, and other glob/path metacharacters.\n */\nexport const ACTION_KEY_SEGMENT_PATTERN =\n /^[A-Za-z0-9._+:-]+(?:@[A-Za-z0-9._+:-]+)?$/;\n\n/**\n * Parse an action resource string of the form\n * `action/{selected_api}/{action_type}/{action_key}` into its parts.\n * Throws if the string doesn't match the canonical 4-segment shape or\n * if its `action_type` segment isn't one of the canonical 8 — every\n * action_run context that has been through `ActionRunContextSchema` is\n * guaranteed to parse cleanly, so a thrown error here means upstream\n * validation was bypassed.\n */\nexport function parseActionResource(resource: string): {\n selected_api: string;\n action_type: ActionType;\n action_key: string;\n} {\n const segments = resource.split(\"/\");\n if (segments.length !== 4 || segments[0] !== \"action\") {\n throw new Error(\n `action resource must be action/{selected_api}/{action_type}/{action_key}: got ${resource}`,\n );\n }\n const [, selectedApi, actionTypeRaw, actionKey] = segments;\n if (!selectedApi || !actionTypeRaw || !actionKey) {\n throw new Error(`action resource has empty segment: ${resource}`);\n }\n const actionType = ActionTypeSchema.safeParse(actionTypeRaw);\n if (!actionType.success) {\n throw new Error(\n `action resource has unknown action_type \"${actionTypeRaw}\": ${resource}`,\n );\n }\n if (!ACTION_RESOURCE_SEGMENT_PATTERN.test(selectedApi)) {\n throw new Error(\n `action resource has invalid selected_api segment \"${selectedApi}\": ${resource}`,\n );\n }\n if (!ACTION_KEY_SEGMENT_PATTERN.test(actionKey)) {\n throw new Error(\n `action resource has invalid action_key segment \"${actionKey}\": ${resource}`,\n );\n }\n return {\n selected_api: selectedApi,\n action_type: actionType.data,\n action_key: actionKey,\n };\n}\n\n/**\n * Strip the `@<version>` suffix from a `selected_api` / implementation\n * identifier. `Slack@1.0.0` → `Slack`. Passing a value without `@` is a\n * no-op. Used by UIs to render a human-friendly app key independent of\n * version, and by `globSelectedApiVersion` below.\n */\nexport function toAppKey(selectedApi: string): string {\n const at = selectedApi.indexOf(\"@\");\n return at === -1 ? selectedApi : selectedApi.slice(0, at);\n}\n\n/**\n * Replace the implementation-version suffix of a `selected_api` with a `@*`\n * wildcard so policies stay valid across version bumps. A runtime request\n * with `selected_api: \"App@2.7.3\"` matches a policy resource scoped to\n * `App@*` while still being distinguishable from a different app\n * (e.g. `App2@1.0.0`).\n *\n * No-op when the input has no `@` — assumed to be already version-less.\n */\nexport function globSelectedApiVersion(selectedApi: string): string {\n const at = selectedApi.indexOf(\"@\");\n return at === -1 ? selectedApi : selectedApi.slice(0, at) + \"@*\";\n}\n\n/**\n * Raw input shape for `ActionRunContextSchema`, before the transform that\n * canonicalizes legacy fields into `resource`. Exposed for the OpenAPI\n * schema generator (which can't represent transforms) — runtime callers\n * should use `ActionRunContextSchema`, which accepts either the canonical\n * `resource` field or the legacy `{selected_api, action_type, action_key}`\n * triple on input.\n */\nexport const ActionRunContextInputSchema = z\n .object({\n request_type: z\n .literal(\"action_run\")\n .describe(\"Context type discriminator\"),\n resource: z\n .string()\n .max(1024)\n .optional()\n .describe(\n \"Canonical action resource, e.g. action/Slack@1.0.0/write/send_message\",\n ),\n selected_api: z.string().max(255).optional().meta({\n deprecated: true,\n description:\n \"Legacy: app identifier, e.g. Slack@1.0.0. Prefer `resource`.\",\n }),\n action_type: ActionTypeSchema.optional().meta({\n deprecated: true,\n description: \"Legacy: canonical Zapier action type. Prefer `resource`.\",\n }),\n action_key: z.string().max(255).optional().meta({\n deprecated: true,\n description: \"Legacy: action key, e.g. send_message. Prefer `resource`.\",\n }),\n connection_id: z\n .string()\n .max(255)\n .optional()\n .describe(\"Zapier connection ID used for this request\"),\n /** Action input parameters. See body_json above for the pipe rationale. */\n inputs: z\n .unknown()\n .pipe(z.json())\n .optional()\n .describe(\"Action input parameters\"),\n reason: z\n .string()\n .max(1024)\n .optional()\n .describe(\"Optional human-readable reason for the request\"),\n })\n .meta({\n id: \"ActionRunContext\",\n description:\n \"Action run context. The canonical shape carries the action identity in a single `resource` field of the form `action/{selected_api}/{action_type}/{action_key}`. The legacy `{selected_api, action_type, action_key}` shape is also accepted on input during the migration window — approvalsapi normalizes it to the canonical form before storage.\",\n });\n\nexport const ActionRunContextSchema = ActionRunContextInputSchema.transform(\n (input, ctx) => {\n const resource =\n input.resource ??\n (input.selected_api && input.action_type && input.action_key\n ? `action/${input.selected_api}/${input.action_type}/${input.action_key}`\n : undefined);\n if (resource === undefined) {\n ctx.addIssue({\n code: \"custom\",\n message:\n \"action_run context requires either `resource` or all of `selected_api`/`action_type`/`action_key`\",\n });\n return z.NEVER;\n }\n try {\n parseActionResource(resource);\n } catch (err) {\n ctx.addIssue({\n code: \"custom\",\n message: err instanceof Error ? err.message : String(err),\n });\n return z.NEVER;\n }\n return {\n request_type: \"action_run\" as const,\n resource,\n ...(input.connection_id !== undefined && {\n connection_id: input.connection_id,\n }),\n ...(input.inputs !== undefined && { inputs: input.inputs }),\n ...(input.reason !== undefined && { reason: input.reason }),\n };\n },\n);\nexport type ActionRunContext = z.infer<typeof ActionRunContextSchema>;\n\n/**\n * Union of all request context types, keyed on `request_type`.\n *\n * Plain `z.union` (not `z.discriminatedUnion`) because\n * `ActionRunContextSchema` carries a `.transform` and discriminated\n * unions can't accept a `ZodEffects` member. The `request_type`\n * discriminator carried in `.meta()` below is read natively by the\n * OpenAPI generator (`@zapier/openapi-spec`), which emits it as\n * `anyOf` + discriminator that openapi-typescript and other codegen\n * targets render as a properly narrowed TS union.\n */\nexport const RequestContextSchema = z\n .union([HttpRequestContextSchema, ActionRunContextSchema])\n .meta({\n id: \"RequestContext\",\n description: \"Union of request context shapes, keyed on `request_type`.\",\n discriminator: {\n propertyName: \"request_type\",\n mapping: {\n http_request: \"#/components/schemas/HttpRequestContext\",\n action_run: \"#/components/schemas/ActionRunContext\",\n },\n },\n });\nexport type RequestContext = z.infer<typeof RequestContextSchema>;\n","// ABOUTME: Canonical set of headers to exclude when building request contexts.\n// ABOUTME: Shared between sdkapi (context creation) and approvalsapi (condition building).\n\n/**\n * Headers to exclude when building request contexts from raw HTTP requests.\n *\n * These are either sensitive (auth credentials), HTTP infrastructure headers\n * that vary per-request, or proxy-internal headers that are not meaningful\n * for policy decisions.\n */\nexport const IGNORED_HEADERS = new Set([\n // Auth / credentials — never include in contexts or policy conditions\n \"authorization\",\n \"x-relay-authorization\",\n \"x-relay-authentication-id\",\n \"x-api-key\",\n \"cookie\",\n \"set-cookie\",\n \"proxy-authorization\",\n\n // HTTP infrastructure — varies per-request, not policy-relevant\n \"host\",\n \"connection\",\n \"content-length\",\n \"transfer-encoding\",\n \"accept-encoding\",\n \"user-agent\",\n \"accept\",\n \"accept-language\",\n \"sec-fetch-mode\",\n\n // Proxy / forwarding — infrastructure, not meaningful for policy\n \"x-forwarded-for\",\n \"x-forwarded-host\",\n \"x-forwarded-proto\",\n \"x-real-ip\",\n\n // Proxy internal — sdkapi-specific headers\n \"x-is-interactive-session\",\n \"x-relay-callback-url\",\n]);\n","// ABOUTME: Canonical builders for creating request contexts from raw request parts.\n// ABOUTME: Used by sdkapi to build both approval contexts and policy eval contexts.\n\nimport { z } from \"zod\";\nimport {\n HttpRequestContextSchema,\n ActionRunContextSchema,\n ActionTypeSchema,\n parseUrl,\n ACTION_RESOURCE_SEGMENT_PATTERN,\n ACTION_KEY_SEGMENT_PATTERN,\n type HttpRequestContext,\n type ActionRunContext,\n} from \"./types.ts\";\nimport { buildActionResource } from \"./conditions.ts\";\nimport { IGNORED_HEADERS } from \"./constants.ts\";\n\nexport const BuildHttpRequestContextOptionsSchema = z.object({\n method: z.string(),\n /** Raw URL string. Will be normalized with https:// if no protocol present. */\n url: z.string(),\n /** Raw headers from the request. Will be filtered through IGNORED_HEADERS. */\n headers: z\n .record(\n z.string(),\n z.union([z.string(), z.array(z.string()), z.undefined()]),\n )\n .optional(),\n /** Raw body string */\n body: z.string().nullable().optional(),\n /** Pre-parsed JSON body (e.g. from Fastify's automatic JSON parsing) */\n body_json: z.json().optional(),\n /** Connection ID associated with this request */\n connection_id: z.string().optional(),\n});\nexport type BuildHttpRequestContextOptions = z.infer<\n typeof BuildHttpRequestContextOptionsSchema\n>;\n\n/**\n * Build a canonical HttpRequestContext from raw request parts.\n *\n * This is the single source of truth for how HTTP request contexts are created.\n * Both sdkapi (for policy evaluation) and approvalsapi (for context storage)\n * should use this to ensure the context shape is consistent.\n *\n * Matches the behavior of createPolicyHttpRequest from @zapier/policy, with\n * the addition of header filtering through IGNORED_HEADERS.\n *\n * - Normalizes URL (adds https:// if missing) and parses into { scheme, host, port, path, query }\n * - Filters headers through IGNORED_HEADERS, lowercases keys, string values only\n * - Auto-parses body_json from body when content-type is JSON and body_json not provided\n * - body defaults to null (not undefined)\n */\nexport function buildHttpRequestContext(\n options: BuildHttpRequestContextOptions,\n): HttpRequestContext {\n // Validate options up-front so downstream string ops (e.g. method.toUpperCase)\n // see well-typed values. Mirrors the pattern in buildActionRunContext.\n const parsed = BuildHttpRequestContextOptionsSchema.parse(options);\n\n // Normalize URL — SDK CLI strips the protocol\n const rawUrl = parsed.url.includes(\"://\")\n ? parsed.url\n : `https://${parsed.url}`;\n const url = parseUrl(rawUrl);\n\n // Filter headers: exclude ignored, lowercase keys, string values only\n const headers: Record<string, string> = {};\n if (parsed.headers) {\n for (const [key, value] of Object.entries(parsed.headers)) {\n const lowerKey = key.toLowerCase();\n if (!IGNORED_HEADERS.has(lowerKey) && typeof value === \"string\") {\n headers[lowerKey] = value;\n }\n }\n }\n\n // Auto-parse body_json from body when content-type is JSON\n // (matches createPolicyHttpRequest behavior from @zapier/policy)\n let body_json: unknown = null;\n if (parsed.body_json !== undefined) {\n body_json = parsed.body_json;\n } else if (parsed.body) {\n const contentType = headers[\"content-type\"];\n const isJson =\n typeof contentType === \"string\" &&\n (contentType.includes(\"application/json\") ||\n (contentType.includes(\"application/\") &&\n contentType.includes(\"+json\")));\n if (isJson) {\n try {\n body_json = JSON.parse(parsed.body);\n } catch {\n // Invalid JSON body — leave body_json as null\n }\n }\n }\n\n return HttpRequestContextSchema.parse({\n request_type: \"http_request\",\n method: parsed.method.toUpperCase(),\n url,\n headers,\n body: parsed.body ?? null,\n body_json,\n connection_id: parsed.connection_id,\n });\n}\n\nexport const BuildActionRunContextOptionsSchema = z.object({\n selected_api: z.string().regex(ACTION_RESOURCE_SEGMENT_PATTERN, {\n message:\n \"selected_api must contain only [A-Za-z0-9._@+-] (no globs, slashes, or whitespace)\",\n }),\n action_type: ActionTypeSchema,\n action_key: z.string().regex(ACTION_KEY_SEGMENT_PATTERN, {\n message:\n \"action_key must contain only [A-Za-z0-9._@:+-] (no globs, slashes, or whitespace)\",\n }),\n connection_id: z.string().optional(),\n inputs: z.json().optional(),\n reason: z.string().optional(),\n});\nexport type BuildActionRunContextOptions = z.infer<\n typeof BuildActionRunContextOptionsSchema\n>;\n\n/**\n * Build a canonical ActionRunContext from raw action parts.\n *\n * Callers pass the three identity fields separately for readability;\n * this validates them and collapses them into the canonical `resource`\n * string the schema stores.\n */\nexport function buildActionRunContext(\n options: BuildActionRunContextOptions,\n): ActionRunContext {\n const parsed = BuildActionRunContextOptionsSchema.parse(options);\n return ActionRunContextSchema.parse({\n request_type: \"action_run\",\n resource: buildActionResource({\n selected_api: parsed.selected_api,\n action_type: parsed.action_type,\n action_key: parsed.action_key,\n }),\n connection_id: parsed.connection_id,\n inputs: parsed.inputs,\n reason: parsed.reason,\n });\n}\n","// ABOUTME: Builds policy conditions from stored request contexts.\n// ABOUTME: Used by approvalsapi's \"allow exact request\" and \"allow domain\" instant policy flows.\n\nimport type { Condition } from \"@zapier/policy-schema\";\nimport type {\n HttpRequestContext,\n ActionRunContext,\n ActionType,\n} from \"./types.ts\";\nimport { IGNORED_HEADERS } from \"./constants.ts\";\n\n/**\n * Build conditions that match an exact HTTP request.\n *\n * Handles the matches_url / query param split correctly:\n * - `matches_url` only supports scheme+host+port+path (no query string per spec)\n * - Query parameters are added as separate decomposed conditions on `url.query.<key>`\n *\n * @returns Condition[] for an http permission statement\n */\nexport function buildExactHttpConditions(\n context: HttpRequestContext,\n): Condition[] {\n const conditions: Condition[] = [\n { path: [\"method\"], operator: \"equals\", value: context.method },\n ];\n\n const { url } = context;\n\n // matches_url condition uses URL without query string (per @zapier/policy spec)\n const defaultPort =\n url.scheme === \"https\" ? 443 : url.scheme === \"http\" ? 80 : 0;\n const portString = url.port !== defaultPort ? `:${String(url.port)}` : \"\";\n const urlWithoutQuery = `${url.scheme}://${url.host}${portString}${url.path}`;\n conditions.push({\n path: [\"url\"],\n operator: \"matches_url\",\n value: urlWithoutQuery,\n });\n\n // Add decomposed conditions for each query parameter.\n for (const [key, values] of Object.entries(url.query)) {\n conditions.push({\n path: [\"url\", \"query\", key],\n operator: \"equals\",\n value: values,\n });\n }\n\n // body_json condition\n if (context.body_json !== null) {\n conditions.push({\n path: [\"body_json\"],\n operator: \"equals\",\n value: context.body_json,\n });\n } else if (context.body !== null) {\n // Non-JSON body (text/plain, XML, form-encoded): pin the raw body so\n // exact-match policies actually match the originating request.\n conditions.push({\n path: [\"body\"],\n operator: \"equals\",\n value: context.body,\n });\n }\n\n // Header conditions (filtered through IGNORED_HEADERS again for safety)\n for (const [key, value] of Object.entries(context.headers)) {\n if (!IGNORED_HEADERS.has(key.toLowerCase()) && typeof value === \"string\") {\n conditions.push({\n path: [\"headers\", key.toLowerCase()],\n operator: \"equals\",\n value,\n });\n }\n }\n\n return conditions;\n}\n\n/**\n * Build conditions that match any request to a given domain.\n * Uses the host from the parsed URL.\n *\n * @returns Condition[] for an http permission statement\n */\nexport function buildDomainHttpConditions(\n context: HttpRequestContext,\n): Condition[] {\n return [\n {\n path: [\"url\", \"host\"],\n operator: \"matches_host\",\n value: context.url.host,\n },\n ];\n}\n\n/**\n * Build conditions that match an exact action run (with inputs).\n *\n * @returns Condition[] for an action permission statement\n */\nexport function buildExactActionConditions(\n context: ActionRunContext,\n): Condition[] {\n const conditions: Condition[] = [];\n\n if (context.inputs !== undefined && context.inputs !== null) {\n conditions.push({\n path: [\"inputs\"],\n operator: \"equals\",\n value: context.inputs,\n });\n }\n\n return conditions;\n}\n\n/**\n * The three identity fields that compose an action resource string.\n */\nexport interface ActionResourceParts {\n selected_api: string;\n action_type: ActionType;\n action_key: string;\n}\n\n/**\n * Build the resource string for an action.\n * Format: action/{selected_api}/{action_type}/{action_key}\n */\nexport function buildActionResource(parts: ActionResourceParts): string {\n return `action/${parts.selected_api}/${parts.action_type}/${parts.action_key}`;\n}\n\n/**\n * Build a broad action resource that matches all actions of the same type\n * for an app (e.g. all reads, all writes). Scopes on `action_type` to\n * avoid silently granting cross-type access.\n *\n * Format: action/{selected_api}/{action_type}/{wildcard}\n */\nexport function buildBroadActionResource(\n parts: Pick<ActionResourceParts, \"selected_api\" | \"action_type\">,\n): string {\n return `action/${parts.selected_api}/${parts.action_type}/*`;\n}\n","// ABOUTME: Assembles complete Policy objects from request contexts.\n// ABOUTME: Single source of truth for \"exact request\" instant policies used by web UI and API.\n\nimport type { Policy, Statement } from \"@zapier/policy-schema\";\nimport type {\n RequestContext,\n HttpRequestContext,\n ActionRunContext,\n} from \"./types.ts\";\nimport {\n buildExactHttpConditions,\n buildExactActionConditions,\n} from \"./conditions.ts\";\n\n/**\n * Build a `can_use` authentication statement, if the context has a connection_id.\n */\nfunction buildAuthStatement(authenticationId: string): Statement {\n return {\n effect: \"allow\",\n permissions: [\"can_use\"],\n resources: [`connection/${authenticationId}`],\n conditions: [],\n };\n}\n\n/**\n * Build an exact-match policy from an HTTP request context.\n *\n * Produces a policy that allows only the specific request described by the context:\n * - `can_use` statement for the authentication (if present)\n * - `can_execute` statement for `http` with conditions from `buildExactHttpConditions`\n * plus a `keys_in` guard restricting allowed query parameter keys\n */\nfunction httpContextToPolicy(context: HttpRequestContext): Policy {\n const statements: Statement[] = [];\n\n if (context.connection_id) {\n statements.push(buildAuthStatement(context.connection_id));\n }\n\n const conditions = buildExactHttpConditions(context);\n\n // Add a keys_in guard so only the query param keys present in the original\n // request are allowed — blocks injection of extra query params.\n conditions.push({\n path: [\"url\", \"query\"],\n operator: \"keys_in\",\n value: Object.keys(context.url.query),\n });\n\n statements.push({\n effect: \"allow\",\n permissions: [\"can_execute\"],\n resources: [\"http\"],\n conditions,\n });\n\n return { version: 2, statements };\n}\n\n/**\n * Build an exact-match policy from an action run context.\n *\n * Produces a policy that allows only the specific action described by the context:\n * - `can_use` statement for the authentication (if present)\n * - `can_execute` statement for the action resource with input conditions\n */\nfunction actionContextToPolicy(context: ActionRunContext): Policy {\n const statements: Statement[] = [];\n\n if (context.connection_id) {\n statements.push(buildAuthStatement(context.connection_id));\n }\n\n statements.push({\n effect: \"allow\",\n permissions: [\"can_execute\"],\n resources: [context.resource],\n conditions: buildExactActionConditions(context),\n });\n\n return { version: 2, statements };\n}\n\n/**\n * Build an exact-match policy from any supported request context.\n *\n * This is the single source of truth for \"allow this exact request\" instant policies.\n * Used by the web UI and anywhere else that needs to produce an exact policy from a context.\n */\nexport function toExactPolicy(context: RequestContext): Policy {\n if (context.request_type === \"http_request\") {\n return httpContextToPolicy(context);\n }\n return actionContextToPolicy(context);\n}\n","// ABOUTME: Builds connection-level policies for the basic approvals MVP.\n// ABOUTME: Generates deterministic policies that allow read or read+write access scoped to a specific connection.\n\nimport { z } from \"zod\";\nimport type { Policy, Statement, Condition } from \"@zapier/policy-schema\";\nimport {\n globSelectedApiVersion,\n parseActionResource,\n type ActionType,\n type RequestContext,\n} from \"./types.ts\";\n\nexport const AccessLevelSchema = z.enum([\"read\", \"read_write\"]);\nexport type AccessLevel = z.infer<typeof AccessLevelSchema>;\n\n/** HTTP methods that count as side-effect-free reads for connection-level policies. */\nexport const READ_HTTP_METHODS = [\"GET\", \"HEAD\", \"OPTIONS\"] as const;\n\n/**\n * Action types that count as side-effect-free reads for connection-level\n * policies. `read_bulk` is the paginated/bulk variant of `read` — same\n * external API semantics, no mutations. Widely used by major apps (Slack,\n * Gmail, Jira, Salesforce, etc.) via the public `bulkReads` schema key.\n * `filter` and `run` are excluded: neither has a runtime executor for\n * external apps, and `filter` actions don't carry a connection_id anyway,\n * so this allowlist has no effect on them.\n */\nexport const READ_ACTION_TYPES = [\n \"read\",\n \"read_bulk\",\n \"search\",\n] as const satisfies readonly ActionType[];\n\nconst READ_HTTP_METHOD_SET: ReadonlySet<string> = new Set(READ_HTTP_METHODS);\nconst READ_ACTION_TYPE_SET: ReadonlySet<ActionType> = new Set(\n READ_ACTION_TYPES,\n);\n\n/**\n * Returns true when the request needs write access (i.e. it is NOT a\n * side-effect-free read). Mirrors the logic encoded in `buildConnectionPolicy`\n * so UI surfaces that gate the read-vs-read_write choice stay consistent\n * with the policies they generate.\n */\nexport function isWriteRequest(context: RequestContext): boolean {\n if (context.request_type === \"http_request\") {\n // Method is uppercase by construction (buildHttpRequestContext canonicalizes\n // it on the way in), so no normalization is needed here.\n return !READ_HTTP_METHOD_SET.has(context.method);\n }\n const { action_type } = parseActionResource(context.resource);\n return !READ_ACTION_TYPE_SET.has(action_type);\n}\n\n/**\n * Build a connection-level policy that covers both HTTP and action access.\n *\n * Always produces three statements:\n * 1. `can_use` for the authentication\n * 2. `can_execute` on `http` scoped by connection_id (+ method filter for read)\n * 3. `can_execute` on `action/{selectedApi}/{action_type}/*` per allowed type,\n * scoped by connection_id. For read access, the resource list expands to\n * one entry per read action_type so the engine matches via the resource\n * string rather than a separate `path: [\"action_type\"]` condition.\n */\nexport function buildConnectionPolicy(options: {\n connectionId: string;\n selectedApi: string;\n accessLevel: AccessLevel;\n}): Policy {\n const { connectionId, selectedApi, accessLevel } = options;\n\n const authStatement: Statement = {\n effect: \"allow\",\n permissions: [\"can_use\"],\n resources: [`connection/${connectionId}`],\n conditions: [],\n };\n\n const connectionCondition: Condition = {\n path: [\"connection_id\"],\n operator: \"equals\",\n value: connectionId,\n };\n\n const httpConditions: Condition[] = [connectionCondition];\n if (accessLevel === \"read\") {\n httpConditions.push({\n path: [\"method\"],\n operator: \"in\",\n value: [...READ_HTTP_METHODS],\n });\n }\n\n const httpStatement: Statement = {\n effect: \"allow\",\n permissions: [\"can_execute\"],\n resources: [\"http\"],\n conditions: httpConditions,\n };\n\n const apiPattern = globSelectedApiVersion(selectedApi);\n const actionResources =\n accessLevel === \"read\"\n ? READ_ACTION_TYPES.map((t) => `action/${apiPattern}/${t}/*`)\n : [`action/${apiPattern}/*/*`];\n\n const actionStatement: Statement = {\n effect: \"allow\",\n permissions: [\"can_execute\"],\n resources: actionResources,\n conditions: [connectionCondition],\n };\n\n return {\n version: 2,\n statements: [authStatement, httpStatement, actionStatement],\n };\n}\n","// ABOUTME: Builds connectionless approval policies bound to a domain (HTTP) or an action (action_run).\n// ABOUTME: Used when the smart-policy flag is off and the request has no connection_id.\n\nimport type { Policy, Statement, Condition } from \"@zapier/policy-schema\";\nimport {\n globSelectedApiVersion,\n parseActionResource,\n type RequestContext,\n} from \"./types.ts\";\nimport {\n READ_ACTION_TYPES,\n READ_HTTP_METHODS,\n type AccessLevel,\n} from \"./connection-policy.ts\";\n\n/**\n * Build a connectionless policy that scopes access to the request's domain\n * (HTTP) or its app (action_run). Mirrors the read/write semantics of\n * `buildConnectionPolicy` minus the auth statement and `connection_id`\n * condition, since there is no connection to bind to.\n */\nexport function buildConnectionlessPolicy(options: {\n context: RequestContext;\n accessLevel: AccessLevel;\n}): Policy {\n const { context, accessLevel } = options;\n\n if (context.request_type === \"http_request\") {\n const conditions: Condition[] = [\n {\n path: [\"url\", \"host\"],\n operator: \"matches_host\",\n value: context.url.host,\n },\n ];\n if (accessLevel === \"read\") {\n conditions.push({\n path: [\"method\"],\n operator: \"in\",\n value: [...READ_HTTP_METHODS],\n });\n }\n\n const statement: Statement = {\n effect: \"allow\",\n permissions: [\"can_execute\"],\n resources: [\"http\"],\n conditions,\n };\n return { version: 2, statements: [statement] };\n }\n\n const { selected_api } = parseActionResource(context.resource);\n const apiPattern = globSelectedApiVersion(selected_api);\n const resources =\n accessLevel === \"read\"\n ? READ_ACTION_TYPES.map((t) => `action/${apiPattern}/${t}/*`)\n : [`action/${apiPattern}/*/*`];\n\n const statement: Statement = {\n effect: \"allow\",\n permissions: [\"can_execute\"],\n resources,\n conditions: [],\n };\n return { version: 2, statements: [statement] };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;A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AAA,EAClC;AAEA,SAAO;AAAA,IACL,SAAS;AAAA,IACT,YAAY,CAAC,eAAe,eAAe,eAAe;AAAA,EAC5D;AACF;;;ACjGO,SAAS,0BAA0B,SAG/B;AACT,QAAM,EAAE,SAAS,YAAY,IAAI;AAEjC,MAAI,QAAQ,iBAAiB,gBAAgB;AAC3C,UAAM,aAA0B;AAAA,MAC9B;AAAA,QACE,MAAM,CAAC,OAAO,MAAM;AAAA,QACpB,UAAU;AAAA,QACV,OAAO,QAAQ,IAAI;AAAA,MACrB;AAAA,IACF;AACA,QAAI,gBAAgB,QAAQ;AAC1B,iBAAW,KAAK;AAAA,QACd,MAAM,CAAC,QAAQ;AAAA,QACf,UAAU;AAAA,QACV,OAAO,CAAC,GAAG,iBAAiB;AAAA,MAC9B,CAAC;AAAA,IACH;AAEA,UAAMC,aAAuB;AAAA,MAC3B,QAAQ;AAAA,MACR,aAAa,CAAC,aAAa;AAAA,MAC3B,WAAW,CAAC,MAAM;AAAA,MAClB;AAAA,IACF;AACA,WAAO,EAAE,SAAS,GAAG,YAAY,CAACA,UAAS,EAAE;AAAA,EAC/C;AAEA,QAAM,EAAE,aAAa,IAAI,oBAAoB,QAAQ,QAAQ;AAC7D,QAAM,aAAa,uBAAuB,YAAY;AACtD,QAAM,YACJ,gBAAgB,SACZ,kBAAkB,IAAI,CAAC,MAAM,UAAU,UAAU,IAAI,CAAC,IAAI,IAC1D,CAAC,UAAU,UAAU,MAAM;AAEjC,QAAM,YAAuB;AAAA,IAC3B,QAAQ;AAAA,IACR,aAAa,CAAC,aAAa;AAAA,IAC3B;AAAA,IACA,YAAY,CAAC;AAAA,EACf;AACA,SAAO,EAAE,SAAS,GAAG,YAAY,CAAC,SAAS,EAAE;AAC/C;","names":["import_zod","import_zod","statement"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/types.ts","../src/constants.ts","../src/builders.ts","../src/conditions.ts","../src/policies.ts","../src/connection-policy.ts","../src/connectionless-policy.ts"],"sourcesContent":["// ABOUTME: Public API for @zapier/policy-context.\n// ABOUTME: Shared context types, builders, and condition generators for sdkapi + approvalsapi.\n\nexport {\n HttpRequestContextSchema,\n ActionRunContextSchema,\n ActionRunContextInputSchema,\n ActionTypeSchema,\n RequestContextSchema,\n ParsedUrlSchema,\n DEFAULT_PORTS,\n parseUrl,\n buildUrlString,\n parseActionResource,\n toAppKey,\n globSelectedApiVersion,\n type HttpRequestContext,\n type ActionRunContext,\n type ActionType,\n type RequestContext,\n type ParsedUrl,\n} from \"./types.ts\";\n\nexport { IGNORED_HEADERS, isIgnoredHeader } from \"./constants.ts\";\n\nexport {\n buildHttpRequestContext,\n buildActionRunContext,\n BuildHttpRequestContextOptionsSchema,\n BuildActionRunContextOptionsSchema,\n type BuildHttpRequestContextOptions,\n type BuildActionRunContextOptions,\n} from \"./builders.ts\";\n\nexport {\n buildExactHttpConditions,\n buildDomainHttpConditions,\n buildExactActionConditions,\n buildActionResource,\n buildBroadActionResource,\n} from \"./conditions.ts\";\n\nexport { toExactPolicy } from \"./policies.ts\";\n\nexport {\n buildConnectionPolicy,\n isWriteRequest,\n AccessLevelSchema,\n READ_ACTION_TYPES,\n READ_HTTP_METHODS,\n type AccessLevel,\n} from \"./connection-policy.ts\";\n\nexport { buildConnectionlessPolicy } from \"./connectionless-policy.ts\";\n","// ABOUTME: Canonical request context types shared between sdkapi and approvalsapi.\n// ABOUTME: These define the contract for how requests are described in approval flows and policy evaluation.\n\nimport { z } from \"zod\";\n\n/**\n * Parsed URL components for policy evaluation.\n * Matches the ParsedUrl shape from @zapier/policy-schema so that\n * evaluatePolicy condition paths like [\"url\", \"host\"] resolve correctly.\n */\nexport const ParsedUrlSchema = z\n .object({\n scheme: z.string().describe('URL scheme, e.g. \"https\"'),\n host: z.string().describe('Hostname, e.g. \"api.example.com\"'),\n port: z\n .number()\n .int()\n .describe(\"Port number (defaults to 443 for https, 80 for http)\"),\n path: z.string().describe('URL path, e.g. \"/v1/foo\"'),\n query: z\n .record(z.string(), z.array(z.string()))\n .describe(\"Query parameters as key to string array mapping\"),\n })\n .meta({\n id: \"ParsedUrl\",\n description: \"Parsed URL components for policy condition matching\",\n });\nexport type ParsedUrl = z.infer<typeof ParsedUrlSchema>;\n\n/** Default ports by scheme, used when URL has no explicit port. */\nexport const DEFAULT_PORTS: Record<string, number> = {\n http: 80,\n https: 443,\n};\n\n/**\n * Parse a raw URL string into a ParsedUrl.\n * Same logic as parseUrlForPolicyContext in @zapier/policy.\n */\nexport function parseUrl(raw: string): ParsedUrl {\n const url = new URL(raw);\n const scheme = url.protocol.slice(0, -1).toLowerCase();\n const host = url.hostname.toLowerCase();\n const port = url.port ? parseInt(url.port, 10) : (DEFAULT_PORTS[scheme] ?? 0);\n const path = url.pathname || \"/\";\n const query: Record<string, string[]> = {};\n for (const [key, value] of url.searchParams) {\n if (!query[key]) {\n query[key] = [];\n }\n query[key].push(value);\n }\n return { scheme, host, port, path, query };\n}\n\n/**\n * Reconstruct a URL string from a ParsedUrl.\n * Same logic as buildUrl in @zapier/policy.\n */\nexport function buildUrlString(parsed: ParsedUrl): string {\n const { scheme, host, port, path, query } = parsed;\n const defaultPort = DEFAULT_PORTS[scheme];\n const portString = port !== defaultPort ? `:${String(port)}` : \"\";\n const params = new URLSearchParams();\n for (const [key, values] of Object.entries(query)) {\n for (const value of values) {\n params.append(key, value);\n }\n }\n const queryString = params.toString();\n return `${scheme}://${host}${portString}${path}${queryString ? \"?\" + queryString : \"\"}`;\n}\n\n/**\n * HTTP request context for approval/policy flows.\n * Sent by sdkapi when a relay request is denied, stored by approvalsapi,\n * and used for both policy evaluation and building policy conditions.\n *\n * The url field is a ParsedUrl object (matching @zapier/policy-schema's ParsedUrl)\n * so that evaluatePolicy conditions like [\"url\", \"host\"] resolve correctly.\n */\nexport const HttpRequestContextSchema = z\n .object({\n request_type: z\n .literal(\"http_request\")\n .describe(\"Context type discriminator\"),\n method: z\n .string()\n .max(10)\n .transform((m) => m.toUpperCase())\n .describe(\"HTTP method\"),\n /** Parsed URL components for policy condition matching */\n url: ParsedUrlSchema,\n /** Filtered headers (IGNORED_HEADERS excluded, keys lowercased) */\n headers: z\n .record(z.string(), z.string())\n .describe(\"Filtered headers (IGNORED_HEADERS excluded, keys lowercased)\"),\n /** Raw body string */\n body: z.string().max(65536).nullable().describe(\"Raw body string\"),\n /**\n * Parsed JSON body. Authored as `z.unknown().pipe(z.json())` so\n * the OpenAPI generator sees the outer `z.unknown()` and emits a\n * permissive field (no recursive `$ref`, no type), while the inner\n * `z.json()` still rejects non-JSON values (`Date`, `undefined`,\n * functions) at parse time. Same inferred `JsonValue` type either way.\n */\n body_json: z\n .unknown()\n .pipe(z.json())\n .nullable()\n .describe(\"Parsed JSON body (if applicable)\"),\n /** Zapier connection ID used for this request */\n connection_id: z\n .string()\n .max(255)\n .optional()\n .describe(\"Zapier connection ID used for this request\"),\n /** Optional human-readable reason for the request */\n reason: z\n .string()\n .max(1024)\n .optional()\n .describe(\"Optional human-readable reason for the request\"),\n })\n .meta({ id: \"HttpRequestContext\" });\nexport type HttpRequestContext = z.infer<typeof HttpRequestContextSchema>;\n\n/**\n * Canonical Zapier action types.\n *\n * Mirrors the `action_type` enum in sdkapi's OpenAPI spec\n * (`packages/openapi-spec/openapi.d.ts` `action_type`). Single source of\n * truth for any code that branches on or filters by action_type — keeps\n * `ActionRunContextSchema`, `BuildActionRunContextOptionsSchema`, and the\n * `READ_ACTION_TYPES` allowlist in `connection-policy.ts` aligned.\n */\nexport const ActionTypeSchema = z\n .enum([\n \"filter\",\n \"read\",\n \"read_bulk\",\n \"run\",\n \"search\",\n \"search_and_write\",\n \"search_or_write\",\n \"write\",\n ])\n .meta({ id: \"action_type\", description: \"Canonical Zapier action type.\" });\nexport type ActionType = z.infer<typeof ActionTypeSchema>;\n\n/**\n * Allowed character set for the `selected_api` segment of an action\n * resource. Blocks `*`, `/`, `:`, whitespace, and other glob/path\n * metacharacters that would otherwise widen policy scope. Permits at\n * most one `@`, which `globSelectedApiVersion` treats as the\n * version separator.\n */\nexport const ACTION_RESOURCE_SEGMENT_PATTERN =\n /^[A-Za-z0-9._+-]+(?:@[A-Za-z0-9._+-]+)?$/;\n\n/**\n * Allowed character set for the `action_key` segment of an action\n * resource. More permissive than `ACTION_RESOURCE_SEGMENT_PATTERN`\n * because sdkapi emits keys like `ae:358405` and `core:123abc` that\n * carry a namespace prefix separated by `:`. Still blocks `*`, `/`,\n * whitespace, and other glob/path metacharacters.\n */\nexport const ACTION_KEY_SEGMENT_PATTERN =\n /^[A-Za-z0-9._+:-]+(?:@[A-Za-z0-9._+:-]+)?$/;\n\n/**\n * Parse an action resource string of the form\n * `action/{selected_api}/{action_type}/{action_key}` into its parts.\n * Throws if the string doesn't match the canonical 4-segment shape or\n * if its `action_type` segment isn't one of the canonical 8 — every\n * action_run context that has been through `ActionRunContextSchema` is\n * guaranteed to parse cleanly, so a thrown error here means upstream\n * validation was bypassed.\n */\nexport function parseActionResource(resource: string): {\n selected_api: string;\n action_type: ActionType;\n action_key: string;\n} {\n const segments = resource.split(\"/\");\n if (segments.length !== 4 || segments[0] !== \"action\") {\n throw new Error(\n `action resource must be action/{selected_api}/{action_type}/{action_key}: got ${resource}`,\n );\n }\n const [, selectedApi, actionTypeRaw, actionKey] = segments;\n if (!selectedApi || !actionTypeRaw || !actionKey) {\n throw new Error(`action resource has empty segment: ${resource}`);\n }\n const actionType = ActionTypeSchema.safeParse(actionTypeRaw);\n if (!actionType.success) {\n throw new Error(\n `action resource has unknown action_type \"${actionTypeRaw}\": ${resource}`,\n );\n }\n if (!ACTION_RESOURCE_SEGMENT_PATTERN.test(selectedApi)) {\n throw new Error(\n `action resource has invalid selected_api segment \"${selectedApi}\": ${resource}`,\n );\n }\n if (!ACTION_KEY_SEGMENT_PATTERN.test(actionKey)) {\n throw new Error(\n `action resource has invalid action_key segment \"${actionKey}\": ${resource}`,\n );\n }\n return {\n selected_api: selectedApi,\n action_type: actionType.data,\n action_key: actionKey,\n };\n}\n\n/**\n * Strip the `@<version>` suffix from a `selected_api` / implementation\n * identifier. `Slack@1.0.0` → `Slack`. Passing a value without `@` is a\n * no-op. Used by UIs to render a human-friendly app key independent of\n * version, and by `globSelectedApiVersion` below.\n */\nexport function toAppKey(selectedApi: string): string {\n const at = selectedApi.indexOf(\"@\");\n return at === -1 ? selectedApi : selectedApi.slice(0, at);\n}\n\n/**\n * Replace the implementation-version suffix of a `selected_api` with a `@*`\n * wildcard so policies stay valid across version bumps. A runtime request\n * with `selected_api: \"App@2.7.3\"` matches a policy resource scoped to\n * `App@*` while still being distinguishable from a different app\n * (e.g. `App2@1.0.0`).\n *\n * No-op when the input has no `@` — assumed to be already version-less.\n */\nexport function globSelectedApiVersion(selectedApi: string): string {\n const at = selectedApi.indexOf(\"@\");\n return at === -1 ? selectedApi : selectedApi.slice(0, at) + \"@*\";\n}\n\n/**\n * Raw input shape for `ActionRunContextSchema`, before the transform that\n * canonicalizes legacy fields into `resource`. Exposed for the OpenAPI\n * schema generator (which can't represent transforms) — runtime callers\n * should use `ActionRunContextSchema`, which accepts either the canonical\n * `resource` field or the legacy `{selected_api, action_type, action_key}`\n * triple on input.\n */\nexport const ActionRunContextInputSchema = z\n .object({\n request_type: z\n .literal(\"action_run\")\n .describe(\"Context type discriminator\"),\n resource: z\n .string()\n .max(1024)\n .optional()\n .describe(\n \"Canonical action resource, e.g. action/Slack@1.0.0/write/send_message\",\n ),\n selected_api: z.string().max(255).optional().meta({\n deprecated: true,\n description:\n \"Legacy: app identifier, e.g. Slack@1.0.0. Prefer `resource`.\",\n }),\n action_type: ActionTypeSchema.optional().meta({\n deprecated: true,\n description: \"Legacy: canonical Zapier action type. Prefer `resource`.\",\n }),\n action_key: z.string().max(255).optional().meta({\n deprecated: true,\n description: \"Legacy: action key, e.g. send_message. Prefer `resource`.\",\n }),\n connection_id: z\n .string()\n .max(255)\n .optional()\n .describe(\"Zapier connection ID used for this request\"),\n /** Action input parameters. See body_json above for the pipe rationale. */\n inputs: z\n .unknown()\n .pipe(z.json())\n .optional()\n .describe(\"Action input parameters\"),\n reason: z\n .string()\n .max(1024)\n .optional()\n .describe(\"Optional human-readable reason for the request\"),\n })\n .meta({\n id: \"ActionRunContext\",\n description:\n \"Action run context. The canonical shape carries the action identity in a single `resource` field of the form `action/{selected_api}/{action_type}/{action_key}`. The legacy `{selected_api, action_type, action_key}` shape is also accepted on input during the migration window — approvalsapi normalizes it to the canonical form before storage.\",\n });\n\nexport const ActionRunContextSchema = ActionRunContextInputSchema.transform(\n (input, ctx) => {\n const resource =\n input.resource ??\n (input.selected_api && input.action_type && input.action_key\n ? `action/${input.selected_api}/${input.action_type}/${input.action_key}`\n : undefined);\n if (resource === undefined) {\n ctx.addIssue({\n code: \"custom\",\n message:\n \"action_run context requires either `resource` or all of `selected_api`/`action_type`/`action_key`\",\n });\n return z.NEVER;\n }\n try {\n parseActionResource(resource);\n } catch (err) {\n ctx.addIssue({\n code: \"custom\",\n message: err instanceof Error ? err.message : String(err),\n });\n return z.NEVER;\n }\n return {\n request_type: \"action_run\" as const,\n resource,\n ...(input.connection_id !== undefined && {\n connection_id: input.connection_id,\n }),\n ...(input.inputs !== undefined && { inputs: input.inputs }),\n ...(input.reason !== undefined && { reason: input.reason }),\n };\n },\n);\nexport type ActionRunContext = z.infer<typeof ActionRunContextSchema>;\n\n/**\n * Union of all request context types, keyed on `request_type`.\n *\n * Plain `z.union` (not `z.discriminatedUnion`) because\n * `ActionRunContextSchema` carries a `.transform` and discriminated\n * unions can't accept a `ZodEffects` member. The `request_type`\n * discriminator carried in `.meta()` below is read natively by the\n * OpenAPI generator (`@zapier/openapi-spec`), which emits it as\n * `anyOf` + discriminator that openapi-typescript and other codegen\n * targets render as a properly narrowed TS union.\n */\nexport const RequestContextSchema = z\n .union([HttpRequestContextSchema, ActionRunContextSchema])\n .meta({\n id: \"RequestContext\",\n description: \"Union of request context shapes, keyed on `request_type`.\",\n discriminator: {\n propertyName: \"request_type\",\n mapping: {\n http_request: \"#/components/schemas/HttpRequestContext\",\n action_run: \"#/components/schemas/ActionRunContext\",\n },\n },\n });\nexport type RequestContext = z.infer<typeof RequestContextSchema>;\n","// ABOUTME: Canonical set of headers to exclude when building request contexts.\n// ABOUTME: Shared between sdkapi (context creation) and approvalsapi (condition building).\n\n/**\n * Headers to exclude when building request contexts from raw HTTP requests.\n *\n * These are either sensitive (auth credentials), HTTP infrastructure headers\n * that vary per-request, or proxy-internal headers that are not meaningful\n * for policy decisions.\n */\nexport const IGNORED_HEADERS = new Set([\n // Auth / credentials — never include in contexts or policy conditions\n \"authorization\",\n \"x-relay-authorization\",\n \"x-relay-authentication-id\",\n \"x-api-key\",\n \"cookie\",\n \"set-cookie\",\n \"proxy-authorization\",\n\n // HTTP infrastructure — varies per-request, not policy-relevant\n \"host\",\n \"connection\",\n \"content-length\",\n \"transfer-encoding\",\n \"accept-encoding\",\n \"user-agent\",\n \"accept\",\n \"accept-language\",\n \"sec-fetch-mode\",\n\n // Proxy / forwarding — infrastructure, not meaningful for policy\n \"x-forwarded-for\",\n \"x-forwarded-host\",\n \"x-forwarded-proto\",\n \"x-real-ip\",\n\n // Proxy internal — sdkapi-specific headers\n \"x-is-interactive-session\",\n \"x-relay-callback-url\",\n // Subsumed by isIgnoredHeader's x-zapier- prefix rule; kept for byte-parity\n // with the approvalsapi source and for consumers reading the set directly.\n \"x-zapier-approval-token\",\n]);\n\nexport function isIgnoredHeader(name: string): boolean {\n const normalized = name.toLowerCase();\n return (\n IGNORED_HEADERS.has(normalized) ||\n normalized.startsWith(\"zapier-\") ||\n normalized.startsWith(\"x-zapier-\")\n );\n}\n","// ABOUTME: Canonical builders for creating request contexts from raw request parts.\n// ABOUTME: Used by sdkapi to build both approval contexts and policy eval contexts.\n\nimport { z } from \"zod\";\nimport {\n HttpRequestContextSchema,\n ActionRunContextSchema,\n ActionTypeSchema,\n parseUrl,\n ACTION_RESOURCE_SEGMENT_PATTERN,\n ACTION_KEY_SEGMENT_PATTERN,\n type HttpRequestContext,\n type ActionRunContext,\n} from \"./types.ts\";\nimport { buildActionResource } from \"./conditions.ts\";\nimport { isIgnoredHeader } from \"./constants.ts\";\n\nexport const BuildHttpRequestContextOptionsSchema = z.object({\n method: z.string(),\n /** Raw URL string. Will be normalized with https:// if no protocol present. */\n url: z.string(),\n /** Raw headers from the request. Will be filtered through isIgnoredHeader. */\n headers: z\n .record(\n z.string(),\n z.union([z.string(), z.array(z.string()), z.undefined()]),\n )\n .optional(),\n /** Raw body string */\n body: z.string().nullable().optional(),\n /** Pre-parsed JSON body (e.g. from Fastify's automatic JSON parsing) */\n body_json: z.json().optional(),\n /** Connection ID associated with this request */\n connection_id: z.string().optional(),\n});\nexport type BuildHttpRequestContextOptions = z.infer<\n typeof BuildHttpRequestContextOptionsSchema\n>;\n\n/**\n * Build a canonical HttpRequestContext from raw request parts.\n *\n * This is the single source of truth for how HTTP request contexts are created.\n * Both sdkapi (for policy evaluation) and approvalsapi (for context storage)\n * should use this to ensure the context shape is consistent.\n *\n * Matches the behavior of createPolicyHttpRequest from @zapier/policy, with\n * two additions: header filtering through isIgnoredHeader, and body/body_json\n * exclusivity (createPolicyHttpRequest keeps the raw body alongside body_json).\n *\n * - Normalizes URL (adds https:// if missing) and parses into { scheme, host, port, path, query }\n * - Filters headers through isIgnoredHeader (IGNORED_HEADERS set plus\n * zapier-* / x-zapier-* prefixes), lowercases keys, string values only\n * - Auto-parses body_json from body when content-type is JSON and body_json not provided\n * - Exactly one of body / body_json is populated: body is null whenever\n * body_json is set; both default to null (not undefined)\n */\nexport function buildHttpRequestContext(\n options: BuildHttpRequestContextOptions,\n): HttpRequestContext {\n // Validate options up-front so downstream string ops (e.g. method.toUpperCase)\n // see well-typed values. Mirrors the pattern in buildActionRunContext.\n const parsed = BuildHttpRequestContextOptionsSchema.parse(options);\n\n // Normalize URL — SDK CLI strips the protocol\n const rawUrl = parsed.url.includes(\"://\")\n ? parsed.url\n : `https://${parsed.url}`;\n const url = parseUrl(rawUrl);\n\n // Filter headers: exclude ignored, lowercase keys, string values only\n const headers: Record<string, string> = {};\n if (parsed.headers) {\n for (const [key, value] of Object.entries(parsed.headers)) {\n const lowerKey = key.toLowerCase();\n if (!isIgnoredHeader(lowerKey) && typeof value === \"string\") {\n headers[lowerKey] = value;\n }\n }\n }\n\n // Auto-parse body_json from body when content-type is JSON\n // (matches createPolicyHttpRequest behavior from @zapier/policy)\n let body_json: unknown = null;\n if (parsed.body_json !== undefined) {\n body_json = parsed.body_json;\n } else if (parsed.body) {\n const contentType = headers[\"content-type\"];\n const isJson =\n typeof contentType === \"string\" &&\n (contentType.includes(\"application/json\") ||\n (contentType.includes(\"application/\") &&\n contentType.includes(\"+json\")));\n if (isJson) {\n try {\n body_json = JSON.parse(parsed.body);\n } catch {\n // Invalid JSON body — leave body_json as null\n }\n }\n }\n\n return HttpRequestContextSchema.parse({\n request_type: \"http_request\",\n method: parsed.method.toUpperCase(),\n url,\n headers,\n body: body_json === null ? (parsed.body ?? null) : null,\n body_json,\n connection_id: parsed.connection_id,\n });\n}\n\nexport const BuildActionRunContextOptionsSchema = z.object({\n selected_api: z.string().regex(ACTION_RESOURCE_SEGMENT_PATTERN, {\n message:\n \"selected_api must contain only [A-Za-z0-9._@+-] (no globs, slashes, or whitespace)\",\n }),\n action_type: ActionTypeSchema,\n action_key: z.string().regex(ACTION_KEY_SEGMENT_PATTERN, {\n message:\n \"action_key must contain only [A-Za-z0-9._@:+-] (no globs, slashes, or whitespace)\",\n }),\n connection_id: z.string().optional(),\n inputs: z.json().optional(),\n reason: z.string().optional(),\n});\nexport type BuildActionRunContextOptions = z.infer<\n typeof BuildActionRunContextOptionsSchema\n>;\n\n/**\n * Build a canonical ActionRunContext from raw action parts.\n *\n * Callers pass the three identity fields separately for readability;\n * this validates them and collapses them into the canonical `resource`\n * string the schema stores.\n */\nexport function buildActionRunContext(\n options: BuildActionRunContextOptions,\n): ActionRunContext {\n const parsed = BuildActionRunContextOptionsSchema.parse(options);\n return ActionRunContextSchema.parse({\n request_type: \"action_run\",\n resource: buildActionResource({\n selected_api: parsed.selected_api,\n action_type: parsed.action_type,\n action_key: parsed.action_key,\n }),\n connection_id: parsed.connection_id,\n inputs: parsed.inputs,\n reason: parsed.reason,\n });\n}\n","// ABOUTME: Builds policy conditions from stored request contexts.\n// ABOUTME: Used by approvalsapi's \"allow exact request\" and \"allow domain\" instant policy flows.\n\nimport type { Condition } from \"@zapier/policy-schema\";\nimport type {\n HttpRequestContext,\n ActionRunContext,\n ActionType,\n} from \"./types.ts\";\nimport { isIgnoredHeader } from \"./constants.ts\";\n\n/**\n * Build conditions that match an exact HTTP request.\n *\n * Handles the matches_url / query param split correctly:\n * - `matches_url` only supports scheme+host+port+path (no query string per spec)\n * - Query parameters are added as separate decomposed conditions on `url.query.<key>`\n *\n * @returns Condition[] for an http permission statement\n */\nexport function buildExactHttpConditions(\n context: HttpRequestContext,\n): Condition[] {\n const conditions: Condition[] = [\n { path: [\"method\"], operator: \"equals\", value: context.method },\n ];\n\n const { url } = context;\n\n // matches_url condition uses URL without query string (per @zapier/policy spec)\n const defaultPort =\n url.scheme === \"https\" ? 443 : url.scheme === \"http\" ? 80 : 0;\n const portString = url.port !== defaultPort ? `:${String(url.port)}` : \"\";\n const urlWithoutQuery = `${url.scheme}://${url.host}${portString}${url.path}`;\n conditions.push({\n path: [\"url\"],\n operator: \"matches_url\",\n value: urlWithoutQuery,\n });\n\n // Add decomposed conditions for each query parameter.\n for (const [key, values] of Object.entries(url.query)) {\n conditions.push({\n path: [\"url\", \"query\", key],\n operator: \"equals\",\n value: values,\n });\n }\n\n // body_json condition\n if (context.body_json !== null) {\n conditions.push({\n path: [\"body_json\"],\n operator: \"equals\",\n value: context.body_json,\n });\n } else if (context.body !== null) {\n // Non-JSON body (text/plain, XML, form-encoded): pin the raw body so\n // exact-match policies actually match the originating request.\n conditions.push({\n path: [\"body\"],\n operator: \"equals\",\n value: context.body,\n });\n }\n\n // Header conditions (filtered through isIgnoredHeader again for safety)\n for (const [key, value] of Object.entries(context.headers)) {\n if (!isIgnoredHeader(key) && typeof value === \"string\") {\n conditions.push({\n path: [\"headers\", key.toLowerCase()],\n operator: \"equals\",\n value,\n });\n }\n }\n\n return conditions;\n}\n\n/**\n * Build conditions that match any request to a given domain.\n * Uses the host from the parsed URL.\n *\n * @returns Condition[] for an http permission statement\n */\nexport function buildDomainHttpConditions(\n context: HttpRequestContext,\n): Condition[] {\n return [\n {\n path: [\"url\", \"host\"],\n operator: \"matches_host\",\n value: context.url.host,\n },\n ];\n}\n\n/**\n * Build conditions that match an exact action run (with inputs).\n *\n * @returns Condition[] for an action permission statement\n */\nexport function buildExactActionConditions(\n context: ActionRunContext,\n): Condition[] {\n const conditions: Condition[] = [];\n\n if (context.inputs !== undefined && context.inputs !== null) {\n conditions.push({\n path: [\"inputs\"],\n operator: \"equals\",\n value: context.inputs,\n });\n }\n\n return conditions;\n}\n\n/**\n * The three identity fields that compose an action resource string.\n */\nexport interface ActionResourceParts {\n selected_api: string;\n action_type: ActionType;\n action_key: string;\n}\n\n/**\n * Build the resource string for an action.\n * Format: action/{selected_api}/{action_type}/{action_key}\n */\nexport function buildActionResource(parts: ActionResourceParts): string {\n return `action/${parts.selected_api}/${parts.action_type}/${parts.action_key}`;\n}\n\n/**\n * Build a broad action resource that matches all actions of the same type\n * for an app (e.g. all reads, all writes). Scopes on `action_type` to\n * avoid silently granting cross-type access.\n *\n * Format: action/{selected_api}/{action_type}/{wildcard}\n */\nexport function buildBroadActionResource(\n parts: Pick<ActionResourceParts, \"selected_api\" | \"action_type\">,\n): string {\n return `action/${parts.selected_api}/${parts.action_type}/*`;\n}\n","// ABOUTME: Assembles complete Policy objects from request contexts.\n// ABOUTME: Single source of truth for \"exact request\" instant policies used by web UI and API.\n\nimport type { Policy, Statement } from \"@zapier/policy-schema\";\nimport type {\n RequestContext,\n HttpRequestContext,\n ActionRunContext,\n} from \"./types.ts\";\nimport {\n buildExactHttpConditions,\n buildExactActionConditions,\n} from \"./conditions.ts\";\n\n/**\n * Build a `can_use` authentication statement, if the context has a connection_id.\n */\nfunction buildAuthStatement(authenticationId: string): Statement {\n return {\n effect: \"allow\",\n permissions: [\"can_use\"],\n resources: [`connection/${authenticationId}`],\n conditions: [],\n };\n}\n\n/**\n * Build an exact-match policy from an HTTP request context.\n *\n * Produces a policy that allows only the specific request described by the context:\n * - `can_use` statement for the authentication (if present)\n * - `can_execute` statement for `http` with conditions from `buildExactHttpConditions`\n * plus a `keys_in` guard restricting allowed query parameter keys\n */\nfunction httpContextToPolicy(context: HttpRequestContext): Policy {\n const statements: Statement[] = [];\n\n if (context.connection_id) {\n statements.push(buildAuthStatement(context.connection_id));\n }\n\n const conditions = buildExactHttpConditions(context);\n\n // Add a keys_in guard so only the query param keys present in the original\n // request are allowed — blocks injection of extra query params.\n conditions.push({\n path: [\"url\", \"query\"],\n operator: \"keys_in\",\n value: Object.keys(context.url.query),\n });\n\n statements.push({\n effect: \"allow\",\n permissions: [\"can_execute\"],\n resources: [\"http\"],\n conditions,\n });\n\n return { version: 2, statements };\n}\n\n/**\n * Build an exact-match policy from an action run context.\n *\n * Produces a policy that allows only the specific action described by the context:\n * - `can_use` statement for the authentication (if present)\n * - `can_execute` statement for the action resource with input conditions\n */\nfunction actionContextToPolicy(context: ActionRunContext): Policy {\n const statements: Statement[] = [];\n\n if (context.connection_id) {\n statements.push(buildAuthStatement(context.connection_id));\n }\n\n statements.push({\n effect: \"allow\",\n permissions: [\"can_execute\"],\n resources: [context.resource],\n conditions: buildExactActionConditions(context),\n });\n\n return { version: 2, statements };\n}\n\n/**\n * Build an exact-match policy from any supported request context.\n *\n * This is the single source of truth for \"allow this exact request\" instant policies.\n * Used by the web UI and anywhere else that needs to produce an exact policy from a context.\n */\nexport function toExactPolicy(context: RequestContext): Policy {\n if (context.request_type === \"http_request\") {\n return httpContextToPolicy(context);\n }\n return actionContextToPolicy(context);\n}\n","// ABOUTME: Builds connection-level policies for the basic approvals MVP.\n// ABOUTME: Generates deterministic policies that allow read or read+write access scoped to a specific connection.\n\nimport { z } from \"zod\";\nimport type { Policy, Statement, Condition } from \"@zapier/policy-schema\";\nimport {\n globSelectedApiVersion,\n parseActionResource,\n type ActionType,\n type RequestContext,\n} from \"./types.ts\";\n\nexport const AccessLevelSchema = z.enum([\"read\", \"read_write\"]);\nexport type AccessLevel = z.infer<typeof AccessLevelSchema>;\n\n/** HTTP methods that count as side-effect-free reads for connection-level policies. */\nexport const READ_HTTP_METHODS = [\"GET\", \"HEAD\", \"OPTIONS\"] as const;\n\n/**\n * Action types that count as side-effect-free reads for connection-level\n * policies. `read_bulk` is the paginated/bulk variant of `read` — same\n * external API semantics, no mutations. Widely used by major apps (Slack,\n * Gmail, Jira, Salesforce, etc.) via the public `bulkReads` schema key.\n * `filter` and `run` are excluded: neither has a runtime executor for\n * external apps, and `filter` actions don't carry a connection_id anyway,\n * so this allowlist has no effect on them.\n */\nexport const READ_ACTION_TYPES = [\n \"read\",\n \"read_bulk\",\n \"search\",\n] as const satisfies readonly ActionType[];\n\nconst READ_HTTP_METHOD_SET: ReadonlySet<string> = new Set(READ_HTTP_METHODS);\nconst READ_ACTION_TYPE_SET: ReadonlySet<ActionType> = new Set(\n READ_ACTION_TYPES,\n);\n\n/**\n * Returns true when the request needs write access (i.e. it is NOT a\n * side-effect-free read). Mirrors the logic encoded in `buildConnectionPolicy`\n * so UI surfaces that gate the read-vs-read_write choice stay consistent\n * with the policies they generate.\n */\nexport function isWriteRequest(context: RequestContext): boolean {\n if (context.request_type === \"http_request\") {\n // Method is uppercase by construction (buildHttpRequestContext canonicalizes\n // it on the way in), so no normalization is needed here.\n return !READ_HTTP_METHOD_SET.has(context.method);\n }\n const { action_type } = parseActionResource(context.resource);\n return !READ_ACTION_TYPE_SET.has(action_type);\n}\n\n/**\n * Build a connection-level policy that covers both HTTP and action access.\n *\n * Always produces three statements:\n * 1. `can_use` for the authentication\n * 2. `can_execute` on `http` scoped by connection_id (+ method filter for read)\n * 3. `can_execute` on `action/{selectedApi}/{action_type}/*` per allowed type,\n * scoped by connection_id. For read access, the resource list expands to\n * one entry per read action_type so the engine matches via the resource\n * string rather than a separate `path: [\"action_type\"]` condition.\n */\nexport function buildConnectionPolicy(options: {\n connectionId: string;\n selectedApi: string;\n accessLevel: AccessLevel;\n}): Policy {\n const { connectionId, selectedApi, accessLevel } = options;\n\n const authStatement: Statement = {\n effect: \"allow\",\n permissions: [\"can_use\"],\n resources: [`connection/${connectionId}`],\n conditions: [],\n };\n\n const connectionCondition: Condition = {\n path: [\"connection_id\"],\n operator: \"equals\",\n value: connectionId,\n };\n\n const httpConditions: Condition[] = [connectionCondition];\n if (accessLevel === \"read\") {\n httpConditions.push({\n path: [\"method\"],\n operator: \"in\",\n value: [...READ_HTTP_METHODS],\n });\n }\n\n const httpStatement: Statement = {\n effect: \"allow\",\n permissions: [\"can_execute\"],\n resources: [\"http\"],\n conditions: httpConditions,\n };\n\n const apiPattern = globSelectedApiVersion(selectedApi);\n const actionResources =\n accessLevel === \"read\"\n ? READ_ACTION_TYPES.map((t) => `action/${apiPattern}/${t}/*`)\n : [`action/${apiPattern}/*/*`];\n\n const actionStatement: Statement = {\n effect: \"allow\",\n permissions: [\"can_execute\"],\n resources: actionResources,\n conditions: [connectionCondition],\n };\n\n return {\n version: 2,\n statements: [authStatement, httpStatement, actionStatement],\n };\n}\n","// ABOUTME: Builds connectionless approval policies bound to a domain (HTTP) or an action (action_run).\n// ABOUTME: Used when the smart-policy flag is off and the request has no connection_id.\n\nimport type { Policy, Statement, Condition } from \"@zapier/policy-schema\";\nimport {\n globSelectedApiVersion,\n parseActionResource,\n type RequestContext,\n} from \"./types.ts\";\nimport {\n READ_ACTION_TYPES,\n READ_HTTP_METHODS,\n type AccessLevel,\n} from \"./connection-policy.ts\";\n\n/**\n * Build a connectionless policy that scopes access to the request's domain\n * (HTTP) or its app (action_run). Mirrors the read/write semantics of\n * `buildConnectionPolicy` minus the auth statement and `connection_id`\n * condition, since there is no connection to bind to.\n */\nexport function buildConnectionlessPolicy(options: {\n context: RequestContext;\n accessLevel: AccessLevel;\n}): Policy {\n const { context, accessLevel } = options;\n\n if (context.request_type === \"http_request\") {\n const conditions: Condition[] = [\n {\n path: [\"url\", \"host\"],\n operator: \"matches_host\",\n value: context.url.host,\n },\n ];\n if (accessLevel === \"read\") {\n conditions.push({\n path: [\"method\"],\n operator: \"in\",\n value: [...READ_HTTP_METHODS],\n });\n }\n\n const statement: Statement = {\n effect: \"allow\",\n permissions: [\"can_execute\"],\n resources: [\"http\"],\n conditions,\n };\n return { version: 2, statements: [statement] };\n }\n\n const { selected_api } = parseActionResource(context.resource);\n const apiPattern = globSelectedApiVersion(selected_api);\n const resources =\n accessLevel === \"read\"\n ? READ_ACTION_TYPES.map((t) => `action/${apiPattern}/${t}/*`)\n : [`action/${apiPattern}/*/*`];\n\n const statement: Statement = {\n effect: \"allow\",\n permissions: [\"can_execute\"],\n resources,\n conditions: [],\n };\n return { version: 2, statements: [statement] };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACGA,iBAAkB;AAOX,IAAM,kBAAkB,aAC5B,OAAO;AAAA,EACN,QAAQ,aAAE,OAAO,EAAE,SAAS,0BAA0B;AAAA,EACtD,MAAM,aAAE,OAAO,EAAE,SAAS,kCAAkC;AAAA,EAC5D,MAAM,aACH,OAAO,EACP,IAAI,EACJ,SAAS,sDAAsD;AAAA,EAClE,MAAM,aAAE,OAAO,EAAE,SAAS,0BAA0B;AAAA,EACpD,OAAO,aACJ,OAAO,aAAE,OAAO,GAAG,aAAE,MAAM,aAAE,OAAO,CAAC,CAAC,EACtC,SAAS,iDAAiD;AAC/D,CAAC,EACA,KAAK;AAAA,EACJ,IAAI;AAAA,EACJ,aAAa;AAC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AAW,KAAK;AAAA,QACd,MAAM,CAAC,QAAQ;AAAA,QACf,UAAU;AAAA,QACV,OAAO,CAAC,GAAG,iBAAiB;AAAA,MAC9B,CAAC;AAAA,IACH;AAEA,UAAMC,aAAuB;AAAA,MAC3B,QAAQ;AAAA,MACR,aAAa,CAAC,aAAa;AAAA,MAC3B,WAAW,CAAC,MAAM;AAAA,MAClB;AAAA,IACF;AACA,WAAO,EAAE,SAAS,GAAG,YAAY,CAACA,UAAS,EAAE;AAAA,EAC/C;AAEA,QAAM,EAAE,aAAa,IAAI,oBAAoB,QAAQ,QAAQ;AAC7D,QAAM,aAAa,uBAAuB,YAAY;AACtD,QAAM,YACJ,gBAAgB,SACZ,kBAAkB,IAAI,CAAC,MAAM,UAAU,UAAU,IAAI,CAAC,IAAI,IAC1D,CAAC,UAAU,UAAU,MAAM;AAEjC,QAAM,YAAuB;AAAA,IAC3B,QAAQ;AAAA,IACR,aAAa,CAAC,aAAa;AAAA,IAC3B;AAAA,IACA,YAAY,CAAC;AAAA,EACf;AACA,SAAO,EAAE,SAAS,GAAG,YAAY,CAAC,SAAS,EAAE;AAC/C;","names":["import_zod","import_zod","statement"]}
package/dist/index.d.cts CHANGED
@@ -234,6 +234,7 @@ type RequestContext = z.infer<typeof RequestContextSchema>;
234
234
  * for policy decisions.
235
235
  */
236
236
  declare const IGNORED_HEADERS: Set<string>;
237
+ declare function isIgnoredHeader(name: string): boolean;
237
238
 
238
239
  declare const BuildHttpRequestContextOptionsSchema: z.ZodObject<{
239
240
  method: z.ZodString;
@@ -252,12 +253,15 @@ type BuildHttpRequestContextOptions = z.infer<typeof BuildHttpRequestContextOpti
252
253
  * should use this to ensure the context shape is consistent.
253
254
  *
254
255
  * Matches the behavior of createPolicyHttpRequest from @zapier/policy, with
255
- * the addition of header filtering through IGNORED_HEADERS.
256
+ * two additions: header filtering through isIgnoredHeader, and body/body_json
257
+ * exclusivity (createPolicyHttpRequest keeps the raw body alongside body_json).
256
258
  *
257
259
  * - Normalizes URL (adds https:// if missing) and parses into { scheme, host, port, path, query }
258
- * - Filters headers through IGNORED_HEADERS, lowercases keys, string values only
260
+ * - Filters headers through isIgnoredHeader (IGNORED_HEADERS set plus
261
+ * zapier-* / x-zapier-* prefixes), lowercases keys, string values only
259
262
  * - Auto-parses body_json from body when content-type is JSON and body_json not provided
260
- * - body defaults to null (not undefined)
263
+ * - Exactly one of body / body_json is populated: body is null whenever
264
+ * body_json is set; both default to null (not undefined)
261
265
  */
262
266
  declare function buildHttpRequestContext(options: BuildHttpRequestContextOptions): HttpRequestContext;
263
267
  declare const BuildActionRunContextOptionsSchema: z.ZodObject<{
@@ -392,4 +396,4 @@ declare function buildConnectionlessPolicy(options: {
392
396
  accessLevel: AccessLevel;
393
397
  }): Policy;
394
398
 
395
- export { type AccessLevel, AccessLevelSchema, type ActionRunContext, ActionRunContextInputSchema, ActionRunContextSchema, type ActionType, ActionTypeSchema, type BuildActionRunContextOptions, BuildActionRunContextOptionsSchema, type BuildHttpRequestContextOptions, BuildHttpRequestContextOptionsSchema, DEFAULT_PORTS, type HttpRequestContext, HttpRequestContextSchema, IGNORED_HEADERS, type ParsedUrl, ParsedUrlSchema, READ_ACTION_TYPES, READ_HTTP_METHODS, type RequestContext, RequestContextSchema, buildActionResource, buildActionRunContext, buildBroadActionResource, buildConnectionPolicy, buildConnectionlessPolicy, buildDomainHttpConditions, buildExactActionConditions, buildExactHttpConditions, buildHttpRequestContext, buildUrlString, globSelectedApiVersion, isWriteRequest, parseActionResource, parseUrl, toAppKey, toExactPolicy };
399
+ export { type AccessLevel, AccessLevelSchema, type ActionRunContext, ActionRunContextInputSchema, ActionRunContextSchema, type ActionType, ActionTypeSchema, type BuildActionRunContextOptions, BuildActionRunContextOptionsSchema, type BuildHttpRequestContextOptions, BuildHttpRequestContextOptionsSchema, DEFAULT_PORTS, type HttpRequestContext, HttpRequestContextSchema, IGNORED_HEADERS, type ParsedUrl, ParsedUrlSchema, READ_ACTION_TYPES, READ_HTTP_METHODS, type RequestContext, RequestContextSchema, buildActionResource, buildActionRunContext, buildBroadActionResource, buildConnectionPolicy, buildConnectionlessPolicy, buildDomainHttpConditions, buildExactActionConditions, buildExactHttpConditions, buildHttpRequestContext, buildUrlString, globSelectedApiVersion, isIgnoredHeader, isWriteRequest, parseActionResource, parseUrl, toAppKey, toExactPolicy };
package/dist/index.d.ts CHANGED
@@ -234,6 +234,7 @@ type RequestContext = z.infer<typeof RequestContextSchema>;
234
234
  * for policy decisions.
235
235
  */
236
236
  declare const IGNORED_HEADERS: Set<string>;
237
+ declare function isIgnoredHeader(name: string): boolean;
237
238
 
238
239
  declare const BuildHttpRequestContextOptionsSchema: z.ZodObject<{
239
240
  method: z.ZodString;
@@ -252,12 +253,15 @@ type BuildHttpRequestContextOptions = z.infer<typeof BuildHttpRequestContextOpti
252
253
  * should use this to ensure the context shape is consistent.
253
254
  *
254
255
  * Matches the behavior of createPolicyHttpRequest from @zapier/policy, with
255
- * the addition of header filtering through IGNORED_HEADERS.
256
+ * two additions: header filtering through isIgnoredHeader, and body/body_json
257
+ * exclusivity (createPolicyHttpRequest keeps the raw body alongside body_json).
256
258
  *
257
259
  * - Normalizes URL (adds https:// if missing) and parses into { scheme, host, port, path, query }
258
- * - Filters headers through IGNORED_HEADERS, lowercases keys, string values only
260
+ * - Filters headers through isIgnoredHeader (IGNORED_HEADERS set plus
261
+ * zapier-* / x-zapier-* prefixes), lowercases keys, string values only
259
262
  * - Auto-parses body_json from body when content-type is JSON and body_json not provided
260
- * - body defaults to null (not undefined)
263
+ * - Exactly one of body / body_json is populated: body is null whenever
264
+ * body_json is set; both default to null (not undefined)
261
265
  */
262
266
  declare function buildHttpRequestContext(options: BuildHttpRequestContextOptions): HttpRequestContext;
263
267
  declare const BuildActionRunContextOptionsSchema: z.ZodObject<{
@@ -392,4 +396,4 @@ declare function buildConnectionlessPolicy(options: {
392
396
  accessLevel: AccessLevel;
393
397
  }): Policy;
394
398
 
395
- export { type AccessLevel, AccessLevelSchema, type ActionRunContext, ActionRunContextInputSchema, ActionRunContextSchema, type ActionType, ActionTypeSchema, type BuildActionRunContextOptions, BuildActionRunContextOptionsSchema, type BuildHttpRequestContextOptions, BuildHttpRequestContextOptionsSchema, DEFAULT_PORTS, type HttpRequestContext, HttpRequestContextSchema, IGNORED_HEADERS, type ParsedUrl, ParsedUrlSchema, READ_ACTION_TYPES, READ_HTTP_METHODS, type RequestContext, RequestContextSchema, buildActionResource, buildActionRunContext, buildBroadActionResource, buildConnectionPolicy, buildConnectionlessPolicy, buildDomainHttpConditions, buildExactActionConditions, buildExactHttpConditions, buildHttpRequestContext, buildUrlString, globSelectedApiVersion, isWriteRequest, parseActionResource, parseUrl, toAppKey, toExactPolicy };
399
+ export { type AccessLevel, AccessLevelSchema, type ActionRunContext, ActionRunContextInputSchema, ActionRunContextSchema, type ActionType, ActionTypeSchema, type BuildActionRunContextOptions, BuildActionRunContextOptionsSchema, type BuildHttpRequestContextOptions, BuildHttpRequestContextOptionsSchema, DEFAULT_PORTS, type HttpRequestContext, HttpRequestContextSchema, IGNORED_HEADERS, type ParsedUrl, ParsedUrlSchema, READ_ACTION_TYPES, READ_HTTP_METHODS, type RequestContext, RequestContextSchema, buildActionResource, buildActionRunContext, buildBroadActionResource, buildConnectionPolicy, buildConnectionlessPolicy, buildDomainHttpConditions, buildExactActionConditions, buildExactHttpConditions, buildHttpRequestContext, buildUrlString, globSelectedApiVersion, isIgnoredHeader, isWriteRequest, parseActionResource, parseUrl, toAppKey, toExactPolicy };
package/dist/index.js CHANGED
@@ -211,8 +211,15 @@ var IGNORED_HEADERS = /* @__PURE__ */ new Set([
211
211
  "x-real-ip",
212
212
  // Proxy internal — sdkapi-specific headers
213
213
  "x-is-interactive-session",
214
- "x-relay-callback-url"
214
+ "x-relay-callback-url",
215
+ // Subsumed by isIgnoredHeader's x-zapier- prefix rule; kept for byte-parity
216
+ // with the approvalsapi source and for consumers reading the set directly.
217
+ "x-zapier-approval-token"
215
218
  ]);
219
+ function isIgnoredHeader(name) {
220
+ const normalized = name.toLowerCase();
221
+ return IGNORED_HEADERS.has(normalized) || normalized.startsWith("zapier-") || normalized.startsWith("x-zapier-");
222
+ }
216
223
 
217
224
  // src/builders.ts
218
225
  import { z as z2 } from "zod";
@@ -252,7 +259,7 @@ function buildExactHttpConditions(context) {
252
259
  });
253
260
  }
254
261
  for (const [key, value] of Object.entries(context.headers)) {
255
- if (!IGNORED_HEADERS.has(key.toLowerCase()) && typeof value === "string") {
262
+ if (!isIgnoredHeader(key) && typeof value === "string") {
256
263
  conditions.push({
257
264
  path: ["headers", key.toLowerCase()],
258
265
  operator: "equals",
@@ -294,7 +301,7 @@ var BuildHttpRequestContextOptionsSchema = z2.object({
294
301
  method: z2.string(),
295
302
  /** Raw URL string. Will be normalized with https:// if no protocol present. */
296
303
  url: z2.string(),
297
- /** Raw headers from the request. Will be filtered through IGNORED_HEADERS. */
304
+ /** Raw headers from the request. Will be filtered through isIgnoredHeader. */
298
305
  headers: z2.record(
299
306
  z2.string(),
300
307
  z2.union([z2.string(), z2.array(z2.string()), z2.undefined()])
@@ -314,7 +321,7 @@ function buildHttpRequestContext(options) {
314
321
  if (parsed.headers) {
315
322
  for (const [key, value] of Object.entries(parsed.headers)) {
316
323
  const lowerKey = key.toLowerCase();
317
- if (!IGNORED_HEADERS.has(lowerKey) && typeof value === "string") {
324
+ if (!isIgnoredHeader(lowerKey) && typeof value === "string") {
318
325
  headers[lowerKey] = value;
319
326
  }
320
327
  }
@@ -337,7 +344,7 @@ function buildHttpRequestContext(options) {
337
344
  method: parsed.method.toUpperCase(),
338
345
  url,
339
346
  headers,
340
- body: parsed.body ?? null,
347
+ body: body_json === null ? parsed.body ?? null : null,
341
348
  body_json,
342
349
  connection_id: parsed.connection_id
343
350
  });
@@ -540,6 +547,7 @@ export {
540
547
  buildHttpRequestContext,
541
548
  buildUrlString,
542
549
  globSelectedApiVersion,
550
+ isIgnoredHeader,
543
551
  isWriteRequest,
544
552
  parseActionResource,
545
553
  parseUrl,
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/types.ts","../src/constants.ts","../src/builders.ts","../src/conditions.ts","../src/policies.ts","../src/connection-policy.ts","../src/connectionless-policy.ts"],"sourcesContent":["// ABOUTME: Canonical request context types shared between sdkapi and approvalsapi.\n// ABOUTME: These define the contract for how requests are described in approval flows and policy evaluation.\n\nimport { z } from \"zod\";\n\n/**\n * Parsed URL components for policy evaluation.\n * Matches the ParsedUrl shape from @zapier/policy-schema so that\n * evaluatePolicy condition paths like [\"url\", \"host\"] resolve correctly.\n */\nexport const ParsedUrlSchema = z\n .object({\n scheme: z.string().describe('URL scheme, e.g. \"https\"'),\n host: z.string().describe('Hostname, e.g. \"api.example.com\"'),\n port: z\n .number()\n .int()\n .describe(\"Port number (defaults to 443 for https, 80 for http)\"),\n path: z.string().describe('URL path, e.g. \"/v1/foo\"'),\n query: z\n .record(z.string(), z.array(z.string()))\n .describe(\"Query parameters as key to string array mapping\"),\n })\n .meta({\n id: \"ParsedUrl\",\n description: \"Parsed URL components for policy condition matching\",\n });\nexport type ParsedUrl = z.infer<typeof ParsedUrlSchema>;\n\n/** Default ports by scheme, used when URL has no explicit port. */\nexport const DEFAULT_PORTS: Record<string, number> = {\n http: 80,\n https: 443,\n};\n\n/**\n * Parse a raw URL string into a ParsedUrl.\n * Same logic as parseUrlForPolicyContext in @zapier/policy.\n */\nexport function parseUrl(raw: string): ParsedUrl {\n const url = new URL(raw);\n const scheme = url.protocol.slice(0, -1).toLowerCase();\n const host = url.hostname.toLowerCase();\n const port = url.port ? parseInt(url.port, 10) : (DEFAULT_PORTS[scheme] ?? 0);\n const path = url.pathname || \"/\";\n const query: Record<string, string[]> = {};\n for (const [key, value] of url.searchParams) {\n if (!query[key]) {\n query[key] = [];\n }\n query[key].push(value);\n }\n return { scheme, host, port, path, query };\n}\n\n/**\n * Reconstruct a URL string from a ParsedUrl.\n * Same logic as buildUrl in @zapier/policy.\n */\nexport function buildUrlString(parsed: ParsedUrl): string {\n const { scheme, host, port, path, query } = parsed;\n const defaultPort = DEFAULT_PORTS[scheme];\n const portString = port !== defaultPort ? `:${String(port)}` : \"\";\n const params = new URLSearchParams();\n for (const [key, values] of Object.entries(query)) {\n for (const value of values) {\n params.append(key, value);\n }\n }\n const queryString = params.toString();\n return `${scheme}://${host}${portString}${path}${queryString ? \"?\" + queryString : \"\"}`;\n}\n\n/**\n * HTTP request context for approval/policy flows.\n * Sent by sdkapi when a relay request is denied, stored by approvalsapi,\n * and used for both policy evaluation and building policy conditions.\n *\n * The url field is a ParsedUrl object (matching @zapier/policy-schema's ParsedUrl)\n * so that evaluatePolicy conditions like [\"url\", \"host\"] resolve correctly.\n */\nexport const HttpRequestContextSchema = z\n .object({\n request_type: z\n .literal(\"http_request\")\n .describe(\"Context type discriminator\"),\n method: z\n .string()\n .max(10)\n .transform((m) => m.toUpperCase())\n .describe(\"HTTP method\"),\n /** Parsed URL components for policy condition matching */\n url: ParsedUrlSchema,\n /** Filtered headers (IGNORED_HEADERS excluded, keys lowercased) */\n headers: z\n .record(z.string(), z.string())\n .describe(\"Filtered headers (IGNORED_HEADERS excluded, keys lowercased)\"),\n /** Raw body string */\n body: z.string().max(65536).nullable().describe(\"Raw body string\"),\n /**\n * Parsed JSON body. Authored as `z.unknown().pipe(z.json())` so\n * the OpenAPI generator sees the outer `z.unknown()` and emits a\n * permissive field (no recursive `$ref`, no type), while the inner\n * `z.json()` still rejects non-JSON values (`Date`, `undefined`,\n * functions) at parse time. Same inferred `JsonValue` type either way.\n */\n body_json: z\n .unknown()\n .pipe(z.json())\n .nullable()\n .describe(\"Parsed JSON body (if applicable)\"),\n /** Zapier connection ID used for this request */\n connection_id: z\n .string()\n .max(255)\n .optional()\n .describe(\"Zapier connection ID used for this request\"),\n /** Optional human-readable reason for the request */\n reason: z\n .string()\n .max(1024)\n .optional()\n .describe(\"Optional human-readable reason for the request\"),\n })\n .meta({ id: \"HttpRequestContext\" });\nexport type HttpRequestContext = z.infer<typeof HttpRequestContextSchema>;\n\n/**\n * Canonical Zapier action types.\n *\n * Mirrors the `action_type` enum in sdkapi's OpenAPI spec\n * (`packages/openapi-spec/openapi.d.ts` `action_type`). Single source of\n * truth for any code that branches on or filters by action_type — keeps\n * `ActionRunContextSchema`, `BuildActionRunContextOptionsSchema`, and the\n * `READ_ACTION_TYPES` allowlist in `connection-policy.ts` aligned.\n */\nexport const ActionTypeSchema = z\n .enum([\n \"filter\",\n \"read\",\n \"read_bulk\",\n \"run\",\n \"search\",\n \"search_and_write\",\n \"search_or_write\",\n \"write\",\n ])\n .meta({ id: \"action_type\", description: \"Canonical Zapier action type.\" });\nexport type ActionType = z.infer<typeof ActionTypeSchema>;\n\n/**\n * Allowed character set for the `selected_api` segment of an action\n * resource. Blocks `*`, `/`, `:`, whitespace, and other glob/path\n * metacharacters that would otherwise widen policy scope. Permits at\n * most one `@`, which `globSelectedApiVersion` treats as the\n * version separator.\n */\nexport const ACTION_RESOURCE_SEGMENT_PATTERN =\n /^[A-Za-z0-9._+-]+(?:@[A-Za-z0-9._+-]+)?$/;\n\n/**\n * Allowed character set for the `action_key` segment of an action\n * resource. More permissive than `ACTION_RESOURCE_SEGMENT_PATTERN`\n * because sdkapi emits keys like `ae:358405` and `core:123abc` that\n * carry a namespace prefix separated by `:`. Still blocks `*`, `/`,\n * whitespace, and other glob/path metacharacters.\n */\nexport const ACTION_KEY_SEGMENT_PATTERN =\n /^[A-Za-z0-9._+:-]+(?:@[A-Za-z0-9._+:-]+)?$/;\n\n/**\n * Parse an action resource string of the form\n * `action/{selected_api}/{action_type}/{action_key}` into its parts.\n * Throws if the string doesn't match the canonical 4-segment shape or\n * if its `action_type` segment isn't one of the canonical 8 — every\n * action_run context that has been through `ActionRunContextSchema` is\n * guaranteed to parse cleanly, so a thrown error here means upstream\n * validation was bypassed.\n */\nexport function parseActionResource(resource: string): {\n selected_api: string;\n action_type: ActionType;\n action_key: string;\n} {\n const segments = resource.split(\"/\");\n if (segments.length !== 4 || segments[0] !== \"action\") {\n throw new Error(\n `action resource must be action/{selected_api}/{action_type}/{action_key}: got ${resource}`,\n );\n }\n const [, selectedApi, actionTypeRaw, actionKey] = segments;\n if (!selectedApi || !actionTypeRaw || !actionKey) {\n throw new Error(`action resource has empty segment: ${resource}`);\n }\n const actionType = ActionTypeSchema.safeParse(actionTypeRaw);\n if (!actionType.success) {\n throw new Error(\n `action resource has unknown action_type \"${actionTypeRaw}\": ${resource}`,\n );\n }\n if (!ACTION_RESOURCE_SEGMENT_PATTERN.test(selectedApi)) {\n throw new Error(\n `action resource has invalid selected_api segment \"${selectedApi}\": ${resource}`,\n );\n }\n if (!ACTION_KEY_SEGMENT_PATTERN.test(actionKey)) {\n throw new Error(\n `action resource has invalid action_key segment \"${actionKey}\": ${resource}`,\n );\n }\n return {\n selected_api: selectedApi,\n action_type: actionType.data,\n action_key: actionKey,\n };\n}\n\n/**\n * Strip the `@<version>` suffix from a `selected_api` / implementation\n * identifier. `Slack@1.0.0` → `Slack`. Passing a value without `@` is a\n * no-op. Used by UIs to render a human-friendly app key independent of\n * version, and by `globSelectedApiVersion` below.\n */\nexport function toAppKey(selectedApi: string): string {\n const at = selectedApi.indexOf(\"@\");\n return at === -1 ? selectedApi : selectedApi.slice(0, at);\n}\n\n/**\n * Replace the implementation-version suffix of a `selected_api` with a `@*`\n * wildcard so policies stay valid across version bumps. A runtime request\n * with `selected_api: \"App@2.7.3\"` matches a policy resource scoped to\n * `App@*` while still being distinguishable from a different app\n * (e.g. `App2@1.0.0`).\n *\n * No-op when the input has no `@` — assumed to be already version-less.\n */\nexport function globSelectedApiVersion(selectedApi: string): string {\n const at = selectedApi.indexOf(\"@\");\n return at === -1 ? selectedApi : selectedApi.slice(0, at) + \"@*\";\n}\n\n/**\n * Raw input shape for `ActionRunContextSchema`, before the transform that\n * canonicalizes legacy fields into `resource`. Exposed for the OpenAPI\n * schema generator (which can't represent transforms) — runtime callers\n * should use `ActionRunContextSchema`, which accepts either the canonical\n * `resource` field or the legacy `{selected_api, action_type, action_key}`\n * triple on input.\n */\nexport const ActionRunContextInputSchema = z\n .object({\n request_type: z\n .literal(\"action_run\")\n .describe(\"Context type discriminator\"),\n resource: z\n .string()\n .max(1024)\n .optional()\n .describe(\n \"Canonical action resource, e.g. action/Slack@1.0.0/write/send_message\",\n ),\n selected_api: z.string().max(255).optional().meta({\n deprecated: true,\n description:\n \"Legacy: app identifier, e.g. Slack@1.0.0. Prefer `resource`.\",\n }),\n action_type: ActionTypeSchema.optional().meta({\n deprecated: true,\n description: \"Legacy: canonical Zapier action type. Prefer `resource`.\",\n }),\n action_key: z.string().max(255).optional().meta({\n deprecated: true,\n description: \"Legacy: action key, e.g. send_message. Prefer `resource`.\",\n }),\n connection_id: z\n .string()\n .max(255)\n .optional()\n .describe(\"Zapier connection ID used for this request\"),\n /** Action input parameters. See body_json above for the pipe rationale. */\n inputs: z\n .unknown()\n .pipe(z.json())\n .optional()\n .describe(\"Action input parameters\"),\n reason: z\n .string()\n .max(1024)\n .optional()\n .describe(\"Optional human-readable reason for the request\"),\n })\n .meta({\n id: \"ActionRunContext\",\n description:\n \"Action run context. The canonical shape carries the action identity in a single `resource` field of the form `action/{selected_api}/{action_type}/{action_key}`. The legacy `{selected_api, action_type, action_key}` shape is also accepted on input during the migration window — approvalsapi normalizes it to the canonical form before storage.\",\n });\n\nexport const ActionRunContextSchema = ActionRunContextInputSchema.transform(\n (input, ctx) => {\n const resource =\n input.resource ??\n (input.selected_api && input.action_type && input.action_key\n ? `action/${input.selected_api}/${input.action_type}/${input.action_key}`\n : undefined);\n if (resource === undefined) {\n ctx.addIssue({\n code: \"custom\",\n message:\n \"action_run context requires either `resource` or all of `selected_api`/`action_type`/`action_key`\",\n });\n return z.NEVER;\n }\n try {\n parseActionResource(resource);\n } catch (err) {\n ctx.addIssue({\n code: \"custom\",\n message: err instanceof Error ? err.message : String(err),\n });\n return z.NEVER;\n }\n return {\n request_type: \"action_run\" as const,\n resource,\n ...(input.connection_id !== undefined && {\n connection_id: input.connection_id,\n }),\n ...(input.inputs !== undefined && { inputs: input.inputs }),\n ...(input.reason !== undefined && { reason: input.reason }),\n };\n },\n);\nexport type ActionRunContext = z.infer<typeof ActionRunContextSchema>;\n\n/**\n * Union of all request context types, keyed on `request_type`.\n *\n * Plain `z.union` (not `z.discriminatedUnion`) because\n * `ActionRunContextSchema` carries a `.transform` and discriminated\n * unions can't accept a `ZodEffects` member. The `request_type`\n * discriminator carried in `.meta()` below is read natively by the\n * OpenAPI generator (`@zapier/openapi-spec`), which emits it as\n * `anyOf` + discriminator that openapi-typescript and other codegen\n * targets render as a properly narrowed TS union.\n */\nexport const RequestContextSchema = z\n .union([HttpRequestContextSchema, ActionRunContextSchema])\n .meta({\n id: \"RequestContext\",\n description: \"Union of request context shapes, keyed on `request_type`.\",\n discriminator: {\n propertyName: \"request_type\",\n mapping: {\n http_request: \"#/components/schemas/HttpRequestContext\",\n action_run: \"#/components/schemas/ActionRunContext\",\n },\n },\n });\nexport type RequestContext = z.infer<typeof RequestContextSchema>;\n","// ABOUTME: Canonical set of headers to exclude when building request contexts.\n// ABOUTME: Shared between sdkapi (context creation) and approvalsapi (condition building).\n\n/**\n * Headers to exclude when building request contexts from raw HTTP requests.\n *\n * These are either sensitive (auth credentials), HTTP infrastructure headers\n * that vary per-request, or proxy-internal headers that are not meaningful\n * for policy decisions.\n */\nexport const IGNORED_HEADERS = new Set([\n // Auth / credentials — never include in contexts or policy conditions\n \"authorization\",\n \"x-relay-authorization\",\n \"x-relay-authentication-id\",\n \"x-api-key\",\n \"cookie\",\n \"set-cookie\",\n \"proxy-authorization\",\n\n // HTTP infrastructure — varies per-request, not policy-relevant\n \"host\",\n \"connection\",\n \"content-length\",\n \"transfer-encoding\",\n \"accept-encoding\",\n \"user-agent\",\n \"accept\",\n \"accept-language\",\n \"sec-fetch-mode\",\n\n // Proxy / forwarding — infrastructure, not meaningful for policy\n \"x-forwarded-for\",\n \"x-forwarded-host\",\n \"x-forwarded-proto\",\n \"x-real-ip\",\n\n // Proxy internal — sdkapi-specific headers\n \"x-is-interactive-session\",\n \"x-relay-callback-url\",\n]);\n","// ABOUTME: Canonical builders for creating request contexts from raw request parts.\n// ABOUTME: Used by sdkapi to build both approval contexts and policy eval contexts.\n\nimport { z } from \"zod\";\nimport {\n HttpRequestContextSchema,\n ActionRunContextSchema,\n ActionTypeSchema,\n parseUrl,\n ACTION_RESOURCE_SEGMENT_PATTERN,\n ACTION_KEY_SEGMENT_PATTERN,\n type HttpRequestContext,\n type ActionRunContext,\n} from \"./types.ts\";\nimport { buildActionResource } from \"./conditions.ts\";\nimport { IGNORED_HEADERS } from \"./constants.ts\";\n\nexport const BuildHttpRequestContextOptionsSchema = z.object({\n method: z.string(),\n /** Raw URL string. Will be normalized with https:// if no protocol present. */\n url: z.string(),\n /** Raw headers from the request. Will be filtered through IGNORED_HEADERS. */\n headers: z\n .record(\n z.string(),\n z.union([z.string(), z.array(z.string()), z.undefined()]),\n )\n .optional(),\n /** Raw body string */\n body: z.string().nullable().optional(),\n /** Pre-parsed JSON body (e.g. from Fastify's automatic JSON parsing) */\n body_json: z.json().optional(),\n /** Connection ID associated with this request */\n connection_id: z.string().optional(),\n});\nexport type BuildHttpRequestContextOptions = z.infer<\n typeof BuildHttpRequestContextOptionsSchema\n>;\n\n/**\n * Build a canonical HttpRequestContext from raw request parts.\n *\n * This is the single source of truth for how HTTP request contexts are created.\n * Both sdkapi (for policy evaluation) and approvalsapi (for context storage)\n * should use this to ensure the context shape is consistent.\n *\n * Matches the behavior of createPolicyHttpRequest from @zapier/policy, with\n * the addition of header filtering through IGNORED_HEADERS.\n *\n * - Normalizes URL (adds https:// if missing) and parses into { scheme, host, port, path, query }\n * - Filters headers through IGNORED_HEADERS, lowercases keys, string values only\n * - Auto-parses body_json from body when content-type is JSON and body_json not provided\n * - body defaults to null (not undefined)\n */\nexport function buildHttpRequestContext(\n options: BuildHttpRequestContextOptions,\n): HttpRequestContext {\n // Validate options up-front so downstream string ops (e.g. method.toUpperCase)\n // see well-typed values. Mirrors the pattern in buildActionRunContext.\n const parsed = BuildHttpRequestContextOptionsSchema.parse(options);\n\n // Normalize URL — SDK CLI strips the protocol\n const rawUrl = parsed.url.includes(\"://\")\n ? parsed.url\n : `https://${parsed.url}`;\n const url = parseUrl(rawUrl);\n\n // Filter headers: exclude ignored, lowercase keys, string values only\n const headers: Record<string, string> = {};\n if (parsed.headers) {\n for (const [key, value] of Object.entries(parsed.headers)) {\n const lowerKey = key.toLowerCase();\n if (!IGNORED_HEADERS.has(lowerKey) && typeof value === \"string\") {\n headers[lowerKey] = value;\n }\n }\n }\n\n // Auto-parse body_json from body when content-type is JSON\n // (matches createPolicyHttpRequest behavior from @zapier/policy)\n let body_json: unknown = null;\n if (parsed.body_json !== undefined) {\n body_json = parsed.body_json;\n } else if (parsed.body) {\n const contentType = headers[\"content-type\"];\n const isJson =\n typeof contentType === \"string\" &&\n (contentType.includes(\"application/json\") ||\n (contentType.includes(\"application/\") &&\n contentType.includes(\"+json\")));\n if (isJson) {\n try {\n body_json = JSON.parse(parsed.body);\n } catch {\n // Invalid JSON body — leave body_json as null\n }\n }\n }\n\n return HttpRequestContextSchema.parse({\n request_type: \"http_request\",\n method: parsed.method.toUpperCase(),\n url,\n headers,\n body: parsed.body ?? null,\n body_json,\n connection_id: parsed.connection_id,\n });\n}\n\nexport const BuildActionRunContextOptionsSchema = z.object({\n selected_api: z.string().regex(ACTION_RESOURCE_SEGMENT_PATTERN, {\n message:\n \"selected_api must contain only [A-Za-z0-9._@+-] (no globs, slashes, or whitespace)\",\n }),\n action_type: ActionTypeSchema,\n action_key: z.string().regex(ACTION_KEY_SEGMENT_PATTERN, {\n message:\n \"action_key must contain only [A-Za-z0-9._@:+-] (no globs, slashes, or whitespace)\",\n }),\n connection_id: z.string().optional(),\n inputs: z.json().optional(),\n reason: z.string().optional(),\n});\nexport type BuildActionRunContextOptions = z.infer<\n typeof BuildActionRunContextOptionsSchema\n>;\n\n/**\n * Build a canonical ActionRunContext from raw action parts.\n *\n * Callers pass the three identity fields separately for readability;\n * this validates them and collapses them into the canonical `resource`\n * string the schema stores.\n */\nexport function buildActionRunContext(\n options: BuildActionRunContextOptions,\n): ActionRunContext {\n const parsed = BuildActionRunContextOptionsSchema.parse(options);\n return ActionRunContextSchema.parse({\n request_type: \"action_run\",\n resource: buildActionResource({\n selected_api: parsed.selected_api,\n action_type: parsed.action_type,\n action_key: parsed.action_key,\n }),\n connection_id: parsed.connection_id,\n inputs: parsed.inputs,\n reason: parsed.reason,\n });\n}\n","// ABOUTME: Builds policy conditions from stored request contexts.\n// ABOUTME: Used by approvalsapi's \"allow exact request\" and \"allow domain\" instant policy flows.\n\nimport type { Condition } from \"@zapier/policy-schema\";\nimport type {\n HttpRequestContext,\n ActionRunContext,\n ActionType,\n} from \"./types.ts\";\nimport { IGNORED_HEADERS } from \"./constants.ts\";\n\n/**\n * Build conditions that match an exact HTTP request.\n *\n * Handles the matches_url / query param split correctly:\n * - `matches_url` only supports scheme+host+port+path (no query string per spec)\n * - Query parameters are added as separate decomposed conditions on `url.query.<key>`\n *\n * @returns Condition[] for an http permission statement\n */\nexport function buildExactHttpConditions(\n context: HttpRequestContext,\n): Condition[] {\n const conditions: Condition[] = [\n { path: [\"method\"], operator: \"equals\", value: context.method },\n ];\n\n const { url } = context;\n\n // matches_url condition uses URL without query string (per @zapier/policy spec)\n const defaultPort =\n url.scheme === \"https\" ? 443 : url.scheme === \"http\" ? 80 : 0;\n const portString = url.port !== defaultPort ? `:${String(url.port)}` : \"\";\n const urlWithoutQuery = `${url.scheme}://${url.host}${portString}${url.path}`;\n conditions.push({\n path: [\"url\"],\n operator: \"matches_url\",\n value: urlWithoutQuery,\n });\n\n // Add decomposed conditions for each query parameter.\n for (const [key, values] of Object.entries(url.query)) {\n conditions.push({\n path: [\"url\", \"query\", key],\n operator: \"equals\",\n value: values,\n });\n }\n\n // body_json condition\n if (context.body_json !== null) {\n conditions.push({\n path: [\"body_json\"],\n operator: \"equals\",\n value: context.body_json,\n });\n } else if (context.body !== null) {\n // Non-JSON body (text/plain, XML, form-encoded): pin the raw body so\n // exact-match policies actually match the originating request.\n conditions.push({\n path: [\"body\"],\n operator: \"equals\",\n value: context.body,\n });\n }\n\n // Header conditions (filtered through IGNORED_HEADERS again for safety)\n for (const [key, value] of Object.entries(context.headers)) {\n if (!IGNORED_HEADERS.has(key.toLowerCase()) && typeof value === \"string\") {\n conditions.push({\n path: [\"headers\", key.toLowerCase()],\n operator: \"equals\",\n value,\n });\n }\n }\n\n return conditions;\n}\n\n/**\n * Build conditions that match any request to a given domain.\n * Uses the host from the parsed URL.\n *\n * @returns Condition[] for an http permission statement\n */\nexport function buildDomainHttpConditions(\n context: HttpRequestContext,\n): Condition[] {\n return [\n {\n path: [\"url\", \"host\"],\n operator: \"matches_host\",\n value: context.url.host,\n },\n ];\n}\n\n/**\n * Build conditions that match an exact action run (with inputs).\n *\n * @returns Condition[] for an action permission statement\n */\nexport function buildExactActionConditions(\n context: ActionRunContext,\n): Condition[] {\n const conditions: Condition[] = [];\n\n if (context.inputs !== undefined && context.inputs !== null) {\n conditions.push({\n path: [\"inputs\"],\n operator: \"equals\",\n value: context.inputs,\n });\n }\n\n return conditions;\n}\n\n/**\n * The three identity fields that compose an action resource string.\n */\nexport interface ActionResourceParts {\n selected_api: string;\n action_type: ActionType;\n action_key: string;\n}\n\n/**\n * Build the resource string for an action.\n * Format: action/{selected_api}/{action_type}/{action_key}\n */\nexport function buildActionResource(parts: ActionResourceParts): string {\n return `action/${parts.selected_api}/${parts.action_type}/${parts.action_key}`;\n}\n\n/**\n * Build a broad action resource that matches all actions of the same type\n * for an app (e.g. all reads, all writes). Scopes on `action_type` to\n * avoid silently granting cross-type access.\n *\n * Format: action/{selected_api}/{action_type}/{wildcard}\n */\nexport function buildBroadActionResource(\n parts: Pick<ActionResourceParts, \"selected_api\" | \"action_type\">,\n): string {\n return `action/${parts.selected_api}/${parts.action_type}/*`;\n}\n","// ABOUTME: Assembles complete Policy objects from request contexts.\n// ABOUTME: Single source of truth for \"exact request\" instant policies used by web UI and API.\n\nimport type { Policy, Statement } from \"@zapier/policy-schema\";\nimport type {\n RequestContext,\n HttpRequestContext,\n ActionRunContext,\n} from \"./types.ts\";\nimport {\n buildExactHttpConditions,\n buildExactActionConditions,\n} from \"./conditions.ts\";\n\n/**\n * Build a `can_use` authentication statement, if the context has a connection_id.\n */\nfunction buildAuthStatement(authenticationId: string): Statement {\n return {\n effect: \"allow\",\n permissions: [\"can_use\"],\n resources: [`connection/${authenticationId}`],\n conditions: [],\n };\n}\n\n/**\n * Build an exact-match policy from an HTTP request context.\n *\n * Produces a policy that allows only the specific request described by the context:\n * - `can_use` statement for the authentication (if present)\n * - `can_execute` statement for `http` with conditions from `buildExactHttpConditions`\n * plus a `keys_in` guard restricting allowed query parameter keys\n */\nfunction httpContextToPolicy(context: HttpRequestContext): Policy {\n const statements: Statement[] = [];\n\n if (context.connection_id) {\n statements.push(buildAuthStatement(context.connection_id));\n }\n\n const conditions = buildExactHttpConditions(context);\n\n // Add a keys_in guard so only the query param keys present in the original\n // request are allowed — blocks injection of extra query params.\n conditions.push({\n path: [\"url\", \"query\"],\n operator: \"keys_in\",\n value: Object.keys(context.url.query),\n });\n\n statements.push({\n effect: \"allow\",\n permissions: [\"can_execute\"],\n resources: [\"http\"],\n conditions,\n });\n\n return { version: 2, statements };\n}\n\n/**\n * Build an exact-match policy from an action run context.\n *\n * Produces a policy that allows only the specific action described by the context:\n * - `can_use` statement for the authentication (if present)\n * - `can_execute` statement for the action resource with input conditions\n */\nfunction actionContextToPolicy(context: ActionRunContext): Policy {\n const statements: Statement[] = [];\n\n if (context.connection_id) {\n statements.push(buildAuthStatement(context.connection_id));\n }\n\n statements.push({\n effect: \"allow\",\n permissions: [\"can_execute\"],\n resources: [context.resource],\n conditions: buildExactActionConditions(context),\n });\n\n return { version: 2, statements };\n}\n\n/**\n * Build an exact-match policy from any supported request context.\n *\n * This is the single source of truth for \"allow this exact request\" instant policies.\n * Used by the web UI and anywhere else that needs to produce an exact policy from a context.\n */\nexport function toExactPolicy(context: RequestContext): Policy {\n if (context.request_type === \"http_request\") {\n return httpContextToPolicy(context);\n }\n return actionContextToPolicy(context);\n}\n","// ABOUTME: Builds connection-level policies for the basic approvals MVP.\n// ABOUTME: Generates deterministic policies that allow read or read+write access scoped to a specific connection.\n\nimport { z } from \"zod\";\nimport type { Policy, Statement, Condition } from \"@zapier/policy-schema\";\nimport {\n globSelectedApiVersion,\n parseActionResource,\n type ActionType,\n type RequestContext,\n} from \"./types.ts\";\n\nexport const AccessLevelSchema = z.enum([\"read\", \"read_write\"]);\nexport type AccessLevel = z.infer<typeof AccessLevelSchema>;\n\n/** HTTP methods that count as side-effect-free reads for connection-level policies. */\nexport const READ_HTTP_METHODS = [\"GET\", \"HEAD\", \"OPTIONS\"] as const;\n\n/**\n * Action types that count as side-effect-free reads for connection-level\n * policies. `read_bulk` is the paginated/bulk variant of `read` — same\n * external API semantics, no mutations. Widely used by major apps (Slack,\n * Gmail, Jira, Salesforce, etc.) via the public `bulkReads` schema key.\n * `filter` and `run` are excluded: neither has a runtime executor for\n * external apps, and `filter` actions don't carry a connection_id anyway,\n * so this allowlist has no effect on them.\n */\nexport const READ_ACTION_TYPES = [\n \"read\",\n \"read_bulk\",\n \"search\",\n] as const satisfies readonly ActionType[];\n\nconst READ_HTTP_METHOD_SET: ReadonlySet<string> = new Set(READ_HTTP_METHODS);\nconst READ_ACTION_TYPE_SET: ReadonlySet<ActionType> = new Set(\n READ_ACTION_TYPES,\n);\n\n/**\n * Returns true when the request needs write access (i.e. it is NOT a\n * side-effect-free read). Mirrors the logic encoded in `buildConnectionPolicy`\n * so UI surfaces that gate the read-vs-read_write choice stay consistent\n * with the policies they generate.\n */\nexport function isWriteRequest(context: RequestContext): boolean {\n if (context.request_type === \"http_request\") {\n // Method is uppercase by construction (buildHttpRequestContext canonicalizes\n // it on the way in), so no normalization is needed here.\n return !READ_HTTP_METHOD_SET.has(context.method);\n }\n const { action_type } = parseActionResource(context.resource);\n return !READ_ACTION_TYPE_SET.has(action_type);\n}\n\n/**\n * Build a connection-level policy that covers both HTTP and action access.\n *\n * Always produces three statements:\n * 1. `can_use` for the authentication\n * 2. `can_execute` on `http` scoped by connection_id (+ method filter for read)\n * 3. `can_execute` on `action/{selectedApi}/{action_type}/*` per allowed type,\n * scoped by connection_id. For read access, the resource list expands to\n * one entry per read action_type so the engine matches via the resource\n * string rather than a separate `path: [\"action_type\"]` condition.\n */\nexport function buildConnectionPolicy(options: {\n connectionId: string;\n selectedApi: string;\n accessLevel: AccessLevel;\n}): Policy {\n const { connectionId, selectedApi, accessLevel } = options;\n\n const authStatement: Statement = {\n effect: \"allow\",\n permissions: [\"can_use\"],\n resources: [`connection/${connectionId}`],\n conditions: [],\n };\n\n const connectionCondition: Condition = {\n path: [\"connection_id\"],\n operator: \"equals\",\n value: connectionId,\n };\n\n const httpConditions: Condition[] = [connectionCondition];\n if (accessLevel === \"read\") {\n httpConditions.push({\n path: [\"method\"],\n operator: \"in\",\n value: [...READ_HTTP_METHODS],\n });\n }\n\n const httpStatement: Statement = {\n effect: \"allow\",\n permissions: [\"can_execute\"],\n resources: [\"http\"],\n conditions: httpConditions,\n };\n\n const apiPattern = globSelectedApiVersion(selectedApi);\n const actionResources =\n accessLevel === \"read\"\n ? READ_ACTION_TYPES.map((t) => `action/${apiPattern}/${t}/*`)\n : [`action/${apiPattern}/*/*`];\n\n const actionStatement: Statement = {\n effect: \"allow\",\n permissions: [\"can_execute\"],\n resources: actionResources,\n conditions: [connectionCondition],\n };\n\n return {\n version: 2,\n statements: [authStatement, httpStatement, actionStatement],\n };\n}\n","// ABOUTME: Builds connectionless approval policies bound to a domain (HTTP) or an action (action_run).\n// ABOUTME: Used when the smart-policy flag is off and the request has no connection_id.\n\nimport type { Policy, Statement, Condition } from \"@zapier/policy-schema\";\nimport {\n globSelectedApiVersion,\n parseActionResource,\n type RequestContext,\n} from \"./types.ts\";\nimport {\n READ_ACTION_TYPES,\n READ_HTTP_METHODS,\n type AccessLevel,\n} from \"./connection-policy.ts\";\n\n/**\n * Build a connectionless policy that scopes access to the request's domain\n * (HTTP) or its app (action_run). Mirrors the read/write semantics of\n * `buildConnectionPolicy` minus the auth statement and `connection_id`\n * condition, since there is no connection to bind to.\n */\nexport function buildConnectionlessPolicy(options: {\n context: RequestContext;\n accessLevel: AccessLevel;\n}): Policy {\n const { context, accessLevel } = options;\n\n if (context.request_type === \"http_request\") {\n const conditions: Condition[] = [\n {\n path: [\"url\", \"host\"],\n operator: \"matches_host\",\n value: context.url.host,\n },\n ];\n if (accessLevel === \"read\") {\n conditions.push({\n path: [\"method\"],\n operator: \"in\",\n value: [...READ_HTTP_METHODS],\n });\n }\n\n const statement: Statement = {\n effect: \"allow\",\n permissions: [\"can_execute\"],\n resources: [\"http\"],\n conditions,\n };\n return { version: 2, statements: [statement] };\n }\n\n const { selected_api } = parseActionResource(context.resource);\n const apiPattern = globSelectedApiVersion(selected_api);\n const resources =\n accessLevel === \"read\"\n ? READ_ACTION_TYPES.map((t) => `action/${apiPattern}/${t}/*`)\n : [`action/${apiPattern}/*/*`];\n\n const statement: Statement = {\n effect: \"allow\",\n permissions: [\"can_execute\"],\n resources,\n conditions: [],\n };\n return { version: 2, statements: [statement] };\n}\n"],"mappings":";AAGA,SAAS,SAAS;AAOX,IAAM,kBAAkB,EAC5B,OAAO;AAAA,EACN,QAAQ,EAAE,OAAO,EAAE,SAAS,0BAA0B;AAAA,EACtD,MAAM,EAAE,OAAO,EAAE,SAAS,kCAAkC;AAAA,EAC5D,MAAM,EACH,OAAO,EACP,IAAI,EACJ,SAAS,sDAAsD;AAAA,EAClE,MAAM,EAAE,OAAO,EAAE,SAAS,0BAA0B;AAAA,EACpD,OAAO,EACJ,OAAO,EAAE,OAAO,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC,EACtC,SAAS,iDAAiD;AAC/D,CAAC,EACA,KAAK;AAAA,EACJ,IAAI;AAAA,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;AAEA,UAAMC,aAAuB;AAAA,MAC3B,QAAQ;AAAA,MACR,aAAa,CAAC,aAAa;AAAA,MAC3B,WAAW,CAAC,MAAM;AAAA,MAClB;AAAA,IACF;AACA,WAAO,EAAE,SAAS,GAAG,YAAY,CAACA,UAAS,EAAE;AAAA,EAC/C;AAEA,QAAM,EAAE,aAAa,IAAI,oBAAoB,QAAQ,QAAQ;AAC7D,QAAM,aAAa,uBAAuB,YAAY;AACtD,QAAM,YACJ,gBAAgB,SACZ,kBAAkB,IAAI,CAAC,MAAM,UAAU,UAAU,IAAI,CAAC,IAAI,IAC1D,CAAC,UAAU,UAAU,MAAM;AAEjC,QAAM,YAAuB;AAAA,IAC3B,QAAQ;AAAA,IACR,aAAa,CAAC,aAAa;AAAA,IAC3B;AAAA,IACA,YAAY,CAAC;AAAA,EACf;AACA,SAAO,EAAE,SAAS,GAAG,YAAY,CAAC,SAAS,EAAE;AAC/C;","names":["z","z","z","z","statement"]}
1
+ {"version":3,"sources":["../src/types.ts","../src/constants.ts","../src/builders.ts","../src/conditions.ts","../src/policies.ts","../src/connection-policy.ts","../src/connectionless-policy.ts"],"sourcesContent":["// ABOUTME: Canonical request context types shared between sdkapi and approvalsapi.\n// ABOUTME: These define the contract for how requests are described in approval flows and policy evaluation.\n\nimport { z } from \"zod\";\n\n/**\n * Parsed URL components for policy evaluation.\n * Matches the ParsedUrl shape from @zapier/policy-schema so that\n * evaluatePolicy condition paths like [\"url\", \"host\"] resolve correctly.\n */\nexport const ParsedUrlSchema = z\n .object({\n scheme: z.string().describe('URL scheme, e.g. \"https\"'),\n host: z.string().describe('Hostname, e.g. \"api.example.com\"'),\n port: z\n .number()\n .int()\n .describe(\"Port number (defaults to 443 for https, 80 for http)\"),\n path: z.string().describe('URL path, e.g. \"/v1/foo\"'),\n query: z\n .record(z.string(), z.array(z.string()))\n .describe(\"Query parameters as key to string array mapping\"),\n })\n .meta({\n id: \"ParsedUrl\",\n description: \"Parsed URL components for policy condition matching\",\n });\nexport type ParsedUrl = z.infer<typeof ParsedUrlSchema>;\n\n/** Default ports by scheme, used when URL has no explicit port. */\nexport const DEFAULT_PORTS: Record<string, number> = {\n http: 80,\n https: 443,\n};\n\n/**\n * Parse a raw URL string into a ParsedUrl.\n * Same logic as parseUrlForPolicyContext in @zapier/policy.\n */\nexport function parseUrl(raw: string): ParsedUrl {\n const url = new URL(raw);\n const scheme = url.protocol.slice(0, -1).toLowerCase();\n const host = url.hostname.toLowerCase();\n const port = url.port ? parseInt(url.port, 10) : (DEFAULT_PORTS[scheme] ?? 0);\n const path = url.pathname || \"/\";\n const query: Record<string, string[]> = {};\n for (const [key, value] of url.searchParams) {\n if (!query[key]) {\n query[key] = [];\n }\n query[key].push(value);\n }\n return { scheme, host, port, path, query };\n}\n\n/**\n * Reconstruct a URL string from a ParsedUrl.\n * Same logic as buildUrl in @zapier/policy.\n */\nexport function buildUrlString(parsed: ParsedUrl): string {\n const { scheme, host, port, path, query } = parsed;\n const defaultPort = DEFAULT_PORTS[scheme];\n const portString = port !== defaultPort ? `:${String(port)}` : \"\";\n const params = new URLSearchParams();\n for (const [key, values] of Object.entries(query)) {\n for (const value of values) {\n params.append(key, value);\n }\n }\n const queryString = params.toString();\n return `${scheme}://${host}${portString}${path}${queryString ? \"?\" + queryString : \"\"}`;\n}\n\n/**\n * HTTP request context for approval/policy flows.\n * Sent by sdkapi when a relay request is denied, stored by approvalsapi,\n * and used for both policy evaluation and building policy conditions.\n *\n * The url field is a ParsedUrl object (matching @zapier/policy-schema's ParsedUrl)\n * so that evaluatePolicy conditions like [\"url\", \"host\"] resolve correctly.\n */\nexport const HttpRequestContextSchema = z\n .object({\n request_type: z\n .literal(\"http_request\")\n .describe(\"Context type discriminator\"),\n method: z\n .string()\n .max(10)\n .transform((m) => m.toUpperCase())\n .describe(\"HTTP method\"),\n /** Parsed URL components for policy condition matching */\n url: ParsedUrlSchema,\n /** Filtered headers (IGNORED_HEADERS excluded, keys lowercased) */\n headers: z\n .record(z.string(), z.string())\n .describe(\"Filtered headers (IGNORED_HEADERS excluded, keys lowercased)\"),\n /** Raw body string */\n body: z.string().max(65536).nullable().describe(\"Raw body string\"),\n /**\n * Parsed JSON body. Authored as `z.unknown().pipe(z.json())` so\n * the OpenAPI generator sees the outer `z.unknown()` and emits a\n * permissive field (no recursive `$ref`, no type), while the inner\n * `z.json()` still rejects non-JSON values (`Date`, `undefined`,\n * functions) at parse time. Same inferred `JsonValue` type either way.\n */\n body_json: z\n .unknown()\n .pipe(z.json())\n .nullable()\n .describe(\"Parsed JSON body (if applicable)\"),\n /** Zapier connection ID used for this request */\n connection_id: z\n .string()\n .max(255)\n .optional()\n .describe(\"Zapier connection ID used for this request\"),\n /** Optional human-readable reason for the request */\n reason: z\n .string()\n .max(1024)\n .optional()\n .describe(\"Optional human-readable reason for the request\"),\n })\n .meta({ id: \"HttpRequestContext\" });\nexport type HttpRequestContext = z.infer<typeof HttpRequestContextSchema>;\n\n/**\n * Canonical Zapier action types.\n *\n * Mirrors the `action_type` enum in sdkapi's OpenAPI spec\n * (`packages/openapi-spec/openapi.d.ts` `action_type`). Single source of\n * truth for any code that branches on or filters by action_type — keeps\n * `ActionRunContextSchema`, `BuildActionRunContextOptionsSchema`, and the\n * `READ_ACTION_TYPES` allowlist in `connection-policy.ts` aligned.\n */\nexport const ActionTypeSchema = z\n .enum([\n \"filter\",\n \"read\",\n \"read_bulk\",\n \"run\",\n \"search\",\n \"search_and_write\",\n \"search_or_write\",\n \"write\",\n ])\n .meta({ id: \"action_type\", description: \"Canonical Zapier action type.\" });\nexport type ActionType = z.infer<typeof ActionTypeSchema>;\n\n/**\n * Allowed character set for the `selected_api` segment of an action\n * resource. Blocks `*`, `/`, `:`, whitespace, and other glob/path\n * metacharacters that would otherwise widen policy scope. Permits at\n * most one `@`, which `globSelectedApiVersion` treats as the\n * version separator.\n */\nexport const ACTION_RESOURCE_SEGMENT_PATTERN =\n /^[A-Za-z0-9._+-]+(?:@[A-Za-z0-9._+-]+)?$/;\n\n/**\n * Allowed character set for the `action_key` segment of an action\n * resource. More permissive than `ACTION_RESOURCE_SEGMENT_PATTERN`\n * because sdkapi emits keys like `ae:358405` and `core:123abc` that\n * carry a namespace prefix separated by `:`. Still blocks `*`, `/`,\n * whitespace, and other glob/path metacharacters.\n */\nexport const ACTION_KEY_SEGMENT_PATTERN =\n /^[A-Za-z0-9._+:-]+(?:@[A-Za-z0-9._+:-]+)?$/;\n\n/**\n * Parse an action resource string of the form\n * `action/{selected_api}/{action_type}/{action_key}` into its parts.\n * Throws if the string doesn't match the canonical 4-segment shape or\n * if its `action_type` segment isn't one of the canonical 8 — every\n * action_run context that has been through `ActionRunContextSchema` is\n * guaranteed to parse cleanly, so a thrown error here means upstream\n * validation was bypassed.\n */\nexport function parseActionResource(resource: string): {\n selected_api: string;\n action_type: ActionType;\n action_key: string;\n} {\n const segments = resource.split(\"/\");\n if (segments.length !== 4 || segments[0] !== \"action\") {\n throw new Error(\n `action resource must be action/{selected_api}/{action_type}/{action_key}: got ${resource}`,\n );\n }\n const [, selectedApi, actionTypeRaw, actionKey] = segments;\n if (!selectedApi || !actionTypeRaw || !actionKey) {\n throw new Error(`action resource has empty segment: ${resource}`);\n }\n const actionType = ActionTypeSchema.safeParse(actionTypeRaw);\n if (!actionType.success) {\n throw new Error(\n `action resource has unknown action_type \"${actionTypeRaw}\": ${resource}`,\n );\n }\n if (!ACTION_RESOURCE_SEGMENT_PATTERN.test(selectedApi)) {\n throw new Error(\n `action resource has invalid selected_api segment \"${selectedApi}\": ${resource}`,\n );\n }\n if (!ACTION_KEY_SEGMENT_PATTERN.test(actionKey)) {\n throw new Error(\n `action resource has invalid action_key segment \"${actionKey}\": ${resource}`,\n );\n }\n return {\n selected_api: selectedApi,\n action_type: actionType.data,\n action_key: actionKey,\n };\n}\n\n/**\n * Strip the `@<version>` suffix from a `selected_api` / implementation\n * identifier. `Slack@1.0.0` → `Slack`. Passing a value without `@` is a\n * no-op. Used by UIs to render a human-friendly app key independent of\n * version, and by `globSelectedApiVersion` below.\n */\nexport function toAppKey(selectedApi: string): string {\n const at = selectedApi.indexOf(\"@\");\n return at === -1 ? selectedApi : selectedApi.slice(0, at);\n}\n\n/**\n * Replace the implementation-version suffix of a `selected_api` with a `@*`\n * wildcard so policies stay valid across version bumps. A runtime request\n * with `selected_api: \"App@2.7.3\"` matches a policy resource scoped to\n * `App@*` while still being distinguishable from a different app\n * (e.g. `App2@1.0.0`).\n *\n * No-op when the input has no `@` — assumed to be already version-less.\n */\nexport function globSelectedApiVersion(selectedApi: string): string {\n const at = selectedApi.indexOf(\"@\");\n return at === -1 ? selectedApi : selectedApi.slice(0, at) + \"@*\";\n}\n\n/**\n * Raw input shape for `ActionRunContextSchema`, before the transform that\n * canonicalizes legacy fields into `resource`. Exposed for the OpenAPI\n * schema generator (which can't represent transforms) — runtime callers\n * should use `ActionRunContextSchema`, which accepts either the canonical\n * `resource` field or the legacy `{selected_api, action_type, action_key}`\n * triple on input.\n */\nexport const ActionRunContextInputSchema = z\n .object({\n request_type: z\n .literal(\"action_run\")\n .describe(\"Context type discriminator\"),\n resource: z\n .string()\n .max(1024)\n .optional()\n .describe(\n \"Canonical action resource, e.g. action/Slack@1.0.0/write/send_message\",\n ),\n selected_api: z.string().max(255).optional().meta({\n deprecated: true,\n description:\n \"Legacy: app identifier, e.g. Slack@1.0.0. Prefer `resource`.\",\n }),\n action_type: ActionTypeSchema.optional().meta({\n deprecated: true,\n description: \"Legacy: canonical Zapier action type. Prefer `resource`.\",\n }),\n action_key: z.string().max(255).optional().meta({\n deprecated: true,\n description: \"Legacy: action key, e.g. send_message. Prefer `resource`.\",\n }),\n connection_id: z\n .string()\n .max(255)\n .optional()\n .describe(\"Zapier connection ID used for this request\"),\n /** Action input parameters. See body_json above for the pipe rationale. */\n inputs: z\n .unknown()\n .pipe(z.json())\n .optional()\n .describe(\"Action input parameters\"),\n reason: z\n .string()\n .max(1024)\n .optional()\n .describe(\"Optional human-readable reason for the request\"),\n })\n .meta({\n id: \"ActionRunContext\",\n description:\n \"Action run context. The canonical shape carries the action identity in a single `resource` field of the form `action/{selected_api}/{action_type}/{action_key}`. The legacy `{selected_api, action_type, action_key}` shape is also accepted on input during the migration window — approvalsapi normalizes it to the canonical form before storage.\",\n });\n\nexport const ActionRunContextSchema = ActionRunContextInputSchema.transform(\n (input, ctx) => {\n const resource =\n input.resource ??\n (input.selected_api && input.action_type && input.action_key\n ? `action/${input.selected_api}/${input.action_type}/${input.action_key}`\n : undefined);\n if (resource === undefined) {\n ctx.addIssue({\n code: \"custom\",\n message:\n \"action_run context requires either `resource` or all of `selected_api`/`action_type`/`action_key`\",\n });\n return z.NEVER;\n }\n try {\n parseActionResource(resource);\n } catch (err) {\n ctx.addIssue({\n code: \"custom\",\n message: err instanceof Error ? err.message : String(err),\n });\n return z.NEVER;\n }\n return {\n request_type: \"action_run\" as const,\n resource,\n ...(input.connection_id !== undefined && {\n connection_id: input.connection_id,\n }),\n ...(input.inputs !== undefined && { inputs: input.inputs }),\n ...(input.reason !== undefined && { reason: input.reason }),\n };\n },\n);\nexport type ActionRunContext = z.infer<typeof ActionRunContextSchema>;\n\n/**\n * Union of all request context types, keyed on `request_type`.\n *\n * Plain `z.union` (not `z.discriminatedUnion`) because\n * `ActionRunContextSchema` carries a `.transform` and discriminated\n * unions can't accept a `ZodEffects` member. The `request_type`\n * discriminator carried in `.meta()` below is read natively by the\n * OpenAPI generator (`@zapier/openapi-spec`), which emits it as\n * `anyOf` + discriminator that openapi-typescript and other codegen\n * targets render as a properly narrowed TS union.\n */\nexport const RequestContextSchema = z\n .union([HttpRequestContextSchema, ActionRunContextSchema])\n .meta({\n id: \"RequestContext\",\n description: \"Union of request context shapes, keyed on `request_type`.\",\n discriminator: {\n propertyName: \"request_type\",\n mapping: {\n http_request: \"#/components/schemas/HttpRequestContext\",\n action_run: \"#/components/schemas/ActionRunContext\",\n },\n },\n });\nexport type RequestContext = z.infer<typeof RequestContextSchema>;\n","// ABOUTME: Canonical set of headers to exclude when building request contexts.\n// ABOUTME: Shared between sdkapi (context creation) and approvalsapi (condition building).\n\n/**\n * Headers to exclude when building request contexts from raw HTTP requests.\n *\n * These are either sensitive (auth credentials), HTTP infrastructure headers\n * that vary per-request, or proxy-internal headers that are not meaningful\n * for policy decisions.\n */\nexport const IGNORED_HEADERS = new Set([\n // Auth / credentials — never include in contexts or policy conditions\n \"authorization\",\n \"x-relay-authorization\",\n \"x-relay-authentication-id\",\n \"x-api-key\",\n \"cookie\",\n \"set-cookie\",\n \"proxy-authorization\",\n\n // HTTP infrastructure — varies per-request, not policy-relevant\n \"host\",\n \"connection\",\n \"content-length\",\n \"transfer-encoding\",\n \"accept-encoding\",\n \"user-agent\",\n \"accept\",\n \"accept-language\",\n \"sec-fetch-mode\",\n\n // Proxy / forwarding — infrastructure, not meaningful for policy\n \"x-forwarded-for\",\n \"x-forwarded-host\",\n \"x-forwarded-proto\",\n \"x-real-ip\",\n\n // Proxy internal — sdkapi-specific headers\n \"x-is-interactive-session\",\n \"x-relay-callback-url\",\n // Subsumed by isIgnoredHeader's x-zapier- prefix rule; kept for byte-parity\n // with the approvalsapi source and for consumers reading the set directly.\n \"x-zapier-approval-token\",\n]);\n\nexport function isIgnoredHeader(name: string): boolean {\n const normalized = name.toLowerCase();\n return (\n IGNORED_HEADERS.has(normalized) ||\n normalized.startsWith(\"zapier-\") ||\n normalized.startsWith(\"x-zapier-\")\n );\n}\n","// ABOUTME: Canonical builders for creating request contexts from raw request parts.\n// ABOUTME: Used by sdkapi to build both approval contexts and policy eval contexts.\n\nimport { z } from \"zod\";\nimport {\n HttpRequestContextSchema,\n ActionRunContextSchema,\n ActionTypeSchema,\n parseUrl,\n ACTION_RESOURCE_SEGMENT_PATTERN,\n ACTION_KEY_SEGMENT_PATTERN,\n type HttpRequestContext,\n type ActionRunContext,\n} from \"./types.ts\";\nimport { buildActionResource } from \"./conditions.ts\";\nimport { isIgnoredHeader } from \"./constants.ts\";\n\nexport const BuildHttpRequestContextOptionsSchema = z.object({\n method: z.string(),\n /** Raw URL string. Will be normalized with https:// if no protocol present. */\n url: z.string(),\n /** Raw headers from the request. Will be filtered through isIgnoredHeader. */\n headers: z\n .record(\n z.string(),\n z.union([z.string(), z.array(z.string()), z.undefined()]),\n )\n .optional(),\n /** Raw body string */\n body: z.string().nullable().optional(),\n /** Pre-parsed JSON body (e.g. from Fastify's automatic JSON parsing) */\n body_json: z.json().optional(),\n /** Connection ID associated with this request */\n connection_id: z.string().optional(),\n});\nexport type BuildHttpRequestContextOptions = z.infer<\n typeof BuildHttpRequestContextOptionsSchema\n>;\n\n/**\n * Build a canonical HttpRequestContext from raw request parts.\n *\n * This is the single source of truth for how HTTP request contexts are created.\n * Both sdkapi (for policy evaluation) and approvalsapi (for context storage)\n * should use this to ensure the context shape is consistent.\n *\n * Matches the behavior of createPolicyHttpRequest from @zapier/policy, with\n * two additions: header filtering through isIgnoredHeader, and body/body_json\n * exclusivity (createPolicyHttpRequest keeps the raw body alongside body_json).\n *\n * - Normalizes URL (adds https:// if missing) and parses into { scheme, host, port, path, query }\n * - Filters headers through isIgnoredHeader (IGNORED_HEADERS set plus\n * zapier-* / x-zapier-* prefixes), lowercases keys, string values only\n * - Auto-parses body_json from body when content-type is JSON and body_json not provided\n * - Exactly one of body / body_json is populated: body is null whenever\n * body_json is set; both default to null (not undefined)\n */\nexport function buildHttpRequestContext(\n options: BuildHttpRequestContextOptions,\n): HttpRequestContext {\n // Validate options up-front so downstream string ops (e.g. method.toUpperCase)\n // see well-typed values. Mirrors the pattern in buildActionRunContext.\n const parsed = BuildHttpRequestContextOptionsSchema.parse(options);\n\n // Normalize URL — SDK CLI strips the protocol\n const rawUrl = parsed.url.includes(\"://\")\n ? parsed.url\n : `https://${parsed.url}`;\n const url = parseUrl(rawUrl);\n\n // Filter headers: exclude ignored, lowercase keys, string values only\n const headers: Record<string, string> = {};\n if (parsed.headers) {\n for (const [key, value] of Object.entries(parsed.headers)) {\n const lowerKey = key.toLowerCase();\n if (!isIgnoredHeader(lowerKey) && typeof value === \"string\") {\n headers[lowerKey] = value;\n }\n }\n }\n\n // Auto-parse body_json from body when content-type is JSON\n // (matches createPolicyHttpRequest behavior from @zapier/policy)\n let body_json: unknown = null;\n if (parsed.body_json !== undefined) {\n body_json = parsed.body_json;\n } else if (parsed.body) {\n const contentType = headers[\"content-type\"];\n const isJson =\n typeof contentType === \"string\" &&\n (contentType.includes(\"application/json\") ||\n (contentType.includes(\"application/\") &&\n contentType.includes(\"+json\")));\n if (isJson) {\n try {\n body_json = JSON.parse(parsed.body);\n } catch {\n // Invalid JSON body — leave body_json as null\n }\n }\n }\n\n return HttpRequestContextSchema.parse({\n request_type: \"http_request\",\n method: parsed.method.toUpperCase(),\n url,\n headers,\n body: body_json === null ? (parsed.body ?? null) : null,\n body_json,\n connection_id: parsed.connection_id,\n });\n}\n\nexport const BuildActionRunContextOptionsSchema = z.object({\n selected_api: z.string().regex(ACTION_RESOURCE_SEGMENT_PATTERN, {\n message:\n \"selected_api must contain only [A-Za-z0-9._@+-] (no globs, slashes, or whitespace)\",\n }),\n action_type: ActionTypeSchema,\n action_key: z.string().regex(ACTION_KEY_SEGMENT_PATTERN, {\n message:\n \"action_key must contain only [A-Za-z0-9._@:+-] (no globs, slashes, or whitespace)\",\n }),\n connection_id: z.string().optional(),\n inputs: z.json().optional(),\n reason: z.string().optional(),\n});\nexport type BuildActionRunContextOptions = z.infer<\n typeof BuildActionRunContextOptionsSchema\n>;\n\n/**\n * Build a canonical ActionRunContext from raw action parts.\n *\n * Callers pass the three identity fields separately for readability;\n * this validates them and collapses them into the canonical `resource`\n * string the schema stores.\n */\nexport function buildActionRunContext(\n options: BuildActionRunContextOptions,\n): ActionRunContext {\n const parsed = BuildActionRunContextOptionsSchema.parse(options);\n return ActionRunContextSchema.parse({\n request_type: \"action_run\",\n resource: buildActionResource({\n selected_api: parsed.selected_api,\n action_type: parsed.action_type,\n action_key: parsed.action_key,\n }),\n connection_id: parsed.connection_id,\n inputs: parsed.inputs,\n reason: parsed.reason,\n });\n}\n","// ABOUTME: Builds policy conditions from stored request contexts.\n// ABOUTME: Used by approvalsapi's \"allow exact request\" and \"allow domain\" instant policy flows.\n\nimport type { Condition } from \"@zapier/policy-schema\";\nimport type {\n HttpRequestContext,\n ActionRunContext,\n ActionType,\n} from \"./types.ts\";\nimport { isIgnoredHeader } from \"./constants.ts\";\n\n/**\n * Build conditions that match an exact HTTP request.\n *\n * Handles the matches_url / query param split correctly:\n * - `matches_url` only supports scheme+host+port+path (no query string per spec)\n * - Query parameters are added as separate decomposed conditions on `url.query.<key>`\n *\n * @returns Condition[] for an http permission statement\n */\nexport function buildExactHttpConditions(\n context: HttpRequestContext,\n): Condition[] {\n const conditions: Condition[] = [\n { path: [\"method\"], operator: \"equals\", value: context.method },\n ];\n\n const { url } = context;\n\n // matches_url condition uses URL without query string (per @zapier/policy spec)\n const defaultPort =\n url.scheme === \"https\" ? 443 : url.scheme === \"http\" ? 80 : 0;\n const portString = url.port !== defaultPort ? `:${String(url.port)}` : \"\";\n const urlWithoutQuery = `${url.scheme}://${url.host}${portString}${url.path}`;\n conditions.push({\n path: [\"url\"],\n operator: \"matches_url\",\n value: urlWithoutQuery,\n });\n\n // Add decomposed conditions for each query parameter.\n for (const [key, values] of Object.entries(url.query)) {\n conditions.push({\n path: [\"url\", \"query\", key],\n operator: \"equals\",\n value: values,\n });\n }\n\n // body_json condition\n if (context.body_json !== null) {\n conditions.push({\n path: [\"body_json\"],\n operator: \"equals\",\n value: context.body_json,\n });\n } else if (context.body !== null) {\n // Non-JSON body (text/plain, XML, form-encoded): pin the raw body so\n // exact-match policies actually match the originating request.\n conditions.push({\n path: [\"body\"],\n operator: \"equals\",\n value: context.body,\n });\n }\n\n // Header conditions (filtered through isIgnoredHeader again for safety)\n for (const [key, value] of Object.entries(context.headers)) {\n if (!isIgnoredHeader(key) && typeof value === \"string\") {\n conditions.push({\n path: [\"headers\", key.toLowerCase()],\n operator: \"equals\",\n value,\n });\n }\n }\n\n return conditions;\n}\n\n/**\n * Build conditions that match any request to a given domain.\n * Uses the host from the parsed URL.\n *\n * @returns Condition[] for an http permission statement\n */\nexport function buildDomainHttpConditions(\n context: HttpRequestContext,\n): Condition[] {\n return [\n {\n path: [\"url\", \"host\"],\n operator: \"matches_host\",\n value: context.url.host,\n },\n ];\n}\n\n/**\n * Build conditions that match an exact action run (with inputs).\n *\n * @returns Condition[] for an action permission statement\n */\nexport function buildExactActionConditions(\n context: ActionRunContext,\n): Condition[] {\n const conditions: Condition[] = [];\n\n if (context.inputs !== undefined && context.inputs !== null) {\n conditions.push({\n path: [\"inputs\"],\n operator: \"equals\",\n value: context.inputs,\n });\n }\n\n return conditions;\n}\n\n/**\n * The three identity fields that compose an action resource string.\n */\nexport interface ActionResourceParts {\n selected_api: string;\n action_type: ActionType;\n action_key: string;\n}\n\n/**\n * Build the resource string for an action.\n * Format: action/{selected_api}/{action_type}/{action_key}\n */\nexport function buildActionResource(parts: ActionResourceParts): string {\n return `action/${parts.selected_api}/${parts.action_type}/${parts.action_key}`;\n}\n\n/**\n * Build a broad action resource that matches all actions of the same type\n * for an app (e.g. all reads, all writes). Scopes on `action_type` to\n * avoid silently granting cross-type access.\n *\n * Format: action/{selected_api}/{action_type}/{wildcard}\n */\nexport function buildBroadActionResource(\n parts: Pick<ActionResourceParts, \"selected_api\" | \"action_type\">,\n): string {\n return `action/${parts.selected_api}/${parts.action_type}/*`;\n}\n","// ABOUTME: Assembles complete Policy objects from request contexts.\n// ABOUTME: Single source of truth for \"exact request\" instant policies used by web UI and API.\n\nimport type { Policy, Statement } from \"@zapier/policy-schema\";\nimport type {\n RequestContext,\n HttpRequestContext,\n ActionRunContext,\n} from \"./types.ts\";\nimport {\n buildExactHttpConditions,\n buildExactActionConditions,\n} from \"./conditions.ts\";\n\n/**\n * Build a `can_use` authentication statement, if the context has a connection_id.\n */\nfunction buildAuthStatement(authenticationId: string): Statement {\n return {\n effect: \"allow\",\n permissions: [\"can_use\"],\n resources: [`connection/${authenticationId}`],\n conditions: [],\n };\n}\n\n/**\n * Build an exact-match policy from an HTTP request context.\n *\n * Produces a policy that allows only the specific request described by the context:\n * - `can_use` statement for the authentication (if present)\n * - `can_execute` statement for `http` with conditions from `buildExactHttpConditions`\n * plus a `keys_in` guard restricting allowed query parameter keys\n */\nfunction httpContextToPolicy(context: HttpRequestContext): Policy {\n const statements: Statement[] = [];\n\n if (context.connection_id) {\n statements.push(buildAuthStatement(context.connection_id));\n }\n\n const conditions = buildExactHttpConditions(context);\n\n // Add a keys_in guard so only the query param keys present in the original\n // request are allowed — blocks injection of extra query params.\n conditions.push({\n path: [\"url\", \"query\"],\n operator: \"keys_in\",\n value: Object.keys(context.url.query),\n });\n\n statements.push({\n effect: \"allow\",\n permissions: [\"can_execute\"],\n resources: [\"http\"],\n conditions,\n });\n\n return { version: 2, statements };\n}\n\n/**\n * Build an exact-match policy from an action run context.\n *\n * Produces a policy that allows only the specific action described by the context:\n * - `can_use` statement for the authentication (if present)\n * - `can_execute` statement for the action resource with input conditions\n */\nfunction actionContextToPolicy(context: ActionRunContext): Policy {\n const statements: Statement[] = [];\n\n if (context.connection_id) {\n statements.push(buildAuthStatement(context.connection_id));\n }\n\n statements.push({\n effect: \"allow\",\n permissions: [\"can_execute\"],\n resources: [context.resource],\n conditions: buildExactActionConditions(context),\n });\n\n return { version: 2, statements };\n}\n\n/**\n * Build an exact-match policy from any supported request context.\n *\n * This is the single source of truth for \"allow this exact request\" instant policies.\n * Used by the web UI and anywhere else that needs to produce an exact policy from a context.\n */\nexport function toExactPolicy(context: RequestContext): Policy {\n if (context.request_type === \"http_request\") {\n return httpContextToPolicy(context);\n }\n return actionContextToPolicy(context);\n}\n","// ABOUTME: Builds connection-level policies for the basic approvals MVP.\n// ABOUTME: Generates deterministic policies that allow read or read+write access scoped to a specific connection.\n\nimport { z } from \"zod\";\nimport type { Policy, Statement, Condition } from \"@zapier/policy-schema\";\nimport {\n globSelectedApiVersion,\n parseActionResource,\n type ActionType,\n type RequestContext,\n} from \"./types.ts\";\n\nexport const AccessLevelSchema = z.enum([\"read\", \"read_write\"]);\nexport type AccessLevel = z.infer<typeof AccessLevelSchema>;\n\n/** HTTP methods that count as side-effect-free reads for connection-level policies. */\nexport const READ_HTTP_METHODS = [\"GET\", \"HEAD\", \"OPTIONS\"] as const;\n\n/**\n * Action types that count as side-effect-free reads for connection-level\n * policies. `read_bulk` is the paginated/bulk variant of `read` — same\n * external API semantics, no mutations. Widely used by major apps (Slack,\n * Gmail, Jira, Salesforce, etc.) via the public `bulkReads` schema key.\n * `filter` and `run` are excluded: neither has a runtime executor for\n * external apps, and `filter` actions don't carry a connection_id anyway,\n * so this allowlist has no effect on them.\n */\nexport const READ_ACTION_TYPES = [\n \"read\",\n \"read_bulk\",\n \"search\",\n] as const satisfies readonly ActionType[];\n\nconst READ_HTTP_METHOD_SET: ReadonlySet<string> = new Set(READ_HTTP_METHODS);\nconst READ_ACTION_TYPE_SET: ReadonlySet<ActionType> = new Set(\n READ_ACTION_TYPES,\n);\n\n/**\n * Returns true when the request needs write access (i.e. it is NOT a\n * side-effect-free read). Mirrors the logic encoded in `buildConnectionPolicy`\n * so UI surfaces that gate the read-vs-read_write choice stay consistent\n * with the policies they generate.\n */\nexport function isWriteRequest(context: RequestContext): boolean {\n if (context.request_type === \"http_request\") {\n // Method is uppercase by construction (buildHttpRequestContext canonicalizes\n // it on the way in), so no normalization is needed here.\n return !READ_HTTP_METHOD_SET.has(context.method);\n }\n const { action_type } = parseActionResource(context.resource);\n return !READ_ACTION_TYPE_SET.has(action_type);\n}\n\n/**\n * Build a connection-level policy that covers both HTTP and action access.\n *\n * Always produces three statements:\n * 1. `can_use` for the authentication\n * 2. `can_execute` on `http` scoped by connection_id (+ method filter for read)\n * 3. `can_execute` on `action/{selectedApi}/{action_type}/*` per allowed type,\n * scoped by connection_id. For read access, the resource list expands to\n * one entry per read action_type so the engine matches via the resource\n * string rather than a separate `path: [\"action_type\"]` condition.\n */\nexport function buildConnectionPolicy(options: {\n connectionId: string;\n selectedApi: string;\n accessLevel: AccessLevel;\n}): Policy {\n const { connectionId, selectedApi, accessLevel } = options;\n\n const authStatement: Statement = {\n effect: \"allow\",\n permissions: [\"can_use\"],\n resources: [`connection/${connectionId}`],\n conditions: [],\n };\n\n const connectionCondition: Condition = {\n path: [\"connection_id\"],\n operator: \"equals\",\n value: connectionId,\n };\n\n const httpConditions: Condition[] = [connectionCondition];\n if (accessLevel === \"read\") {\n httpConditions.push({\n path: [\"method\"],\n operator: \"in\",\n value: [...READ_HTTP_METHODS],\n });\n }\n\n const httpStatement: Statement = {\n effect: \"allow\",\n permissions: [\"can_execute\"],\n resources: [\"http\"],\n conditions: httpConditions,\n };\n\n const apiPattern = globSelectedApiVersion(selectedApi);\n const actionResources =\n accessLevel === \"read\"\n ? READ_ACTION_TYPES.map((t) => `action/${apiPattern}/${t}/*`)\n : [`action/${apiPattern}/*/*`];\n\n const actionStatement: Statement = {\n effect: \"allow\",\n permissions: [\"can_execute\"],\n resources: actionResources,\n conditions: [connectionCondition],\n };\n\n return {\n version: 2,\n statements: [authStatement, httpStatement, actionStatement],\n };\n}\n","// ABOUTME: Builds connectionless approval policies bound to a domain (HTTP) or an action (action_run).\n// ABOUTME: Used when the smart-policy flag is off and the request has no connection_id.\n\nimport type { Policy, Statement, Condition } from \"@zapier/policy-schema\";\nimport {\n globSelectedApiVersion,\n parseActionResource,\n type RequestContext,\n} from \"./types.ts\";\nimport {\n READ_ACTION_TYPES,\n READ_HTTP_METHODS,\n type AccessLevel,\n} from \"./connection-policy.ts\";\n\n/**\n * Build a connectionless policy that scopes access to the request's domain\n * (HTTP) or its app (action_run). Mirrors the read/write semantics of\n * `buildConnectionPolicy` minus the auth statement and `connection_id`\n * condition, since there is no connection to bind to.\n */\nexport function buildConnectionlessPolicy(options: {\n context: RequestContext;\n accessLevel: AccessLevel;\n}): Policy {\n const { context, accessLevel } = options;\n\n if (context.request_type === \"http_request\") {\n const conditions: Condition[] = [\n {\n path: [\"url\", \"host\"],\n operator: \"matches_host\",\n value: context.url.host,\n },\n ];\n if (accessLevel === \"read\") {\n conditions.push({\n path: [\"method\"],\n operator: \"in\",\n value: [...READ_HTTP_METHODS],\n });\n }\n\n const statement: Statement = {\n effect: \"allow\",\n permissions: [\"can_execute\"],\n resources: [\"http\"],\n conditions,\n };\n return { version: 2, statements: [statement] };\n }\n\n const { selected_api } = parseActionResource(context.resource);\n const apiPattern = globSelectedApiVersion(selected_api);\n const resources =\n accessLevel === \"read\"\n ? READ_ACTION_TYPES.map((t) => `action/${apiPattern}/${t}/*`)\n : [`action/${apiPattern}/*/*`];\n\n const statement: Statement = {\n effect: \"allow\",\n permissions: [\"can_execute\"],\n resources,\n conditions: [],\n };\n return { version: 2, statements: [statement] };\n}\n"],"mappings":";AAGA,SAAS,SAAS;AAOX,IAAM,kBAAkB,EAC5B,OAAO;AAAA,EACN,QAAQ,EAAE,OAAO,EAAE,SAAS,0BAA0B;AAAA,EACtD,MAAM,EAAE,OAAO,EAAE,SAAS,kCAAkC;AAAA,EAC5D,MAAM,EACH,OAAO,EACP,IAAI,EACJ,SAAS,sDAAsD;AAAA,EAClE,MAAM,EAAE,OAAO,EAAE,SAAS,0BAA0B;AAAA,EACpD,OAAO,EACJ,OAAO,EAAE,OAAO,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,CAAC,EACtC,SAAS,iDAAiD;AAC/D,CAAC,EACA,KAAK;AAAA,EACJ,IAAI;AAAA,EACJ,aAAa;AACf,CAAC;AAII,IAAM,gBAAwC;AAAA,EACnD,MAAM;AAAA,EACN,OAAO;AACT;AAMO,SAAS,SAAS,KAAwB;AAC/C,QAAM,MAAM,IAAI,IAAI,GAAG;AACvB,QAAM,SAAS,IAAI,SAAS,MAAM,GAAG,EAAE,EAAE,YAAY;AACrD,QAAM,OAAO,IAAI,SAAS,YAAY;AACtC,QAAM,OAAO,IAAI,OAAO,SAAS,IAAI,MAAM,EAAE,IAAK,cAAc,MAAM,KAAK;AAC3E,QAAM,OA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AS,EAAE;AAAA,EAC/C;AAEA,QAAM,EAAE,aAAa,IAAI,oBAAoB,QAAQ,QAAQ;AAC7D,QAAM,aAAa,uBAAuB,YAAY;AACtD,QAAM,YACJ,gBAAgB,SACZ,kBAAkB,IAAI,CAAC,MAAM,UAAU,UAAU,IAAI,CAAC,IAAI,IAC1D,CAAC,UAAU,UAAU,MAAM;AAEjC,QAAM,YAAuB;AAAA,IAC3B,QAAQ;AAAA,IACR,aAAa,CAAC,aAAa;AAAA,IAC3B;AAAA,IACA,YAAY,CAAC;AAAA,EACf;AACA,SAAO,EAAE,SAAS,GAAG,YAAY,CAAC,SAAS,EAAE;AAC/C;","names":["z","z","z","z","statement"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@zapier/policy-context",
3
- "version": "1.3.0-mr.6.c3a1f51e",
3
+ "version": "2.0.0",
4
4
  "description": "Shared request-context types, builders, and policy condition generators — the canonical encoding of a request (HTTP, action, connection) into the shape the policy engine expects.",
5
5
  "license": "SEE LICENSE IN LICENSE",
6
6
  "repository": {