@ornexus/neocortex 4.61.5 → 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.
Files changed (254) hide show
  1. package/dist/release-source.json +1 -1
  2. package/dist/sbom.cdx.json +1193 -1193
  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 -220
  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 -443
  18. package/packages/client/dist/agent/update-agent-yaml.js +1 -102
  19. package/packages/client/dist/agent/update-description.js +1 -260
  20. package/packages/client/dist/cache/crypto-utils.js +1 -78
  21. package/packages/client/dist/cache/encrypted-cache.js +1 -338
  22. package/packages/client/dist/cache/in-memory-asset-cache.js +1 -73
  23. package/packages/client/dist/cache/index.js +1 -13
  24. package/packages/client/dist/cache/protected-pi-boundary.js +1 -44
  25. package/packages/client/dist/checkpoint/checkpoint-client-reader.js +2 -127
  26. package/packages/client/dist/checkpoint/index.js +1 -11
  27. package/packages/client/dist/checkpoint/shared-checkpoint-types.js +1 -32
  28. package/packages/client/dist/cli.js +5 -364
  29. package/packages/client/dist/commands/activate.js +8 -394
  30. package/packages/client/dist/commands/architecture-answers.js +7 -274
  31. package/packages/client/dist/commands/architecture-memory-terminal.js +4 -253
  32. package/packages/client/dist/commands/architecture-non-ui-continuation.js +1 -100
  33. package/packages/client/dist/commands/architecture-root-binding.js +1 -51
  34. package/packages/client/dist/commands/cache-status.js +2 -112
  35. package/packages/client/dist/commands/config.js +1 -88
  36. package/packages/client/dist/commands/doctor.js +2 -635
  37. package/packages/client/dist/commands/invoke.js +148 -7822
  38. package/packages/client/dist/commands/legacy-epic-terminal.js +1 -71
  39. package/packages/client/dist/commands/legacy-story-branch.js +1 -96
  40. package/packages/client/dist/commands/legacy-story-pr.js +1 -276
  41. package/packages/client/dist/commands/mutation-qa-checkpoint.js +5 -285
  42. package/packages/client/dist/commands/mutation-qa-gate.js +1 -54
  43. package/packages/client/dist/commands/mutation-qa-git.js +1 -41
  44. package/packages/client/dist/commands/mutation-qa-policy.js +1 -102
  45. package/packages/client/dist/commands/mutation-qa-run.js +3 -219
  46. package/packages/client/dist/commands/mutation-qa-verdict.js +1 -149
  47. package/packages/client/dist/commands/mutation-qa.js +1 -220
  48. package/packages/client/dist/commands/native-agent.js +2 -136
  49. package/packages/client/dist/commands/planning-diagnosis.js +1 -43
  50. package/packages/client/dist/commands/planning-generation.js +1 -53
  51. package/packages/client/dist/commands/planning-memory.js +1 -40
  52. package/packages/client/dist/commands/planning-research.js +1 -42
  53. package/packages/client/dist/commands/private-session.js +1 -75
  54. package/packages/client/dist/commands/property-qa.js +1 -139
  55. package/packages/client/dist/commands/qa-control.js +1 -16
  56. package/packages/client/dist/commands/qa-scan-browser-launch.js +1 -55
  57. package/packages/client/dist/commands/qa-scan-browser-route.js +1 -28
  58. package/packages/client/dist/commands/qa-scan-capture.js +5 -663
  59. package/packages/client/dist/commands/qa-scan-discovery.js +3 -376
  60. package/packages/client/dist/commands/qa-scan-review.js +5 -826
  61. package/packages/client/dist/commands/qa-synthetic-backend-capture.js +1 -266
  62. package/packages/client/dist/commands/qa-synthetic-backend-review.js +1 -297
  63. package/packages/client/dist/commands/qa-synthetic-backend.js +2 -340
  64. package/packages/client/dist/commands/qa-synthetic-broker-port.js +1 -85
  65. package/packages/client/dist/commands/qa-synthetic-browser.js +1 -39
  66. package/packages/client/dist/commands/refactor-characterization.js +21 -671
  67. package/packages/client/dist/commands/refactor-commit.js +13 -399
  68. package/packages/client/dist/commands/refactor-control.js +3 -142
  69. package/packages/client/dist/commands/refactor-cpp-assertions.js +3 -93
  70. package/packages/client/dist/commands/refactor-review.js +5 -283
  71. package/packages/client/dist/commands/refactor-root.js +7 -588
  72. package/packages/client/dist/commands/refresh-memory.js +3 -174
  73. package/packages/client/dist/commands/shared-architecture-non-ui.js +1 -24
  74. package/packages/client/dist/commands/story-checkpoint.d.ts +5 -1
  75. package/packages/client/dist/commands/story-checkpoint.js +1 -203
  76. package/packages/client/dist/commands/story-worktree.js +5 -258
  77. package/packages/client/dist/config/host-auth-broker.js +1 -60
  78. package/packages/client/dist/config/host-auth-reference.js +1 -93
  79. package/packages/client/dist/config/profile-directory.js +1 -13
  80. package/packages/client/dist/config/resolver-selection.js +1 -278
  81. package/packages/client/dist/config/secure-config.js +12 -281
  82. package/packages/client/dist/config.js +2 -224
  83. package/packages/client/dist/constants.js +1 -25
  84. package/packages/client/dist/context/context-collector.js +2 -222
  85. package/packages/client/dist/context/context-sanitizer.js +1 -145
  86. package/packages/client/dist/continuity/autonomous-governance.js +1 -285
  87. package/packages/client/dist/continuity/continuity-client-state-store.js +1 -1587
  88. package/packages/client/dist/continuity/invoke-hooks.js +1 -129
  89. package/packages/client/dist/continuity/migrations/001-initial-schema.js +2 -12
  90. package/packages/client/dist/continuity/migrations/002-processing-output-summary-indexes.js +2 -12
  91. package/packages/client/dist/continuity/migrations/003-headless-execution-attempts.js +2 -12
  92. package/packages/client/dist/continuity/migrations/004-outbox-delivery-state.js +2 -12
  93. package/packages/client/dist/continuity/migrations/005-bounded-headless-queue.js +2 -12
  94. package/packages/client/dist/continuity/migrations/006-native-agent-dispatches.js +2 -10
  95. package/packages/client/dist/continuity/native-agent-store.js +1 -69
  96. package/packages/client/dist/continuity/native-agent-types.js +1 -105
  97. package/packages/client/dist/continuity/outbox.js +1 -117
  98. package/packages/client/dist/continuity/runner-bootstrap-policy.js +1 -172
  99. package/packages/client/dist/continuity/sqlite-store.js +81 -2612
  100. package/packages/client/dist/effects/invoke-effect-gateways.js +1 -62
  101. package/packages/client/dist/errors/error-messages.js +2 -258
  102. package/packages/client/dist/errors/frontmatter-diagnostics.js +1 -125
  103. package/packages/client/dist/evidence/collector.js +1 -347
  104. package/packages/client/dist/evidence/index.js +1 -1
  105. package/packages/client/dist/evidence/types.js +0 -2
  106. package/packages/client/dist/fs/atomic-state-replace.js +1 -152
  107. package/packages/client/dist/generated/command-registry.generated.js +1 -4076
  108. package/packages/client/dist/generated/public-projections.generated.js +1 -149
  109. package/packages/client/dist/git/direct-yolo-c01-retry.js +4 -138
  110. package/packages/client/dist/git/direct-yolo-checkpoint.d.ts +70 -0
  111. package/packages/client/dist/git/direct-yolo-checkpoint.js +4 -1592
  112. package/packages/client/dist/git/epic-operational-state.js +2 -672
  113. package/packages/client/dist/git/git-lifecycle-step-ids.js +1 -14
  114. package/packages/client/dist/git/git-lifecycle-store.d.ts +22 -0
  115. package/packages/client/dist/git/git-lifecycle-store.js +8 -2529
  116. package/packages/client/dist/git/legacy-story-branch-checkpoint.js +9 -259
  117. package/packages/client/dist/git/legacy-story-branch-setup.js +4 -348
  118. package/packages/client/dist/git/legacy-story-pr.js +70 -3538
  119. package/packages/client/dist/git/neocortex-trailers.js +2 -53
  120. package/packages/client/dist/git/secure-filesystem-boundary.js +5 -182
  121. package/packages/client/dist/git/story-worktree-cleanup.js +4 -1058
  122. package/packages/client/dist/git/story-worktree-integration.d.ts +62 -0
  123. package/packages/client/dist/git/story-worktree-integration.js +3 -603
  124. package/packages/client/dist/git/story-worktree-manager.js +3 -843
  125. package/packages/client/dist/git/story-worktree-paths.js +1 -150
  126. package/packages/client/dist/git/story-write-set-extension.d.ts +44 -0
  127. package/packages/client/dist/git/story-write-set-extension.js +1 -0
  128. package/packages/client/dist/graph-retrieval/pre-command-hook.js +1 -284
  129. package/packages/client/dist/graph-retrieval/shared-graph-retrieval-contract.js +1 -237
  130. package/packages/client/dist/i18n/first-run.js +2 -60
  131. package/packages/client/dist/index.js +1 -50
  132. package/packages/client/dist/invocation/invoke-input.js +1 -24
  133. package/packages/client/dist/license/host-auth-recovery.js +1 -401
  134. package/packages/client/dist/license/index.js +1 -5
  135. package/packages/client/dist/license/license-client.js +1 -337
  136. package/packages/client/dist/machine/fingerprint.js +2 -163
  137. package/packages/client/dist/machine/index.js +1 -5
  138. package/packages/client/dist/memory/project-memory-path-scope.js +1 -62
  139. package/packages/client/dist/memory/project-memory-writer.js +41 -1117
  140. package/packages/client/dist/memory/shared-project-memory-types.js +2 -259
  141. package/packages/client/dist/migrations/epic-lifecycle-backfill.js +3 -1060
  142. package/packages/client/dist/migrations/project-identity-capability.js +1 -50
  143. package/packages/client/dist/migrations/project-identity.js +7 -493
  144. package/packages/client/dist/migrations/state-json.js +4 -393
  145. package/packages/client/dist/policy/architecture-policy.js +2 -184
  146. package/packages/client/dist/policy/index.js +1 -7
  147. package/packages/client/dist/policy/shared-policy-types.js +0 -38
  148. package/packages/client/dist/policy/subagent-approval-policy.js +1 -57
  149. package/packages/client/dist/private-execution/clean-baseline.js +2 -279
  150. package/packages/client/dist/private-execution/codex-executor.js +4 -574
  151. package/packages/client/dist/private-execution/codex-host-runtime.js +1 -137
  152. package/packages/client/dist/private-execution/codex-lifecycle-guard.js +1 -97
  153. package/packages/client/dist/private-execution/codex-scoped-permissions.js +1 -128
  154. package/packages/client/dist/private-execution/delivery.js +13 -410
  155. package/packages/client/dist/private-execution/diagnosis-root-review.js +2 -294
  156. package/packages/client/dist/private-execution/frozen-handoff.js +6 -19
  157. package/packages/client/dist/private-execution/implementation-validation.js +2 -106
  158. package/packages/client/dist/private-execution/isolated-admission.js +23 -1432
  159. package/packages/client/dist/private-execution/isolated-session.js +5 -725
  160. package/packages/client/dist/private-execution/isolated-workspace.js +1 -122
  161. package/packages/client/dist/private-execution/pact-consumer-runtime.js +3 -409
  162. package/packages/client/dist/private-execution/pact-test-source.js +1 -258
  163. package/packages/client/dist/private-execution/pact-toolchain.js +3 -290
  164. package/packages/client/dist/private-execution/pact-write-set.js +1 -172
  165. package/packages/client/dist/private-execution/planning-diagnosis-checkpoint.js +5 -406
  166. package/packages/client/dist/private-execution/planning-generation-checkpoint.js +5 -462
  167. package/packages/client/dist/private-execution/planning-memory-checkpoint.js +3 -139
  168. package/packages/client/dist/private-execution/planning-research-checkpoint.js +4 -325
  169. package/packages/client/dist/private-execution/private-report-store.js +1 -42
  170. package/packages/client/dist/private-execution/property-test-candidate.js +1 -103
  171. package/packages/client/dist/private-execution/property-test-choices.js +3 -147
  172. package/packages/client/dist/private-execution/property-test-plan.js +7 -271
  173. package/packages/client/dist/private-execution/property-test-review.js +4 -258
  174. package/packages/client/dist/private-execution/property-test-runtime.js +9 -372
  175. package/packages/client/dist/private-execution/property-test-source.js +1 -139
  176. package/packages/client/dist/private-execution/root-checkpoint.js +1 -80
  177. package/packages/client/dist/private-execution/root-memory-git-evidence.js +3 -135
  178. package/packages/client/dist/private-execution/root-memory-recovery.js +1 -93
  179. package/packages/client/dist/private-execution/root-memory-request.js +1 -29
  180. package/packages/client/dist/private-execution/root-memory-scope.js +1 -178
  181. package/packages/client/dist/private-execution/root-memory-writer.js +1 -102
  182. package/packages/client/dist/private-execution/session-lease.js +1 -63
  183. package/packages/client/dist/private-execution/shared-private-admission-types.js +1 -50
  184. package/packages/client/dist/private-execution/shared-project-validation.js +1 -66
  185. package/packages/client/dist/private-execution/shared-root-memory-types.js +1 -61
  186. package/packages/client/dist/private-execution/ux-source-validation.js +1 -372
  187. package/packages/client/dist/private-execution/ux-write-set.js +2 -191
  188. package/packages/client/dist/registry/registry-reconciliation.js +1 -234
  189. package/packages/client/dist/resilience/circuit-breaker.js +1 -170
  190. package/packages/client/dist/resilience/degradation-manager.js +1 -164
  191. package/packages/client/dist/resilience/freshness-indicator.js +1 -100
  192. package/packages/client/dist/resilience/index.js +1 -8
  193. package/packages/client/dist/resilience/recovery-detector.js +1 -74
  194. package/packages/client/dist/resolvers/asset-resolver.js +0 -13
  195. package/packages/client/dist/resolvers/local-resolver.js +8 -255
  196. package/packages/client/dist/resolvers/remote-resolver.js +1 -233
  197. package/packages/client/dist/runner/binary.js +1 -404
  198. package/packages/client/dist/runner/cli.js +17 -1571
  199. package/packages/client/dist/runner/epic-background-dispatcher.js +1 -124
  200. package/packages/client/dist/runner/headless/adapters.js +1 -49
  201. package/packages/client/dist/runner/headless/background-root.js +1 -85
  202. package/packages/client/dist/runner/headless/claude-code-adapter.js +1 -79
  203. package/packages/client/dist/runner/headless/continuous-story-workspace.js +11 -1776
  204. package/packages/client/dist/runner/headless/epic-git-reconciliation-inventory.js +1 -69
  205. package/packages/client/dist/runner/headless/epic-merge-candidate-qa.js +2 -111
  206. package/packages/client/dist/runner/headless/epic-terminal-git-cli-adapter.js +10 -1464
  207. package/packages/client/dist/runner/headless/epic-terminal-git-runner.js +2 -357
  208. package/packages/client/dist/runner/headless/fake-adapter.js +1 -62
  209. package/packages/client/dist/runner/headless/managed-environment-cleanup.js +1 -274
  210. package/packages/client/dist/runner/headless/managed-profile.js +1 -149
  211. package/packages/client/dist/runner/headless/opencode-adapter.js +2 -145
  212. package/packages/client/dist/runner/headless/prepared-story-bundle.js +1 -43
  213. package/packages/client/dist/runner/headless/resolver.js +1 -231
  214. package/packages/client/dist/runner/headless/run-yolo.js +1 -886
  215. package/packages/client/dist/runner/headless/run-yoloop.js +2 -2657
  216. package/packages/client/dist/runner/headless/types.js +2 -575
  217. package/packages/client/dist/runner/host-capacity.js +1 -59
  218. package/packages/client/dist/runner/local-console.js +13 -396
  219. package/packages/client/dist/runner/portal-sync-worker.js +1 -1487
  220. package/packages/client/dist/runner/project-identity.js +1 -106
  221. package/packages/client/dist/runner/scheduler.js +7 -995
  222. package/packages/client/dist/runner-cli.js +2 -18
  223. package/packages/client/dist/state/invocation-shape.js +1 -13
  224. package/packages/client/dist/state/project-state-snapshot.js +1 -1754
  225. package/packages/client/dist/state/state-json-repair.js +3 -785
  226. package/packages/client/dist/state/structural-dag-projection.js +1 -118
  227. package/packages/client/dist/telemetry/index.js +1 -5
  228. package/packages/client/dist/telemetry/offline-queue.js +1 -131
  229. package/packages/client/dist/tier/index.js +1 -5
  230. package/packages/client/dist/tier/tier-aware-client.js +1 -405
  231. package/packages/client/dist/types/index.js +1 -38
  232. package/packages/client/dist/version.js +1 -27
  233. package/packages/client/dist/yolo/change-evidence-collector.d.ts +10 -0
  234. package/packages/client/dist/yolo/change-evidence-collector.js +1 -262
  235. package/packages/client/dist/yolo/invoke-envelope-capability.js +1 -65
  236. package/packages/client/dist/yolo/spec-envelope-collector.js +5 -184
  237. package/packages/client/dist/yoloop/discovery-hook.js +2 -300
  238. package/packages/client/dist/yoloop/index.js +1 -8
  239. package/packages/client/dist/yoloop/invoke-hooks.js +12 -669
  240. package/packages/client/dist/yoloop/shared-discover-epics.js +1 -1007
  241. package/packages/client/dist/yoloop/shared-yoloop-types.js +1 -33
  242. package/packages/client/dist/yoloop/target-normalization.js +1 -180
  243. package/packages/client/dist/yoloop/yoloop-client-state-store.js +1 -1920
  244. package/targets-stubs/antigravity/gemini.md +1 -1
  245. package/targets-stubs/antigravity/skill/SKILL.md +1 -1
  246. package/targets-stubs/claude-code/neocortex-root.agent.yaml +1 -1
  247. package/targets-stubs/claude-code/neocortex-root.md +2 -2
  248. package/targets-stubs/claude-code/neocortex.agent.yaml +1 -1
  249. package/targets-stubs/claude-code/neocortex.md +2 -2
  250. package/targets-stubs/codex/AGENTS.md +1 -1
  251. package/targets-stubs/cursor/agent.md +2 -2
  252. package/targets-stubs/gemini-cli/agent.md +2 -2
  253. package/targets-stubs/opencode/neocortex-root.md +1 -1
  254. package/targets-stubs/vscode/neocortex.agent.md +2 -2
@@ -1,337 +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
- causalAuthRecovery;
44
- token = null;
45
- refreshToken = null;
46
- lastRecoveryResult = null;
47
- constructor(options) {
48
- this.serverUrl = options.serverUrl.replace(/\/+$/, '');
49
- this.licenseKey = options.licenseKey;
50
- this.cache = options.cacheProvider ?? new NoOpCache();
51
- this.clientVersion = options.clientVersion ?? CLIENT_VERSION;
52
- this.strictReadOnly = options.strictReadOnly ?? false;
53
- this.causalAuthRecovery = options.causalAuthRecovery ?? false;
54
- this.machineId = getMachineFingerprint({ strictReadOnly: this.strictReadOnly });
55
- }
56
- /**
57
- * Get a valid JWT token. Checks memory, cache, refresh token, then activation.
58
- * NEVER throws - returns null on failure.
59
- *
60
- * Flow:
61
- * 1. in-memory JWT valid? -> return
62
- * 2. in-memory JWT needs-refresh? -> refresh(refresh_token) -> return
63
- * 3. cached JWT valid? -> return
64
- * 4. cached JWT needs-refresh? -> refresh(refresh_token) -> return
65
- * 5. cached refresh_token exists? -> refresh(refresh_token) -> return (Story 31.02)
66
- * 6. activate() -> return
67
- */
68
- async getToken() {
69
- try {
70
- if (this.strictReadOnly) {
71
- const inspection = await this.inspectToken();
72
- return inspection.status === 'authenticated' ? inspection.token : null;
73
- }
74
- // 1. Check in-memory token
75
- if (this.token) {
76
- const validity = this.checkTokenValidity(this.token);
77
- if (validity === 'valid')
78
- return this.token;
79
- if (validity === 'needs-refresh') {
80
- if (this.strictReadOnly)
81
- return this.token;
82
- const refreshed = await this.refresh();
83
- return refreshed?.token ?? this.token; // fallback to current if refresh fails
84
- }
85
- // expired or invalid - clear memory
86
- this.token = null;
87
- }
88
- // 2. Check JWT cache
89
- const cached = await this.loadFromCache();
90
- if (cached) {
91
- this.token = cached;
92
- const validity = this.checkTokenValidity(cached);
93
- if (validity === 'valid')
94
- return cached;
95
- if (validity === 'needs-refresh') {
96
- if (this.strictReadOnly)
97
- return cached;
98
- const refreshed = await this.refresh();
99
- return refreshed?.token ?? cached; // fallback to current if refresh fails
100
- }
101
- // expired - clear
102
- this.token = null;
103
- }
104
- // Strict inspection never turns authentication into activation or token
105
- // refresh state. Missing/expired cached credentials fail closed.
106
- if (this.strictReadOnly)
107
- return null;
108
- // 3. Try refresh with cached refresh_token (Story 31.02/31.03)
109
- // Lazy load refresh_token from cache if not in memory
110
- if (!this.refreshToken) {
111
- this.refreshToken = await this.loadRefreshTokenFromCache();
112
- }
113
- if (this.refreshToken) {
114
- const refreshed = await this.refresh();
115
- if (refreshed?.token)
116
- return refreshed.token;
117
- if (this.causalAuthRecovery)
118
- return null;
119
- }
120
- // 4. Activate (last resort)
121
- const result = await this.activate();
122
- return result?.token ?? null;
123
- }
124
- catch {
125
- return null;
126
- }
127
- }
128
- /** Read-only authentication classification. It never refreshes, activates, clears or writes cache state. */
129
- async inspectToken() {
130
- try {
131
- const candidate = this.token ?? await this.loadFromCache();
132
- if (candidate) {
133
- const validity = this.checkTokenValidity(candidate);
134
- if (validity === 'valid')
135
- return { status: 'authenticated', token: candidate };
136
- return { status: 'refresh-required', reason: validity === 'needs-refresh' ? 'near-expiry' : 'expired' };
137
- }
138
- return this.licenseKey
139
- ? { status: 'refresh-required', reason: 'unavailable' }
140
- : { status: 'not-configured' };
141
- }
142
- catch {
143
- return this.licenseKey
144
- ? { status: 'refresh-required', reason: 'unavailable' }
145
- : { status: 'not-configured' };
146
- }
147
- }
148
- /** Last causal result, excluding raw server bodies and refresh credentials. */
149
- getLastRecoveryResult() {
150
- return this.lastRecoveryResult;
151
- }
152
- refreshRequired(cause, action) {
153
- this.lastRecoveryResult = { status: 'refresh-required', cause, action };
154
- return null;
155
- }
156
- /**
157
- * Activate through the endpoint matching the configured credential type.
158
- * Stores token and refresh_token in memory and cache on success.
159
- * NEVER throws - returns null on failure.
160
- */
161
- async activate() {
162
- if (this.strictReadOnly)
163
- return null;
164
- try {
165
- const apiKey = this.licenseKey.startsWith('nxk_');
166
- const endpoint = apiKey ? 'activate-key' : 'activate';
167
- const credential = apiKey ? { api_key: this.licenseKey } : { license_key: this.licenseKey };
168
- const response = await fetch(`${this.serverUrl}/api/v1/license/${endpoint}`, {
169
- method: 'POST',
170
- headers: { 'Content-Type': 'application/json' },
171
- body: JSON.stringify({
172
- ...credential,
173
- machine_id: this.machineId,
174
- client_version: this.clientVersion,
175
- }),
176
- });
177
- if (!response.ok)
178
- return null;
179
- const data = (await response.json());
180
- if (data.tier !== undefined && data.tier !== 'free' && data.tier !== 'pro'
181
- && data.tier !== 'enterprise')
182
- return null;
183
- this.token = data.token;
184
- this.refreshToken = data.refresh_token ?? null;
185
- // Drain capability-backed persistence before returning so invoke receipt
186
- // completion cannot race an owned cache effect.
187
- await this.cache.set(CACHE_KEY, data.token, data.expires_in * 1000).catch(() => { });
188
- // Persist refresh token with 7-day TTL (fire-and-forget)
189
- if (data.refresh_token) {
190
- await this.cache.set(REFRESH_CACHE_KEY, data.refresh_token, REFRESH_TOKEN_TTL_MS).catch(() => { });
191
- }
192
- return {
193
- token: data.token,
194
- expiresIn: data.expires_in,
195
- refreshToken: data.refresh_token,
196
- tier: data.tier,
197
- };
198
- }
199
- catch {
200
- return null;
201
- }
202
- }
203
- /**
204
- * Refresh using refresh_token by calling POST /api/v1/license/refresh.
205
- * Sends refresh_token in body (no Authorization header needed).
206
- * Handles token rotation: stores the new refresh_token from response.
207
- * NEVER throws - returns null on failure.
208
- *
209
- * Story 31.02: Signature changed from refresh(currentToken) to refresh().
210
- * The refresh_token in the body is the credential, not the JWT.
211
- *
212
- * @param _currentToken - Deprecated. Kept for backward compat but ignored.
213
- */
214
- async refresh(_currentToken) {
215
- if (this.strictReadOnly)
216
- return null;
217
- try {
218
- // Load refresh_token: in-memory first, then cache
219
- const rt = this.refreshToken ?? await this.loadRefreshTokenFromCache();
220
- if (!rt) {
221
- // No refresh token available -- cannot use new flow
222
- return this.refreshRequired('not-configured', 'reactivate');
223
- }
224
- const response = await fetch(`${this.serverUrl}/api/v1/license/refresh`, {
225
- method: 'POST',
226
- headers: { 'Content-Type': 'application/json' },
227
- body: JSON.stringify({ refresh_token: rt }),
228
- });
229
- if (!response.ok) {
230
- let code = '';
231
- try {
232
- code = String((await response.json()).error ?? '');
233
- }
234
- catch { /* bounded classification */ }
235
- if (response.status === 429)
236
- return this.refreshRequired('rate-limited', 'retry-later');
237
- if (response.status >= 500)
238
- return this.refreshRequired('service-unavailable', 'retry-later');
239
- if (code === 'invalid_grant' || code === 'revoked')
240
- return this.refreshRequired('revoked', 'reactivate');
241
- if (code === 'invalid_scope' || code === 'scope_denied')
242
- return this.refreshRequired('scope-denied', 'request-scope');
243
- if (code === 'client_denied')
244
- return this.refreshRequired('client-denied', 'stop');
245
- return this.refreshRequired('protocol-invalid', 'stop');
246
- }
247
- const data = (await response.json());
248
- this.token = data.token;
249
- // Token rotation: server issues new refresh token
250
- this.refreshToken = data.refresh_token ?? null;
251
- await this.cache.set(CACHE_KEY, data.token, data.expires_in * 1000).catch(() => { });
252
- // Persist rotated refresh token (fire-and-forget)
253
- if (data.refresh_token) {
254
- await this.cache.set(REFRESH_CACHE_KEY, data.refresh_token, REFRESH_TOKEN_TTL_MS).catch(() => { });
255
- }
256
- this.lastRecoveryResult = {
257
- status: 'authenticated', generation: 0, accessCredential: data.token,
258
- expiresAt: new Date(Date.now() + data.expires_in * 1000).toISOString(),
259
- };
260
- return {
261
- token: data.token,
262
- expiresIn: data.expires_in,
263
- refreshToken: data.refresh_token,
264
- };
265
- }
266
- catch {
267
- return this.refreshRequired('transport-error', 'retry-later');
268
- }
269
- }
270
- /**
271
- * Force-refresh the token.
272
- * Used when tier_changed is detected or a 401 response indicates the token is expired.
273
- * Does not clear or re-activate on an ambiguous refresh failure. Recovery is
274
- * governed by the causal result so transient or uncertain state is preserved.
275
- * NEVER throws - returns new token or null on failure.
276
- *
277
- * Story 18.8: Updated to prefer refresh over re-activate (preserves updated tier).
278
- * Story 31.02: Uses refresh_token flow instead of JWT-based refresh.
279
- */
280
- async forceRefresh() {
281
- if (this.strictReadOnly)
282
- return null;
283
- try {
284
- // 1. Try refresh with refresh_token first
285
- const refreshResult = await this.refresh();
286
- if (refreshResult?.token)
287
- return refreshResult.token;
288
- if (this.causalAuthRecovery)
289
- return null;
290
- // Compatibility path. P224.04 switches invoke consumers to causal mode;
291
- // older direct library consumers retain their historical explicit force.
292
- this.token = null;
293
- this.refreshToken = null;
294
- await this.cache.clear().catch(() => { });
295
- const result = await this.activate();
296
- return result?.token ?? null;
297
- }
298
- catch {
299
- return null;
300
- }
301
- }
302
- // ── Private Methods ─────────────────────────────────────────────────
303
- checkTokenValidity(token) {
304
- try {
305
- const payload = decodeJwt(token);
306
- if (!payload.exp)
307
- return 'expired';
308
- const now = Math.floor(Date.now() / 1000);
309
- if (payload.exp <= now)
310
- return 'expired';
311
- if (payload.exp - now <= REFRESH_THRESHOLD_S)
312
- return 'needs-refresh';
313
- return 'valid';
314
- }
315
- catch {
316
- return 'expired';
317
- }
318
- }
319
- async loadFromCache() {
320
- try {
321
- return await this.cache.get(CACHE_KEY);
322
- }
323
- catch {
324
- return null;
325
- }
326
- }
327
- async loadRefreshTokenFromCache() {
328
- try {
329
- const rt = await this.cache.get(REFRESH_CACHE_KEY);
330
- // Guard against empty/expired entries
331
- return rt && rt.length > 0 ? rt : null;
332
- }
333
- catch {
334
- return null;
335
- }
336
- }
337
- }
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};