@kya-os/checkpoint-shared 1.6.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/dist/{browser-posture-DIaVLuW3.d.ts → browser-posture-B8YiPa5c.d.ts} +5 -5
- package/dist/{browser-posture-DIaVLuW3.d.ts.map → browser-posture-B8YiPa5c.d.ts.map} +1 -1
- package/dist/{browser-posture-BuChqmH5.d.mts → browser-posture-BLhw-MON.d.mts} +5 -5
- package/dist/{browser-posture-BuChqmH5.d.mts.map → browser-posture-BLhw-MON.d.mts.map} +1 -1
- package/dist/browser-posture-cookie.js +1 -1
- package/dist/browser-posture-cookie.mjs +1 -1
- package/dist/browser-posture-cookie.mjs.map +1 -1
- package/dist/browser-posture-proof.d.mts +1 -1
- package/dist/browser-posture-proof.d.mts.map +1 -1
- package/dist/browser-posture-proof.d.ts +1 -1
- package/dist/browser-posture-proof.d.ts.map +1 -1
- package/dist/browser-posture-proof.js +42 -1
- package/dist/browser-posture-proof.mjs +42 -1
- package/dist/browser-posture-proof.mjs.map +1 -1
- package/dist/browser-posture.d.mts +1 -1
- package/dist/browser-posture.d.ts +1 -1
- package/dist/browser-posture.js +1 -1
- package/dist/browser-posture.mjs +1 -1
- package/dist/canonical-signer/index.d.mts.map +1 -1
- package/dist/canonical-signer/index.d.ts.map +1 -1
- package/dist/canonical-signer/index.js +86 -51
- package/dist/canonical-signer/index.mjs +86 -51
- package/dist/canonical-signer/index.mjs.map +1 -1
- package/dist/client-ip-DFamiNoz.d.mts +34 -0
- package/dist/client-ip-DFamiNoz.d.mts.map +1 -0
- package/dist/client-ip-DFamiNoz.d.ts +34 -0
- package/dist/client-ip-DFamiNoz.d.ts.map +1 -0
- package/dist/client-ip.d.mts +2 -0
- package/dist/client-ip.d.ts +2 -0
- package/dist/client-ip.js +7 -0
- package/dist/client-ip.mjs +3 -0
- package/dist/host-adapter/index.d.mts +2 -0
- package/dist/host-adapter/index.d.ts +2 -0
- package/dist/host-adapter/index.js +23 -0
- package/dist/host-adapter/index.mjs +3 -0
- package/dist/host-adapter-C-4IxmqM.mjs +540 -0
- package/dist/host-adapter-C-4IxmqM.mjs.map +1 -0
- package/dist/host-adapter-CwW9YB0U.js +694 -0
- package/dist/index-B7rTovHa.d.mts +707 -0
- package/dist/index-B7rTovHa.d.mts.map +1 -0
- package/dist/index-HaqfPtaL.d.ts +707 -0
- package/dist/index-HaqfPtaL.d.ts.map +1 -0
- package/dist/index.d.mts +107 -981
- package/dist/index.d.mts.map +1 -1
- package/dist/index.d.ts +107 -981
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +73 -2308
- package/dist/index.mjs +5 -2240
- package/dist/index.mjs.map +1 -1
- package/dist/kya-http-error-codes-7ewV5RuK.d.mts +29 -0
- package/dist/kya-http-error-codes-7ewV5RuK.d.mts.map +1 -0
- package/dist/kya-http-error-codes-7ewV5RuK.d.ts +29 -0
- package/dist/kya-http-error-codes-7ewV5RuK.d.ts.map +1 -0
- package/dist/kya-http-error-codes-C2JiWPsi.mjs +73 -0
- package/dist/kya-http-error-codes-C2JiWPsi.mjs.map +1 -0
- package/dist/kya-http-error-codes-UYb1zpGM.js +83 -0
- package/dist/kya-http.d.mts +3 -0
- package/dist/kya-http.d.ts +3 -0
- package/dist/kya-http.js +11 -0
- package/dist/kya-http.mjs +4 -0
- package/dist/policy/enforcement.d.mts +2 -0
- package/dist/policy/enforcement.d.ts +2 -0
- package/dist/policy/enforcement.js +15 -0
- package/dist/policy/enforcement.mjs +3 -0
- package/dist/{posture-origins-Pn-ii-Pp.mjs → posture-origins-Ba83O0cD.mjs} +2 -2
- package/dist/posture-origins-Ba83O0cD.mjs.map +1 -0
- package/dist/{posture-origins-LFkX80oF.js → posture-origins-CdVOdiMT.js} +1 -1
- package/dist/registered-sid-D3g-gZQF.d.mts +11 -0
- package/dist/registered-sid-D3g-gZQF.d.mts.map +1 -0
- package/dist/registered-sid-D3g-gZQF.d.ts +11 -0
- package/dist/registered-sid-D3g-gZQF.d.ts.map +1 -0
- package/dist/registered-sid-eLCNZvIF.js +170 -0
- package/dist/registered-sid-hUl-bvM5.mjs +142 -0
- package/dist/registered-sid-hUl-bvM5.mjs.map +1 -0
- package/dist/step-up-BjP--hG-.d.mts +114 -0
- package/dist/step-up-BjP--hG-.d.mts.map +1 -0
- package/dist/step-up-BjP--hG-.d.ts +114 -0
- package/dist/step-up-BjP--hG-.d.ts.map +1 -0
- package/dist/step-up-C2d8C20x.js +1697 -0
- package/dist/step-up-COlmWJN8.mjs +1513 -0
- package/dist/step-up-COlmWJN8.mjs.map +1 -0
- package/package.json +23 -1
- package/dist/posture-origins-Pn-ii-Pp.mjs.map +0 -1
package/dist/index.mjs
CHANGED
|
@@ -1,7 +1,11 @@
|
|
|
1
1
|
import { t as __commonJSMin } from "./rolldown-runtime-iY2fYEqi.mjs";
|
|
2
2
|
import { A as NEVER, C as string, D as _coercedBoolean, E as ZodError, O as _coercedDate, S as strictObject, T as unknown, _ as never, a as _instanceof, b as partialRecord, c as array, d as date$1, f as discriminatedUnion, g as literal, h as ipv6, i as _enum, k as _coercedNumber, l as boolean$1, m as ipv4, n as ZodDate, o as _null, r as ZodNumber, s as any, t as ZodBoolean, u as custom, v as number$1, w as union, x as record, y as object } from "./schemas-7qodsG-Z.mjs";
|
|
3
|
-
import { a as BROWSER_PATTERNS, c as OS_PATTERNS, d as UUID_PATTERN, f as VALIDATION_PATTERNS, g as testPatterns, h as testPattern, i as validatePostureOrigins, l as SUSPICIOUS_PATTERNS, m as findMatchingPattern, o as HEADER_PATTERNS, p as extractMatch, s as MOBILE_PATTERNS, t as isPublicSuffixLike, u as USER_AGENT_PATTERNS } from "./posture-origins-
|
|
3
|
+
import { a as BROWSER_PATTERNS, c as OS_PATTERNS, d as UUID_PATTERN, f as VALIDATION_PATTERNS, g as testPatterns, h as testPattern, i as validatePostureOrigins, l as SUSPICIOUS_PATTERNS, m as findMatchingPattern, o as HEADER_PATTERNS, p as extractMatch, s as MOBILE_PATTERNS, t as isPublicSuffixLike, u as USER_AGENT_PATTERNS } from "./posture-origins-Ba83O0cD.mjs";
|
|
4
|
+
import { C as isLegacyDetectionClass, E as normalizeDetectionClassEnum, S as enumToDetectionClass, T as normalizeDetectionClass, _ as acceptsHtml, a as buildDelegationBearerHeader, b as encodeVerdictCookie, c as buildDelegationChallengeHeader, d as generateDelegationSid, f as ACCEPT_CHALLENGE_HEADER, g as classifyResponseShape, h as BLOCKED_PATH, i as buildChallengeWire, l as buildDelegationInstructions, m as serveBodyReadable200, n as resolveChallengeContext, o as buildDelegationChallengeBody, p as selectBodyReadable200, r as ChallengeWireError, s as buildDelegationChallengeEnvelope, t as DEFAULT_CHALLENGE_CONTEXT_TIMEOUT_MS, u as deriveDelegationPickupUri, v as VERDICT_COOKIE_NAME, w as migrateLegacyDetectionClass, x as detectionClassToEnum, y as deriveVerdict } from "./host-adapter-C-4IxmqM.mjs";
|
|
4
5
|
import { i as resolveClientIp, n as normalizeClientIp, r as parseIpv6, t as compressIpv6 } from "./client-ip-B2Xeo-GK.mjs";
|
|
6
|
+
import { A as FAIL_CLOSED_STATUS, C as NO_EVIDENCE_EXCLUSION_TERM, D as unescapeCedarString, E as escapeCedarString, O as FAIL_CLOSED_BODY, S as NO_EVIDENCE_EQUALITY_TERM, T as cedarQuotedValueRegExp, _ as parseCedarStatements, a as ByteBoundedMemo, b as unnarrowedDenyStatements, c as isForbidBlock, d as pathHasUnnarrowedDenyRule, f as pathHasUnnarrowedDenyRuleFor, g as lacksBaselinePermit, h as PROBE_CLASSES, i as requiredScopesForRequest, j as isEngineEnforcing, k as FAIL_CLOSED_HEADERS, l as isUnnarrowedDenyBlock, m as splitCedarBlocks, n as approvalQuorumForRequest, o as analyzePolicySource, p as pathLiteralsInBlock, r as decisionPolicyId, s as blockEqualityLiterals, t as validateStepUpQuorum, u as pathHasExplicitDenyRuleFor, v as statementApplies, w as withNoEvidenceExclusion, x as NO_EVIDENCE_CATEGORY, y as statementId } from "./step-up-COlmWJN8.mjs";
|
|
7
|
+
import { n as KYA_HTTP_ERROR_STATUS, t as KYA_HTTP_ERROR } from "./kya-http-error-codes-C2JiWPsi.mjs";
|
|
8
|
+
import { a as requestPresentedCredential, i as requestCarriesDelegationProof, n as SID_ATTRIBUTABLE_RESULT, r as DELEGATION_PROOF_HEADERS, t as REGISTERED_SID_MAX_LENGTH } from "./registered-sid-hUl-bvM5.mjs";
|
|
5
9
|
import { sha256 } from "@noble/hashes/sha2.js";
|
|
6
10
|
import { bytesToHex } from "@noble/hashes/utils.js";
|
|
7
11
|
import { AUTH_MODES, CredentialProviderConfigSchema, OAuthProviderConfigSchema, PROVIDER_AUTH_TYPES, ProviderConfigSchema, ProviderDefinitionSchema as ProviderRegistryDefinitionSchema, validateProviderConfig, validateProviderDefinition } from "@kya-os/provider-registry";
|
|
@@ -11514,74 +11518,6 @@ function createValidationErrorResponse(message, details, meta) {
|
|
|
11514
11518
|
};
|
|
11515
11519
|
}
|
|
11516
11520
|
|
|
11517
|
-
//#endregion
|
|
11518
|
-
//#region src/utils/detection-class.ts
|
|
11519
|
-
/**
|
|
11520
|
-
* Convert DetectionClass discriminated union to database enum string
|
|
11521
|
-
* Note: Automation and Unknown are legacy types, converted to Bot and IncompleteData respectively
|
|
11522
|
-
*/
|
|
11523
|
-
function detectionClassToEnum(detectionClass) {
|
|
11524
|
-
switch (detectionClass.type) {
|
|
11525
|
-
case "Human": return "human";
|
|
11526
|
-
case "AiAgent": return "ai_agent";
|
|
11527
|
-
case "Automation": return "bot";
|
|
11528
|
-
case "Bot": return "bot";
|
|
11529
|
-
case "IncompleteData": return "incomplete_data";
|
|
11530
|
-
default: return "incomplete_data";
|
|
11531
|
-
}
|
|
11532
|
-
}
|
|
11533
|
-
/**
|
|
11534
|
-
* Convert database enum string to DetectionClass discriminated union
|
|
11535
|
-
* Handles both current and legacy enum values for backwards compatibility
|
|
11536
|
-
*/
|
|
11537
|
-
function enumToDetectionClass(enumValue) {
|
|
11538
|
-
switch (enumValue) {
|
|
11539
|
-
case "human": return { type: "Human" };
|
|
11540
|
-
case "ai_agent": return { type: "AiAgent" };
|
|
11541
|
-
case "automation": return { type: "Bot" };
|
|
11542
|
-
case "bot": return { type: "Bot" };
|
|
11543
|
-
case "incomplete_data": return { type: "IncompleteData" };
|
|
11544
|
-
case "unknown": return { type: "IncompleteData" };
|
|
11545
|
-
default: return { type: "IncompleteData" };
|
|
11546
|
-
}
|
|
11547
|
-
}
|
|
11548
|
-
/**
|
|
11549
|
-
* Check if a value is a valid string-based detection class (current or legacy)
|
|
11550
|
-
*/
|
|
11551
|
-
function isLegacyDetectionClass(value) {
|
|
11552
|
-
return typeof value === "string" && [
|
|
11553
|
-
"human",
|
|
11554
|
-
"ai_agent",
|
|
11555
|
-
"bot",
|
|
11556
|
-
"incomplete_data",
|
|
11557
|
-
"automation",
|
|
11558
|
-
"unknown"
|
|
11559
|
-
].includes(value);
|
|
11560
|
-
}
|
|
11561
|
-
/**
|
|
11562
|
-
* Migrate legacy string detection class to new discriminated union
|
|
11563
|
-
* @deprecated Use enumToDetectionClass instead
|
|
11564
|
-
*/
|
|
11565
|
-
function migrateLegacyDetectionClass(value) {
|
|
11566
|
-
return enumToDetectionClass(value);
|
|
11567
|
-
}
|
|
11568
|
-
/**
|
|
11569
|
-
* Safely convert any detection class value to the discriminated union format
|
|
11570
|
-
*/
|
|
11571
|
-
function normalizeDetectionClass(value) {
|
|
11572
|
-
if (value && typeof value === "object" && "type" in value) return value;
|
|
11573
|
-
if (isLegacyDetectionClass(value)) return enumToDetectionClass(value);
|
|
11574
|
-
return { type: "IncompleteData" };
|
|
11575
|
-
}
|
|
11576
|
-
/**
|
|
11577
|
-
* Safely convert any detection class value to database enum format
|
|
11578
|
-
*/
|
|
11579
|
-
function normalizeDetectionClassEnum(value) {
|
|
11580
|
-
if (value && typeof value === "object" && "type" in value) return detectionClassToEnum(value);
|
|
11581
|
-
if (isLegacyDetectionClass(value)) return detectionClassToEnum(enumToDetectionClass(value));
|
|
11582
|
-
return "incomplete_data";
|
|
11583
|
-
}
|
|
11584
|
-
|
|
11585
11521
|
//#endregion
|
|
11586
11522
|
//#region src/utils/agent-runtime-label.ts
|
|
11587
11523
|
/**
|
|
@@ -14885,9 +14821,6 @@ const PolicyEvaluationResultSchema = object({
|
|
|
14885
14821
|
/** What type of match triggered this decision */
|
|
14886
14822
|
matchType: PolicyMatchTypeSchema
|
|
14887
14823
|
});
|
|
14888
|
-
function isEngineEnforcing(flags) {
|
|
14889
|
-
return flags.engineEnforcementEnabled === true && flags.enabled !== false;
|
|
14890
|
-
}
|
|
14891
14824
|
/**
|
|
14892
14825
|
* Validate and parse a policy configuration
|
|
14893
14826
|
*/
|
|
@@ -14908,20 +14841,6 @@ function parseEvaluationContext(data) {
|
|
|
14908
14841
|
return PolicyEvaluationContextSchema.parse(data);
|
|
14909
14842
|
}
|
|
14910
14843
|
|
|
14911
|
-
//#endregion
|
|
14912
|
-
//#region src/policy/fail-closed-response.ts
|
|
14913
|
-
const FAIL_CLOSED_STATUS = 503;
|
|
14914
|
-
const FAIL_CLOSED_RETRY_AFTER_SECONDS = 3;
|
|
14915
|
-
const FAIL_CLOSED_BODY = {
|
|
14916
|
-
error: "Service temporarily unavailable",
|
|
14917
|
-
source: "checkpoint-middleware"
|
|
14918
|
-
};
|
|
14919
|
-
const FAIL_CLOSED_HEADERS = {
|
|
14920
|
-
"Content-Type": "application/json",
|
|
14921
|
-
"Cache-Control": "no-store",
|
|
14922
|
-
"Retry-After": String(3)
|
|
14923
|
-
};
|
|
14924
|
-
|
|
14925
14844
|
//#endregion
|
|
14926
14845
|
//#region src/policy/evaluator.ts
|
|
14927
14846
|
/**
|
|
@@ -15166,1390 +15085,6 @@ function createResult(action, reason, matchType, extras) {
|
|
|
15166
15085
|
};
|
|
15167
15086
|
}
|
|
15168
15087
|
|
|
15169
|
-
//#endregion
|
|
15170
|
-
//#region src/policy/cedar-mask.ts
|
|
15171
|
-
const blank = (char) => char === "\n" || char === "\r" ? char : " ";
|
|
15172
|
-
function maskCedar(cedar) {
|
|
15173
|
-
const visible = cedar.split("");
|
|
15174
|
-
const code = cedar.split("");
|
|
15175
|
-
const inString = new Array(cedar.length).fill(false);
|
|
15176
|
-
let i = 0;
|
|
15177
|
-
while (i < cedar.length) if (cedar[i] === "\"") {
|
|
15178
|
-
let end = i + 1;
|
|
15179
|
-
while (end < cedar.length && cedar[end] !== "\"") end += cedar[end] === "\\" ? 2 : 1;
|
|
15180
|
-
const bodyEnd = Math.min(end, cedar.length);
|
|
15181
|
-
for (let k = i + 1; k < bodyEnd; k++) {
|
|
15182
|
-
inString[k] = true;
|
|
15183
|
-
code[k] = blank(cedar[k]);
|
|
15184
|
-
}
|
|
15185
|
-
i = end + 1;
|
|
15186
|
-
} else if (cedar[i] === "/" && cedar[i + 1] === "/") while (i < cedar.length && cedar[i] !== "\n" && cedar[i] !== "\r") {
|
|
15187
|
-
visible[i] = " ";
|
|
15188
|
-
code[i] = " ";
|
|
15189
|
-
i++;
|
|
15190
|
-
}
|
|
15191
|
-
else i++;
|
|
15192
|
-
return {
|
|
15193
|
-
visible: visible.join(""),
|
|
15194
|
-
code: code.join(""),
|
|
15195
|
-
inString
|
|
15196
|
-
};
|
|
15197
|
-
}
|
|
15198
|
-
|
|
15199
|
-
//#endregion
|
|
15200
|
-
//#region src/policy/cedar-space.ts
|
|
15201
|
-
const CEDAR_SPACE_CLASS = "[\\t-\\r \\u0085\\u00a0\\u1680\\u2000-\\u200a\\u2028\\u2029\\u202f\\u205f\\u3000]";
|
|
15202
|
-
function isCedarSpace(char) {
|
|
15203
|
-
const code = char.charCodeAt(0);
|
|
15204
|
-
return code >= 9 && code <= 13 || code === 32 || code === 133 || code === 160 || code === 5760 || code >= 8192 && code <= 8202 || code === 8232 || code === 8233 || code === 8239 || code === 8287 || code === 12288;
|
|
15205
|
-
}
|
|
15206
|
-
|
|
15207
|
-
//#endregion
|
|
15208
|
-
//#region src/policy/cedar-string.ts
|
|
15209
|
-
/**
|
|
15210
|
-
* The Cedar double-quoted string grammar shared by the compose engine's emitter/
|
|
15211
|
-
* parser and every enforcement-path TEXT reader (required-scopes, cedar-rule-match).
|
|
15212
|
-
* Keeping the escape codec AND the capture pattern in one place means a value the
|
|
15213
|
-
* emitter escapes is decoded identically wherever a reader parses it back — they
|
|
15214
|
-
* can never drift. (Rust/.NET parse Cedar with a real parser and are unaffected.)
|
|
15215
|
-
*/
|
|
15216
|
-
/** Escape a value for embedding inside a Cedar double-quoted string literal. */
|
|
15217
|
-
function escapeCedarString(value) {
|
|
15218
|
-
return value.replace(/\\/g, "\\\\").replace(/"/g, "\\\"").replace(/\n/g, "\\n").replace(/\r/g, "\\r").replace(/\t/g, "\\t");
|
|
15219
|
-
}
|
|
15220
|
-
/** Inverse of {@link escapeCedarString} — decode Cedar string escapes to raw text. */
|
|
15221
|
-
function unescapeCedarString(value) {
|
|
15222
|
-
return value.replace(/\\([\\"nrt])/g, (_m, ch) => ch === "n" ? "\n" : ch === "r" ? "\r" : ch === "t" ? " " : ch);
|
|
15223
|
-
}
|
|
15224
|
-
/**
|
|
15225
|
-
* Build a RegExp matching `<prefixSource>"<body>"`, where <body> is an escape-aware
|
|
15226
|
-
* Cedar string. Capture group 1 is the RAW (still-escaped) body — pass it through
|
|
15227
|
-
* {@link unescapeCedarString} before use. `prefixSource` is a regex-source fragment
|
|
15228
|
-
* (escape its own metacharacters). This is the single source of the quoted-string
|
|
15229
|
-
* capture pattern.
|
|
15230
|
-
*/
|
|
15231
|
-
function cedarQuotedValueRegExp(prefixSource, flags = "") {
|
|
15232
|
-
return new RegExp(`${prefixSource}"((?:\\\\.|[^"\\\\])*)"`, flags);
|
|
15233
|
-
}
|
|
15234
|
-
const LIKE_ESCAPES = {
|
|
15235
|
-
n: "\n",
|
|
15236
|
-
r: "\r",
|
|
15237
|
-
t: " ",
|
|
15238
|
-
"0": "\0"
|
|
15239
|
-
};
|
|
15240
|
-
const NUMERIC_ESCAPE = /x([0-9a-fA-F]{2})|u\{([0-9a-fA-F][0-9a-fA-F_]*)\}/y;
|
|
15241
|
-
const MAX_CODE_POINT = 1114111;
|
|
15242
|
-
const MAX_UNICODE_DIGITS = 6;
|
|
15243
|
-
function numericEscapeCode(raw, at) {
|
|
15244
|
-
NUMERIC_ESCAPE.lastIndex = at;
|
|
15245
|
-
const match = NUMERIC_ESCAPE.exec(raw);
|
|
15246
|
-
if (match === null) return null;
|
|
15247
|
-
if (match[1] !== void 0) return {
|
|
15248
|
-
code: parseInt(match[1], 16),
|
|
15249
|
-
length: match[0].length
|
|
15250
|
-
};
|
|
15251
|
-
const digits = match[2].replace(/_/g, "");
|
|
15252
|
-
const code = parseInt(digits, 16);
|
|
15253
|
-
return digits.length <= MAX_UNICODE_DIGITS && code <= MAX_CODE_POINT && (code < 55296 || code > 57343) ? {
|
|
15254
|
-
code,
|
|
15255
|
-
length: match[0].length
|
|
15256
|
-
} : null;
|
|
15257
|
-
}
|
|
15258
|
-
function cedarLikeSegments(rawPattern) {
|
|
15259
|
-
const segments = [""];
|
|
15260
|
-
const append = (char) => {
|
|
15261
|
-
if (char === "*") segments.push("");
|
|
15262
|
-
else segments[segments.length - 1] += char;
|
|
15263
|
-
};
|
|
15264
|
-
for (let i = 0; i < rawPattern.length; i++) {
|
|
15265
|
-
const char = rawPattern.charAt(i);
|
|
15266
|
-
if (char !== "\\") {
|
|
15267
|
-
append(char);
|
|
15268
|
-
continue;
|
|
15269
|
-
}
|
|
15270
|
-
const numeric = numericEscapeCode(rawPattern, i + 1);
|
|
15271
|
-
if (numeric !== null) {
|
|
15272
|
-
append(String.fromCodePoint(numeric.code));
|
|
15273
|
-
i += numeric.length;
|
|
15274
|
-
} else {
|
|
15275
|
-
const next = rawPattern.charAt(++i);
|
|
15276
|
-
segments[segments.length - 1] += LIKE_ESCAPES[next] ?? next;
|
|
15277
|
-
}
|
|
15278
|
-
}
|
|
15279
|
-
return segments;
|
|
15280
|
-
}
|
|
15281
|
-
function globMatches(segments, value) {
|
|
15282
|
-
const first = segments[0];
|
|
15283
|
-
if (segments.length === 1) return value === first;
|
|
15284
|
-
const last = segments[segments.length - 1];
|
|
15285
|
-
const end = value.length - last.length;
|
|
15286
|
-
if (end < first.length || !value.startsWith(first) || !value.endsWith(last)) return false;
|
|
15287
|
-
let position = first.length;
|
|
15288
|
-
for (let i = 1; i < segments.length - 1; i++) {
|
|
15289
|
-
const at = value.indexOf(segments[i], position);
|
|
15290
|
-
if (at === -1 || at + segments[i].length > end) return false;
|
|
15291
|
-
position = at + segments[i].length;
|
|
15292
|
-
}
|
|
15293
|
-
return true;
|
|
15294
|
-
}
|
|
15295
|
-
|
|
15296
|
-
//#endregion
|
|
15297
|
-
//#region src/policy/legacy-carve-out.ts
|
|
15298
|
-
const NO_EVIDENCE_CATEGORY = "no_evidence";
|
|
15299
|
-
const NO_EVIDENCE_EXCLUSION_TERM = `principal.category != "${NO_EVIDENCE_CATEGORY}"`;
|
|
15300
|
-
const NO_EVIDENCE_EQUALITY_TERM = `principal.category == "${NO_EVIDENCE_CATEGORY}"`;
|
|
15301
|
-
const WS = `${CEDAR_SPACE_CLASS}*`;
|
|
15302
|
-
const SEGMENT_BOUNDARY = new RegExp(`\\b(?:forbid|permit)${WS}\\(|;`, "g");
|
|
15303
|
-
const ACCESSOR = `(?:\\.${WS}category\\b|\\[${WS}"C[^"]*"${WS}\\])`;
|
|
15304
|
-
const SUBJECT = `(?<![.\\w])principal${WS}${ACCESSOR}`;
|
|
15305
|
-
const EXACT = "\"E[^\"]*\"";
|
|
15306
|
-
const LIKEABLE = "\"[EL][^\"]*\"";
|
|
15307
|
-
const ELEMENTS = `[^\\]\\[]*(?:\\[${WS}"[^"]*"${WS}\\][^\\]\\[]*){0,16}`;
|
|
15308
|
-
const CATEGORY_READ = new RegExp(`(?<![.\\w])principal(?:${WS}\\))*${WS}${ACCESSOR}`, "g");
|
|
15309
|
-
const GROUP_OR_PRINCIPAL = /[()[\]{}]|(?<![\w.])principal(?!\w)/g;
|
|
15310
|
-
const CHAIN_LINK = new RegExp(`${WS}(?:\\.${WS}(category\\b)|\\.${WS}\\w+|\\[${WS}"(C)?[^"]*"${WS}\\])`, "y");
|
|
15311
|
-
const PRINCIPAL_LENGTH = 9;
|
|
15312
|
-
const BARE_GROUP = new RegExp(`^(?:\\(|${CEDAR_SPACE_CLASS})*$`);
|
|
15313
|
-
const CATEGORY_COMPARED = new RegExp(`${SUBJECT}${WS}(?:(?:==|!=)${WS}${EXACT}|like${WS}${LIKEABLE})|${EXACT}${WS}(?:==|!=)${WS}${SUBJECT}`);
|
|
15314
|
-
const LIST_CALL = new RegExp(`\\[(${ELEMENTS})\\]${WS}\\.${WS}contains(?:All|Any)?${WS}(?:(${SUBJECT})|(${EXACT})|\\[(${ELEMENTS})\\])`, "g");
|
|
15315
|
-
const HAS_CATEGORY = new RegExp(SUBJECT);
|
|
15316
|
-
const HAS_NO_EVIDENCE = new RegExp(EXACT);
|
|
15317
|
-
const SUBSTITUTED_READ = new RegExp(`\\(if ((?:\\(|${CEDAR_SPACE_CLASS})*principal(?:\\)|${CEDAR_SPACE_CLASS})*(?:\\.${WS}category\\b|\\[${WS}("(?:\\\\.|[^"\\\\])*")${WS}\\])) == "${NO_EVIDENCE_CATEGORY}" then "human" else \\1\\)`, "g");
|
|
15318
|
-
function literalMarker(body) {
|
|
15319
|
-
const segments = cedarLikeSegments(body);
|
|
15320
|
-
if (segments.length === 1) {
|
|
15321
|
-
if (segments[0] === "no_evidence") return "E";
|
|
15322
|
-
return segments[0] === "category" ? "C" : " ";
|
|
15323
|
-
}
|
|
15324
|
-
return segments.some((segment) => segment.includes("no_evidence")) && globMatches(segments, "no_evidence") ? "L" : " ";
|
|
15325
|
-
}
|
|
15326
|
-
function scan(cedar) {
|
|
15327
|
-
const { visible, code, inString } = maskCedar(cedar);
|
|
15328
|
-
const marked = code.split("");
|
|
15329
|
-
for (let start = 0; start < cedar.length;) {
|
|
15330
|
-
if (!inString[start]) {
|
|
15331
|
-
start++;
|
|
15332
|
-
continue;
|
|
15333
|
-
}
|
|
15334
|
-
let end = start;
|
|
15335
|
-
while (end < cedar.length && inString[end]) end++;
|
|
15336
|
-
const marker = literalMarker(visible.slice(start, end));
|
|
15337
|
-
if (marker !== " ") marked[start] = marker;
|
|
15338
|
-
start = end;
|
|
15339
|
-
}
|
|
15340
|
-
const text = marked.join("");
|
|
15341
|
-
return {
|
|
15342
|
-
visible,
|
|
15343
|
-
text,
|
|
15344
|
-
flat: text.replace(/[()]/g, " "),
|
|
15345
|
-
pairs: pairParentheses(text)
|
|
15346
|
-
};
|
|
15347
|
-
}
|
|
15348
|
-
function pairParentheses(text) {
|
|
15349
|
-
const pairs = new Int32Array(text.length).fill(-1);
|
|
15350
|
-
const open = [];
|
|
15351
|
-
for (let i = 0; i < text.length; i++) if (text[i] === "(") open.push(i);
|
|
15352
|
-
else if (text[i] === ")") pairs[i] = open.pop() ?? -1;
|
|
15353
|
-
return pairs;
|
|
15354
|
-
}
|
|
15355
|
-
function statementRanges(text) {
|
|
15356
|
-
const ranges = [];
|
|
15357
|
-
let open = -1;
|
|
15358
|
-
for (const boundary of text.matchAll(SEGMENT_BOUNDARY)) if (boundary[0] === ";") {
|
|
15359
|
-
if (open !== -1) ranges.push([open, boundary.index + 1]);
|
|
15360
|
-
open = -1;
|
|
15361
|
-
} else {
|
|
15362
|
-
if (open !== -1) ranges.push([open, boundary.index]);
|
|
15363
|
-
open = boundary.index;
|
|
15364
|
-
}
|
|
15365
|
-
if (open !== -1) ranges.push([open, text.length]);
|
|
15366
|
-
return ranges;
|
|
15367
|
-
}
|
|
15368
|
-
function applyEdits(cedar, edits) {
|
|
15369
|
-
if (edits.length === 0) return cedar;
|
|
15370
|
-
const pieces = [];
|
|
15371
|
-
let position = 0;
|
|
15372
|
-
for (const edit of edits) {
|
|
15373
|
-
pieces.push(cedar.slice(position, edit.start), edit.text);
|
|
15374
|
-
position = edit.end;
|
|
15375
|
-
}
|
|
15376
|
-
pieces.push(cedar.slice(position));
|
|
15377
|
-
return pieces.join("");
|
|
15378
|
-
}
|
|
15379
|
-
function namesNoEvidenceIn(flat) {
|
|
15380
|
-
if (CATEGORY_COMPARED.test(flat)) return true;
|
|
15381
|
-
for (const [, receiver, subject, exact, list = ""] of flat.matchAll(LIST_CALL)) {
|
|
15382
|
-
const receiverReadsCategory = HAS_CATEGORY.test(receiver);
|
|
15383
|
-
const receiverNamesNoEvidence = HAS_NO_EVIDENCE.test(receiver);
|
|
15384
|
-
if (receiverReadsCategory && (exact !== void 0 || HAS_NO_EVIDENCE.test(list)) || receiverNamesNoEvidence && (subject !== void 0 || HAS_CATEGORY.test(list))) return true;
|
|
15385
|
-
}
|
|
15386
|
-
return false;
|
|
15387
|
-
}
|
|
15388
|
-
function namesNoEvidence(cedar) {
|
|
15389
|
-
return namesNoEvidenceIn(scan(cedar).flat);
|
|
15390
|
-
}
|
|
15391
|
-
function groupStart({ text, pairs }, principal, read) {
|
|
15392
|
-
const lastCloser = read.lastIndexOf(")");
|
|
15393
|
-
if (lastCloser === -1) return principal;
|
|
15394
|
-
const open = pairs[principal + lastCloser];
|
|
15395
|
-
return open !== -1 && BARE_GROUP.test(text.slice(open, principal)) ? open : -1;
|
|
15396
|
-
}
|
|
15397
|
-
const isWordChar = (char) => char !== void 0 && /\w/.test(char);
|
|
15398
|
-
function skipSpaceBack(text, from) {
|
|
15399
|
-
let i = from;
|
|
15400
|
-
while (i >= 0 && isCedarSpace(text[i])) i--;
|
|
15401
|
-
return i;
|
|
15402
|
-
}
|
|
15403
|
-
function skipSpaceForward(text, from) {
|
|
15404
|
-
let i = from;
|
|
15405
|
-
while (i < text.length && isCedarSpace(text[i])) i++;
|
|
15406
|
-
return i;
|
|
15407
|
-
}
|
|
15408
|
-
function wordEndingAt(text, end) {
|
|
15409
|
-
let start = end;
|
|
15410
|
-
while (start > 0 && isWordChar(text[start - 1])) start--;
|
|
15411
|
-
return text.slice(start, end + 1);
|
|
15412
|
-
}
|
|
15413
|
-
function isPrincipalVariable(text, at) {
|
|
15414
|
-
const before = skipSpaceBack(text, at - 1);
|
|
15415
|
-
const char = text[before];
|
|
15416
|
-
if (char === "." || char === "?") return false;
|
|
15417
|
-
if (char === ":" && text[before - 1] === ":") return false;
|
|
15418
|
-
if (isWordChar(char) && wordEndingAt(text, before) === "has") return false;
|
|
15419
|
-
return text[skipSpaceForward(text, at + PRINCIPAL_LENGTH)] !== ":";
|
|
15420
|
-
}
|
|
15421
|
-
function isBranchValue(text, at) {
|
|
15422
|
-
let before = skipSpaceBack(text, at - 1);
|
|
15423
|
-
while (text[before] === "(") before = skipSpaceBack(text, before - 1);
|
|
15424
|
-
const char = text[before];
|
|
15425
|
-
const word = isWordChar(char) ? wordEndingAt(text, before) : "";
|
|
15426
|
-
const introduced = word === "then" || word === "else" || char === ":" && text[before - 1] !== ":";
|
|
15427
|
-
const after = skipSpaceForward(text, at + PRINCIPAL_LENGTH);
|
|
15428
|
-
const next = text[after];
|
|
15429
|
-
const ends = next === ")" || next === "}" || next === "]" || next === "," || text.startsWith("else", after) && !isWordChar(text[after + 4]);
|
|
15430
|
-
return introduced && ends;
|
|
15431
|
-
}
|
|
15432
|
-
function headEnd(text, from, to) {
|
|
15433
|
-
let depth = 0;
|
|
15434
|
-
for (let i = text.indexOf("(", from); i < to; i++) if (text[i] === "(") depth++;
|
|
15435
|
-
else if (text[i] === ")" && --depth === 0) return i + 1;
|
|
15436
|
-
return from;
|
|
15437
|
-
}
|
|
15438
|
-
function directReads(scanned, from, to) {
|
|
15439
|
-
const reads = [];
|
|
15440
|
-
for (const read of scanned.text.slice(from, to).matchAll(CATEGORY_READ)) {
|
|
15441
|
-
const principal = from + read.index;
|
|
15442
|
-
if (!isPrincipalVariable(scanned.text, principal)) continue;
|
|
15443
|
-
const start = groupStart(scanned, principal, read[0]);
|
|
15444
|
-
if (start !== -1) reads.push({
|
|
15445
|
-
principal,
|
|
15446
|
-
start,
|
|
15447
|
-
end: principal + read[0].length
|
|
15448
|
-
});
|
|
15449
|
-
}
|
|
15450
|
-
return reads;
|
|
15451
|
-
}
|
|
15452
|
-
function readsCategoryAfter(text, from) {
|
|
15453
|
-
CHAIN_LINK.lastIndex = from;
|
|
15454
|
-
for (let link = CHAIN_LINK.exec(text); link !== null; link = CHAIN_LINK.exec(text)) if (link[1] !== void 0 || link[2] !== void 0) return true;
|
|
15455
|
-
return false;
|
|
15456
|
-
}
|
|
15457
|
-
function readsCategoryOfCarriedPrincipal(text, from, to, reads) {
|
|
15458
|
-
const direct = new Set(reads.map((read) => read.principal));
|
|
15459
|
-
const holding = [false];
|
|
15460
|
-
for (const token of text.slice(from, to).matchAll(GROUP_OR_PRINCIPAL)) {
|
|
15461
|
-
const at = from + token.index;
|
|
15462
|
-
if (token[0] === "principal") {
|
|
15463
|
-
if (!direct.has(at) && isPrincipalVariable(text, at) && isBranchValue(text, at)) holding[holding.length - 1] = true;
|
|
15464
|
-
} else if ("([{".includes(token[0])) holding.push(false);
|
|
15465
|
-
else if (holding.length > 1 && holding.pop()) {
|
|
15466
|
-
holding[holding.length - 1] = true;
|
|
15467
|
-
if (readsCategoryAfter(text, at + 1)) return true;
|
|
15468
|
-
}
|
|
15469
|
-
}
|
|
15470
|
-
return false;
|
|
15471
|
-
}
|
|
15472
|
-
function withNoEvidenceExclusion(cedar) {
|
|
15473
|
-
const scanned = scan(cedar);
|
|
15474
|
-
const { visible, text, flat } = scanned;
|
|
15475
|
-
const edits = [];
|
|
15476
|
-
for (const [from, to] of statementRanges(text)) {
|
|
15477
|
-
if (namesNoEvidenceIn(flat.slice(from, to))) continue;
|
|
15478
|
-
const reads = directReads(scanned, from, to);
|
|
15479
|
-
if (reads.length === 0) continue;
|
|
15480
|
-
if (readsCategoryOfCarriedPrincipal(text, headEnd(text, from, to), to, reads)) continue;
|
|
15481
|
-
for (const { start, end } of reads) {
|
|
15482
|
-
const accessor = visible.slice(start, end);
|
|
15483
|
-
edits.push({
|
|
15484
|
-
start,
|
|
15485
|
-
end,
|
|
15486
|
-
text: `(if ${accessor} == "${NO_EVIDENCE_CATEGORY}" then "human" else ${accessor})`
|
|
15487
|
-
});
|
|
15488
|
-
}
|
|
15489
|
-
}
|
|
15490
|
-
return applyEdits(cedar, edits);
|
|
15491
|
-
}
|
|
15492
|
-
function withoutNoEvidenceExclusion(cedar) {
|
|
15493
|
-
const { visible, inString } = maskCedar(cedar);
|
|
15494
|
-
const edits = [];
|
|
15495
|
-
for (const read of visible.matchAll(SUBSTITUTED_READ)) {
|
|
15496
|
-
const key = read[2];
|
|
15497
|
-
if (!inString[read.index] && (key === void 0 || literalMarker(key.slice(1, -1)) === "C")) edits.push({
|
|
15498
|
-
start: read.index,
|
|
15499
|
-
end: read.index + read[0].length,
|
|
15500
|
-
text: read[1]
|
|
15501
|
-
});
|
|
15502
|
-
}
|
|
15503
|
-
return applyEdits(cedar, edits);
|
|
15504
|
-
}
|
|
15505
|
-
|
|
15506
|
-
//#endregion
|
|
15507
|
-
//#region src/policy/cedar-expression.ts
|
|
15508
|
-
const MAX_NESTING = 48;
|
|
15509
|
-
const MAX_HEX_ESCAPE = 127;
|
|
15510
|
-
const UNNAMED_CATEGORY = "\ud800";
|
|
15511
|
-
const LONE_SURROGATE = /\p{Surrogate}/u;
|
|
15512
|
-
const HUMAN_NAMES = [
|
|
15513
|
-
"",
|
|
15514
|
-
"human",
|
|
15515
|
-
"unknown",
|
|
15516
|
-
"anonymous"
|
|
15517
|
-
];
|
|
15518
|
-
const UNKNOWN = { k: "unknown" };
|
|
15519
|
-
const PUNCTUATION = /* @__PURE__ */ new Set("<>!+-*()[]{}.,:");
|
|
15520
|
-
const TWO_CHARACTER = /* @__PURE__ */ new Set([
|
|
15521
|
-
"&&",
|
|
15522
|
-
"||",
|
|
15523
|
-
"==",
|
|
15524
|
-
"!=",
|
|
15525
|
-
"<=",
|
|
15526
|
-
">=",
|
|
15527
|
-
"::"
|
|
15528
|
-
]);
|
|
15529
|
-
const SIMPLE_ESCAPES = {
|
|
15530
|
-
n: "\n",
|
|
15531
|
-
r: "\r",
|
|
15532
|
-
t: " ",
|
|
15533
|
-
"\\": "\\",
|
|
15534
|
-
"0": "\0",
|
|
15535
|
-
"'": "'",
|
|
15536
|
-
"\"": "\""
|
|
15537
|
-
};
|
|
15538
|
-
const IDENTIFIER_START = /[A-Za-z_]/;
|
|
15539
|
-
const IDENTIFIER_PART = /[A-Za-z0-9_]/;
|
|
15540
|
-
const DIGIT = /[0-9]/;
|
|
15541
|
-
const UNSUPPORTED_PATTERN_ESCAPE = /\\[0u]/;
|
|
15542
|
-
function tokenize(text) {
|
|
15543
|
-
const tokens = [];
|
|
15544
|
-
let i = 0;
|
|
15545
|
-
while (i < text.length) {
|
|
15546
|
-
const char = text[i];
|
|
15547
|
-
if (isCedarSpace(char)) i += 1;
|
|
15548
|
-
else if (char === "/" && text[i + 1] === "/") while (i < text.length && text[i] !== "\n" && text[i] !== "\r") i += 1;
|
|
15549
|
-
else if (char === "\"") {
|
|
15550
|
-
let end = i + 1;
|
|
15551
|
-
while (end < text.length && text[end] !== "\"") end += text[end] === "\\" ? 2 : 1;
|
|
15552
|
-
if (end >= text.length) throw new SyntaxError("unterminated string");
|
|
15553
|
-
const body = text.slice(i + 1, end);
|
|
15554
|
-
if (LONE_SURROGATE.test(body)) throw new SyntaxError("ill-formed string");
|
|
15555
|
-
tokens.push({
|
|
15556
|
-
t: "str",
|
|
15557
|
-
v: body
|
|
15558
|
-
});
|
|
15559
|
-
i = end + 1;
|
|
15560
|
-
} else if (IDENTIFIER_START.test(char)) {
|
|
15561
|
-
let end = i + 1;
|
|
15562
|
-
while (end < text.length && IDENTIFIER_PART.test(text[end])) end += 1;
|
|
15563
|
-
tokens.push({
|
|
15564
|
-
t: "id",
|
|
15565
|
-
v: text.slice(i, end)
|
|
15566
|
-
});
|
|
15567
|
-
i = end;
|
|
15568
|
-
} else if (DIGIT.test(char)) {
|
|
15569
|
-
let end = i + 1;
|
|
15570
|
-
while (end < text.length && DIGIT.test(text[end])) end += 1;
|
|
15571
|
-
tokens.push({
|
|
15572
|
-
t: "num",
|
|
15573
|
-
v: text.slice(i, end)
|
|
15574
|
-
});
|
|
15575
|
-
i = end;
|
|
15576
|
-
} else if (TWO_CHARACTER.has(text.slice(i, i + 2))) {
|
|
15577
|
-
tokens.push({
|
|
15578
|
-
t: "p",
|
|
15579
|
-
v: text.slice(i, i + 2)
|
|
15580
|
-
});
|
|
15581
|
-
i += 2;
|
|
15582
|
-
} else if (PUNCTUATION.has(char)) {
|
|
15583
|
-
tokens.push({
|
|
15584
|
-
t: "p",
|
|
15585
|
-
v: char
|
|
15586
|
-
});
|
|
15587
|
-
i += 1;
|
|
15588
|
-
} else throw new SyntaxError("unexpected character");
|
|
15589
|
-
}
|
|
15590
|
-
return tokens;
|
|
15591
|
-
}
|
|
15592
|
-
function decodeCedarString(raw) {
|
|
15593
|
-
let out = "";
|
|
15594
|
-
for (let i = 0; i < raw.length; i += 1) if (raw[i] !== "\\") out += raw[i];
|
|
15595
|
-
else if (raw[i + 1] === "x" || raw[i + 1] === "u") {
|
|
15596
|
-
const numeric = numericEscapeCode(raw, i + 1);
|
|
15597
|
-
if (numeric === null || raw[i + 1] === "x" && numeric.code > MAX_HEX_ESCAPE) return null;
|
|
15598
|
-
out += String.fromCodePoint(numeric.code);
|
|
15599
|
-
i += numeric.length;
|
|
15600
|
-
} else {
|
|
15601
|
-
const mapped = SIMPLE_ESCAPES[raw[i + 1]];
|
|
15602
|
-
if (mapped === void 0) return null;
|
|
15603
|
-
out += mapped;
|
|
15604
|
-
i += 1;
|
|
15605
|
-
}
|
|
15606
|
-
return out;
|
|
15607
|
-
}
|
|
15608
|
-
var Parser = class {
|
|
15609
|
-
tokens;
|
|
15610
|
-
position = 0;
|
|
15611
|
-
readsTag = false;
|
|
15612
|
-
constructor(tokens) {
|
|
15613
|
-
this.tokens = tokens;
|
|
15614
|
-
}
|
|
15615
|
-
parseAll() {
|
|
15616
|
-
const expression = this.expression(0);
|
|
15617
|
-
if (this.position < this.tokens.length) throw new SyntaxError("trailing tokens");
|
|
15618
|
-
return this.readsTag ? UNKNOWN : expression;
|
|
15619
|
-
}
|
|
15620
|
-
peek() {
|
|
15621
|
-
return this.tokens[this.position];
|
|
15622
|
-
}
|
|
15623
|
-
is(type, value) {
|
|
15624
|
-
const token = this.peek();
|
|
15625
|
-
return token !== void 0 && token.t === type && token.v === value;
|
|
15626
|
-
}
|
|
15627
|
-
take(type, value) {
|
|
15628
|
-
const found = this.is(type, value);
|
|
15629
|
-
if (found) this.position += 1;
|
|
15630
|
-
return found;
|
|
15631
|
-
}
|
|
15632
|
-
expect(type, value) {
|
|
15633
|
-
if (!this.take(type, value)) throw new SyntaxError(`expected ${value}`);
|
|
15634
|
-
}
|
|
15635
|
-
next(type) {
|
|
15636
|
-
const token = this.peek();
|
|
15637
|
-
if (token === void 0 || token.t !== type) throw new SyntaxError(`expected ${type}`);
|
|
15638
|
-
this.position += 1;
|
|
15639
|
-
return token;
|
|
15640
|
-
}
|
|
15641
|
-
expression(depth) {
|
|
15642
|
-
if (depth > MAX_NESTING) throw new SyntaxError("too deep");
|
|
15643
|
-
if (this.take("id", "if")) {
|
|
15644
|
-
const cond = this.expression(depth + 1);
|
|
15645
|
-
this.expect("id", "then");
|
|
15646
|
-
const then = this.expression(depth + 1);
|
|
15647
|
-
this.expect("id", "else");
|
|
15648
|
-
return {
|
|
15649
|
-
k: "if",
|
|
15650
|
-
cond,
|
|
15651
|
-
then,
|
|
15652
|
-
otherwise: this.expression(depth + 1)
|
|
15653
|
-
};
|
|
15654
|
-
}
|
|
15655
|
-
return this.chain("||", () => this.chain("&&", () => this.relation(depth)));
|
|
15656
|
-
}
|
|
15657
|
-
chain(operator, operand) {
|
|
15658
|
-
const terms = [operand()];
|
|
15659
|
-
while (this.take("p", operator)) terms.push(operand());
|
|
15660
|
-
return terms.length === 1 ? terms[0] : {
|
|
15661
|
-
k: operator === "&&" ? "and" : "or",
|
|
15662
|
-
terms
|
|
15663
|
-
};
|
|
15664
|
-
}
|
|
15665
|
-
relation(depth) {
|
|
15666
|
-
const left = this.additive(depth);
|
|
15667
|
-
const token = this.peek();
|
|
15668
|
-
if (token === void 0) return left;
|
|
15669
|
-
if (token.t === "p" && (token.v === "==" || token.v === "!=")) {
|
|
15670
|
-
this.position += 1;
|
|
15671
|
-
return {
|
|
15672
|
-
k: "cmp",
|
|
15673
|
-
equals: token.v === "==",
|
|
15674
|
-
left,
|
|
15675
|
-
right: this.additive(depth)
|
|
15676
|
-
};
|
|
15677
|
-
}
|
|
15678
|
-
if (token.t === "p" && [
|
|
15679
|
-
"<",
|
|
15680
|
-
"<=",
|
|
15681
|
-
">",
|
|
15682
|
-
">="
|
|
15683
|
-
].includes(token.v)) {
|
|
15684
|
-
this.position += 1;
|
|
15685
|
-
this.additive(depth);
|
|
15686
|
-
return UNKNOWN;
|
|
15687
|
-
}
|
|
15688
|
-
if (token.t === "id" && token.v === "in") {
|
|
15689
|
-
this.position += 1;
|
|
15690
|
-
this.additive(depth);
|
|
15691
|
-
return UNKNOWN;
|
|
15692
|
-
}
|
|
15693
|
-
if (token.t === "id" && token.v === "like") {
|
|
15694
|
-
this.position += 1;
|
|
15695
|
-
return {
|
|
15696
|
-
k: "like",
|
|
15697
|
-
operand: left,
|
|
15698
|
-
pattern: this.next("str").v
|
|
15699
|
-
};
|
|
15700
|
-
}
|
|
15701
|
-
if (token.t === "id" && token.v === "has") {
|
|
15702
|
-
this.position += 1;
|
|
15703
|
-
this.attributePath();
|
|
15704
|
-
return UNKNOWN;
|
|
15705
|
-
}
|
|
15706
|
-
if (token.t === "id" && token.v === "is") {
|
|
15707
|
-
this.position += 1;
|
|
15708
|
-
this.namePath();
|
|
15709
|
-
if (this.take("id", "in")) this.additive(depth);
|
|
15710
|
-
return UNKNOWN;
|
|
15711
|
-
}
|
|
15712
|
-
return left;
|
|
15713
|
-
}
|
|
15714
|
-
attributePath() {
|
|
15715
|
-
const first = this.peek();
|
|
15716
|
-
if (first === void 0 || first.t !== "id" && first.t !== "str") throw new SyntaxError("expected attribute");
|
|
15717
|
-
this.position += 1;
|
|
15718
|
-
while (this.take("p", ".")) {
|
|
15719
|
-
const part = this.peek();
|
|
15720
|
-
if (part === void 0 || part.t !== "id" && part.t !== "str") throw new SyntaxError("expected attribute");
|
|
15721
|
-
this.position += 1;
|
|
15722
|
-
}
|
|
15723
|
-
}
|
|
15724
|
-
namePath() {
|
|
15725
|
-
this.next("id");
|
|
15726
|
-
while (this.take("p", "::")) this.next("id");
|
|
15727
|
-
}
|
|
15728
|
-
additive(depth) {
|
|
15729
|
-
let result = this.multiplicative(depth);
|
|
15730
|
-
while (this.is("p", "+") || this.is("p", "-")) {
|
|
15731
|
-
this.position += 1;
|
|
15732
|
-
this.multiplicative(depth);
|
|
15733
|
-
result = UNKNOWN;
|
|
15734
|
-
}
|
|
15735
|
-
return result;
|
|
15736
|
-
}
|
|
15737
|
-
multiplicative(depth) {
|
|
15738
|
-
let result = this.unary(depth);
|
|
15739
|
-
while (this.take("p", "*")) {
|
|
15740
|
-
this.unary(depth);
|
|
15741
|
-
result = UNKNOWN;
|
|
15742
|
-
}
|
|
15743
|
-
return result;
|
|
15744
|
-
}
|
|
15745
|
-
unary(depth) {
|
|
15746
|
-
const prefixes = [];
|
|
15747
|
-
while (this.is("p", "!") || this.is("p", "-")) {
|
|
15748
|
-
prefixes.push(this.peek().v);
|
|
15749
|
-
this.position += 1;
|
|
15750
|
-
if (prefixes.length > MAX_NESTING) throw new SyntaxError("too deep");
|
|
15751
|
-
}
|
|
15752
|
-
let result = this.member(depth);
|
|
15753
|
-
for (let i = prefixes.length - 1; i >= 0; i -= 1) result = prefixes[i] === "!" ? {
|
|
15754
|
-
k: "not",
|
|
15755
|
-
operand: result
|
|
15756
|
-
} : UNKNOWN;
|
|
15757
|
-
return result;
|
|
15758
|
-
}
|
|
15759
|
-
member(depth) {
|
|
15760
|
-
let result = this.primary(depth);
|
|
15761
|
-
let links = 0;
|
|
15762
|
-
for (;;) {
|
|
15763
|
-
if (this.take("p", ".")) {
|
|
15764
|
-
const method = this.next("id").v;
|
|
15765
|
-
if (method === "getTag") this.readsTag = true;
|
|
15766
|
-
result = this.is("p", "(") ? {
|
|
15767
|
-
k: "call",
|
|
15768
|
-
method,
|
|
15769
|
-
receiver: result,
|
|
15770
|
-
args: this.arguments(depth)
|
|
15771
|
-
} : attribute(result, method);
|
|
15772
|
-
} else if (this.take("p", "[")) {
|
|
15773
|
-
const key = this.next("str").v;
|
|
15774
|
-
this.expect("p", "]");
|
|
15775
|
-
result = attribute(result, decodeCedarString(key));
|
|
15776
|
-
} else return result;
|
|
15777
|
-
links += 1;
|
|
15778
|
-
if (links > MAX_NESTING) throw new SyntaxError("too deep");
|
|
15779
|
-
}
|
|
15780
|
-
}
|
|
15781
|
-
arguments(depth) {
|
|
15782
|
-
this.expect("p", "(");
|
|
15783
|
-
return this.list(")", depth + 1);
|
|
15784
|
-
}
|
|
15785
|
-
list(close, depth) {
|
|
15786
|
-
const items = [];
|
|
15787
|
-
while (!this.take("p", close)) {
|
|
15788
|
-
items.push(this.expression(depth));
|
|
15789
|
-
if (!this.is("p", close)) this.expect("p", ",");
|
|
15790
|
-
}
|
|
15791
|
-
return items;
|
|
15792
|
-
}
|
|
15793
|
-
primary(depth) {
|
|
15794
|
-
const token = this.peek();
|
|
15795
|
-
if (token === void 0) throw new SyntaxError("unexpected end");
|
|
15796
|
-
this.position += 1;
|
|
15797
|
-
if (token.t === "str") return {
|
|
15798
|
-
k: "str",
|
|
15799
|
-
raw: token.v
|
|
15800
|
-
};
|
|
15801
|
-
if (token.t === "num") return UNKNOWN;
|
|
15802
|
-
if (token.t === "id") {
|
|
15803
|
-
if (token.v === "true" || token.v === "false") return {
|
|
15804
|
-
k: "lit",
|
|
15805
|
-
v: token.v === "true"
|
|
15806
|
-
};
|
|
15807
|
-
if ([
|
|
15808
|
-
"principal",
|
|
15809
|
-
"resource",
|
|
15810
|
-
"action",
|
|
15811
|
-
"context"
|
|
15812
|
-
].includes(token.v)) return {
|
|
15813
|
-
k: "var",
|
|
15814
|
-
name: token.v
|
|
15815
|
-
};
|
|
15816
|
-
while (this.take("p", "::")) {
|
|
15817
|
-
if (this.peek()?.t === "str") {
|
|
15818
|
-
this.position += 1;
|
|
15819
|
-
return UNKNOWN;
|
|
15820
|
-
}
|
|
15821
|
-
this.next("id");
|
|
15822
|
-
}
|
|
15823
|
-
if (this.is("p", "(")) this.arguments(depth);
|
|
15824
|
-
return UNKNOWN;
|
|
15825
|
-
}
|
|
15826
|
-
if (token.v === "(") {
|
|
15827
|
-
const inner = this.expression(depth + 1);
|
|
15828
|
-
this.expect("p", ")");
|
|
15829
|
-
return inner;
|
|
15830
|
-
}
|
|
15831
|
-
if (token.v === "[") return {
|
|
15832
|
-
k: "set",
|
|
15833
|
-
items: this.list("]", depth + 1)
|
|
15834
|
-
};
|
|
15835
|
-
if (token.v === "{") {
|
|
15836
|
-
while (!this.take("p", "}")) {
|
|
15837
|
-
const key = this.peek();
|
|
15838
|
-
if (key === void 0 || key.t !== "id" && key.t !== "str") throw new SyntaxError("expected key");
|
|
15839
|
-
this.position += 1;
|
|
15840
|
-
this.expect("p", ":");
|
|
15841
|
-
this.expression(depth + 1);
|
|
15842
|
-
if (!this.is("p", "}")) this.expect("p", ",");
|
|
15843
|
-
}
|
|
15844
|
-
return UNKNOWN;
|
|
15845
|
-
}
|
|
15846
|
-
throw new SyntaxError("unexpected token");
|
|
15847
|
-
}
|
|
15848
|
-
};
|
|
15849
|
-
function attribute(target, name) {
|
|
15850
|
-
if (target.k !== "var" || name === null) return UNKNOWN;
|
|
15851
|
-
if (target.name === "principal" && (name === "category" || name === "name")) return { k: name };
|
|
15852
|
-
return target.name === "resource" && name === "path" ? { k: "path" } : UNKNOWN;
|
|
15853
|
-
}
|
|
15854
|
-
const parseExpression = (text) => new Parser(tokenize(text)).parseAll();
|
|
15855
|
-
const triOf = (value) => value ? "yes" : "no";
|
|
15856
|
-
const invert = (value) => value === "maybe" ? "maybe" : value === "yes" ? "no" : "yes";
|
|
15857
|
-
const constantSets = /* @__PURE__ */ new WeakMap();
|
|
15858
|
-
function valueOf(expr, facts, read) {
|
|
15859
|
-
switch (expr.k) {
|
|
15860
|
-
case "str": {
|
|
15861
|
-
const decoded = decodeCedarString(expr.raw);
|
|
15862
|
-
return decoded === null ? { k: "unknown" } : {
|
|
15863
|
-
k: "str",
|
|
15864
|
-
v: decoded
|
|
15865
|
-
};
|
|
15866
|
-
}
|
|
15867
|
-
case "category": return {
|
|
15868
|
-
k: "str",
|
|
15869
|
-
v: read
|
|
15870
|
-
};
|
|
15871
|
-
case "path": return facts.path === void 0 ? { k: "unknown" } : {
|
|
15872
|
-
k: "str",
|
|
15873
|
-
v: facts.path
|
|
15874
|
-
};
|
|
15875
|
-
case "name": return { k: "name" };
|
|
15876
|
-
case "set": {
|
|
15877
|
-
const known = constantSets.get(expr);
|
|
15878
|
-
if (known !== void 0) return known;
|
|
15879
|
-
const items = expr.items.map((item) => valueOf(item, facts, read));
|
|
15880
|
-
const value = items.some((item) => item.k === "set") ? { k: "unknown" } : {
|
|
15881
|
-
k: "set",
|
|
15882
|
-
items
|
|
15883
|
-
};
|
|
15884
|
-
if (expr.items.every((item) => item.k === "str")) constantSets.set(expr, value);
|
|
15885
|
-
return value;
|
|
15886
|
-
}
|
|
15887
|
-
case "if": {
|
|
15888
|
-
const cond = evaluateExpression(expr.cond, facts);
|
|
15889
|
-
if (cond === "maybe") return { k: "unknown" };
|
|
15890
|
-
return valueOf(cond === "yes" ? expr.then : expr.otherwise, facts, read);
|
|
15891
|
-
}
|
|
15892
|
-
case "lit":
|
|
15893
|
-
case "and":
|
|
15894
|
-
case "or":
|
|
15895
|
-
case "not":
|
|
15896
|
-
case "cmp":
|
|
15897
|
-
case "like":
|
|
15898
|
-
case "call": return {
|
|
15899
|
-
k: "tri",
|
|
15900
|
-
v: evaluateExpression(expr, facts)
|
|
15901
|
-
};
|
|
15902
|
-
default: return { k: "unknown" };
|
|
15903
|
-
}
|
|
15904
|
-
}
|
|
15905
|
-
function sameValue(left, right) {
|
|
15906
|
-
if (left.k === "unknown" || right.k === "unknown") return "maybe";
|
|
15907
|
-
if (left.k === "name" || right.k === "name") {
|
|
15908
|
-
const other = left.k === "name" ? right : left;
|
|
15909
|
-
if (other.k !== "str") return other.k === "name" ? "maybe" : "no";
|
|
15910
|
-
return HUMAN_NAMES.includes(other.v.trim().toLowerCase()) ? "maybe" : "no";
|
|
15911
|
-
}
|
|
15912
|
-
if (left.k === "tri" && right.k === "tri") return left.v === "maybe" || right.v === "maybe" ? "maybe" : triOf(left.v === right.v);
|
|
15913
|
-
if (left.k === "tri" || right.k === "tri") return "no";
|
|
15914
|
-
if (left.k === "str" && right.k === "str") return triOf(left.v === right.v);
|
|
15915
|
-
if (left.k === "set" && right.k === "set") {
|
|
15916
|
-
const [leftIndex, rightIndex] = [indexItems(left.items), indexItems(right.items)];
|
|
15917
|
-
if (leftIndex.pure && rightIndex.pure) return triOf(leftIndex.strings.size === rightIndex.strings.size && holdsAll(leftIndex, rightIndex));
|
|
15918
|
-
const covers = (from, into) => {
|
|
15919
|
-
const index = indexItems(into);
|
|
15920
|
-
return combine(from.map((item) => member(item, index)), "and");
|
|
15921
|
-
};
|
|
15922
|
-
return combine([covers(left.items, right.items), covers(right.items, left.items)], "and");
|
|
15923
|
-
}
|
|
15924
|
-
return "no";
|
|
15925
|
-
}
|
|
15926
|
-
function holdsAll(index, other) {
|
|
15927
|
-
for (const value of other.strings) if (!index.strings.has(value)) return false;
|
|
15928
|
-
return true;
|
|
15929
|
-
}
|
|
15930
|
-
function shareAny(left, right) {
|
|
15931
|
-
const [small, large] = left.strings.size <= right.strings.size ? [left, right] : [right, left];
|
|
15932
|
-
for (const value of small.strings) if (large.strings.has(value)) return true;
|
|
15933
|
-
return false;
|
|
15934
|
-
}
|
|
15935
|
-
const indexes = /* @__PURE__ */ new WeakMap();
|
|
15936
|
-
function indexItems(items) {
|
|
15937
|
-
const known = indexes.get(items);
|
|
15938
|
-
if (known !== void 0) return known;
|
|
15939
|
-
const index = buildIndex(items);
|
|
15940
|
-
indexes.set(items, index);
|
|
15941
|
-
return index;
|
|
15942
|
-
}
|
|
15943
|
-
function buildIndex(items) {
|
|
15944
|
-
const strings = /* @__PURE__ */ new Set();
|
|
15945
|
-
const representatives = /* @__PURE__ */ new Map();
|
|
15946
|
-
for (const item of items) if (item.k === "str") {
|
|
15947
|
-
strings.add(item.v);
|
|
15948
|
-
representatives.set(HUMAN_NAMES.includes(item.v.trim().toLowerCase()) ? "human" : "str", item);
|
|
15949
|
-
} else representatives.set(item.k === "tri" ? `tri:${item.v}` : item.k, item);
|
|
15950
|
-
return {
|
|
15951
|
-
strings,
|
|
15952
|
-
representatives: [...representatives.values()],
|
|
15953
|
-
pure: items.every((item) => item.k === "str")
|
|
15954
|
-
};
|
|
15955
|
-
}
|
|
15956
|
-
function member(item, index) {
|
|
15957
|
-
if (item.k === "str" && index.strings.has(item.v)) return "yes";
|
|
15958
|
-
return combine(index.representatives.map((candidate) => sameValue(item, candidate)), "or");
|
|
15959
|
-
}
|
|
15960
|
-
function combine(results, op) {
|
|
15961
|
-
const decisive = op === "and" ? "no" : "yes";
|
|
15962
|
-
if (results.includes(decisive)) return decisive;
|
|
15963
|
-
return results.includes("maybe") ? "maybe" : invert(decisive);
|
|
15964
|
-
}
|
|
15965
|
-
function setCall(method, receiver, args) {
|
|
15966
|
-
if (receiver.k !== "set") return "maybe";
|
|
15967
|
-
if (method === "isEmpty" && args.length === 0) return triOf(receiver.items.length === 0);
|
|
15968
|
-
const [argument] = args;
|
|
15969
|
-
if (args.length !== 1) return "maybe";
|
|
15970
|
-
const index = indexItems(receiver.items);
|
|
15971
|
-
if (method === "contains") return member(argument, index);
|
|
15972
|
-
if (argument.k !== "set") return "maybe";
|
|
15973
|
-
if (method === "containsAny" || method === "containsAll") {
|
|
15974
|
-
const other = indexItems(argument.items);
|
|
15975
|
-
if (index.pure && other.pure) return triOf(method === "containsAny" ? shareAny(index, other) : other.strings.size <= index.strings.size && holdsAll(index, other));
|
|
15976
|
-
return combine(argument.items.map((item) => member(item, index)), method === "containsAny" ? "or" : "and");
|
|
15977
|
-
}
|
|
15978
|
-
return "maybe";
|
|
15979
|
-
}
|
|
15980
|
-
const leaves = (expr) => expr.k === "set" ? expr.items.flatMap(leaves) : expr.k === "if" ? [...leaves(expr.then), ...leaves(expr.otherwise)] : [expr];
|
|
15981
|
-
function strings(exprs) {
|
|
15982
|
-
const found = [];
|
|
15983
|
-
for (const part of exprs.flatMap(leaves)) {
|
|
15984
|
-
const decoded = part.k === "str" ? decodeCedarString(part.raw) : null;
|
|
15985
|
-
if (decoded !== null) found.push(decoded);
|
|
15986
|
-
}
|
|
15987
|
-
return found;
|
|
15988
|
-
}
|
|
15989
|
-
const readsCategory = (exprs) => exprs.flatMap(leaves).some((part) => part.k === "category");
|
|
15990
|
-
const spelledAtoms = /* @__PURE__ */ new WeakMap();
|
|
15991
|
-
function spelledBy(expr) {
|
|
15992
|
-
let spelled = spelledAtoms.get(expr);
|
|
15993
|
-
if (spelled === void 0) {
|
|
15994
|
-
const sides = expr.k === "cmp" ? [expr.left, expr.right] : [expr.receiver, ...expr.args];
|
|
15995
|
-
spelled = {
|
|
15996
|
-
reads: readsCategory(sides),
|
|
15997
|
-
names: new Set(strings(sides))
|
|
15998
|
-
};
|
|
15999
|
-
spelledAtoms.set(expr, spelled);
|
|
16000
|
-
}
|
|
16001
|
-
return spelled;
|
|
16002
|
-
}
|
|
16003
|
-
function mentions(expr, name) {
|
|
16004
|
-
if (name === void 0) return false;
|
|
16005
|
-
if (expr.k === "like") {
|
|
16006
|
-
const segments = cedarLikeSegments(expr.pattern);
|
|
16007
|
-
return readsCategory([expr.operand]) && segments.some((segment) => segment.includes(name)) && globMatches(segments, name);
|
|
16008
|
-
}
|
|
16009
|
-
const { reads, names } = spelledBy(expr);
|
|
16010
|
-
return reads && names.has(name);
|
|
16011
|
-
}
|
|
16012
|
-
const readOf = (expr, facts) => mentions(expr, facts.unnamed) ? UNNAMED_CATEGORY : facts.category;
|
|
16013
|
-
function evaluateExpression(expr, facts) {
|
|
16014
|
-
switch (expr.k) {
|
|
16015
|
-
case "lit": return triOf(expr.v);
|
|
16016
|
-
case "not": return invert(evaluateExpression(expr.operand, facts));
|
|
16017
|
-
case "and":
|
|
16018
|
-
case "or": return combine(expr.terms.map((term) => evaluateExpression(term, facts)), expr.k);
|
|
16019
|
-
case "if": {
|
|
16020
|
-
const cond = evaluateExpression(expr.cond, facts);
|
|
16021
|
-
if (cond !== "maybe") return evaluateExpression(cond === "yes" ? expr.then : expr.otherwise, facts);
|
|
16022
|
-
const [then, otherwise] = [expr.then, expr.otherwise].map((branch) => evaluateExpression(branch, facts));
|
|
16023
|
-
return then === otherwise ? then : "maybe";
|
|
16024
|
-
}
|
|
16025
|
-
case "cmp": {
|
|
16026
|
-
const read = readOf(expr, facts);
|
|
16027
|
-
const same = sameValue(valueOf(expr.left, facts, read), valueOf(expr.right, facts, read));
|
|
16028
|
-
return expr.equals ? same : invert(same);
|
|
16029
|
-
}
|
|
16030
|
-
case "like": {
|
|
16031
|
-
const subject = valueOf(expr.operand, facts, readOf(expr, facts));
|
|
16032
|
-
if (UNSUPPORTED_PATTERN_ESCAPE.test(expr.pattern)) return "maybe";
|
|
16033
|
-
const segments = cedarLikeSegments(expr.pattern);
|
|
16034
|
-
if (subject.k === "name") return HUMAN_NAMES.some((candidate) => globMatches(segments, candidate)) ? "maybe" : "no";
|
|
16035
|
-
if (subject.k !== "str") return "maybe";
|
|
16036
|
-
return triOf(globMatches(segments, subject.v));
|
|
16037
|
-
}
|
|
16038
|
-
case "call": {
|
|
16039
|
-
const read = readOf(expr, facts);
|
|
16040
|
-
return setCall(expr.method, valueOf(expr.receiver, facts, read), expr.args.map((arg) => valueOf(arg, facts, read)));
|
|
16041
|
-
}
|
|
16042
|
-
default: return "maybe";
|
|
16043
|
-
}
|
|
16044
|
-
}
|
|
16045
|
-
|
|
16046
|
-
//#endregion
|
|
16047
|
-
//#region src/policy/cedar-principal-scope.ts
|
|
16048
|
-
const PROBE_CLASSES = ["human", NO_EVIDENCE_CATEGORY];
|
|
16049
|
-
const ANONYMOUS_PRINCIPAL_ID = "anonymous";
|
|
16050
|
-
const S = CEDAR_SPACE_CLASS;
|
|
16051
|
-
const HEAD = new RegExp(`\\b(forbid|permit)${S}*\\(`, "g");
|
|
16052
|
-
const isAnnotationName = (code, index) => {
|
|
16053
|
-
let position = index - 1;
|
|
16054
|
-
while (position >= 0 && isCedarSpace(code[position])) position -= 1;
|
|
16055
|
-
return code[position] === "@";
|
|
16056
|
-
};
|
|
16057
|
-
const skipSpace = (text, from) => {
|
|
16058
|
-
let index = from;
|
|
16059
|
-
while (index < text.length && isCedarSpace(text[index])) index += 1;
|
|
16060
|
-
return index;
|
|
16061
|
-
};
|
|
16062
|
-
const conditionAt = (text, from) => {
|
|
16063
|
-
const keywordStart = skipSpace(text, from);
|
|
16064
|
-
const kind = text.startsWith("when", keywordStart) ? "when" : text.startsWith("unless", keywordStart) ? "unless" : null;
|
|
16065
|
-
if (kind === null) return null;
|
|
16066
|
-
const braceOpen = skipSpace(text, keywordStart + kind.length);
|
|
16067
|
-
return text[braceOpen] === "{" ? {
|
|
16068
|
-
kind,
|
|
16069
|
-
braceOpen
|
|
16070
|
-
} : null;
|
|
16071
|
-
};
|
|
16072
|
-
function matching(code, openIndex, open, close) {
|
|
16073
|
-
let depth = 0;
|
|
16074
|
-
for (let i = openIndex; i < code.length; i++) if (code[i] === open) depth++;
|
|
16075
|
-
else if (code[i] === close) {
|
|
16076
|
-
depth--;
|
|
16077
|
-
if (depth === 0) return i;
|
|
16078
|
-
}
|
|
16079
|
-
return -1;
|
|
16080
|
-
}
|
|
16081
|
-
function parseCedarStatements(cedar) {
|
|
16082
|
-
const { visible, code } = maskCedar(cedar);
|
|
16083
|
-
const statements = [];
|
|
16084
|
-
const heads = new RegExp(HEAD.source, "g");
|
|
16085
|
-
let previousEnd = 0;
|
|
16086
|
-
let match = heads.exec(code);
|
|
16087
|
-
while (match !== null) {
|
|
16088
|
-
if (isAnnotationName(code, match.index)) {
|
|
16089
|
-
match = heads.exec(code);
|
|
16090
|
-
continue;
|
|
16091
|
-
}
|
|
16092
|
-
const open = match.index + match[0].length - 1;
|
|
16093
|
-
const scopeEnd = matching(code, open, "(", ")");
|
|
16094
|
-
if (scopeEnd < 0) break;
|
|
16095
|
-
const conditions = [];
|
|
16096
|
-
let position = scopeEnd + 1;
|
|
16097
|
-
for (;;) {
|
|
16098
|
-
const condition = conditionAt(code, position);
|
|
16099
|
-
if (condition === null) break;
|
|
16100
|
-
const braceClose = matching(code, condition.braceOpen, "{", "}");
|
|
16101
|
-
if (braceClose < 0) {
|
|
16102
|
-
position = code.length;
|
|
16103
|
-
break;
|
|
16104
|
-
}
|
|
16105
|
-
conditions.push({
|
|
16106
|
-
kind: condition.kind,
|
|
16107
|
-
body: visible.slice(condition.braceOpen + 1, braceClose)
|
|
16108
|
-
});
|
|
16109
|
-
position = braceClose + 1;
|
|
16110
|
-
}
|
|
16111
|
-
const terminatorAt = skipSpace(code, position);
|
|
16112
|
-
const end = code[terminatorAt] === ";" ? terminatorAt + 1 : position;
|
|
16113
|
-
statements.push({
|
|
16114
|
-
effect: match[1],
|
|
16115
|
-
blockStart: Math.min(skipSpace(cedar, previousEnd), match.index),
|
|
16116
|
-
start: match.index,
|
|
16117
|
-
end,
|
|
16118
|
-
text: visible.slice(match.index, end),
|
|
16119
|
-
scope: visible.slice(open + 1, scopeEnd),
|
|
16120
|
-
conditions,
|
|
16121
|
-
annotations: visible.slice(previousEnd, match.index)
|
|
16122
|
-
});
|
|
16123
|
-
previousEnd = end;
|
|
16124
|
-
heads.lastIndex = end;
|
|
16125
|
-
match = heads.exec(code);
|
|
16126
|
-
}
|
|
16127
|
-
return statements;
|
|
16128
|
-
}
|
|
16129
|
-
const TRUE_BODY = new RegExp(`^${S}*true${S}*$`);
|
|
16130
|
-
const PRINCIPAL_EQUALS = new RegExp(`\\bprincipal${S}*==`);
|
|
16131
|
-
const ENTITY_ID = new RegExp(`::${S}*"((?:\\\\.|[^"\\\\])*)"`, "g");
|
|
16132
|
-
const IS_TYPE = new RegExp(`\\bis${S}+([\\w:]+)`);
|
|
16133
|
-
const ID_ANNOTATION = new RegExp(`@id\\(${S}*"((?:\\\\.|[^"\\\\])*)"${S}*\\)`, "g");
|
|
16134
|
-
function principalScope(scope) {
|
|
16135
|
-
const { visible, code } = maskCedar(scope);
|
|
16136
|
-
let depth = 0;
|
|
16137
|
-
let end = code.length;
|
|
16138
|
-
for (let i = 0; i < code.length; i++) {
|
|
16139
|
-
const char = code[i];
|
|
16140
|
-
if (char === "(" || char === "[" || char === "{") depth++;
|
|
16141
|
-
else if (char === ")" || char === "]" || char === "}") depth--;
|
|
16142
|
-
else if (char === "," && depth === 0) {
|
|
16143
|
-
end = i;
|
|
16144
|
-
break;
|
|
16145
|
-
}
|
|
16146
|
-
}
|
|
16147
|
-
const text = visible.slice(0, end);
|
|
16148
|
-
const masked = code.slice(0, end);
|
|
16149
|
-
if (PRINCIPAL_EQUALS.test(masked) || /\bin\b/.test(masked)) return Array.from(text.matchAll(ENTITY_ID), (m) => decodeCedarString(m[1])).some((id) => id === null || id === ANONYMOUS_PRINCIPAL_ID) ? "maybe" : "no";
|
|
16150
|
-
const isType = IS_TYPE.exec(masked);
|
|
16151
|
-
if (isType) return isType[1].split("::").pop() === "Agent" ? "maybe" : "no";
|
|
16152
|
-
return "yes";
|
|
16153
|
-
}
|
|
16154
|
-
const prepared = /* @__PURE__ */ new WeakMap();
|
|
16155
|
-
function parsedCondition(body) {
|
|
16156
|
-
try {
|
|
16157
|
-
return parseExpression(body);
|
|
16158
|
-
} catch {
|
|
16159
|
-
return null;
|
|
16160
|
-
}
|
|
16161
|
-
}
|
|
16162
|
-
function evaluableOf(statement) {
|
|
16163
|
-
return {
|
|
16164
|
-
scope: principalScope(statement.scope),
|
|
16165
|
-
conditions: statement.conditions.map(({ kind, body }) => ({
|
|
16166
|
-
kind,
|
|
16167
|
-
node: parsedCondition(body)
|
|
16168
|
-
}))
|
|
16169
|
-
};
|
|
16170
|
-
}
|
|
16171
|
-
function preparedOf(statement) {
|
|
16172
|
-
let entry = prepared.get(statement);
|
|
16173
|
-
if (entry === void 0) {
|
|
16174
|
-
const named = namesNoEvidence(statement.text);
|
|
16175
|
-
entry = {
|
|
16176
|
-
namesNoEvidence: named,
|
|
16177
|
-
substituted: !named && withNoEvidenceExclusion(statement.text) !== statement.text,
|
|
16178
|
-
evaluable: evaluableOf(statement)
|
|
16179
|
-
};
|
|
16180
|
-
prepared.set(statement, entry);
|
|
16181
|
-
}
|
|
16182
|
-
return entry;
|
|
16183
|
-
}
|
|
16184
|
-
function statementApplies(statement, facts) {
|
|
16185
|
-
const { substituted, evaluable } = preparedOf(statement);
|
|
16186
|
-
const read = facts.category === "no_evidence" && substituted ? {
|
|
16187
|
-
...facts,
|
|
16188
|
-
category: "human"
|
|
16189
|
-
} : facts;
|
|
16190
|
-
const effective = {
|
|
16191
|
-
category: read.category,
|
|
16192
|
-
path: read.path,
|
|
16193
|
-
unnamed: facts.discountNaming ? read.category : void 0
|
|
16194
|
-
};
|
|
16195
|
-
if (evaluable.scope === "no") return false;
|
|
16196
|
-
for (const { kind, node } of evaluable.conditions) {
|
|
16197
|
-
const result = node === null ? "maybe" : evaluateExpression(node, effective);
|
|
16198
|
-
if (kind === "when" && result === "no") return false;
|
|
16199
|
-
if (kind === "unless" && result === "yes") return false;
|
|
16200
|
-
}
|
|
16201
|
-
return true;
|
|
16202
|
-
}
|
|
16203
|
-
function reachesClassOnlyByNaming(statement, probe, path) {
|
|
16204
|
-
return statementApplies(statement, {
|
|
16205
|
-
category: probe,
|
|
16206
|
-
path
|
|
16207
|
-
}) && !statementApplies(statement, {
|
|
16208
|
-
category: probe,
|
|
16209
|
-
path,
|
|
16210
|
-
discountNaming: true
|
|
16211
|
-
});
|
|
16212
|
-
}
|
|
16213
|
-
function statementId(statement) {
|
|
16214
|
-
return Array.from(statement.annotations.matchAll(ID_ANNOTATION), (m) => unescapeCedarString(m[1])).at(-1);
|
|
16215
|
-
}
|
|
16216
|
-
let memoText;
|
|
16217
|
-
let memoParsed = {
|
|
16218
|
-
text: "",
|
|
16219
|
-
statements: []
|
|
16220
|
-
};
|
|
16221
|
-
function parsedOf(cedar) {
|
|
16222
|
-
if (memoText !== cedar) {
|
|
16223
|
-
const text = withoutNoEvidenceExclusion(cedar);
|
|
16224
|
-
memoParsed = {
|
|
16225
|
-
text,
|
|
16226
|
-
statements: parseCedarStatements(text)
|
|
16227
|
-
};
|
|
16228
|
-
memoText = cedar;
|
|
16229
|
-
}
|
|
16230
|
-
return memoParsed;
|
|
16231
|
-
}
|
|
16232
|
-
function analyzePolicyScope(cedar) {
|
|
16233
|
-
const { text, statements } = parsedOf(cedar);
|
|
16234
|
-
return {
|
|
16235
|
-
unnarrowedDeny(path) {
|
|
16236
|
-
const found = [];
|
|
16237
|
-
let line = 1;
|
|
16238
|
-
let counted = 0;
|
|
16239
|
-
for (const statement of statements) {
|
|
16240
|
-
if (statement.effect !== "forbid") continue;
|
|
16241
|
-
const classes = PROBE_CLASSES.filter((probe) => statementApplies(statement, {
|
|
16242
|
-
category: probe,
|
|
16243
|
-
path
|
|
16244
|
-
}) && !reachesClassOnlyByNaming(statement, probe, path));
|
|
16245
|
-
if (classes.length > 0) {
|
|
16246
|
-
for (; counted < statement.blockStart; counted++) if (text.charCodeAt(counted) === 10) line++;
|
|
16247
|
-
found.push({
|
|
16248
|
-
statement,
|
|
16249
|
-
classes,
|
|
16250
|
-
line
|
|
16251
|
-
});
|
|
16252
|
-
}
|
|
16253
|
-
}
|
|
16254
|
-
return found;
|
|
16255
|
-
},
|
|
16256
|
-
denyNamingClass(path, probe) {
|
|
16257
|
-
return statements.filter((statement) => statement.effect === "forbid" && (probe !== "no_evidence" || preparedOf(statement).namesNoEvidence) && reachesClassOnlyByNaming(statement, probe, path));
|
|
16258
|
-
},
|
|
16259
|
-
lacksBaselinePermit() {
|
|
16260
|
-
return statements.length > 0 && !statements.some(isBaselinePermit);
|
|
16261
|
-
}
|
|
16262
|
-
};
|
|
16263
|
-
}
|
|
16264
|
-
const unnarrowedDenyStatements = (cedar, path) => analyzePolicyScope(cedar).unnarrowedDeny(path);
|
|
16265
|
-
const lacksBaselinePermit = (cedar) => analyzePolicyScope(cedar).lacksBaselinePermit();
|
|
16266
|
-
function isBaselinePermit(statement) {
|
|
16267
|
-
return statement.effect === "permit" && principalScope(statement.scope) === "yes" && statement.conditions.every((condition) => condition.kind === "when" && TRUE_BODY.test(condition.body));
|
|
16268
|
-
}
|
|
16269
|
-
|
|
16270
|
-
//#endregion
|
|
16271
|
-
//#region src/policy/cedar-rule-match.ts
|
|
16272
|
-
/**
|
|
16273
|
-
* Shared best-effort matchers for reading a composed Cedar policy's per-rule
|
|
16274
|
-
* annotations (`@scopes`, `@approvers`, …) WITHOUT a Cedar AST. Both
|
|
16275
|
-
* `requiredScopesForRequest` (consent scopes) and `approvalQuorumForRequest`
|
|
16276
|
-
* (step-up quorum) narrow a rule's annotation to a request the same way the
|
|
16277
|
-
* compose engine's own `parseExistingCedar` does: blocks split on blank lines,
|
|
16278
|
-
* a rule contributes only when EVERY request fact it constrains matches.
|
|
16279
|
-
*
|
|
16280
|
-
* A fact is matched against the SAME projection the gateway/edge feeds the
|
|
16281
|
-
* engine (`name = agentName`, `category = scraper|detectionClass`), so the
|
|
16282
|
-
* narrowing mirrors the engine's own evaluation. An UNKNOWN fact never narrows.
|
|
16283
|
-
*/
|
|
16284
|
-
const UNLESS_BRACE = new RegExp(`unless${CEDAR_SPACE_CLASS}*\\{`);
|
|
16285
|
-
const FORBID_HEAD = new RegExp(`\\bforbid${CEDAR_SPACE_CLASS}*\\(`, "g");
|
|
16286
|
-
/**
|
|
16287
|
-
* A block applies when its path AND principal conditions all match the KNOWN
|
|
16288
|
-
* request facts. An unknown fact never narrows (so the no-`request` case unions
|
|
16289
|
-
* every matching rule's annotation).
|
|
16290
|
-
*/
|
|
16291
|
-
function blockApplies(block, request) {
|
|
16292
|
-
if (request?.path !== void 0 && !blockMatchesPath(block, request.path)) return false;
|
|
16293
|
-
if (request?.name !== void 0 && !blockMatchesEquality(block, "principal.name", request.name)) return false;
|
|
16294
|
-
if (request?.category !== void 0) {
|
|
16295
|
-
if (!blockMatchesEquality(block, "principal.category", categoryRead(block, request.category))) return false;
|
|
16296
|
-
}
|
|
16297
|
-
return true;
|
|
16298
|
-
}
|
|
16299
|
-
function categoryRead(block, category) {
|
|
16300
|
-
if (category !== "no_evidence") return category;
|
|
16301
|
-
const original = withoutNoEvidenceExclusion(block);
|
|
16302
|
-
return withNoEvidenceExclusion(original) !== original ? "human" : category;
|
|
16303
|
-
}
|
|
16304
|
-
/** The `resource.path` literals appearing anywhere in `text` (no `when`/
|
|
16305
|
-
* `unless` scoping — callers that care about scope use `splitWhenUnless`
|
|
16306
|
-
* first). Shared regex extraction for `pathLiteralsInBlock` and the
|
|
16307
|
-
* scope-aware helpers below. */
|
|
16308
|
-
function pathLiteralsInText(text) {
|
|
16309
|
-
return Array.from(text.matchAll(cedarQuotedValueRegExp("resource\\.path (?:like|==) ", "g")), (m) => unescapeCedarString(m[1]));
|
|
16310
|
-
}
|
|
16311
|
-
/**
|
|
16312
|
-
* The `resource.path` literals a block MENTIONS anywhere — `when` or
|
|
16313
|
-
* `unless` alike (empty = the block never mentions a path). Used for
|
|
16314
|
-
* enumeration (which concrete paths does this bundle reference at all),
|
|
16315
|
-
* NOT for "does this block's condition match path" — that's
|
|
16316
|
-
* `blockMatchesPath`, which is `unless`-aware. Mixing the two up is exactly
|
|
16317
|
-
* the bug Bugbot caught (2026-09-10): a literal that appears ONLY inside
|
|
16318
|
-
* `unless { … }` names a path this block does NOT apply to, not one it
|
|
16319
|
-
* targets.
|
|
16320
|
-
*/
|
|
16321
|
-
function pathLiteralsInBlock(block) {
|
|
16322
|
-
return pathLiteralsInText(block);
|
|
16323
|
-
}
|
|
16324
|
-
/**
|
|
16325
|
-
* Split `block` into its `when`-scoped text and its `unless`-scoped inner
|
|
16326
|
-
* text, mirroring the compose engine's own excision order
|
|
16327
|
-
* (`apps/web/lib/compose/cedar.ts`'s `unless` handling): `unless { … }` is
|
|
16328
|
-
* located first and excised, so its own literals never leak into what
|
|
16329
|
-
* counts as the block's `when` (narrowing) scope.
|
|
16330
|
-
*
|
|
16331
|
-
* CodeQL js/polynomial-redos: a single `/unless\s*\{([\s\S]*?)\}\s*;?/`
|
|
16332
|
-
* regex is quadratic on a policy blob containing many "unless{"
|
|
16333
|
-
* substrings with no closing brace (composed policy text is untrusted,
|
|
16334
|
-
* customer-authored input evaluated on the request hot path) — an
|
|
16335
|
-
* unanchored match retries the unbounded `[\s\S]*?` scan-to-end at every
|
|
16336
|
-
* failed start position. `search()` for the fixed-length "unless\s*{"
|
|
16337
|
-
* prefix has no such ambiguity (each position fails fast), and the
|
|
16338
|
-
* closing brace is then found with a single linear `indexOf`, so the
|
|
16339
|
-
* whole split stays O(n) regardless of how many false "unless{" starts
|
|
16340
|
-
* the text contains.
|
|
16341
|
-
*/
|
|
16342
|
-
function splitWhenUnless(block) {
|
|
16343
|
-
const unlessIndex = block.search(UNLESS_BRACE);
|
|
16344
|
-
if (unlessIndex === -1) return {
|
|
16345
|
-
whenText: block,
|
|
16346
|
-
unlessText: ""
|
|
16347
|
-
};
|
|
16348
|
-
const openBraceIndex = block.indexOf("{", unlessIndex);
|
|
16349
|
-
const closeBraceIndex = block.indexOf("}", openBraceIndex + 1);
|
|
16350
|
-
if (closeBraceIndex === -1) return {
|
|
16351
|
-
whenText: block,
|
|
16352
|
-
unlessText: ""
|
|
16353
|
-
};
|
|
16354
|
-
return {
|
|
16355
|
-
whenText: block.slice(0, unlessIndex),
|
|
16356
|
-
unlessText: block.slice(openBraceIndex + 1, closeBraceIndex)
|
|
16357
|
-
};
|
|
16358
|
-
}
|
|
16359
|
-
/**
|
|
16360
|
-
* A block applies to `path` when: no `unless` literal excludes it, AND
|
|
16361
|
-
* either the `when` scope has no path constraint at all (unconstrained →
|
|
16362
|
-
* matches every path except what `unless` just excluded), or one of the
|
|
16363
|
-
* `when` scope's path literals matches (exact, or a `*`-prefix glob).
|
|
16364
|
-
*
|
|
16365
|
-
* Bugbot (2026-09-10): the previous version read path literals from the
|
|
16366
|
-
* WHOLE block regardless of `when` vs `unless`, so a site-wide forbid whose
|
|
16367
|
-
* only path mention was an `unless { resource.path == "/checkout" }`
|
|
16368
|
-
* exemption got scored as "targets only /checkout" — backwards. It applies
|
|
16369
|
-
* to every path EXCEPT the excepted one, not ONLY the excepted one.
|
|
16370
|
-
*/
|
|
16371
|
-
function blockMatchesPath(block, path) {
|
|
16372
|
-
const { whenText, unlessText } = splitWhenUnless(block);
|
|
16373
|
-
if (pathLiteralsInText(unlessText).some((literal) => pathLiteralMatches(literal, path))) return false;
|
|
16374
|
-
const whenLiterals = pathLiteralsInText(whenText);
|
|
16375
|
-
if (whenLiterals.length === 0) return true;
|
|
16376
|
-
return whenLiterals.some((literal) => pathLiteralMatches(literal, path));
|
|
16377
|
-
}
|
|
16378
|
-
/** Escape every regex metacharacter in `s` (so it matches literally). */
|
|
16379
|
-
function escapeRegExp(s) {
|
|
16380
|
-
return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
16381
|
-
}
|
|
16382
|
-
/**
|
|
16383
|
-
* Split a composed Cedar bundle into per-rule blocks (blank-line separated),
|
|
16384
|
-
* trimmed and with empties dropped. Mirrors the compose engine's own block
|
|
16385
|
-
* split (`apps/web/lib/compose/cedar.ts` `parseCedarBlocks`).
|
|
16386
|
-
*/
|
|
16387
|
-
function splitCedarBlocks(cedar) {
|
|
16388
|
-
return cedar.split(/\n\s*\n/).map((b) => b.trim()).filter((b) => b.length > 0);
|
|
16389
|
-
}
|
|
16390
|
-
/**
|
|
16391
|
-
* The set of values a block positively constrains `attr` to via `== ` literals.
|
|
16392
|
-
* Empty = the block places no `==` constraint on `attr` (unconstrained).
|
|
16393
|
-
*/
|
|
16394
|
-
function blockEqualityLiterals(block, attr) {
|
|
16395
|
-
const a = escapeRegExp(attr);
|
|
16396
|
-
return Array.from(block.matchAll(cedarQuotedValueRegExp(`${a} == `, "g")), (m) => unescapeCedarString(m[1]));
|
|
16397
|
-
}
|
|
16398
|
-
/**
|
|
16399
|
-
* The set of values a block EXCLUDES `attr` from via `!= ` literals.
|
|
16400
|
-
* Empty = the block places no `!=` constraint on `attr`.
|
|
16401
|
-
*/
|
|
16402
|
-
function blockExclusionLiterals(block, attr) {
|
|
16403
|
-
const a = escapeRegExp(attr);
|
|
16404
|
-
return Array.from(block.matchAll(cedarQuotedValueRegExp(`${a} != `, "g")), (m) => unescapeCedarString(m[1]));
|
|
16405
|
-
}
|
|
16406
|
-
/** A block applies to `value` when it is NOT excluded by a `!=` literal AND
|
|
16407
|
-
* (it declares no `==` literal — unconstrained → applies to all — or `value` is
|
|
16408
|
-
* one of them; compose emits an OR-disjunction for a name set). Without the `!=`
|
|
16409
|
-
* arm a rule that challenges everyone EXCEPT X (`principal.name != "X"`) would
|
|
16410
|
-
* over-advertise its annotation to X — a broader grant than the rule meant. */
|
|
16411
|
-
function blockMatchesEquality(block, attr, value) {
|
|
16412
|
-
const eq = blockEqualityLiterals(block, attr);
|
|
16413
|
-
if (blockExclusionLiterals(block, attr).includes(value)) return false;
|
|
16414
|
-
if (eq.length > 0) return eq.includes(value);
|
|
16415
|
-
return true;
|
|
16416
|
-
}
|
|
16417
|
-
/**
|
|
16418
|
-
* Match a `resource.path` literal against the request path with CEDAR `like`
|
|
16419
|
-
* semantics — NOT the package's `matchPath`. Cedar `*` matches any sequence
|
|
16420
|
-
* INCLUDING `/` (regex `.*`), whereas `matchPath` treats a single `*` as
|
|
16421
|
-
* `[^/]*` (no slash); using it here would disagree with what the engine
|
|
16422
|
-
* actually matched. A `==`/non-wildcard literal is an exact match; a `like`
|
|
16423
|
-
* literal maps each `*` (and `**`) to `.*`, anchored.
|
|
16424
|
-
*/
|
|
16425
|
-
function pathLiteralMatches(literal, path) {
|
|
16426
|
-
return globMatches(literal.split("*"), path);
|
|
16427
|
-
}
|
|
16428
|
-
/**
|
|
16429
|
-
* True when the block contains a Cedar `forbid` statement (a deny rule). A bare
|
|
16430
|
-
* `forbid` defaults to BLOCK; a `@verdict(...)` annotation refines the kind.
|
|
16431
|
-
*/
|
|
16432
|
-
function isForbidBlock(block) {
|
|
16433
|
-
const { code } = maskCedar(block);
|
|
16434
|
-
return Array.from(code.matchAll(FORBID_HEAD)).some(({ index }) => !isAnnotationName(code, index));
|
|
16435
|
-
}
|
|
16436
|
-
function isUnnarrowedDenyBlock(block) {
|
|
16437
|
-
return unnarrowedDenyStatements(block).some(({ classes }) => classes.includes("human"));
|
|
16438
|
-
}
|
|
16439
|
-
function analyzePolicySource(cedar) {
|
|
16440
|
-
const scope = analyzePolicyScope(cedar);
|
|
16441
|
-
const analysis = {
|
|
16442
|
-
unnarrowedDenyFor: (path, probe) => scope.unnarrowedDeny(path).some(({ classes }) => classes.includes(probe)),
|
|
16443
|
-
explicitDenyFor: (path, probe) => scope.denyNamingClass(path, probe).length > 0,
|
|
16444
|
-
humanHazard: (path) => analysis.unnarrowedDenyFor(path, "human"),
|
|
16445
|
-
noEvidenceHazard: (path) => analysis.unnarrowedDenyFor(path, "no_evidence") && !analysis.noEvidenceNamed(path),
|
|
16446
|
-
noEvidenceNamed: (path) => analysis.explicitDenyFor(path, NO_EVIDENCE_CATEGORY)
|
|
16447
|
-
};
|
|
16448
|
-
return analysis;
|
|
16449
|
-
}
|
|
16450
|
-
function pathHasUnnarrowedDenyRuleFor(cedar, path, probe) {
|
|
16451
|
-
return analyzePolicySource(cedar).unnarrowedDenyFor(path, probe);
|
|
16452
|
-
}
|
|
16453
|
-
function pathHasExplicitDenyRuleFor(cedar, path, probe) {
|
|
16454
|
-
return analyzePolicySource(cedar).explicitDenyFor(path, probe);
|
|
16455
|
-
}
|
|
16456
|
-
function pathHasUnnarrowedDenyRule(cedar, path) {
|
|
16457
|
-
return analyzePolicySource(cedar).humanHazard(path);
|
|
16458
|
-
}
|
|
16459
|
-
|
|
16460
|
-
//#endregion
|
|
16461
|
-
//#region src/policy/byte-bounded-memo.ts
|
|
16462
|
-
var ByteBoundedMemo = class {
|
|
16463
|
-
budgetBytes;
|
|
16464
|
-
entries = /* @__PURE__ */ new Map();
|
|
16465
|
-
used = 0;
|
|
16466
|
-
constructor(budgetBytes) {
|
|
16467
|
-
this.budgetBytes = budgetBytes;
|
|
16468
|
-
}
|
|
16469
|
-
remember(key, bytes, make) {
|
|
16470
|
-
const hit = this.entries.get(key);
|
|
16471
|
-
if (hit !== void 0) {
|
|
16472
|
-
this.entries.delete(key);
|
|
16473
|
-
this.entries.set(key, hit);
|
|
16474
|
-
return hit.value;
|
|
16475
|
-
}
|
|
16476
|
-
const value = make();
|
|
16477
|
-
if (bytes > this.budgetBytes) return value;
|
|
16478
|
-
this.entries.set(key, {
|
|
16479
|
-
value,
|
|
16480
|
-
bytes
|
|
16481
|
-
});
|
|
16482
|
-
this.used += bytes;
|
|
16483
|
-
for (const [oldest, entry] of this.entries) {
|
|
16484
|
-
if (this.used <= this.budgetBytes) break;
|
|
16485
|
-
this.entries.delete(oldest);
|
|
16486
|
-
this.used -= entry.bytes;
|
|
16487
|
-
}
|
|
16488
|
-
return value;
|
|
16489
|
-
}
|
|
16490
|
-
};
|
|
16491
|
-
|
|
16492
|
-
//#endregion
|
|
16493
|
-
//#region src/policy/unsubstituted-source.ts
|
|
16494
|
-
const BUDGET_BYTES = 4194304;
|
|
16495
|
-
const BYTES_PER_CHARACTER = 4;
|
|
16496
|
-
const memo = new ByteBoundedMemo(BUDGET_BYTES);
|
|
16497
|
-
const unsubstitutedSource = (source) => memo.remember(source, source.length * BYTES_PER_CHARACTER, () => withoutNoEvidenceExclusion(source));
|
|
16498
|
-
|
|
16499
|
-
//#endregion
|
|
16500
|
-
//#region src/policy/required-scopes.ts
|
|
16501
|
-
/**
|
|
16502
|
-
* Consent scopes a composed Cedar policy REQUIRES for a request — the
|
|
16503
|
-
* `@scopes(...)` annotations the compose engine writes on CHALLENGE-verdict
|
|
16504
|
-
* rules (alongside `unless { context.granted_scopes.contains("S") }`).
|
|
16505
|
-
*
|
|
16506
|
-
* WHY: when a scope-gated rule challenges a request, the step-up must request
|
|
16507
|
-
* EXACTLY the scopes the policy demands, so the consent flow mints a delegation
|
|
16508
|
-
* carrying them (and the agent's retry then satisfies the carve-out). The
|
|
16509
|
-
* policy is the source of truth for "what this route requires", so reading its
|
|
16510
|
-
* `@scopes` is reading the SSOT — not re-deriving an engine-computed value.
|
|
16511
|
-
*
|
|
16512
|
-
* Best-effort TEXT parse (no Cedar AST), mirroring the compose engine's own
|
|
16513
|
-
* `parseExistingCedar`: blocks are split on blank lines. A CHALLENGE block
|
|
16514
|
-
* contributes its scopes only when EVERY request fact it constrains matches —
|
|
16515
|
-
* `resource.path`, `principal.name`, and `principal.category` — so on a shared
|
|
16516
|
-
* path the scopes of ANOTHER agent's CHALLENGE rule are not advertised (the
|
|
16517
|
-
* engine challenged on the rule whose `when` matched, not merely the path).
|
|
16518
|
-
*
|
|
16519
|
-
* A fact is matched against the SAME projection the gateway feeds the engine
|
|
16520
|
-
* (`name = detection.agentName`, `category = scraper|detectionClass`), so the
|
|
16521
|
-
* narrowing mirrors the engine's own evaluation. An UNKNOWN fact never narrows:
|
|
16522
|
-
* with no `request` (the consent allow-list case) this returns the union of
|
|
16523
|
-
* every CHALLENGE rule's scopes — exactly what consent must be able to grant.
|
|
16524
|
-
*/
|
|
16525
|
-
function requiredScopesForRequest(policySource, request) {
|
|
16526
|
-
if (!policySource || !policySource.trim()) return [];
|
|
16527
|
-
const out = /* @__PURE__ */ new Set();
|
|
16528
|
-
for (const block of unsubstitutedSource(policySource).split(/\n\s*\n/)) {
|
|
16529
|
-
if (!/@verdict\("CHALLENGE"\)/.test(block)) continue;
|
|
16530
|
-
const scopesMatch = block.match(cedarQuotedValueRegExp("@scopes\\("));
|
|
16531
|
-
if (!scopesMatch) continue;
|
|
16532
|
-
const scopes = scopesMatch[1].split(/\s+/).filter(Boolean).map(unescapeCedarString);
|
|
16533
|
-
if (scopes.length === 0) continue;
|
|
16534
|
-
if (!blockApplies(block, request)) continue;
|
|
16535
|
-
for (const scope of scopes) out.add(scope);
|
|
16536
|
-
}
|
|
16537
|
-
return [...out];
|
|
16538
|
-
}
|
|
16539
|
-
|
|
16540
|
-
//#endregion
|
|
16541
|
-
//#region src/policy/decision-policy-id.ts
|
|
16542
|
-
function decisionPolicyId(decision) {
|
|
16543
|
-
switch (decision.kind) {
|
|
16544
|
-
case "Permit": return decision.policyId;
|
|
16545
|
-
case "Block": return decision.reason?.kind === "PolicyDenied" ? decision.reason.policyId : void 0;
|
|
16546
|
-
case "Challenge": return decision.params?.policyId;
|
|
16547
|
-
case "Redirect": return decision.target?.policyId;
|
|
16548
|
-
case "Instruct": return decision.payload?.policyId;
|
|
16549
|
-
default: return;
|
|
16550
|
-
}
|
|
16551
|
-
}
|
|
16552
|
-
|
|
16553
15088
|
//#endregion
|
|
16554
15089
|
//#region src/policy/bespoke-policy.ts
|
|
16555
15090
|
/** Stable synthetic `@id` per explicit bespoke mechanism. */
|
|
@@ -16628,106 +15163,6 @@ function lintMissingBaselinePermit(cedar) {
|
|
|
16628
15163
|
}] : [];
|
|
16629
15164
|
}
|
|
16630
15165
|
|
|
16631
|
-
//#endregion
|
|
16632
|
-
//#region src/policy/approval-quorum.ts
|
|
16633
|
-
/**
|
|
16634
|
-
* The step-up APPROVAL QUORUM a composed Cedar policy requires for a request —
|
|
16635
|
-
* the `@approvers(...)` (+ optional `@quorum("N")`) annotations on a
|
|
16636
|
-
* CHALLENGE-verdict rule.
|
|
16637
|
-
*
|
|
16638
|
-
* WHY (ADR D7 — distinct verdict): the engine emits a single `Challenge` for
|
|
16639
|
-
* both consent (`@scopes`) and human-approval step-up (`@approvers`). They are
|
|
16640
|
-
* DIFFERENT security flows and must not collide — a consent challenge mints a
|
|
16641
|
-
* delegation; an approval-quorum challenge demands N-of-M humans cryptographically
|
|
16642
|
-
* sign. This classifier is the seam that tells them apart from the policy text:
|
|
16643
|
-
* - a CHALLENGE rule carrying `@approvers` → an approval quorum (this returns it)
|
|
16644
|
-
* - a CHALLENGE rule with only `@scopes` (or neither) → consent (returns null)
|
|
16645
|
-
*
|
|
16646
|
-
* It mirrors {@link requiredScopesForRequest}: the SAME best-effort block parse
|
|
16647
|
-
* and the SAME request narrowing (shared {@link blockApplies}), so the rule it
|
|
16648
|
-
* reads the quorum off is the rule the engine actually challenged on — not merely
|
|
16649
|
-
* one that shares a path. Reading the annotation is reading the SSOT (the policy
|
|
16650
|
-
* is the source of truth for "what this action requires"), not re-deriving it.
|
|
16651
|
-
*
|
|
16652
|
-
* The engine carries no rule id on its Challenge, so the classifier re-matches by
|
|
16653
|
-
* request facts and is FAIL-CLOSED on ambiguity:
|
|
16654
|
-
* - if a CONSENT-only CHALLENGE rule ALSO applies, it returns null — the engine
|
|
16655
|
-
* may have challenged on THAT, and reading approval off a different rule would
|
|
16656
|
-
* conflate the two flows (ADR D7)
|
|
16657
|
-
* - if two applying approval rules disagree on {n, approvers}, it returns null —
|
|
16658
|
-
* enforcing the wrong approver roster is a worse failure than a clean deny
|
|
16659
|
-
* Each caller feeds it the SAME facts its engine evaluated, so it narrows to the
|
|
16660
|
-
* rule the engine could have fired on. The EDGE worker sets resource.path +
|
|
16661
|
-
* principal.name and narrows on them; the Fly gateway sets NEITHER (it populates
|
|
16662
|
-
* category + the resource entity, leaving resource.path=="" and principal.name=""),
|
|
16663
|
-
* so it passes those as "" — path/name-scoped rules don't fire there, exactly as
|
|
16664
|
-
* the engine sees it, and a same-scope tie falls to the fail-closed guard above.
|
|
16665
|
-
*/
|
|
16666
|
-
function approvalQuorumForRequest(policySource, request) {
|
|
16667
|
-
if (!policySource || !policySource.trim()) return null;
|
|
16668
|
-
let chosen = null;
|
|
16669
|
-
for (const block of unsubstitutedSource(policySource).split(/\n\s*\n/)) {
|
|
16670
|
-
if (!/@verdict\("CHALLENGE"\)/.test(block)) continue;
|
|
16671
|
-
if (!blockApplies(block, request)) continue;
|
|
16672
|
-
const approvers = parseApprovers(block);
|
|
16673
|
-
if (!approvers) return null;
|
|
16674
|
-
const candidate = {
|
|
16675
|
-
n: parseQuorumN(block),
|
|
16676
|
-
approvers
|
|
16677
|
-
};
|
|
16678
|
-
if (chosen && !sameQuorum(chosen, candidate)) return null;
|
|
16679
|
-
chosen = candidate;
|
|
16680
|
-
}
|
|
16681
|
-
return chosen;
|
|
16682
|
-
}
|
|
16683
|
-
/** The DIDs of an `@approvers("did … did")` annotation, or null when the rule
|
|
16684
|
-
* carries none (a consent challenge) or an empty/whitespace list (no real gate). */
|
|
16685
|
-
function parseApprovers(block) {
|
|
16686
|
-
const m = block.match(/@approvers\("([^"]*)"\)/);
|
|
16687
|
-
if (!m) return null;
|
|
16688
|
-
const approvers = m[1].split(/\s+/).filter(Boolean);
|
|
16689
|
-
return approvers.length > 0 ? approvers : null;
|
|
16690
|
-
}
|
|
16691
|
-
/** Two quorums match iff same n and same ordered approver list. */
|
|
16692
|
-
function sameQuorum(a, b) {
|
|
16693
|
-
return a.n === b.n && a.approvers.length === b.approvers.length && a.approvers.every((did, i) => did === b.approvers[i]);
|
|
16694
|
-
}
|
|
16695
|
-
/**
|
|
16696
|
-
* The `@quorum("N")` count, or 1 when absent/malformed. Fail-secure: an
|
|
16697
|
-
* unparseable or `< 1` value falls back to 1 (the smallest real quorum), never 0
|
|
16698
|
-
* — which would make the step-up gate a no-op. The route's own
|
|
16699
|
-
* `validateStepUpQuorum` is the second line of defence on a misconfigured n.
|
|
16700
|
-
*/
|
|
16701
|
-
function parseQuorumN(block) {
|
|
16702
|
-
const m = block.match(/@quorum\("([^"]*)"\)/);
|
|
16703
|
-
if (!m) return 1;
|
|
16704
|
-
const n = Number(m[1]);
|
|
16705
|
-
return Number.isInteger(n) && n >= 1 ? n : 1;
|
|
16706
|
-
}
|
|
16707
|
-
|
|
16708
|
-
//#endregion
|
|
16709
|
-
//#region src/policy/step-up.ts
|
|
16710
|
-
/**
|
|
16711
|
-
* Validate a `step_up` decision's quorum before approval verification.
|
|
16712
|
-
* Fail-closed: returns a deny `reason` for any quorum that can never be
|
|
16713
|
-
* legitimately met; `{ ok: true }` only when the quorum is a real gate.
|
|
16714
|
-
*
|
|
16715
|
-
* Ordering is load-bearing: the `n` guard runs first, so an invalid quorum that
|
|
16716
|
-
* is both non-positive AND has no approvers reports `invalid_step_up_quorum`
|
|
16717
|
-
* (stable/deterministic reason).
|
|
16718
|
-
*/
|
|
16719
|
-
function validateStepUpQuorum(quorum) {
|
|
16720
|
-
if (!Number.isInteger(quorum.n) || quorum.n < 1) return {
|
|
16721
|
-
ok: false,
|
|
16722
|
-
reason: "invalid_step_up_quorum"
|
|
16723
|
-
};
|
|
16724
|
-
if (!Array.isArray(quorum.approvers) || quorum.approvers.length === 0) return {
|
|
16725
|
-
ok: false,
|
|
16726
|
-
reason: "step_up_no_approvers"
|
|
16727
|
-
};
|
|
16728
|
-
return { ok: true };
|
|
16729
|
-
}
|
|
16730
|
-
|
|
16731
15166
|
//#endregion
|
|
16732
15167
|
//#region src/policy/fetcher.ts
|
|
16733
15168
|
/**
|
|
@@ -17023,545 +15458,6 @@ function createEvaluationContext(options) {
|
|
|
17023
15458
|
};
|
|
17024
15459
|
}
|
|
17025
15460
|
|
|
17026
|
-
//#endregion
|
|
17027
|
-
//#region src/host-adapter/verdict-cookie.ts
|
|
17028
|
-
/**
|
|
17029
|
-
* Canonical cookie name. Sites-1's `/blocked` page reads from this
|
|
17030
|
-
* exact key; do not rename without updating the dashboard route.
|
|
17031
|
-
*/
|
|
17032
|
-
const VERDICT_COOKIE_NAME = "__checkpoint_verdict";
|
|
17033
|
-
/**
|
|
17034
|
-
* Compute the verdict label from a `RenderedResponse`.
|
|
17035
|
-
*/
|
|
17036
|
-
function deriveVerdict(rendered) {
|
|
17037
|
-
if (rendered.status === null) return "allowed";
|
|
17038
|
-
if (rendered.status === 302) return "redirected";
|
|
17039
|
-
return "denied";
|
|
17040
|
-
}
|
|
17041
|
-
/**
|
|
17042
|
-
* Build the `__checkpoint_verdict` cookie value Sites-1's Sonner toast
|
|
17043
|
-
* reads. Byte-format pinned by tests in both `checkpoint-nextjs` and
|
|
17044
|
-
* `checkpoint-express`:
|
|
17045
|
-
*
|
|
17046
|
-
* - allowed: `{"verdict":"allowed"}`
|
|
17047
|
-
* - denied: `{"verdict":"denied","reason":"<r>"}`
|
|
17048
|
-
* - redirected: `{"verdict":"redirected"}`
|
|
17049
|
-
*
|
|
17050
|
-
* Returns raw JSON; the host's cookie-write call URL-encodes.
|
|
17051
|
-
*/
|
|
17052
|
-
function encodeVerdictCookie(rendered) {
|
|
17053
|
-
const verdict = deriveVerdict(rendered);
|
|
17054
|
-
const reason = rendered.headers["X-Checkpoint-Reason"];
|
|
17055
|
-
return JSON.stringify(reason ? {
|
|
17056
|
-
verdict,
|
|
17057
|
-
reason
|
|
17058
|
-
} : { verdict });
|
|
17059
|
-
}
|
|
17060
|
-
|
|
17061
|
-
//#endregion
|
|
17062
|
-
//#region src/host-adapter/content-negotiation.ts
|
|
17063
|
-
/**
|
|
17064
|
-
* Content negotiation — framework-agnostic Accept-header parsing for
|
|
17065
|
-
* host adapters.
|
|
17066
|
-
*
|
|
17067
|
-
* The engine's `RenderedResponse` doesn't make HTML-vs-JSON branching
|
|
17068
|
-
* decisions; the host wrapper does that based on what the client
|
|
17069
|
-
* accepts. Both Next.js (NextRequest) and Express (Request) carry the
|
|
17070
|
-
* Accept header in different shapes — `req.headers.get('accept')` vs
|
|
17071
|
-
* `req.get('Accept')` vs `req.headers.accept` — so we accept any
|
|
17072
|
-
* Headers-like input and do the parsing here.
|
|
17073
|
-
*/
|
|
17074
|
-
/**
|
|
17075
|
-
* `true` when the client signaled it accepts HTML or XHTML. Used by
|
|
17076
|
-
* host adapters to choose between an HTML `/blocked` rewrite (browsers)
|
|
17077
|
-
* and a JSON 4xx response (curl, fetch-from-a-tool, ChatGPT-User).
|
|
17078
|
-
*
|
|
17079
|
-
* Loose match — q-values, parameters, and additional MIME types are
|
|
17080
|
-
* allowed. The spec's q-value precedence (RFC 9110 § 12.5.1) doesn't
|
|
17081
|
-
* matter here; we only care whether HTML is present at all.
|
|
17082
|
-
*
|
|
17083
|
-
* Accepts:
|
|
17084
|
-
* - a `Headers` instance (Web Fetch API; Next.js, Hono, Cloudflare)
|
|
17085
|
-
* - a plain `Record<string, string>` (Express, Connect, Fastify)
|
|
17086
|
-
* - a single string (caller already extracted the Accept value)
|
|
17087
|
-
* - `undefined` (treated as no-HTML)
|
|
17088
|
-
*/
|
|
17089
|
-
function acceptsHtml(input) {
|
|
17090
|
-
const accept = extractAccept(input);
|
|
17091
|
-
if (!accept) return false;
|
|
17092
|
-
return accept.includes("text/html") || accept.includes("application/xhtml+xml");
|
|
17093
|
-
}
|
|
17094
|
-
function extractAccept(input) {
|
|
17095
|
-
if (!input) return void 0;
|
|
17096
|
-
if (typeof input === "string") return input;
|
|
17097
|
-
if (typeof input.get === "function") return input.get("accept") ?? void 0;
|
|
17098
|
-
const rec = input;
|
|
17099
|
-
const value = rec.accept ?? rec.Accept;
|
|
17100
|
-
if (Array.isArray(value)) return value.join(",");
|
|
17101
|
-
return value;
|
|
17102
|
-
}
|
|
17103
|
-
|
|
17104
|
-
//#endregion
|
|
17105
|
-
//#region src/host-adapter/decision-mapping.ts
|
|
17106
|
-
/**
|
|
17107
|
-
* Path the `/blocked` dashboard route lives at. HTML clients that hit
|
|
17108
|
-
* a 4xx verdict get rewritten here at status 200 so the page renders
|
|
17109
|
-
* with the verdict cookie set and Sonner can pick up the toast.
|
|
17110
|
-
*
|
|
17111
|
-
* Hard-coded by convention; if a customer ever needs a custom path,
|
|
17112
|
-
* pass it through `CheckpointConfig.blockedPath` and override in the
|
|
17113
|
-
* host adapter (not in this lookup).
|
|
17114
|
-
*/
|
|
17115
|
-
const BLOCKED_PATH = "/blocked";
|
|
17116
|
-
/**
|
|
17117
|
-
* Classify a `RenderedResponse` into one of the four host-adapter
|
|
17118
|
-
* branches. `clientAcceptsHtml` comes from `acceptsHtml()` in
|
|
17119
|
-
* `content-negotiation.ts`.
|
|
17120
|
-
*/
|
|
17121
|
-
function classifyResponseShape(rendered, clientAcceptsHtml) {
|
|
17122
|
-
if (rendered.status === null) return "pass-through";
|
|
17123
|
-
if (rendered.status === 302 && rendered.headers.Location) return "redirect";
|
|
17124
|
-
if (clientAcceptsHtml && rendered.status >= 400 && rendered.status < 500) return "html-block";
|
|
17125
|
-
return "json-block";
|
|
17126
|
-
}
|
|
17127
|
-
|
|
17128
|
-
//#endregion
|
|
17129
|
-
//#region src/host-adapter/fetcher-envelope.ts
|
|
17130
|
-
/**
|
|
17131
|
-
* Dual-envelope selection predicate (draft-kya-http-02 §8.1 fetcher-200).
|
|
17132
|
-
*
|
|
17133
|
-
* AI-agent fetchers (Claude-User WebFetch, ChatGPT) collapse 4xx/5xx
|
|
17134
|
-
* responses and never surface the body to the LLM, so the §8.1 step-up
|
|
17135
|
-
* challenge served at 401 is invisible. The fix is a dual envelope: keep
|
|
17136
|
-
* the spec 401 for capable/discovery clients, and serve a body-readable
|
|
17137
|
-
* HTTP 200 (no `WWW-Authenticate`) for cooperative, self-identifying
|
|
17138
|
-
* agents so they can read the body + relay the consent link.
|
|
17139
|
-
*
|
|
17140
|
-
* `serveBodyReadable200` is the shared selection predicate every TS PEP
|
|
17141
|
-
* (checkpoint-nextjs, checkpoint-express / wasm-runtime) consults when its
|
|
17142
|
-
* challenge-emission mode is `negotiated`. Centralising it here — rather
|
|
17143
|
-
* than re-implementing per PEP — makes drift structurally impossible; the
|
|
17144
|
-
* fetcher-200 fixture freezes envelope BYTES, this function freezes the
|
|
17145
|
-
* SELECTION.
|
|
17146
|
-
*
|
|
17147
|
-
* **This is a cooperative-UX bridge, NOT an access control.** A spoofer
|
|
17148
|
-
* that hides its identity and does not opt in simply receives the spec
|
|
17149
|
-
* 401 (and the original body-drop). Access is still gated entirely by the
|
|
17150
|
-
* unchanged detection + delegation verification — never by which envelope
|
|
17151
|
-
* is selected.
|
|
17152
|
-
*/
|
|
17153
|
-
/**
|
|
17154
|
-
* Durable opt-in header — the primary, framework-agnostic signal that a
|
|
17155
|
-
* caller is a cooperative agent able to handle the 200 fetcher envelope.
|
|
17156
|
-
* Any non-empty value counts as opt-in (value semantics are reconciled
|
|
17157
|
-
* with mcp-i-cloudflare's `KYA-Accept-Challenge: delegation` in the spec).
|
|
17158
|
-
*/
|
|
17159
|
-
const ACCEPT_CHALLENGE_HEADER = "kya-accept-challenge";
|
|
17160
|
-
function readHeader(input, name) {
|
|
17161
|
-
if (!input) return void 0;
|
|
17162
|
-
if (typeof input.get === "function") return input.get(name) ?? void 0;
|
|
17163
|
-
const rec = input;
|
|
17164
|
-
const lower = name.toLowerCase();
|
|
17165
|
-
for (const key of Object.keys(rec)) if (key.toLowerCase() === lower) {
|
|
17166
|
-
const v = rec[key];
|
|
17167
|
-
return Array.isArray(v) ? v[0] : v ?? void 0;
|
|
17168
|
-
}
|
|
17169
|
-
}
|
|
17170
|
-
/**
|
|
17171
|
-
* Decide whether a `negotiated`-mode PEP should serve the body-readable
|
|
17172
|
-
* HTTP 200 fetcher envelope (`true`) or the spec 401 (`false`).
|
|
17173
|
-
*
|
|
17174
|
-
* Serve 200 when EITHER:
|
|
17175
|
-
* 1. the caller opts in via a non-empty `KYA-Accept-Challenge` header
|
|
17176
|
-
* (the durable, primary signal), OR
|
|
17177
|
-
* 2. detection classifies the caller as an AI agent — BOTH `isAgent` and
|
|
17178
|
-
* `detectionClass === 'ai_agent'` must agree (a transitional UA heuristic,
|
|
17179
|
-
* retired as frameworks adopt the header).
|
|
17180
|
-
*
|
|
17181
|
-
* Otherwise serve the 401 — spoofers, silent, discovery, and OAuth
|
|
17182
|
-
* clients all land here, which is acceptable because this is UX, not a
|
|
17183
|
-
* security boundary.
|
|
17184
|
-
*
|
|
17185
|
-
* Requiring both `isAgent` AND the `ai_agent` class to fire the heuristic
|
|
17186
|
-
* mirrors .NET `IsInteractiveAiAgent` (`IsAgent && DetectionClass.Type ==
|
|
17187
|
-
* AiAgent`) and the gateway worker, so the cross-PEP selection cannot drift on
|
|
17188
|
-
* the pathological case where the two signals disagree (class says agent,
|
|
17189
|
-
* `isAgent` says no): that caller is treated as non-cooperative (spec 401),
|
|
17190
|
-
* never demoted past it. In normal engine output the two signals agree, so
|
|
17191
|
-
* who-gets-200 is unchanged for real traffic.
|
|
17192
|
-
*
|
|
17193
|
-
* @param headers request headers (for the opt-in signal)
|
|
17194
|
-
* @param detectionClass the caller's detection class in any representation
|
|
17195
|
-
* the engine produces (a `DetectionClass` object, the
|
|
17196
|
-
* `ai_agent` wire string, or absent)
|
|
17197
|
-
* @param isAgent the engine's `isAgent` verdict — gates the `ai_agent`
|
|
17198
|
-
* heuristic so a class/`isAgent` disagreement gets the 401
|
|
17199
|
-
*/
|
|
17200
|
-
function serveBodyReadable200(headers, detectionClass, isAgent) {
|
|
17201
|
-
const optIn = readHeader(headers, ACCEPT_CHALLENGE_HEADER);
|
|
17202
|
-
if (optIn && optIn.trim().length > 0) return true;
|
|
17203
|
-
if (isAgent && detectionClass !== void 0 && detectionClass !== null) {
|
|
17204
|
-
if (normalizeDetectionClassEnum(detectionClass) === "ai_agent") return true;
|
|
17205
|
-
}
|
|
17206
|
-
return false;
|
|
17207
|
-
}
|
|
17208
|
-
/**
|
|
17209
|
-
* Resolve the challenge-emission mode + request signals into the single
|
|
17210
|
-
* boolean each PEP needs: serve the body-readable 200 (`true`) or the spec
|
|
17211
|
-
* 401 (`false`). Centralising the mode gate here — not just the predicate —
|
|
17212
|
-
* keeps the rollout switch identical across every TS PEP.
|
|
17213
|
-
*/
|
|
17214
|
-
function selectBodyReadable200(mode, headers, detectionClass, isAgent) {
|
|
17215
|
-
if (mode === "always-200") return true;
|
|
17216
|
-
if (mode === "negotiated") return serveBodyReadable200(headers, detectionClass, isAgent);
|
|
17217
|
-
return false;
|
|
17218
|
-
}
|
|
17219
|
-
|
|
17220
|
-
//#endregion
|
|
17221
|
-
//#region src/mcpi/kya-http-error-codes.ts
|
|
17222
|
-
/**
|
|
17223
|
-
* KYA-HTTP error code registry — draft-kya-http-02 §9 / H1.2 (#3245).
|
|
17224
|
-
*
|
|
17225
|
-
* The `kyaos/*` strings are wire constants returned in the `error` field of a
|
|
17226
|
-
* KYA-HTTP failure response (and mapped to an HTTP status). Emitters MUST use
|
|
17227
|
-
* these EXACT bytes; consumers MAY additionally accept the legacy `kya/*`
|
|
17228
|
-
* spellings for one transition cycle.
|
|
17229
|
-
*
|
|
17230
|
-
* The single source of truth is the golden fixture
|
|
17231
|
-
* `packages/checkpoint-shared/fixtures/kya-http/error-codes.json`; the parity
|
|
17232
|
-
* test in `__tests__/kya-http-error-codes.test.ts` reads that JSON via `fs` and
|
|
17233
|
-
* asserts this map is byte-exact against it (no drift, no omissions).
|
|
17234
|
-
*
|
|
17235
|
-
* `as const satisfies Record<string, \`kyaos/${string}\`>` keeps the narrow
|
|
17236
|
-
* literal value types (so consumers get autocomplete and a compile error on a
|
|
17237
|
-
* typo'd code) while still proving every value is a well-formed `kyaos/…` string.
|
|
17238
|
-
*/
|
|
17239
|
-
const KYA_HTTP_ERROR = {
|
|
17240
|
-
MISSING_SIGNATURE: "kyaos/missing-signature",
|
|
17241
|
-
INVALID_SIGNATURE: "kyaos/invalid-signature",
|
|
17242
|
-
EXPIRED: "kyaos/expired",
|
|
17243
|
-
REPLAY: "kyaos/replay",
|
|
17244
|
-
DID_UNRESOLVABLE: "kyaos/did-unresolvable",
|
|
17245
|
-
AUTHORIZATION_REQUIRED: "kyaos/authorization-required",
|
|
17246
|
-
PROFILE_VIOLATION: "kyaos/profile-violation",
|
|
17247
|
-
DELEGATION_REVOKED: "kyaos/delegation-revoked",
|
|
17248
|
-
SCOPE_INSUFFICIENT: "kyaos/scope-insufficient",
|
|
17249
|
-
CHAIN_BROKEN: "kyaos/chain-broken",
|
|
17250
|
-
HOLDER_MISMATCH: "kyaos/holder-mismatch",
|
|
17251
|
-
AUDIENCE_MISMATCH: "kyaos/audience-mismatch",
|
|
17252
|
-
SESSION_MISMATCH: "kyaos/session-mismatch",
|
|
17253
|
-
PICKUP_PINNED: "kyaos/pickup-pinned",
|
|
17254
|
-
ASSURANCE_INSUFFICIENT: "kyaos/assurance-insufficient",
|
|
17255
|
-
STATUS_PENDING: "kyaos/status-pending",
|
|
17256
|
-
AUTHORIZATION_HOST_UNAVAILABLE: "kyaos/authorization-host-unavailable",
|
|
17257
|
-
REPLAY_STATE_UNAVAILABLE: "kyaos/replay-state-unavailable",
|
|
17258
|
-
REPLAY_CAPACITY: "kyaos/replay-capacity",
|
|
17259
|
-
INVALID_SESSION: "kyaos/invalid-session",
|
|
17260
|
-
PICKUP_EXPIRED: "kyaos/pickup-expired"
|
|
17261
|
-
};
|
|
17262
|
-
/**
|
|
17263
|
-
* The HTTP status the registry assigns each code (draft-kya-http-02 §9).
|
|
17264
|
-
* Mirrors `error-codes.json` exactly, pinned by `__tests__/kya-http-error-codes.test.ts`,
|
|
17265
|
-
* and matches the engine's own table (`rust/crates/kya-os-engine/src/render/kya_error.rs`).
|
|
17266
|
-
*/
|
|
17267
|
-
const KYA_HTTP_ERROR_STATUS = {
|
|
17268
|
-
[KYA_HTTP_ERROR.MISSING_SIGNATURE]: 401,
|
|
17269
|
-
[KYA_HTTP_ERROR.INVALID_SIGNATURE]: 401,
|
|
17270
|
-
[KYA_HTTP_ERROR.EXPIRED]: 401,
|
|
17271
|
-
[KYA_HTTP_ERROR.REPLAY]: 401,
|
|
17272
|
-
[KYA_HTTP_ERROR.DID_UNRESOLVABLE]: 401,
|
|
17273
|
-
[KYA_HTTP_ERROR.AUTHORIZATION_REQUIRED]: 401,
|
|
17274
|
-
[KYA_HTTP_ERROR.PROFILE_VIOLATION]: 403,
|
|
17275
|
-
[KYA_HTTP_ERROR.DELEGATION_REVOKED]: 403,
|
|
17276
|
-
[KYA_HTTP_ERROR.SCOPE_INSUFFICIENT]: 403,
|
|
17277
|
-
[KYA_HTTP_ERROR.CHAIN_BROKEN]: 403,
|
|
17278
|
-
[KYA_HTTP_ERROR.HOLDER_MISMATCH]: 403,
|
|
17279
|
-
[KYA_HTTP_ERROR.AUDIENCE_MISMATCH]: 403,
|
|
17280
|
-
[KYA_HTTP_ERROR.SESSION_MISMATCH]: 403,
|
|
17281
|
-
[KYA_HTTP_ERROR.PICKUP_PINNED]: 403,
|
|
17282
|
-
[KYA_HTTP_ERROR.ASSURANCE_INSUFFICIENT]: 403,
|
|
17283
|
-
[KYA_HTTP_ERROR.STATUS_PENDING]: 503,
|
|
17284
|
-
[KYA_HTTP_ERROR.AUTHORIZATION_HOST_UNAVAILABLE]: 503,
|
|
17285
|
-
[KYA_HTTP_ERROR.REPLAY_STATE_UNAVAILABLE]: 503,
|
|
17286
|
-
[KYA_HTTP_ERROR.REPLAY_CAPACITY]: 429,
|
|
17287
|
-
[KYA_HTTP_ERROR.INVALID_SESSION]: 404,
|
|
17288
|
-
[KYA_HTTP_ERROR.PICKUP_EXPIRED]: 410
|
|
17289
|
-
};
|
|
17290
|
-
|
|
17291
|
-
//#endregion
|
|
17292
|
-
//#region src/host-adapter/challenge-wire.ts
|
|
17293
|
-
/**
|
|
17294
|
-
* Canonical fixture-pinned KYA HTTP challenge-wire builder.
|
|
17295
|
-
*
|
|
17296
|
-
* The builder is transport-neutral and Edge-safe. Hosts must register the
|
|
17297
|
-
* challenge and resolve every URI before calling it; this module validates and
|
|
17298
|
-
* serializes those trusted values without network, database, or request access.
|
|
17299
|
-
*/
|
|
17300
|
-
const PROTECTED_RESOURCE_METADATA_PATH = "/.well-known/oauth-protected-resource";
|
|
17301
|
-
const DEFAULT_POLL_INTERVAL_S = 3;
|
|
17302
|
-
const INVALID_QUOTED_VALUE = /[\u0000-\u001f\u007f"\\]/;
|
|
17303
|
-
const SCOPE_TOKEN = /^[\x21\x23-\x5b\x5d-\x7e]+$/;
|
|
17304
|
-
const SID = /^kya-[0-9a-f]{16,}$/;
|
|
17305
|
-
const ASSURANCE_TIERS = /* @__PURE__ */ new Set([
|
|
17306
|
-
"anonymous",
|
|
17307
|
-
"attested-bearer",
|
|
17308
|
-
"key-bound",
|
|
17309
|
-
"registered",
|
|
17310
|
-
"delegated"
|
|
17311
|
-
]);
|
|
17312
|
-
/** Typed validation failure raised before any response is materialized. */
|
|
17313
|
-
var ChallengeWireError = class extends TypeError {
|
|
17314
|
-
code;
|
|
17315
|
-
constructor(code, message) {
|
|
17316
|
-
super(message);
|
|
17317
|
-
this.name = "ChallengeWireError";
|
|
17318
|
-
this.code = code;
|
|
17319
|
-
}
|
|
17320
|
-
};
|
|
17321
|
-
/** Generate a 128-bit, lower-case hexadecimal challenge id. */
|
|
17322
|
-
function generateDelegationSid() {
|
|
17323
|
-
const bytes = /* @__PURE__ */ new Uint8Array(16);
|
|
17324
|
-
crypto.getRandomValues(bytes);
|
|
17325
|
-
let hex = "";
|
|
17326
|
-
for (const byte of bytes) hex += byte.toString(16).padStart(2, "0");
|
|
17327
|
-
return `kya-${hex}`;
|
|
17328
|
-
}
|
|
17329
|
-
/** Derive pickup from the registered consent origin, never request Host. */
|
|
17330
|
-
function deriveDelegationPickupUri(consentUri, sid) {
|
|
17331
|
-
const consent = parseHttpsUrl("consentUri", consentUri);
|
|
17332
|
-
assertQuotedValue("sid", sid, "invalid-sid");
|
|
17333
|
-
return `${consent.origin}/api/delegation/pickup/${sid}`;
|
|
17334
|
-
}
|
|
17335
|
-
/** Build the byte-pinned Delegation authentication field value. */
|
|
17336
|
-
function buildDelegationChallengeHeader(input) {
|
|
17337
|
-
const normalized = validateInput(input);
|
|
17338
|
-
const params = [
|
|
17339
|
-
["realm", normalized.realm],
|
|
17340
|
-
["sid", normalized.sid],
|
|
17341
|
-
["consent_uri", normalized.consentUri],
|
|
17342
|
-
["pickup_uri", normalized.pickupUri]
|
|
17343
|
-
];
|
|
17344
|
-
if (normalized.requiredScopes.length > 0) params.push(["scope", normalized.requiredScopes.join(" ")]);
|
|
17345
|
-
if (normalized.minAssurance) params.push(["min_assurance", normalized.minAssurance]);
|
|
17346
|
-
if (input.pollIntervalS !== void 0) params.push(["interval", String(normalized.pollIntervalS)]);
|
|
17347
|
-
params.push(["kind", normalized.kind]);
|
|
17348
|
-
return `Delegation ${params.map(([name, value]) => `${name}="${value}"`).join(", ")}`;
|
|
17349
|
-
}
|
|
17350
|
-
/** Build RFC 9728 Bearer discovery for a protected-resource realm. */
|
|
17351
|
-
function buildDelegationBearerHeader(realm) {
|
|
17352
|
-
assertRealm(realm);
|
|
17353
|
-
return `Bearer resource_metadata="https://${realm}${PROTECTED_RESOURCE_METADATA_PATH}"`;
|
|
17354
|
-
}
|
|
17355
|
-
/** Build the four required machine-followable delegation instruction elements. */
|
|
17356
|
-
function buildDelegationInstructions(consentUri, pickupUri, pollIntervalS) {
|
|
17357
|
-
return `This action requires human authorization. First establish your pickup binding at ${pickupUri}. If you can sign HTTP requests, sign each poll with an ephemeral did:key; otherwise generate one random 32-byte token encoded as unpadded base64url and send it as X-KYA-Pickup-Token on EVERY poll. After receiving 202 pending, show your user this link and ask them to approve: ${consentUri}. Continue polling ${pickupUri} every ${pollIntervalS} seconds with the same binding. When the response status is 200, take the 'delegation' value and retry your original request with header 'Authorization: Bearer <delegation>'.`;
|
|
17358
|
-
}
|
|
17359
|
-
/** Build the proof-bound body shared byte-for-byte by both HTTP envelopes. */
|
|
17360
|
-
function buildDelegationChallengeBody(input) {
|
|
17361
|
-
const normalized = validateInput(input);
|
|
17362
|
-
const common = {
|
|
17363
|
-
sid: normalized.sid,
|
|
17364
|
-
consent_uri: normalized.consentUri,
|
|
17365
|
-
pickup_uri: normalized.pickupUri,
|
|
17366
|
-
...normalized.requiredScopes.length > 0 ? { required_scopes: [...normalized.requiredScopes] } : {},
|
|
17367
|
-
...normalized.minAssurance ? { min_assurance: normalized.minAssurance } : {},
|
|
17368
|
-
poll_interval_s: normalized.pollIntervalS,
|
|
17369
|
-
challenge_proof: input.challengeProof
|
|
17370
|
-
};
|
|
17371
|
-
if (normalized.kind === "approval_quorum") return {
|
|
17372
|
-
error: KYA_HTTP_ERROR.AUTHORIZATION_REQUIRED,
|
|
17373
|
-
kyaos: {
|
|
17374
|
-
sid: common.sid,
|
|
17375
|
-
kind: "approval_quorum",
|
|
17376
|
-
quorum: normalized.quorum,
|
|
17377
|
-
action_nonce: normalized.actionNonce,
|
|
17378
|
-
consent_uri: common.consent_uri,
|
|
17379
|
-
pickup_uri: common.pickup_uri,
|
|
17380
|
-
...common.required_scopes ? { required_scopes: common.required_scopes } : {},
|
|
17381
|
-
...common.min_assurance ? { min_assurance: common.min_assurance } : {},
|
|
17382
|
-
poll_interval_s: common.poll_interval_s,
|
|
17383
|
-
challenge_proof: common.challenge_proof
|
|
17384
|
-
},
|
|
17385
|
-
instructions: buildApprovalQuorumInstructions(normalized)
|
|
17386
|
-
};
|
|
17387
|
-
return {
|
|
17388
|
-
error: KYA_HTTP_ERROR.AUTHORIZATION_REQUIRED,
|
|
17389
|
-
kyaos: {
|
|
17390
|
-
...common,
|
|
17391
|
-
action: {
|
|
17392
|
-
type: "delegation",
|
|
17393
|
-
consent_uri: normalized.consentUri,
|
|
17394
|
-
pickup_uri: normalized.pickupUri,
|
|
17395
|
-
poll_interval_s: normalized.pollIntervalS,
|
|
17396
|
-
pin: { header: "X-KYA-Pickup-Token" },
|
|
17397
|
-
retry: {
|
|
17398
|
-
header: "Authorization",
|
|
17399
|
-
scheme: "Bearer",
|
|
17400
|
-
value_from: "delegation"
|
|
17401
|
-
}
|
|
17402
|
-
}
|
|
17403
|
-
},
|
|
17404
|
-
instructions: buildDelegationInstructions(normalized.consentUri, normalized.pickupUri, normalized.pollIntervalS)
|
|
17405
|
-
};
|
|
17406
|
-
}
|
|
17407
|
-
/** Build either the canonical 401 or its body-identical fetcher-200 envelope. */
|
|
17408
|
-
function buildDelegationChallengeEnvelope(input, mode = "spec-401") {
|
|
17409
|
-
const normalized = validateInput(input);
|
|
17410
|
-
if (normalized.kind === "approval_quorum" && mode === "fetcher-200") throw new ChallengeWireError("unsupported-envelope", "fetcher-200 is not fixture-defined for approval_quorum");
|
|
17411
|
-
const body = buildDelegationChallengeBody(input);
|
|
17412
|
-
if (normalized.kind === "approval_quorum") return {
|
|
17413
|
-
status: 401,
|
|
17414
|
-
headers: [
|
|
17415
|
-
["WWW-Authenticate", buildDelegationChallengeHeader(input)],
|
|
17416
|
-
["Retry-After", String(normalized.pollIntervalS)],
|
|
17417
|
-
["Content-Type", "application/json"],
|
|
17418
|
-
["Cache-Control", "no-store"]
|
|
17419
|
-
],
|
|
17420
|
-
body
|
|
17421
|
-
};
|
|
17422
|
-
const hintHeaders = [
|
|
17423
|
-
["Content-Type", "application/json"],
|
|
17424
|
-
["Cache-Control", "no-store"],
|
|
17425
|
-
["KYA-Auth-Required", "true"],
|
|
17426
|
-
["KYA-Auth-Url", normalized.consentUri],
|
|
17427
|
-
["Link", `<${normalized.consentUri}>; rel="kya-authorize"`],
|
|
17428
|
-
["KYA-Action", "challenge"]
|
|
17429
|
-
];
|
|
17430
|
-
if (mode === "fetcher-200") return {
|
|
17431
|
-
status: 200,
|
|
17432
|
-
headers: hintHeaders,
|
|
17433
|
-
body
|
|
17434
|
-
};
|
|
17435
|
-
return {
|
|
17436
|
-
status: 401,
|
|
17437
|
-
headers: [
|
|
17438
|
-
["WWW-Authenticate", buildDelegationChallengeHeader(input)],
|
|
17439
|
-
["WWW-Authenticate", `Bearer resource_metadata="${normalized.resourceMetadataUri}"`],
|
|
17440
|
-
["Retry-After", String(normalized.pollIntervalS)],
|
|
17441
|
-
...hintHeaders
|
|
17442
|
-
],
|
|
17443
|
-
body
|
|
17444
|
-
};
|
|
17445
|
-
}
|
|
17446
|
-
/** Preferred generic name; the legacy export remains for host compatibility. */
|
|
17447
|
-
const buildChallengeWire = buildDelegationChallengeEnvelope;
|
|
17448
|
-
function validateInput(input) {
|
|
17449
|
-
assertRealm(input.realm);
|
|
17450
|
-
assertQuotedValue("sid", input.sid, "invalid-sid");
|
|
17451
|
-
if (!SID.test(input.sid)) throw new ChallengeWireError("invalid-sid", "sid must start with kya- and contain at least 64 bits of lower-case hexadecimal entropy");
|
|
17452
|
-
const consent = parseHttpsUrl("consentUri", input.consentUri);
|
|
17453
|
-
const pickup = parseHttpsUrl("pickupUri", input.pickupUri);
|
|
17454
|
-
const expectedPickup = `${consent.origin}/api/delegation/pickup/${input.sid}`;
|
|
17455
|
-
if (pickup.href !== expectedPickup) throw new ChallengeWireError("invalid-uri", "pickupUri must use the registered consent origin and sid");
|
|
17456
|
-
const pollIntervalS = input.pollIntervalS ?? DEFAULT_POLL_INTERVAL_S;
|
|
17457
|
-
if (!Number.isInteger(pollIntervalS) || pollIntervalS < 1 || pollIntervalS > 999) throw new ChallengeWireError("invalid-interval", "pollIntervalS must be an integer from 1 through 999");
|
|
17458
|
-
if (input.challengeProof === void 0 || input.challengeProof === null) throw new ChallengeWireError("invalid-proof", "challengeProof is required");
|
|
17459
|
-
const requiredScopes = input.requiredScopes ?? [];
|
|
17460
|
-
for (const scope of requiredScopes) if (!SCOPE_TOKEN.test(scope)) throw new ChallengeWireError("invalid-scope", `invalid required scope: ${scope}`);
|
|
17461
|
-
if (input.minAssurance && !ASSURANCE_TIERS.has(input.minAssurance)) throw new ChallengeWireError("invalid-assurance", `invalid minAssurance: ${input.minAssurance}`);
|
|
17462
|
-
const kind = input.kind ?? "delegation";
|
|
17463
|
-
if (kind !== "delegation" && kind !== "approval_quorum") throw new ChallengeWireError("invalid-kind", `unsupported challenge kind: ${String(kind)}`);
|
|
17464
|
-
let resourceMetadataUri;
|
|
17465
|
-
let quorum;
|
|
17466
|
-
let actionNonce;
|
|
17467
|
-
if (kind === "delegation") {
|
|
17468
|
-
resourceMetadataUri = parseHttpsUrl("resourceMetadataUri", input.resourceMetadataUri).href;
|
|
17469
|
-
const expectedMetadata = `https://${input.realm}${PROTECTED_RESOURCE_METADATA_PATH}`;
|
|
17470
|
-
if (resourceMetadataUri !== expectedMetadata) throw new ChallengeWireError("invalid-uri", "resourceMetadataUri must be the protected resource RFC 9728 metadata URL");
|
|
17471
|
-
} else {
|
|
17472
|
-
const approval = input;
|
|
17473
|
-
quorum = approval.quorum;
|
|
17474
|
-
actionNonce = approval.actionNonce;
|
|
17475
|
-
if (!Number.isInteger(quorum) || quorum < 1) throw new ChallengeWireError("invalid-quorum", "quorum must be a positive integer");
|
|
17476
|
-
assertQuotedValue("actionNonce", actionNonce, "invalid-action-nonce");
|
|
17477
|
-
}
|
|
17478
|
-
return {
|
|
17479
|
-
realm: input.realm,
|
|
17480
|
-
sid: input.sid,
|
|
17481
|
-
consentUri: consent.href,
|
|
17482
|
-
pickupUri: pickup.href,
|
|
17483
|
-
resourceMetadataUri,
|
|
17484
|
-
requiredScopes,
|
|
17485
|
-
pollIntervalS,
|
|
17486
|
-
minAssurance: input.minAssurance,
|
|
17487
|
-
kind,
|
|
17488
|
-
quorum,
|
|
17489
|
-
actionNonce
|
|
17490
|
-
};
|
|
17491
|
-
}
|
|
17492
|
-
function buildApprovalQuorumInstructions(input) {
|
|
17493
|
-
return `This action requires approval from ${input.quorum} human approvers. Show your user this link to begin the approval process: ${input.consentUri}. Then poll ${input.pickupUri} every ${input.pollIntervalS} seconds (sign polls with an ephemeral did:key, or send one random 32-byte X-KYA-Pickup-Token on EVERY poll). When the response status is 200, retry your original request presenting the returned grants in the KYA-Approvals header.`;
|
|
17494
|
-
}
|
|
17495
|
-
function assertRealm(realm) {
|
|
17496
|
-
assertQuotedValue("realm", realm, "invalid-realm");
|
|
17497
|
-
if (realm.includes("/") || realm.includes("@") || realm.includes("?") || realm.includes("#")) throw new ChallengeWireError("invalid-realm", "realm must be a host with an optional port");
|
|
17498
|
-
try {
|
|
17499
|
-
if (new URL(`https://${realm}`).host !== realm) throw new Error("invalid authority");
|
|
17500
|
-
} catch {
|
|
17501
|
-
throw new ChallengeWireError("invalid-realm", "realm must be a valid host with an optional port");
|
|
17502
|
-
}
|
|
17503
|
-
}
|
|
17504
|
-
function assertQuotedValue(name, value, code) {
|
|
17505
|
-
if (typeof value !== "string" || value.length === 0 || INVALID_QUOTED_VALUE.test(value)) throw new ChallengeWireError(code, `${name} contains characters unsafe for an HTTP quoted-string`);
|
|
17506
|
-
}
|
|
17507
|
-
function parseHttpsUrl(name, value) {
|
|
17508
|
-
assertQuotedValue(name, value, "invalid-uri");
|
|
17509
|
-
let parsed;
|
|
17510
|
-
try {
|
|
17511
|
-
parsed = new URL(value);
|
|
17512
|
-
} catch {
|
|
17513
|
-
throw new ChallengeWireError("invalid-uri", `${name} must be an absolute HTTPS URL`);
|
|
17514
|
-
}
|
|
17515
|
-
if (parsed.protocol !== "https:" || parsed.username || parsed.password) throw new ChallengeWireError("invalid-uri", `${name} must be an absolute HTTPS URL without credentials`);
|
|
17516
|
-
return parsed;
|
|
17517
|
-
}
|
|
17518
|
-
|
|
17519
|
-
//#endregion
|
|
17520
|
-
//#region src/host-adapter/challenge-context.ts
|
|
17521
|
-
const DEFAULT_CHALLENGE_CONTEXT_TIMEOUT_MS = 3e3;
|
|
17522
|
-
/**
|
|
17523
|
-
* Resolve and validate registered challenge context at the async host boundary.
|
|
17524
|
-
* Resolver failures become an absent context so the renderer can emit the
|
|
17525
|
-
* canonical retryable status-pending response; secrets and proof values are
|
|
17526
|
-
* never included in failure events.
|
|
17527
|
-
*/
|
|
17528
|
-
async function resolveChallengeContext(resolver, context, options = {}) {
|
|
17529
|
-
if (!resolver) return void 0;
|
|
17530
|
-
const timeoutMs = options.timeoutMs ?? 3e3;
|
|
17531
|
-
if (!Number.isInteger(timeoutMs) || timeoutMs < 1) throw new TypeError("challenge context timeout must be a positive integer");
|
|
17532
|
-
let timeoutId;
|
|
17533
|
-
try {
|
|
17534
|
-
const value = await Promise.race([Promise.resolve(resolver(context)), new Promise((_resolve, reject) => {
|
|
17535
|
-
timeoutId = setTimeout(() => reject(new ChallengeContextTimeoutError(timeoutMs)), timeoutMs);
|
|
17536
|
-
})]);
|
|
17537
|
-
if (timeoutId !== void 0) clearTimeout(timeoutId);
|
|
17538
|
-
if (!value) return void 0;
|
|
17539
|
-
try {
|
|
17540
|
-
buildChallengeWire(value, "spec-401");
|
|
17541
|
-
return value;
|
|
17542
|
-
} catch (error) {
|
|
17543
|
-
options.onFailure?.({
|
|
17544
|
-
reason: "invalid-context",
|
|
17545
|
-
message: error.message
|
|
17546
|
-
});
|
|
17547
|
-
return;
|
|
17548
|
-
}
|
|
17549
|
-
} catch (error) {
|
|
17550
|
-
if (timeoutId !== void 0) clearTimeout(timeoutId);
|
|
17551
|
-
options.onFailure?.({
|
|
17552
|
-
reason: error instanceof ChallengeContextTimeoutError ? "timeout" : "resolver-error",
|
|
17553
|
-
message: error instanceof ChallengeContextTimeoutError ? error.message : "challenge context resolver failed"
|
|
17554
|
-
});
|
|
17555
|
-
return;
|
|
17556
|
-
}
|
|
17557
|
-
}
|
|
17558
|
-
var ChallengeContextTimeoutError = class extends Error {
|
|
17559
|
-
constructor(timeoutMs) {
|
|
17560
|
-
super(`challenge context resolution exceeded ${timeoutMs}ms`);
|
|
17561
|
-
this.name = "ChallengeContextTimeoutError";
|
|
17562
|
-
}
|
|
17563
|
-
};
|
|
17564
|
-
|
|
17565
15461
|
//#endregion
|
|
17566
15462
|
//#region src/wire/vault.ts
|
|
17567
15463
|
/**
|
|
@@ -17707,119 +15603,6 @@ function deriveMcpiUserDid(slug, userId) {
|
|
|
17707
15603
|
return `${deriveMcpiOrgDid(slug)}:users:${userId}`;
|
|
17708
15604
|
}
|
|
17709
15605
|
|
|
17710
|
-
//#endregion
|
|
17711
|
-
//#region src/mcpi/delegation-headers.ts
|
|
17712
|
-
/**
|
|
17713
|
-
* Delegation-proof request detection (P2 / DR-1).
|
|
17714
|
-
*
|
|
17715
|
-
* The engine's L2 delegation-root pinning (`ContextSpec.trustedDelegationRoots`)
|
|
17716
|
-
* is consulted for every credential the engine verifies: the delegation-proof
|
|
17717
|
-
* headers below AND an `Authorization: Bearer` VC-JWT. Consumers gate root
|
|
17718
|
-
* resolution on `requestPresentedCredential`, so the human / no-credential hot
|
|
17719
|
-
* path stays a precise no-op.
|
|
17720
|
-
*
|
|
17721
|
-
* Keeping the header set here (rather than re-listing the literals at each site)
|
|
17722
|
-
* is the whole point: a new delegation transport header is added in one place
|
|
17723
|
-
* and every verifier surface agrees.
|
|
17724
|
-
*/
|
|
17725
|
-
/**
|
|
17726
|
-
* Lowercased delegation-proof header names. `kya-os-delegation-credential` is the
|
|
17727
|
-
* canonical KYA-OS transport; `kya-delegation` is the legacy envelope form still
|
|
17728
|
-
* accepted via `legacyEnvelopeFallback`.
|
|
17729
|
-
*/
|
|
17730
|
-
const DELEGATION_PROOF_HEADERS = ["kya-os-delegation-credential", "kya-delegation"];
|
|
17731
|
-
/** A header value is "present" when it is a non-empty string (or non-empty list). */
|
|
17732
|
-
function isPresent(value) {
|
|
17733
|
-
if (Array.isArray(value)) return value.length > 0;
|
|
17734
|
-
return typeof value === "string" && value.length > 0;
|
|
17735
|
-
}
|
|
17736
|
-
/**
|
|
17737
|
-
* Does the request carry a KYA-OS delegation-proof header?
|
|
17738
|
-
*
|
|
17739
|
-
* Accepts either a `Headers` instance (Next.js / fetch — case-insensitive
|
|
17740
|
-
* lookup) or a plain header record (raw Node/Express headers, gateway worker's
|
|
17741
|
-
* lowercased map). Record keys are matched case-insensitively, so callers do not
|
|
17742
|
-
* need to pre-normalize. Returns `false` for `null`/`undefined`.
|
|
17743
|
-
*/
|
|
17744
|
-
function requestCarriesDelegationProof(headers) {
|
|
17745
|
-
if (!headers) return false;
|
|
17746
|
-
if (typeof headers.get === "function") {
|
|
17747
|
-
const h = headers;
|
|
17748
|
-
return DELEGATION_PROOF_HEADERS.some((name) => isPresent(h.get(name)));
|
|
17749
|
-
}
|
|
17750
|
-
const record = headers;
|
|
17751
|
-
const lowerKeyed = /* @__PURE__ */ new Map();
|
|
17752
|
-
for (const key of Object.keys(record)) lowerKeyed.set(key.toLowerCase(), record[key]);
|
|
17753
|
-
return DELEGATION_PROOF_HEADERS.some((name) => isPresent(lowerKeyed.get(name)));
|
|
17754
|
-
}
|
|
17755
|
-
const MAX_VC_JWT_PAYLOAD_CHARS = 16384;
|
|
17756
|
-
function headerText(headers, name) {
|
|
17757
|
-
if (typeof headers.get === "function") return headers.get(name) ?? void 0;
|
|
17758
|
-
for (const [key, value] of Object.entries(headers)) {
|
|
17759
|
-
if (key.toLowerCase() !== name) continue;
|
|
17760
|
-
if (Array.isArray(value)) return value.join(", ");
|
|
17761
|
-
return typeof value === "string" ? value : void 0;
|
|
17762
|
-
}
|
|
17763
|
-
}
|
|
17764
|
-
function isMemberDelimiter(c) {
|
|
17765
|
-
return c === "=" || c === ";" || c === "," || c === " " || c === " ";
|
|
17766
|
-
}
|
|
17767
|
-
function hasKyaMember(value) {
|
|
17768
|
-
let memberStart = true;
|
|
17769
|
-
let quoted = false;
|
|
17770
|
-
let escaped = false;
|
|
17771
|
-
for (let i = 0; i < value.length; i++) {
|
|
17772
|
-
const c = value[i];
|
|
17773
|
-
if (quoted) {
|
|
17774
|
-
if (escaped) escaped = false;
|
|
17775
|
-
else if (c === "\\") escaped = true;
|
|
17776
|
-
else if (c === "\"") quoted = false;
|
|
17777
|
-
continue;
|
|
17778
|
-
}
|
|
17779
|
-
if (memberStart) {
|
|
17780
|
-
if (c === " " || c === " ") continue;
|
|
17781
|
-
if (value.startsWith("kya", i) && (i + 3 === value.length || isMemberDelimiter(value[i + 3]))) return true;
|
|
17782
|
-
memberStart = false;
|
|
17783
|
-
}
|
|
17784
|
-
if (c === "\"") quoted = true;
|
|
17785
|
-
else if (c === ",") memberStart = true;
|
|
17786
|
-
}
|
|
17787
|
-
return false;
|
|
17788
|
-
}
|
|
17789
|
-
function decodeBase64UrlJson(segment) {
|
|
17790
|
-
const padded = segment.replace(/-/g, "+").replace(/_/g, "/");
|
|
17791
|
-
const binary = atob(padded + "=".repeat((4 - padded.length % 4) % 4));
|
|
17792
|
-
const bytes = Uint8Array.from(binary, (ch) => ch.charCodeAt(0));
|
|
17793
|
-
return JSON.parse(new TextDecoder().decode(bytes));
|
|
17794
|
-
}
|
|
17795
|
-
function isDelegationCredentialPayload(payload) {
|
|
17796
|
-
if (typeof payload !== "object" || payload === null) return false;
|
|
17797
|
-
if ("vc" in payload) return true;
|
|
17798
|
-
const type = payload.type;
|
|
17799
|
-
return Array.isArray(type) && type.includes("DelegationCredential");
|
|
17800
|
-
}
|
|
17801
|
-
function looksLikeVcJwt(token) {
|
|
17802
|
-
const parts = token.split(".");
|
|
17803
|
-
if (parts.length !== 3 || parts.some((part) => part.length === 0)) return false;
|
|
17804
|
-
if (parts[1].length > MAX_VC_JWT_PAYLOAD_CHARS) return true;
|
|
17805
|
-
try {
|
|
17806
|
-
return isDelegationCredentialPayload(decodeBase64UrlJson(parts[1]));
|
|
17807
|
-
} catch {
|
|
17808
|
-
return false;
|
|
17809
|
-
}
|
|
17810
|
-
}
|
|
17811
|
-
/** Same definition as the .NET / Java `IsCredentialPresented`. */
|
|
17812
|
-
function requestPresentedCredential(headers) {
|
|
17813
|
-
if (!headers) return false;
|
|
17814
|
-
for (const name of ["signature-input", "signature"]) {
|
|
17815
|
-
const value = headerText(headers, name);
|
|
17816
|
-
if (value && hasKyaMember(value)) return true;
|
|
17817
|
-
}
|
|
17818
|
-
if (requestCarriesDelegationProof(headers)) return true;
|
|
17819
|
-
const bearer = headerText(headers, "authorization")?.match(/^bearer\s+(\S+)/i);
|
|
17820
|
-
return bearer !== null && bearer !== void 0 && looksLikeVcJwt(bearer[1]);
|
|
17821
|
-
}
|
|
17822
|
-
|
|
17823
15606
|
//#endregion
|
|
17824
15607
|
//#region src/mcpi/principal.ts
|
|
17825
15608
|
/**
|
|
@@ -18057,24 +15840,6 @@ const DelegationVerifiedBySchema = _enum([
|
|
|
18057
15840
|
"checkpoint"
|
|
18058
15841
|
]);
|
|
18059
15842
|
/**
|
|
18060
|
-
* Max length of a registered session anchor (`sid`) accepted on the wire and
|
|
18061
|
-
* enforced again at the customer route. The join partner
|
|
18062
|
-
* `bouncer_sessions.id` is `varchar(100)`; `detections.registered_sid` stays
|
|
18063
|
-
* `text` (converting a live column to `varchar` would take an ACCESS EXCLUSIVE
|
|
18064
|
-
* rewrite of the hottest table), so this constant is the width contract
|
|
18065
|
-
* instead of the column type.
|
|
18066
|
-
*/
|
|
18067
|
-
const REGISTERED_SID_MAX_LENGTH = 100;
|
|
18068
|
-
/**
|
|
18069
|
-
* The one delegation result that may attribute a `sid` to a session timeline.
|
|
18070
|
-
* A rejected presentation carries no engine-emitted sid, and a sid on a
|
|
18071
|
-
* `failed` / `not_presented` report is attacker-shaped, so ingest stamps
|
|
18072
|
-
* `registered_sid` only for this result and nulls it otherwise (D4 / D15).
|
|
18073
|
-
* One member on purpose: Section 13 of the plan records how an explicitly
|
|
18074
|
-
* unverified-labeled `failed` could join it later.
|
|
18075
|
-
*/
|
|
18076
|
-
const SID_ATTRIBUTABLE_RESULT = "verified";
|
|
18077
|
-
/**
|
|
18078
15843
|
* The delegation the agent presented (a reference + outcome, not the proof).
|
|
18079
15844
|
* `result` and `verifiedBy` are required; the JWT claims (`jti` / `iss` / `aud`
|
|
18080
15845
|
* / `capabilities` / `exp`) are optional because `not_presented` carries none.
|