@intentrax/sdk 1.3.0 → 1.7.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/index.ts CHANGED
@@ -4,6 +4,7 @@ export const SDK_VERSION = "1.0.0";
4
4
  export const API_VERSION = "v1";
5
5
  export const VERIFY_REQUEST_HASH_DOMAIN = "INTENTRAX_PUBLIC_SDK_VERIFY_REQUEST_V1";
6
6
  export const IDEMPOTENCY_KEY_DOMAIN = "INTENTRAX_PUBLIC_SDK_IDEMPOTENCY_V1";
7
+ export const AGENT_HOOK_IDEMPOTENCY_KEY_DOMAIN = "INTENTRAX_AGENT_HOOK_IDEMPOTENCY_V1";
7
8
  export const AGENT_GATEWAY_ADMISSION_REQUEST_HASH_DOMAIN = "INTENTRAX_AGENT_GATEWAY_ADMISSION_REQUEST_V1";
8
9
  export const AGENT_ADMISSION_SCHEMA_VERSION = "intentrax.runtime.agent_admission_request/1.0";
9
10
  export const AGENT_ADMISSION_ENDPOINT = "/v1/agent/admissions";
@@ -178,7 +179,36 @@ export function createIdempotencyKey(request) {
178
179
  // one raw, one hashed — so a durable admission receipt can be correlated against
179
180
  // the execution that carried the same key.
180
181
  export function admissionIdempotencyKeyHash(request) {
181
- return sha256Hex(createIdempotencyKey(request));
182
+ return executeIdempotencyKeyHash(createIdempotencyKey(request));
183
+ }
184
+
185
+ // executeIdempotencyKeyHash is the ONE idempotency-key rule shared by the
186
+ // admission and execute lanes. The engine records SHA-256(raw execute
187
+ // idempotency_key), with no domain prefix, as the execution's link key; an
188
+ // admission receipt correlates with an execution only when its
189
+ // idempotency_key_hash equals that value. So send the raw key K as the execute
190
+ // request's idempotency_key and executeIdempotencyKeyHash(K) as the admission
191
+ // request's idempotency_key_hash. Any other derivation (for example a
192
+ // domain-prefixed hash of a payload hash with no raw key the caller can send to
193
+ // execute) can never match, and every such execution reads as unadmitted.
194
+ export function executeIdempotencyKeyHash(idempotencyKey) {
195
+ if (!isNonEmptyStable(idempotencyKey)) {
196
+ throw new TypeError("executeIdempotencyKeyHash: idempotencyKey must be a non-empty string without leading or trailing whitespace");
197
+ }
198
+ return sha256Hex(idempotencyKey);
199
+ }
200
+
201
+ // agentHookExecuteIdempotencyKey returns the raw execute idempotency key that
202
+ // hooks generated by `intentrax agent init` derive from an admission
203
+ // request_payload_hash. The hook's admission idempotency_key_hash is
204
+ // executeIdempotencyKeyHash of this key, and the hook result exposes the key as
205
+ // execute_idempotency_key, so the execution that follows the admission carries
206
+ // the matching key.
207
+ export function agentHookExecuteIdempotencyKey(requestPayloadHash) {
208
+ if (!isSha256Hex(requestPayloadHash)) {
209
+ throw new TypeError("agentHookExecuteIdempotencyKey: requestPayloadHash must be 64 lowercase hex");
210
+ }
211
+ return AGENT_HOOK_IDEMPOTENCY_KEY_DOMAIN + requestPayloadHash;
182
212
  }
183
213
 
184
214
  export function buildVerificationEnvelope(request) {
@@ -999,3 +1029,882 @@ export function verificationPointerMetaTag({ proof_id: proofId, verify_url: veri
999
1029
  if (href.includes(";")) return null;
1000
1030
  return `<meta name="${VERIFICATION_POINTER_META_NAME}" content="${escapeVerificationPointerAttribute(`proof_id=${proofId};verify_url=${href}`)}">`;
1001
1031
  }
1032
+
1033
+ // Evidence-quality model (INTENTRAX_ASSURANCE_GAP_ANALYSIS.md §5,
1034
+ // implementation plan P0-6 / P1-D).
1035
+ //
1036
+ // A verification result is a set of per-dimension assessments. The overall
1037
+ // verdict is COMPUTED from them by the fixed rule in deriveAssuranceVerdict();
1038
+ // no signer asserts it. The rule, dimensions, results, profiles and verdict
1039
+ // precedence are ported unchanged from examples/effect-assurance-demo
1040
+ // (src/model.mjs), plus the LEGACY_DECISION_RECORD profile that every proof
1041
+ // issued today maps to. The Go offline verifier carries the same model
1042
+ // (engine/internal/verificationinfra/offlineproof/assessment.go); the two must
1043
+ // stay in step.
1044
+ export const VERIFICATION_ASSESSMENT_SCHEMA_VERSION = "intentrax.verification.assessment/0.1";
1045
+
1046
+ export const ASSURANCE_DIMENSIONS = Object.freeze([
1047
+ "RECORD_INTEGRITY",
1048
+ "SIGNER_AUTHENTICITY",
1049
+ "AUTHORIZATION",
1050
+ "EXECUTION_REPORTED",
1051
+ "EXECUTION_ATTESTED",
1052
+ "EFFECT_OBSERVED",
1053
+ "EFFECT_CONFIRMED",
1054
+ "CAUSAL_CHAIN",
1055
+ ]);
1056
+
1057
+ // §5.2, plus OBSERVED for the EFFECT_OBSERVED dimension.
1058
+ export const ASSESSMENT_RESULTS = Object.freeze([
1059
+ "VERIFIED",
1060
+ "REPORTED",
1061
+ "ATTESTED",
1062
+ "OBSERVED",
1063
+ "CONFIRMED",
1064
+ "CONTRADICTED",
1065
+ "PENDING",
1066
+ "INSUFFICIENT_EVIDENCE",
1067
+ "NOT_ASSESSED",
1068
+ "NOT_APPLICABLE",
1069
+ "FAILED",
1070
+ ]);
1071
+
1072
+ export const ASSESSMENT_PROVENANCE = Object.freeze({
1073
+ SELF_REPORTED: "SELF_REPORTED",
1074
+ INTENTRAX_DECISION: "INTENTRAX_DECISION",
1075
+ ENFORCEMENT_ATTESTED: "ENFORCEMENT_ATTESTED",
1076
+ AUTHORITATIVE_SOURCE: "AUTHORITATIVE_SOURCE",
1077
+ THIRD_PARTY_ATTESTED: "THIRD_PARTY_ATTESTED",
1078
+ VERIFIER_COMPUTED: "VERIFIER_COMPUTED",
1079
+ });
1080
+
1081
+ // Required dimensions per assurance profile. EXECUTION_REPORTED is
1082
+ // deliberately never required: a self-report can never satisfy a profile
1083
+ // (invariant 1).
1084
+ export const ASSURANCE_PROFILES = Object.freeze({
1085
+ LEGACY_DECISION_RECORD: Object.freeze(["RECORD_INTEGRITY"]),
1086
+ DECISION_RECORD: Object.freeze(["RECORD_INTEGRITY", "SIGNER_AUTHENTICITY", "AUTHORIZATION"]),
1087
+ AUTHORIZED_AND_ATTESTED: Object.freeze(["RECORD_INTEGRITY", "SIGNER_AUTHENTICITY", "AUTHORIZATION", "EXECUTION_ATTESTED"]),
1088
+ EFFECT_CONFIRMED: Object.freeze(["RECORD_INTEGRITY", "SIGNER_AUTHENTICITY", "AUTHORIZATION", "EFFECT_OBSERVED", "EFFECT_CONFIRMED"]),
1089
+ CAUSAL_CHAIN: Object.freeze([
1090
+ "RECORD_INTEGRITY", "SIGNER_AUTHENTICITY", "AUTHORIZATION", "EFFECT_OBSERVED", "EFFECT_CONFIRMED", "CAUSAL_CHAIN",
1091
+ ]),
1092
+ });
1093
+
1094
+ export const ASSURANCE_VERDICTS = Object.freeze({
1095
+ VERIFICATION_FAILED: "VERIFICATION_FAILED",
1096
+ INTEGRITY_ONLY: "INTEGRITY_ONLY",
1097
+ CONFLICTING_EVIDENCE: "CONFLICTING_EVIDENCE",
1098
+ PENDING_FINALITY: "PENDING_FINALITY",
1099
+ INSUFFICIENT_EVIDENCE: "INSUFFICIENT_EVIDENCE",
1100
+ VERIFIED_FOR_SCOPE: "VERIFIED_FOR_SCOPE",
1101
+ });
1102
+
1103
+ // Rule precedence, first-matching rule = 0. Weakening any dimension must
1104
+ // never move the verdict to a later rule.
1105
+ export const ASSURANCE_VERDICT_PRECEDENCE = Object.freeze({
1106
+ VERIFICATION_FAILED: 0,
1107
+ INTEGRITY_ONLY: 1,
1108
+ CONFLICTING_EVIDENCE: 2,
1109
+ PENDING_FINALITY: 3,
1110
+ INSUFFICIENT_EVIDENCE: 4,
1111
+ VERIFIED_FOR_SCOPE: 5,
1112
+ });
1113
+
1114
+ const WEAK_ASSESSMENT_RESULTS = new Set(["REPORTED", "INSUFFICIENT_EVIDENCE", "NOT_ASSESSED"]);
1115
+ const SATISFYING_ASSESSMENT_RESULTS = new Set(["VERIFIED", "ATTESTED", "OBSERVED", "CONFIRMED"]);
1116
+
1117
+ // §5.4, verbatim order. `assessments` is { [dimension]: result }. A required
1118
+ // dimension that is missing or NOT_APPLICABLE counts as INSUFFICIENT_EVIDENCE
1119
+ // (invariant 4: never a bare pass). A CONTRADICTED result in ANY dimension,
1120
+ // required by the profile or not, yields CONFLICTING_EVIDENCE (finding V-1):
1121
+ // a sealed NON_COMPLIANT policy decision must never read as VERIFIED_FOR_SCOPE.
1122
+ export function deriveAssuranceVerdict(assessments, profile) {
1123
+ const required = Object.hasOwn(ASSURANCE_PROFILES, profile) ? ASSURANCE_PROFILES[profile] : undefined;
1124
+ if (!required) {
1125
+ throw new Error("unknown assurance profile " + profile);
1126
+ }
1127
+ const all = Object.values(assessments);
1128
+ const req = required.map((d) => assessments[d] ?? "INSUFFICIENT_EVIDENCE");
1129
+ if (all.includes("FAILED")) return ASSURANCE_VERDICTS.VERIFICATION_FAILED;
1130
+ if (assessments.SIGNER_AUTHENTICITY !== "VERIFIED") return ASSURANCE_VERDICTS.INTEGRITY_ONLY;
1131
+ if (all.includes("CONTRADICTED")) return ASSURANCE_VERDICTS.CONFLICTING_EVIDENCE;
1132
+ if (req.includes("PENDING")) return ASSURANCE_VERDICTS.PENDING_FINALITY;
1133
+ if (req.some((r) => WEAK_ASSESSMENT_RESULTS.has(r) || !SATISFYING_ASSESSMENT_RESULTS.has(r))) return ASSURANCE_VERDICTS.INSUFFICIENT_EVIDENCE;
1134
+ return ASSURANCE_VERDICTS.VERIFIED_FOR_SCOPE;
1135
+ }
1136
+
1137
+ // Published wording of each limitation code; identical to the Go verifier.
1138
+ export const ASSURANCE_LIMITATION_TEXT = Object.freeze({
1139
+ EXECUTION_NOT_ATTESTED: "No trusted in-path enforcement component observed the action. The proof records an Intentrax decision, not an attested execution.",
1140
+ EFFECT_NOT_VERIFIED: "No authoritative downstream system was queried. The proof does not show that any external effect happened.",
1141
+ POLICY_BINDING_SYNTHETIC: "The policy reference in this proof is a fixed value of the proof pipeline, not a binding to an evaluated customer policy or mandate.",
1142
+ COMPLETENESS_NOT_ESTABLISHED: "Nothing proves that every consequential agent action was routed through Intentrax. A proof covers only the action it records.",
1143
+ SIGNER_AUTHENTICITY_REQUIRES_PINNED_ANCHORS: "Signatures were checked against public keys carried inside the proof. Who signed is established only when every signing key is pinned to a trust-bearing key in a published Intentrax key set.",
1144
+ // Used instead of POLICY_BINDING_SYNTHETIC when the signed AEP seals a
1145
+ // policy binding (AEP 1.1 policy-binding profile, RECORD_ONLY).
1146
+ POLICY_EVALUATION_NOT_RECHECKABLE: "The proof seals Intentrax's evaluation of a hash-pinned policy, but this verifier did not re-run it: the evaluated event cannot be rebuilt from this proof, or the policy document was not available. The recorded decision is Intentrax's statement, not an independently checked result.",
1147
+ POLICY_DECISION_NOT_ENFORCED: "The policy binding is RECORD_ONLY: the evaluation was recorded with the action, and nothing shows the action was gated on its result.",
1148
+ POLICY_CONSTRAINT_NOT_EVALUATED: "At least one constraint of the matched policy rule was not checked. This proof binds no evidence that it was met.",
1149
+ // Used instead of POLICY_EVALUATION_NOT_RECHECKABLE when the verifier
1150
+ // re-ran the sealed evaluation and it matched.
1151
+ POLICY_EVENT_SELF_REPORTED: "The verifier re-ran the published policy over the facts sealed in this proof and got the same evaluation: the decision follows from those facts and the published rule. The re-check does not independently witness that the facts (such as mutation_performed) are true; the runtime's signature attests to them.",
1152
+ });
1153
+
1154
+ // Limitations every proof under LEGACY_DECISION_RECORD carries.
1155
+ export const LEGACY_DECISION_RECORD_LIMITATIONS = Object.freeze([
1156
+ "EXECUTION_NOT_ATTESTED",
1157
+ "EFFECT_NOT_VERIFIED",
1158
+ "POLICY_BINDING_SYNTHETIC",
1159
+ "COMPLETENESS_NOT_ESTABLISHED",
1160
+ ]);
1161
+
1162
+ // Maps a verifier's signer-trust outcome to the SIGNER_AUTHENTICITY result.
1163
+ // Only TRUSTED against a supplied key set is VERIFIED. Without any key set the
1164
+ // dimension is NOT_ASSESSED; a REVOKED signer is FAILED; every other outcome
1165
+ // is INSUFFICIENT_EVIDENCE. Accepts the CLI's labels (UNPINNED_SIGNER,
1166
+ // MIXED_TRUST) and the Go verifier's (UNPINNED).
1167
+ export function signerAuthenticityAssessment(signerTrust, keySetSupplied) {
1168
+ if (!keySetSupplied) return { result: "NOT_ASSESSED", reasons: ["NO_TRUSTED_KEY_SET"] };
1169
+ switch (signerTrust) {
1170
+ case "TRUSTED":
1171
+ return { result: "VERIFIED", reasons: [] };
1172
+ case "REVOKED_SIGNER":
1173
+ return { result: "FAILED", reasons: ["REVOKED_SIGNER"] };
1174
+ case "SANDBOX_NON_TRUST_BEARING":
1175
+ case "INSUFFICIENT_TRUSTED_SIGNERS":
1176
+ case "MIXED_TRUST":
1177
+ return { result: "INSUFFICIENT_EVIDENCE", reasons: [signerTrust] };
1178
+ default:
1179
+ return { result: "INSUFFICIENT_EVIDENCE", reasons: ["UNPINNED_SIGNER"] };
1180
+ }
1181
+ }
1182
+
1183
+ // Maps the policy binding sealed in the signed AEP (null when there is none)
1184
+ // and the outcome of re-running it (null when no re-run was attempted) to the
1185
+ // AUTHORIZATION result, provenance, reasons and limitations. Same rule as the
1186
+ // Go verifier. Without a binding nothing is assessed. Only a re-run that
1187
+ // MATCHed lifts the dimension above REPORTED: a re-checked COMPLIANT decision
1188
+ // with no unchecked constraint is VERIFIED (VERIFIER_COMPUTED); with an
1189
+ // unchecked constraint it stays REPORTED. Without a matching re-run COMPLIANT
1190
+ // is REPORTED (INTENTRAX_DECISION). NON_COMPLIANT is CONTRADICTED and ERROR is
1191
+ // INSUFFICIENT_EVIDENCE either way.
1192
+ export function authorizationAssessment(policyBinding, policyReevaluation = null) {
1193
+ if (policyBinding === null || policyBinding === undefined) {
1194
+ return { result: "NOT_ASSESSED", provenance: "INTENTRAX_DECISION", reasons: ["DECISION_NOT_REEVALUATED_OFFLINE"], limitations: ["POLICY_BINDING_SYNTHETIC"] };
1195
+ }
1196
+ const rechecked = policyReevaluation !== null && policyReevaluation !== undefined && policyReevaluation.status === "MATCH";
1197
+ const unchecked = (Array.isArray(policyBinding.constraints) ? policyBinding.constraints : []).filter((constraint) => constraint.status !== "SATISFIED");
1198
+ let result = "INSUFFICIENT_EVIDENCE";
1199
+ const reasons = [];
1200
+ if (policyBinding.decision === "COMPLIANT") {
1201
+ result = rechecked && unchecked.length === 0 ? "VERIFIED" : "REPORTED";
1202
+ reasons.push("POLICY_DECISION_COMPLIANT");
1203
+ } else if (policyBinding.decision === "NON_COMPLIANT") {
1204
+ result = "CONTRADICTED";
1205
+ reasons.push("POLICY_DECISION_NON_COMPLIANT");
1206
+ } else {
1207
+ reasons.push("POLICY_DECISION_ERROR");
1208
+ }
1209
+ let limitations;
1210
+ if (rechecked) {
1211
+ reasons.push("POLICY_EVALUATION_RECHECKED");
1212
+ limitations = ["POLICY_EVENT_SELF_REPORTED", "POLICY_DECISION_NOT_ENFORCED"];
1213
+ } else {
1214
+ reasons.push("POLICY_EVALUATION_NOT_RECHECKED_OFFLINE");
1215
+ const reason = policyReevaluation === null || policyReevaluation === undefined ? "" : policyReevaluation.reason;
1216
+ if (typeof reason === "string" && reason !== "") reasons.push(`POLICY_REEVALUATION_${reason}`);
1217
+ limitations = ["POLICY_EVALUATION_NOT_RECHECKABLE", "POLICY_DECISION_NOT_ENFORCED"];
1218
+ }
1219
+ for (const constraint of unchecked) reasons.push(`POLICY_CONSTRAINT_NOT_EVALUATED:${constraint.constraint_id}`);
1220
+ if (unchecked.length > 0) limitations.push("POLICY_CONSTRAINT_NOT_EVALUATED");
1221
+ return { result, provenance: rechecked ? "VERIFIER_COMPUTED" : "INTENTRAX_DECISION", reasons, limitations };
1222
+ }
1223
+
1224
+ // Builds the verification_assessment block for a proof whose record
1225
+ // integrity has been verified, under the LEGACY_DECISION_RECORD profile.
1226
+ // policyBinding is the binding sealed in the signed AEP, or null;
1227
+ // policyReevaluation is the outcome of re-running it, or null. Nothing beyond
1228
+ // the record, its signers and the (re-checked or recorded) policy decision is
1229
+ // claimed.
1230
+ export function buildLegacyVerificationAssessment({ signerTrust, keySetSupplied, policyBinding = null, policyReevaluation = null } = {}) {
1231
+ const signer = signerAuthenticityAssessment(signerTrust, keySetSupplied === true);
1232
+ const authorization = authorizationAssessment(policyBinding, policyReevaluation);
1233
+ const signerVerified = signer.result === "VERIFIED";
1234
+ const row = (dimension, result, provenance, reasons, limitations) => ({ dimension, result, provenance, reasons, limitations });
1235
+ const assessments = [
1236
+ row("RECORD_INTEGRITY", "VERIFIED", "VERIFIER_COMPUTED", [], []),
1237
+ row("SIGNER_AUTHENTICITY", signer.result, "VERIFIER_COMPUTED", signer.reasons, signerVerified ? [] : ["SIGNER_AUTHENTICITY_REQUIRES_PINNED_ANCHORS"]),
1238
+ row("AUTHORIZATION", authorization.result, authorization.provenance, authorization.reasons, authorization.limitations),
1239
+ row("EXECUTION_REPORTED", "NOT_ASSESSED", null, ["NO_EXECUTION_REPORT_IN_PROOF"], []),
1240
+ row("EXECUTION_ATTESTED", "NOT_ASSESSED", null, ["NO_IN_PATH_ENFORCEMENT_ATTESTATION"], ["EXECUTION_NOT_ATTESTED"]),
1241
+ row("EFFECT_OBSERVED", "NOT_ASSESSED", null, ["NO_EFFECT_EVIDENCE"], ["EFFECT_NOT_VERIFIED"]),
1242
+ row("EFFECT_CONFIRMED", "NOT_ASSESSED", null, ["NO_EFFECT_EVIDENCE"], ["EFFECT_NOT_VERIFIED"]),
1243
+ row("CAUSAL_CHAIN", "NOT_ASSESSED", null, ["NO_DELEGATION_CHAIN_IN_PROOF"], []),
1244
+ ];
1245
+ const verdict = deriveAssuranceVerdict(Object.fromEntries(assessments.map((a) => [a.dimension, a.result])), "LEGACY_DECISION_RECORD");
1246
+ // The fixed legacy set, with POLICY_BINDING_SYNTHETIC replaced by the
1247
+ // AUTHORIZATION limitations when the proof seals a policy binding.
1248
+ const codes = [
1249
+ ...LEGACY_DECISION_RECORD_LIMITATIONS.flatMap((code) => (code === "POLICY_BINDING_SYNTHETIC" ? authorization.limitations : [code])),
1250
+ ...(signerVerified ? [] : ["SIGNER_AUTHENTICITY_REQUIRES_PINNED_ANCHORS"]),
1251
+ ];
1252
+ return {
1253
+ schema_version: VERIFICATION_ASSESSMENT_SCHEMA_VERSION,
1254
+ assurance_profile: "LEGACY_DECISION_RECORD",
1255
+ required_dimensions: [...ASSURANCE_PROFILES.LEGACY_DECISION_RECORD],
1256
+ verdict,
1257
+ assessments,
1258
+ limitations: codes.map((code) => ({ code, text: ASSURANCE_LIMITATION_TEXT[code] })),
1259
+ };
1260
+ }
1261
+
1262
+ // ---------------------------------------------------------------------------
1263
+ // Policy re-evaluation (AEP 1.1 policy-binding profile, P1-C step 2).
1264
+ //
1265
+ // A port of the Go policy engine pipeline (engine/internal/policyengine:
1266
+ // C2.1 DSL -> C2.2 parser -> C2.3 bytecode compiler -> C2.4 VM) that
1267
+ // recomputes every value an aep.policy_binding seals: source_policy_hash,
1268
+ // compiled_policy_hash, execution_event_hash, evaluation_hash, decision,
1269
+ // rule_id and the matched rule's constraints. A verifier fetches the policy by
1270
+ // hash (GET /v1/policies/{source_policy_hash}), rebuilds the evaluated event,
1271
+ // re-runs it here, and requires identical values instead of trusting them.
1272
+ //
1273
+ // It must reproduce the Go engine byte for byte: the shared vectors in
1274
+ // test-fixtures/policy-binding/policy-reevaluation-vectors.json are
1275
+ // generated by the Go engine and checked by policy-reevaluation.test.mjs. Any
1276
+ // divergence fails closed (a hash mismatch), never open.
1277
+ // ---------------------------------------------------------------------------
1278
+
1279
+ export const POLICY_HASH_DOMAIN = "INTENTRAX_POLICY_V1";
1280
+ export const POLICY_BYTECODE_HASH_DOMAIN = "INTENTRAX_BYTECODE_V1";
1281
+ export const POLICY_VM_TRACE_HASH_DOMAIN = "INTENTRAX_TRACE_V1";
1282
+ export const POLICY_VM_EVENT_HASH_DOMAIN = "INTENTRAX_POLICY_VM_EVENT_V1";
1283
+ export const POLICY_VM_EVALUATION_HASH_DOMAIN = "INTENTRAX_POLICY_VM_EVALUATION_V1";
1284
+
1285
+ const POLICY_BYTECODE_SCHEMA_VERSION = "1.0";
1286
+ const POLICY_BYTECODE_VERSION = "1.0";
1287
+ const POLICY_COMPILER_VERSION = "C2.3-1.0.0";
1288
+ const POLICY_VM_RUNTIME_VERSION = "PVM-1";
1289
+ const POLICY_MAX_RULES = 100;
1290
+ const POLICY_MAX_CONDITIONS_PER_RULE = 20;
1291
+ const POLICY_MAX_INSTRUCTIONS = 10000;
1292
+ const POLICY_MAX_CONSTANTS = 1000;
1293
+ const POLICY_MAX_STACK_DEPTH = 256;
1294
+ const POLICY_VM_MAX_EXECUTION_COST = 10000;
1295
+ const POLICY_VM_TASK_IDS = Object.freeze([
1296
+ "C2.4-S1-T1", "C2.4-S1-T2", "C2.4-S1-T3",
1297
+ "C2.4-S2-T1", "C2.4-S2-T2", "C2.4-S2-T3",
1298
+ "C2.4-S3-T1", "C2.4-S3-T2", "C2.4-S3-T3",
1299
+ ]);
1300
+
1301
+ const POLICY_IDENTIFIER_RE = /^[A-Za-z0-9][A-Za-z0-9._:-]{2,127}$/;
1302
+ const POLICY_VERSION_RE = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,63}$/;
1303
+ const POLICY_FIELDS = new Set(["policy_id", "policy_version", "rules", "default_effect"]);
1304
+ const POLICY_RULE_FIELDS = new Set(["rule_id", "effect", "conditions", "constraints", "priority"]);
1305
+ const POLICY_CONDITION_FIELDS = new Set(["field", "operator", "value"]);
1306
+ const POLICY_CONSTRAINT_FIELDS = new Set(["constraint_id", "type", "value"]);
1307
+ const POLICY_EFFECTS = new Set(["ALLOW", "DENY", "CONDITIONAL"]);
1308
+ const POLICY_CONDITION_OPERATORS = new Set(["EQUALS", "NOT_EQUALS", "IN", "NOT_IN", "EXISTS", "GREATER_THAN", "GREATER_THAN_OR_EQUAL", "LESS_THAN", "LESS_THAN_OR_EQUAL"]);
1309
+ const POLICY_CONSTRAINT_TYPES = new Set(["MAX_AMOUNT", "MAX_RETRIES", "TIMEOUT_MS", "REQUIRE_APPROVAL", "REQUIRE_GUARDRAIL_PASS", "RESTRICT_TARGET"]);
1310
+ const POLICY_FORBIDDEN_TOKENS = Object.freeze(["clock", "command", "dynamic", "eval", "external", "function", "http://", "https://", "latest", "now", "random", "script", "webhook"]);
1311
+ const POLICY_COMPARISON_OPCODES = Object.freeze({
1312
+ EQUALS: "CMP_EQ",
1313
+ NOT_EQUALS: "CMP_NEQ",
1314
+ GREATER_THAN: "CMP_GT",
1315
+ GREATER_THAN_OR_EQUAL: "CMP_GTE",
1316
+ LESS_THAN: "CMP_LT",
1317
+ LESS_THAN_OR_EQUAL: "CMP_LTE",
1318
+ });
1319
+ const POLICY_OPCODE_VALUES = Object.freeze({
1320
+ LOAD_FIELD: 0x01, LOAD_CONST: 0x02, CMP_EQ: 0x03, CMP_NEQ: 0x04, CMP_GT: 0x05, CMP_GTE: 0x06,
1321
+ CMP_LT: 0x07, CMP_LTE: 0x08, AND: 0x09, OR: 0x0a, NOT: 0x0b, JUMP: 0x0c, JUMP_IF_FALSE: 0x0d,
1322
+ RULE_ALLOW: 0x0e, RULE_DENY: 0x0f, RULE_END: 0x10,
1323
+ });
1324
+
1325
+ class PolicyReevaluationError extends Error {
1326
+ constructor(code, message) {
1327
+ super(message);
1328
+ this.name = "PolicyReevaluationError";
1329
+ this.code = code;
1330
+ }
1331
+ }
1332
+
1333
+ // Members of an ordered object are emitted in declaration order (Go
1334
+ // canonicaljson.OrderedObject); plain objects are emitted with keys sorted
1335
+ // bytewise (Go maps).
1336
+ const ORDERED_MEMBERS = Symbol("intentrax.policy.ordered");
1337
+
1338
+ function orderedObject(...members) {
1339
+ return { [ORDERED_MEMBERS]: members };
1340
+ }
1341
+
1342
+ function utf8Compare(left, right) {
1343
+ return Buffer.compare(Buffer.from(left, "utf8"), Buffer.from(right, "utf8"));
1344
+ }
1345
+
1346
+ // Go encoding/json string encoding: HTML-safe escapes and U+2028/U+2029.
1347
+ function goJSONString(value) {
1348
+ if (/[\ud800-\udfff]/.test(value.replace(/[\ud800-\udbff][\udc00-\udfff]/g, ""))) {
1349
+ throw new PolicyReevaluationError("POLICY_ENCODING_UNSUPPORTED", "lone surrogate in a policy string");
1350
+ }
1351
+ return JSON.stringify(value)
1352
+ .replace(/</g, "\\u003c")
1353
+ .replace(/>/g, "\\u003e")
1354
+ .replace(/&/g, "\\u0026")
1355
+ .replace(new RegExp(String.fromCharCode(0x2028), "g"), "\\u2028")
1356
+ .replace(new RegExp(String.fromCharCode(0x2029), "g"), "\\u2029");
1357
+ }
1358
+
1359
+ function policyCanonical(value) {
1360
+ if (value === null) return "null";
1361
+ if (typeof value === "string") return goJSONString(value);
1362
+ if (typeof value === "boolean") return value ? "true" : "false";
1363
+ if (typeof value === "number") {
1364
+ if (!Number.isSafeInteger(value)) throw new PolicyReevaluationError("POLICY_ENCODING_UNSUPPORTED", "only safe integers are supported");
1365
+ return String(value);
1366
+ }
1367
+ if (Array.isArray(value)) return "[" + value.map(policyCanonical).join(",") + "]";
1368
+ if (typeof value === "object") {
1369
+ const members = value[ORDERED_MEMBERS];
1370
+ if (members !== undefined) {
1371
+ return "{" + members.map(([key, member]) => goJSONString(key) + ":" + policyCanonical(member)).join(",") + "}";
1372
+ }
1373
+ const keys = Object.keys(value).sort(utf8Compare);
1374
+ return "{" + keys.map((key) => goJSONString(key) + ":" + policyCanonical(value[key])).join(",") + "}";
1375
+ }
1376
+ throw new PolicyReevaluationError("POLICY_ENCODING_UNSUPPORTED", "unsupported value");
1377
+ }
1378
+
1379
+ function isPlainPolicyObject(value) {
1380
+ return value !== null && typeof value === "object" && !Array.isArray(value);
1381
+ }
1382
+
1383
+ function policyNonEmpty(value) {
1384
+ return typeof value === "string" && value !== "" && value.trim() === value;
1385
+ }
1386
+
1387
+ function hasForbiddenPolicyToken(value) {
1388
+ const lower = value.toLowerCase();
1389
+ return POLICY_FORBIDDEN_TOKENS.some((token) => lower.includes(token));
1390
+ }
1391
+
1392
+ function policyLiteral(value) {
1393
+ if (typeof value === "string") return policyNonEmpty(value) && !hasForbiddenPolicyToken(value) ? { ok: true, value } : { ok: false };
1394
+ if (typeof value === "boolean") return { ok: true, value };
1395
+ if (typeof value === "number") return Number.isSafeInteger(value) ? { ok: true, value } : { ok: false };
1396
+ if (Array.isArray(value)) {
1397
+ if (value.length === 0) return { ok: false };
1398
+ const out = [];
1399
+ for (const item of value) {
1400
+ const literal = policyLiteral(item);
1401
+ if (!literal.ok) return { ok: false };
1402
+ out.push(literal.value);
1403
+ }
1404
+ return { ok: true, value: out };
1405
+ }
1406
+ return { ok: false };
1407
+ }
1408
+
1409
+ function onlyKnownFields(object, allowed) {
1410
+ return Object.keys(object).every((key) => allowed.has(key));
1411
+ }
1412
+
1413
+ function invalidPolicy(message) {
1414
+ return new PolicyReevaluationError("POLICY_DOCUMENT_INVALID", message);
1415
+ }
1416
+
1417
+ // C2.1: validate the policy document and return the normalized definition.
1418
+ function validatePolicyDefinition(policy, allowedEventFields) {
1419
+ if (!isPlainPolicyObject(policy)) throw invalidPolicy("policy must be a JSON object");
1420
+ if (!onlyKnownFields(policy, POLICY_FIELDS)) throw invalidPolicy("policy contains unknown top-level fields");
1421
+ if (typeof policy.policy_id !== "string" || !POLICY_IDENTIFIER_RE.test(policy.policy_id)) throw invalidPolicy("policy_id invalid");
1422
+ if (typeof policy.policy_version !== "string" || !POLICY_VERSION_RE.test(policy.policy_version)) throw invalidPolicy("policy_version invalid");
1423
+ if (policy.default_effect !== "DENY") throw invalidPolicy("default_effect must be DENY");
1424
+ const allowedFields = new Set(allowedEventFields);
1425
+ if (!Array.isArray(policy.rules) || policy.rules.length === 0) throw invalidPolicy("rules must be a non-empty array");
1426
+ const seenRuleIDs = new Set();
1427
+ const rules = policy.rules.map((rule, ruleIndex) => {
1428
+ if (!isPlainPolicyObject(rule) || !onlyKnownFields(rule, POLICY_RULE_FIELDS)) throw invalidPolicy(`rules[${ruleIndex}] invalid`);
1429
+ if (typeof rule.rule_id !== "string" || !POLICY_IDENTIFIER_RE.test(rule.rule_id) || seenRuleIDs.has(rule.rule_id)) throw invalidPolicy(`rules[${ruleIndex}].rule_id invalid`);
1430
+ seenRuleIDs.add(rule.rule_id);
1431
+ if (!POLICY_EFFECTS.has(rule.effect)) throw invalidPolicy(`rules[${ruleIndex}].effect invalid`);
1432
+ if (!Number.isSafeInteger(rule.priority)) throw invalidPolicy(`rules[${ruleIndex}].priority invalid`);
1433
+ if (!Array.isArray(rule.conditions)) throw invalidPolicy(`rules[${ruleIndex}].conditions invalid`);
1434
+ const conditions = rule.conditions.map((condition, conditionIndex) => {
1435
+ const at = `rules[${ruleIndex}].conditions[${conditionIndex}]`;
1436
+ if (!isPlainPolicyObject(condition) || !onlyKnownFields(condition, POLICY_CONDITION_FIELDS)) throw invalidPolicy(`${at} invalid`);
1437
+ if (!policyNonEmpty(condition.field) || !allowedFields.has(condition.field)) throw invalidPolicy(`${at}.field invalid`);
1438
+ if (!POLICY_CONDITION_OPERATORS.has(condition.operator)) throw invalidPolicy(`${at}.operator invalid`);
1439
+ const literal = policyLiteral(condition.value);
1440
+ if (!literal.ok) throw invalidPolicy(`${at}.value invalid`);
1441
+ return { field: condition.field, operator: condition.operator, value: literal.value, sourcePath: `policy.rules[${ruleIndex}].conditions[${conditionIndex}]` };
1442
+ });
1443
+ if (!Array.isArray(rule.constraints)) throw invalidPolicy(`rules[${ruleIndex}].constraints invalid`);
1444
+ const seenConstraintIDs = new Set();
1445
+ const constraints = rule.constraints.map((constraint, constraintIndex) => {
1446
+ const at = `rules[${ruleIndex}].constraints[${constraintIndex}]`;
1447
+ if (!isPlainPolicyObject(constraint) || !onlyKnownFields(constraint, POLICY_CONSTRAINT_FIELDS)) throw invalidPolicy(`${at} invalid`);
1448
+ if (typeof constraint.constraint_id !== "string" || !POLICY_IDENTIFIER_RE.test(constraint.constraint_id) || seenConstraintIDs.has(constraint.constraint_id)) throw invalidPolicy(`${at}.constraint_id invalid`);
1449
+ seenConstraintIDs.add(constraint.constraint_id);
1450
+ if (!POLICY_CONSTRAINT_TYPES.has(constraint.type)) throw invalidPolicy(`${at}.type invalid`);
1451
+ const literal = policyLiteral(constraint.value);
1452
+ if (!literal.ok) throw invalidPolicy(`${at}.value invalid`);
1453
+ return { constraint_id: constraint.constraint_id, type: constraint.type, value: literal.value };
1454
+ });
1455
+ if (rule.effect === "CONDITIONAL" && constraints.length === 0) throw invalidPolicy(`rules[${ruleIndex}] CONDITIONAL needs a constraint`);
1456
+ return { rule_id: rule.rule_id, effect: rule.effect, conditions, constraints, priority: rule.priority };
1457
+ });
1458
+ const seenPriorities = new Set();
1459
+ rules.forEach((rule, index) => {
1460
+ if (seenPriorities.has(rule.priority) || (index > 0 && rule.priority > rules[index - 1].priority)) throw invalidPolicy("rule priorities must be unique and descending");
1461
+ seenPriorities.add(rule.priority);
1462
+ });
1463
+ return { policy_id: policy.policy_id, policy_version: policy.policy_version, rules, default_effect: policy.default_effect };
1464
+ }
1465
+
1466
+ function canonicalPolicyDefinition(definition) {
1467
+ return policyCanonical(orderedObject(
1468
+ ["policy_id", definition.policy_id],
1469
+ ["policy_version", definition.policy_version],
1470
+ ["rules", definition.rules.map((rule) => orderedObject(
1471
+ ["rule_id", rule.rule_id],
1472
+ ["effect", rule.effect],
1473
+ ["conditions", rule.conditions.map((condition) => orderedObject(["field", condition.field], ["operator", condition.operator], ["value", condition.value]))],
1474
+ ["constraints", rule.constraints.map((constraint) => orderedObject(["constraint_id", constraint.constraint_id], ["type", constraint.type], ["value", constraint.value]))],
1475
+ ["priority", rule.priority],
1476
+ ))],
1477
+ ["default_effect", definition.default_effect],
1478
+ ));
1479
+ }
1480
+
1481
+ function literalConstantType(value) {
1482
+ if (typeof value === "number") return "NUMBER";
1483
+ if (typeof value === "boolean") return "BOOLEAN";
1484
+ if (typeof value === "string") return "STRING";
1485
+ return "STRUCTURED";
1486
+ }
1487
+
1488
+ function constantTypeRank(type) {
1489
+ return { FIELD: 1, STRING: 2, NUMBER: 3, BOOLEAN: 4 }[type] ?? 5;
1490
+ }
1491
+
1492
+ function sortedPolicyConditions(conditions) {
1493
+ return [...conditions].sort((left, right) =>
1494
+ utf8Compare(left.field, right.field)
1495
+ || utf8Compare(left.operator, right.operator)
1496
+ || utf8Compare(policyCanonical(left.value), policyCanonical(right.value))
1497
+ || utf8Compare(left.sourcePath, right.sourcePath));
1498
+ }
1499
+
1500
+ function constraintsPayload(constraints) {
1501
+ return constraints
1502
+ .map((constraint) => ({ constraint_id: constraint.constraint_id, type: constraint.type, value: constraint.value }))
1503
+ .sort((left, right) => utf8Compare(policyCanonical(left), policyCanonical(right)));
1504
+ }
1505
+
1506
+ function estimatePolicyStackDepth(rules) {
1507
+ let maxDepth = 0;
1508
+ for (const rule of rules) {
1509
+ let depth = 0;
1510
+ rule.conditions.forEach((_, conditionIndex) => {
1511
+ depth += 1;
1512
+ maxDepth = Math.max(maxDepth, depth);
1513
+ depth += 1;
1514
+ maxDepth = Math.max(maxDepth, depth);
1515
+ depth -= 1;
1516
+ if (conditionIndex > 0) depth -= 1;
1517
+ });
1518
+ }
1519
+ return maxDepth;
1520
+ }
1521
+
1522
+ function compiledPolicyHash(bytecode) {
1523
+ const header = bytecode.bytecode_header_domain;
1524
+ return sha256Hex(POLICY_BYTECODE_HASH_DOMAIN + policyCanonical(orderedObject(
1525
+ ["bytecode_header_domain", orderedObject(
1526
+ ["bytecode_schema_version", header.bytecode_schema_version],
1527
+ ["bytecode_version", header.bytecode_version],
1528
+ ["policy_hash", header.policy_hash],
1529
+ ["compiler_version", header.compiler_version],
1530
+ ["instruction_count", header.instruction_count],
1531
+ )],
1532
+ ["constant_pool", bytecode.constant_pool.map((constant) => orderedObject(
1533
+ ["index", constant.index], ["constant_type", constant.constant_type], ["value", constant.value], ["value_hash", constant.value_hash],
1534
+ ))],
1535
+ ["instruction_stream", bytecode.instruction_stream.map((instruction) => orderedObject(
1536
+ ["index", instruction.index], ["opcode", instruction.opcode], ["opcode_value", instruction.opcode_value],
1537
+ ["operand_a_type", instruction.operand_a_type], ["operand_a", instruction.operand_a],
1538
+ ["operand_b_type", instruction.operand_b_type], ["operand_b", instruction.operand_b],
1539
+ ))],
1540
+ )));
1541
+ }
1542
+
1543
+ // C2.1 -> C2.3: compile a policy document (its JSON text) to bytecode.
1544
+ export function compilePolicyDocument(policyJSON, allowedEventFields) {
1545
+ if (typeof policyJSON !== "string") throw invalidPolicy("policy document must be JSON text");
1546
+ if (!Array.isArray(allowedEventFields) || allowedEventFields.length === 0 || !allowedEventFields.every(policyNonEmpty)) {
1547
+ throw invalidPolicy("allowed event fields are required");
1548
+ }
1549
+ let parsed;
1550
+ try {
1551
+ parsed = JSON.parse(policyJSON);
1552
+ } catch {
1553
+ throw invalidPolicy("policy document is not JSON");
1554
+ }
1555
+ const definition = validatePolicyDefinition(parsed, allowedEventFields);
1556
+ const sourcePolicyHash = sha256Hex(POLICY_HASH_DOMAIN + canonicalPolicyDefinition(definition));
1557
+ // C2.3 supports ALLOW/DENY with comparison operators only.
1558
+ for (const rule of definition.rules) {
1559
+ if (rule.effect !== "ALLOW" && rule.effect !== "DENY") throw new PolicyReevaluationError("POLICY_COMPILE_FAILED", `rule ${rule.rule_id}: effect not compilable`);
1560
+ for (const condition of rule.conditions) {
1561
+ if (!(condition.operator in POLICY_COMPARISON_OPCODES)) throw new PolicyReevaluationError("POLICY_COMPILE_FAILED", `rule ${rule.rule_id}: operator not compilable`);
1562
+ }
1563
+ }
1564
+ const entries = new Map();
1565
+ const addConstant = (type, value) => {
1566
+ const canonical = policyCanonical(value);
1567
+ const key = type + "\u0000" + canonical;
1568
+ if (!entries.has(key)) entries.set(key, { type, canonical, value, value_hash: sha256Hex(type + "|" + canonical) });
1569
+ };
1570
+ for (const rule of definition.rules) {
1571
+ addConstant("STRING", rule.rule_id);
1572
+ addConstant("STRUCTURED", constraintsPayload(rule.constraints));
1573
+ for (const condition of sortedPolicyConditions(rule.conditions)) {
1574
+ addConstant("FIELD", condition.field);
1575
+ addConstant(literalConstantType(condition.value), condition.value);
1576
+ }
1577
+ }
1578
+ addConstant("STRING", "__default__");
1579
+ addConstant("STRUCTURED", []);
1580
+ if (entries.size > POLICY_MAX_CONSTANTS) throw new PolicyReevaluationError("POLICY_COMPILE_FAILED", "constant pool too large");
1581
+ const constants = [...entries.values()]
1582
+ .sort((left, right) => (constantTypeRank(left.type) - constantTypeRank(right.type)) || utf8Compare(left.canonical, right.canonical) || utf8Compare(left.type, right.type))
1583
+ .map((entry, index) => ({ index, constant_type: entry.type, value: entry.value, value_hash: entry.value_hash, canonical: entry.canonical }));
1584
+ const constantIndex = (type, value) => {
1585
+ const canonical = policyCanonical(value);
1586
+ const found = constants.find((constant) => constant.constant_type === type && constant.canonical === canonical);
1587
+ if (found === undefined) throw new PolicyReevaluationError("POLICY_COMPILE_FAILED", "constant missing");
1588
+ return found.index;
1589
+ };
1590
+ const instructions = [];
1591
+ const add = (opcode, operandAType, operandA, operandBType, operandB) => {
1592
+ instructions.push({ index: instructions.length, opcode, opcode_value: POLICY_OPCODE_VALUES[opcode], operand_a_type: operandAType, operand_a: operandA, operand_b_type: operandBType, operand_b: operandB });
1593
+ return instructions.length - 1;
1594
+ };
1595
+ for (const rule of definition.rules) {
1596
+ sortedPolicyConditions(rule.conditions).forEach((condition, conditionIndex) => {
1597
+ add("LOAD_FIELD", "FIELD_INDEX", constantIndex("FIELD", condition.field), "NONE", 0);
1598
+ add("LOAD_CONST", "CONST_INDEX", constantIndex(literalConstantType(condition.value), condition.value), "NONE", 0);
1599
+ add(POLICY_COMPARISON_OPCODES[condition.operator], "NONE", 0, "NONE", 0);
1600
+ if (conditionIndex > 0) add("AND", "NONE", 0, "NONE", 0);
1601
+ });
1602
+ const jumpIndex = rule.conditions.length > 0 ? add("JUMP_IF_FALSE", "JUMP_OFFSET", 0, "NONE", 0) : -1;
1603
+ const ruleIDIndex = constantIndex("STRING", rule.rule_id);
1604
+ const constraintIndex = constantIndex("STRUCTURED", constraintsPayload(rule.constraints));
1605
+ add(rule.effect === "ALLOW" ? "RULE_ALLOW" : "RULE_DENY", "CONST_INDEX", ruleIDIndex, "CONST_INDEX", constraintIndex);
1606
+ const ruleEndIndex = add("RULE_END", "NONE", 0, "NONE", 0);
1607
+ if (jumpIndex >= 0) instructions[jumpIndex].operand_a = ruleEndIndex - jumpIndex;
1608
+ }
1609
+ add("RULE_DENY", "CONST_INDEX", constantIndex("STRING", "__default__"), "CONST_INDEX", constantIndex("STRUCTURED", []));
1610
+ add("RULE_END", "NONE", 0, "NONE", 0);
1611
+ if (definition.rules.length > POLICY_MAX_RULES
1612
+ || definition.rules.some((rule) => rule.conditions.length > POLICY_MAX_CONDITIONS_PER_RULE)
1613
+ || instructions.length > POLICY_MAX_INSTRUCTIONS
1614
+ || estimatePolicyStackDepth(definition.rules) > POLICY_MAX_STACK_DEPTH) {
1615
+ throw new PolicyReevaluationError("POLICY_COMPILE_FAILED", "policy exceeds compiler safety limits");
1616
+ }
1617
+ const bytecode = {
1618
+ bytecode_header_domain: {
1619
+ bytecode_schema_version: POLICY_BYTECODE_SCHEMA_VERSION,
1620
+ bytecode_version: POLICY_BYTECODE_VERSION,
1621
+ policy_hash: sourcePolicyHash,
1622
+ compiled_policy_hash: "",
1623
+ compiler_version: POLICY_COMPILER_VERSION,
1624
+ instruction_count: instructions.length,
1625
+ },
1626
+ constant_pool: constants.map(({ canonical, ...constant }) => constant),
1627
+ instruction_stream: instructions,
1628
+ };
1629
+ bytecode.bytecode_header_domain.compiled_policy_hash = compiledPolicyHash(bytecode);
1630
+ return {
1631
+ policy_id: definition.policy_id,
1632
+ policy_version: definition.policy_version,
1633
+ source_policy_hash: sourcePolicyHash,
1634
+ compiled_policy_hash: bytecode.bytecode_header_domain.compiled_policy_hash,
1635
+ bytecode,
1636
+ };
1637
+ }
1638
+
1639
+ function cloneStackValue(value) {
1640
+ return { value_type: value.value_type, value: clonePolicyValue(value.value) };
1641
+ }
1642
+
1643
+ function clonePolicyValue(value) {
1644
+ if (Array.isArray(value)) return value.map(clonePolicyValue);
1645
+ if (isPlainPolicyObject(value)) return Object.fromEntries(Object.entries(value).map(([key, member]) => [key, clonePolicyValue(member)]));
1646
+ return value;
1647
+ }
1648
+
1649
+ function stackValueFromEventValue(value) {
1650
+ if (typeof value === "string") return { value_type: "string", value };
1651
+ if (typeof value === "boolean") return { value_type: "boolean", value };
1652
+ if (typeof value === "number" && Number.isSafeInteger(value)) return { value_type: "number", value };
1653
+ return { value_type: "unsupported", value: null };
1654
+ }
1655
+
1656
+ function resolveEventField(event, field) {
1657
+ let current = event;
1658
+ for (const part of field.split(".")) {
1659
+ if (!isPlainPolicyObject(current) || !Object.hasOwn(current, part)) return { value_type: "NULL_VALUE", value: null };
1660
+ current = current[part];
1661
+ }
1662
+ if (current === null) return { value_type: "NULL_LITERAL", value: null };
1663
+ return stackValueFromEventValue(current);
1664
+ }
1665
+
1666
+ function stackValueFromConstant(constant) {
1667
+ switch (constant.constant_type) {
1668
+ case "STRING": return typeof constant.value === "string" ? { value_type: "string", value: constant.value } : null;
1669
+ case "NUMBER": return Number.isSafeInteger(constant.value) ? { value_type: "number", value: constant.value } : null;
1670
+ case "BOOLEAN": return typeof constant.value === "boolean" ? { value_type: "boolean", value: constant.value } : null;
1671
+ default: return null;
1672
+ }
1673
+ }
1674
+
1675
+ function isNullStackValue(value) {
1676
+ return value.value_type === "NULL_VALUE" || value.value_type === "NULL_LITERAL";
1677
+ }
1678
+
1679
+ function compareStackValues(left, right, opcode) {
1680
+ if (isNullStackValue(left) || isNullStackValue(right)) {
1681
+ if (opcode === "CMP_EQ") return { value: left.value_type === right.value_type };
1682
+ if (opcode === "CMP_NEQ") return { value: left.value_type !== right.value_type };
1683
+ return { error: "ERR_TYPE_MISMATCH" };
1684
+ }
1685
+ if (left.value_type !== right.value_type) return { error: "ERR_TYPE_MISMATCH" };
1686
+ if (left.value_type === "string" || left.value_type === "boolean") {
1687
+ if (opcode === "CMP_EQ") return { value: left.value === right.value };
1688
+ if (opcode === "CMP_NEQ") return { value: left.value !== right.value };
1689
+ return { error: "ERR_TYPE_MISMATCH" };
1690
+ }
1691
+ if (left.value_type === "number") {
1692
+ switch (opcode) {
1693
+ case "CMP_EQ": return { value: left.value === right.value };
1694
+ case "CMP_NEQ": return { value: left.value !== right.value };
1695
+ case "CMP_GT": return { value: left.value > right.value };
1696
+ case "CMP_GTE": return { value: left.value >= right.value };
1697
+ case "CMP_LT": return { value: left.value < right.value };
1698
+ case "CMP_LTE": return { value: left.value <= right.value };
1699
+ default: return { error: "ERR_INVALID_INSTRUCTION" };
1700
+ }
1701
+ }
1702
+ return { error: "ERR_TYPE_MISMATCH" };
1703
+ }
1704
+
1705
+ function policyInstructionCost(opcode) {
1706
+ if (opcode === "LOAD_FIELD") return 3;
1707
+ if (opcode.startsWith("CMP_")) return 2;
1708
+ return 1;
1709
+ }
1710
+
1711
+ function policyRuntimeError(errorCode) {
1712
+ return { decision: "ERROR", rule_id: "", constraints: [], error_code: errorCode };
1713
+ }
1714
+
1715
+ // C2.4: run the bytecode over the event; returns the evaluation result and
1716
+ // the VM trace exactly as the Go VM records them.
1717
+ function executePolicyBytecode(bytecode, event) {
1718
+ const instructions = bytecode.instruction_stream;
1719
+ const constants = bytecode.constant_pool;
1720
+ const stack = [];
1721
+ const trace = [];
1722
+ let ip = 0;
1723
+ let step = 0;
1724
+ let cost = 0;
1725
+ const constantAt = (index, type) => {
1726
+ const constant = Number.isInteger(index) && index >= 0 && index < constants.length ? constants[index] : undefined;
1727
+ if (constant === undefined || (type !== "" && constant.constant_type !== type)) return undefined;
1728
+ return constant;
1729
+ };
1730
+ const push = (value) => {
1731
+ if (stack.length + 1 > POLICY_MAX_STACK_DEPTH) return "ERR_STACK_OVERFLOW";
1732
+ stack.push(value);
1733
+ return "";
1734
+ };
1735
+ const pop = () => (stack.length === 0 ? { error: "ERR_STACK_UNDERFLOW" } : { value: stack.pop() });
1736
+ const popBool = () => {
1737
+ const popped = pop();
1738
+ if (popped.error) return popped;
1739
+ if (popped.value.value_type !== "boolean" || typeof popped.value.value !== "boolean") return { error: "ERR_TYPE_MISMATCH" };
1740
+ return { value: popped.value.value };
1741
+ };
1742
+ const apply = (instruction) => {
1743
+ const next = ip + 1;
1744
+ switch (instruction.opcode) {
1745
+ case "LOAD_FIELD": {
1746
+ const constant = constantAt(instruction.operand_a, "FIELD");
1747
+ if (constant === undefined || typeof constant.value !== "string" || constant.value === "") return { next, error: "ERR_INVALID_CONSTANT" };
1748
+ return { next, error: push(resolveEventField(event, constant.value)) };
1749
+ }
1750
+ case "LOAD_CONST": {
1751
+ const constant = constantAt(instruction.operand_a, "");
1752
+ if (constant === undefined || constant.constant_type === "FIELD" || constant.constant_type === "STRUCTURED") return { next, error: "ERR_INVALID_CONSTANT" };
1753
+ const value = stackValueFromConstant(constant);
1754
+ if (value === null) return { next, error: "ERR_INVALID_CONSTANT" };
1755
+ return { next, error: push(value) };
1756
+ }
1757
+ case "CMP_EQ": case "CMP_NEQ": case "CMP_GT": case "CMP_GTE": case "CMP_LT": case "CMP_LTE": {
1758
+ const right = pop();
1759
+ if (right.error) return { next, error: right.error };
1760
+ const left = pop();
1761
+ if (left.error) return { next, error: left.error };
1762
+ const compared = compareStackValues(left.value, right.value, instruction.opcode);
1763
+ if (compared.error) return { next, error: compared.error };
1764
+ return { next, error: push({ value_type: "boolean", value: compared.value }) };
1765
+ }
1766
+ case "AND": case "OR": {
1767
+ const right = popBool();
1768
+ if (right.error) return { next, error: right.error };
1769
+ const left = popBool();
1770
+ if (left.error) return { next, error: left.error };
1771
+ const value = instruction.opcode === "AND" ? left.value && right.value : left.value || right.value;
1772
+ return { next, error: push({ value_type: "boolean", value }) };
1773
+ }
1774
+ case "NOT": {
1775
+ const value = popBool();
1776
+ if (value.error) return { next, error: value.error };
1777
+ return { next, error: push({ value_type: "boolean", value: !value.value }) };
1778
+ }
1779
+ case "JUMP": {
1780
+ const target = ip + instruction.operand_a;
1781
+ if (target < 0 || target >= instructions.length) return { next, error: "ERR_INVALID_JUMP" };
1782
+ return { next: target, error: "" };
1783
+ }
1784
+ case "JUMP_IF_FALSE": {
1785
+ const condition = popBool();
1786
+ if (condition.error) return { next, error: condition.error };
1787
+ if (condition.value) return { next, error: "" };
1788
+ const target = ip + instruction.operand_a;
1789
+ if (target < 0 || target >= instructions.length) return { next, error: "ERR_INVALID_JUMP" };
1790
+ return { next: target, error: "" };
1791
+ }
1792
+ case "RULE_ALLOW": case "RULE_DENY": {
1793
+ const ruleConstant = constantAt(instruction.operand_a, "STRING");
1794
+ if (ruleConstant === undefined || typeof ruleConstant.value !== "string" || ruleConstant.value === "") return { next, error: "ERR_INVALID_CONSTANT" };
1795
+ const constraintConstant = constantAt(instruction.operand_b, "STRUCTURED");
1796
+ if (constraintConstant === undefined || !Array.isArray(constraintConstant.value)) return { next, error: "ERR_INVALID_CONSTANT" };
1797
+ return {
1798
+ next,
1799
+ error: "",
1800
+ result: {
1801
+ decision: instruction.opcode === "RULE_DENY" ? "NON_COMPLIANT" : "COMPLIANT",
1802
+ rule_id: ruleConstant.value,
1803
+ constraints: clonePolicyValue(constraintConstant.value),
1804
+ error_code: "",
1805
+ },
1806
+ };
1807
+ }
1808
+ case "RULE_END":
1809
+ return { next, error: "" };
1810
+ default:
1811
+ return { next, error: "ERR_INVALID_INSTRUCTION" };
1812
+ }
1813
+ };
1814
+ while (ip >= 0 && ip < instructions.length) {
1815
+ const instruction = instructions[ip];
1816
+ if (step >= POLICY_MAX_INSTRUCTIONS || cost + policyInstructionCost(instruction.opcode) > POLICY_VM_MAX_EXECUTION_COST) return { result: policyRuntimeError("ERR_RUNTIME_LIMIT_EXCEEDED"), trace };
1817
+ if (trace.length + 1 > POLICY_MAX_INSTRUCTIONS) return { result: policyRuntimeError("ERR_RUNTIME_LIMIT_EXCEEDED"), trace };
1818
+ const before = stack.map(cloneStackValue);
1819
+ const applied = apply(instruction);
1820
+ const after = stack.map(cloneStackValue);
1821
+ step += 1;
1822
+ cost += policyInstructionCost(instruction.opcode);
1823
+ trace.push({ step, instruction_index: instruction.index, opcode: instruction.opcode, stack_before: before, stack_after: after });
1824
+ if (applied.error) return { result: policyRuntimeError(applied.error), trace };
1825
+ if (applied.result) return { result: applied.result, trace };
1826
+ ip = applied.next;
1827
+ }
1828
+ return { result: policyRuntimeError("ERR_NO_TERMINAL_RULE"), trace };
1829
+ }
1830
+
1831
+ function orderedPolicyTrace(trace) {
1832
+ const stackOrdered = (stack) => stack.map((value) => orderedObject(["value_type", value.value_type], ["value", value.value]));
1833
+ return trace.map((entry) => orderedObject(
1834
+ ["step", entry.step],
1835
+ ["instruction_index", entry.instruction_index],
1836
+ ["opcode", entry.opcode],
1837
+ ["stack_before", stackOrdered(entry.stack_before)],
1838
+ ["stack_after", stackOrdered(entry.stack_after)],
1839
+ ));
1840
+ }
1841
+
1842
+ // The C2.4 execution-event hash of an event object.
1843
+ export function policyExecutionEventHash(event) {
1844
+ return sha256Hex(POLICY_VM_EVENT_HASH_DOMAIN + policyCanonical(event));
1845
+ }
1846
+
1847
+ // C2.4: evaluate a compiled policy over an execution event and return every
1848
+ // value a policy binding seals.
1849
+ export function evaluateCompiledPolicy(compiled, event) {
1850
+ if (!isPlainPolicyObject(event) || Object.keys(event).length === 0) throw new PolicyReevaluationError("POLICY_EVENT_INVALID", "execution event must be a non-empty object");
1851
+ const header = compiled.bytecode.bytecode_header_domain;
1852
+ const { result, trace } = executePolicyBytecode(compiled.bytecode, event);
1853
+ const vmTrace = orderedPolicyTrace(trace);
1854
+ const traceHash = sha256Hex(POLICY_VM_TRACE_HASH_DOMAIN + policyCanonical(vmTrace));
1855
+ const executionEventHash = policyExecutionEventHash(event);
1856
+ const evaluationHash = sha256Hex(POLICY_VM_EVALUATION_HASH_DOMAIN + policyCanonical(orderedObject(
1857
+ ["evaluation_result", orderedObject(["decision", result.decision], ["rule_id", result.rule_id], ["constraints", result.constraints], ["error_code", result.error_code])],
1858
+ ["vm_trace", vmTrace],
1859
+ ["trace_hash", traceHash],
1860
+ ["runtime_fingerprint", orderedObject(["pvm_runtime_version", POLICY_VM_RUNTIME_VERSION], ["compiler_version", header.compiler_version], ["bytecode_version", header.bytecode_version])],
1861
+ ["integrity", orderedObject(
1862
+ ["source_policy_hash", header.policy_hash],
1863
+ ["compiled_policy_hash", header.compiled_policy_hash],
1864
+ ["execution_event_hash", executionEventHash],
1865
+ ["trace_hash", traceHash],
1866
+ ["hash_algorithm", "SHA-256"],
1867
+ )],
1868
+ ["task_ids", [...POLICY_VM_TASK_IDS]],
1869
+ ["valid", true],
1870
+ )));
1871
+ const constraints = result.constraints.map((constraint) => {
1872
+ if (!isPlainPolicyObject(constraint) || !policyNonEmpty(constraint.constraint_id) || !policyNonEmpty(constraint.type)) {
1873
+ throw new PolicyReevaluationError("POLICY_EVALUATION_INVALID", "evaluation constraint has no id or type");
1874
+ }
1875
+ return { constraint_id: constraint.constraint_id, type: constraint.type };
1876
+ }).sort((left, right) => utf8Compare(left.constraint_id, right.constraint_id));
1877
+ return {
1878
+ policy_id: compiled.policy_id,
1879
+ policy_version: compiled.policy_version,
1880
+ source_policy_hash: header.policy_hash,
1881
+ compiled_policy_hash: header.compiled_policy_hash,
1882
+ execution_event_hash: executionEventHash,
1883
+ evaluation_hash: evaluationHash,
1884
+ decision: result.decision,
1885
+ rule_id: result.rule_id,
1886
+ error_code: result.error_code,
1887
+ constraints,
1888
+ };
1889
+ }
1890
+
1891
+ // Compiles policyJSON and evaluates event in one step.
1892
+ export function reevaluatePolicy({ policyJSON, allowedEventFields, event }) {
1893
+ return evaluateCompiledPolicy(compilePolicyDocument(policyJSON, allowedEventFields), event);
1894
+ }
1895
+
1896
+ // Lists every sealed policy-binding member the recomputed evaluation
1897
+ // disagrees with (sorted policy_binding.<member> paths). Constraint statuses
1898
+ // are not part of the evaluation and are not compared.
1899
+ export function policyReevaluationMismatches(binding, recomputed) {
1900
+ const fields = [];
1901
+ for (const member of ["compiled_policy_hash", "decision", "evaluation_hash", "execution_event_hash", "policy_id", "policy_version", "rule_id", "source_policy_hash"]) {
1902
+ if (binding[member] !== recomputed[member]) fields.push(`policy_binding.${member}`);
1903
+ }
1904
+ const sealed = Array.isArray(binding.constraints) ? binding.constraints : [];
1905
+ if (sealed.length !== recomputed.constraints.length
1906
+ || sealed.some((constraint, index) => constraint.constraint_id !== recomputed.constraints[index].constraint_id || constraint.type !== recomputed.constraints[index].type)) {
1907
+ fields.push("policy_binding.constraints");
1908
+ }
1909
+ return fields.sort();
1910
+ }