{"version":3,"file":"policy.mjs","names":[],"sources":["../../../node_modules/.pnpm/tsdown@0.23.0_@typescript+typescript6@6.0.2_oxc-resolver@11.24.2_tsx@4.21.0_unrun@0.3.1/node_modules/tsdown/esm-shims.js","../src/cedar-nesting.ts","../src/policy-evaluator.ts"],"sourcesContent":["// Shim globals in esm bundle\nimport path from 'node:path'\nimport { fileURLToPath } from 'node:url'\n\nconst getFilename = () => fileURLToPath(import.meta.url)\nconst getDirname = () => path.dirname(getFilename())\n\nexport const __dirname = /* @__PURE__ */ getDirname()\nexport const __filename = /* @__PURE__ */ getFilename()\n","export const REJECTED_POLICY_PREFIX = 'PolicyEvaluator construction failed: malformed policy';\nexport const MAX_CEDAR_NESTING = 32;\n\nconst isWordChar = (char: string | undefined): boolean => char !== undefined && /\\w/.test(char);\n\nexport function cedarNestingDepth(cedar: string): number {\n  const conditionals = [0];\n  let depth = 0;\n  let deepest = 0;\n  for (let i = 0; i < cedar.length; i++) {\n    const char = cedar[i];\n    if (char === '\"') {\n      i++;\n      while (i < cedar.length && cedar[i] !== '\"') i += cedar[i] === '\\\\' ? 2 : 1;\n    } else if (char === '/' && cedar[i + 1] === '/') {\n      while (i < cedar.length && cedar[i] !== '\\n' && cedar[i] !== '\\r') i++;\n    } else if (char === '(' || char === '[' || char === '{') {\n      conditionals.push(0);\n      deepest = Math.max(deepest, ++depth);\n    } else if (char === ')' || char === ']' || char === '}') {\n      if (conditionals.length > 1) depth -= 1 + conditionals.pop()!;\n    } else if (char === ',') {\n      depth -= conditionals[conditionals.length - 1];\n      conditionals[conditionals.length - 1] = 0;\n    } else if (\n      char === 'i' &&\n      cedar[i + 1] === 'f' &&\n      !isWordChar(cedar[i - 1]) &&\n      !isWordChar(cedar[i + 2])\n    ) {\n      conditionals[conditionals.length - 1]++;\n      deepest = Math.max(deepest, ++depth);\n    }\n  }\n  return deepest;\n}\n\nexport function cedarNestingError(cedar: string): string | undefined {\n  return cedarNestingDepth(cedar) > MAX_CEDAR_NESTING\n    ? `nested deeper than ${MAX_CEDAR_NESTING} levels`\n    : undefined;\n}\n\nexport function assertCedarNesting(cedar: string): void {\n  const error = cedarNestingError(cedar);\n  if (error !== undefined) throw new Error(`${REJECTED_POLICY_PREFIX}: ${error}`);\n}\n","/**\n * Cedar policy-evaluator bridge — Node fallback.\n *\n * Surfaces the `PolicyEvaluator` class exported by the cedar-enabled\n * `kya-os-engine` WASM artifact (built by\n * `rust/scripts/build-engine-cedar-wasm.sh`, gated on the Rust\n * `wasm,cedar` features). A JS host (the gateway) compiles a tenant\n * policy bundle once and authorizes many requests against it in-process,\n * with no round-trip to a separate policy service.\n *\n * The cedar artifact is a SEPARATE, larger binary than the lean\n * detection artifact — it pulls in `cedar-policy`. Detection-only\n * consumers load `./engine` (the lean `verify()` glue); only callers that\n * need in-process authorization reach for this bridge.\n *\n * ## Lazy loading\n *\n * The cedar `--target nodejs` glue instantiates the ~2 MB cedar WASM the\n * moment it is `require`d (it `fs.readFileSync`s its `.wasm` sibling at\n * module load). To keep the separate-artifact promise — detection-only\n * consumers must NOT pay cedar's memory/startup — the glue is loaded\n * LAZILY: nothing happens on `import`; the artifact is `require`d (and\n * memoised) only on the first {@link createPolicyEvaluator} call. This is\n * also why cedar lives behind the dedicated `./policy` subpath and is NOT\n * re-exported from the `./node` barrel.\n *\n * `createRequire(__filename)` resolves the glue at call time in both\n * builds — native `require` under CJS, the tsup `shims` / `createRequire`\n * banner under ESM. The glue stays external (regex\n * `wasm/kya-os-engine-cedar/` in tsup's `commonOpts.external`), so its\n * `__dirname` resolves against the `wasm/kya-os-engine-cedar/` directory\n * where the `.wasm` lives, and `\"type\": \"commonjs\"` on the artifact's\n * package.json keeps Node from throwing `ERR_REQUIRE_ESM`.\n *\n * The specifier is RELATIVE (`../wasm/...`), not the package's own name.\n * It used to be `@kya-os/checkpoint-wasm-runtime/wasm/...`, which works\n * in a normal install only via Node's package self-reference — and self-\n * reference needs to find this package's `package.json` by walking up\n * from `__filename`, or a `node_modules/@kya-os/checkpoint-wasm-runtime`\n * entry. Neither survives Vercel's output-file tracing: the lambda gets\n * `packages/checkpoint-wasm-runtime/dist/policy.mjs` copied under\n * `/var/task` WITHOUT the sibling `package.json` and without a\n * node_modules link, so every `/api/v1/enforce` call on kya.vouched.id\n * failed with `Cannot find module '@kya-os/checkpoint-wasm-runtime/wasm/\n * kya-os-engine-cedar/kya_os_engine.js'` and fell back to the bespoke\n * decision — Cedar was never evaluated in production. (The bare specifier\n * in that message is the tell: when self-reference DOES resolve and only\n * the file is missing, Node reports the resolved absolute path instead.)\n * A relative specifier resolves purely by path from `__filename`, so it\n * depends on nothing but the two directories travelling together — which\n * `files: [\"dist\", \"wasm\"]` guarantees for npm consumers, and which is\n * also statically analyzable by `@vercel/nft`. `src/` and `dist/` are\n * both exactly one level under the package root, so `../wasm/...` is\n * correct from either.\n *\n * Direct .wasm path (for callers building their own loaders):\n *   `@kya-os/checkpoint-wasm-runtime/wasm/kya-os-engine-cedar/kya_os_engine_bg.wasm`\n */\n\nimport { createRequire } from 'node:module';\n\nimport { assertCedarNesting, cedarNestingError } from './cedar-nesting';\nimport type { Decision } from './engine/types';\nimport type { AssuranceTier } from '@kya-os/checkpoint-shared';\n\nexport type { Decision, BlockReason } from './engine/types';\n\n/**\n * Owned, plain-data request the host hands to\n * {@link PolicyEvaluatorRuntime.authorize}. Mirrors the Rust\n * `AuthorizeInput` (`rust/crates/kya-os-engine/src/policy/authorize.rs`);\n * keys are camelCase across the wasm-bindgen boundary, matching every\n * other engine wire type.\n *\n * The evaluator is **synchronous over pre-resolved facts** (H-1 Kickoff\n * § 4.5): the host pre-fetches the agent's delegation chain, reputation,\n * etc. and ships the results here — no JS callbacks cross the boundary.\n *\n * `agentDid` and `reputation` are optional (omit or pass `undefined` for\n * an anonymous or reputation-less request); `grantedScopes` defaults to an\n * empty list when omitted.\n *\n * The attribute-based facts — `name`, `category`, `delegation`, `path` —\n * are optional too. They populate the principal / resource entity\n * attributes (`principal.name`, `principal.category`,\n * `principal.delegation`, `resource.path`) that attribute-based Cedar\n * policies reference. When omitted, the engine fills each with its default\n * (`\"\"` for strings) so a policy comparing them evaluates to `false`\n * instead of erroring on an undefined attribute.\n */\nexport interface AuthorizeInput {\n  /** Server-owned application permission for this authenticated user/operation.\n   * Never accept from request JSON, headers, classification, or clearance. */\n  applicationAuthorized?: boolean;\n  /** Agent DID if identity has been established, otherwise omitted. */\n  agentDid?: string;\n  /** Exact user DID asserted by a verified delegation issuer; not merchant IAM. */\n  authorizingUserDid?: string;\n  /** The action being requested (e.g., `\"book_flight\"`). */\n  action: string;\n  /** The resource being acted on (e.g., `\"travel_api\"`). */\n  resource: string;\n  /** Scopes granted by the agent's delegation chain. Defaults to `[]`. */\n  grantedScopes?: string[];\n  /** Agent's reputation score in `[0.0, 1.0]`, if computed. */\n  reputation?: number;\n  /** Tenant identifier. */\n  tenantId: string;\n  /** Known-agent label (e.g. `\"ClaudeDesktop\"`) → `principal.name`. */\n  name?: string;\n  /** Agent category (e.g. `\"scraper\"`) → `principal.category`. */\n  category?: string;\n  /** Delegation posture (e.g. `\"verified\"`) → `principal.delegation`. */\n  delegation?: string;\n  /** Resource path (e.g. `\"/checkout\"`) → `resource.path`. */\n  path?: string;\n  /**\n   * draft-kya-http-02 §1 assurance tier the request reached\n   * (`anonymous` | `attested-bearer` | `key-bound` | `registered` |\n   * `delegated`) → `context.assurance`. Defaults to `\"anonymous\"` (the\n   * monotone floor) when omitted, so a policy gating on\n   * `context.assurance == \"delegated\"` evaluates rather than erroring.\n   */\n  assurance?: AssuranceTier;\n  /**\n   * Locally verified browser risk, independent of credential assurance.\n   * `'cleared'` is the human step-up outcome: a request carrying a valid\n   * `__Host-kya_clearance` JWT (verified by the host, bound to the\n   * session cookie, 10-minute lifetime) → `context.integrity = \"cleared\"`,\n   * which the engine-default policy permits.\n   */\n  integrity?: 'agent-driven' | 'human' | 'insufficient' | 'unknown' | 'cleared';\n  /**\n   * Detection confidence on the shared 0-100 scale → `principal.confidence`\n   * (a Cedar Long). Absent stays absent — no default — so a caller that\n   * never supplies this leaves the Cedar entity byte-identical to before\n   * this field existed.\n   */\n  confidence?: number;\n  /**\n   * Coarse IP-routing classification from the host's network context →\n   * `context.ip_routing_type`. Omit when the host has no network context.\n   */\n  ipRoutingType?: 'residential' | 'mobile' | 'datacenter' | 'hosting' | 'unknown';\n  /**\n   * Whether the request's `trueIp` was flagged as a proxy/anonymization\n   * exit → `context.is_proxy`. Omit when the host has no network context.\n   */\n  isProxy?: boolean;\n  /**\n   * Coarse category of a confirmed proxy/anonymization service →\n   * `context.proxy_type`. Omit when the host has no proxy verdict (same\n   * posture as `isProxy` — only present once a proxy verdict was computed).\n   */\n  proxyType?: 'vpn' | 'tor' | 'datacenter' | 'residential_proxy' | 'unknown';\n  /**\n   * The host's IP-intelligence provider's confidence in the proxy verdict,\n   * `0..=100` → `context.network_confidence` (a Cedar Long). Omit when the\n   * host has no proxy verdict.\n   */\n  networkConfidence?: number;\n  /**\n   * Gateway-computed request count for this client (session-cookie or\n   * JA4+IP keyed) in the trailing 300-second window →\n   * `context.request_rate_300s` (a Cedar Long). Omit when the host has no\n   * velocity tracker for this request.\n   */\n  requestRate300s?: number;\n}\n\n/**\n * Structural type of the WASM `PolicyEvaluator` class the cedar glue\n * exports. Pinned here so this bridge type-checks against the artifact's\n * `.d.ts` (`constructor(policy_text: string)`, `authorize(input): any`,\n * `free()`).\n */\ninterface WasmPolicyEvaluator {\n  authorize(input: AuthorizeInput): unknown;\n  free(): void;\n}\n\n/**\n * Result of validating a tenant policy bundle against the canonical Cedar\n * schema. Mirrors the Rust `PolicyValidation`\n * (`rust/crates/kya-os-engine/src/policy/schema.rs`); a typo'd attribute,\n * wrong-type comparison, or unknown entity surfaces in `errors`.\n */\nexport interface PolicyValidation {\n  /** True iff the bundle compiled AND type-checked with no errors (warnings OK). */\n  valid: boolean;\n  /** Type/parse errors — author must fix (typo'd attribute, wrong type, …). */\n  errors: string[];\n  /** Non-fatal validation warnings (impossible/shadowed clause, …). */\n  warnings: string[];\n}\n\ninterface CedarWasmModule {\n  PolicyEvaluator: new (policyText: string) => WasmPolicyEvaluator;\n  validatePolicy: (policyText: string) => PolicyValidation;\n}\n\n// Lazy, memoised require of the cedar nodejs glue. The glue instantiates\n// the ~2 MB cedar WASM on require (see the file header), so it is deferred\n// to the first createPolicyEvaluator call rather than module load — merely\n// importing this module (or, transitively, the ./node barrel) stays free.\nconst cedarRequire = createRequire(__filename);\nlet cedarModule: CedarWasmModule | undefined;\nfunction loadCedarModule(): CedarWasmModule {\n  cedarModule ??= cedarRequire('../wasm/kya-os-engine-cedar/kya_os_engine.js') as CedarWasmModule;\n  return cedarModule;\n}\n\n/**\n * Host-facing wrapper around one compiled Cedar policy bundle.\n *\n * Construction compiles the bundle once; every {@link authorize} call\n * evaluates a single owned request against it without re-parsing policy\n * text (the compile-once / evaluate-many contract the engine upholds,\n * carried across the boundary).\n */\nexport class PolicyEvaluatorRuntime {\n  /**\n   * @param inner - The compiled WASM `PolicyEvaluator` handle. Built in\n   *   {@link createPolicyEvaluator}; reused by every {@link authorize}\n   *   call for the lifetime of this wrapper.\n   */\n  constructor(private readonly inner: WasmPolicyEvaluator) {}\n\n  /**\n   * Authorize one owned request against the compiled policy bundle.\n   *\n   * The evaluator owns the fail-closed posture — a request it cannot\n   * marshal into Cedar, or one matching no `permit`, comes back as a\n   * {@link Decision} `Block` (not a thrown error). Authorization\n   * *verdicts* never throw; they surface inside the returned value.\n   *\n   * @throws {Error} only for boundary faults the WASM glue rejects: a\n   *   malformed `input` that fails `AuthorizeInput` deserialisation, or a\n   *   failure serialising the resulting `Decision`.\n   */\n  authorize(input: AuthorizeInput): Decision {\n    return this.inner.authorize(input) as Decision;\n  }\n\n  /**\n   * Release the compiled bundle's WASM memory. Call when the evaluator is\n   * no longer needed; after this the wrapper must not be reused.\n   */\n  free(): void {\n    this.inner.free();\n  }\n}\n\n/**\n * Compile a Cedar policy bundle into a reusable in-process evaluator.\n *\n * Loads like `engine/node.ts`: routes through the cedar\n * `--target nodejs` glue, which self-loads its `.wasm` sibling via CJS\n * `__dirname` + `require('fs')`. The returned {@link PolicyEvaluatorRuntime}\n * holds one compiled bundle and authorizes many requests against it.\n *\n * @param policyText - The tenant's Cedar policy bundle as source text.\n * @throws {Error} if `policyText` is not syntactically valid Cedar — a\n *   malformed bundle is an infrastructure fault surfaced here at\n *   construction, never as a per-request deny.\n *\n * @example\n * ```typescript\n * import { createPolicyEvaluator } from '@kya-os/checkpoint-wasm-runtime/policy';\n *\n * const evaluator = createPolicyEvaluator('permit(principal, action, resource);');\n * const decision = evaluator.authorize({\n *   action: 'book_flight',\n *   resource: 'travel_api',\n *   tenantId: 'tenant-a',\n *   grantedScopes: ['book_flight'],\n * });\n * if (decision.kind === 'Permit') {\n *   // proceed\n * }\n * ```\n */\nexport function createPolicyEvaluator(policyText: string): PolicyEvaluatorRuntime {\n  assertCedarNesting(policyText);\n  // Lazily require the cedar glue on first use (see loadCedarModule) so the\n  // ~2 MB cedar WASM is instantiated only when a host actually builds an\n  // evaluator — never at import time.\n  const { PolicyEvaluator } = loadCedarModule();\n  return new PolicyEvaluatorRuntime(new PolicyEvaluator(policyText));\n}\n\n/**\n * Validate a tenant Cedar bundle against the canonical schema WITHOUT compiling\n * an evaluator or throwing (E4.7 / #3076). Returns the type/parse errors +\n * warnings so an author-time surface (the dashboard's /policy-compose path) can\n * show a typo'd attribute / wrong type as a LOUD error before deploy — instead\n * of the runtime's silent fail-closed deny. A blank bundle is valid (\"no\n * composed policy\"). Pure: changes no authorization verdict.\n *\n * @example\n * ```typescript\n * import { validatePolicy } from '@kya-os/checkpoint-wasm-runtime/policy';\n * const { valid, errors } = validatePolicy('permit(principal, action, resource) when { principal.catgory == \"x\" };');\n * // valid === false; errors describes the unknown `catgory` attribute.\n * ```\n */\nexport function validatePolicy(policyText: string): PolicyValidation {\n  const nesting = cedarNestingError(policyText);\n  if (nesting !== undefined) return { valid: false, errors: [nesting], warnings: [] };\n  const { validatePolicy: was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