@ornexus/neocortex 4.60.73 → 4.60.75

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (269) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +1216 -1210
  3. package/install.ps1 +1 -1
  4. package/install.sh +1 -1
  5. package/package.json +2 -2
  6. package/packages/client/dist/adapters/adapter-registry.js +1 -108
  7. package/packages/client/dist/adapters/antigravity-adapter.js +2 -77
  8. package/packages/client/dist/adapters/claude-code-adapter.js +3 -79
  9. package/packages/client/dist/adapters/codex-adapter.js +2 -80
  10. package/packages/client/dist/adapters/cursor-adapter.js +4 -115
  11. package/packages/client/dist/adapters/gemini-adapter.js +2 -71
  12. package/packages/client/dist/adapters/grok-adapter.js +2 -42
  13. package/packages/client/dist/adapters/index.js +1 -22
  14. package/packages/client/dist/adapters/platform-detector.js +1 -212
  15. package/packages/client/dist/adapters/target-adapter.js +0 -12
  16. package/packages/client/dist/adapters/vscode-adapter.js +2 -72
  17. package/packages/client/dist/agent/refresh-stubs.js +2 -417
  18. package/packages/client/dist/agent/update-agent-yaml.js +1 -102
  19. package/packages/client/dist/agent/update-description.js +1 -251
  20. package/packages/client/dist/cache/crypto-utils.js +1 -78
  21. package/packages/client/dist/cache/encrypted-cache.d.ts +27 -0
  22. package/packages/client/dist/cache/encrypted-cache.js +1 -108
  23. package/packages/client/dist/cache/in-memory-asset-cache.js +1 -73
  24. package/packages/client/dist/cache/index.js +1 -13
  25. package/packages/client/dist/cache/protected-pi-boundary.js +1 -44
  26. package/packages/client/dist/checkpoint/checkpoint-client-reader.js +2 -127
  27. package/packages/client/dist/checkpoint/index.js +1 -11
  28. package/packages/client/dist/checkpoint/shared-checkpoint-types.js +1 -32
  29. package/packages/client/dist/cli.js +5 -358
  30. package/packages/client/dist/commands/activate.js +8 -394
  31. package/packages/client/dist/commands/architecture-answers.js +7 -274
  32. package/packages/client/dist/commands/architecture-memory-terminal.js +4 -253
  33. package/packages/client/dist/commands/architecture-non-ui-continuation.js +1 -100
  34. package/packages/client/dist/commands/architecture-root-binding.js +1 -51
  35. package/packages/client/dist/commands/cache-status.js +2 -112
  36. package/packages/client/dist/commands/config.js +1 -88
  37. package/packages/client/dist/commands/doctor.js +2 -635
  38. package/packages/client/dist/commands/invoke.d.ts +38 -1
  39. package/packages/client/dist/commands/invoke.js +143 -7200
  40. package/packages/client/dist/commands/legacy-epic-terminal.js +1 -71
  41. package/packages/client/dist/commands/legacy-story-branch.js +1 -96
  42. package/packages/client/dist/commands/legacy-story-pr.js +1 -276
  43. package/packages/client/dist/commands/mutation-qa-checkpoint.js +5 -285
  44. package/packages/client/dist/commands/mutation-qa-gate.js +1 -54
  45. package/packages/client/dist/commands/mutation-qa-git.js +1 -41
  46. package/packages/client/dist/commands/mutation-qa-policy.js +1 -102
  47. package/packages/client/dist/commands/mutation-qa-run.js +3 -219
  48. package/packages/client/dist/commands/mutation-qa-verdict.js +1 -149
  49. package/packages/client/dist/commands/mutation-qa.js +1 -220
  50. package/packages/client/dist/commands/native-agent.js +2 -136
  51. package/packages/client/dist/commands/planning-diagnosis.js +1 -43
  52. package/packages/client/dist/commands/planning-generation.js +1 -53
  53. package/packages/client/dist/commands/planning-memory.js +1 -40
  54. package/packages/client/dist/commands/planning-research.js +1 -42
  55. package/packages/client/dist/commands/private-session.js +1 -75
  56. package/packages/client/dist/commands/property-qa.js +1 -139
  57. package/packages/client/dist/commands/qa-control.js +1 -16
  58. package/packages/client/dist/commands/qa-scan-browser-launch.js +1 -55
  59. package/packages/client/dist/commands/qa-scan-browser-route.js +1 -28
  60. package/packages/client/dist/commands/qa-scan-capture.js +5 -663
  61. package/packages/client/dist/commands/qa-scan-discovery.js +3 -376
  62. package/packages/client/dist/commands/qa-scan-review.js +5 -826
  63. package/packages/client/dist/commands/qa-synthetic-backend-capture.js +1 -266
  64. package/packages/client/dist/commands/qa-synthetic-backend-review.js +1 -297
  65. package/packages/client/dist/commands/qa-synthetic-backend.js +2 -340
  66. package/packages/client/dist/commands/qa-synthetic-broker-port.js +1 -85
  67. package/packages/client/dist/commands/qa-synthetic-browser.js +1 -39
  68. package/packages/client/dist/commands/refactor-characterization.js +21 -671
  69. package/packages/client/dist/commands/refactor-commit.js +13 -399
  70. package/packages/client/dist/commands/refactor-control.js +3 -142
  71. package/packages/client/dist/commands/refactor-cpp-assertions.js +3 -93
  72. package/packages/client/dist/commands/refactor-review.js +5 -283
  73. package/packages/client/dist/commands/refactor-root.js +7 -588
  74. package/packages/client/dist/commands/refresh-memory.js +3 -156
  75. package/packages/client/dist/commands/shared-architecture-non-ui.js +1 -24
  76. package/packages/client/dist/commands/story-checkpoint.js +1 -171
  77. package/packages/client/dist/config/host-auth-broker.d.ts +31 -0
  78. package/packages/client/dist/config/host-auth-broker.js +1 -0
  79. package/packages/client/dist/config/host-auth-reference.d.ts +32 -0
  80. package/packages/client/dist/config/host-auth-reference.js +1 -0
  81. package/packages/client/dist/config/profile-directory.js +1 -13
  82. package/packages/client/dist/config/resolver-selection.js +1 -278
  83. package/packages/client/dist/config/secure-config.js +12 -281
  84. package/packages/client/dist/config.js +2 -223
  85. package/packages/client/dist/constants.js +1 -25
  86. package/packages/client/dist/context/context-collector.js +2 -222
  87. package/packages/client/dist/context/context-sanitizer.js +1 -145
  88. package/packages/client/dist/continuity/autonomous-governance.js +1 -285
  89. package/packages/client/dist/continuity/continuity-client-state-store.js +1 -1587
  90. package/packages/client/dist/continuity/invoke-hooks.js +1 -129
  91. package/packages/client/dist/continuity/migrations/001-initial-schema.js +2 -12
  92. package/packages/client/dist/continuity/migrations/002-processing-output-summary-indexes.js +2 -12
  93. package/packages/client/dist/continuity/migrations/003-headless-execution-attempts.js +2 -12
  94. package/packages/client/dist/continuity/migrations/004-outbox-delivery-state.js +2 -12
  95. package/packages/client/dist/continuity/migrations/005-bounded-headless-queue.js +2 -12
  96. package/packages/client/dist/continuity/migrations/006-native-agent-dispatches.js +2 -10
  97. package/packages/client/dist/continuity/native-agent-store.js +1 -69
  98. package/packages/client/dist/continuity/native-agent-types.d.ts +11 -0
  99. package/packages/client/dist/continuity/native-agent-types.js +1 -90
  100. package/packages/client/dist/continuity/outbox.js +1 -117
  101. package/packages/client/dist/continuity/runner-bootstrap-policy.js +1 -172
  102. package/packages/client/dist/continuity/sqlite-store.js +81 -2612
  103. package/packages/client/dist/effects/invoke-effect-gateways.js +1 -62
  104. package/packages/client/dist/errors/error-messages.d.ts +3 -0
  105. package/packages/client/dist/errors/error-messages.js +2 -228
  106. package/packages/client/dist/errors/frontmatter-diagnostics.js +1 -125
  107. package/packages/client/dist/evidence/collector.js +1 -347
  108. package/packages/client/dist/evidence/index.js +1 -1
  109. package/packages/client/dist/evidence/types.js +0 -2
  110. package/packages/client/dist/fs/atomic-state-replace.js +1 -152
  111. package/packages/client/dist/generated/command-registry.generated.js +1 -4076
  112. package/packages/client/dist/generated/public-projections.generated.js +1 -149
  113. package/packages/client/dist/git/direct-yolo-c01-retry.js +4 -138
  114. package/packages/client/dist/git/direct-yolo-checkpoint.d.ts +11 -1
  115. package/packages/client/dist/git/direct-yolo-checkpoint.js +4 -1234
  116. package/packages/client/dist/git/epic-operational-state.js +2 -672
  117. package/packages/client/dist/git/git-lifecycle-step-ids.js +1 -14
  118. package/packages/client/dist/git/git-lifecycle-store.d.ts +23 -0
  119. package/packages/client/dist/git/git-lifecycle-store.js +10 -1981
  120. package/packages/client/dist/git/legacy-story-branch-checkpoint.js +9 -259
  121. package/packages/client/dist/git/legacy-story-branch-setup.js +4 -348
  122. package/packages/client/dist/git/legacy-story-pr.js +70 -3538
  123. package/packages/client/dist/git/secure-filesystem-boundary.js +5 -182
  124. package/packages/client/dist/graph-retrieval/pre-command-hook.js +1 -284
  125. package/packages/client/dist/graph-retrieval/shared-graph-retrieval-contract.js +1 -237
  126. package/packages/client/dist/i18n/first-run.js +2 -60
  127. package/packages/client/dist/index.d.ts +2 -0
  128. package/packages/client/dist/index.js +1 -47
  129. package/packages/client/dist/invocation/invoke-input.js +1 -24
  130. package/packages/client/dist/license/host-auth-recovery.d.ts +158 -0
  131. package/packages/client/dist/license/host-auth-recovery.js +1 -0
  132. package/packages/client/dist/license/index.js +1 -5
  133. package/packages/client/dist/license/license-client.d.ts +10 -1
  134. package/packages/client/dist/license/license-client.js +1 -304
  135. package/packages/client/dist/machine/fingerprint.js +2 -163
  136. package/packages/client/dist/machine/index.js +1 -5
  137. package/packages/client/dist/memory/project-memory-path-scope.js +1 -62
  138. package/packages/client/dist/memory/project-memory-writer.js +40 -1007
  139. package/packages/client/dist/memory/shared-project-memory-types.js +2 -253
  140. package/packages/client/dist/migrations/epic-lifecycle-backfill.js +3 -1060
  141. package/packages/client/dist/migrations/project-identity-capability.js +1 -50
  142. package/packages/client/dist/migrations/project-identity.js +7 -493
  143. package/packages/client/dist/migrations/state-json.js +4 -393
  144. package/packages/client/dist/policy/architecture-policy.js +2 -184
  145. package/packages/client/dist/policy/index.js +1 -7
  146. package/packages/client/dist/policy/shared-policy-types.js +0 -38
  147. package/packages/client/dist/policy/subagent-approval-policy.js +1 -55
  148. package/packages/client/dist/private-execution/clean-baseline.js +2 -279
  149. package/packages/client/dist/private-execution/codex-executor.js +4 -574
  150. package/packages/client/dist/private-execution/codex-host-runtime.js +1 -137
  151. package/packages/client/dist/private-execution/codex-lifecycle-guard.js +1 -97
  152. package/packages/client/dist/private-execution/codex-scoped-permissions.js +1 -128
  153. package/packages/client/dist/private-execution/delivery.js +13 -410
  154. package/packages/client/dist/private-execution/diagnosis-root-review.js +2 -294
  155. package/packages/client/dist/private-execution/frozen-handoff.js +6 -19
  156. package/packages/client/dist/private-execution/implementation-validation.js +2 -106
  157. package/packages/client/dist/private-execution/isolated-admission.js +23 -1432
  158. package/packages/client/dist/private-execution/isolated-session.js +5 -725
  159. package/packages/client/dist/private-execution/isolated-workspace.js +1 -122
  160. package/packages/client/dist/private-execution/pact-consumer-runtime.js +3 -409
  161. package/packages/client/dist/private-execution/pact-test-source.js +1 -258
  162. package/packages/client/dist/private-execution/pact-toolchain.js +3 -290
  163. package/packages/client/dist/private-execution/pact-write-set.js +1 -172
  164. package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.js +5 -406
  165. package/packages/client/dist/private-execution/planning-generation-checkpoint.js +5 -462
  166. package/packages/client/dist/private-execution/planning-memory-checkpoint.js +3 -139
  167. package/packages/client/dist/private-execution/planning-research-checkpoint.js +4 -325
  168. package/packages/client/dist/private-execution/private-report-store.js +1 -42
  169. package/packages/client/dist/private-execution/property-test-candidate.js +1 -103
  170. package/packages/client/dist/private-execution/property-test-choices.js +3 -147
  171. package/packages/client/dist/private-execution/property-test-plan.js +7 -271
  172. package/packages/client/dist/private-execution/property-test-review.js +4 -258
  173. package/packages/client/dist/private-execution/property-test-runtime.js +9 -372
  174. package/packages/client/dist/private-execution/property-test-source.js +1 -139
  175. package/packages/client/dist/private-execution/root-checkpoint.js +1 -80
  176. package/packages/client/dist/private-execution/root-memory-git-evidence.js +3 -135
  177. package/packages/client/dist/private-execution/root-memory-recovery.js +1 -93
  178. package/packages/client/dist/private-execution/root-memory-request.js +1 -29
  179. package/packages/client/dist/private-execution/root-memory-scope.js +1 -178
  180. package/packages/client/dist/private-execution/root-memory-writer.js +1 -102
  181. package/packages/client/dist/private-execution/session-lease.js +1 -63
  182. package/packages/client/dist/private-execution/shared-private-admission-types.js +1 -50
  183. package/packages/client/dist/private-execution/shared-project-validation.js +1 -66
  184. package/packages/client/dist/private-execution/shared-root-memory-types.js +1 -61
  185. package/packages/client/dist/private-execution/ux-source-validation.js +1 -372
  186. package/packages/client/dist/private-execution/ux-write-set.js +2 -191
  187. package/packages/client/dist/registry/registry-reconciliation.js +1 -234
  188. package/packages/client/dist/resilience/circuit-breaker.js +1 -170
  189. package/packages/client/dist/resilience/degradation-manager.js +1 -164
  190. package/packages/client/dist/resilience/freshness-indicator.js +1 -100
  191. package/packages/client/dist/resilience/index.js +1 -8
  192. package/packages/client/dist/resilience/recovery-detector.js +1 -74
  193. package/packages/client/dist/resolvers/asset-resolver.js +0 -13
  194. package/packages/client/dist/resolvers/local-resolver.js +8 -255
  195. package/packages/client/dist/resolvers/remote-resolver.js +1 -233
  196. package/packages/client/dist/runner/binary.js +1 -404
  197. package/packages/client/dist/runner/cli.js +17 -1571
  198. package/packages/client/dist/runner/epic-background-dispatcher.d.ts +61 -0
  199. package/packages/client/dist/runner/epic-background-dispatcher.js +1 -0
  200. package/packages/client/dist/runner/headless/adapters.js +1 -49
  201. package/packages/client/dist/runner/headless/background-root.d.ts +65 -0
  202. package/packages/client/dist/runner/headless/background-root.js +1 -0
  203. package/packages/client/dist/runner/headless/claude-code-adapter.js +1 -79
  204. package/packages/client/dist/runner/headless/continuous-story-workspace.js +11 -1628
  205. package/packages/client/dist/runner/headless/epic-git-reconciliation-inventory.js +1 -69
  206. package/packages/client/dist/runner/headless/epic-merge-candidate-qa.d.ts +1 -1
  207. package/packages/client/dist/runner/headless/epic-merge-candidate-qa.js +2 -110
  208. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.d.ts +2 -0
  209. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.js +10 -1236
  210. package/packages/client/dist/runner/headless/epic-terminal-git-runner.d.ts +27 -2
  211. package/packages/client/dist/runner/headless/epic-terminal-git-runner.js +2 -318
  212. package/packages/client/dist/runner/headless/fake-adapter.js +1 -62
  213. package/packages/client/dist/runner/headless/managed-environment-cleanup.d.ts +95 -0
  214. package/packages/client/dist/runner/headless/managed-environment-cleanup.js +1 -0
  215. package/packages/client/dist/runner/headless/managed-profile.js +1 -132
  216. package/packages/client/dist/runner/headless/opencode-adapter.js +2 -145
  217. package/packages/client/dist/runner/headless/prepared-story-bundle.js +1 -43
  218. package/packages/client/dist/runner/headless/resolver.js +1 -231
  219. package/packages/client/dist/runner/headless/run-yolo.js +1 -885
  220. package/packages/client/dist/runner/headless/run-yoloop.d.ts +1 -0
  221. package/packages/client/dist/runner/headless/run-yoloop.js +2 -2574
  222. package/packages/client/dist/runner/headless/types.js +2 -574
  223. package/packages/client/dist/runner/local-console.js +13 -396
  224. package/packages/client/dist/runner/portal-sync-worker.js +1 -1487
  225. package/packages/client/dist/runner/project-identity.js +1 -106
  226. package/packages/client/dist/runner/scheduler.js +7 -995
  227. package/packages/client/dist/runner-cli.js +2 -18
  228. package/packages/client/dist/state/invocation-shape.js +1 -13
  229. package/packages/client/dist/state/project-state-snapshot.d.ts +7 -0
  230. package/packages/client/dist/state/project-state-snapshot.js +1 -1731
  231. package/packages/client/dist/state/state-json-repair.js +3 -785
  232. package/packages/client/dist/state/structural-dag-projection.js +1 -118
  233. package/packages/client/dist/telemetry/index.js +1 -5
  234. package/packages/client/dist/telemetry/offline-queue.js +1 -131
  235. package/packages/client/dist/tier/index.js +1 -5
  236. package/packages/client/dist/tier/tier-aware-client.js +1 -405
  237. package/packages/client/dist/types/index.js +1 -38
  238. package/packages/client/dist/version.js +1 -27
  239. package/packages/client/dist/yolo/change-evidence-collector.d.ts +21 -1
  240. package/packages/client/dist/yolo/change-evidence-collector.js +1 -126
  241. package/packages/client/dist/yolo/invoke-envelope-capability.js +1 -62
  242. package/packages/client/dist/yolo/spec-envelope-collector.js +5 -184
  243. package/packages/client/dist/yoloop/discovery-hook.js +2 -300
  244. package/packages/client/dist/yoloop/index.js +1 -8
  245. package/packages/client/dist/yoloop/invoke-hooks.js +12 -669
  246. package/packages/client/dist/yoloop/shared-discover-epics.js +1 -1007
  247. package/packages/client/dist/yoloop/shared-yoloop-types.js +1 -33
  248. package/packages/client/dist/yoloop/target-normalization.js +1 -180
  249. package/packages/client/dist/yoloop/yoloop-client-state-store.js +1 -1920
  250. package/packages/shared/dist/invocation/explicit-intent-recovery.d.ts +83 -0
  251. package/packages/shared/dist/invocation/explicit-intent-recovery.js +187 -0
  252. package/packages/shared/dist/invocation/index.d.ts +7 -0
  253. package/packages/shared/dist/invocation/index.js +22 -0
  254. package/packages/shared/dist/yolo/change-evidence.js +1 -1
  255. package/packages/shared/dist/yoloop/epic-terminal-git.js +144 -2
  256. package/targets-stubs/antigravity/gemini.md +1 -1
  257. package/targets-stubs/antigravity/skill/SKILL.md +1 -1
  258. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  259. package/targets-stubs/claude-code/neocortex-root.md +2 -2
  260. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  261. package/targets-stubs/claude-code/neocortex.md +2 -2
  262. package/targets-stubs/codex/AGENTS.md +24 -21
  263. package/targets-stubs/codex/README.md +6 -1
  264. package/targets-stubs/codex/neocortex.toml +7 -2
  265. package/targets-stubs/cursor/agent.md +2 -2
  266. package/targets-stubs/gemini-cli/agent.md +2 -2
  267. package/targets-stubs/opencode/neocortex-root.md +16 -1
  268. package/targets-stubs/opencode/neocortex.md +6 -0
  269. package/targets-stubs/vscode/neocortex.agent.md +2 -2
@@ -1,5 +1 @@
1
- /**
2
- * @license FSL-1.1
3
- * Copyright (c) 2026 OrNexus AI
4
- */
5
- export { LicenseClient } from './license-client.js';
1
+ import{LicenseClient as n}from"./license-client.js";export{n as LicenseClient};
@@ -11,6 +11,7 @@
11
11
  * See the LICENSE file in the project root for full license text.
12
12
  */
13
13
  import type { CacheProvider } from '../types/index.js';
14
+ import type { AuthRecoveryResultV1 } from './host-auth-recovery.js';
14
15
  export interface LicenseClientOptions {
15
16
  readonly serverUrl: string;
16
17
  readonly licenseKey: string;
@@ -18,6 +19,8 @@ export interface LicenseClientOptions {
18
19
  readonly clientVersion?: string;
19
20
  /** Use only an already-valid cached JWT; never refresh or activate. */
20
21
  readonly strictReadOnly?: boolean;
22
+ /** Opt into P224 causal recovery. P224.04 owns enabling this in invoke wiring. */
23
+ readonly causalAuthRecovery?: boolean;
21
24
  }
22
25
  interface ActivationResult {
23
26
  readonly token: string;
@@ -42,8 +45,10 @@ export declare class LicenseClient {
42
45
  private readonly clientVersion;
43
46
  private readonly machineId;
44
47
  private readonly strictReadOnly;
48
+ private readonly causalAuthRecovery;
45
49
  private token;
46
50
  private refreshToken;
51
+ private lastRecoveryResult;
47
52
  constructor(options: LicenseClientOptions);
48
53
  /**
49
54
  * Get a valid JWT token. Checks memory, cache, refresh token, then activation.
@@ -60,6 +65,9 @@ export declare class LicenseClient {
60
65
  getToken(): Promise<string | null>;
61
66
  /** Read-only authentication classification. It never refreshes, activates, clears or writes cache state. */
62
67
  inspectToken(): Promise<LicenseTokenInspection>;
68
+ /** Last causal result, excluding raw server bodies and refresh credentials. */
69
+ getLastRecoveryResult(): AuthRecoveryResultV1 | null;
70
+ private refreshRequired;
63
71
  /**
64
72
  * Activate through the endpoint matching the configured credential type.
65
73
  * Stores token and refresh_token in memory and cache on success.
@@ -81,7 +89,8 @@ export declare class LicenseClient {
81
89
  /**
82
90
  * Force-refresh the token.
83
91
  * Used when tier_changed is detected or a 401 response indicates the token is expired.
84
- * Falls back to re-activation if refresh fails.
92
+ * Does not clear or re-activate on an ambiguous refresh failure. Recovery is
93
+ * governed by the causal result so transient or uncertain state is preserved.
85
94
  * NEVER throws - returns new token or null on failure.
86
95
  *
87
96
  * Story 18.8: Updated to prefer refresh over re-activate (preserves updated tier).
@@ -1,304 +1 @@
1
- /**
2
- * @license FSL-1.1
3
- * Copyright (c) 2026 OrNexus AI
4
- *
5
- * This file is part of Neocortex CLI, licensed under the
6
- * Functional Source License, Version 1.1 (FSL-1.1).
7
- *
8
- * Change Date: February 20, 2029
9
- * Change License: MIT
10
- *
11
- * See the LICENSE file in the project root for full license text.
12
- */
13
- /**
14
- * @neocortex/client - License Client
15
- *
16
- * Manages license activation, JWT token caching, and proactive refresh.
17
- * Integrates with the IP Protection Server's license endpoints and
18
- * uses EncryptedCache for persistent token storage.
19
- *
20
- * Story 31.01: REFRESH_THRESHOLD_S fixed from 3600 to 300 (5 min)
21
- * Story 31.02: Refresh token support (store, use, rotate)
22
- * Story 31.03: Refresh token persistence in EncryptedCache
23
- *
24
- * NEVER throws exceptions - returns null on failure (graceful degradation).
25
- */
26
- import { decodeJwt } from 'jose';
27
- import { NoOpCache } from '../types/index.js';
28
- import { getMachineFingerprint } from '../machine/fingerprint.js';
29
- import { CLIENT_VERSION } from '../version.js';
30
- // ── Constants ────────────────────────────────────────────────────────────
31
- const CACHE_KEY = 'neocortex:jwt:token';
32
- const REFRESH_CACHE_KEY = 'neocortex:jwt:refresh_token';
33
- const REFRESH_THRESHOLD_S = 300; // 5 minutes before expiry
34
- const REFRESH_TOKEN_TTL_MS = 7 * 24 * 60 * 60 * 1000; // 7 days (matches server REFRESH_TOKEN_TTL_DAYS)
35
- // ── LicenseClient ────────────────────────────────────────────────────────
36
- export class LicenseClient {
37
- serverUrl;
38
- licenseKey;
39
- cache;
40
- clientVersion;
41
- machineId;
42
- strictReadOnly;
43
- token = null;
44
- refreshToken = null;
45
- constructor(options) {
46
- this.serverUrl = options.serverUrl.replace(/\/+$/, '');
47
- this.licenseKey = options.licenseKey;
48
- this.cache = options.cacheProvider ?? new NoOpCache();
49
- this.clientVersion = options.clientVersion ?? CLIENT_VERSION;
50
- this.strictReadOnly = options.strictReadOnly ?? false;
51
- this.machineId = getMachineFingerprint({ strictReadOnly: this.strictReadOnly });
52
- }
53
- /**
54
- * Get a valid JWT token. Checks memory, cache, refresh token, then activation.
55
- * NEVER throws - returns null on failure.
56
- *
57
- * Flow:
58
- * 1. in-memory JWT valid? -> return
59
- * 2. in-memory JWT needs-refresh? -> refresh(refresh_token) -> return
60
- * 3. cached JWT valid? -> return
61
- * 4. cached JWT needs-refresh? -> refresh(refresh_token) -> return
62
- * 5. cached refresh_token exists? -> refresh(refresh_token) -> return (Story 31.02)
63
- * 6. activate() -> return
64
- */
65
- async getToken() {
66
- try {
67
- if (this.strictReadOnly) {
68
- const inspection = await this.inspectToken();
69
- return inspection.status === 'authenticated' ? inspection.token : null;
70
- }
71
- // 1. Check in-memory token
72
- if (this.token) {
73
- const validity = this.checkTokenValidity(this.token);
74
- if (validity === 'valid')
75
- return this.token;
76
- if (validity === 'needs-refresh') {
77
- if (this.strictReadOnly)
78
- return this.token;
79
- const refreshed = await this.refresh();
80
- return refreshed?.token ?? this.token; // fallback to current if refresh fails
81
- }
82
- // expired or invalid - clear memory
83
- this.token = null;
84
- }
85
- // 2. Check JWT cache
86
- const cached = await this.loadFromCache();
87
- if (cached) {
88
- this.token = cached;
89
- const validity = this.checkTokenValidity(cached);
90
- if (validity === 'valid')
91
- return cached;
92
- if (validity === 'needs-refresh') {
93
- if (this.strictReadOnly)
94
- return cached;
95
- const refreshed = await this.refresh();
96
- return refreshed?.token ?? cached; // fallback to current if refresh fails
97
- }
98
- // expired - clear
99
- this.token = null;
100
- }
101
- // Strict inspection never turns authentication into activation or token
102
- // refresh state. Missing/expired cached credentials fail closed.
103
- if (this.strictReadOnly)
104
- return null;
105
- // 3. Try refresh with cached refresh_token (Story 31.02/31.03)
106
- // Lazy load refresh_token from cache if not in memory
107
- if (!this.refreshToken) {
108
- this.refreshToken = await this.loadRefreshTokenFromCache();
109
- }
110
- if (this.refreshToken) {
111
- const refreshed = await this.refresh();
112
- if (refreshed?.token)
113
- return refreshed.token;
114
- }
115
- // 4. Activate (last resort)
116
- const result = await this.activate();
117
- return result?.token ?? null;
118
- }
119
- catch {
120
- return null;
121
- }
122
- }
123
- /** Read-only authentication classification. It never refreshes, activates, clears or writes cache state. */
124
- async inspectToken() {
125
- try {
126
- const candidate = this.token ?? await this.loadFromCache();
127
- if (candidate) {
128
- const validity = this.checkTokenValidity(candidate);
129
- if (validity === 'valid')
130
- return { status: 'authenticated', token: candidate };
131
- return { status: 'refresh-required', reason: validity === 'needs-refresh' ? 'near-expiry' : 'expired' };
132
- }
133
- return this.licenseKey
134
- ? { status: 'refresh-required', reason: 'unavailable' }
135
- : { status: 'not-configured' };
136
- }
137
- catch {
138
- return this.licenseKey
139
- ? { status: 'refresh-required', reason: 'unavailable' }
140
- : { status: 'not-configured' };
141
- }
142
- }
143
- /**
144
- * Activate through the endpoint matching the configured credential type.
145
- * Stores token and refresh_token in memory and cache on success.
146
- * NEVER throws - returns null on failure.
147
- */
148
- async activate() {
149
- if (this.strictReadOnly)
150
- return null;
151
- try {
152
- const apiKey = this.licenseKey.startsWith('nxk_');
153
- const endpoint = apiKey ? 'activate-key' : 'activate';
154
- const credential = apiKey ? { api_key: this.licenseKey } : { license_key: this.licenseKey };
155
- const response = await fetch(`${this.serverUrl}/api/v1/license/${endpoint}`, {
156
- method: 'POST',
157
- headers: { 'Content-Type': 'application/json' },
158
- body: JSON.stringify({
159
- ...credential,
160
- machine_id: this.machineId,
161
- client_version: this.clientVersion,
162
- }),
163
- });
164
- if (!response.ok)
165
- return null;
166
- const data = (await response.json());
167
- if (data.tier !== undefined && data.tier !== 'free' && data.tier !== 'pro'
168
- && data.tier !== 'enterprise')
169
- return null;
170
- this.token = data.token;
171
- this.refreshToken = data.refresh_token ?? null;
172
- // Drain capability-backed persistence before returning so invoke receipt
173
- // completion cannot race an owned cache effect.
174
- await this.cache.set(CACHE_KEY, data.token, data.expires_in * 1000).catch(() => { });
175
- // Persist refresh token with 7-day TTL (fire-and-forget)
176
- if (data.refresh_token) {
177
- await this.cache.set(REFRESH_CACHE_KEY, data.refresh_token, REFRESH_TOKEN_TTL_MS).catch(() => { });
178
- }
179
- return {
180
- token: data.token,
181
- expiresIn: data.expires_in,
182
- refreshToken: data.refresh_token,
183
- tier: data.tier,
184
- };
185
- }
186
- catch {
187
- return null;
188
- }
189
- }
190
- /**
191
- * Refresh using refresh_token by calling POST /api/v1/license/refresh.
192
- * Sends refresh_token in body (no Authorization header needed).
193
- * Handles token rotation: stores the new refresh_token from response.
194
- * NEVER throws - returns null on failure.
195
- *
196
- * Story 31.02: Signature changed from refresh(currentToken) to refresh().
197
- * The refresh_token in the body is the credential, not the JWT.
198
- *
199
- * @param _currentToken - Deprecated. Kept for backward compat but ignored.
200
- */
201
- async refresh(_currentToken) {
202
- if (this.strictReadOnly)
203
- return null;
204
- try {
205
- // Load refresh_token: in-memory first, then cache
206
- const rt = this.refreshToken ?? await this.loadRefreshTokenFromCache();
207
- if (!rt) {
208
- // No refresh token available -- cannot use new flow
209
- return null;
210
- }
211
- const response = await fetch(`${this.serverUrl}/api/v1/license/refresh`, {
212
- method: 'POST',
213
- headers: { 'Content-Type': 'application/json' },
214
- body: JSON.stringify({ refresh_token: rt }),
215
- });
216
- if (!response.ok) {
217
- // Refresh token invalid/expired -- clear it
218
- this.refreshToken = null;
219
- await this.cache.set(REFRESH_CACHE_KEY, '', 1).catch(() => { }); // expire immediately
220
- return null;
221
- }
222
- const data = (await response.json());
223
- this.token = data.token;
224
- // Token rotation: server issues new refresh token
225
- this.refreshToken = data.refresh_token ?? null;
226
- await this.cache.set(CACHE_KEY, data.token, data.expires_in * 1000).catch(() => { });
227
- // Persist rotated refresh token (fire-and-forget)
228
- if (data.refresh_token) {
229
- await this.cache.set(REFRESH_CACHE_KEY, data.refresh_token, REFRESH_TOKEN_TTL_MS).catch(() => { });
230
- }
231
- return {
232
- token: data.token,
233
- expiresIn: data.expires_in,
234
- refreshToken: data.refresh_token,
235
- };
236
- }
237
- catch {
238
- return null;
239
- }
240
- }
241
- /**
242
- * Force-refresh the token.
243
- * Used when tier_changed is detected or a 401 response indicates the token is expired.
244
- * Falls back to re-activation if refresh fails.
245
- * NEVER throws - returns new token or null on failure.
246
- *
247
- * Story 18.8: Updated to prefer refresh over re-activate (preserves updated tier).
248
- * Story 31.02: Uses refresh_token flow instead of JWT-based refresh.
249
- */
250
- async forceRefresh() {
251
- if (this.strictReadOnly)
252
- return null;
253
- try {
254
- // 1. Try refresh with refresh_token first
255
- const refreshResult = await this.refresh();
256
- if (refreshResult?.token)
257
- return refreshResult.token;
258
- // 2. Refresh failed -- clear everything and re-activate
259
- this.token = null;
260
- this.refreshToken = null;
261
- await this.cache.clear().catch(() => { });
262
- const result = await this.activate();
263
- return result?.token ?? null;
264
- }
265
- catch {
266
- return null;
267
- }
268
- }
269
- // ── Private Methods ─────────────────────────────────────────────────
270
- checkTokenValidity(token) {
271
- try {
272
- const payload = decodeJwt(token);
273
- if (!payload.exp)
274
- return 'expired';
275
- const now = Math.floor(Date.now() / 1000);
276
- if (payload.exp <= now)
277
- return 'expired';
278
- if (payload.exp - now <= REFRESH_THRESHOLD_S)
279
- return 'needs-refresh';
280
- return 'valid';
281
- }
282
- catch {
283
- return 'expired';
284
- }
285
- }
286
- async loadFromCache() {
287
- try {
288
- return await this.cache.get(CACHE_KEY);
289
- }
290
- catch {
291
- return null;
292
- }
293
- }
294
- async loadRefreshTokenFromCache() {
295
- try {
296
- const rt = await this.cache.get(REFRESH_CACHE_KEY);
297
- // Guard against empty/expired entries
298
- return rt && rt.length > 0 ? rt : null;
299
- }
300
- catch {
301
- return null;
302
- }
303
- }
304
- }
1
+ import{decodeJwt as h}from"jose";import{NoOpCache as o}from"../types/index.js";import{getMachineFingerprint as l}from"../machine/fingerprint.js";import{CLIENT_VERSION as u}from"../version.js";const s="neocortex:jwt:token",a="neocortex:jwt:refresh_token",f=300,c=10080*60*1e3;class v{serverUrl;licenseKey;cache;clientVersion;machineId;strictReadOnly;causalAuthRecovery;token=null;refreshToken=null;lastRecoveryResult=null;constructor(e){this.serverUrl=e.serverUrl.replace(/\/+$/,""),this.licenseKey=e.licenseKey,this.cache=e.cacheProvider??new o,this.clientVersion=e.clientVersion??u,this.strictReadOnly=e.strictReadOnly??!1,this.causalAuthRecovery=e.causalAuthRecovery??!1,this.machineId=l({strictReadOnly:this.strictReadOnly})}async getToken(){try{if(this.strictReadOnly){const t=await this.inspectToken();return t.status==="authenticated"?t.token:null}if(this.token){const t=this.checkTokenValidity(this.token);if(t==="valid")return this.token;if(t==="needs-refresh")return this.strictReadOnly?this.token:(await this.refresh())?.token??this.token;this.token=null}const e=await this.loadFromCache();if(e){this.token=e;const t=this.checkTokenValidity(e);if(t==="valid")return e;if(t==="needs-refresh")return this.strictReadOnly?e:(await this.refresh())?.token??e;this.token=null}if(this.strictReadOnly)return null;if(this.refreshToken||(this.refreshToken=await this.loadRefreshTokenFromCache()),this.refreshToken){const t=await this.refresh();if(t?.token)return t.token;if(this.causalAuthRecovery)return null}return(await this.activate())?.token??null}catch{return null}}async inspectToken(){try{const e=this.token??await this.loadFromCache();if(e){const n=this.checkTokenValidity(e);return n==="valid"?{status:"authenticated",token:e}:{status:"refresh-required",reason:n==="needs-refresh"?"near-expiry":"expired"}}return this.licenseKey?{status:"refresh-required",reason:"unavailable"}:{status:"not-configured"}}catch{return this.licenseKey?{status:"refresh-required",reason:"unavailable"}:{status:"not-configured"}}}getLastRecoveryResult(){return this.lastRecoveryResult}refreshRequired(e,n){return this.lastRecoveryResult={status:"refresh-required",cause:e,action:n},null}async activate(){if(this.strictReadOnly)return null;try{const e=this.licenseKey.startsWith("nxk_"),n=e?"activate-key":"activate",t=e?{api_key:this.licenseKey}:{license_key:this.licenseKey},i=await fetch(`${this.serverUrl}/api/v1/license/${n}`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({...t,machine_id:this.machineId,client_version:this.clientVersion})});if(!i.ok)return null;const r=await i.json();return r.tier!==void 0&&r.tier!=="free"&&r.tier!=="pro"&&r.tier!=="enterprise"?null:(this.token=r.token,this.refreshToken=r.refresh_token??null,await this.cache.set(s,r.token,r.expires_in*1e3).catch(()=>{}),r.refresh_token&&await this.cache.set(a,r.refresh_token,c).catch(()=>{}),{token:r.token,expiresIn:r.expires_in,refreshToken:r.refresh_token,tier:r.tier})}catch{return null}}async refresh(e){if(this.strictReadOnly)return null;try{const n=this.refreshToken??await this.loadRefreshTokenFromCache();if(!n)return this.refreshRequired("not-configured","reactivate");const t=await fetch(`${this.serverUrl}/api/v1/license/refresh`,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({refresh_token:n})});if(!t.ok){let r="";try{r=String((await t.json()).error??"")}catch{}return t.status===429?this.refreshRequired("rate-limited","retry-later"):t.status>=500?this.refreshRequired("service-unavailable","retry-later"):r==="invalid_grant"||r==="revoked"?this.refreshRequired("revoked","reactivate"):r==="invalid_scope"||r==="scope_denied"?this.refreshRequired("scope-denied","request-scope"):r==="client_denied"?this.refreshRequired("client-denied","stop"):this.refreshRequired("protocol-invalid","stop")}const i=await t.json();return this.token=i.token,this.refreshToken=i.refresh_token??null,await this.cache.set(s,i.token,i.expires_in*1e3).catch(()=>{}),i.refresh_token&&await this.cache.set(a,i.refresh_token,c).catch(()=>{}),this.lastRecoveryResult={status:"authenticated",generation:0,accessCredential:i.token,expiresAt:new Date(Date.now()+i.expires_in*1e3).toISOString()},{token:i.token,expiresIn:i.expires_in,refreshToken:i.refresh_token}}catch{return this.refreshRequired("transport-error","retry-later")}}async forceRefresh(){if(this.strictReadOnly)return null;try{const e=await this.refresh();return e?.token?e.token:this.causalAuthRecovery?null:(this.token=null,this.refreshToken=null,await this.cache.clear().catch(()=>{}),(await this.activate())?.token??null)}catch{return null}}checkTokenValidity(e){try{const n=h(e);if(!n.exp)return"expired";const t=Math.floor(Date.now()/1e3);return n.exp<=t?"expired":n.exp-t<=f?"needs-refresh":"valid"}catch{return"expired"}}async loadFromCache(){try{return await this.cache.get(s)}catch{return null}}async loadRefreshTokenFromCache(){try{const e=await this.cache.get(a);return e&&e.length>0?e:null}catch{return null}}}export{v as LicenseClient};
@@ -1,163 +1,2 @@
1
- /**
2
- * @license FSL-1.1
3
- * Copyright (c) 2026 OrNexus AI
4
- *
5
- * This file is part of Neocortex CLI, licensed under the
6
- * Functional Source License, Version 1.1 (FSL-1.1).
7
- *
8
- * Change Date: February 20, 2029
9
- * Change License: MIT
10
- *
11
- * See the LICENSE file in the project root for full license text.
12
- */
13
- /**
14
- * @neocortex/client - Machine Fingerprint
15
- *
16
- * Generates a stable, deterministic machine identifier from hardware/OS
17
- * attributes using SHA-256. Used for license activation machine tracking.
18
- */
19
- import { createHash } from 'node:crypto';
20
- import { existsSync, readFileSync, writeFileSync, mkdirSync, chmodSync } from 'node:fs';
21
- import { join } from 'node:path';
22
- import { arch, cpus, hostname, networkInterfaces, platform } from 'node:os';
23
- import { neocortexProfileDirectory } from '../config/profile-directory.js';
24
- const ALL_ZEROS_MAC = '00:00:00:00:00:00';
25
- /** Path to the persisted machine-id file */
26
- const NEOCORTEX_DIR = neocortexProfileDirectory();
27
- const MACHINE_ID_FILE = join(NEOCORTEX_DIR, '.machine-id');
28
- /**
29
- * Collect sorted, non-internal MAC addresses from network interfaces.
30
- * Filters out internal/loopback interfaces and all-zeros MACs.
31
- */
32
- function collectMacAddresses() {
33
- const interfaces = networkInterfaces();
34
- const macs = [];
35
- for (const entries of Object.values(interfaces)) {
36
- if (!entries)
37
- continue;
38
- for (const entry of entries) {
39
- if (!entry.internal && entry.mac !== ALL_ZEROS_MAC) {
40
- macs.push(entry.mac);
41
- }
42
- }
43
- }
44
- // Sort for determinism regardless of NIC enumeration order
45
- return [...new Set(macs)].sort();
46
- }
47
- /**
48
- * Generate a hardware-based fingerprint (not persisted).
49
- * This is the original computation used as fallback and for seeding.
50
- *
51
- * @returns 64-character hex string (SHA-256 digest)
52
- */
53
- export function computeHardwareFingerprint() {
54
- const host = hostname();
55
- const plat = platform();
56
- const architecture = arch();
57
- const cpuList = cpus();
58
- const cpuModel = cpuList.length > 0 ? cpuList[0].model : '';
59
- const macs = collectMacAddresses();
60
- const input = `${host}|${plat}|${architecture}|${cpuModel}|${macs.join(',')}`;
61
- return createHash('sha256').update(input).digest('hex');
62
- }
63
- /**
64
- * Set restrictive file permissions (chmod 600) on a file.
65
- * Fail-open: never throws.
66
- */
67
- function setFilePermissions600(filePath) {
68
- try {
69
- if (process.platform !== 'win32') {
70
- chmodSync(filePath, 0o600);
71
- }
72
- // Windows ACL handled by secure-config.ts setSecureFilePermissions() if needed
73
- }
74
- catch {
75
- // Fail-open
76
- }
77
- }
78
- /**
79
- * Read persisted machine ID from disk.
80
- * Returns null if file doesn't exist or can't be read.
81
- */
82
- function readPersistedMachineId() {
83
- try {
84
- if (!existsSync(MACHINE_ID_FILE))
85
- return null;
86
- const raw = readFileSync(MACHINE_ID_FILE, 'utf-8').trim();
87
- // Validate: must be a 64-char hex string
88
- if (/^[a-f0-9]{64}$/.test(raw))
89
- return raw;
90
- return null;
91
- }
92
- catch {
93
- return null;
94
- }
95
- }
96
- /**
97
- * Persist machine ID to disk.
98
- * Creates ~/.neocortex/ if needed. Sets chmod 600 on the file.
99
- * Fail-open: never throws.
100
- */
101
- function persistMachineId(machineId) {
102
- try {
103
- mkdirSync(NEOCORTEX_DIR, { recursive: true });
104
- writeFileSync(MACHINE_ID_FILE, machineId + '\n', 'utf-8');
105
- setFilePermissions600(MACHINE_ID_FILE);
106
- }
107
- catch {
108
- // Fail-open: if disk fails, fingerprint still works from hardware
109
- }
110
- }
111
- /**
112
- * Check if config.json has a machineId field that can seed .machine-id.
113
- * This provides backward compatibility for existing installations.
114
- */
115
- function readMachineIdFromConfig() {
116
- try {
117
- const configPath = join(NEOCORTEX_DIR, 'config.json');
118
- if (!existsSync(configPath))
119
- return null;
120
- const raw = readFileSync(configPath, 'utf-8');
121
- const config = JSON.parse(raw.replace(/^\uFEFF/, ''));
122
- const machineId = config.machineId;
123
- if (typeof machineId === 'string' && /^[a-f0-9]{64}$/.test(machineId)) {
124
- return machineId;
125
- }
126
- return null;
127
- }
128
- catch {
129
- return null;
130
- }
131
- }
132
- /**
133
- * Generate a stable machine fingerprint as a SHA-256 hex digest.
134
- *
135
- * Story P26.01: On first call, generates from hardware and persists to
136
- * ~/.neocortex/.machine-id. On subsequent calls, reads from disk.
137
- * This ensures the fingerprint remains stable even if hardware attributes
138
- * change (e.g., USB NIC added/removed, hostname change).
139
- *
140
- * Backward compat: if config.json has machineId, uses that to seed .machine-id.
141
- *
142
- * Fail-open: if disk operations fail, falls back to hardware-generated fingerprint.
143
- *
144
- * @returns 64-character hex string (SHA-256 digest)
145
- */
146
- export function getMachineFingerprint(options = {}) {
147
- // 1. Try reading persisted machine ID from disk
148
- const persisted = readPersistedMachineId();
149
- if (persisted)
150
- return persisted;
151
- // 2. Check config.json for backward-compatible machineId
152
- const fromConfig = readMachineIdFromConfig();
153
- if (fromConfig) {
154
- if (!options.strictReadOnly)
155
- persistMachineId(fromConfig);
156
- return fromConfig;
157
- }
158
- // 3. Generate from hardware and persist
159
- const fingerprint = computeHardwareFingerprint();
160
- if (!options.strictReadOnly)
161
- persistMachineId(fingerprint);
162
- return fingerprint;
163
- }
1
+ import{createHash as p}from"node:crypto";import{existsSync as i,readFileSync as s,writeFileSync as d,mkdirSync as h,chmodSync as y}from"node:fs";import{join as f}from"node:path";import{arch as g,cpus as F,hostname as I,networkInterfaces as M,platform as S}from"node:os";import{neocortexProfileDirectory as w}from"../config/profile-directory.js";const O="00:00:00:00:00:00",o=w(),c=f(o,".machine-id");function $(){const t=M(),r=[];for(const e of Object.values(t))if(e)for(const n of e)!n.internal&&n.mac!==O&&r.push(n.mac);return[...new Set(r)].sort()}function E(){const t=I(),r=S(),e=g(),n=F(),u=n.length>0?n[0].model:"",l=$(),m=`${t}|${r}|${e}|${u}|${l.join(",")}`;return p("sha256").update(m).digest("hex")}function x(t){try{process.platform!=="win32"&&y(t,384)}catch{}}function C(){try{if(!i(c))return null;const t=s(c,"utf-8").trim();return/^[a-f0-9]{64}$/.test(t)?t:null}catch{return null}}function a(t){try{h(o,{recursive:!0}),d(c,t+`
2
+ `,"utf-8"),x(c)}catch{}}function R(){try{const t=f(o,"config.json");if(!i(t))return null;const r=s(t,"utf-8"),n=JSON.parse(r.replace(/^\uFEFF/,"")).machineId;return typeof n=="string"&&/^[a-f0-9]{64}$/.test(n)?n:null}catch{return null}}function D(t={}){const r=C();if(r)return r;const e=R();if(e)return t.strictReadOnly||a(e),e;const n=E();return t.strictReadOnly||a(n),n}export{E as computeHardwareFingerprint,D as getMachineFingerprint};
@@ -1,5 +1 @@
1
- /**
2
- * @license FSL-1.1
3
- * Copyright (c) 2026 OrNexus AI
4
- */
5
- export { getMachineFingerprint } from './fingerprint.js';
1
+ import{getMachineFingerprint as i}from"./fingerprint.js";export{i as getMachineFingerprint};
@@ -1,62 +1 @@
1
- import { lstatSync, readlinkSync, realpathSync } from 'node:fs';
2
- import { dirname, isAbsolute, join, relative, resolve, sep, win32 } from 'node:path';
3
- import { CANONICAL_PROJECT_MEMORY_SOURCE } from './shared-project-memory-types.js';
4
- export function invalidProjectMemoryPath(reason) {
5
- throw new Error(`project-memory-path-${reason}`);
6
- }
7
- export function isValidScopedRelativePath(path) {
8
- return typeof path === 'string' && path.length > 0 && !path.startsWith('~') &&
9
- !path.includes('\\') && !path.includes('\0') && !isAbsolute(path) &&
10
- !win32.isAbsolute(path) && !/^[a-zA-Z]:/.test(path) &&
11
- !path.split('/').some((segment) => segment === '' || segment === '.' || segment === '..');
12
- }
13
- /** Reject unsafe paths before canonical content or any target is read or written. */
14
- export function assertProjectMemoryPaths(projectRoot, relativeFiles) {
15
- let root;
16
- try {
17
- root = realpathSync(projectRoot);
18
- }
19
- catch {
20
- invalidProjectMemoryPath('out-of-scope');
21
- }
22
- const canonical = join(root, CANONICAL_PROJECT_MEMORY_SOURCE);
23
- for (const relativeFile of relativeFiles) {
24
- if (!isValidScopedRelativePath(relativeFile)) {
25
- invalidProjectMemoryPath('invalid');
26
- }
27
- const candidate = resolve(root, relativeFile);
28
- const fromRoot = relative(root, candidate);
29
- if (fromRoot === '' || fromRoot === '..' || fromRoot.startsWith(`..${sep}`) || isAbsolute(fromRoot)) {
30
- invalidProjectMemoryPath('out-of-scope');
31
- }
32
- const segments = relativeFile.split('/');
33
- for (let index = 0; index < segments.length; index++) {
34
- const current = join(root, ...segments.slice(0, index + 1));
35
- let stat;
36
- try {
37
- stat = lstatSync(current);
38
- }
39
- catch (error) {
40
- if (error.code === 'ENOENT')
41
- continue;
42
- invalidProjectMemoryPath('out-of-scope');
43
- }
44
- if (!stat.isSymbolicLink())
45
- continue;
46
- if (index !== segments.length - 1 || relativeFile === CANONICAL_PROJECT_MEMORY_SOURCE) {
47
- invalidProjectMemoryPath('out-of-scope');
48
- }
49
- // A pre-existing semantic file may link only to the canonical file.
50
- let linkTarget;
51
- try {
52
- linkTarget = readlinkSync(current);
53
- }
54
- catch {
55
- invalidProjectMemoryPath('out-of-scope');
56
- }
57
- if (resolve(dirname(current), linkTarget) !== canonical) {
58
- invalidProjectMemoryPath('out-of-scope');
59
- }
60
- }
61
- }
62
- }
1
+ import{lstatSync as E,readlinkSync as P,realpathSync as S}from"node:fs";import{dirname as A,isAbsolute as u,join as m,relative as O,resolve as d,sep as R,win32 as g}from"node:path";import{CANONICAL_PROJECT_MEMORY_SOURCE as p}from"./shared-project-memory-types.js";function t(o){throw new Error(`project-memory-path-${o}`)}function j(o){return typeof o=="string"&&o.length>0&&!o.startsWith("~")&&!o.includes("\\")&&!o.includes("\0")&&!u(o)&&!g.isAbsolute(o)&&!/^[a-zA-Z]:/.test(o)&&!o.split("/").some(e=>e===""||e==="."||e==="..")}function N(o,e){let i;try{i=S(o)}catch{t("out-of-scope")}const y=m(i,p);for(const r of e){j(r)||t("invalid");const h=d(i,r),c=O(i,h);(c===""||c===".."||c.startsWith(`..${R}`)||u(c))&&t("out-of-scope");const s=r.split("/");for(let n=0;n<s.length;n++){const l=m(i,...s.slice(0,n+1));let f;try{f=E(l)}catch(v){if(v.code==="ENOENT")continue;t("out-of-scope")}if(!f.isSymbolicLink())continue;(n!==s.length-1||r===p)&&t("out-of-scope");let a;try{a=P(l)}catch{t("out-of-scope")}d(A(l),a)!==y&&t("out-of-scope")}}}export{N as assertProjectMemoryPaths,t as invalidProjectMemoryPath,j as isValidScopedRelativePath};