@ornexus/neocortex 4.60.78 → 4.60.79
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/release-source.json +1 -1
- package/dist/sbom.cdx.json +1193 -1206
- package/install.ps1 +1 -1
- package/install.sh +1 -1
- package/package.json +2 -2
- package/packages/client/dist/adapters/adapter-registry.js +108 -1
- package/packages/client/dist/adapters/antigravity-adapter.js +77 -2
- package/packages/client/dist/adapters/claude-code-adapter.js +79 -3
- package/packages/client/dist/adapters/codex-adapter.js +80 -2
- package/packages/client/dist/adapters/cursor-adapter.js +115 -4
- package/packages/client/dist/adapters/gemini-adapter.js +71 -2
- package/packages/client/dist/adapters/grok-adapter.js +42 -2
- package/packages/client/dist/adapters/index.js +22 -1
- package/packages/client/dist/adapters/platform-detector.js +214 -1
- package/packages/client/dist/adapters/target-adapter.js +12 -0
- package/packages/client/dist/adapters/vscode-adapter.js +72 -2
- package/packages/client/dist/agent/refresh-stubs.js +443 -2
- package/packages/client/dist/agent/update-agent-yaml.js +102 -1
- package/packages/client/dist/agent/update-description.js +260 -1
- package/packages/client/dist/cache/crypto-utils.js +78 -1
- package/packages/client/dist/cache/encrypted-cache.js +338 -1
- package/packages/client/dist/cache/in-memory-asset-cache.js +73 -1
- package/packages/client/dist/cache/index.js +13 -1
- package/packages/client/dist/cache/protected-pi-boundary.js +44 -1
- package/packages/client/dist/checkpoint/checkpoint-client-reader.js +127 -2
- package/packages/client/dist/checkpoint/index.js +11 -1
- package/packages/client/dist/checkpoint/shared-checkpoint-types.js +32 -1
- package/packages/client/dist/cli.js +358 -5
- package/packages/client/dist/commands/activate.js +394 -8
- package/packages/client/dist/commands/architecture-answers.js +274 -7
- package/packages/client/dist/commands/architecture-memory-terminal.js +253 -4
- package/packages/client/dist/commands/architecture-non-ui-continuation.js +100 -1
- package/packages/client/dist/commands/architecture-root-binding.js +51 -1
- package/packages/client/dist/commands/cache-status.js +112 -2
- package/packages/client/dist/commands/config.js +88 -1
- package/packages/client/dist/commands/doctor.js +635 -2
- package/packages/client/dist/commands/invoke.js +7712 -143
- package/packages/client/dist/commands/legacy-epic-terminal.js +71 -1
- package/packages/client/dist/commands/legacy-story-branch.js +96 -1
- package/packages/client/dist/commands/legacy-story-pr.js +276 -1
- package/packages/client/dist/commands/mutation-qa-checkpoint.js +285 -5
- package/packages/client/dist/commands/mutation-qa-gate.js +54 -1
- package/packages/client/dist/commands/mutation-qa-git.js +41 -1
- package/packages/client/dist/commands/mutation-qa-policy.js +102 -1
- package/packages/client/dist/commands/mutation-qa-run.js +219 -3
- package/packages/client/dist/commands/mutation-qa-verdict.js +149 -1
- package/packages/client/dist/commands/mutation-qa.js +220 -1
- package/packages/client/dist/commands/native-agent.js +136 -2
- package/packages/client/dist/commands/planning-diagnosis.js +43 -1
- package/packages/client/dist/commands/planning-generation.js +53 -1
- package/packages/client/dist/commands/planning-memory.js +40 -1
- package/packages/client/dist/commands/planning-research.js +42 -1
- package/packages/client/dist/commands/private-session.js +75 -1
- package/packages/client/dist/commands/property-qa.js +139 -1
- package/packages/client/dist/commands/qa-control.js +16 -1
- package/packages/client/dist/commands/qa-scan-browser-launch.js +55 -1
- package/packages/client/dist/commands/qa-scan-browser-route.js +28 -1
- package/packages/client/dist/commands/qa-scan-capture.js +663 -5
- package/packages/client/dist/commands/qa-scan-discovery.js +376 -3
- package/packages/client/dist/commands/qa-scan-review.js +826 -5
- package/packages/client/dist/commands/qa-synthetic-backend-capture.js +266 -1
- package/packages/client/dist/commands/qa-synthetic-backend-review.js +297 -1
- package/packages/client/dist/commands/qa-synthetic-backend.js +340 -2
- package/packages/client/dist/commands/qa-synthetic-broker-port.js +85 -1
- package/packages/client/dist/commands/qa-synthetic-browser.js +39 -1
- package/packages/client/dist/commands/refactor-characterization.js +671 -21
- package/packages/client/dist/commands/refactor-commit.js +399 -13
- package/packages/client/dist/commands/refactor-control.js +142 -3
- package/packages/client/dist/commands/refactor-cpp-assertions.js +93 -3
- package/packages/client/dist/commands/refactor-review.js +283 -5
- package/packages/client/dist/commands/refactor-root.js +588 -7
- package/packages/client/dist/commands/refresh-memory.js +159 -3
- package/packages/client/dist/commands/shared-architecture-non-ui.js +24 -1
- package/packages/client/dist/commands/story-checkpoint.js +171 -1
- package/packages/client/dist/config/host-auth-broker.js +60 -1
- package/packages/client/dist/config/host-auth-reference.js +93 -1
- package/packages/client/dist/config/profile-directory.js +13 -1
- package/packages/client/dist/config/resolver-selection.js +278 -1
- package/packages/client/dist/config/secure-config.js +281 -12
- package/packages/client/dist/config.js +223 -2
- package/packages/client/dist/constants.js +25 -1
- package/packages/client/dist/context/context-collector.js +222 -2
- package/packages/client/dist/context/context-sanitizer.js +145 -1
- package/packages/client/dist/continuity/autonomous-governance.js +285 -1
- package/packages/client/dist/continuity/continuity-client-state-store.js +1587 -1
- package/packages/client/dist/continuity/invoke-hooks.js +129 -1
- package/packages/client/dist/continuity/migrations/001-initial-schema.js +12 -2
- package/packages/client/dist/continuity/migrations/002-processing-output-summary-indexes.js +12 -2
- package/packages/client/dist/continuity/migrations/003-headless-execution-attempts.js +12 -2
- package/packages/client/dist/continuity/migrations/004-outbox-delivery-state.js +12 -2
- package/packages/client/dist/continuity/migrations/005-bounded-headless-queue.js +12 -2
- package/packages/client/dist/continuity/migrations/006-native-agent-dispatches.js +10 -2
- package/packages/client/dist/continuity/native-agent-store.js +69 -1
- package/packages/client/dist/continuity/native-agent-types.js +105 -1
- package/packages/client/dist/continuity/outbox.js +117 -1
- package/packages/client/dist/continuity/runner-bootstrap-policy.js +172 -1
- package/packages/client/dist/continuity/sqlite-store.js +2612 -81
- package/packages/client/dist/effects/invoke-effect-gateways.js +62 -1
- package/packages/client/dist/errors/error-messages.js +258 -2
- package/packages/client/dist/errors/frontmatter-diagnostics.js +125 -1
- package/packages/client/dist/evidence/collector.js +347 -1
- package/packages/client/dist/evidence/index.js +1 -1
- package/packages/client/dist/evidence/types.js +2 -0
- package/packages/client/dist/fs/atomic-state-replace.js +152 -1
- package/packages/client/dist/generated/command-registry.generated.js +4076 -1
- package/packages/client/dist/generated/public-projections.generated.js +149 -1
- package/packages/client/dist/git/direct-yolo-c01-retry.js +138 -4
- package/packages/client/dist/git/direct-yolo-checkpoint.js +1341 -4
- package/packages/client/dist/git/epic-operational-state.js +672 -2
- package/packages/client/dist/git/git-lifecycle-step-ids.js +14 -1
- package/packages/client/dist/git/git-lifecycle-store.js +2185 -10
- package/packages/client/dist/git/legacy-story-branch-checkpoint.js +259 -9
- package/packages/client/dist/git/legacy-story-branch-setup.js +348 -4
- package/packages/client/dist/git/legacy-story-pr.js +3538 -70
- package/packages/client/dist/git/secure-filesystem-boundary.js +182 -5
- package/packages/client/dist/graph-retrieval/pre-command-hook.js +284 -1
- package/packages/client/dist/graph-retrieval/shared-graph-retrieval-contract.js +237 -1
- package/packages/client/dist/i18n/first-run.js +60 -2
- package/packages/client/dist/index.js +50 -1
- package/packages/client/dist/invocation/invoke-input.js +24 -1
- package/packages/client/dist/license/host-auth-recovery.js +401 -1
- package/packages/client/dist/license/index.js +5 -1
- package/packages/client/dist/license/license-client.js +337 -1
- package/packages/client/dist/machine/fingerprint.js +163 -2
- package/packages/client/dist/machine/index.js +5 -1
- package/packages/client/dist/memory/project-memory-path-scope.js +62 -1
- package/packages/client/dist/memory/project-memory-writer.js +1067 -41
- package/packages/client/dist/memory/shared-project-memory-types.js +259 -2
- package/packages/client/dist/migrations/epic-lifecycle-backfill.js +1060 -3
- package/packages/client/dist/migrations/project-identity-capability.js +50 -1
- package/packages/client/dist/migrations/project-identity.js +493 -7
- package/packages/client/dist/migrations/state-json.js +393 -4
- package/packages/client/dist/policy/architecture-policy.js +184 -2
- package/packages/client/dist/policy/index.js +7 -1
- package/packages/client/dist/policy/shared-policy-types.js +38 -0
- package/packages/client/dist/policy/subagent-approval-policy.js +55 -1
- package/packages/client/dist/private-execution/clean-baseline.js +279 -2
- package/packages/client/dist/private-execution/codex-executor.js +574 -4
- package/packages/client/dist/private-execution/codex-host-runtime.js +137 -1
- package/packages/client/dist/private-execution/codex-lifecycle-guard.js +97 -1
- package/packages/client/dist/private-execution/codex-scoped-permissions.js +128 -1
- package/packages/client/dist/private-execution/delivery.js +410 -13
- package/packages/client/dist/private-execution/diagnosis-root-review.js +294 -2
- package/packages/client/dist/private-execution/frozen-handoff.js +19 -6
- package/packages/client/dist/private-execution/implementation-validation.js +106 -2
- package/packages/client/dist/private-execution/isolated-admission.js +1432 -23
- package/packages/client/dist/private-execution/isolated-session.js +725 -5
- package/packages/client/dist/private-execution/isolated-workspace.js +122 -1
- package/packages/client/dist/private-execution/pact-consumer-runtime.js +409 -3
- package/packages/client/dist/private-execution/pact-test-source.js +258 -1
- package/packages/client/dist/private-execution/pact-toolchain.js +290 -3
- package/packages/client/dist/private-execution/pact-write-set.js +172 -1
- package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.js +406 -5
- package/packages/client/dist/private-execution/planning-generation-checkpoint.js +462 -5
- package/packages/client/dist/private-execution/planning-memory-checkpoint.js +139 -3
- package/packages/client/dist/private-execution/planning-research-checkpoint.js +325 -4
- package/packages/client/dist/private-execution/private-report-store.js +42 -1
- package/packages/client/dist/private-execution/property-test-candidate.js +103 -1
- package/packages/client/dist/private-execution/property-test-choices.js +147 -3
- package/packages/client/dist/private-execution/property-test-plan.js +271 -7
- package/packages/client/dist/private-execution/property-test-review.js +258 -4
- package/packages/client/dist/private-execution/property-test-runtime.js +372 -9
- package/packages/client/dist/private-execution/property-test-source.js +139 -1
- package/packages/client/dist/private-execution/root-checkpoint.js +80 -1
- package/packages/client/dist/private-execution/root-memory-git-evidence.js +135 -3
- package/packages/client/dist/private-execution/root-memory-recovery.js +93 -1
- package/packages/client/dist/private-execution/root-memory-request.js +29 -1
- package/packages/client/dist/private-execution/root-memory-scope.js +178 -1
- package/packages/client/dist/private-execution/root-memory-writer.js +102 -1
- package/packages/client/dist/private-execution/session-lease.js +63 -1
- package/packages/client/dist/private-execution/shared-private-admission-types.js +50 -1
- package/packages/client/dist/private-execution/shared-project-validation.js +66 -1
- package/packages/client/dist/private-execution/shared-root-memory-types.js +61 -1
- package/packages/client/dist/private-execution/ux-source-validation.js +372 -1
- package/packages/client/dist/private-execution/ux-write-set.js +191 -2
- package/packages/client/dist/registry/registry-reconciliation.js +234 -1
- package/packages/client/dist/resilience/circuit-breaker.js +170 -1
- package/packages/client/dist/resilience/degradation-manager.js +164 -1
- package/packages/client/dist/resilience/freshness-indicator.js +100 -1
- package/packages/client/dist/resilience/index.js +8 -1
- package/packages/client/dist/resilience/recovery-detector.js +74 -1
- package/packages/client/dist/resolvers/asset-resolver.js +13 -0
- package/packages/client/dist/resolvers/local-resolver.js +255 -8
- package/packages/client/dist/resolvers/remote-resolver.js +233 -1
- package/packages/client/dist/runner/binary.js +404 -1
- package/packages/client/dist/runner/cli.js +1571 -17
- package/packages/client/dist/runner/epic-background-dispatcher.js +124 -1
- package/packages/client/dist/runner/headless/adapters.js +49 -1
- package/packages/client/dist/runner/headless/background-root.js +85 -1
- package/packages/client/dist/runner/headless/claude-code-adapter.js +79 -1
- package/packages/client/dist/runner/headless/continuous-story-workspace.js +1628 -11
- package/packages/client/dist/runner/headless/epic-git-reconciliation-inventory.js +69 -1
- package/packages/client/dist/runner/headless/epic-merge-candidate-qa.js +111 -2
- package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.js +1464 -10
- package/packages/client/dist/runner/headless/epic-terminal-git-runner.js +357 -2
- package/packages/client/dist/runner/headless/fake-adapter.js +62 -1
- package/packages/client/dist/runner/headless/managed-environment-cleanup.js +274 -1
- package/packages/client/dist/runner/headless/managed-profile.js +149 -1
- package/packages/client/dist/runner/headless/opencode-adapter.js +145 -2
- package/packages/client/dist/runner/headless/prepared-story-bundle.js +43 -1
- package/packages/client/dist/runner/headless/resolver.js +231 -1
- package/packages/client/dist/runner/headless/run-yolo.js +886 -1
- package/packages/client/dist/runner/headless/run-yoloop.js +2582 -2
- package/packages/client/dist/runner/headless/types.js +575 -2
- package/packages/client/dist/runner/host-capacity.js +59 -1
- package/packages/client/dist/runner/local-console.js +396 -13
- package/packages/client/dist/runner/portal-sync-worker.js +1487 -1
- package/packages/client/dist/runner/project-identity.js +106 -1
- package/packages/client/dist/runner/scheduler.js +995 -7
- package/packages/client/dist/runner-cli.js +18 -2
- package/packages/client/dist/state/invocation-shape.js +13 -1
- package/packages/client/dist/state/project-state-snapshot.js +1751 -1
- package/packages/client/dist/state/state-json-repair.js +785 -3
- package/packages/client/dist/state/structural-dag-projection.js +118 -1
- package/packages/client/dist/telemetry/index.js +5 -1
- package/packages/client/dist/telemetry/offline-queue.js +131 -1
- package/packages/client/dist/tier/index.js +5 -1
- package/packages/client/dist/tier/tier-aware-client.js +405 -1
- package/packages/client/dist/types/index.js +38 -1
- package/packages/client/dist/version.js +27 -1
- package/packages/client/dist/yolo/change-evidence-collector.js +222 -1
- package/packages/client/dist/yolo/invoke-envelope-capability.js +62 -1
- package/packages/client/dist/yolo/spec-envelope-collector.js +184 -5
- package/packages/client/dist/yoloop/discovery-hook.js +300 -2
- package/packages/client/dist/yoloop/index.js +8 -1
- package/packages/client/dist/yoloop/invoke-hooks.js +669 -12
- package/packages/client/dist/yoloop/shared-discover-epics.js +1007 -1
- package/packages/client/dist/yoloop/shared-yoloop-types.js +33 -1
- package/packages/client/dist/yoloop/target-normalization.js +180 -1
- package/packages/client/dist/yoloop/yoloop-client-state-store.js +1920 -1
- package/targets-stubs/antigravity/gemini.md +1 -1
- package/targets-stubs/antigravity/skill/SKILL.md +1 -1
- package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
- package/targets-stubs/claude-code/neocortex-root.md +2 -2
- package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
- package/targets-stubs/claude-code/neocortex.md +2 -2
- package/targets-stubs/codex/AGENTS.md +1 -1
- package/targets-stubs/cursor/agent.md +2 -2
- package/targets-stubs/gemini-cli/agent.md +2 -2
- package/targets-stubs/opencode/neocortex-root.md +1 -1
- 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
|
+
}
|