@fabricorg/policy-opa 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/decision-schema.ts","../src/hash.ts","../src/factory.ts"],"names":["createHash"],"mappings":";;;;;AAGA,IAAM,cAAA,GAAoD,CAAC,MAAA,EAAQ,MAAA,EAAQ,OAAO,CAAA;AAe3E,SAAS,iBAAiB,GAAA,EAAsC;AACtE,EAAA,IAAI,GAAA,KAAQ,IAAA,IAAQ,OAAO,GAAA,KAAQ,QAAA,EAAU;AAC5C,IAAA,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,KAAA,EAAO,4BAAA,EAA6B;AAAA,EACzD;AAEA,EAAA,MAAM,CAAA,GAAI,GAAA;AAEV,EAAA,IAAI,OAAO,EAAE,MAAA,KAAW,QAAA,IAAY,CAAC,cAAA,CAAe,QAAA,CAAS,CAAA,CAAE,MAAgC,CAAA,EAAG;AACjG,IAAA,OAAO;AAAA,MACN,EAAA,EAAI,KAAA;AAAA,MACJ,OAAO,CAAA,8CAAA,EAAiD,IAAA,CAAK,SAAA,CAAU,CAAA,CAAE,MAAM,CAAC,CAAA,CAAA;AAAA,KACjF;AAAA,EACD;AAEA,EAAA,IAAI,EAAE,MAAA,KAAW,MAAA,IAAa,OAAO,CAAA,CAAE,WAAW,QAAA,EAAU;AAC3D,IAAA,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,KAAA,EAAO,sCAAA,EAAuC;AAAA,EACnE;AAEA,EAAA,IAAI,CAAA,CAAE,qBAAqB,MAAA,EAAW;AACrC,IAAA,IAAI,CAAC,KAAA,CAAM,OAAA,CAAQ,CAAA,CAAE,gBAAgB,CAAA,EAAG;AACvC,MAAA,OAAO,EAAE,EAAA,EAAI,KAAA,EAAO,KAAA,EAAO,gDAAA,EAAiD;AAAA,IAC7E;AACA,IAAA,KAAA,IAAS,IAAI,CAAA,EAAG,CAA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eAAe,OAAA,CAAQ,OAAA;AAAA,MACvB,YAAA,EAAc,CAAC,MAAM,CAAA;AAAA,MACrB,MAAA,EAAQ;AAAA,QACP,IAAA,EAAM,WAAA;AAAA,QACN,OAAA,EAAS,aAAA;AAAA,QACT,UAAU,cAAA,CAAe;AAAA,UACxB,cAAc,OAAA,CAAQ,YAAA;AAAA,UACtB,aAAa,OAAA,CAAQ,WAAA;AAAA,UACrB,SAAA;AAAA,UACA,KAAA;AAAA,UACA,WAAA,EAAa;AAAA,SACb;AAAA;AACF;AACD,GACD;AACD;AAEA,SAAS,eAAe,GAAA,EAAuD;AAC9E,EAAA,MAAM,MAA+B,EAAC;AACtC,EAAA,KAAA,MAAW,CAAC,CAAA,EAAG,CAAC,KAAK,MAAA,CAAO,OAAA,CAAQ,GAAG,CAAA,EAAG;AACzC,IAAA,IAAI,CAAA,KAAM,MAAA,EAAW,GAAA,CAAI,CAAC,CAAA,GAAI,CAAA;AAAA,EAC/B;AACA,EAAA,OAAO,GAAA;AACR;AAEA,SAAS,YAAY,GAAA,EAAsB;AAC1C,EAAA,IAAI,GAAA,YAAe,KAAA,EAAO,OAAO,GAAA,CAAI,OAAA;AACrC,EAAA,IAAI,OAAO,GAAA,KAAQ,QAAA,EAAU,OAAO,GAAA;AACpC,EAAA,IAAI;AACH,IAAA,OAAO,IAAA,CAAK,UAAU,GAAG,CAAA;AAAA,EAC1B,CAAA,CAAA,MAAQ;AACP,IAAA,OAAO,OAAO,GAAG,CAAA;AAAA,EAClB;AACD","file":"index.cjs","sourcesContent":["import type { PolicyEvaluationResult } from \"@fabricorg/platform/policies\";\nimport type { OpaDecision } from \"./types\";\n\nconst POLICY_RESULTS: readonly PolicyEvaluationResult[] = [\"pass\", \"warn\", \"block\"];\n\nexport type OpaDecisionParseResult =\n\t| { ok: true; decision: OpaDecision }\n\t| { ok: false; error: string };\n\n/**\n * Hand-rolled validator for the Rego \"house style\" decision shape. Avoids a\n * runtime zod dependency to keep the adapter zero-dep.\n *\n * Accepts a raw OPA result and either returns the parsed `OpaDecision` or a\n * single human-readable error string describing the first violation. We don't\n * accumulate every error: when audit evidence has to record \"OPA returned\n * something invalid\", one precise reason is more useful than a list.\n */\nexport function parseOpaDecision(raw: unknown): OpaDecisionParseResult {\n\tif (raw === null || typeof raw !== \"object\") {\n\t\treturn { ok: false, error: \"decision must be an object\" };\n\t}\n\n\tconst d = raw as Record<string, unknown>;\n\n\tif (typeof d.result !== \"string\" || !POLICY_RESULTS.includes(d.result as PolicyEvaluationResult)) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\terror: `result must be \"pass\" | \"warn\" | \"block\" (got ${JSON.stringify(d.result)})`,\n\t\t};\n\t}\n\n\tif (d.reason !== undefined && typeof d.reason !== \"string\") {\n\t\treturn { ok: false, error: \"reason must be a string when present\" };\n\t}\n\n\tif (d.conditionResults !== undefined) {\n\t\tif (!Array.isArray(d.conditionResults)) {\n\t\t\treturn { ok: false, error: \"conditionResults must be an array when present\" };\n\t\t}\n\t\tfor (let i = 0; i < d.conditionResults.length; i += 1) {\n\t\t\tconst err = validateConditionResult(d.conditionResults[i], i);\n\t\t\tif (err) return { ok: false, error: err };\n\t\t}\n\t}\n\n\tif (d.factsUsed !== undefined && !isPlainObject(d.factsUsed)) {\n\t\treturn { ok: false, error: \"factsUsed must be an object when present\" };\n\t}\n\n\tif (d.obligations !== undefined && !isPlainObject(d.obligations)) {\n\t\treturn { ok: false, error: \"obligations must be an object when present\" };\n\t}\n\n\treturn { ok: true, decision: d as unknown as OpaDecision };\n}\n\nfunction validateConditionResult(value: unknown, index: number): string | null {\n\tif (!isPlainObject(value)) {\n\t\treturn `conditionResults[${index}] must be an object`;\n\t}\n\tconst c = value as Record<string, unknown>;\n\tif (typeof c.conditionId !== \"string\" || c.conditionId.length === 0) {\n\t\treturn `conditionResults[${index}].conditionId must be a non-empty string`;\n\t}\n\tif (typeof c.passed !== \"boolean\") {\n\t\treturn `conditionResults[${index}].passed must be a boolean`;\n\t}\n\tif (typeof c.result !== \"string\" || !POLICY_RESULTS.includes(c.result as PolicyEvaluationResult)) {\n\t\treturn `conditionResults[${index}].result must be \"pass\" | \"warn\" | \"block\"`;\n\t}\n\tif (c.reason !== undefined && typeof c.reason !== \"string\") {\n\t\treturn `conditionResults[${index}].reason must be a string when present`;\n\t}\n\treturn null;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n\treturn value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n","import { createHash } from \"node:crypto\";\n\n/**\n * Stable JSON stringify — sorts object keys recursively so two\n * structurally-equal inputs produce the same string regardless of property\n * insertion order. Required for hash determinism across builds of the same\n * `buildInput` function.\n */\nexport function stableStringify(value: unknown): string {\n\tif (value === undefined) return \"null\";\n\tif (value === null || typeof value !== \"object\") return JSON.stringify(value);\n\tif (Array.isArray(value)) {\n\t\treturn `[${value.map(stableStringify).join(\",\")}]`;\n\t}\n\tconst obj = value as Record<string, unknown>;\n\tconst keys = Object.keys(obj).sort();\n\treturn `{${keys\n\t\t.map((k) => `${JSON.stringify(k)}:${stableStringify(obj[k])}`)\n\t\t.join(\",\")}}`;\n}\n\n/**\n * Default input hasher: SHA-256 over a stable stringification.\n * Format: `sha256:<hex>` — namespaced so future migrations to a different\n * algorithm can be detected by a prefix check in evidence dashboards.\n */\nexport function defaultHashInput(input: Record<string, unknown>): string {\n\tconst hex = createHash(\"sha256\").update(stableStringify(input)).digest(\"hex\");\n\treturn `sha256:${hex}`;\n}\n","import type {\n\tPolicyContext,\n\tPolicyEvaluator,\n\tPolicyOutcome,\n} from \"@fabricorg/platform/policies\";\n\nimport { parseOpaDecision } from \"./decision-schema\";\nimport { defaultHashInput } from \"./hash\";\nimport type {\n\tCreateOpaPolicyEvaluatorOptions,\n\tOpaDecision,\n\tOpaPolicyClient,\n\tOpaPolicyFailureKind,\n} from \"./types\";\n\nconst DEFAULT_SERVICE_KEY = \"opa\";\nconst ENGINE_NAME = \"opa\";\n\n/**\n * Build a Fabric `PolicyEvaluator` that delegates decision-making to an OPA\n * (Open Policy Agent) deployment. The evaluator:\n *\n * 1. Reads the host-injected OPA client from `ctx.services[serviceKey]`.\n * 2. Builds a JSON input snapshot via `buildInput(ctx)` — domain code that\n * snapshots facts the engine needs. Fabric platform never lets OPA reach\n * into the database directly; all facts flow through this function.\n * 3. Evaluates the Rego decision at `binding.decisionPath`.\n * 4. Validates the response against the house-style shape (`OpaDecision`).\n * 5. Maps the decision to a `PolicyOutcome` and attaches engine provenance\n * (`engine.name = \"opa\"`, `decisionPath`, `inputHash`) for audit.\n *\n * Failures (missing client, build failure, network failure, malformed response)\n * are governed by `onError`. Default `\"block\"` honors Fabric's default-deny\n * posture and records the failure category under `engine.metadata.error`.\n */\nexport function createOpaPolicyEvaluator<TDb = unknown>(\n\toptions: CreateOpaPolicyEvaluatorOptions<TDb>,\n): PolicyEvaluator<TDb> {\n\tconst {\n\t\tbinding,\n\t\tbuildInput,\n\t\tserviceKey = DEFAULT_SERVICE_KEY,\n\t\tonError = \"block\",\n\t\tpreviewSafe = false,\n\t\tengineVersion,\n\t\tmapDecision,\n\t\thashInput = defaultHashInput,\n\t} = options;\n\n\treturn {\n\t\tpolicyId: binding.policyId,\n\t\tversion: binding.version,\n\t\tpreviewSafe,\n\t\tevaluate: async (ctx) => {\n\t\t\tconst client = ctx.services?.[serviceKey] as OpaPolicyClient | undefined;\n\t\t\tif (!client || typeof client.evaluate !== \"function\") {\n\t\t\t\treturn makeFailureOutcome(\n\t\t\t\t\tbinding,\n\t\t\t\t\tengineVersion,\n\t\t\t\t\t\"client_unavailable\",\n\t\t\t\t\t`No OPA client at ctx.services[\"${serviceKey}\"]`,\n\t\t\t\t\tonError,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tlet input: Record<string, unknown>;\n\t\t\ttry {\n\t\t\t\tinput = await buildInput(ctx);\n\t\t\t} catch (err) {\n\t\t\t\treturn makeFailureOutcome(\n\t\t\t\t\tbinding,\n\t\t\t\t\tengineVersion,\n\t\t\t\t\t\"input_build_failed\",\n\t\t\t\t\t`buildInput threw: ${formatError(err)}`,\n\t\t\t\t\tonError,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tlet inputHash: string | undefined;\n\t\t\ttry {\n\t\t\t\tinputHash = hashInput(input);\n\t\t\t} catch {\n\t\t\t\t// hashing is best-effort — if a custom hasher throws, omit the\n\t\t\t\t// field rather than fail the policy.\n\t\t\t}\n\n\t\t\tlet rawResult: unknown;\n\t\t\ttry {\n\t\t\t\trawResult = await client.evaluate(binding.decisionPath, input);\n\t\t\t} catch (err) {\n\t\t\t\treturn makeFailureOutcome(\n\t\t\t\t\tbinding,\n\t\t\t\t\tengineVersion,\n\t\t\t\t\t\"evaluation_failed\",\n\t\t\t\t\t`OPA evaluation failed: ${formatError(err)}`,\n\t\t\t\t\tonError,\n\t\t\t\t\tinputHash,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst parsed = parseOpaDecision(rawResult);\n\t\t\tif (!parsed.ok) {\n\t\t\t\treturn makeFailureOutcome(\n\t\t\t\t\tbinding,\n\t\t\t\t\tengineVersion,\n\t\t\t\t\t\"invalid_response\",\n\t\t\t\t\t`OPA returned malformed decision: ${parsed.error}`,\n\t\t\t\t\tonError,\n\t\t\t\t\tinputHash,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\treturn buildSuccessOutcome(\n\t\t\t\tbinding,\n\t\t\t\tengineVersion,\n\t\t\t\tparsed.decision,\n\t\t\t\tinputHash,\n\t\t\t\tctx,\n\t\t\t\tmapDecision,\n\t\t\t);\n\t\t},\n\t};\n}\n\nfunction buildSuccessOutcome<TDb>(\n\tbinding: CreateOpaPolicyEvaluatorOptions<TDb>[\"binding\"],\n\tengineVersion: string | undefined,\n\tdecision: OpaDecision,\n\tinputHash: string | undefined,\n\tctx: PolicyContext<TDb>,\n\tmapDecision: CreateOpaPolicyEvaluatorOptions<TDb>[\"mapDecision\"],\n): PolicyOutcome {\n\tconst mapped = mapDecision\n\t\t? mapDecision(decision, ctx)\n\t\t: { result: decision.result, reason: decision.reason };\n\n\treturn {\n\t\tpolicyId: binding.policyId,\n\t\tpolicyVersion: binding.version,\n\t\tresult: mapped.result,\n\t\treason: mapped.reason,\n\t\tmetadata: {\n\t\t\t...(mapped.metadata ?? {}),\n\t\t\topaDecision: decision,\n\t\t},\n\t\tdispatchEvidence: {\n\t\t\tpolicyKind: \"code\",\n\t\t\tpolicyId: binding.policyId,\n\t\t\tpolicyVersion: binding.version,\n\t\t\tdispatchPath: [\"code\"],\n\t\t\tengine: {\n\t\t\t\tname: ENGINE_NAME,\n\t\t\t\tversion: engineVersion,\n\t\t\t\tmetadata: stripUndefined({\n\t\t\t\t\tdecisionPath: binding.decisionPath,\n\t\t\t\t\tregoPackage: binding.regoPackage,\n\t\t\t\t\tinputHash,\n\t\t\t\t\tconditionResults: decision.conditionResults,\n\t\t\t\t\tfactsUsed: decision.factsUsed,\n\t\t\t\t\tobligations: decision.obligations,\n\t\t\t\t}),\n\t\t\t},\n\t\t},\n\t};\n}\n\nfunction makeFailureOutcome(\n\tbinding: CreateOpaPolicyEvaluatorOptions[\"binding\"],\n\tengineVersion: string | undefined,\n\terror: OpaPolicyFailureKind,\n\treason: string,\n\tonError: \"block\" | \"throw\",\n\tinputHash?: string,\n): PolicyOutcome {\n\tif (onError === \"throw\") {\n\t\tconst err = new Error(reason);\n\t\t(err as Error & { kind?: OpaPolicyFailureKind }).kind = error;\n\t\tthrow err;\n\t}\n\n\treturn {\n\t\tpolicyId: binding.policyId,\n\t\tpolicyVersion: binding.version,\n\t\tresult: \"block\",\n\t\treason,\n\t\tmetadata: {\n\t\t\topaError: error,\n\t\t},\n\t\tdispatchEvidence: {\n\t\t\tpolicyKind: \"code\",\n\t\t\tpolicyId: binding.policyId,\n\t\t\tpolicyVersion: binding.version,\n\t\t\tdispatchPath: [\"code\"],\n\t\t\tengine: {\n\t\t\t\tname: ENGINE_NAME,\n\t\t\t\tversion: engineVersion,\n\t\t\t\tmetadata: stripUndefined({\n\t\t\t\t\tdecisionPath: binding.decisionPath,\n\t\t\t\t\tregoPackage: binding.regoPackage,\n\t\t\t\t\tinputHash,\n\t\t\t\t\terror,\n\t\t\t\t\terrorReason: reason,\n\t\t\t\t}),\n\t\t\t},\n\t\t},\n\t};\n}\n\nfunction stripUndefined(obj: Record<string, unknown>): Record<string, unknown> {\n\tconst out: Record<string, unknown> = {};\n\tfor (const [k, v] of Object.entries(obj)) {\n\t\tif (v !== undefined) out[k] = v;\n\t}\n\treturn out;\n}\n\nfunction formatError(err: unknown): string {\n\tif (err instanceof Error) return err.message;\n\tif (typeof err === \"string\") return err;\n\ttry {\n\t\treturn JSON.stringify(err);\n\t} catch {\n\t\treturn String(err);\n\t}\n}\n"]}
1
+ {"version":3,"sources":["../src/bundle-selector.ts","../src/decision-schema.ts","../src/hash.ts","../src/factory.ts","../src/executor-client.ts","../src/executor-http.ts"],"names":["createHash"],"mappings":";;;;;AA0BO,SAAS,oBAAA,CACf,WACA,OAAA,EACkB;AAClB,EAAA,IAAI,OAAO,SAAA,CAAU,cAAA,KAAmB,YAAY,SAAA,CAAU,cAAA,CAAe,SAAS,CAAA,EAAG;AACxF,IAAA,OAAO,EAAE,cAAA,EAAgB,SAAA,CAAU,cAAA,EAAe;AAAA,EACnD;AAEA,EAAA,MAAM,OAAA,GAAU,WAAA,CAAY,SAAA,CAAU,UAAU,CAAA;AAChD,EAAA,IAAI,CAAC,OAAA,EAAS,OAAO,EAAC;AAEtB,EAAA,MAAM,KAAA,GAAQ,MAAA,CAAO,IAAA,CAAK,OAAO,CAAA;AACjC,EAAA,IAAI,KAAA,CAAM,MAAA,KAAW,CAAA,EAAG,OAAO,EAAC;AAEhC,EAAA,IAAI,QAAQ,UAAA,EAAY;AACvB,IAAA,MAAM,QAAA,GAAW,OAAA,CAAQ,OAAA,CAAQ,UAAU,CAAA,EAAG,QAAA;AAC9C,IAAA,OAAO,OAAO,QAAA,KAAa,QAAA,IAAY,QAAA,CAAS,MAAA,GAAS,IACtD,EAAE,c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IAAA,CAAK,MAAA;AAAA,QACf,YAAY,IAAA,CAAK,WAAA;AAAA,QACjB,UAAA,EAAY,KAAK,UAAA,EAAY,OAAA;AAAA,QAC7B,YAAY,IAAA,CAAK;AAAA,OAClB;AAAA,IACD;AAAA,GACD;AACD;AAEA,SAAS,mBAAmB,CAAA,EAAmB;AAC9C,EAAA,OAAO,CAAA,CAAE,OAAA,CAAQ,MAAA,EAAQ,EAAE,CAAA;AAC5B;AAEA,SAAS,kBAAkB,CAAA,EAAmB;AAC7C,EAAA,OAAO,CAAA,CAAE,OAAA,CAAQ,MAAA,EAAQ,EAAE,CAAA;AAC5B;AAEA,eAAe,aAAa,QAAA,EAAqC;AAChE,EAAA,IAAI;AACH,IAAA,OAAO,MAAM,SAAS,IAAA,EAAK;AAAA,EAC5B,CAAA,CAAA,MAAQ;AACP,IAAA,OAAO,mBAAA;AAAA,EACR;AACD;AAEA,SAAS,QAAA,CAAS,GAAW,GAAA,EAAqB;AACjD,EAAA,OAAO,CAAA,CAAE,UAAU,GAAA,GAAM,CAAA,GAAI,GAAG,CAAA,CAAE,KAAA,CAAM,CAAA,EAAG,GAAG,CAAC,CAAA,MAAA,CAAA;AAChD","file":"index.cjs","sourcesContent":["import type { OpaPolicyBinding, OpaPolicyExecution } from \"./types\";\n\nexport interface BundleSelection {\n\tbundleRevision?: string;\n\t/**\n\t * Set to `\"ambiguous\"` when OPA reports multiple bundles and the binding\n\t * did not pick one with `bundleName`. The adapter records this on the\n\t * evidence so dashboards can flag policies that need explicit selectors.\n\t * `\"missing\"` is set when provenance was expected but absent.\n\t */\n\tbundleRevisionStatus?: \"ambiguous\" | \"missing\";\n}\n\n/**\n * Determine which OPA bundle revision applies to this decision.\n *\n * Rules (in order):\n * 1. If the executor already populated `execution.bundleRevision`, use it.\n * 2. If `binding.bundleName` is set, look it up in `provenance.bundles`.\n * 3. If exactly one bundle is reported, use its revision unambiguously.\n * 4. If multiple bundles are reported and no selector exists, mark\n * `bundleRevisionStatus: \"ambiguous\"`.\n * 5. If no provenance is reported at all, return `{}` — the caller decides\n * whether absence is meaningful (it is not, for executors that don't\n * carry provenance).\n */\nexport function selectBundleRevision(\n\texecution: OpaPolicyExecution,\n\tbinding: OpaPolicyBinding,\n): BundleSelection {\n\tif (typeof execution.bundleRevision === \"string\" && execution.bundleRevision.length > 0) {\n\t\treturn { bundleRevision: execution.bundleRevision };\n\t}\n\n\tconst bundles = readBundles(execution.provenance);\n\tif (!bundles) return {};\n\n\tconst names = Object.keys(bundles);\n\tif (names.length === 0) return {};\n\n\tif (binding.bundleName) {\n\t\tconst revision = bundles[binding.bundleName]?.revision;\n\t\treturn typeof revision === \"string\" && revision.length > 0\n\t\t\t? { bundleRevision: revision }\n\t\t\t: {};\n\t}\n\n\tif (names.length === 1) {\n\t\tconst only = names[0];\n\t\t// names.length === 1 guarantees names[0] is defined, but the\n\t\t// non-null assertion satisfies noUncheckedIndexedAccess if enabled.\n\t\tconst revision = only !== undefined ? bundles[only]?.revision : undefined;\n\t\treturn typeof revision === \"string\" && revision.length > 0\n\t\t\t? { bundleRevision: revision }\n\t\t\t: {};\n\t}\n\n\treturn { bundleRevisionStatus: \"ambiguous\" };\n}\n\nfunction readBundles(\n\tprovenance: Record<string, unknown> | undefined,\n): Record<string, { revision?: unknown }> | undefined {\n\tif (!provenance || typeof provenance !== \"object\") return undefined;\n\tconst b = (provenance as { bundles?: unknown }).bundles;\n\tif (!b || typeof b !== \"object\" || Array.isArray(b)) return undefined;\n\treturn b as Record<string, { revision?: unknown }>;\n}\n","import type { PolicyEvaluationResult } from \"@fabricorg/platform/policies\";\nimport type { OpaDecision } from \"./types\";\n\nconst POLICY_RESULTS: readonly PolicyEvaluationResult[] = [\"pass\", \"warn\", \"block\"];\n\nexport type OpaDecisionParseResult =\n\t| { ok: true; decision: OpaDecision }\n\t| { ok: false; error: string };\n\n/**\n * Hand-rolled validator for the Rego \"house style\" decision shape. Avoids a\n * runtime zod dependency to keep the adapter zero-dep.\n *\n * Accepts a raw OPA result and either returns the parsed `OpaDecision` or a\n * single human-readable error string describing the first violation. We don't\n * accumulate every error: when audit evidence has to record \"OPA returned\n * something invalid\", one precise reason is more useful than a list.\n */\nexport function parseOpaDecision(raw: unknown): OpaDecisionParseResult {\n\tif (raw === null || typeof raw !== \"object\") {\n\t\treturn { ok: false, error: \"decision must be an object\" };\n\t}\n\n\tconst d = raw as Record<string, unknown>;\n\n\tif (typeof d.result !== \"string\" || !POLICY_RESULTS.includes(d.result as PolicyEvaluationResult)) {\n\t\treturn {\n\t\t\tok: false,\n\t\t\terror: `result must be \"pass\" | \"warn\" | \"block\" (got ${JSON.stringify(d.result)})`,\n\t\t};\n\t}\n\n\tif (d.reason !== undefined && typeof d.reason !== \"string\") {\n\t\treturn { ok: false, error: \"reason must be a string when present\" };\n\t}\n\n\tif (d.conditionResults !== undefined) {\n\t\tif (!Array.isArray(d.conditionResults)) {\n\t\t\treturn { ok: false, error: \"conditionResults must be an array when present\" };\n\t\t}\n\t\tfor (let i = 0; i < d.conditionResults.length; i += 1) {\n\t\t\tconst err = validateConditionResult(d.conditionResults[i], i);\n\t\t\tif (err) return { ok: false, error: err };\n\t\t}\n\t}\n\n\tif (d.guidance !== undefined) {\n\t\tconst err = validateGuidance(d.guidance);\n\t\tif (err) return { ok: false, error: err };\n\t}\n\n\tif (d.obligations !== undefined && !isPlainObject(d.obligations)) {\n\t\treturn { ok: false, error: \"obligations must be an object when present\" };\n\t}\n\n\treturn { ok: true, decision: d as unknown as OpaDecision };\n}\n\nfunction validateConditionResult(value: unknown, index: number): string | null {\n\tif (!isPlainObject(value)) {\n\t\treturn `conditionResults[${index}] must be an object`;\n\t}\n\tconst c = value as Record<string, unknown>;\n\tif (typeof c.conditionId !== \"string\" || c.conditionId.length === 0) {\n\t\treturn `conditionResults[${index}].conditionId must be a non-empty string`;\n\t}\n\tif (typeof c.passed !== \"boolean\") {\n\t\treturn `conditionResults[${index}].passed must be a boolean`;\n\t}\n\tif (typeof c.result !== \"string\" || !POLICY_RESULTS.includes(c.result as PolicyEvaluationResult)) {\n\t\treturn `conditionResults[${index}].result must be \"pass\" | \"warn\" | \"block\"`;\n\t}\n\tif (c.reason !== undefined && typeof c.reason !== \"string\") {\n\t\treturn `conditionResults[${index}].reason must be a string when present`;\n\t}\n\treturn null;\n}\n\nfunction validateGuidance(value: unknown): string | null {\n\tif (!isPlainObject(value)) {\n\t\treturn \"guidance must be an object when present\";\n\t}\n\tconst guidance = value as Record<string, unknown>;\n\tif (guidance.summary !== undefined && typeof guidance.summary !== \"string\") {\n\t\treturn \"guidance.summary must be a string when present\";\n\t}\n\tif (!Array.isArray(guidance.factsUsed)) {\n\t\treturn \"guidance.factsUsed must be an array\";\n\t}\n\tfor (let i = 0; i < guidance.factsUsed.length; i += 1) {\n\t\tconst err = validatePolicyFact(guidance.factsUsed[i], i);\n\t\tif (err) return err;\n\t}\n\tif (!Array.isArray(guidance.correctiveActions)) {\n\t\treturn \"guidance.correctiveActions must be an array\";\n\t}\n\tfor (let i = 0; i < guidance.correctiveActions.length; i += 1) {\n\t\tconst err = validateCorrectiveAction(guidance.correctiveActions[i], i);\n\t\tif (err) return err;\n\t}\n\treturn null;\n}\n\nfunction validatePolicyFact(value: unknown, index: number): string | null {\n\tif (!isPlainObject(value)) {\n\t\treturn `guidance.factsUsed[${index}] must be an object`;\n\t}\n\tconst fact = value as Record<string, unknown>;\n\tif (typeof fact.name !== \"string\" || fact.name.length === 0) {\n\t\treturn `guidance.factsUsed[${index}].name must be a non-empty string`;\n\t}\n\tif (fact.label !== undefined && typeof fact.label !== \"string\") {\n\t\treturn `guidance.factsUsed[${index}].label must be a string when present`;\n\t}\n\treturn null;\n}\n\nfunction validateCorrectiveAction(value: unknown, index: number): string | null {\n\tif (!isPlainObject(value)) {\n\t\treturn `guidance.correctiveActions[${index}] must be an object`;\n\t}\n\tconst action = value as Record<string, unknown>;\n\tif (typeof action.label !== \"string\" || action.label.length === 0) {\n\t\treturn `guidance.correctiveActions[${index}].label must be a non-empty string`;\n\t}\n\tif (action.description !== undefined && typeof action.description !== \"string\") {\n\t\treturn `guidance.correctiveActions[${index}].description must be a string when present`;\n\t}\n\tif (action.actionId !== undefined && typeof action.actionId !== \"string\") {\n\t\treturn `guidance.correctiveActions[${index}].actionId must be a string when present`;\n\t}\n\tif (action.parameters !== undefined && !isPlainObject(action.parameters)) {\n\t\treturn `guidance.correctiveActions[${index}].parameters must be an object when present`;\n\t}\n\tif (action.target !== undefined && !isPlainObject(action.target)) {\n\t\treturn `guidance.correctiveActions[${index}].target must be an object when present`;\n\t}\n\tif (action.requiresConfirmation !== undefined && typeof action.requiresConfirmation !== \"boolean\") {\n\t\treturn `guidance.correctiveActions[${index}].requiresConfirmation must be a boolean when present`;\n\t}\n\treturn null;\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n\treturn value !== null && typeof value === \"object\" && !Array.isArray(value);\n}\n","import { createHash } from \"node:crypto\";\n\n/**\n * Stable JSON stringify — sorts object keys recursively so two\n * structurally-equal inputs produce the same string regardless of property\n * insertion order. Required for hash determinism across builds of the same\n * `buildInput` function.\n */\nexport function stableStringify(value: unknown): string {\n\tif (value === undefined) return \"null\";\n\tif (value === null || typeof value !== \"object\") return JSON.stringify(value);\n\tif (Array.isArray(value)) {\n\t\treturn `[${value.map(stableStringify).join(\",\")}]`;\n\t}\n\tconst obj = value as Record<string, unknown>;\n\tconst keys = Object.keys(obj).sort();\n\treturn `{${keys\n\t\t.map((k) => `${JSON.stringify(k)}:${stableStringify(obj[k])}`)\n\t\t.join(\",\")}}`;\n}\n\n/**\n * Default input hasher: SHA-256 over a stable stringification.\n * Format: `sha256:<hex>` — namespaced so future migrations to a different\n * algorithm can be detected by a prefix check in evidence dashboards.\n */\nexport function defaultHashInput(input: Record<string, unknown>): string {\n\tconst hex = createHash(\"sha256\").update(stableStringify(input)).digest(\"hex\");\n\treturn `sha256:${hex}`;\n}\n","import type {\n\tPolicyContext,\n\tPolicyEvaluator,\n\tPolicyOutcome,\n} from \"@fabricorg/platform/policies\";\n\nimport { selectBundleRevision } from \"./bundle-selector\";\nimport { parseOpaDecision } from \"./decision-schema\";\nimport { defaultHashInput } from \"./hash\";\nimport type {\n\tCreateOpaPolicyEvaluatorOptions,\n\tOpaDecision,\n\tOpaPolicyBinding,\n\tOpaPolicyClient,\n\tOpaPolicyExecution,\n\tOpaPolicyExecutor,\n\tOpaPolicyFailureKind,\n} from \"./types\";\n\nconst DEFAULT_SERVICE_KEY = \"opa\";\nconst ENGINE_NAME = \"opa\";\n\n/**\n * Build a Fabric `PolicyEvaluator` that delegates decision-making to an OPA\n * (Open Policy Agent) deployment.\n *\n * The adapter accepts either of two service shapes under\n * `ctx.services[serviceKey]`:\n *\n * - `OpaPolicyExecutor` (preferred) — `execute(path, input)` returning a rich\n * `OpaPolicyExecution` (decision plus `decisionId`, `bundleRevision`,\n * `opaVersion`, `provenance`). Ship one with {@link executorFromOpaHttp} or\n * {@link executorFromOpaClient}.\n * - `OpaPolicyClient` — `evaluate(path, input)` returning the raw decision\n * only. Compatible with the high-level `@open-policy-agent/opa` SDK at the\n * cost of OPA-side provenance.\n *\n * If both methods are present, `execute` is preferred.\n *\n * The evaluator:\n *\n * 1. Resolves the service from `ctx.services[serviceKey]`.\n * 2. Builds a JSON input snapshot via `buildInput(ctx)` — domain code that\n * snapshots facts the engine needs. OPA never reaches into the database\n * directly; all facts flow through this function.\n * 3. Calls OPA at `binding.decisionPath`.\n * 4. Validates the response against the house-style shape (`OpaDecision`).\n * 5. Maps the decision to a `PolicyOutcome` and attaches engine provenance\n * under `dispatchEvidence.engine` — `name`, optional `version`, and\n * metadata covering `decisionPath`, `regoPackage`, `inputHash`, plus (when\n * the executor surfaces them) `decisionId`, `bundleName`, `bundleRevision`,\n * `bundleRevisionStatus`, and the raw `provenance` block.\n *\n * Failures (missing client, build failure, network failure, malformed\n * response) are governed by `onError`. Default `\"block\"` honors Fabric's\n * default-deny posture and records the failure category under\n * `engine.metadata.error`.\n */\nexport function createOpaPolicyEvaluator<TDb = unknown>(\n\toptions: CreateOpaPolicyEvaluatorOptions<TDb>,\n): PolicyEvaluator<TDb> {\n\tconst {\n\t\tbinding,\n\t\tbuildInput,\n\t\tserviceKey = DEFAULT_SERVICE_KEY,\n\t\tonError = \"block\",\n\t\tpreviewSafe = false,\n\t\tengineVersion,\n\t\tmapDecision,\n\t\thashInput = defaultHashInput,\n\t} = options;\n\n\treturn {\n\t\tpolicyId: binding.policyId,\n\t\tversion: binding.version,\n\t\tpreviewSafe,\n\t\tevaluate: async (ctx) => {\n\t\t\tconst service = ctx.services?.[serviceKey];\n\t\t\tconst transport = resolveTransport(service);\n\t\t\tif (!transport) {\n\t\t\t\treturn makeFailureOutcome(\n\t\t\t\t\tbinding,\n\t\t\t\t\tengineVersion,\n\t\t\t\t\t\"client_unavailable\",\n\t\t\t\t\t`No OPA client/executor at ctx.services[\"${serviceKey}\"]`,\n\t\t\t\t\tonError,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tlet input: Record<string, unknown>;\n\t\t\ttry {\n\t\t\t\tinput = await buildInput(ctx);\n\t\t\t} catch (err) {\n\t\t\t\treturn makeFailureOutcome(\n\t\t\t\t\tbinding,\n\t\t\t\t\tengineVersion,\n\t\t\t\t\t\"input_build_failed\",\n\t\t\t\t\t`buildInput threw: ${formatError(err)}`,\n\t\t\t\t\tonError,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tlet inputHash: string | undefined;\n\t\t\ttry {\n\t\t\t\tinputHash = hashInput(input);\n\t\t\t} catch {\n\t\t\t\t// hashing is best-effort — if a custom hasher throws, omit the\n\t\t\t\t// field rather than fail the policy.\n\t\t\t}\n\n\t\t\tlet execution: OpaPolicyExecution;\n\t\t\ttry {\n\t\t\t\texecution = await transport(binding.decisionPath, input);\n\t\t\t} catch (err) {\n\t\t\t\treturn makeFailureOutcome(\n\t\t\t\t\tbinding,\n\t\t\t\t\tengineVersion,\n\t\t\t\t\t\"evaluation_failed\",\n\t\t\t\t\t`OPA evaluation failed: ${formatError(err)}`,\n\t\t\t\t\tonError,\n\t\t\t\t\tinputHash,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst parsed = parseOpaDecision(execution.decision);\n\t\t\tif (!parsed.ok) {\n\t\t\t\treturn makeFailureOutcome(\n\t\t\t\t\tbinding,\n\t\t\t\t\tengineVersion,\n\t\t\t\t\t\"invalid_response\",\n\t\t\t\t\t`OPA returned malformed decision: ${parsed.error}`,\n\t\t\t\t\tonError,\n\t\t\t\t\tinputHash,\n\t\t\t\t\texecution,\n\t\t\t\t);\n\t\t\t}\n\n\t\t\treturn buildSuccessOutcome(\n\t\t\t\tbinding,\n\t\t\t\tengineVersion,\n\t\t\t\tparsed.decision,\n\t\t\t\texecution,\n\t\t\t\tinputHash,\n\t\t\t\tctx,\n\t\t\t\tmapDecision,\n\t\t\t);\n\t\t},\n\t};\n}\n\n/**\n * Discriminates between the rich executor shape and the legacy client shape.\n * Returns a uniform `(path, input) => OpaPolicyExecution` transport, or\n * `null` if the service doesn't implement either contract.\n *\n * `execute` is preferred when both are present so a v0.1 client wrapped by a\n * richer executor still wins.\n */\nfunction resolveTransport(\n\tservice: unknown,\n): ((path: string, input: unknown) => Promise<OpaPolicyExecution>) | null {\n\tif (!service || typeof service !== \"object\") return null;\n\tconst exec = (service as Partial<OpaPolicyExecutor>).execute;\n\tif (typeof exec === \"function\") {\n\t\treturn (path, input) => (service as OpaPolicyExecutor).execute(path, input);\n\t}\n\tconst eval_ = (service as Partial<OpaPolicyClient>).evaluate;\n\tif (typeof eval_ === \"function\") {\n\t\treturn async (path, input) => ({\n\t\t\tdecision: await (service as OpaPolicyClient).evaluate(path, input),\n\t\t});\n\t}\n\treturn null;\n}\n\nfunction buildSuccessOutcome<TDb>(\n\tbinding: OpaPolicyBinding,\n\tengineVersion: string | undefined,\n\tdecision: OpaDecision,\n\texecution: OpaPolicyExecution,\n\tinputHash: string | undefined,\n\tctx: PolicyContext<TDb>,\n\tmapDecision: CreateOpaPolicyEvaluatorOptions<TDb>[\"mapDecision\"],\n): PolicyOutcome {\n\tconst selection = selectBundleRevision(execution, binding);\n\tconst mapped = mapDecision\n\t\t? mapDecision(decision, ctx, execution)\n\t\t: { result: decision.result, reason: decision.reason };\n\n\treturn {\n\t\tpolicyId: binding.policyId,\n\t\tpolicyVersion: binding.version,\n\t\tresult: mapped.result ?? decision.result,\n\t\treason: mapped.reason ?? decision.reason,\n\t\tguidance: mapped.guidance ?? decision.guidance,\n\t\tmetadata: {\n\t\t\t...(mapped.metadata ?? {}),\n\t\t\topaDecision: decision,\n\t\t},\n\t\tdispatchEvidence: {\n\t\t\tpolicyKind: \"code\",\n\t\t\tpolicyId: binding.policyId,\n\t\t\tpolicyVersion: binding.version,\n\t\t\tdispatchPath: [\"code\"],\n\t\t\tengine: {\n\t\t\t\tname: ENGINE_NAME,\n\t\t\t\tversion: execution.opaVersion ?? engineVersion,\n\t\t\t\tmetadata: stripUndefined({\n\t\t\t\t\tdecisionPath: binding.decisionPath,\n\t\t\t\t\tregoPackage: binding.regoPackage,\n\t\t\t\t\tinputHash,\n\t\t\t\t\tdecisionId: execution.decisionId,\n\t\t\t\t\tbundleName: binding.bundleName,\n\t\t\t\t\tbundleRevision: selection.bundleRevision,\n\t\t\t\t\tbundleRevisionStatus: selection.bundleRevisionStatus,\n\t\t\t\t\tprovenance: execution.provenance,\n\t\t\t\t\tconditionResults: decision.conditionResults,\n\t\t\t\t\tobligations: decision.obligations,\n\t\t\t\t}),\n\t\t\t},\n\t\t},\n\t};\n}\n\nfunction makeFailureOutcome(\n\tbinding: OpaPolicyBinding,\n\tengineVersion: string | undefined,\n\terror: OpaPolicyFailureKind,\n\treason: string,\n\tonError: \"block\" | \"throw\",\n\tinputHash?: string,\n\texecution?: OpaPolicyExecution,\n): PolicyOutcome {\n\tif (onError === \"throw\") {\n\t\tconst err = new Error(reason);\n\t\t(err as Error & { kind?: OpaPolicyFailureKind }).kind = error;\n\t\tthrow err;\n\t}\n\n\tconst selection = execution ? selectBundleRevision(execution, binding) : {};\n\n\treturn {\n\t\tpolicyId: binding.policyId,\n\t\tpolicyVersion: binding.version,\n\t\tresult: \"block\",\n\t\treason,\n\t\tguidance: {\n\t\t\tsummary: \"OPA policy evaluation could not complete.\",\n\t\t\tfactsUsed: [\n\t\t\t\t{ name: \"opaFailureKind\", value: error, label: \"Failure kind\" },\n\t\t\t\t{ name: \"decisionPath\", value: binding.decisionPath, label: \"Decision path\" },\n\t\t\t],\n\t\t\tcorrectiveActions: [\n\t\t\t\t{\n\t\t\t\t\tlabel: \"Check OPA policy engine\",\n\t\t\t\t\tdescription:\n\t\t\t\t\t\t\"Verify the OPA service is reachable, serving the expected bundle, and returning the Fabric OPA decision shape.\",\n\t\t\t\t},\n\t\t\t],\n\t\t},\n\t\tmetadata: {\n\t\t\topaError: error,\n\t\t},\n\t\tdispatchEvidence: {\n\t\t\tpolicyKind: \"code\",\n\t\t\tpolicyId: binding.policyId,\n\t\t\tpolicyVersion: binding.version,\n\t\t\tdispatchPath: [\"code\"],\n\t\t\tengine: {\n\t\t\t\tname: ENGINE_NAME,\n\t\t\t\tversion: execution?.opaVersion ?? engineVersion,\n\t\t\t\tmetadata: stripUndefined({\n\t\t\t\t\tdecisionPath: binding.decisionPath,\n\t\t\t\t\tregoPackage: binding.regoPackage,\n\t\t\t\t\tinputHash,\n\t\t\t\t\tdecisionId: execution?.decisionId,\n\t\t\t\t\tbundleName: binding.bundleName,\n\t\t\t\t\tbundleRevision: selection.bundleRevision,\n\t\t\t\t\tbundleRevisionStatus: selection.bundleRevisionStatus,\n\t\t\t\t\tprovenance: execution?.provenance,\n\t\t\t\t\terror,\n\t\t\t\t\terrorReason: reason,\n\t\t\t\t}),\n\t\t\t},\n\t\t},\n\t};\n}\n\nfunction stripUndefined(obj: Record<string, unknown>): Record<string, unknown> {\n\tconst out: Record<string, unknown> = {};\n\tfor (const [k, v] of Object.entries(obj)) {\n\t\tif (v !== undefined) out[k] = v;\n\t}\n\treturn out;\n}\n\nfunction formatError(err: unknown): string {\n\tif (err instanceof Error) return err.message;\n\tif (typeof err === \"string\") return err;\n\ttry {\n\t\treturn JSON.stringify(err);\n\t} catch {\n\t\treturn String(err);\n\t}\n}\n","import type {\n\tOpaPolicyClient,\n\tOpaPolicyExecution,\n\tOpaPolicyExecutor,\n} from \"./types\";\n\n/**\n * Wrap an `OpaPolicyClient` (the high-level `@open-policy-agent/opa` SDK\n * shape) as an {@link OpaPolicyExecutor}. The resulting executor carries no\n * OPA-side provenance — the high-level SDK discards `decisionId` and\n * `provenance` from the response — but does centralize the\n * `(path, input) => execution` plumbing so hosts can choose at startup whether\n * to wire a client or a full executor.\n *\n * For full provenance (decisionId, bundleRevision, opaVersion), prefer\n * {@link executorFromOpaHttp}.\n */\nexport function executorFromOpaClient(client: OpaPolicyClient): OpaPolicyExecutor {\n\treturn {\n\t\tasync execute(path: string, input: unknown): Promise<OpaPolicyExecution> {\n\t\t\tconst decision = await client.evaluate(path, input);\n\t\t\treturn { decision };\n\t\t},\n\t};\n}\n","import type { OpaPolicyExecution, OpaPolicyExecutor } from \"./types\";\n\nexport interface OpaHttpExecutorOptions {\n\t/**\n\t * Base URL of the OPA server, e.g. `\"http://localhost:8181\"` or\n\t * `\"https://opa.internal.example.com\"`. Trailing slash is permitted; the\n\t * executor normalizes it.\n\t */\n\tbaseUrl: string;\n\t/**\n\t * Override for `globalThis.fetch`. Lets the host inject a fetch instance\n\t * with retries, mTLS, OpenTelemetry instrumentation, etc. Defaults to\n\t * `globalThis.fetch`.\n\t */\n\tfetch?: typeof globalThis.fetch;\n\t/** Extra request headers (e.g. `Authorization`). */\n\theaders?: Record<string, string>;\n\t/**\n\t * Request OPA-side provenance (`decision_id`, `provenance.version`,\n\t * `provenance.bundles[*].revision`) via `?provenance=true`. Defaults to\n\t * `true` — turning it off forfeits OPA's contribution to audit evidence\n\t * and is rarely what you want.\n\t */\n\tprovenance?: boolean;\n}\n\ninterface OpaHttpResponseBody {\n\tresult?: unknown;\n\tdecision_id?: string;\n\tprovenance?: {\n\t\tversion?: string;\n\t\tbuild_commit?: string;\n\t\tbuild_timestamp?: string;\n\t\tbuild_host?: string;\n\t\tbundles?: Record<string, { revision?: string }>;\n\t};\n}\n\n/**\n * Build an {@link OpaPolicyExecutor} that talks to OPA's REST API directly.\n *\n * POSTs to `{baseUrl}/v1/data/{path}?provenance=true` with body\n * `{ \"input\": ... }`. Parses the snake_case response and lifts:\n *\n * - `result` → `execution.decision`\n * - `decision_id` → `execution.decisionId`\n * - `provenance.version` → `execution.opaVersion`\n * - `provenance` (whole block) → `execution.provenance`\n *\n * Bundle revision selection happens in the factory, not the executor, because\n * it depends on `binding.bundleName`.\n *\n * Calling this in environments without `globalThis.fetch` (older Node) throws\n * at call time; pass `fetch: nodeFetch` or `fetch: undici-fetch` etc. via the\n * options to support those runtimes explicitly.\n */\nexport function executorFromOpaHttp(opts: OpaHttpExecutorOptions): OpaPolicyExecutor {\n\tconst baseUrl = stripTrailingSlash(opts.baseUrl);\n\tconst provenance = opts.provenance ?? true;\n\tconst customFetch = opts.fetch;\n\tconst headers = {\n\t\t\"content-type\": \"application/json\",\n\t\taccept: \"application/json\",\n\t\t...(opts.headers ?? {}),\n\t};\n\n\treturn {\n\t\tasync execute(path: string, input: unknown): Promise<OpaPolicyExecution> {\n\t\t\tconst fetchImpl = customFetch ?? globalThis.fetch;\n\t\t\tif (typeof fetchImpl !== \"function\") {\n\t\t\t\tthrow new Error(\n\t\t\t\t\t\"executorFromOpaHttp: no fetch implementation available. Pass `fetch` in options or run on a runtime with `globalThis.fetch`.\",\n\t\t\t\t);\n\t\t\t}\n\n\t\t\tconst url = `${baseUrl}/v1/data/${stripLeadingSlash(path)}${\n\t\t\t\tprovenance ? \"?provenance=true\" : \"\"\n\t\t\t}`;\n\t\t\tconst response = await fetchImpl(url, {\n\t\t\t\tmethod: \"POST\",\n\t\t\t\theaders,\n\t\t\t\tbody: JSON.stringify({ input }),\n\t\t\t});\n\n\t\t\tif (!response.ok) {\n\t\t\t\tconst text = await safeReadText(response);\n\t\t\t\tthrow new Error(`OPA HTTP ${response.status} at ${url}: ${truncate(text, 500)}`);\n\t\t\t}\n\n\t\t\tconst body = (await response.json()) as OpaHttpResponseBody;\n\n\t\t\treturn {\n\t\t\t\tdecision: body.result,\n\t\t\t\tdecisionId: body.decision_id,\n\t\t\t\topaVersion: body.provenance?.version,\n\t\t\t\tprovenance: body.provenance as Record<string, unknown> | undefined,\n\t\t\t};\n\t\t},\n\t};\n}\n\nfunction stripTrailingSlash(s: string): string {\n\treturn s.replace(/\\/+$/, \"\");\n}\n\nfunction stripLeadingSlash(s: string): string {\n\treturn s.replace(/^\\/+/, \"\");\n}\n\nasync function safeReadText(response: Response): Promise<string> {\n\ttry {\n\t\treturn await response.text();\n\t} catch {\n\t\treturn \"<unreadable body>\";\n\t}\n}\n\nfunction truncate(s: string, max: number): string {\n\treturn s.length <= max ? s : `${s.slice(0, max)}…`;\n}\n"]}
package/dist/index.d.cts CHANGED
@@ -1,4 +1,4 @@
1
- import { PolicyId, PolicyContext, PolicyEvaluationResult, PolicyOutcome, PolicyEvaluator } from '@fabricorg/platform/policies';
1
+ import { PolicyId, PolicyContext, PolicyEvaluationResult, PolicyGuidance, PolicyOutcome, PolicyEvaluator } from '@fabricorg/platform/policies';
2
2
 
3
3
  /**
4
4
  * Binding between a Fabric platform policy and an OPA decision. Verticals
@@ -25,6 +25,58 @@ interface OpaPolicyBinding {
25
25
  * keep the package name aligned with the decision path.
26
26
  */
27
27
  regoPackage?: string;
28
+ /**
29
+ * Optional selector for `bundleRevision` extraction when OPA's
30
+ * `provenance.bundles` carries multiple bundles. If absent and OPA reports
31
+ * a single bundle, the adapter uses that revision unambiguously. If absent
32
+ * and multiple bundles are present, the adapter marks the evidence with
33
+ * `bundleRevisionStatus: "ambiguous"` so audit dashboards can flag policies
34
+ * that need explicit selectors.
35
+ *
36
+ * Example: `"lending"` for a bundle named `lending` served by OPA.
37
+ */
38
+ bundleName?: string;
39
+ }
40
+ /**
41
+ * Result of one OPA evaluation, normalized for the adapter. Returned by
42
+ * implementations of {@link OpaPolicyExecutor}. The adapter accepts either a
43
+ * client (with `evaluate`) or an executor (with `execute`); the executor path
44
+ * preserves provenance OPA exposes via `?provenance=true` — primarily
45
+ * `decision_id` and `provenance.bundles[*].revision`.
46
+ */
47
+ interface OpaPolicyExecution {
48
+ /** The raw decision body — the value of `result` in OPA's response. */
49
+ decision: unknown;
50
+ /** OPA's per-request decision ID (response field `decision_id`). */
51
+ decisionId?: string;
52
+ /**
53
+ * Pre-selected bundle revision, when the executor can determine it
54
+ * unambiguously without binding context (e.g. a transport that only ever
55
+ * sees a single bundle). The factory may override this from
56
+ * `provenance.bundles` + `binding.bundleName`.
57
+ */
58
+ bundleRevision?: string;
59
+ /** OPA server version (response field `provenance.version`). */
60
+ opaVersion?: string;
61
+ /**
62
+ * Raw `provenance` block from the OPA response. Carries
63
+ * `bundles: { [name]: { revision } }`, build info, etc. The factory uses
64
+ * this together with `binding.bundleName` to select `bundleRevision`.
65
+ */
66
+ provenance?: Record<string, unknown>;
67
+ }
68
+ /**
69
+ * Rich execution interface. Implementations are responsible for talking to
70
+ * OPA and surfacing provenance. Two official implementations ship in this
71
+ * package: {@link executorFromOpaClient} (wraps the high-level SDK; limited
72
+ * provenance) and {@link executorFromOpaHttp} (calls OPA REST directly with
73
+ * `?provenance=true`; full provenance).
74
+ *
75
+ * Hosts wire one of these into `ctx.services[serviceKey]` as an alternative
76
+ * to {@link OpaPolicyClient}.
77
+ */
78
+ interface OpaPolicyExecutor {
79
+ execute(path: string, input: unknown): Promise<OpaPolicyExecution>;
28
80
  }
29
81
  /**
30
82
  * Structured Rego decision shape — the "house style" the adapter expects from
@@ -35,13 +87,13 @@ interface OpaPolicyBinding {
35
87
  interface OpaDecision {
36
88
  result: PolicyEvaluationResult;
37
89
  reason?: string;
90
+ guidance?: PolicyGuidance;
38
91
  conditionResults?: Array<{
39
92
  conditionId: string;
40
93
  passed: boolean;
41
94
  result: PolicyEvaluationResult;
42
95
  reason?: string;
43
96
  }>;
44
- factsUsed?: Record<string, unknown>;
45
97
  obligations?: Record<string, unknown>;
46
98
  }
47
99
  /**
@@ -60,7 +112,18 @@ type OpaPolicyErrorMode = "block" | "throw";
60
112
  * something we couldn't parse" from "no client was injected at runtime".
61
113
  */
62
114
  type OpaPolicyFailureKind = "client_unavailable" | "input_build_failed" | "evaluation_failed" | "invalid_response";
63
- type OpaPolicyDecisionMapper<TDb = unknown> = (decision: OpaDecision, ctx: PolicyContext<TDb>) => Pick<PolicyOutcome, "result" | "reason"> & {
115
+ /**
116
+ * Maps a validated `OpaDecision` to the fields of a `PolicyOutcome` the
117
+ * adapter consumes (`result`, `reason`, optional extra `metadata`). The
118
+ * optional third argument, `execution`, exposes OPA-side provenance
119
+ * (`decisionId`, `bundleRevision`, raw `provenance`) so a mapper can lift
120
+ * specific fields into `outcome.metadata` if the host wants them queryable
121
+ * outside `dispatchEvidence.engine`.
122
+ *
123
+ * Existing two-argument mappers (`(decision, ctx) => …`) remain valid —
124
+ * TypeScript permits implementations with fewer parameters.
125
+ */
126
+ type OpaPolicyDecisionMapper<TDb = unknown> = (decision: OpaDecision, ctx: PolicyContext<TDb>, execution: OpaPolicyExecution) => Partial<PolicyOutcome> & {
64
127
  metadata?: Record<string, unknown>;
65
128
  };
66
129
  interface CreateOpaPolicyEvaluatorOptions<TDb = unknown> {
@@ -111,20 +174,39 @@ interface CreateOpaPolicyEvaluatorOptions<TDb = unknown> {
111
174
 
112
175
  /**
113
176
  * Build a Fabric `PolicyEvaluator` that delegates decision-making to an OPA
114
- * (Open Policy Agent) deployment. The evaluator:
177
+ * (Open Policy Agent) deployment.
178
+ *
179
+ * The adapter accepts either of two service shapes under
180
+ * `ctx.services[serviceKey]`:
115
181
  *
116
- * 1. Reads the host-injected OPA client from `ctx.services[serviceKey]`.
182
+ * - `OpaPolicyExecutor` (preferred) `execute(path, input)` returning a rich
183
+ * `OpaPolicyExecution` (decision plus `decisionId`, `bundleRevision`,
184
+ * `opaVersion`, `provenance`). Ship one with {@link executorFromOpaHttp} or
185
+ * {@link executorFromOpaClient}.
186
+ * - `OpaPolicyClient` — `evaluate(path, input)` returning the raw decision
187
+ * only. Compatible with the high-level `@open-policy-agent/opa` SDK at the
188
+ * cost of OPA-side provenance.
189
+ *
190
+ * If both methods are present, `execute` is preferred.
191
+ *
192
+ * The evaluator:
193
+ *
194
+ * 1. Resolves the service from `ctx.services[serviceKey]`.
117
195
  * 2. Builds a JSON input snapshot via `buildInput(ctx)` — domain code that
118
- * snapshots facts the engine needs. Fabric platform never lets OPA reach
119
- * into the database directly; all facts flow through this function.
120
- * 3. Evaluates the Rego decision at `binding.decisionPath`.
196
+ * snapshots facts the engine needs. OPA never reaches into the database
197
+ * directly; all facts flow through this function.
198
+ * 3. Calls OPA at `binding.decisionPath`.
121
199
  * 4. Validates the response against the house-style shape (`OpaDecision`).
122
200
  * 5. Maps the decision to a `PolicyOutcome` and attaches engine provenance
123
- * (`engine.name = "opa"`, `decisionPath`, `inputHash`) for audit.
201
+ * under `dispatchEvidence.engine` `name`, optional `version`, and
202
+ * metadata covering `decisionPath`, `regoPackage`, `inputHash`, plus (when
203
+ * the executor surfaces them) `decisionId`, `bundleName`, `bundleRevision`,
204
+ * `bundleRevisionStatus`, and the raw `provenance` block.
124
205
  *
125
- * Failures (missing client, build failure, network failure, malformed response)
126
- * are governed by `onError`. Default `"block"` honors Fabric's default-deny
127
- * posture and records the failure category under `engine.metadata.error`.
206
+ * Failures (missing client, build failure, network failure, malformed
207
+ * response) are governed by `onError`. Default `"block"` honors Fabric's
208
+ * default-deny posture and records the failure category under
209
+ * `engine.metadata.error`.
128
210
  */
129
211
  declare function createOpaPolicyEvaluator<TDb = unknown>(options: CreateOpaPolicyEvaluatorOptions<TDb>): PolicyEvaluator<TDb>;
130
212
 
@@ -160,4 +242,85 @@ declare function stableStringify(value: unknown): string;
160
242
  */
161
243
  declare function defaultHashInput(input: Record<string, unknown>): string;
162
244
 
163
- export { type CreateOpaPolicyEvaluatorOptions, type OpaDecision, type OpaDecisionParseResult, type OpaPolicyBinding, type OpaPolicyClient, type OpaPolicyDecisionMapper, type OpaPolicyErrorMode, type OpaPolicyFailureKind, createOpaPolicyEvaluator, defaultHashInput, parseOpaDecision, stableStringify };
245
+ /**
246
+ * Wrap an `OpaPolicyClient` (the high-level `@open-policy-agent/opa` SDK
247
+ * shape) as an {@link OpaPolicyExecutor}. The resulting executor carries no
248
+ * OPA-side provenance — the high-level SDK discards `decisionId` and
249
+ * `provenance` from the response — but does centralize the
250
+ * `(path, input) => execution` plumbing so hosts can choose at startup whether
251
+ * to wire a client or a full executor.
252
+ *
253
+ * For full provenance (decisionId, bundleRevision, opaVersion), prefer
254
+ * {@link executorFromOpaHttp}.
255
+ */
256
+ declare function executorFromOpaClient(client: OpaPolicyClient): OpaPolicyExecutor;
257
+
258
+ interface OpaHttpExecutorOptions {
259
+ /**
260
+ * Base URL of the OPA server, e.g. `"http://localhost:8181"` or
261
+ * `"https://opa.internal.example.com"`. Trailing slash is permitted; the
262
+ * executor normalizes it.
263
+ */
264
+ baseUrl: string;
265
+ /**
266
+ * Override for `globalThis.fetch`. Lets the host inject a fetch instance
267
+ * with retries, mTLS, OpenTelemetry instrumentation, etc. Defaults to
268
+ * `globalThis.fetch`.
269
+ */
270
+ fetch?: typeof globalThis.fetch;
271
+ /** Extra request headers (e.g. `Authorization`). */
272
+ headers?: Record<string, string>;
273
+ /**
274
+ * Request OPA-side provenance (`decision_id`, `provenance.version`,
275
+ * `provenance.bundles[*].revision`) via `?provenance=true`. Defaults to
276
+ * `true` — turning it off forfeits OPA's contribution to audit evidence
277
+ * and is rarely what you want.
278
+ */
279
+ provenance?: boolean;
280
+ }
281
+ /**
282
+ * Build an {@link OpaPolicyExecutor} that talks to OPA's REST API directly.
283
+ *
284
+ * POSTs to `{baseUrl}/v1/data/{path}?provenance=true` with body
285
+ * `{ "input": ... }`. Parses the snake_case response and lifts:
286
+ *
287
+ * - `result` → `execution.decision`
288
+ * - `decision_id` → `execution.decisionId`
289
+ * - `provenance.version` → `execution.opaVersion`
290
+ * - `provenance` (whole block) → `execution.provenance`
291
+ *
292
+ * Bundle revision selection happens in the factory, not the executor, because
293
+ * it depends on `binding.bundleName`.
294
+ *
295
+ * Calling this in environments without `globalThis.fetch` (older Node) throws
296
+ * at call time; pass `fetch: nodeFetch` or `fetch: undici-fetch` etc. via the
297
+ * options to support those runtimes explicitly.
298
+ */
299
+ declare function executorFromOpaHttp(opts: OpaHttpExecutorOptions): OpaPolicyExecutor;
300
+
301
+ interface BundleSelection {
302
+ bundleRevision?: string;
303
+ /**
304
+ * Set to `"ambiguous"` when OPA reports multiple bundles and the binding
305
+ * did not pick one with `bundleName`. The adapter records this on the
306
+ * evidence so dashboards can flag policies that need explicit selectors.
307
+ * `"missing"` is set when provenance was expected but absent.
308
+ */
309
+ bundleRevisionStatus?: "ambiguous" | "missing";
310
+ }
311
+ /**
312
+ * Determine which OPA bundle revision applies to this decision.
313
+ *
314
+ * Rules (in order):
315
+ * 1. If the executor already populated `execution.bundleRevision`, use it.
316
+ * 2. If `binding.bundleName` is set, look it up in `provenance.bundles`.
317
+ * 3. If exactly one bundle is reported, use its revision unambiguously.
318
+ * 4. If multiple bundles are reported and no selector exists, mark
319
+ * `bundleRevisionStatus: "ambiguous"`.
320
+ * 5. If no provenance is reported at all, return `{}` — the caller decides
321
+ * whether absence is meaningful (it is not, for executors that don't
322
+ * carry provenance).
323
+ */
324
+ declare function selectBundleRevision(execution: OpaPolicyExecution, binding: OpaPolicyBinding): BundleSelection;
325
+
326
+ export { type BundleSelection, type CreateOpaPolicyEvaluatorOptions, type OpaDecision, type OpaDecisionParseResult, type OpaHttpExecutorOptions, type OpaPolicyBinding, type OpaPolicyClient, type OpaPolicyDecisionMapper, type OpaPolicyErrorMode, type OpaPolicyExecution, type OpaPolicyExecutor, type OpaPolicyFailureKind, createOpaPolicyEvaluator, defaultHashInput, executorFromOpaClient, executorFromOpaHttp, parseOpaDecision, selectBundleRevision, stableStringify };
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { PolicyId, PolicyContext, PolicyEvaluationResult, PolicyOutcome, PolicyEvaluator } from '@fabricorg/platform/policies';
1
+ import { PolicyId, PolicyContext, PolicyEvaluationResult, PolicyGuidance, PolicyOutcome, PolicyEvaluator } from '@fabricorg/platform/policies';
2
2
 
3
3
  /**
4
4
  * Binding between a Fabric platform policy and an OPA decision. Verticals
@@ -25,6 +25,58 @@ interface OpaPolicyBinding {
25
25
  * keep the package name aligned with the decision path.
26
26
  */
27
27
  regoPackage?: string;
28
+ /**
29
+ * Optional selector for `bundleRevision` extraction when OPA's
30
+ * `provenance.bundles` carries multiple bundles. If absent and OPA reports
31
+ * a single bundle, the adapter uses that revision unambiguously. If absent
32
+ * and multiple bundles are present, the adapter marks the evidence with
33
+ * `bundleRevisionStatus: "ambiguous"` so audit dashboards can flag policies
34
+ * that need explicit selectors.
35
+ *
36
+ * Example: `"lending"` for a bundle named `lending` served by OPA.
37
+ */
38
+ bundleName?: string;
39
+ }
40
+ /**
41
+ * Result of one OPA evaluation, normalized for the adapter. Returned by
42
+ * implementations of {@link OpaPolicyExecutor}. The adapter accepts either a
43
+ * client (with `evaluate`) or an executor (with `execute`); the executor path
44
+ * preserves provenance OPA exposes via `?provenance=true` — primarily
45
+ * `decision_id` and `provenance.bundles[*].revision`.
46
+ */
47
+ interface OpaPolicyExecution {
48
+ /** The raw decision body — the value of `result` in OPA's response. */
49
+ decision: unknown;
50
+ /** OPA's per-request decision ID (response field `decision_id`). */
51
+ decisionId?: string;
52
+ /**
53
+ * Pre-selected bundle revision, when the executor can determine it
54
+ * unambiguously without binding context (e.g. a transport that only ever
55
+ * sees a single bundle). The factory may override this from
56
+ * `provenance.bundles` + `binding.bundleName`.
57
+ */
58
+ bundleRevision?: string;
59
+ /** OPA server version (response field `provenance.version`). */
60
+ opaVersion?: string;
61
+ /**
62
+ * Raw `provenance` block from the OPA response. Carries
63
+ * `bundles: { [name]: { revision } }`, build info, etc. The factory uses
64
+ * this together with `binding.bundleName` to select `bundleRevision`.
65
+ */
66
+ provenance?: Record<string, unknown>;
67
+ }
68
+ /**
69
+ * Rich execution interface. Implementations are responsible for talking to
70
+ * OPA and surfacing provenance. Two official implementations ship in this
71
+ * package: {@link executorFromOpaClient} (wraps the high-level SDK; limited
72
+ * provenance) and {@link executorFromOpaHttp} (calls OPA REST directly with
73
+ * `?provenance=true`; full provenance).
74
+ *
75
+ * Hosts wire one of these into `ctx.services[serviceKey]` as an alternative
76
+ * to {@link OpaPolicyClient}.
77
+ */
78
+ interface OpaPolicyExecutor {
79
+ execute(path: string, input: unknown): Promise<OpaPolicyExecution>;
28
80
  }
29
81
  /**
30
82
  * Structured Rego decision shape — the "house style" the adapter expects from
@@ -35,13 +87,13 @@ interface OpaPolicyBinding {
35
87
  interface OpaDecision {
36
88
  result: PolicyEvaluationResult;
37
89
  reason?: string;
90
+ guidance?: PolicyGuidance;
38
91
  conditionResults?: Array<{
39
92
  conditionId: string;
40
93
  passed: boolean;
41
94
  result: PolicyEvaluationResult;
42
95
  reason?: string;
43
96
  }>;
44
- factsUsed?: Record<string, unknown>;
45
97
  obligations?: Record<string, unknown>;
46
98
  }
47
99
  /**
@@ -60,7 +112,18 @@ type OpaPolicyErrorMode = "block" | "throw";
60
112
  * something we couldn't parse" from "no client was injected at runtime".
61
113
  */
62
114
  type OpaPolicyFailureKind = "client_unavailable" | "input_build_failed" | "evaluation_failed" | "invalid_response";
63
- type OpaPolicyDecisionMapper<TDb = unknown> = (decision: OpaDecision, ctx: PolicyContext<TDb>) => Pick<PolicyOutcome, "result" | "reason"> & {
115
+ /**
116
+ * Maps a validated `OpaDecision` to the fields of a `PolicyOutcome` the
117
+ * adapter consumes (`result`, `reason`, optional extra `metadata`). The
118
+ * optional third argument, `execution`, exposes OPA-side provenance
119
+ * (`decisionId`, `bundleRevision`, raw `provenance`) so a mapper can lift
120
+ * specific fields into `outcome.metadata` if the host wants them queryable
121
+ * outside `dispatchEvidence.engine`.
122
+ *
123
+ * Existing two-argument mappers (`(decision, ctx) => …`) remain valid —
124
+ * TypeScript permits implementations with fewer parameters.
125
+ */
126
+ type OpaPolicyDecisionMapper<TDb = unknown> = (decision: OpaDecision, ctx: PolicyContext<TDb>, execution: OpaPolicyExecution) => Partial<PolicyOutcome> & {
64
127
  metadata?: Record<string, unknown>;
65
128
  };
66
129
  interface CreateOpaPolicyEvaluatorOptions<TDb = unknown> {
@@ -111,20 +174,39 @@ interface CreateOpaPolicyEvaluatorOptions<TDb = unknown> {
111
174
 
112
175
  /**
113
176
  * Build a Fabric `PolicyEvaluator` that delegates decision-making to an OPA
114
- * (Open Policy Agent) deployment. The evaluator:
177
+ * (Open Policy Agent) deployment.
178
+ *
179
+ * The adapter accepts either of two service shapes under
180
+ * `ctx.services[serviceKey]`:
115
181
  *
116
- * 1. Reads the host-injected OPA client from `ctx.services[serviceKey]`.
182
+ * - `OpaPolicyExecutor` (preferred) `execute(path, input)` returning a rich
183
+ * `OpaPolicyExecution` (decision plus `decisionId`, `bundleRevision`,
184
+ * `opaVersion`, `provenance`). Ship one with {@link executorFromOpaHttp} or
185
+ * {@link executorFromOpaClient}.
186
+ * - `OpaPolicyClient` — `evaluate(path, input)` returning the raw decision
187
+ * only. Compatible with the high-level `@open-policy-agent/opa` SDK at the
188
+ * cost of OPA-side provenance.
189
+ *
190
+ * If both methods are present, `execute` is preferred.
191
+ *
192
+ * The evaluator:
193
+ *
194
+ * 1. Resolves the service from `ctx.services[serviceKey]`.
117
195
  * 2. Builds a JSON input snapshot via `buildInput(ctx)` — domain code that
118
- * snapshots facts the engine needs. Fabric platform never lets OPA reach
119
- * into the database directly; all facts flow through this function.
120
- * 3. Evaluates the Rego decision at `binding.decisionPath`.
196
+ * snapshots facts the engine needs. OPA never reaches into the database
197
+ * directly; all facts flow through this function.
198
+ * 3. Calls OPA at `binding.decisionPath`.
121
199
  * 4. Validates the response against the house-style shape (`OpaDecision`).
122
200
  * 5. Maps the decision to a `PolicyOutcome` and attaches engine provenance
123
- * (`engine.name = "opa"`, `decisionPath`, `inputHash`) for audit.
201
+ * under `dispatchEvidence.engine` `name`, optional `version`, and
202
+ * metadata covering `decisionPath`, `regoPackage`, `inputHash`, plus (when
203
+ * the executor surfaces them) `decisionId`, `bundleName`, `bundleRevision`,
204
+ * `bundleRevisionStatus`, and the raw `provenance` block.
124
205
  *
125
- * Failures (missing client, build failure, network failure, malformed response)
126
- * are governed by `onError`. Default `"block"` honors Fabric's default-deny
127
- * posture and records the failure category under `engine.metadata.error`.
206
+ * Failures (missing client, build failure, network failure, malformed
207
+ * response) are governed by `onError`. Default `"block"` honors Fabric's
208
+ * default-deny posture and records the failure category under
209
+ * `engine.metadata.error`.
128
210
  */
129
211
  declare function createOpaPolicyEvaluator<TDb = unknown>(options: CreateOpaPolicyEvaluatorOptions<TDb>): PolicyEvaluator<TDb>;
130
212
 
@@ -160,4 +242,85 @@ declare function stableStringify(value: unknown): string;
160
242
  */
161
243
  declare function defaultHashInput(input: Record<string, unknown>): string;
162
244
 
163
- export { type CreateOpaPolicyEvaluatorOptions, type OpaDecision, type OpaDecisionParseResult, type OpaPolicyBinding, type OpaPolicyClient, type OpaPolicyDecisionMapper, type OpaPolicyErrorMode, type OpaPolicyFailureKind, createOpaPolicyEvaluator, defaultHashInput, parseOpaDecision, stableStringify };
245
+ /**
246
+ * Wrap an `OpaPolicyClient` (the high-level `@open-policy-agent/opa` SDK
247
+ * shape) as an {@link OpaPolicyExecutor}. The resulting executor carries no
248
+ * OPA-side provenance — the high-level SDK discards `decisionId` and
249
+ * `provenance` from the response — but does centralize the
250
+ * `(path, input) => execution` plumbing so hosts can choose at startup whether
251
+ * to wire a client or a full executor.
252
+ *
253
+ * For full provenance (decisionId, bundleRevision, opaVersion), prefer
254
+ * {@link executorFromOpaHttp}.
255
+ */
256
+ declare function executorFromOpaClient(client: OpaPolicyClient): OpaPolicyExecutor;
257
+
258
+ interface OpaHttpExecutorOptions {
259
+ /**
260
+ * Base URL of the OPA server, e.g. `"http://localhost:8181"` or
261
+ * `"https://opa.internal.example.com"`. Trailing slash is permitted; the
262
+ * executor normalizes it.
263
+ */
264
+ baseUrl: string;
265
+ /**
266
+ * Override for `globalThis.fetch`. Lets the host inject a fetch instance
267
+ * with retries, mTLS, OpenTelemetry instrumentation, etc. Defaults to
268
+ * `globalThis.fetch`.
269
+ */
270
+ fetch?: typeof globalThis.fetch;
271
+ /** Extra request headers (e.g. `Authorization`). */
272
+ headers?: Record<string, string>;
273
+ /**
274
+ * Request OPA-side provenance (`decision_id`, `provenance.version`,
275
+ * `provenance.bundles[*].revision`) via `?provenance=true`. Defaults to
276
+ * `true` — turning it off forfeits OPA's contribution to audit evidence
277
+ * and is rarely what you want.
278
+ */
279
+ provenance?: boolean;
280
+ }
281
+ /**
282
+ * Build an {@link OpaPolicyExecutor} that talks to OPA's REST API directly.
283
+ *
284
+ * POSTs to `{baseUrl}/v1/data/{path}?provenance=true` with body
285
+ * `{ "input": ... }`. Parses the snake_case response and lifts:
286
+ *
287
+ * - `result` → `execution.decision`
288
+ * - `decision_id` → `execution.decisionId`
289
+ * - `provenance.version` → `execution.opaVersion`
290
+ * - `provenance` (whole block) → `execution.provenance`
291
+ *
292
+ * Bundle revision selection happens in the factory, not the executor, because
293
+ * it depends on `binding.bundleName`.
294
+ *
295
+ * Calling this in environments without `globalThis.fetch` (older Node) throws
296
+ * at call time; pass `fetch: nodeFetch` or `fetch: undici-fetch` etc. via the
297
+ * options to support those runtimes explicitly.
298
+ */
299
+ declare function executorFromOpaHttp(opts: OpaHttpExecutorOptions): OpaPolicyExecutor;
300
+
301
+ interface BundleSelection {
302
+ bundleRevision?: string;
303
+ /**
304
+ * Set to `"ambiguous"` when OPA reports multiple bundles and the binding
305
+ * did not pick one with `bundleName`. The adapter records this on the
306
+ * evidence so dashboards can flag policies that need explicit selectors.
307
+ * `"missing"` is set when provenance was expected but absent.
308
+ */
309
+ bundleRevisionStatus?: "ambiguous" | "missing";
310
+ }
311
+ /**
312
+ * Determine which OPA bundle revision applies to this decision.
313
+ *
314
+ * Rules (in order):
315
+ * 1. If the executor already populated `execution.bundleRevision`, use it.
316
+ * 2. If `binding.bundleName` is set, look it up in `provenance.bundles`.
317
+ * 3. If exactly one bundle is reported, use its revision unambiguously.
318
+ * 4. If multiple bundles are reported and no selector exists, mark
319
+ * `bundleRevisionStatus: "ambiguous"`.
320
+ * 5. If no provenance is reported at all, return `{}` — the caller decides
321
+ * whether absence is meaningful (it is not, for executors that don't
322
+ * carry provenance).
323
+ */
324
+ declare function selectBundleRevision(execution: OpaPolicyExecution, binding: OpaPolicyBinding): BundleSelection;
325
+
326
+ export { type BundleSelection, type CreateOpaPolicyEvaluatorOptions, type OpaDecision, type OpaDecisionParseResult, type OpaHttpExecutorOptions, type OpaPolicyBinding, type OpaPolicyClient, type OpaPolicyDecisionMapper, type OpaPolicyErrorMode, type OpaPolicyExecution, type OpaPolicyExecutor, type OpaPolicyFailureKind, createOpaPolicyEvaluator, defaultHashInput, executorFromOpaClient, executorFromOpaHttp, parseOpaDecision, selectBundleRevision, stableStringify };