@kya-os/checkpoint-shared 1.5.0 → 1.5.2

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.
Files changed (141) hide show
  1. package/CHANGELOG.md +129 -0
  2. package/dist/beacon-nonce/index.d.mts +36 -0
  3. package/dist/beacon-nonce/index.d.mts.map +1 -0
  4. package/dist/beacon-nonce/index.d.ts +36 -0
  5. package/dist/beacon-nonce/index.d.ts.map +1 -0
  6. package/dist/beacon-nonce/index.js +305 -0
  7. package/dist/beacon-nonce/index.mjs +294 -0
  8. package/dist/beacon-nonce/index.mjs.map +1 -0
  9. package/dist/beacon-types/index.d.mts +50 -14
  10. package/dist/beacon-types/index.d.mts.map +1 -1
  11. package/dist/beacon-types/index.d.ts +50 -14
  12. package/dist/beacon-types/index.d.ts.map +1 -1
  13. package/dist/beacon-types/index.js +127 -8
  14. package/dist/beacon-types/index.mjs +122 -9
  15. package/dist/beacon-types/index.mjs.map +1 -1
  16. package/dist/browser-posture-D4j2a5gi.d.ts +169 -0
  17. package/dist/browser-posture-D4j2a5gi.d.ts.map +1 -0
  18. package/dist/browser-posture-DVoHMHjY.d.mts +169 -0
  19. package/dist/browser-posture-DVoHMHjY.d.mts.map +1 -0
  20. package/dist/browser-posture-cookie.d.mts +4 -2
  21. package/dist/browser-posture-cookie.d.mts.map +1 -0
  22. package/dist/browser-posture-cookie.d.ts +4 -2
  23. package/dist/browser-posture-cookie.d.ts.map +1 -0
  24. package/dist/browser-posture-cookie.mjs.map +1 -1
  25. package/dist/browser-posture-proof.d.mts +18 -0
  26. package/dist/browser-posture-proof.d.mts.map +1 -0
  27. package/dist/browser-posture-proof.d.ts +18 -0
  28. package/dist/browser-posture-proof.d.ts.map +1 -0
  29. package/dist/browser-posture-proof.js +66 -0
  30. package/dist/browser-posture-proof.mjs +63 -0
  31. package/dist/browser-posture-proof.mjs.map +1 -0
  32. package/dist/browser-posture-report.d.mts +59 -2
  33. package/dist/browser-posture-report.d.mts.map +1 -1
  34. package/dist/browser-posture-report.d.ts +59 -2
  35. package/dist/browser-posture-report.d.ts.map +1 -1
  36. package/dist/browser-posture-report.js +1 -1
  37. package/dist/browser-posture-report.mjs +1 -1
  38. package/dist/browser-posture-report.mjs.map +1 -1
  39. package/dist/browser-posture.d.mts +2 -83
  40. package/dist/browser-posture.d.ts +2 -83
  41. package/dist/browser-posture.js +214 -44
  42. package/dist/browser-posture.mjs +203 -45
  43. package/dist/browser-posture.mjs.map +1 -1
  44. package/dist/browser.d.mts +3 -11
  45. package/dist/browser.d.mts.map +1 -1
  46. package/dist/browser.d.ts +3 -11
  47. package/dist/browser.d.ts.map +1 -1
  48. package/dist/browser.js +1 -1
  49. package/dist/browser.mjs +1 -1
  50. package/dist/browser.mjs.map +1 -1
  51. package/dist/clearance.d.mts +1 -1
  52. package/dist/clearance.d.ts +1 -1
  53. package/dist/{client-ip-HOfe6ucV.mjs → client-ip-B2Xeo-GK.mjs} +2 -2
  54. package/dist/{client-ip-HOfe6ucV.mjs.map → client-ip-B2Xeo-GK.mjs.map} +1 -1
  55. package/dist/{client-ip-1y2iXAYW.js → client-ip-CW6pRyLf.js} +1 -1
  56. package/dist/consent-handoff.d.mts +41 -0
  57. package/dist/consent-handoff.d.mts.map +1 -0
  58. package/dist/consent-handoff.d.ts +41 -0
  59. package/dist/consent-handoff.d.ts.map +1 -0
  60. package/dist/consent-handoff.js +1 -0
  61. package/dist/consent-handoff.mjs +2 -0
  62. package/dist/consent-handoff.mjs.map +1 -0
  63. package/dist/errors/index.d.mts +138 -0
  64. package/dist/errors/index.d.mts.map +1 -1
  65. package/dist/errors/index.d.ts +138 -0
  66. package/dist/errors/index.d.ts.map +1 -1
  67. package/dist/errors/index.js +441 -9
  68. package/dist/errors/index.mjs +441 -10
  69. package/dist/errors/index.mjs.map +1 -1
  70. package/dist/{external-jr_S4iSS.d.mts → external-Ct8j_hto.d.mts} +2 -2
  71. package/dist/{external-jr_S4iSS.d.mts.map → external-Ct8j_hto.d.mts.map} +1 -1
  72. package/dist/{external-jr_S4iSS.d.ts → external-Ct8j_hto.d.ts} +2 -2
  73. package/dist/{external-jr_S4iSS.d.ts.map → external-Ct8j_hto.d.ts.map} +1 -1
  74. package/dist/gateway-client-ip.d.mts +1 -1
  75. package/dist/gateway-client-ip.d.ts +1 -1
  76. package/dist/gateway-client-ip.js +1 -1
  77. package/dist/gateway-client-ip.mjs +1 -1
  78. package/dist/index.d.mts +5227 -1063
  79. package/dist/index.d.mts.map +1 -1
  80. package/dist/index.d.ts +5227 -1063
  81. package/dist/index.d.ts.map +1 -1
  82. package/dist/index.js +3678 -546
  83. package/dist/index.mjs +3446 -534
  84. package/dist/index.mjs.map +1 -1
  85. package/dist/mcpi/approval-grant/index.d.mts +1 -1
  86. package/dist/mcpi/approval-grant/index.d.mts.map +1 -1
  87. package/dist/mcpi/approval-grant/index.d.ts +1 -1
  88. package/dist/mcpi/approval-grant/index.d.ts.map +1 -1
  89. package/dist/mcpi/approval-grant/index.js +48 -48
  90. package/dist/mcpi/approval-grant/index.mjs +48 -48
  91. package/dist/mcpi/approval-grant/index.mjs.map +1 -1
  92. package/dist/posture-origins/index.d.mts +41 -0
  93. package/dist/posture-origins/index.d.mts.map +1 -0
  94. package/dist/posture-origins/index.d.ts +41 -0
  95. package/dist/posture-origins/index.d.ts.map +1 -0
  96. package/dist/posture-origins/index.js +441 -0
  97. package/dist/posture-origins/index.mjs +430 -0
  98. package/dist/posture-origins/index.mjs.map +1 -0
  99. package/dist/posture-origins-CEm83u4D.js +621 -0
  100. package/dist/posture-origins-Dl7i8j93.mjs +533 -0
  101. package/dist/posture-origins-Dl7i8j93.mjs.map +1 -0
  102. package/dist/rules.json +0 -1
  103. package/dist/signals/index.d.mts +75 -55
  104. package/dist/signals/index.d.mts.map +1 -1
  105. package/dist/signals/index.d.ts +75 -55
  106. package/dist/signals/index.d.ts.map +1 -1
  107. package/dist/signals/index.js +246 -2
  108. package/dist/signals/index.mjs +236 -3
  109. package/dist/signals/index.mjs.map +1 -1
  110. package/fixtures/browser-integrity/captured-java-0.2.1-missing-score.json +10 -0
  111. package/fixtures/browser-integrity/null-score.json +11 -0
  112. package/fixtures/browser-integrity/numeric-score.json +11 -0
  113. package/fixtures/browser-posture-claims.json +168 -0
  114. package/fixtures/browser-posture-headers.json +6 -0
  115. package/fixtures/kya-http/README.md +1 -0
  116. package/fixtures/kya-http/consent-handoff.codes.json +34 -0
  117. package/fixtures/workbench/a2a-signed-request.v1.json +255 -0
  118. package/fixtures/workbench/artifact-bindings.v1.json +1003 -0
  119. package/fixtures/workbench/delegation-management.v1.json +507 -0
  120. package/fixtures/workbench/didcomm-task-source.v1.json +191 -0
  121. package/fixtures/workbench/graph-interfaces.v1.json +1887 -0
  122. package/fixtures/workbench/identity-provisioning.v1.json +643 -0
  123. package/fixtures/workbench/linear-installation.v1.json +484 -0
  124. package/fixtures/workbench/management-session.v1.json +716 -0
  125. package/fixtures/workbench/model-credentials.v1.json +630 -0
  126. package/fixtures/workbench/source-claim-pooled.v1.json +50 -0
  127. package/fixtures/workbench/task-grant.v1.json +695 -0
  128. package/fixtures/workbench/task-status-projection.v1.json +591 -0
  129. package/fixtures/workbench/workload-enrollment.v1.json +580 -0
  130. package/package.json +21 -2
  131. package/src/data/compiled/merged-rules.json +2 -9
  132. package/src/data/default-rules.json +0 -1
  133. package/dist/browser-posture-cookie-Dmq9Brf_.d.mts +0 -5
  134. package/dist/browser-posture-cookie-Dmq9Brf_.d.mts.map +0 -1
  135. package/dist/browser-posture-cookie-Dmq9Brf_.d.ts +0 -5
  136. package/dist/browser-posture-cookie-Dmq9Brf_.d.ts.map +0 -1
  137. package/dist/browser-posture.d.mts.map +0 -1
  138. package/dist/browser-posture.d.ts.map +0 -1
  139. package/dist/patterns-CkRVOdtV.js +0 -243
  140. package/dist/patterns-DzkGy_qk.mjs +0 -173
  141. package/dist/patterns-DzkGy_qk.mjs.map +0 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,134 @@
1
1
  # @kya-os/checkpoint-shared
2
2
 
3
+ ## Unreleased
4
+
5
+ ### Changed
6
+
7
+ - `PolicyFetcher` can expose fast origin failures as `POLICY_UNAVAILABLE` with
8
+ `throwOnUnavailable`; its default continues to return `DEFAULT_POLICY` on
9
+ ordinary fetch errors.
10
+
11
+ `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`).
12
+
13
+ `computeSessionFingerprintHash` keeps its published behavior and nothing in this
14
+ repo calls it any more; use `computeDeviceFingerprint`. The new
15
+ function hashes only the client attributes `CLIENT_ATTRIBUTE_CLASSIFICATION`
16
+ marks `include` (stable device properties every browser lane emits, and the
17
+ persistent `device.id`; never counters, timings, probe verdicts or lazy-chunk
18
+ attributes), folds synonymous names such as `platform.timezone` onto
19
+ `browser.timezone` first, and returns a different digest for the same
20
+ attributes, so a stored old digest never equals a new one. New exports:
21
+ `CLIENT_ATTRIBUTE_CLASSIFICATION`, `isChurningClientAttribute`,
22
+ `isStatsRecordableClientAttribute`,
23
+ `deviceFingerprintComponents`, `canonicalizeClientAttributes`,
24
+ `DEVICE_FINGERPRINT_VERSION` and `DEVICE_FINGERPRINT_PREFIX` (`fp2:`, the prefix
25
+ a caller puts on the stored, salted value so a later definition can be told
26
+ apart from this one).
27
+
28
+ `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.
29
+
30
+ `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.
31
+
32
+ `BrowserPostureConfig.origins` lists further allowed page origins beside the
33
+ required `origin`. A posture token is accepted only when its `origin` claim
34
+ matches `origin` or an `origins` entry (exact, or a leftmost wildcard that
35
+ never matches the apex, same rules as `posture-origins`) and its `aud`
36
+ contains that claim. `validateBrowserPostureConfig` rejects an invalid entry
37
+ or more than 20. A config without `origins` behaves as before.
38
+
39
+ `postureOutcomeFromRequest` and `inspectBrowserPosture` report why a token was
40
+ refused (`BROWSER_POSTURE_REJECTION_REASONS`) instead of only returning
41
+ nothing, and `BrowserPostureOutcomeSchema` is the wire shape of
42
+ `postureOutcome` on a detection report. `verifyBrowserPosture` and
43
+ `postureFromRequest` are unchanged. Every token part must now be base64url.
44
+
45
+ `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.
46
+
47
+ `AgentShieldConfigSchema` now rejects `allowedIps`, `blockedIps`,
48
+ `allowedAgents`, `blockedAgents`, `customRules`, `customPatterns` and every
49
+ `network` setting (`enabled`, `checkCloudProviders`, `checkDataCenters`,
50
+ `checkVpn`, `checkProxy`, `customIpRanges`) with an error naming the setting,
51
+ and the fields are typed `?: undefined`. The schema accepted them but no
52
+ runtime ever read them, so a caller who set an allow/block list or a network
53
+ check was unprotected. Any defined value is rejected, `false` and `[]`
54
+ included, so a parsed config that carried the old `network` defaults can no
55
+ longer be fed back through the schema; the parsed `network` object is now
56
+ empty. The same applies to `ExpressMiddlewareOptionsSchema`,
57
+ `NextMiddlewareOptionsSchema` and `validateConfig` in `@kya-os/checkpoint`.
58
+
59
+ `RuleLoader.loadRules({ cdnUrl })` now throws instead of fetching. It accepted
60
+ any schema-valid document from the URL with no signature check, and its
61
+ default endpoints pointed at retired domains. Remote delivery of vendor IP
62
+ ranges and key expiry is a signed rule bundle verified inside the engine
63
+ (`@kya-os/checkpoint-wasm-runtime`'s `createRuleBundleUpdater`). Removed the
64
+ `RULE_CDN` and `RULE_CACHE` constants and the `RULE_ERRORS.CDN_UNAVAILABLE` /
65
+ `CACHE_EXPIRED` messages; `cdnUrl` stays on `RuleLoadOptions` as
66
+ `@deprecated`.
67
+
68
+ Additive. `./browser-posture` gains `postureFromRequest`,
69
+ `postureRequestFromHeaders`, `POSTURE_HEADER` (`kya-posture`) and
70
+ `POSTURE_SESSION_HEADER` (`kya-posture-session`): posture read from the
71
+ `KYA-Posture` and `KYA-Posture-Session` request headers, each winning over its
72
+ cookie, for a page on another host or one that blocks cookies. A header sent
73
+ twice, or comma-joined, is trusted by no one. `postureFromCookies` is
74
+ unchanged.
75
+
76
+ Additive. `./beacon-types` gains `BeaconReceipt` and two `BeaconConfig`
77
+ options, `browserSessionId` and `onReceipt`, both kept by
78
+ `parseBeaconConfig` (an invalid value warns and is dropped). Consumed by
79
+ `@kya-os/checkpoint-beacon`'s receipt hook and session resume.
80
+
81
+ `TrafficTimeSeriesPoint.uniqueIPs` is now `number | null`. It is `null` for a
82
+ bucket served from `analytics_daily_rollup`, which records no client IPs; the
83
+ admin traffic-patterns route previously reported those buckets as `0`.
84
+
85
+ `TrafficTopPage.bounceRate` is removed. No code path computed it, and the
86
+ route set it to `0` on every page.
87
+
88
+ Additive. Extends the `ERROR_CODES` registry with every code the v1
89
+ projects, deploy, shopify and pixel/track routes emit that was still
90
+ route-local: `ANALYTICS_ERRORS` and `DEPLOY_ERRORS` are new groups, and
91
+ `RATE_LIMIT_ERRORS`, `PERMISSION_ERRORS`, `INTERNAL_ERRORS`, `PIXEL_ERRORS`
92
+ and `BARE_ERRORS` gained new codes. No wire string changed. The four
93
+ service-computed deploy codes (`DEPLOY_FAILED`, `WFP_NOT_CONFIGURED`,
94
+ `NATIVE_ISSUER_PROVISIONING_BUSY`, `NATIVE_ISSUER_PROVISIONING_FAILED`)
95
+ carry no fixed status, like `PROJECT_NOT_FOUND`.
96
+
97
+ Additive. Extends the `ERROR_CODES` registry with every code the v1 bouncer,
98
+ delegation OAuth, native HTTP and audit ingest routes emit that was still
99
+ route-local, as six new groups: `BOUNCER_LOWERCASE_ERRORS`,
100
+ `OAUTH_LOWERCASE_ERRORS`, `BOUNCER_UPPERCASE_ERRORS`, `AUDIT_ERRORS`,
101
+ `AUDIT_PROTOCOL_ERRORS` (the `@kya-os/mcp` audit vocabulary, hand-copied
102
+ because this package does not depend on it) and `KYAOS_PROTOCOL_ERRORS`
103
+ (the `kyaos/*` strings, keyed `KYAOS_SLASH_*`). No wire string changed.
104
+ `invalid_grant` and `kyaos/profile-violation` carry no fixed status because
105
+ their emitters disagree. `INVALID_REQUEST_BODY` (400),
106
+ `MCPI_CONFIG_NOT_FOUND` (404) and `CONSENT_CONFIG_NOT_FOUND` (404) are pinned,
107
+ which lets `v1ErrorResponse` resolve the three `new Error('<code>')` sites in
108
+ the bouncer config validate and consent-config routes to their intended
109
+ status instead of a 500 `INTERNAL_SERVER_ERROR`.
110
+
111
+ Handoff and session changes. New exports: `issueHandoffToken`, `handoffTokenAuthentic` and
112
+ `HANDOFF_TOKEN_PATTERN` from `@kya-os/checkpoint-shared/beacon-nonce` (a handoff token is 16 random
113
+ bytes plus a 16 byte HMAC tag under the nonce secret, 43 base64url characters, and one canonical
114
+ spelling), and `SESSION_IDLE_GAP_MAX_MS` from `beacon-types` (six hours). `sessionTimeout` no
115
+ longer defaults to 30 minutes: `parseBeaconConfig` (in `beacon-types` and in `browser.ts`),
116
+ `DEFAULT_CONFIG` and `PixelInstallConfigSchema` leave it unset, so the idle gap is one hour on
117
+ phones and six hours elsewhere, and `PixelInstallConfigSchema.sessionTimeout` is optional. Added
118
+ fields: `deviceId` and `handoffToken` on the beacon batch types, `handoffToken` (at most 2,048
119
+ characters, dropped when invalid) on the pixel request schema, `handoff` (`status` is `adopted`,
120
+ `rejected` or `unavailable`) on the pixel response schema, and `requireConsent` on the beacon
121
+ config.
122
+
123
+ ## 1.5.1
124
+
125
+ Adds `POSTURE_TTL_SECONDS` and `BEACON_MAX_EVENTS_PER_BATCH` to `./beacon-types`,
126
+ both consumed by `@kya-os/checkpoint-beacon` 1.4.1 (#5095).
127
+
128
+ `./browser`'s `BeaconEventType` gains `'evidence'`, matching `./beacon-types`'
129
+ canonical union. `TransportConfig.batchSize`/`flushInterval` are now optional;
130
+ nothing in this package reads them.
131
+
3
132
  ## 1.5.0
4
133
 
5
134
  Two changes below carry breaking content under a minor, the same call as
@@ -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;