@kya-os/checkpoint-shared 1.5.1 → 1.6.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/CHANGELOG.md +217 -0
- package/dist/beacon-nonce/index.d.mts +36 -0
- package/dist/beacon-nonce/index.d.mts.map +1 -0
- package/dist/beacon-nonce/index.d.ts +36 -0
- package/dist/beacon-nonce/index.d.ts.map +1 -0
- package/dist/beacon-nonce/index.js +305 -0
- package/dist/beacon-nonce/index.mjs +294 -0
- package/dist/beacon-nonce/index.mjs.map +1 -0
- package/dist/beacon-types/index.d.mts +40 -0
- package/dist/beacon-types/index.d.mts.map +1 -1
- package/dist/beacon-types/index.d.ts +40 -0
- package/dist/beacon-types/index.d.ts.map +1 -1
- package/dist/beacon-types/index.js +53 -5
- package/dist/beacon-types/index.mjs +49 -6
- package/dist/beacon-types/index.mjs.map +1 -1
- package/dist/browser-posture-BuChqmH5.d.mts +169 -0
- package/dist/browser-posture-BuChqmH5.d.mts.map +1 -0
- package/dist/browser-posture-DIaVLuW3.d.ts +169 -0
- package/dist/browser-posture-DIaVLuW3.d.ts.map +1 -0
- package/dist/browser-posture-cookie.d.mts +4 -2
- package/dist/browser-posture-cookie.d.mts.map +1 -0
- package/dist/browser-posture-cookie.d.ts +4 -2
- package/dist/browser-posture-cookie.d.ts.map +1 -0
- package/dist/browser-posture-cookie.mjs.map +1 -1
- package/dist/browser-posture-proof.d.mts +18 -0
- package/dist/browser-posture-proof.d.mts.map +1 -0
- package/dist/browser-posture-proof.d.ts +18 -0
- package/dist/browser-posture-proof.d.ts.map +1 -0
- package/dist/browser-posture-proof.js +66 -0
- package/dist/browser-posture-proof.mjs +63 -0
- package/dist/browser-posture-proof.mjs.map +1 -0
- package/dist/browser-posture-report.d.mts +59 -2
- package/dist/browser-posture-report.d.mts.map +1 -1
- package/dist/browser-posture-report.d.ts +59 -2
- package/dist/browser-posture-report.d.ts.map +1 -1
- package/dist/browser-posture-report.js +1 -1
- package/dist/browser-posture-report.mjs +1 -1
- package/dist/browser-posture-report.mjs.map +1 -1
- package/dist/browser-posture.d.mts +2 -85
- package/dist/browser-posture.d.ts +2 -85
- package/dist/browser-posture.js +207 -45
- package/dist/browser-posture.mjs +195 -45
- package/dist/browser-posture.mjs.map +1 -1
- package/dist/browser.d.mts +0 -8
- package/dist/browser.d.mts.map +1 -1
- package/dist/browser.d.ts +0 -8
- package/dist/browser.d.ts.map +1 -1
- package/dist/browser.js +1 -1
- package/dist/browser.mjs +1 -1
- package/dist/browser.mjs.map +1 -1
- package/dist/clearance.d.mts +1 -1
- package/dist/clearance.d.ts +1 -1
- package/dist/clearance.js +2 -2
- package/dist/clearance.mjs +2 -2
- package/dist/{client-ip-HOfe6ucV.mjs → client-ip-B2Xeo-GK.mjs} +2 -2
- package/dist/{client-ip-HOfe6ucV.mjs.map → client-ip-B2Xeo-GK.mjs.map} +1 -1
- package/dist/{client-ip-1y2iXAYW.js → client-ip-CW6pRyLf.js} +1 -1
- package/dist/consent-handoff.d.mts +41 -0
- package/dist/consent-handoff.d.mts.map +1 -0
- package/dist/consent-handoff.d.ts +41 -0
- package/dist/consent-handoff.d.ts.map +1 -0
- package/dist/consent-handoff.js +1 -0
- package/dist/consent-handoff.mjs +2 -0
- package/dist/consent-handoff.mjs.map +1 -0
- package/dist/errors/index.d.mts +155 -0
- package/dist/errors/index.d.mts.map +1 -1
- package/dist/errors/index.d.ts +155 -0
- package/dist/errors/index.d.ts.map +1 -1
- package/dist/errors/index.js +513 -9
- package/dist/errors/index.mjs +513 -10
- package/dist/errors/index.mjs.map +1 -1
- package/dist/{external-jr_S4iSS.d.ts → external-B7WI9FyQ.d.mts} +2 -2
- package/dist/{external-jr_S4iSS.d.mts.map → external-B7WI9FyQ.d.mts.map} +1 -1
- package/dist/{external-jr_S4iSS.d.mts → external-B7WI9FyQ.d.ts} +2 -2
- package/dist/{external-jr_S4iSS.d.ts.map → external-B7WI9FyQ.d.ts.map} +1 -1
- package/dist/gateway-client-ip.d.mts +1 -1
- package/dist/gateway-client-ip.d.ts +1 -1
- package/dist/gateway-client-ip.js +2 -2
- package/dist/gateway-client-ip.mjs +2 -2
- package/dist/index.d.mts +6375 -1532
- package/dist/index.d.mts.map +1 -1
- package/dist/index.d.ts +6375 -1532
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +5629 -697
- package/dist/index.mjs +5341 -683
- package/dist/index.mjs.map +1 -1
- package/dist/mcpi/approval-grant/index.d.mts +1 -1
- package/dist/mcpi/approval-grant/index.d.mts.map +1 -1
- package/dist/mcpi/approval-grant/index.d.ts +1 -1
- package/dist/mcpi/approval-grant/index.d.ts.map +1 -1
- package/dist/mcpi/approval-grant/index.js +58 -49
- package/dist/mcpi/approval-grant/index.mjs +58 -49
- package/dist/mcpi/approval-grant/index.mjs.map +1 -1
- package/dist/mcpi/dashboard-config/index.d.mts +3 -2
- package/dist/mcpi/dashboard-config/index.d.mts.map +1 -1
- package/dist/mcpi/dashboard-config/index.d.ts +3 -2
- package/dist/mcpi/dashboard-config/index.d.ts.map +1 -1
- package/dist/posture-origins/index.d.mts +41 -0
- package/dist/posture-origins/index.d.mts.map +1 -0
- package/dist/posture-origins/index.d.ts +41 -0
- package/dist/posture-origins/index.d.ts.map +1 -0
- package/dist/posture-origins/index.js +441 -0
- package/dist/posture-origins/index.mjs +430 -0
- package/dist/posture-origins/index.mjs.map +1 -0
- package/dist/posture-origins-LFkX80oF.js +627 -0
- package/dist/posture-origins-Pn-ii-Pp.mjs +533 -0
- package/dist/posture-origins-Pn-ii-Pp.mjs.map +1 -0
- package/dist/{project-verification-key-CgSVX9_m.mjs → project-verification-key-66N4edKn.mjs} +2 -2
- package/dist/{project-verification-key-CgSVX9_m.mjs.map → project-verification-key-66N4edKn.mjs.map} +1 -1
- package/dist/{project-verification-key-C3L5rd8a.js → project-verification-key-BccT12tQ.js} +1 -1
- package/dist/rules.json +0 -1
- package/dist/{schemas-DxY-dk9y.mjs → schemas-7qodsG-Z.mjs} +49 -2
- package/dist/schemas-7qodsG-Z.mjs.map +1 -0
- package/dist/{schemas-BmjNLAE7.js → schemas-YhagYDx_.js} +59 -0
- package/dist/signals/index.d.mts +75 -55
- package/dist/signals/index.d.mts.map +1 -1
- package/dist/signals/index.d.ts +75 -55
- package/dist/signals/index.d.ts.map +1 -1
- package/dist/signals/index.js +246 -2
- package/dist/signals/index.mjs +236 -3
- package/dist/signals/index.mjs.map +1 -1
- package/fixtures/browser-integrity/captured-java-0.2.1-missing-score.json +10 -0
- package/fixtures/browser-integrity/null-score.json +11 -0
- package/fixtures/browser-integrity/numeric-score.json +11 -0
- package/fixtures/browser-posture-claims.json +168 -0
- package/fixtures/browser-posture-headers.json +6 -0
- package/fixtures/cli-registration.v2.json +115 -0
- package/fixtures/detection/reason-codes.json +1 -1
- package/fixtures/kya-http/README.md +34 -25
- package/fixtures/kya-http/consent-handoff.codes.json +34 -0
- package/fixtures/kya-http/protected-resource-metadata.full.json +14 -5
- package/fixtures/kya-http/protected-resource-metadata.invalid-issuer.json +51 -0
- package/fixtures/kya-http/protected-resource-metadata.no-issuer.json +32 -0
- package/fixtures/reviewer-grant-revocation.v1.json +285 -0
- package/fixtures/workbench/a2a-signed-request.v1.json +255 -0
- package/fixtures/workbench/artifact-bindings.v1.json +1003 -0
- package/fixtures/workbench/delegation-management.v1.json +507 -0
- package/fixtures/workbench/didcomm-task-source.v1.json +191 -0
- package/fixtures/workbench/graph-interfaces.v1.json +1887 -0
- package/fixtures/workbench/identity-provisioning.v1.json +643 -0
- package/fixtures/workbench/linear-installation.v1.json +484 -0
- package/fixtures/workbench/management-session.v1.json +716 -0
- package/fixtures/workbench/model-credentials.v1.json +630 -0
- package/fixtures/workbench/source-claim-pooled.v1.json +50 -0
- package/fixtures/workbench/task-grant.v1.json +695 -0
- package/fixtures/workbench/task-status-projection.v1.json +591 -0
- package/fixtures/workbench/workload-enrollment.v1.json +580 -0
- package/package.json +24 -5
- package/src/data/compiled/merged-rules.json +2 -9
- package/src/data/default-rules.json +0 -1
- package/dist/browser-posture-cookie-Dmq9Brf_.d.mts +0 -5
- package/dist/browser-posture-cookie-Dmq9Brf_.d.mts.map +0 -1
- package/dist/browser-posture-cookie-Dmq9Brf_.d.ts +0 -5
- package/dist/browser-posture-cookie-Dmq9Brf_.d.ts.map +0 -1
- package/dist/browser-posture.d.mts.map +0 -1
- package/dist/browser-posture.d.ts.map +0 -1
- package/dist/patterns-CkRVOdtV.js +0 -243
- package/dist/patterns-DzkGy_qk.mjs +0 -173
- package/dist/patterns-DzkGy_qk.mjs.map +0 -1
- package/dist/schemas-DxY-dk9y.mjs.map +0 -1
- package/fixtures/kya-http/protected-resource-metadata.global.json +0 -28
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,222 @@
|
|
|
1
1
|
# @kya-os/checkpoint-shared
|
|
2
2
|
|
|
3
|
+
## Unreleased - `CheckpointEvents` moves here; `AGENTSHIELD_WASM_PATH` is removed
|
|
4
|
+
|
|
5
|
+
- **Added:** `CheckpointEvents`, the event-handler map the Checkpoint SDKs accept, moved from `@kya-os/checkpoint`.
|
|
6
|
+
`@kya-os/checkpoint-nextjs` types its `events` option with it, so it no longer depends on `@kya-os/checkpoint`.
|
|
7
|
+
- **Removed:** `DEFAULT_ENV_VARS.AGENTSHIELD_WASM_PATH`, the path to the retired `agentshield_wasm` binary.
|
|
8
|
+
Nothing reads it.
|
|
9
|
+
Shipped under a minor because nothing consumes it yet.
|
|
10
|
+
|
|
11
|
+
RELEASE ORDER: publish this first; the `@kya-os/checkpoint-nextjs` release that drops `@kya-os/checkpoint` needs `CheckpointEvents`.
|
|
12
|
+
|
|
13
|
+
## Unreleased - zero-evidence requests and the `no_evidence` policy category
|
|
14
|
+
|
|
15
|
+
The engine now sends a zero-evidence request as `IncompleteData` with `metadata.detection_basis = "no_evidence"`, and
|
|
16
|
+
composed policies see it as the category `no_evidence`. `withNoEvidenceExclusion(cedar)` is the serve-time rewrite that
|
|
17
|
+
makes such a visitor read as `human` in a deployed rule: in each `forbid` or `permit` statement it replaces every read of
|
|
18
|
+
the category, ignoring text in strings and comments, with
|
|
19
|
+
`(if <read> == "no_evidence" then "human" else <read>)`, where `<read>` is the read as written. A direct read of the
|
|
20
|
+
category is rewritten: `principal.category`, `principal["category"]`, the same with the principal in parentheses
|
|
21
|
+
(`(principal).category`, `((principal))["category"]`), and a bracket key written with escapes
|
|
22
|
+
(`principal["cat\u{65}gory"]`, `\x65` or an underscored `\u{6_5}`), with whitespace or a `//` comment between any of
|
|
23
|
+
the tokens. A statement that reads the category through a computed value holding the principal, such as an `if` or a record that carries
|
|
24
|
+
`principal` (`(if c then principal else principal).category`, `{p: principal}.p.category`), is left as written and sees
|
|
25
|
+
`no_evidence`. A `principal` that is an attribute name or a record key (`context has principal`, `{principal: x}`) is
|
|
26
|
+
never rewritten, so the output is valid Cedar whenever the input is. Apart from those computed reads, a statement is left byte-identical only when it compares the principal's category to the literal
|
|
27
|
+
`"no_evidence"`: with `==` or `!=`, with the literal on either side, through any of those reads; with `like`, only when a
|
|
28
|
+
segment of the pattern, split on `*`, spells the whole name and the pattern can match it (`"no_evidence*"` and `"*no_evidence"`
|
|
29
|
+
do, `"no_*"` and `"*evidence"` do not); as a member of a list passed to `.contains(...)`, `.containsAny(...)` or
|
|
30
|
+
`.containsAll(...)` with the category on the other side, with a trailing comma allowed. A literal written with escapes
|
|
31
|
+
counts. The word `no_evidence` anywhere else in a statement, such as `resource.path != "/no_evidence"` or
|
|
32
|
+
`principal.name == "no_evidence"`, does not exempt it. Text that already carries the rewrite comes back unchanged.
|
|
33
|
+
Whitespace is exactly the 25 characters of Unicode `White_Space` that the Cedar 4.12.0 lexer accepts (U+0009 to U+000D,
|
|
34
|
+
U+0020, U+0085, U+00A0, U+1680, U+2000 to U+200A, U+2028, U+2029, U+202F, U+205F, U+3000), not the JavaScript `\s` class, and a
|
|
35
|
+
`//` comment ends only at a line feed or a carriage return, so a lone `\r` ends one. The dashboard serves the stored policy
|
|
36
|
+
text, so a release that predates the rewrite reads it as before; `@kya-os/checkpoint-wasm-runtime` and the .NET and Java
|
|
37
|
+
SDKs apply it inside the compile, which
|
|
38
|
+
their caches run once per distinct policy text on a miss and not on a hit, so text from a custom fetcher behaves the same
|
|
39
|
+
at no per-request cost. The three implementations scan in linear time and are tested against one shared vector file.
|
|
40
|
+
The inverse, `withoutNoEvidenceExclusion`, is internal to the package and not exported: `requiredScopesForRequest`,
|
|
41
|
+
`approvalQuorumForRequest` and the deny-rule analysis read the `@scopes`, `@approvers` and `@quorum` annotations and the
|
|
42
|
+
rule bodies from the text with the rewrite undone, and memoize that text per source, so a rule means the same whether or
|
|
43
|
+
not it was served rewritten. New exports: `withNoEvidenceExclusion`, `NO_EVIDENCE_CATEGORY` (`no_evidence`),
|
|
44
|
+
`NO_EVIDENCE_EXCLUSION_TERM` (`principal.category != "no_evidence"`) and `NO_EVIDENCE_EQUALITY_TERM`
|
|
45
|
+
(`principal.category == "no_evidence"`).
|
|
46
|
+
|
|
47
|
+
The deny-rule checks now parse each Cedar condition and evaluate each statement for a `human` and a `no_evidence` visitor
|
|
48
|
+
instead of scanning the text, and ignore text inside strings and comments: `isUnnarrowedDenyBlock`,
|
|
49
|
+
`pathHasUnnarrowedDenyRule` and `lintUnnarrowedDenyRules` can report different results for the same policy, and the lint
|
|
50
|
+
messages now mention `no_evidence` visitors. A statement the rewrite changes is evaluated with a `no_evidence` visitor
|
|
51
|
+
read as `human`, and one it leaves alone is evaluated literally, so the analysis matches what is served. A
|
|
52
|
+
comparison, set call or `like` that mentions the class being probed is evaluated with the category read as a value
|
|
53
|
+
that names no class, so it decides the rule only through the rest of the condition; a `like` mentions a class only
|
|
54
|
+
when a segment of its pattern spells the whole name and the pattern matches it; and `if ... then ... else` is
|
|
55
|
+
evaluated three-valued. A rule that reads `getTag` is undecided, because Cedar fails closed when the tag is absent;
|
|
56
|
+
escaped entity ids in a rule's principal scope are decoded; the unnamed-category placeholder is a lone surrogate, which
|
|
57
|
+
no Cedar string literal can hold; and a lint finding names the visitors a rule reaches (humans, zero-evidence visitors,
|
|
58
|
+
or both). A condition the
|
|
59
|
+
parser cannot read, or one nested or chained more than 48 deep, is treated as undecidable and counts as reaching the
|
|
60
|
+
visitor; a set that holds a set is read as unknown. Set membership, `containsAny`, `containsAll` and set equality run in
|
|
61
|
+
linear time, and a lint finding's line number is found in one pass over the text. A `forbid` statement that carries
|
|
62
|
+
`@verdict("ALLOW")` counts as a deny like any other, a `containsAny` between the category and a list is read like
|
|
63
|
+
`.contains`, and an annotation named `forbid` or `permit` never starts a statement. New exports:
|
|
64
|
+
`analyzePolicySource(cedar)`, which parses the policy once and returns a `PolicyHazardAnalysis` (also exported) whose
|
|
65
|
+
`unnarrowedDenyFor(path, probe)`, `explicitDenyFor(path, probe)`, `humanHazard(path)`, `noEvidenceHazard(path)` and
|
|
66
|
+
`noEvidenceNamed(path)` (a rule names `no_evidence` on the path) answer
|
|
67
|
+
per path without parsing again; `pathHasUnnarrowedDenyRuleFor(cedar, path, probe)` and
|
|
68
|
+
`pathHasExplicitDenyRuleFor(cedar, path, probe)` (`probe` is the new `ProbeClass`, `human` or `no_evidence`), which
|
|
69
|
+
parse on every call; `lintMissingBaselinePermit` (warns when a policy has no baseline permit, so unmatched visitors are
|
|
70
|
+
denied), `parseCedarStatements`, `statementApplies(statement, facts)` and `statementId`; and `ByteBoundedMemo`, a map that
|
|
71
|
+
evicts its oldest entries to stay under a byte budget and does not keep a value larger than the budget, which the gateway
|
|
72
|
+
worker uses to memoize one analysis per policy hash. A `like` pattern is now matched segment by segment, split on `*`, with `\*` read as a literal
|
|
73
|
+
star, instead of by a regular expression built from the policy text, and `pathLiteralMatches` splits a path literal on `*`
|
|
74
|
+
and matches the segments the same way, with the same results.
|
|
75
|
+
|
|
76
|
+
`AdminOrganizationSessionAnalytics.comparison` gains the optional `incompleteDataSessions`, the `incomplete_data`
|
|
77
|
+
sessions that complete the split beside AI agent, bot and human. A client that constructs the type does not have to set
|
|
78
|
+
it, and one that ignores unknown fields is unaffected. The optional `incompleteDataPercentage` joins the admin session
|
|
79
|
+
comparison (`SessionComparison`) the same way; `DashboardStatsResponse` gains an optional
|
|
80
|
+
`sessionBreakdown { botSessions, humanSessions, incompleteDataSessions }`, and `AnalyticsOverview` gains
|
|
81
|
+
`uniqueIncompleteDataSessions`. `ShopifyStatsResponseSchema` gains the optional `unidentifiedSessions`: sessions with no
|
|
82
|
+
AI agent, bot or human detection and at least one incomplete-data detection carrying the `no_evidence` basis. Those
|
|
83
|
+
visitors were counted as human before, including a visit that also sent a request with suspicious headers, so they are
|
|
84
|
+
counted in `totalRequests` and `humanSessions`; sessions whose incomplete data all comes from other reasons, such as
|
|
85
|
+
suspicious headers, are in no counter.
|
|
86
|
+
|
|
87
|
+
### Security
|
|
88
|
+
|
|
89
|
+
`verifySignedApprovalQuorum` now checks a grant's `approverDid` against `quorum.approvers` before it resolves the
|
|
90
|
+
approver's key. Before, it resolved the request-supplied DID first and checked the allowlist after, so a did:web
|
|
91
|
+
`approverDid` made the host fetch a URL the caller chose. A grant from an approver outside the list is dropped as
|
|
92
|
+
before and the result is unchanged (`quorum_not_met:k/n`); it just never reaches the `ApproverKeyResolver`.
|
|
93
|
+
`verifyApprovalGrant` on its own still resolves whatever DID it is given, so a caller with an allowlist must check it
|
|
94
|
+
first.
|
|
95
|
+
|
|
96
|
+
## 1.5.2
|
|
97
|
+
|
|
98
|
+
### Changed
|
|
99
|
+
|
|
100
|
+
`requestPresentedCredential(headers)` identifies KYA signatures, delegation-proof headers, and structurally recognized VC-JWTs. Opaque bearer tokens and unrelated JWTs do not count as delegation credentials. The helper only selects when callers resolve configured trusted roots; the engine verifies credential claims and trust chains.
|
|
101
|
+
|
|
102
|
+
### Changed
|
|
103
|
+
|
|
104
|
+
- `PolicyFetcher` can expose fast origin failures as `POLICY_UNAVAILABLE` with
|
|
105
|
+
`throwOnUnavailable`; its default continues to return `DEFAULT_POLICY` on
|
|
106
|
+
ordinary fetch errors.
|
|
107
|
+
|
|
108
|
+
`BrowserPostureSchema` gains an optional `detection` claim (`class` `ai_agent` or `bot`, `name` of 1 to 64 characters with no control characters, integer `confidence` 0 to 100); a malformed claim makes the token `invalid-claims`. `postureUpgrade(posture)` returns the reader upgrade with first-match precedence: `detection`, `automation_disclosed`, an `agent-driven` verdict, then `automation_corroborated`. `KNOWN_AGENT_PATTERNS` adds `meta-muse` (`Meta Muse`).
|
|
109
|
+
|
|
110
|
+
`computeSessionFingerprintHash` keeps its published behavior and nothing in this
|
|
111
|
+
repo calls it any more; use `computeDeviceFingerprint`. The new
|
|
112
|
+
function hashes only the client attributes `CLIENT_ATTRIBUTE_CLASSIFICATION`
|
|
113
|
+
marks `include` (stable device properties every browser lane emits, and the
|
|
114
|
+
persistent `device.id`; never counters, timings, probe verdicts or lazy-chunk
|
|
115
|
+
attributes), folds synonymous names such as `platform.timezone` onto
|
|
116
|
+
`browser.timezone` first, and returns a different digest for the same
|
|
117
|
+
attributes, so a stored old digest never equals a new one. New exports:
|
|
118
|
+
`CLIENT_ATTRIBUTE_CLASSIFICATION`, `isChurningClientAttribute`,
|
|
119
|
+
`isStatsRecordableClientAttribute`,
|
|
120
|
+
`deviceFingerprintComponents`, `canonicalizeClientAttributes`,
|
|
121
|
+
`DEVICE_FINGERPRINT_VERSION` and `DEVICE_FINGERPRINT_PREFIX` (`fp2:`, the prefix
|
|
122
|
+
a caller puts on the stored, salted value so a later definition can be told
|
|
123
|
+
apart from this one).
|
|
124
|
+
|
|
125
|
+
`ManagementErrorSchema`'s `error` gains an optional `reason`, and `ManagementErrorReasonSchema` lists its value `management_issuer_unconfigured`. A deployment without `NEXT_PUBLIC_APP_URL` set to its https origin still answers management sign-in with `503` and `error.code: temporarily_unavailable`; the body now also carries `error.reason`. A client that ignores unknown fields is unaffected.
|
|
126
|
+
|
|
127
|
+
`ManagementPostureSchema` no longer models browser posture as something a project turns on. Every project has a posture key, so `enabled` is the constant `true` (kept on the wire so a CLI that still requires the field keeps parsing) and `keyId` and `publicJwk` are no longer nullable. A body with `enabled: false` or a null key is now refused.
|
|
128
|
+
|
|
129
|
+
`BrowserPostureConfig.origins` lists further allowed page origins beside the
|
|
130
|
+
required `origin`. A posture token is accepted only when its `origin` claim
|
|
131
|
+
matches `origin` or an `origins` entry (exact, or a leftmost wildcard that
|
|
132
|
+
never matches the apex, same rules as `posture-origins`) and its `aud`
|
|
133
|
+
contains that claim. `validateBrowserPostureConfig` rejects an invalid entry
|
|
134
|
+
or more than 20. A config without `origins` behaves as before.
|
|
135
|
+
|
|
136
|
+
`postureOutcomeFromRequest` and `inspectBrowserPosture` report why a token was
|
|
137
|
+
refused (`BROWSER_POSTURE_REJECTION_REASONS`) instead of only returning
|
|
138
|
+
nothing, and `BrowserPostureOutcomeSchema` is the wire shape of
|
|
139
|
+
`postureOutcome` on a detection report. `verifyBrowserPosture` and
|
|
140
|
+
`postureFromRequest` are unchanged. Every token part must now be base64url.
|
|
141
|
+
|
|
142
|
+
`BrowserPostureReportIngestSchema`, exported from `@kya-os/checkpoint-shared/browser-posture`, is `BrowserPostureReportSchema` with an omitted `score` read as `null`. The dashboard's log-detection boundary uses it so a reporter that drops a null score (the Java and .NET SDKs did) is no longer refused with `400 invalid_union`; the stored shape is unchanged because the parsed value carries `score: null`. `BrowserPostureReportSchema` itself still requires the key.
|
|
143
|
+
|
|
144
|
+
`AgentShieldConfigSchema` now rejects `allowedIps`, `blockedIps`,
|
|
145
|
+
`allowedAgents`, `blockedAgents`, `customRules`, `customPatterns` and every
|
|
146
|
+
`network` setting (`enabled`, `checkCloudProviders`, `checkDataCenters`,
|
|
147
|
+
`checkVpn`, `checkProxy`, `customIpRanges`) with an error naming the setting,
|
|
148
|
+
and the fields are typed `?: undefined`. The schema accepted them but no
|
|
149
|
+
runtime ever read them, so a caller who set an allow/block list or a network
|
|
150
|
+
check was unprotected. Any defined value is rejected, `false` and `[]`
|
|
151
|
+
included, so a parsed config that carried the old `network` defaults can no
|
|
152
|
+
longer be fed back through the schema; the parsed `network` object is now
|
|
153
|
+
empty. The same applies to `ExpressMiddlewareOptionsSchema`,
|
|
154
|
+
`NextMiddlewareOptionsSchema` and `validateConfig` in `@kya-os/checkpoint`.
|
|
155
|
+
|
|
156
|
+
`RuleLoader.loadRules({ cdnUrl })` now throws instead of fetching. It accepted
|
|
157
|
+
any schema-valid document from the URL with no signature check, and its
|
|
158
|
+
default endpoints pointed at retired domains. Remote delivery of vendor IP
|
|
159
|
+
ranges and key expiry is a signed rule bundle verified inside the engine
|
|
160
|
+
(`@kya-os/checkpoint-wasm-runtime`'s `createRuleBundleUpdater`). Removed the
|
|
161
|
+
`RULE_CDN` and `RULE_CACHE` constants and the `RULE_ERRORS.CDN_UNAVAILABLE` /
|
|
162
|
+
`CACHE_EXPIRED` messages; `cdnUrl` stays on `RuleLoadOptions` as
|
|
163
|
+
`@deprecated`.
|
|
164
|
+
|
|
165
|
+
Additive. `./browser-posture` gains `postureFromRequest`,
|
|
166
|
+
`postureRequestFromHeaders`, `POSTURE_HEADER` (`kya-posture`) and
|
|
167
|
+
`POSTURE_SESSION_HEADER` (`kya-posture-session`): posture read from the
|
|
168
|
+
`KYA-Posture` and `KYA-Posture-Session` request headers, each winning over its
|
|
169
|
+
cookie, for a page on another host or one that blocks cookies. A header sent
|
|
170
|
+
twice, or comma-joined, is trusted by no one. `postureFromCookies` is
|
|
171
|
+
unchanged.
|
|
172
|
+
|
|
173
|
+
Additive. `./beacon-types` gains `BeaconReceipt` and two `BeaconConfig`
|
|
174
|
+
options, `browserSessionId` and `onReceipt`, both kept by
|
|
175
|
+
`parseBeaconConfig` (an invalid value warns and is dropped). Consumed by
|
|
176
|
+
`@kya-os/checkpoint-beacon`'s receipt hook and session resume.
|
|
177
|
+
|
|
178
|
+
`TrafficTimeSeriesPoint.uniqueIPs` is now `number | null`. It is `null` for a
|
|
179
|
+
bucket served from `analytics_daily_rollup`, which records no client IPs; the
|
|
180
|
+
admin traffic-patterns route previously reported those buckets as `0`.
|
|
181
|
+
|
|
182
|
+
`TrafficTopPage.bounceRate` is removed. No code path computed it, and the
|
|
183
|
+
route set it to `0` on every page.
|
|
184
|
+
|
|
185
|
+
Additive. Extends the `ERROR_CODES` registry with every code the v1
|
|
186
|
+
projects, deploy, shopify and pixel/track routes emit that was still
|
|
187
|
+
route-local: `ANALYTICS_ERRORS` and `DEPLOY_ERRORS` are new groups, and
|
|
188
|
+
`RATE_LIMIT_ERRORS`, `PERMISSION_ERRORS`, `INTERNAL_ERRORS`, `PIXEL_ERRORS`
|
|
189
|
+
and `BARE_ERRORS` gained new codes. No wire string changed. The four
|
|
190
|
+
service-computed deploy codes (`DEPLOY_FAILED`, `WFP_NOT_CONFIGURED`,
|
|
191
|
+
`NATIVE_ISSUER_PROVISIONING_BUSY`, `NATIVE_ISSUER_PROVISIONING_FAILED`)
|
|
192
|
+
carry no fixed status, like `PROJECT_NOT_FOUND`.
|
|
193
|
+
|
|
194
|
+
Additive. Extends the `ERROR_CODES` registry with every code the v1 bouncer,
|
|
195
|
+
delegation OAuth, native HTTP and audit ingest routes emit that was still
|
|
196
|
+
route-local, as six new groups: `BOUNCER_LOWERCASE_ERRORS`,
|
|
197
|
+
`OAUTH_LOWERCASE_ERRORS`, `BOUNCER_UPPERCASE_ERRORS`, `AUDIT_ERRORS`,
|
|
198
|
+
`AUDIT_PROTOCOL_ERRORS` (the `@kya-os/mcp` audit vocabulary, hand-copied
|
|
199
|
+
because this package does not depend on it) and `KYAOS_PROTOCOL_ERRORS`
|
|
200
|
+
(the `kyaos/*` strings, keyed `KYAOS_SLASH_*`). No wire string changed.
|
|
201
|
+
`invalid_grant` and `kyaos/profile-violation` carry no fixed status because
|
|
202
|
+
their emitters disagree. `INVALID_REQUEST_BODY` (400),
|
|
203
|
+
`MCPI_CONFIG_NOT_FOUND` (404) and `CONSENT_CONFIG_NOT_FOUND` (404) are pinned,
|
|
204
|
+
which lets `v1ErrorResponse` resolve the three `new Error('<code>')` sites in
|
|
205
|
+
the bouncer config validate and consent-config routes to their intended
|
|
206
|
+
status instead of a 500 `INTERNAL_SERVER_ERROR`.
|
|
207
|
+
|
|
208
|
+
Handoff and session changes. New exports: `issueHandoffToken`, `handoffTokenAuthentic` and
|
|
209
|
+
`HANDOFF_TOKEN_PATTERN` from `@kya-os/checkpoint-shared/beacon-nonce` (a handoff token is 16 random
|
|
210
|
+
bytes plus a 16 byte HMAC tag under the nonce secret, 43 base64url characters, and one canonical
|
|
211
|
+
spelling), and `SESSION_IDLE_GAP_MAX_MS` from `beacon-types` (six hours). `sessionTimeout` no
|
|
212
|
+
longer defaults to 30 minutes: `parseBeaconConfig` (in `beacon-types` and in `browser.ts`),
|
|
213
|
+
`DEFAULT_CONFIG` and `PixelInstallConfigSchema` leave it unset, so the idle gap is one hour on
|
|
214
|
+
phones and six hours elsewhere, and `PixelInstallConfigSchema.sessionTimeout` is optional. Added
|
|
215
|
+
fields: `deviceId` and `handoffToken` on the beacon batch types, `handoffToken` (at most 2,048
|
|
216
|
+
characters, dropped when invalid) on the pixel request schema, `handoff` (`status` is `adopted`,
|
|
217
|
+
`rejected` or `unavailable`) on the pixel response schema, and `requireConsent` on the beacon
|
|
218
|
+
config.
|
|
219
|
+
|
|
3
220
|
## 1.5.1
|
|
4
221
|
|
|
5
222
|
Adds `POSTURE_TTL_SECONDS` and `BEACON_MAX_EVENTS_PER_BATCH` to `./beacon-types`,
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
//#region src/beacon-nonce/index.d.ts
|
|
2
|
+
export declare const HANDOFF_TOKEN_PATTERN: RegExp;
|
|
3
|
+
export declare const BEACON_NONCE_TTL_SECONDS: number;
|
|
4
|
+
export declare const BEACON_NONCE_CLOCK_SKEW_SECONDS = 60;
|
|
5
|
+
export declare const BEACON_NONCE_MAX_LENGTH = 64;
|
|
6
|
+
export type BeaconNonceVerdict = 'verified' | 'forged' | 'unverified';
|
|
7
|
+
export type BeaconNonceVerification = {
|
|
8
|
+
verdict: 'verified';
|
|
9
|
+
} | {
|
|
10
|
+
verdict: 'forged';
|
|
11
|
+
reason: 'signature';
|
|
12
|
+
} | {
|
|
13
|
+
verdict: 'unverified';
|
|
14
|
+
reason: 'malformed' | 'expired' | 'future' | 'no_secret' | 'context';
|
|
15
|
+
};
|
|
16
|
+
export interface BeaconNonceBinding {
|
|
17
|
+
projectId: string;
|
|
18
|
+
sessionId: string;
|
|
19
|
+
context: string;
|
|
20
|
+
}
|
|
21
|
+
export declare function beaconNonceContext(client: {
|
|
22
|
+
ip?: string;
|
|
23
|
+
userAgent?: string;
|
|
24
|
+
}): string;
|
|
25
|
+
export declare function isSignedBeaconNonce(nonce: string | undefined): nonce is string;
|
|
26
|
+
export declare function issueSignedBeaconNonce(secret: string, binding: BeaconNonceBinding, issuedAtMs: number): Promise<string>;
|
|
27
|
+
export declare function verifySignedBeaconNonce(secret: string | undefined, binding: BeaconNonceBinding, nonce: string | undefined, nowMs: number): Promise<BeaconNonceVerification>;
|
|
28
|
+
export declare function issueHandoffToken(secret: string, projectId: string): Promise<string>;
|
|
29
|
+
export declare const HANDOFF_USER_HASH_PATTERN: RegExp;
|
|
30
|
+
export declare function splitHandoffToken(raw: string): {
|
|
31
|
+
token: string;
|
|
32
|
+
userHash?: string;
|
|
33
|
+
};
|
|
34
|
+
export declare function handoffTokenAuthentic(secrets: readonly string[], projectId: string, token: unknown): Promise<boolean>;
|
|
35
|
+
//#endregion
|
|
36
|
+
//# sourceMappingURL=index.d.mts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.mts","names":[],"sources":["../../src/beacon-nonce/index.ts"],"mappings":";qBA4Da,uBAAqB;qBAGrB;qBAEA;qBAEA;YAED;YAEA;EACN;;EACA;EAAmB;;EAEnB;EACA;;iBAGW;EACf;EACA;EAEA;;wBA2Cc,mBAAmB;EAAU;EAAa;;wBAkG1C,oBAAoB,4BAA4B;wBAS1C,uBACpB,gBACA,SAAS,oBACT,qBACC;wBAkBmB,wBACpB,4BACA,SAAS,oBACT,2BACA,gBACC,QAAQ;wBA6DW,kBAAkB,gBAAgB,oBAAoB;qBAS/D,2BAAyB;wBAGtB,kBAAkB;EAAgB;EAAe;;wBAS3C,sBACpB,4BACA,mBACA,iBACC"}
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
//#region src/beacon-nonce/index.d.ts
|
|
2
|
+
export declare const HANDOFF_TOKEN_PATTERN: RegExp;
|
|
3
|
+
export declare const BEACON_NONCE_TTL_SECONDS: number;
|
|
4
|
+
export declare const BEACON_NONCE_CLOCK_SKEW_SECONDS = 60;
|
|
5
|
+
export declare const BEACON_NONCE_MAX_LENGTH = 64;
|
|
6
|
+
export type BeaconNonceVerdict = 'verified' | 'forged' | 'unverified';
|
|
7
|
+
export type BeaconNonceVerification = {
|
|
8
|
+
verdict: 'verified';
|
|
9
|
+
} | {
|
|
10
|
+
verdict: 'forged';
|
|
11
|
+
reason: 'signature';
|
|
12
|
+
} | {
|
|
13
|
+
verdict: 'unverified';
|
|
14
|
+
reason: 'malformed' | 'expired' | 'future' | 'no_secret' | 'context';
|
|
15
|
+
};
|
|
16
|
+
export interface BeaconNonceBinding {
|
|
17
|
+
projectId: string;
|
|
18
|
+
sessionId: string;
|
|
19
|
+
context: string;
|
|
20
|
+
}
|
|
21
|
+
export declare function beaconNonceContext(client: {
|
|
22
|
+
ip?: string;
|
|
23
|
+
userAgent?: string;
|
|
24
|
+
}): string;
|
|
25
|
+
export declare function isSignedBeaconNonce(nonce: string | undefined): nonce is string;
|
|
26
|
+
export declare function issueSignedBeaconNonce(secret: string, binding: BeaconNonceBinding, issuedAtMs: number): Promise<string>;
|
|
27
|
+
export declare function verifySignedBeaconNonce(secret: string | undefined, binding: BeaconNonceBinding, nonce: string | undefined, nowMs: number): Promise<BeaconNonceVerification>;
|
|
28
|
+
export declare function issueHandoffToken(secret: string, projectId: string): Promise<string>;
|
|
29
|
+
export declare const HANDOFF_USER_HASH_PATTERN: RegExp;
|
|
30
|
+
export declare function splitHandoffToken(raw: string): {
|
|
31
|
+
token: string;
|
|
32
|
+
userHash?: string;
|
|
33
|
+
};
|
|
34
|
+
export declare function handoffTokenAuthentic(secrets: readonly string[], projectId: string, token: unknown): Promise<boolean>;
|
|
35
|
+
//#endregion
|
|
36
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","names":[],"sources":["../../src/beacon-nonce/index.ts"],"mappings":";qBA4Da,uBAAqB;qBAGrB;qBAEA;qBAEA;YAED;YAEA;EACN;;EACA;EAAmB;;EAEnB;EACA;;iBAGW;EACf;EACA;EAEA;;wBA2Cc,mBAAmB;EAAU;EAAa;;wBAkG1C,oBAAoB,4BAA4B;wBAS1C,uBACpB,gBACA,SAAS,oBACT,qBACC;wBAkBmB,wBACpB,4BACA,SAAS,oBACT,2BACA,gBACC,QAAQ;wBA6DW,kBAAkB,gBAAgB,oBAAoB;qBAS/D,2BAAyB;wBAGtB,kBAAkB;EAAgB;EAAe;;wBAS3C,sBACpB,4BACA,mBACA,iBACC"}
|
|
@@ -0,0 +1,305 @@
|
|
|
1
|
+
Object.defineProperty(exports, Symbol.toStringTag, { value: 'Module' });
|
|
2
|
+
//#region src/beacon-nonce/index.ts
|
|
3
|
+
/**
|
|
4
|
+
* Stateless, client-bound beacon nonce, issued and verified by both the
|
|
5
|
+
* origin (`apps/web/lib/services/nonce.service.ts`) and the beacon-ingest
|
|
6
|
+
* edge Worker.
|
|
7
|
+
*
|
|
8
|
+
* Every pixel/beacon response hands the browser a per-session nonce that its
|
|
9
|
+
* next post must echo. A queue-only edge returns its receipt before the
|
|
10
|
+
* origin has seen the batch, so the nonce cannot depend on origin state:
|
|
11
|
+
* it is an HMAC-SHA256 under a secret shared by origin and edge. The origin
|
|
12
|
+
* verifies it at synchronous ingest, or on replay using the edge's
|
|
13
|
+
* acceptance time as the clock.
|
|
14
|
+
*
|
|
15
|
+
* Web Crypto only (`crypto.subtle`, `crypto.getRandomValues`): this runs
|
|
16
|
+
* unchanged in Cloudflare Workers, Node ≥ 20 and the browser bundle.
|
|
17
|
+
*
|
|
18
|
+
* Wire format (56 chars, inside the schema's 64-char cap):
|
|
19
|
+
*
|
|
20
|
+
* n2.<issuedAt base36 seconds>.<random 8 bytes b64url>.<HMAC 16 bytes b64url>.<ctx tag 8 bytes b64url>
|
|
21
|
+
*
|
|
22
|
+
* The first HMAC binds the format version + project + session + issue time +
|
|
23
|
+
* random. The trailing context tag additionally binds the requester's
|
|
24
|
+
* network prefix and User-Agent (`beaconNonceContext`), so a nonce lifted
|
|
25
|
+
* from one client does not verify from another. The version is inside the
|
|
26
|
+
* MAC, so a nonce cannot be relabelled to dodge the context tag.
|
|
27
|
+
*
|
|
28
|
+
* Verdict semantics — three states, never two:
|
|
29
|
+
* - `verified`: signature matches THIS project+session, the context matches,
|
|
30
|
+
* and it is within TTL.
|
|
31
|
+
* - `forged`: well-formed but the MAC does not match this session/secret.
|
|
32
|
+
* The only outcome that counts as evidence against the client.
|
|
33
|
+
* - `unverified`: nothing could be proven — not signed-format (absent, or
|
|
34
|
+
* a value from before signing existed), expired, from the future, this
|
|
35
|
+
* side has no secret, or the session signature is genuine but the
|
|
36
|
+
* requester's network/User-Agent differs from the one it was issued to (a
|
|
37
|
+
* roaming phone and a replay from elsewhere look the same, so neither is
|
|
38
|
+
* treated as fabrication). Staleness is not forgery: an edge that stopped
|
|
39
|
+
* issuing (secret unset) leaves clients echoing old values, and that must
|
|
40
|
+
* degrade to "unknown", never to "failed".
|
|
41
|
+
*
|
|
42
|
+
* Any unexpired signature for the session verifies, so a nonce is not
|
|
43
|
+
* single-use within its TTL. Multi-tab sessions need no window at all.
|
|
44
|
+
*/
|
|
45
|
+
const NONCE_VERSION = "n2";
|
|
46
|
+
const MAC_INPUT_PREFIX = `checkpoint-beacon-nonce:${NONCE_VERSION}`;
|
|
47
|
+
const CONTEXT_INPUT_PREFIX = `checkpoint-beacon-nonce:ctx:${NONCE_VERSION}`;
|
|
48
|
+
const RANDOM_BYTES = 8;
|
|
49
|
+
const MAC_BYTES = 16;
|
|
50
|
+
const CONTEXT_TAG_BYTES = 8;
|
|
51
|
+
const MAX_CONTEXT_USER_AGENT_LENGTH = 512;
|
|
52
|
+
const IPV4_PATTERN = /^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/;
|
|
53
|
+
const IPV6_GROUP_PATTERN = /^[0-9a-f]{1,4}$/;
|
|
54
|
+
const ISSUED_AT_PATTERN = /^[0-9a-z]{1,16}$/;
|
|
55
|
+
const BASE64URL_PATTERN = /^[A-Za-z0-9_-]+$/;
|
|
56
|
+
const HANDOFF_TOKEN_INPUT_PREFIX = "checkpoint-handoff-token:v1";
|
|
57
|
+
const HANDOFF_ID_BYTES = 16;
|
|
58
|
+
const HANDOFF_TAG_BYTES = 16;
|
|
59
|
+
const HANDOFF_TOKEN_PATTERN = /^[A-Za-z0-9_-]{43}$/;
|
|
60
|
+
/** How long an issued nonce stays verifiable. */
|
|
61
|
+
const BEACON_NONCE_TTL_SECONDS = 600;
|
|
62
|
+
/** Edge and origin clocks may disagree; a nonce this far "in the future" still verifies. */
|
|
63
|
+
const BEACON_NONCE_CLOCK_SKEW_SECONDS = 60;
|
|
64
|
+
/** The beacon wire schema's `nonce: z.string().max(64)`. */
|
|
65
|
+
const BEACON_NONCE_MAX_LENGTH = 64;
|
|
66
|
+
function ipv4Prefix(ip) {
|
|
67
|
+
const match = IPV4_PATTERN.exec(ip);
|
|
68
|
+
return match ? `${match[1]}.${match[2]}.${match[3]}` : null;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* The first three groups (a /48) of an IPv6 address, expanded so compressed
|
|
72
|
+
* forms agree with their spelled-out equivalents. An IPv4-mapped address
|
|
73
|
+
* (`::ffff:a.b.c.d` or its hex spelling) is a v4 client and keys on its /24.
|
|
74
|
+
* `null` for anything that is not a well-formed address.
|
|
75
|
+
*/
|
|
76
|
+
function ipv6Prefix(ip) {
|
|
77
|
+
const bare = ip.toLowerCase().split("%")[0];
|
|
78
|
+
const lastColon = bare.lastIndexOf(":");
|
|
79
|
+
const embedded = IPV4_PATTERN.exec(bare.slice(lastColon + 1));
|
|
80
|
+
const halves = (embedded ? `${bare.slice(0, lastColon + 1)}${(Number(embedded[1]) << 8 | Number(embedded[2])).toString(16)}:${(Number(embedded[3]) << 8 | Number(embedded[4])).toString(16)}` : bare).split("::");
|
|
81
|
+
if (halves.length > 2) return null;
|
|
82
|
+
const head = halves[0] ? halves[0].split(":") : [];
|
|
83
|
+
const tail = halves.length === 2 && halves[1] ? halves[1].split(":") : [];
|
|
84
|
+
const missing = 8 - head.length - tail.length;
|
|
85
|
+
if (halves.length === 1 ? missing !== 0 : missing < 1) return null;
|
|
86
|
+
const groups = [
|
|
87
|
+
...head,
|
|
88
|
+
...Array(halves.length === 2 ? missing : 0).fill("0"),
|
|
89
|
+
...tail
|
|
90
|
+
];
|
|
91
|
+
if (!groups.every((group) => IPV6_GROUP_PATTERN.test(group))) return null;
|
|
92
|
+
const words = groups.map((group) => parseInt(group, 16));
|
|
93
|
+
if (words.slice(0, 5).every((word) => word === 0) && words[5] === 65535) return `${words[6] >> 8}.${words[6] & 255}.${words[7] >> 8}`;
|
|
94
|
+
return words.slice(0, 3).map((word) => word.toString(16)).join(":");
|
|
95
|
+
}
|
|
96
|
+
/**
|
|
97
|
+
* The requester facts a nonce is bound to: the network prefix (IPv4 /24,
|
|
98
|
+
* IPv6 /48, so NAT and DHCP churn inside one access network still verify)
|
|
99
|
+
* and the User-Agent. Empty when neither is known, which binds nothing.
|
|
100
|
+
*/
|
|
101
|
+
function beaconNonceContext(client) {
|
|
102
|
+
const ip = client.ip?.trim() ?? "";
|
|
103
|
+
const prefix = ipv4Prefix(ip) ?? (ip.includes(":") ? ipv6Prefix(ip) : null) ?? "";
|
|
104
|
+
const userAgent = (client.userAgent ?? "").slice(0, MAX_CONTEXT_USER_AGENT_LENGTH);
|
|
105
|
+
return prefix || userAgent ? `${prefix}|${userAgent}` : "";
|
|
106
|
+
}
|
|
107
|
+
const encoder = new TextEncoder();
|
|
108
|
+
const keyCache = /* @__PURE__ */ new Map();
|
|
109
|
+
function hmacKey(secret) {
|
|
110
|
+
let key = keyCache.get(secret);
|
|
111
|
+
if (!key) {
|
|
112
|
+
key = crypto.subtle.importKey("raw", encoder.encode(secret), {
|
|
113
|
+
name: "HMAC",
|
|
114
|
+
hash: "SHA-256"
|
|
115
|
+
}, false, ["sign"]);
|
|
116
|
+
keyCache.set(secret, key);
|
|
117
|
+
}
|
|
118
|
+
return key;
|
|
119
|
+
}
|
|
120
|
+
function base64url(bytes) {
|
|
121
|
+
let binary = "";
|
|
122
|
+
for (const byte of bytes) binary += String.fromCharCode(byte);
|
|
123
|
+
return btoa(binary).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
|
|
124
|
+
}
|
|
125
|
+
/**
|
|
126
|
+
* Length-prefixed canonical encoding (`<byteLength>:<field>`), never a bare
|
|
127
|
+
* delimiter join: `sessionId` is caller-controlled at the edge, so a value
|
|
128
|
+
* that embeds the delimiter must not be able to shift the field boundaries
|
|
129
|
+
* and re-bind the MAC to another session (Cursor Bugbot, PR #5255).
|
|
130
|
+
*/
|
|
131
|
+
function canonical(fields) {
|
|
132
|
+
const chunks = fields.map((field) => {
|
|
133
|
+
const bytes = encoder.encode(field);
|
|
134
|
+
return [encoder.encode(`${bytes.length}:`), bytes];
|
|
135
|
+
});
|
|
136
|
+
const total = chunks.reduce((sum, [len, bytes]) => sum + len.length + bytes.length, 0);
|
|
137
|
+
const out = new Uint8Array(new ArrayBuffer(total));
|
|
138
|
+
let offset = 0;
|
|
139
|
+
for (const [len, bytes] of chunks) {
|
|
140
|
+
out.set(len, offset);
|
|
141
|
+
offset += len.length;
|
|
142
|
+
out.set(bytes, offset);
|
|
143
|
+
offset += bytes.length;
|
|
144
|
+
}
|
|
145
|
+
return out;
|
|
146
|
+
}
|
|
147
|
+
async function mac(secret, binding, issuedAt, random) {
|
|
148
|
+
const input = canonical([
|
|
149
|
+
MAC_INPUT_PREFIX,
|
|
150
|
+
binding.projectId,
|
|
151
|
+
binding.sessionId,
|
|
152
|
+
issuedAt,
|
|
153
|
+
random
|
|
154
|
+
]);
|
|
155
|
+
const signature = await crypto.subtle.sign("HMAC", await hmacKey(secret), input);
|
|
156
|
+
return base64url(new Uint8Array(signature, 0, MAC_BYTES));
|
|
157
|
+
}
|
|
158
|
+
async function contextTag(secret, binding, issuedAt, random) {
|
|
159
|
+
const input = canonical([
|
|
160
|
+
CONTEXT_INPUT_PREFIX,
|
|
161
|
+
binding.projectId,
|
|
162
|
+
binding.sessionId,
|
|
163
|
+
issuedAt,
|
|
164
|
+
random,
|
|
165
|
+
binding.context
|
|
166
|
+
]);
|
|
167
|
+
const signature = await crypto.subtle.sign("HMAC", await hmacKey(secret), input);
|
|
168
|
+
return base64url(new Uint8Array(signature, 0, CONTEXT_TAG_BYTES));
|
|
169
|
+
}
|
|
170
|
+
function constantTimeEqual(left, right) {
|
|
171
|
+
if (left.length !== right.length) return false;
|
|
172
|
+
let diff = 0;
|
|
173
|
+
for (let i = 0; i < left.length; i += 1) diff |= left.charCodeAt(i) ^ right.charCodeAt(i);
|
|
174
|
+
return diff === 0;
|
|
175
|
+
}
|
|
176
|
+
/** True when `nonce` is in the signed wire format (not necessarily valid). */
|
|
177
|
+
function isSignedBeaconNonce(nonce) {
|
|
178
|
+
return typeof nonce === "string" && nonce.startsWith(`${NONCE_VERSION}.`);
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* Mint a nonce for `binding` at `issuedAtMs`. Throws when `secret` is
|
|
182
|
+
* empty — issuing an unsigned value would be indistinguishable from a
|
|
183
|
+
* real one on the wire, so the caller must decide to issue nothing.
|
|
184
|
+
*/
|
|
185
|
+
async function issueSignedBeaconNonce(secret, binding, issuedAtMs) {
|
|
186
|
+
if (!secret) throw new Error("beacon nonce secret is required to issue a signed nonce");
|
|
187
|
+
const issuedAt = Math.floor(issuedAtMs / 1e3).toString(36);
|
|
188
|
+
const random = base64url(crypto.getRandomValues(new Uint8Array(RANDOM_BYTES)));
|
|
189
|
+
return [
|
|
190
|
+
NONCE_VERSION,
|
|
191
|
+
issuedAt,
|
|
192
|
+
random,
|
|
193
|
+
await mac(secret, binding, issuedAt, random),
|
|
194
|
+
await contextTag(secret, binding, issuedAt, random)
|
|
195
|
+
].join(".");
|
|
196
|
+
}
|
|
197
|
+
/**
|
|
198
|
+
* Verify `nonce` against `binding` as of `nowMs`. Never throws; every
|
|
199
|
+
* failure mode is a verdict (see the module doc for why expiry is
|
|
200
|
+
* `unverified` rather than `forged`).
|
|
201
|
+
*/
|
|
202
|
+
async function verifySignedBeaconNonce(secret, binding, nonce, nowMs) {
|
|
203
|
+
if (!isSignedBeaconNonce(nonce)) return {
|
|
204
|
+
verdict: "unverified",
|
|
205
|
+
reason: "malformed"
|
|
206
|
+
};
|
|
207
|
+
const parts = nonce.split(".");
|
|
208
|
+
if (parts.length !== 5 || parts.some((part) => part.length === 0)) return {
|
|
209
|
+
verdict: "unverified",
|
|
210
|
+
reason: "malformed"
|
|
211
|
+
};
|
|
212
|
+
const [, issuedAt, random, providedMac, providedContextTag] = parts;
|
|
213
|
+
if (!ISSUED_AT_PATTERN.test(issuedAt) || !BASE64URL_PATTERN.test(random) || !BASE64URL_PATTERN.test(providedMac) || !BASE64URL_PATTERN.test(providedContextTag)) return {
|
|
214
|
+
verdict: "unverified",
|
|
215
|
+
reason: "malformed"
|
|
216
|
+
};
|
|
217
|
+
if (!secret) return {
|
|
218
|
+
verdict: "unverified",
|
|
219
|
+
reason: "no_secret"
|
|
220
|
+
};
|
|
221
|
+
if (!constantTimeEqual(providedMac, await mac(secret, binding, issuedAt, random))) return {
|
|
222
|
+
verdict: "forged",
|
|
223
|
+
reason: "signature"
|
|
224
|
+
};
|
|
225
|
+
const issuedAtSeconds = parseInt(issuedAt, 36);
|
|
226
|
+
const nowSeconds = Math.floor(nowMs / 1e3);
|
|
227
|
+
if (!Number.isFinite(issuedAtSeconds)) return {
|
|
228
|
+
verdict: "unverified",
|
|
229
|
+
reason: "malformed"
|
|
230
|
+
};
|
|
231
|
+
if (issuedAtSeconds - nowSeconds > 60) return {
|
|
232
|
+
verdict: "unverified",
|
|
233
|
+
reason: "future"
|
|
234
|
+
};
|
|
235
|
+
if (nowSeconds - issuedAtSeconds > 600) return {
|
|
236
|
+
verdict: "unverified",
|
|
237
|
+
reason: "expired"
|
|
238
|
+
};
|
|
239
|
+
if (!constantTimeEqual(providedContextTag, await contextTag(secret, binding, issuedAt, random))) return {
|
|
240
|
+
verdict: "unverified",
|
|
241
|
+
reason: "context"
|
|
242
|
+
};
|
|
243
|
+
return { verdict: "verified" };
|
|
244
|
+
}
|
|
245
|
+
async function handoffTag(secret, projectId, idBytes) {
|
|
246
|
+
const input = canonical([
|
|
247
|
+
HANDOFF_TOKEN_INPUT_PREFIX,
|
|
248
|
+
projectId,
|
|
249
|
+
base64url(idBytes)
|
|
250
|
+
]);
|
|
251
|
+
const signature = await crypto.subtle.sign("HMAC", await hmacKey(secret), input);
|
|
252
|
+
return new Uint8Array(signature, 0, HANDOFF_TAG_BYTES);
|
|
253
|
+
}
|
|
254
|
+
function base64urlDecode(text) {
|
|
255
|
+
const padded = text.replace(/-/g, "+").replace(/_/g, "/").padEnd(Math.ceil(text.length / 4) * 4, "=");
|
|
256
|
+
return Uint8Array.from(atob(padded), (char) => char.charCodeAt(0));
|
|
257
|
+
}
|
|
258
|
+
function bytesEqual(left, right) {
|
|
259
|
+
if (left.length !== right.length) return false;
|
|
260
|
+
let diff = 0;
|
|
261
|
+
for (let i = 0; i < left.length; i += 1) diff |= left[i] ^ right[i];
|
|
262
|
+
return diff === 0;
|
|
263
|
+
}
|
|
264
|
+
async function issueHandoffToken(secret, projectId) {
|
|
265
|
+
if (!secret) throw new Error("beacon nonce secret is required to issue a handoff token");
|
|
266
|
+
const id = crypto.getRandomValues(new Uint8Array(HANDOFF_ID_BYTES));
|
|
267
|
+
const token = /* @__PURE__ */ new Uint8Array(32);
|
|
268
|
+
token.set(id, 0);
|
|
269
|
+
token.set(await handoffTag(secret, projectId, id), HANDOFF_ID_BYTES);
|
|
270
|
+
return base64url(token);
|
|
271
|
+
}
|
|
272
|
+
const HANDOFF_USER_HASH_PATTERN = /^[0-9a-f]{8}$/;
|
|
273
|
+
const HANDOFF_USER_SEPARATOR = "~";
|
|
274
|
+
function splitHandoffToken(raw) {
|
|
275
|
+
const parts = raw.split(HANDOFF_USER_SEPARATOR);
|
|
276
|
+
const [token, userHash] = parts;
|
|
277
|
+
if (parts.length > 2 || userHash !== void 0 && !HANDOFF_USER_HASH_PATTERN.test(userHash)) return { token: raw };
|
|
278
|
+
return {
|
|
279
|
+
token,
|
|
280
|
+
...userHash === void 0 ? {} : { userHash }
|
|
281
|
+
};
|
|
282
|
+
}
|
|
283
|
+
async function handoffTokenAuthentic(secrets, projectId, token) {
|
|
284
|
+
if (typeof token !== "string" || !HANDOFF_TOKEN_PATTERN.test(token)) return false;
|
|
285
|
+
const bytes = base64urlDecode(token);
|
|
286
|
+
if (bytes.length !== 32) return false;
|
|
287
|
+
if (base64url(bytes) !== token) return false;
|
|
288
|
+
const id = bytes.slice(0, HANDOFF_ID_BYTES);
|
|
289
|
+
const providedTag = bytes.slice(HANDOFF_ID_BYTES);
|
|
290
|
+
return (await Promise.all(secrets.filter((secret) => secret.length > 0).map(async (secret) => bytesEqual(providedTag, await handoffTag(secret, projectId, id))))).includes(true);
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
//#endregion
|
|
294
|
+
exports.BEACON_NONCE_CLOCK_SKEW_SECONDS = BEACON_NONCE_CLOCK_SKEW_SECONDS;
|
|
295
|
+
exports.BEACON_NONCE_MAX_LENGTH = BEACON_NONCE_MAX_LENGTH;
|
|
296
|
+
exports.BEACON_NONCE_TTL_SECONDS = BEACON_NONCE_TTL_SECONDS;
|
|
297
|
+
exports.HANDOFF_TOKEN_PATTERN = HANDOFF_TOKEN_PATTERN;
|
|
298
|
+
exports.HANDOFF_USER_HASH_PATTERN = HANDOFF_USER_HASH_PATTERN;
|
|
299
|
+
exports.beaconNonceContext = beaconNonceContext;
|
|
300
|
+
exports.handoffTokenAuthentic = handoffTokenAuthentic;
|
|
301
|
+
exports.isSignedBeaconNonce = isSignedBeaconNonce;
|
|
302
|
+
exports.issueHandoffToken = issueHandoffToken;
|
|
303
|
+
exports.issueSignedBeaconNonce = issueSignedBeaconNonce;
|
|
304
|
+
exports.splitHandoffToken = splitHandoffToken;
|
|
305
|
+
exports.verifySignedBeaconNonce = verifySignedBeaconNonce;
|