@ornexus/neocortex 4.60.78 → 4.60.80

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 (247) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +1193 -1206
  3. package/install.ps1 +1 -1
  4. package/install.sh +1 -1
  5. package/package.json +2 -2
  6. package/packages/client/dist/adapters/adapter-registry.js +108 -1
  7. package/packages/client/dist/adapters/antigravity-adapter.js +77 -2
  8. package/packages/client/dist/adapters/claude-code-adapter.js +79 -3
  9. package/packages/client/dist/adapters/codex-adapter.js +80 -2
  10. package/packages/client/dist/adapters/cursor-adapter.js +115 -4
  11. package/packages/client/dist/adapters/gemini-adapter.js +71 -2
  12. package/packages/client/dist/adapters/grok-adapter.js +42 -2
  13. package/packages/client/dist/adapters/index.js +22 -1
  14. package/packages/client/dist/adapters/platform-detector.js +214 -1
  15. package/packages/client/dist/adapters/target-adapter.js +12 -0
  16. package/packages/client/dist/adapters/vscode-adapter.js +72 -2
  17. package/packages/client/dist/agent/refresh-stubs.js +443 -2
  18. package/packages/client/dist/agent/update-agent-yaml.js +102 -1
  19. package/packages/client/dist/agent/update-description.js +260 -1
  20. package/packages/client/dist/cache/crypto-utils.js +78 -1
  21. package/packages/client/dist/cache/encrypted-cache.js +338 -1
  22. package/packages/client/dist/cache/in-memory-asset-cache.js +73 -1
  23. package/packages/client/dist/cache/index.js +13 -1
  24. package/packages/client/dist/cache/protected-pi-boundary.js +44 -1
  25. package/packages/client/dist/checkpoint/checkpoint-client-reader.js +127 -2
  26. package/packages/client/dist/checkpoint/index.js +11 -1
  27. package/packages/client/dist/checkpoint/shared-checkpoint-types.js +32 -1
  28. package/packages/client/dist/cli.js +358 -5
  29. package/packages/client/dist/commands/activate.js +394 -8
  30. package/packages/client/dist/commands/architecture-answers.js +274 -7
  31. package/packages/client/dist/commands/architecture-memory-terminal.js +253 -4
  32. package/packages/client/dist/commands/architecture-non-ui-continuation.js +100 -1
  33. package/packages/client/dist/commands/architecture-root-binding.js +51 -1
  34. package/packages/client/dist/commands/cache-status.js +112 -2
  35. package/packages/client/dist/commands/config.js +88 -1
  36. package/packages/client/dist/commands/doctor.js +635 -2
  37. package/packages/client/dist/commands/invoke.js +7712 -143
  38. package/packages/client/dist/commands/legacy-epic-terminal.js +71 -1
  39. package/packages/client/dist/commands/legacy-story-branch.js +96 -1
  40. package/packages/client/dist/commands/legacy-story-pr.js +276 -1
  41. package/packages/client/dist/commands/mutation-qa-checkpoint.js +285 -5
  42. package/packages/client/dist/commands/mutation-qa-gate.js +54 -1
  43. package/packages/client/dist/commands/mutation-qa-git.js +41 -1
  44. package/packages/client/dist/commands/mutation-qa-policy.js +102 -1
  45. package/packages/client/dist/commands/mutation-qa-run.js +219 -3
  46. package/packages/client/dist/commands/mutation-qa-verdict.js +149 -1
  47. package/packages/client/dist/commands/mutation-qa.js +220 -1
  48. package/packages/client/dist/commands/native-agent.js +136 -2
  49. package/packages/client/dist/commands/planning-diagnosis.js +43 -1
  50. package/packages/client/dist/commands/planning-generation.js +53 -1
  51. package/packages/client/dist/commands/planning-memory.js +40 -1
  52. package/packages/client/dist/commands/planning-research.js +42 -1
  53. package/packages/client/dist/commands/private-session.js +75 -1
  54. package/packages/client/dist/commands/property-qa.js +139 -1
  55. package/packages/client/dist/commands/qa-control.js +16 -1
  56. package/packages/client/dist/commands/qa-scan-browser-launch.js +55 -1
  57. package/packages/client/dist/commands/qa-scan-browser-route.js +28 -1
  58. package/packages/client/dist/commands/qa-scan-capture.js +663 -5
  59. package/packages/client/dist/commands/qa-scan-discovery.js +376 -3
  60. package/packages/client/dist/commands/qa-scan-review.js +826 -5
  61. package/packages/client/dist/commands/qa-synthetic-backend-capture.js +266 -1
  62. package/packages/client/dist/commands/qa-synthetic-backend-review.js +297 -1
  63. package/packages/client/dist/commands/qa-synthetic-backend.js +340 -2
  64. package/packages/client/dist/commands/qa-synthetic-broker-port.js +85 -1
  65. package/packages/client/dist/commands/qa-synthetic-browser.js +39 -1
  66. package/packages/client/dist/commands/refactor-characterization.js +671 -21
  67. package/packages/client/dist/commands/refactor-commit.js +399 -13
  68. package/packages/client/dist/commands/refactor-control.js +142 -3
  69. package/packages/client/dist/commands/refactor-cpp-assertions.js +93 -3
  70. package/packages/client/dist/commands/refactor-review.js +283 -5
  71. package/packages/client/dist/commands/refactor-root.js +588 -7
  72. package/packages/client/dist/commands/refresh-memory.d.ts +3 -1
  73. package/packages/client/dist/commands/refresh-memory.js +174 -3
  74. package/packages/client/dist/commands/shared-architecture-non-ui.js +24 -1
  75. package/packages/client/dist/commands/story-checkpoint.js +171 -1
  76. package/packages/client/dist/config/host-auth-broker.js +60 -1
  77. package/packages/client/dist/config/host-auth-reference.js +93 -1
  78. package/packages/client/dist/config/profile-directory.js +13 -1
  79. package/packages/client/dist/config/resolver-selection.js +278 -1
  80. package/packages/client/dist/config/secure-config.js +281 -12
  81. package/packages/client/dist/config.js +223 -2
  82. package/packages/client/dist/constants.js +25 -1
  83. package/packages/client/dist/context/context-collector.js +222 -2
  84. package/packages/client/dist/context/context-sanitizer.js +145 -1
  85. package/packages/client/dist/continuity/autonomous-governance.js +285 -1
  86. package/packages/client/dist/continuity/continuity-client-state-store.js +1587 -1
  87. package/packages/client/dist/continuity/invoke-hooks.js +129 -1
  88. package/packages/client/dist/continuity/migrations/001-initial-schema.js +12 -2
  89. package/packages/client/dist/continuity/migrations/002-processing-output-summary-indexes.js +12 -2
  90. package/packages/client/dist/continuity/migrations/003-headless-execution-attempts.js +12 -2
  91. package/packages/client/dist/continuity/migrations/004-outbox-delivery-state.js +12 -2
  92. package/packages/client/dist/continuity/migrations/005-bounded-headless-queue.js +12 -2
  93. package/packages/client/dist/continuity/migrations/006-native-agent-dispatches.js +10 -2
  94. package/packages/client/dist/continuity/native-agent-store.js +69 -1
  95. package/packages/client/dist/continuity/native-agent-types.js +105 -1
  96. package/packages/client/dist/continuity/outbox.js +117 -1
  97. package/packages/client/dist/continuity/runner-bootstrap-policy.js +172 -1
  98. package/packages/client/dist/continuity/sqlite-store.js +2612 -81
  99. package/packages/client/dist/effects/invoke-effect-gateways.js +62 -1
  100. package/packages/client/dist/errors/error-messages.js +258 -2
  101. package/packages/client/dist/errors/frontmatter-diagnostics.js +125 -1
  102. package/packages/client/dist/evidence/collector.js +347 -1
  103. package/packages/client/dist/evidence/index.js +1 -1
  104. package/packages/client/dist/evidence/types.js +2 -0
  105. package/packages/client/dist/fs/atomic-state-replace.js +152 -1
  106. package/packages/client/dist/generated/command-registry.generated.js +4076 -1
  107. package/packages/client/dist/generated/public-projections.generated.js +149 -1
  108. package/packages/client/dist/git/direct-yolo-c01-retry.js +138 -4
  109. package/packages/client/dist/git/direct-yolo-checkpoint.js +1456 -4
  110. package/packages/client/dist/git/epic-operational-state.js +672 -2
  111. package/packages/client/dist/git/git-lifecycle-step-ids.js +14 -1
  112. package/packages/client/dist/git/git-lifecycle-store.js +2188 -10
  113. package/packages/client/dist/git/legacy-story-branch-checkpoint.js +259 -9
  114. package/packages/client/dist/git/legacy-story-branch-setup.js +348 -4
  115. package/packages/client/dist/git/legacy-story-pr.js +3538 -70
  116. package/packages/client/dist/git/neocortex-trailers.d.ts +26 -0
  117. package/packages/client/dist/git/neocortex-trailers.js +53 -0
  118. package/packages/client/dist/git/secure-filesystem-boundary.js +182 -5
  119. package/packages/client/dist/graph-retrieval/pre-command-hook.js +284 -1
  120. package/packages/client/dist/graph-retrieval/shared-graph-retrieval-contract.js +237 -1
  121. package/packages/client/dist/i18n/first-run.js +60 -2
  122. package/packages/client/dist/index.js +50 -1
  123. package/packages/client/dist/invocation/invoke-input.js +24 -1
  124. package/packages/client/dist/license/host-auth-recovery.js +401 -1
  125. package/packages/client/dist/license/index.js +5 -1
  126. package/packages/client/dist/license/license-client.js +337 -1
  127. package/packages/client/dist/machine/fingerprint.js +163 -2
  128. package/packages/client/dist/machine/index.js +5 -1
  129. package/packages/client/dist/memory/project-memory-path-scope.js +62 -1
  130. package/packages/client/dist/memory/project-memory-writer.d.ts +16 -1
  131. package/packages/client/dist/memory/project-memory-writer.js +1117 -41
  132. package/packages/client/dist/memory/shared-project-memory-types.js +259 -2
  133. package/packages/client/dist/migrations/epic-lifecycle-backfill.js +1060 -3
  134. package/packages/client/dist/migrations/project-identity-capability.js +50 -1
  135. package/packages/client/dist/migrations/project-identity.js +493 -7
  136. package/packages/client/dist/migrations/state-json.js +393 -4
  137. package/packages/client/dist/policy/architecture-policy.js +184 -2
  138. package/packages/client/dist/policy/index.js +7 -1
  139. package/packages/client/dist/policy/shared-policy-types.js +38 -0
  140. package/packages/client/dist/policy/subagent-approval-policy.js +55 -1
  141. package/packages/client/dist/private-execution/clean-baseline.js +279 -2
  142. package/packages/client/dist/private-execution/codex-executor.js +574 -4
  143. package/packages/client/dist/private-execution/codex-host-runtime.js +137 -1
  144. package/packages/client/dist/private-execution/codex-lifecycle-guard.js +97 -1
  145. package/packages/client/dist/private-execution/codex-scoped-permissions.js +128 -1
  146. package/packages/client/dist/private-execution/delivery.js +410 -13
  147. package/packages/client/dist/private-execution/diagnosis-root-review.js +294 -2
  148. package/packages/client/dist/private-execution/frozen-handoff.js +19 -6
  149. package/packages/client/dist/private-execution/implementation-validation.js +106 -2
  150. package/packages/client/dist/private-execution/isolated-admission.js +1432 -23
  151. package/packages/client/dist/private-execution/isolated-session.js +725 -5
  152. package/packages/client/dist/private-execution/isolated-workspace.js +122 -1
  153. package/packages/client/dist/private-execution/pact-consumer-runtime.js +409 -3
  154. package/packages/client/dist/private-execution/pact-test-source.js +258 -1
  155. package/packages/client/dist/private-execution/pact-toolchain.js +290 -3
  156. package/packages/client/dist/private-execution/pact-write-set.js +172 -1
  157. package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.js +406 -5
  158. package/packages/client/dist/private-execution/planning-generation-checkpoint.js +462 -5
  159. package/packages/client/dist/private-execution/planning-memory-checkpoint.js +139 -3
  160. package/packages/client/dist/private-execution/planning-research-checkpoint.js +325 -4
  161. package/packages/client/dist/private-execution/private-report-store.js +42 -1
  162. package/packages/client/dist/private-execution/property-test-candidate.js +103 -1
  163. package/packages/client/dist/private-execution/property-test-choices.js +147 -3
  164. package/packages/client/dist/private-execution/property-test-plan.js +271 -7
  165. package/packages/client/dist/private-execution/property-test-review.js +258 -4
  166. package/packages/client/dist/private-execution/property-test-runtime.js +372 -9
  167. package/packages/client/dist/private-execution/property-test-source.js +139 -1
  168. package/packages/client/dist/private-execution/root-checkpoint.js +80 -1
  169. package/packages/client/dist/private-execution/root-memory-git-evidence.js +135 -3
  170. package/packages/client/dist/private-execution/root-memory-recovery.js +93 -1
  171. package/packages/client/dist/private-execution/root-memory-request.js +29 -1
  172. package/packages/client/dist/private-execution/root-memory-scope.js +178 -1
  173. package/packages/client/dist/private-execution/root-memory-writer.js +102 -1
  174. package/packages/client/dist/private-execution/session-lease.js +63 -1
  175. package/packages/client/dist/private-execution/shared-private-admission-types.js +50 -1
  176. package/packages/client/dist/private-execution/shared-project-validation.js +66 -1
  177. package/packages/client/dist/private-execution/shared-root-memory-types.js +61 -1
  178. package/packages/client/dist/private-execution/ux-source-validation.js +372 -1
  179. package/packages/client/dist/private-execution/ux-write-set.js +191 -2
  180. package/packages/client/dist/registry/registry-reconciliation.js +234 -1
  181. package/packages/client/dist/resilience/circuit-breaker.js +170 -1
  182. package/packages/client/dist/resilience/degradation-manager.js +164 -1
  183. package/packages/client/dist/resilience/freshness-indicator.js +100 -1
  184. package/packages/client/dist/resilience/index.js +8 -1
  185. package/packages/client/dist/resilience/recovery-detector.js +74 -1
  186. package/packages/client/dist/resolvers/asset-resolver.js +13 -0
  187. package/packages/client/dist/resolvers/local-resolver.js +255 -8
  188. package/packages/client/dist/resolvers/remote-resolver.js +233 -1
  189. package/packages/client/dist/runner/binary.js +404 -1
  190. package/packages/client/dist/runner/cli.js +1571 -17
  191. package/packages/client/dist/runner/epic-background-dispatcher.js +124 -1
  192. package/packages/client/dist/runner/headless/adapters.js +49 -1
  193. package/packages/client/dist/runner/headless/background-root.js +85 -1
  194. package/packages/client/dist/runner/headless/claude-code-adapter.js +79 -1
  195. package/packages/client/dist/runner/headless/continuous-story-workspace.js +1628 -11
  196. package/packages/client/dist/runner/headless/epic-git-reconciliation-inventory.js +69 -1
  197. package/packages/client/dist/runner/headless/epic-merge-candidate-qa.js +111 -2
  198. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.js +1464 -10
  199. package/packages/client/dist/runner/headless/epic-terminal-git-runner.js +357 -2
  200. package/packages/client/dist/runner/headless/fake-adapter.js +62 -1
  201. package/packages/client/dist/runner/headless/managed-environment-cleanup.js +274 -1
  202. package/packages/client/dist/runner/headless/managed-profile.js +149 -1
  203. package/packages/client/dist/runner/headless/opencode-adapter.js +145 -2
  204. package/packages/client/dist/runner/headless/prepared-story-bundle.js +43 -1
  205. package/packages/client/dist/runner/headless/resolver.js +231 -1
  206. package/packages/client/dist/runner/headless/run-yolo.js +886 -1
  207. package/packages/client/dist/runner/headless/run-yoloop.js +2586 -2
  208. package/packages/client/dist/runner/headless/types.js +575 -2
  209. package/packages/client/dist/runner/host-capacity.js +59 -1
  210. package/packages/client/dist/runner/local-console.js +396 -13
  211. package/packages/client/dist/runner/portal-sync-worker.js +1487 -1
  212. package/packages/client/dist/runner/project-identity.js +106 -1
  213. package/packages/client/dist/runner/scheduler.js +995 -7
  214. package/packages/client/dist/runner-cli.js +18 -2
  215. package/packages/client/dist/state/invocation-shape.js +13 -1
  216. package/packages/client/dist/state/project-state-snapshot.js +1751 -1
  217. package/packages/client/dist/state/state-json-repair.js +785 -3
  218. package/packages/client/dist/state/structural-dag-projection.js +118 -1
  219. package/packages/client/dist/telemetry/index.js +5 -1
  220. package/packages/client/dist/telemetry/offline-queue.js +131 -1
  221. package/packages/client/dist/tier/index.js +5 -1
  222. package/packages/client/dist/tier/tier-aware-client.js +405 -1
  223. package/packages/client/dist/types/index.js +38 -1
  224. package/packages/client/dist/version.js +27 -1
  225. package/packages/client/dist/yolo/change-evidence-collector.d.ts +1 -1
  226. package/packages/client/dist/yolo/change-evidence-collector.js +245 -1
  227. package/packages/client/dist/yolo/invoke-envelope-capability.js +62 -1
  228. package/packages/client/dist/yolo/spec-envelope-collector.js +184 -5
  229. package/packages/client/dist/yoloop/discovery-hook.js +300 -2
  230. package/packages/client/dist/yoloop/index.js +8 -1
  231. package/packages/client/dist/yoloop/invoke-hooks.js +669 -12
  232. package/packages/client/dist/yoloop/shared-discover-epics.js +1007 -1
  233. package/packages/client/dist/yoloop/shared-yoloop-types.js +33 -1
  234. package/packages/client/dist/yoloop/target-normalization.js +180 -1
  235. package/packages/client/dist/yoloop/yoloop-client-state-store.js +1920 -1
  236. package/packages/shared/dist/yoloop/epic-terminal-git.js +12 -0
  237. package/targets-stubs/antigravity/gemini.md +1 -1
  238. package/targets-stubs/antigravity/skill/SKILL.md +1 -1
  239. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  240. package/targets-stubs/claude-code/neocortex-root.md +2 -2
  241. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  242. package/targets-stubs/claude-code/neocortex.md +2 -2
  243. package/targets-stubs/codex/AGENTS.md +1 -1
  244. package/targets-stubs/cursor/agent.md +2 -2
  245. package/targets-stubs/gemini-cli/agent.md +2 -2
  246. package/targets-stubs/opencode/neocortex-root.md +1 -1
  247. package/targets-stubs/vscode/neocortex.agent.md +2 -2
@@ -1 +1,401 @@
1
- import{createHash as v,randomUUID as D}from"node:crypto";class K{cache;constructor(t){this.cache=t}key(t){if(!u.test(t))throw new Error("auth-business-identity-mismatch");return`neocortex:auth-generation:v1:${t}`}async read(t){const r=await this.cache.getAuthoritative(this.key(t));if(r===null)return null;try{return d(JSON.parse(r),t)}catch(o){throw new Error("auth-generation-corrupt",{cause:o})}}async compareAndSet(t,r){d(r,r.identityHash);const o=this.key(r.identityHash),i=await this.cache.getAuthoritative(o);let s=0;if(i!==null)try{s=d(JSON.parse(i),r.identityHash).revision}catch(n){throw new Error("auth-generation-corrupt",{cause:n})}if(s!==t||r.revision!==t+1)throw new Error("auth-generation-revision-conflict");await this.cache.setAuthoritative(o,JSON.stringify(r),{expectedPlaintextSha256:i===null?null:v("sha256").update(i).digest("hex")})}}const u=/^[a-f0-9]{64}$/,p=/^[A-Za-z0-9._:-]{1,128}$/;function J(e){if(e.length!==5||e.some(t=>t.length===0||t.length>256||/[\r\n\0]/.test(t)))throw new Error("auth-business-identity-mismatch");return v("sha256").update("neocortex-auth-generation-v1\0").update(e.join("\0")).digest("hex")}function d(e,t){let r;try{r=JSON.stringify(e)}catch{throw new Error("auth-generation-corrupt")}if(!l(e)||typeof r!="string")throw new Error("auth-generation-corrupt");if(Buffer.byteLength(r,"utf8")>256*1024)throw new Error("auth-generation-capacity");const o=e;if(o.schemaVersion!=="AuthGeneration/1.0"||!Number.isSafeInteger(o.revision)||o.revision<0||!u.test(o.identityHash)||t&&o.identityHash!==t||!Array.isArray(o.receipts)||o.receipts.length>32)throw new Error("auth-generation-corrupt");if(!m(e,["schemaVersion","revision","identityHash","accepted","activeRecovery","receipts"]))throw new Error("auth-generation-corrupt");S(o.accepted),H(o.activeRecovery);for(const i of o.receipts)T(i);return o}function C(e){return{schemaVersion:"AuthGeneration/1.0",revision:0,identityHash:e,accepted:null,activeRecovery:null,receipts:[]}}async function h(e,t,r){const o=d({...t,...r,revision:t.revision+1},t.identityHash);return await e.compareAndSet(t.revision,o),o}async function U(e,t){if(!u.test(t.identityHash)||!u.test(t.requestDigest)||![t.recoveryId,t.operationId,t.idempotencyKey,t.owner].every(a=>p.test(a)))return{status:"refresh-required",cause:"protocol-invalid",action:"stop"};const r=t.now??Date.now,o=Math.min(Math.max(t.leaseMs??3e4,1),6e4),i=Math.min(Math.max(t.timeoutMs??3e4,1),3e4);let s;try{s=d(await e.read(t.identityHash)??C(t.identityHash),t.identityHash)}catch(a){return x(a)}const n=s.activeRecovery;if(n)if(n.recoveryId===t.recoveryId){if(!_(n,t))return{status:"refresh-required",cause:"protocol-invalid",action:"stop"};if((n.phase==="generation-committed"||n.phase==="completed")&&s.accepted)return A(s.accepted);if(n.attemptCount===1)return y(t.recoveryId,n.phase==="response-received"?"persistence-failed":"rotation-uncertain");if(Date.parse(n.expiresAt)>r()&&n.owner!==t.owner)return{status:"refresh-required",cause:"revision-conflict",action:"retry-later"}}else{if(n.attemptCount===1&&!["generation-committed","completed","aborted-before-request"].includes(n.phase))return y(n.recoveryId,n.phase==="response-received"?"persistence-failed":"rotation-uncertain");if(n.phase==="generation-committed")return{status:"refresh-required",cause:"revision-conflict",action:"retry-later"};if(n.attemptCount===0&&Date.parse(n.expiresAt)>r())return{status:"refresh-required",cause:"revision-conflict",action:"retry-later"}}const g={recoveryId:t.recoveryId,operationId:t.operationId,idempotencyKey:t.idempotencyKey,requestDigest:t.requestDigest,owner:t.owner,createdAt:new Date(r()).toISOString(),expiresAt:new Date(r()+o).toISOString(),attemptCount:0,replayCount:0,phase:"prepared"};try{(!n||n.recoveryId!==t.recoveryId||n.owner!==t.owner||n.phase!=="prepared")&&(s=await h(e,s,{activeRecovery:g}));const a={...g,attemptCount:1,phase:"request-started"};s=await h(e,s,{activeRecovery:a});let c;try{c=await M(t.refresh,i)}catch{return await q(e,s,a),y(t.recoveryId,"rotation-uncertain")}if(!c.token||c.token.length>65536||!Number.isFinite(Date.parse(c.expiresAt)))return await q(e,s,a),y(t.recoveryId,"rotation-uncertain");const w=v("sha256").update(JSON.stringify(c)).digest("hex"),I={...a,phase:"response-received",responseDigest:w};s=await h(e,s,{activeRecovery:I});const k={generation:(s.accepted?.generation??0)+1,accessToken:c.token,accessExpiresAt:c.expiresAt,refreshToken:c.refreshToken??null,refreshExpiresAt:c.refreshExpiresAt??null,acceptedAt:new Date(r()).toISOString(),responseDigest:w},E={...I,phase:"generation-committed"},b=await h(e,s,{accepted:k,activeRecovery:E});return A(b.accepted)}catch(a){return s.activeRecovery?.attemptCount!==1?x(a):y(t.recoveryId,"persistence-failed")}}function R(e){return!e.identityMatches||!e.requestMatches?{kind:"stop",reasonCode:"auth-business-identity-mismatch"}:e.rotationUncertain||!e.generationCommitted?{kind:"stop",reasonCode:"auth-business-replay-unsafe"}:e.replayCount!==0?{kind:"stop",reasonCode:"auth-business-replay-exhausted"}:e.receipt==="accepted"?{kind:"reconcile-receipt",operationId:e.operationId}:e.receipt==="unknown"&&!e.supportsIdempotency?{kind:"reconcile-receipt",operationId:e.operationId}:{kind:"replay-once",recoveryId:e.recoveryId}}async function B(e,t){let r;try{r=d(await e.read(t.identityHash),t.identityHash)}catch{return{kind:"stop",reasonCode:"auth-business-replay-unsafe"}}const o=r.activeRecovery;if(!o||o.recoveryId!==t.recoveryId||o.operationId!==t.operationId)return{kind:"stop",reasonCode:"auth-business-identity-mismatch"};const i=R({recoveryId:t.recoveryId,operationId:t.operationId,generationCommitted:o.phase==="generation-committed"&&r.accepted!==null,identityMatches:r.identityHash===t.identityHash,requestMatches:o.requestDigest===t.requestDigest,replayCount:o.replayCount,receipt:t.receipt,supportsIdempotency:t.supportsIdempotency,rotationUncertain:t.rotationUncertain===!0||o.phase==="uncertain"});if(i.kind!=="replay-once")return i;try{return await h(e,r,{activeRecovery:{...o,replayCount:1}}),i}catch{return{kind:"stop",reasonCode:"auth-generation-revision-conflict"}}}async function G(e,t){if(!u.test(t.identityHash)||![t.recoveryId,t.operationId,t.outcome].every(n=>p.test(n)))throw new Error("auth-business-identity-mismatch");const r=d(await e.read(t.identityHash),t.identityHash),o=r.activeRecovery;if(!o||o.recoveryId!==t.recoveryId||o.operationId!==t.operationId)throw new Error("auth-business-identity-mismatch");const i=r.receipts.find(n=>n.recoveryId===t.recoveryId);if(i){if(i.operationId!==t.operationId||i.outcome!==t.outcome)throw new Error("auth-business-identity-mismatch");return r}if(o.phase!=="generation-committed"||r.accepted===null)throw new Error("auth-business-replay-unsafe");if(r.receipts.length>=32)throw new Error("auth-generation-capacity");const s=t.completedAt??new Date().toISOString();if(!f(s))throw new Error("auth-business-identity-mismatch");return h(e,r,{activeRecovery:{...o,phase:"completed"},receipts:[...r.receipts,{recoveryId:t.recoveryId,operationId:t.operationId,outcome:t.outcome,completedAt:s}]})}function F(e){switch(e.kind){case"token":{const t=e.now??Date.now(),r=Date.parse(e.expiresAt);return Number.isFinite(r)?r<=t?{status:"refresh-required",cause:"expired",action:"prepare"}:r-t<=3e5?{status:"refresh-required",cause:"near-expiry",action:"prepare"}:{status:"authenticated",generation:e.generation,accessCredential:e.credential,expiresAt:e.expiresAt}:{status:"refresh-required",cause:"protocol-invalid",action:"stop"}}case"configuration":return e.configured?{status:"refresh-required",cause:"store-unavailable",action:"stop"}:{status:"not-configured",action:"activate"};case"store":return{status:"refresh-required",cause:e.cause,action:e.cause==="store-unavailable"?"retry-later":"stop"};case"transport":return e.requestStarted?y(e.recoveryId??"unknown-recovery","rotation-uncertain"):{status:"refresh-required",cause:e.timeout?"timeout":"transport-error",action:"retry-later"};case"http":{const t=e.errorCode??"";return e.status===429?{status:"refresh-required",cause:"rate-limited",action:"retry-later"}:e.status>=500?{status:"refresh-required",cause:"service-unavailable",action:"retry-later"}:t==="invalid_grant"||t==="revoked"?{status:"refresh-required",cause:"revoked",action:"reactivate"}:t==="invalid_scope"||t==="scope_denied"?{status:"refresh-required",cause:"scope-denied",action:"request-scope"}:t==="client_denied"?{status:"refresh-required",cause:"client-denied",action:"stop"}:{status:"refresh-required",cause:"protocol-invalid",action:"stop"}}case"persistence":return y(e.recoveryId,"persistence-failed")}}function P(){return D()}function S(e){if(e!==null){if(!l(e)||!m(e,["generation","accessToken","accessExpiresAt","refreshToken","refreshExpiresAt","acceptedAt","responseDigest"]))throw new Error("auth-generation-corrupt");if(!Number.isSafeInteger(e.generation)||e.generation<1||typeof e.accessToken!="string"||e.accessToken.length===0||e.accessToken.length>65536||e.refreshToken!==null&&(typeof e.refreshToken!="string"||e.refreshToken.length>65536)||!f(e.accessExpiresAt)||!f(e.acceptedAt)||e.refreshExpiresAt!==null&&!f(e.refreshExpiresAt)||!u.test(e.responseDigest))throw new Error("auth-generation-corrupt")}}function H(e){if(e===null)return;if(!l(e)||!m(e,["recoveryId","operationId","idempotencyKey","requestDigest","owner","createdAt","expiresAt","attemptCount","replayCount","phase","responseDigest"],!0))throw new Error("auth-generation-corrupt");const t=["prepared","request-started","response-received","generation-committed","uncertain","completed","aborted-before-request"];if(![e.recoveryId,e.operationId,e.idempotencyKey,e.owner].every(r=>p.test(r))||!u.test(e.requestDigest)||!f(e.createdAt)||!f(e.expiresAt)||![0,1].includes(e.attemptCount)||![0,1].includes(e.replayCount)||!t.includes(e.phase)||e.responseDigest!==void 0&&!u.test(e.responseDigest))throw new Error("auth-generation-corrupt")}function T(e){if(!l(e)||!m(e,["recoveryId","operationId","outcome","completedAt"])||!p.test(e.recoveryId)||!p.test(e.operationId)||!p.test(e.outcome)||!f(e.completedAt))throw new Error("auth-generation-corrupt")}function _(e,t){return e.operationId===t.operationId&&e.idempotencyKey===t.idempotencyKey&&e.requestDigest===t.requestDigest}function A(e){return{status:"authenticated",generation:e.generation,accessCredential:e.accessToken,expiresAt:e.accessExpiresAt}}function y(e,t){return{status:"uncertain",cause:t,recoveryId:e,action:"recover-explicitly"}}function x(e){const t=e instanceof Error?e.message:"";return t==="auth-generation-revision-conflict"||t==="auth-recovery-backpressure"?{status:"refresh-required",cause:"revision-conflict",action:"retry-later"}:t==="auth-generation-corrupt"||t==="auth-generation-path-unsafe"?{status:"refresh-required",cause:"store-corrupt",action:"stop"}:{status:"refresh-required",cause:"store-unavailable",action:"retry-later"}}async function q(e,t,r){try{await h(e,t,{activeRecovery:{...r,phase:"uncertain"}})}catch{}}async function M(e,t){const r=new AbortController;let o;const i=new Promise((s,n)=>{o=setTimeout(()=>{r.abort(),n(new Error("auth-refresh-timeout"))},t),o.unref?.()});try{return await Promise.race([e(r.signal),i])}finally{o&&clearTimeout(o)}}function f(e){return typeof e=="string"&&Number.isFinite(Date.parse(e))}function l(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function m(e,t,r=!1){const o=Object.keys(e).sort();return(r?t.slice(0,-1):t).every(s=>o.includes(s))&&o.every(s=>t.includes(s))}export{K as EncryptedAuthGenerationStore,F as classifyAuthCausalEvidence,G as completeAuthRecovery,J as createAuthIdentityHash,R as decideAuthBusinessReplay,P as newRecoveryId,U as recoverHostAuthentication,B as reserveAuthBusinessReplay,d as validateAuthGenerationDocument};
1
+ import { createHash, randomUUID } from 'node:crypto';
2
+ /** Private generation adapter backed by EncryptedCache's mandatory CAS path. */
3
+ export class EncryptedAuthGenerationStore {
4
+ cache;
5
+ constructor(cache) {
6
+ this.cache = cache;
7
+ }
8
+ key(identityHash) {
9
+ if (!HASH.test(identityHash))
10
+ throw new Error('auth-business-identity-mismatch');
11
+ return `neocortex:auth-generation:v1:${identityHash}`;
12
+ }
13
+ async read(identityHash) {
14
+ const raw = await this.cache.getAuthoritative(this.key(identityHash));
15
+ if (raw === null)
16
+ return null;
17
+ try {
18
+ return validateAuthGenerationDocument(JSON.parse(raw), identityHash);
19
+ }
20
+ catch (error) {
21
+ throw new Error('auth-generation-corrupt', { cause: error });
22
+ }
23
+ }
24
+ async compareAndSet(expectedRevision, document) {
25
+ validateAuthGenerationDocument(document, document.identityHash);
26
+ const key = this.key(document.identityHash);
27
+ const current = await this.cache.getAuthoritative(key);
28
+ let currentRevision = 0;
29
+ if (current !== null) {
30
+ try {
31
+ currentRevision = validateAuthGenerationDocument(JSON.parse(current), document.identityHash).revision;
32
+ }
33
+ catch (error) {
34
+ throw new Error('auth-generation-corrupt', { cause: error });
35
+ }
36
+ }
37
+ if (currentRevision !== expectedRevision || document.revision !== expectedRevision + 1) {
38
+ throw new Error('auth-generation-revision-conflict');
39
+ }
40
+ await this.cache.setAuthoritative(key, JSON.stringify(document), {
41
+ expectedPlaintextSha256: current === null ? null : createHash('sha256').update(current).digest('hex'),
42
+ });
43
+ }
44
+ }
45
+ const HASH = /^[a-f0-9]{64}$/;
46
+ const ID = /^[A-Za-z0-9._:-]{1,128}$/;
47
+ export function createAuthIdentityHash(parts) {
48
+ if (parts.length !== 5 || parts.some((part) => part.length === 0 || part.length > 256 || /[\r\n\0]/.test(part))) {
49
+ throw new Error('auth-business-identity-mismatch');
50
+ }
51
+ return createHash('sha256').update('neocortex-auth-generation-v1\0').update(parts.join('\0')).digest('hex');
52
+ }
53
+ export function validateAuthGenerationDocument(value, expectedIdentityHash) {
54
+ let encoded;
55
+ try {
56
+ encoded = JSON.stringify(value);
57
+ }
58
+ catch {
59
+ throw new Error('auth-generation-corrupt');
60
+ }
61
+ if (!isRecord(value) || typeof encoded !== 'string')
62
+ throw new Error('auth-generation-corrupt');
63
+ if (Buffer.byteLength(encoded, 'utf8') > 256 * 1024)
64
+ throw new Error('auth-generation-capacity');
65
+ const doc = value;
66
+ if (doc.schemaVersion !== 'AuthGeneration/1.0' || !Number.isSafeInteger(doc.revision) || doc.revision < 0
67
+ || !HASH.test(doc.identityHash) || (expectedIdentityHash && doc.identityHash !== expectedIdentityHash)
68
+ || !Array.isArray(doc.receipts) || doc.receipts.length > 32)
69
+ throw new Error('auth-generation-corrupt');
70
+ if (!hasExactKeys(value, ['schemaVersion', 'revision', 'identityHash', 'accepted', 'activeRecovery', 'receipts'])) {
71
+ throw new Error('auth-generation-corrupt');
72
+ }
73
+ validateAcceptedGeneration(doc.accepted);
74
+ validateRecoveryJournal(doc.activeRecovery);
75
+ for (const receipt of doc.receipts)
76
+ validateRecoveryReceipt(receipt);
77
+ return doc;
78
+ }
79
+ function emptyDocument(identityHash) {
80
+ return { schemaVersion: 'AuthGeneration/1.0', revision: 0, identityHash, accepted: null, activeRecovery: null, receipts: [] };
81
+ }
82
+ async function commit(store, previous, patch) {
83
+ const next = validateAuthGenerationDocument({ ...previous, ...patch, revision: previous.revision + 1 }, previous.identityHash);
84
+ await store.compareAndSet(previous.revision, next);
85
+ return next;
86
+ }
87
+ export async function recoverHostAuthentication(store, input) {
88
+ if (!HASH.test(input.identityHash) || !HASH.test(input.requestDigest)
89
+ || ![input.recoveryId, input.operationId, input.idempotencyKey, input.owner].every((id) => ID.test(id))) {
90
+ return { status: 'refresh-required', cause: 'protocol-invalid', action: 'stop' };
91
+ }
92
+ const now = input.now ?? Date.now;
93
+ const leaseMs = Math.min(Math.max(input.leaseMs ?? 30_000, 1), 60_000);
94
+ const timeoutMs = Math.min(Math.max(input.timeoutMs ?? 30_000, 1), 30_000);
95
+ let document;
96
+ try {
97
+ document = validateAuthGenerationDocument(await store.read(input.identityHash) ?? emptyDocument(input.identityHash), input.identityHash);
98
+ }
99
+ catch (error) {
100
+ return storeFailureResult(error);
101
+ }
102
+ const active = document.activeRecovery;
103
+ if (active) {
104
+ if (active.recoveryId === input.recoveryId) {
105
+ if (!sameRecoveryBinding(active, input)) {
106
+ return { status: 'refresh-required', cause: 'protocol-invalid', action: 'stop' };
107
+ }
108
+ if ((active.phase === 'generation-committed' || active.phase === 'completed') && document.accepted) {
109
+ return authenticatedResult(document.accepted);
110
+ }
111
+ if (active.attemptCount === 1) {
112
+ return uncertainResult(input.recoveryId, active.phase === 'response-received' ? 'persistence-failed' : 'rotation-uncertain');
113
+ }
114
+ if (Date.parse(active.expiresAt) > now() && active.owner !== input.owner) {
115
+ return { status: 'refresh-required', cause: 'revision-conflict', action: 'retry-later' };
116
+ }
117
+ }
118
+ else {
119
+ if (active.attemptCount === 1
120
+ && !['generation-committed', 'completed', 'aborted-before-request'].includes(active.phase)) {
121
+ return uncertainResult(active.recoveryId, active.phase === 'response-received' ? 'persistence-failed' : 'rotation-uncertain');
122
+ }
123
+ if (active.phase === 'generation-committed') {
124
+ return { status: 'refresh-required', cause: 'revision-conflict', action: 'retry-later' };
125
+ }
126
+ if (active.attemptCount === 0 && Date.parse(active.expiresAt) > now()) {
127
+ return { status: 'refresh-required', cause: 'revision-conflict', action: 'retry-later' };
128
+ }
129
+ }
130
+ }
131
+ const baseJournal = {
132
+ recoveryId: input.recoveryId, operationId: input.operationId, idempotencyKey: input.idempotencyKey,
133
+ requestDigest: input.requestDigest, owner: input.owner, createdAt: new Date(now()).toISOString(),
134
+ expiresAt: new Date(now() + leaseMs).toISOString(), attemptCount: 0, replayCount: 0, phase: 'prepared',
135
+ };
136
+ try {
137
+ if (!active || active.recoveryId !== input.recoveryId || active.owner !== input.owner
138
+ || active.phase !== 'prepared') {
139
+ document = await commit(store, document, { activeRecovery: baseJournal });
140
+ }
141
+ const started = { ...baseJournal, attemptCount: 1, phase: 'request-started' };
142
+ document = await commit(store, document, { activeRecovery: started });
143
+ let response;
144
+ try {
145
+ response = await boundedRefresh(input.refresh, timeoutMs);
146
+ }
147
+ catch {
148
+ await persistUncertainBestEffort(store, document, started);
149
+ return uncertainResult(input.recoveryId, 'rotation-uncertain');
150
+ }
151
+ if (!response.token || response.token.length > 65_536 || !Number.isFinite(Date.parse(response.expiresAt))) {
152
+ await persistUncertainBestEffort(store, document, started);
153
+ return uncertainResult(input.recoveryId, 'rotation-uncertain');
154
+ }
155
+ const responseDigest = createHash('sha256').update(JSON.stringify(response)).digest('hex');
156
+ const received = { ...started, phase: 'response-received', responseDigest };
157
+ document = await commit(store, document, { activeRecovery: received });
158
+ const generation = (document.accepted?.generation ?? 0) + 1;
159
+ const accepted = {
160
+ generation, accessToken: response.token, accessExpiresAt: response.expiresAt,
161
+ refreshToken: response.refreshToken ?? null, refreshExpiresAt: response.refreshExpiresAt ?? null,
162
+ acceptedAt: new Date(now()).toISOString(), responseDigest,
163
+ };
164
+ const committed = { ...received, phase: 'generation-committed' };
165
+ const finalDocument = await commit(store, document, { accepted, activeRecovery: committed });
166
+ return authenticatedResult(finalDocument.accepted);
167
+ }
168
+ catch (error) {
169
+ if (document.activeRecovery?.attemptCount !== 1)
170
+ return storeFailureResult(error);
171
+ return uncertainResult(input.recoveryId, 'persistence-failed');
172
+ }
173
+ }
174
+ export function decideAuthBusinessReplay(input) {
175
+ if (!input.identityMatches || !input.requestMatches)
176
+ return { kind: 'stop', reasonCode: 'auth-business-identity-mismatch' };
177
+ if (input.rotationUncertain || !input.generationCommitted)
178
+ return { kind: 'stop', reasonCode: 'auth-business-replay-unsafe' };
179
+ if (input.replayCount !== 0)
180
+ return { kind: 'stop', reasonCode: 'auth-business-replay-exhausted' };
181
+ if (input.receipt === 'accepted')
182
+ return { kind: 'reconcile-receipt', operationId: input.operationId };
183
+ if (input.receipt === 'unknown' && !input.supportsIdempotency)
184
+ return { kind: 'reconcile-receipt', operationId: input.operationId };
185
+ return { kind: 'replay-once', recoveryId: input.recoveryId };
186
+ }
187
+ /**
188
+ * Reserves the single business replay by CAS before returning authorization.
189
+ * Consumers perform the business effect only after this function succeeds.
190
+ */
191
+ export async function reserveAuthBusinessReplay(store, input) {
192
+ let document;
193
+ try {
194
+ document = validateAuthGenerationDocument(await store.read(input.identityHash), input.identityHash);
195
+ }
196
+ catch {
197
+ return { kind: 'stop', reasonCode: 'auth-business-replay-unsafe' };
198
+ }
199
+ const recovery = document.activeRecovery;
200
+ if (!recovery || recovery.recoveryId !== input.recoveryId || recovery.operationId !== input.operationId) {
201
+ return { kind: 'stop', reasonCode: 'auth-business-identity-mismatch' };
202
+ }
203
+ const decision = decideAuthBusinessReplay({
204
+ recoveryId: input.recoveryId,
205
+ operationId: input.operationId,
206
+ generationCommitted: recovery.phase === 'generation-committed' && document.accepted !== null,
207
+ identityMatches: document.identityHash === input.identityHash,
208
+ requestMatches: recovery.requestDigest === input.requestDigest,
209
+ replayCount: recovery.replayCount,
210
+ receipt: input.receipt,
211
+ supportsIdempotency: input.supportsIdempotency,
212
+ rotationUncertain: input.rotationUncertain === true || recovery.phase === 'uncertain',
213
+ });
214
+ if (decision.kind !== 'replay-once')
215
+ return decision;
216
+ try {
217
+ await commit(store, document, { activeRecovery: { ...recovery, replayCount: 1 } });
218
+ return decision;
219
+ }
220
+ catch {
221
+ return { kind: 'stop', reasonCode: 'auth-generation-revision-conflict' };
222
+ }
223
+ }
224
+ /** Records the compare-bound business outcome before a later recovery may replace the journal. */
225
+ export async function completeAuthRecovery(store, input) {
226
+ if (!HASH.test(input.identityHash) || ![input.recoveryId, input.operationId, input.outcome].every((id) => ID.test(id))) {
227
+ throw new Error('auth-business-identity-mismatch');
228
+ }
229
+ const document = validateAuthGenerationDocument(await store.read(input.identityHash), input.identityHash);
230
+ const recovery = document.activeRecovery;
231
+ if (!recovery || recovery.recoveryId !== input.recoveryId || recovery.operationId !== input.operationId) {
232
+ throw new Error('auth-business-identity-mismatch');
233
+ }
234
+ const prior = document.receipts.find((receipt) => receipt.recoveryId === input.recoveryId);
235
+ if (prior) {
236
+ if (prior.operationId !== input.operationId || prior.outcome !== input.outcome) {
237
+ throw new Error('auth-business-identity-mismatch');
238
+ }
239
+ return document;
240
+ }
241
+ if (recovery.phase !== 'generation-committed' || document.accepted === null) {
242
+ throw new Error('auth-business-replay-unsafe');
243
+ }
244
+ if (document.receipts.length >= 32)
245
+ throw new Error('auth-generation-capacity');
246
+ const completedAt = input.completedAt ?? new Date().toISOString();
247
+ if (!validTimestamp(completedAt))
248
+ throw new Error('auth-business-identity-mismatch');
249
+ return commit(store, document, {
250
+ activeRecovery: { ...recovery, phase: 'completed' },
251
+ receipts: [...document.receipts, {
252
+ recoveryId: input.recoveryId,
253
+ operationId: input.operationId,
254
+ outcome: input.outcome,
255
+ completedAt,
256
+ }],
257
+ });
258
+ }
259
+ /** Pure evidence-to-cause mapping. Generic HTTP status never proves revocation. */
260
+ export function classifyAuthCausalEvidence(evidence) {
261
+ switch (evidence.kind) {
262
+ case 'token': {
263
+ const now = evidence.now ?? Date.now();
264
+ const expiresAt = Date.parse(evidence.expiresAt);
265
+ if (!Number.isFinite(expiresAt))
266
+ return { status: 'refresh-required', cause: 'protocol-invalid', action: 'stop' };
267
+ if (expiresAt <= now)
268
+ return { status: 'refresh-required', cause: 'expired', action: 'prepare' };
269
+ if (expiresAt - now <= 300_000)
270
+ return { status: 'refresh-required', cause: 'near-expiry', action: 'prepare' };
271
+ return { status: 'authenticated', generation: evidence.generation, accessCredential: evidence.credential, expiresAt: evidence.expiresAt };
272
+ }
273
+ case 'configuration':
274
+ return evidence.configured
275
+ ? { status: 'refresh-required', cause: 'store-unavailable', action: 'stop' }
276
+ : { status: 'not-configured', action: 'activate' };
277
+ case 'store':
278
+ return { status: 'refresh-required', cause: evidence.cause, action: evidence.cause === 'store-unavailable' ? 'retry-later' : 'stop' };
279
+ case 'transport':
280
+ if (evidence.requestStarted)
281
+ return uncertainResult(evidence.recoveryId ?? 'unknown-recovery', 'rotation-uncertain');
282
+ return { status: 'refresh-required', cause: evidence.timeout ? 'timeout' : 'transport-error', action: 'retry-later' };
283
+ case 'http': {
284
+ const code = evidence.errorCode ?? '';
285
+ if (evidence.status === 429)
286
+ return { status: 'refresh-required', cause: 'rate-limited', action: 'retry-later' };
287
+ if (evidence.status >= 500)
288
+ return { status: 'refresh-required', cause: 'service-unavailable', action: 'retry-later' };
289
+ if (code === 'invalid_grant' || code === 'revoked')
290
+ return { status: 'refresh-required', cause: 'revoked', action: 'reactivate' };
291
+ if (code === 'invalid_scope' || code === 'scope_denied')
292
+ return { status: 'refresh-required', cause: 'scope-denied', action: 'request-scope' };
293
+ if (code === 'client_denied')
294
+ return { status: 'refresh-required', cause: 'client-denied', action: 'stop' };
295
+ return { status: 'refresh-required', cause: 'protocol-invalid', action: 'stop' };
296
+ }
297
+ case 'persistence':
298
+ return uncertainResult(evidence.recoveryId, 'persistence-failed');
299
+ }
300
+ }
301
+ export function newRecoveryId() { return randomUUID(); }
302
+ function validateAcceptedGeneration(accepted) {
303
+ if (accepted === null)
304
+ return;
305
+ if (!isRecord(accepted) || !hasExactKeys(accepted, [
306
+ 'generation', 'accessToken', 'accessExpiresAt', 'refreshToken', 'refreshExpiresAt',
307
+ 'acceptedAt', 'responseDigest',
308
+ ]))
309
+ throw new Error('auth-generation-corrupt');
310
+ if (!Number.isSafeInteger(accepted.generation) || accepted.generation < 1
311
+ || typeof accepted.accessToken !== 'string' || accepted.accessToken.length === 0
312
+ || accepted.accessToken.length > 65_536
313
+ || (accepted.refreshToken !== null && (typeof accepted.refreshToken !== 'string' || accepted.refreshToken.length > 65_536))
314
+ || !validTimestamp(accepted.accessExpiresAt) || !validTimestamp(accepted.acceptedAt)
315
+ || (accepted.refreshExpiresAt !== null && !validTimestamp(accepted.refreshExpiresAt))
316
+ || !HASH.test(accepted.responseDigest))
317
+ throw new Error('auth-generation-corrupt');
318
+ }
319
+ function validateRecoveryJournal(journal) {
320
+ if (journal === null)
321
+ return;
322
+ if (!isRecord(journal) || !hasExactKeys(journal, [
323
+ 'recoveryId', 'operationId', 'idempotencyKey', 'requestDigest', 'owner', 'createdAt',
324
+ 'expiresAt', 'attemptCount', 'replayCount', 'phase', 'responseDigest',
325
+ ], true))
326
+ throw new Error('auth-generation-corrupt');
327
+ const phases = ['prepared', 'request-started', 'response-received',
328
+ 'generation-committed', 'uncertain', 'completed', 'aborted-before-request'];
329
+ if (![journal.recoveryId, journal.operationId, journal.idempotencyKey, journal.owner].every((id) => ID.test(id))
330
+ || !HASH.test(journal.requestDigest) || !validTimestamp(journal.createdAt) || !validTimestamp(journal.expiresAt)
331
+ || ![0, 1].includes(journal.attemptCount) || ![0, 1].includes(journal.replayCount)
332
+ || !phases.includes(journal.phase)
333
+ || (journal.responseDigest !== undefined && !HASH.test(journal.responseDigest))) {
334
+ throw new Error('auth-generation-corrupt');
335
+ }
336
+ }
337
+ function validateRecoveryReceipt(receipt) {
338
+ if (!isRecord(receipt) || !hasExactKeys(receipt, ['recoveryId', 'operationId', 'outcome', 'completedAt'])
339
+ || !ID.test(receipt.recoveryId) || !ID.test(receipt.operationId) || !ID.test(receipt.outcome)
340
+ || !validTimestamp(receipt.completedAt))
341
+ throw new Error('auth-generation-corrupt');
342
+ }
343
+ function sameRecoveryBinding(journal, input) {
344
+ return journal.operationId === input.operationId
345
+ && journal.idempotencyKey === input.idempotencyKey
346
+ && journal.requestDigest === input.requestDigest;
347
+ }
348
+ function authenticatedResult(accepted) {
349
+ return {
350
+ status: 'authenticated', generation: accepted.generation,
351
+ accessCredential: accepted.accessToken, expiresAt: accepted.accessExpiresAt,
352
+ };
353
+ }
354
+ function uncertainResult(recoveryId, cause) {
355
+ return { status: 'uncertain', cause, recoveryId, action: 'recover-explicitly' };
356
+ }
357
+ function storeFailureResult(error) {
358
+ const message = error instanceof Error ? error.message : '';
359
+ if (message === 'auth-generation-revision-conflict' || message === 'auth-recovery-backpressure') {
360
+ return { status: 'refresh-required', cause: 'revision-conflict', action: 'retry-later' };
361
+ }
362
+ if (message === 'auth-generation-corrupt' || message === 'auth-generation-path-unsafe') {
363
+ return { status: 'refresh-required', cause: 'store-corrupt', action: 'stop' };
364
+ }
365
+ return { status: 'refresh-required', cause: 'store-unavailable', action: 'retry-later' };
366
+ }
367
+ async function persistUncertainBestEffort(store, document, started) {
368
+ try {
369
+ await commit(store, document, { activeRecovery: { ...started, phase: 'uncertain' } });
370
+ }
371
+ catch { /* the durable request-started phase remains the fail-closed authority */ }
372
+ }
373
+ async function boundedRefresh(refresh, timeoutMs) {
374
+ const controller = new AbortController();
375
+ let timer;
376
+ const timeout = new Promise((_resolve, reject) => {
377
+ timer = setTimeout(() => {
378
+ controller.abort();
379
+ reject(new Error('auth-refresh-timeout'));
380
+ }, timeoutMs);
381
+ timer.unref?.();
382
+ });
383
+ try {
384
+ return await Promise.race([refresh(controller.signal), timeout]);
385
+ }
386
+ finally {
387
+ if (timer)
388
+ clearTimeout(timer);
389
+ }
390
+ }
391
+ function validTimestamp(value) {
392
+ return typeof value === 'string' && Number.isFinite(Date.parse(value));
393
+ }
394
+ function isRecord(value) {
395
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
396
+ }
397
+ function hasExactKeys(value, allowed, optionalLast = false) {
398
+ const keys = Object.keys(value).sort();
399
+ const required = optionalLast ? allowed.slice(0, -1) : allowed;
400
+ return required.every((key) => keys.includes(key)) && keys.every((key) => allowed.includes(key));
401
+ }
@@ -1 +1,5 @@
1
- import{LicenseClient as n}from"./license-client.js";export{n as LicenseClient};
1
+ /**
2
+ * @license FSL-1.1
3
+ * Copyright (c) 2026 OrNexus AI
4
+ */
5
+ export { LicenseClient } from './license-client.js';