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