expandai 0.0.2 → 0.0.4

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 (271) hide show
  1. package/README.md +42 -5
  2. package/build/dts/ApiClient.d.ts +128 -194
  3. package/build/dts/ApiClient.d.ts.map +1 -1
  4. package/build/dts/Auth/Domain.d.ts +95 -0
  5. package/build/dts/Auth/Domain.d.ts.map +1 -0
  6. package/build/dts/Auth/ManualAuthorization.d.ts +107 -0
  7. package/build/dts/Auth/ManualAuthorization.d.ts.map +1 -0
  8. package/build/dts/Auth/PendingInit.d.ts +35 -0
  9. package/build/dts/Auth/PendingInit.d.ts.map +1 -0
  10. package/build/dts/Auth/Pkce.d.ts +10 -0
  11. package/build/dts/Auth/Pkce.d.ts.map +1 -0
  12. package/build/dts/Auth/SetupGrantAuthorization.d.ts +34 -0
  13. package/build/dts/Auth/SetupGrantAuthorization.d.ts.map +1 -0
  14. package/build/dts/Authentication.d.ts +10 -9
  15. package/build/dts/Authentication.d.ts.map +1 -1
  16. package/build/dts/BrowserOAuth.d.ts +7 -7
  17. package/build/dts/BrowserOAuth.d.ts.map +1 -1
  18. package/build/dts/CommandPath.d.ts +2 -0
  19. package/build/dts/CommandPath.d.ts.map +1 -0
  20. package/build/dts/Commands/Fetch.d.ts.map +1 -1
  21. package/build/dts/Commands/Hook.d.ts +5 -5
  22. package/build/dts/Commands/Init.d.ts +55 -0
  23. package/build/dts/Commands/Init.d.ts.map +1 -0
  24. package/build/dts/Commands/Mcp.d.ts +6 -6
  25. package/build/dts/Commands/Search.d.ts.map +1 -1
  26. package/build/dts/Commands/Skill.d.ts +4 -4
  27. package/build/dts/Commands/Status.d.ts +27 -0
  28. package/build/dts/Commands/Status.d.ts.map +1 -0
  29. package/build/dts/Commands/Telemetry.d.ts +7 -0
  30. package/build/dts/Commands/Telemetry.d.ts.map +1 -0
  31. package/build/dts/Commands/Uninstall.d.ts +4 -4
  32. package/build/dts/Config.d.ts +108 -17
  33. package/build/dts/Config.d.ts.map +1 -1
  34. package/build/dts/Hook/SnapshotNote.d.ts +8 -4
  35. package/build/dts/Hook/SnapshotNote.d.ts.map +1 -1
  36. package/build/dts/Init/ClaudeAdapter.d.ts +61 -0
  37. package/build/dts/Init/ClaudeAdapter.d.ts.map +1 -0
  38. package/build/dts/Init/ClaudeProfile.d.ts +77 -0
  39. package/build/dts/Init/ClaudeProfile.d.ts.map +1 -0
  40. package/build/dts/Init/Domain.d.ts +139 -0
  41. package/build/dts/Init/Domain.d.ts.map +1 -0
  42. package/build/dts/Init/HarnessAdapter.d.ts +33 -0
  43. package/build/dts/Init/HarnessAdapter.d.ts.map +1 -0
  44. package/build/dts/Init/HarnessDetector.d.ts +19 -0
  45. package/build/dts/Init/HarnessDetector.d.ts.map +1 -0
  46. package/build/dts/Init/HarnessRegistry.d.ts +50 -0
  47. package/build/dts/Init/HarnessRegistry.d.ts.map +1 -0
  48. package/build/dts/Init/MutationTransaction.d.ts +96 -0
  49. package/build/dts/Init/MutationTransaction.d.ts.map +1 -0
  50. package/build/dts/Init/Service.d.ts +72 -0
  51. package/build/dts/Init/Service.d.ts.map +1 -0
  52. package/build/dts/Init/StandardAdapters.d.ts +42 -0
  53. package/build/dts/Init/StandardAdapters.d.ts.map +1 -0
  54. package/build/dts/Init/Status.d.ts +149 -0
  55. package/build/dts/Init/Status.d.ts.map +1 -0
  56. package/build/dts/Install/Claude/Hook.d.ts +57 -29
  57. package/build/dts/Install/Claude/Hook.d.ts.map +1 -1
  58. package/build/dts/Install/Claude/Mcp.d.ts +21 -18
  59. package/build/dts/Install/Claude/Mcp.d.ts.map +1 -1
  60. package/build/dts/Install/Claude/Skill.d.ts +14 -15
  61. package/build/dts/Install/Claude/Skill.d.ts.map +1 -1
  62. package/build/dts/Install/Codex/Mcp.d.ts +14 -8
  63. package/build/dts/Install/Codex/Mcp.d.ts.map +1 -1
  64. package/build/dts/Install/Codex/Skill.d.ts +4 -2
  65. package/build/dts/Install/Codex/Skill.d.ts.map +1 -1
  66. package/build/dts/Install/Cursor/Mcp.d.ts +13 -13
  67. package/build/dts/Install/Cursor/Mcp.d.ts.map +1 -1
  68. package/build/dts/Install/Cursor/Skill.d.ts +4 -2
  69. package/build/dts/Install/Cursor/Skill.d.ts.map +1 -1
  70. package/build/dts/Install/Domain.d.ts +35 -5
  71. package/build/dts/Install/Domain.d.ts.map +1 -1
  72. package/build/dts/Install/Hook.d.ts +4 -4
  73. package/build/dts/Install/Hook.d.ts.map +1 -1
  74. package/build/dts/Install/Mcp.d.ts +5 -5
  75. package/build/dts/Install/Mcp.d.ts.map +1 -1
  76. package/build/dts/Install/Opencode/Hook.d.ts +4 -3
  77. package/build/dts/Install/Opencode/Hook.d.ts.map +1 -1
  78. package/build/dts/Install/Opencode/Mcp.d.ts +11 -11
  79. package/build/dts/Install/Opencode/Mcp.d.ts.map +1 -1
  80. package/build/dts/Install/Opencode/Skill.d.ts +4 -2
  81. package/build/dts/Install/Opencode/Skill.d.ts.map +1 -1
  82. package/build/dts/Install/Skill.d.ts +3 -3
  83. package/build/dts/Install/Uninstall.d.ts +6 -6
  84. package/build/dts/Install/Uninstall.d.ts.map +1 -1
  85. package/build/dts/MarkdownAnsi.d.ts +29 -0
  86. package/build/dts/MarkdownAnsi.d.ts.map +1 -0
  87. package/build/dts/Mcp/ExpandDocs.d.ts +17 -5
  88. package/build/dts/Mcp/ExpandDocs.d.ts.map +1 -1
  89. package/build/dts/Mcp/Server.d.ts +1 -1
  90. package/build/dts/Mcp/Server.d.ts.map +1 -1
  91. package/build/dts/Mcp/tools/Citations.d.ts +100 -71
  92. package/build/dts/Mcp/tools/Citations.d.ts.map +1 -1
  93. package/build/dts/Mcp/tools/Fetch.d.ts +16 -15
  94. package/build/dts/Mcp/tools/Fetch.d.ts.map +1 -1
  95. package/build/dts/SecureFile.d.ts +23 -0
  96. package/build/dts/SecureFile.d.ts.map +1 -0
  97. package/build/dts/Snippets.d.ts +11 -12
  98. package/build/dts/Snippets.d.ts.map +1 -1
  99. package/build/dts/Telemetry.d.ts +30 -0
  100. package/build/dts/Telemetry.d.ts.map +1 -0
  101. package/build/dts/Version.d.ts +2 -0
  102. package/build/dts/Version.d.ts.map +1 -0
  103. package/build/dts/Xdg.d.ts +11 -0
  104. package/build/dts/Xdg.d.ts.map +1 -0
  105. package/build/esm/ApiClient.js +133 -10
  106. package/build/esm/ApiClient.js.map +1 -1
  107. package/build/esm/Auth/Domain.js +56 -0
  108. package/build/esm/Auth/Domain.js.map +1 -0
  109. package/build/esm/Auth/ManualAuthorization.js +253 -0
  110. package/build/esm/Auth/ManualAuthorization.js.map +1 -0
  111. package/build/esm/Auth/PendingInit.js +267 -0
  112. package/build/esm/Auth/PendingInit.js.map +1 -0
  113. package/build/esm/Auth/Pkce.js +23 -0
  114. package/build/esm/Auth/Pkce.js.map +1 -0
  115. package/build/esm/Auth/SetupGrantAuthorization.js +91 -0
  116. package/build/esm/Auth/SetupGrantAuthorization.js.map +1 -0
  117. package/build/esm/Authentication.js +38 -7
  118. package/build/esm/Authentication.js.map +1 -1
  119. package/build/esm/BrowserOAuth.js +7 -10
  120. package/build/esm/BrowserOAuth.js.map +1 -1
  121. package/build/esm/CommandPath.js +31 -0
  122. package/build/esm/CommandPath.js.map +1 -0
  123. package/build/esm/Commands/Fetch.js +30 -6
  124. package/build/esm/Commands/Fetch.js.map +1 -1
  125. package/build/esm/Commands/Init.js +371 -0
  126. package/build/esm/Commands/Init.js.map +1 -0
  127. package/build/esm/Commands/Search.js +6 -3
  128. package/build/esm/Commands/Search.js.map +1 -1
  129. package/build/esm/Commands/Status.js +186 -0
  130. package/build/esm/Commands/Status.js.map +1 -0
  131. package/build/esm/Commands/Telemetry.js +23 -0
  132. package/build/esm/Commands/Telemetry.js.map +1 -0
  133. package/build/esm/Config.js +502 -28
  134. package/build/esm/Config.js.map +1 -1
  135. package/build/esm/Hook/Claude.js +1 -1
  136. package/build/esm/Hook/Claude.js.map +1 -1
  137. package/build/esm/Hook/SnapshotNote.js +54 -7
  138. package/build/esm/Hook/SnapshotNote.js.map +1 -1
  139. package/build/esm/Init/ClaudeAdapter.js +137 -0
  140. package/build/esm/Init/ClaudeAdapter.js.map +1 -0
  141. package/build/esm/Init/ClaudeProfile.js +344 -0
  142. package/build/esm/Init/ClaudeProfile.js.map +1 -0
  143. package/build/esm/Init/Domain.js +118 -0
  144. package/build/esm/Init/Domain.js.map +1 -0
  145. package/build/esm/Init/HarnessAdapter.js +21 -0
  146. package/build/esm/Init/HarnessAdapter.js.map +1 -0
  147. package/build/esm/Init/HarnessDetector.js +65 -0
  148. package/build/esm/Init/HarnessDetector.js.map +1 -0
  149. package/build/esm/Init/HarnessRegistry.js +58 -0
  150. package/build/esm/Init/HarnessRegistry.js.map +1 -0
  151. package/build/esm/Init/MutationTransaction.js +494 -0
  152. package/build/esm/Init/MutationTransaction.js.map +1 -0
  153. package/build/esm/Init/Service.js +319 -0
  154. package/build/esm/Init/Service.js.map +1 -0
  155. package/build/esm/Init/StandardAdapters.js +116 -0
  156. package/build/esm/Init/StandardAdapters.js.map +1 -0
  157. package/build/esm/Init/Status.js +215 -0
  158. package/build/esm/Init/Status.js.map +1 -0
  159. package/build/esm/Install/Claude/Hook.js +52 -64
  160. package/build/esm/Install/Claude/Hook.js.map +1 -1
  161. package/build/esm/Install/Claude/Mcp.js +56 -26
  162. package/build/esm/Install/Claude/Mcp.js.map +1 -1
  163. package/build/esm/Install/Claude/Skill.js +49 -27
  164. package/build/esm/Install/Claude/Skill.js.map +1 -1
  165. package/build/esm/Install/Codex/Mcp.js +9 -4
  166. package/build/esm/Install/Codex/Mcp.js.map +1 -1
  167. package/build/esm/Install/Codex/Skill.js +4 -1
  168. package/build/esm/Install/Codex/Skill.js.map +1 -1
  169. package/build/esm/Install/Cursor/Mcp.js +7 -4
  170. package/build/esm/Install/Cursor/Mcp.js.map +1 -1
  171. package/build/esm/Install/Cursor/Skill.js +4 -1
  172. package/build/esm/Install/Cursor/Skill.js.map +1 -1
  173. package/build/esm/Install/Domain.js +60 -3
  174. package/build/esm/Install/Domain.js.map +1 -1
  175. package/build/esm/Install/Hook.js.map +1 -1
  176. package/build/esm/Install/Mcp.js +1 -1
  177. package/build/esm/Install/Mcp.js.map +1 -1
  178. package/build/esm/Install/Opencode/Hook.js +1 -1
  179. package/build/esm/Install/Opencode/Hook.js.map +1 -1
  180. package/build/esm/Install/Opencode/Mcp.js +6 -3
  181. package/build/esm/Install/Opencode/Mcp.js.map +1 -1
  182. package/build/esm/Install/Opencode/Skill.js +4 -1
  183. package/build/esm/Install/Opencode/Skill.js.map +1 -1
  184. package/build/esm/Install/Opencode/expandai-webfetch.js +27 -9
  185. package/build/esm/Install/Skill.js.map +1 -1
  186. package/build/esm/Install/Uninstall.js +2 -2
  187. package/build/esm/Install/Uninstall.js.map +1 -1
  188. package/build/esm/MarkdownAnsi.js +142 -0
  189. package/build/esm/MarkdownAnsi.js.map +1 -0
  190. package/build/esm/Mcp/ExpandDocs.js +44 -52
  191. package/build/esm/Mcp/ExpandDocs.js.map +1 -1
  192. package/build/esm/Mcp/RequestHeaders.js.map +1 -1
  193. package/build/esm/Mcp/Server.js +2 -1
  194. package/build/esm/Mcp/Server.js.map +1 -1
  195. package/build/esm/Mcp/tools/Citations.js +109 -8
  196. package/build/esm/Mcp/tools/Citations.js.map +1 -1
  197. package/build/esm/Mcp/tools/Fetch.js +36 -12
  198. package/build/esm/Mcp/tools/Fetch.js.map +1 -1
  199. package/build/esm/SecureFile.js +36 -0
  200. package/build/esm/SecureFile.js.map +1 -0
  201. package/build/esm/Snippets.js +12 -1
  202. package/build/esm/Snippets.js.map +1 -1
  203. package/build/esm/Telemetry.js +157 -0
  204. package/build/esm/Telemetry.js.map +1 -0
  205. package/build/esm/Version.js +4 -0
  206. package/build/esm/Version.js.map +1 -0
  207. package/build/esm/Xdg.js +15 -0
  208. package/build/esm/Xdg.js.map +1 -0
  209. package/build/esm/main.js +122 -14
  210. package/build/esm/main.js.map +1 -1
  211. package/build/skills/expandai/SKILL.md +37 -8
  212. package/package.json +4 -4
  213. package/src/ApiClient.ts +206 -13
  214. package/src/Auth/Domain.ts +63 -0
  215. package/src/Auth/ManualAuthorization.ts +296 -0
  216. package/src/Auth/PendingInit.ts +338 -0
  217. package/src/Auth/Pkce.ts +26 -0
  218. package/src/Auth/SetupGrantAuthorization.ts +116 -0
  219. package/src/Authentication.ts +49 -11
  220. package/src/BrowserOAuth.ts +10 -12
  221. package/src/CommandPath.ts +30 -0
  222. package/src/Commands/Fetch.ts +42 -11
  223. package/src/Commands/Init.ts +489 -0
  224. package/src/Commands/Search.ts +8 -3
  225. package/src/Commands/Status.ts +228 -0
  226. package/src/Commands/Telemetry.ts +42 -0
  227. package/src/Config.ts +695 -50
  228. package/src/Hook/Claude.ts +1 -1
  229. package/src/Hook/SnapshotNote.ts +55 -7
  230. package/src/Init/ClaudeAdapter.ts +191 -0
  231. package/src/Init/ClaudeProfile.ts +453 -0
  232. package/src/Init/Domain.ts +153 -0
  233. package/src/Init/HarnessAdapter.ts +35 -0
  234. package/src/Init/HarnessDetector.ts +77 -0
  235. package/src/Init/HarnessRegistry.ts +87 -0
  236. package/src/Init/MutationTransaction.ts +747 -0
  237. package/src/Init/Service.ts +385 -0
  238. package/src/Init/StandardAdapters.ts +141 -0
  239. package/src/Init/Status.ts +253 -0
  240. package/src/Install/Claude/Hook.ts +81 -91
  241. package/src/Install/Claude/Mcp.ts +80 -33
  242. package/src/Install/Claude/Skill.ts +70 -37
  243. package/src/Install/Codex/Mcp.ts +14 -9
  244. package/src/Install/Codex/Skill.ts +9 -5
  245. package/src/Install/Cursor/Mcp.ts +12 -9
  246. package/src/Install/Cursor/Skill.ts +9 -5
  247. package/src/Install/Domain.ts +77 -4
  248. package/src/Install/Hook.ts +3 -3
  249. package/src/Install/Mcp.ts +6 -6
  250. package/src/Install/Opencode/Hook.ts +5 -5
  251. package/src/Install/Opencode/Mcp.ts +11 -8
  252. package/src/Install/Opencode/Skill.ts +9 -5
  253. package/src/Install/Opencode/expandai-webfetch.js +27 -9
  254. package/src/Install/Skill.ts +3 -3
  255. package/src/Install/Uninstall.ts +3 -3
  256. package/src/MarkdownAnsi.ts +162 -0
  257. package/src/Mcp/ExpandDocs.ts +46 -55
  258. package/src/Mcp/Server.ts +2 -1
  259. package/src/Mcp/tools/Citations.ts +117 -8
  260. package/src/Mcp/tools/Fetch.ts +40 -14
  261. package/src/SecureFile.ts +70 -0
  262. package/src/Snippets.ts +19 -12
  263. package/src/Telemetry.ts +186 -0
  264. package/src/Version.ts +3 -0
  265. package/src/Xdg.ts +18 -0
  266. package/src/main.ts +171 -12
  267. package/build/dts/DeviceAuth.d.ts +0 -87
  268. package/build/dts/DeviceAuth.d.ts.map +0 -1
  269. package/build/esm/DeviceAuth.js +0 -127
  270. package/build/esm/DeviceAuth.js.map +0 -1
  271. package/src/DeviceAuth.ts +0 -193
@@ -0,0 +1,338 @@
1
+ import { createHash } from 'node:crypto'
2
+ import { FileSystem, Path, Error as PlatformError } from '@effect/platform'
3
+ import { NodeContext } from '@effect/platform-node'
4
+ import { DateTime, Effect, Either, Option, Schema } from 'effect'
5
+ import { xdgConfigDirectory } from '../Xdg.js'
6
+ import {
7
+ CLI_AUTHORIZATION_CLIENT_ID,
8
+ PendingInitCorrupt,
9
+ type PendingInitKey,
10
+ PendingInitRecord,
11
+ PendingInitStorageError,
12
+ } from './Domain.js'
13
+
14
+ const PendingInitRecordJson = Schema.parseJson(PendingInitRecord)
15
+ const COMPLETION_CODE_RETENTION_GRACE_MS = 5 * 60 * 1_000
16
+
17
+ const PendingInitKeyTupleJson = Schema.parseJson(
18
+ Schema.Tuple(
19
+ Schema.String,
20
+ Schema.Literal(CLI_AUTHORIZATION_CLIENT_ID),
21
+ Schema.Literal('agent-harnesses'),
22
+ Schema.Literal('project', 'global'),
23
+ Schema.String,
24
+ ),
25
+ )
26
+
27
+ function isErrnoCode(input: unknown, code: string): boolean {
28
+ return typeof input === 'object' && input !== null && 'code' in input && input.code === code
29
+ }
30
+
31
+ function isAlreadyExists(error: unknown): boolean {
32
+ return (
33
+ error instanceof PlatformError.SystemError &&
34
+ (error.reason === 'AlreadyExists' || isErrnoCode(error.cause, 'EEXIST'))
35
+ )
36
+ }
37
+
38
+ /** Canonical, collision-free serialization of all pending authorization key fields. */
39
+ export function serializePendingInitKey(key: PendingInitKey): string {
40
+ return Schema.encodeSync(PendingInitKeyTupleJson)([
41
+ key.apiOrigin,
42
+ key.clientId,
43
+ key.harness,
44
+ key.scope,
45
+ key.canonicalScopeRoot,
46
+ ])
47
+ }
48
+
49
+ function ancestorPaths(path: Path.Path, current: string): string[] {
50
+ const parent = path.dirname(current)
51
+ return parent === current ? [current] : [current, ...ancestorPaths(path, parent)]
52
+ }
53
+
54
+ export class PendingInitStore extends Effect.Service<PendingInitStore>()('@expandai/cli/Auth/PendingInitStore', {
55
+ dependencies: [NodeContext.layer],
56
+ effect: Effect.gen(function* () {
57
+ const fileSystem = yield* FileSystem.FileSystem
58
+ const path = yield* Path.Path
59
+ const configDirectory = path.join(yield* xdgConfigDirectory, 'expandai')
60
+ const pendingPath = path.join(configDirectory, 'pending-init')
61
+
62
+ const storageError = (targetPath: string, error: unknown) =>
63
+ new PendingInitStorageError({ path: targetPath, error })
64
+
65
+ /**
66
+ * Maps a platform failure to the domain error for `targetPath`.
67
+ *
68
+ * Deliberately applied per call rather than once around each function: a
69
+ * blanket `mapError` over a whole `Effect.fn` body would also swallow
70
+ * `PendingInitCorrupt`, which `decodeRecord` raises and which `Status.ts`
71
+ * reports differently — corrupt state is recoverable by deleting the file,
72
+ * a storage failure is not.
73
+ */
74
+ const onStorage = <A>(targetPath: string, effect: Effect.Effect<A, PlatformError.PlatformError>) =>
75
+ effect.pipe(Effect.mapError((error) => storageError(targetPath, error)))
76
+
77
+ const assertNotSymbolicLink = Effect.fnUntraced(function* (targetPath: string) {
78
+ const result = yield* Effect.either(fileSystem.readLink(targetPath))
79
+ if (Either.isRight(result)) {
80
+ return yield* storageError(targetPath, new Error('Symbolic links are not allowed for pending authorization'))
81
+ }
82
+ const error = result.left
83
+ if (
84
+ error instanceof PlatformError.SystemError &&
85
+ (error.reason === 'InvalidData' ||
86
+ error.reason === 'NotFound' ||
87
+ (error.method === 'readLink' && isErrnoCode(error.cause, 'EINVAL')))
88
+ ) {
89
+ return
90
+ }
91
+ return yield* storageError(targetPath, error)
92
+ })
93
+
94
+ const ensureDirectory = Effect.fnUntraced(function* () {
95
+ yield* assertNotSymbolicLink(configDirectory)
96
+ yield* assertNotSymbolicLink(pendingPath)
97
+ yield* onStorage(pendingPath, fileSystem.makeDirectory(pendingPath, { recursive: true, mode: 0o700 }))
98
+ yield* assertNotSymbolicLink(configDirectory)
99
+ yield* assertNotSymbolicLink(pendingPath)
100
+ const directoryInfo = yield* onStorage(pendingPath, fileSystem.stat(pendingPath))
101
+ if (directoryInfo.type !== 'Directory') {
102
+ return yield* storageError(pendingPath, new Error('Pending authorization path is not a directory'))
103
+ }
104
+ if (process.platform !== 'win32') {
105
+ yield* onStorage(configDirectory, fileSystem.chmod(configDirectory, 0o700))
106
+ yield* onStorage(pendingPath, fileSystem.chmod(pendingPath, 0o700))
107
+ }
108
+ })
109
+
110
+ const recordPath = (key: PendingInitKey) => {
111
+ const digest = createHash('sha256').update(serializePendingInitKey(key)).digest('hex')
112
+ return path.join(pendingPath, `${digest}.json`)
113
+ }
114
+
115
+ const decodeRecord = Effect.fnUntraced(function* (targetPath: string, encoded: string) {
116
+ const record = yield* Schema.decode(PendingInitRecordJson)(encoded).pipe(
117
+ Effect.mapError(
118
+ () =>
119
+ new PendingInitCorrupt({
120
+ path: targetPath,
121
+ error: new Error('Stored pending authorization did not match the expected schema'),
122
+ }),
123
+ ),
124
+ )
125
+ if (recordPath(record.key) !== targetPath) {
126
+ return yield* new PendingInitCorrupt({
127
+ path: targetPath,
128
+ error: new Error('Stored pending authorization key did not match its file'),
129
+ })
130
+ }
131
+ return record
132
+ })
133
+
134
+ const readRecordPath = Effect.fnUntraced(function* (targetPath: string) {
135
+ yield* assertNotSymbolicLink(targetPath)
136
+ const exists = yield* onStorage(targetPath, fileSystem.exists(targetPath))
137
+ if (!exists) return Option.none<PendingInitRecord>()
138
+ const info = yield* onStorage(targetPath, fileSystem.stat(targetPath))
139
+ if (info.type !== 'File') return yield* storageError(targetPath, new Error('Pending state is not a regular file'))
140
+ if (process.platform !== 'win32' && (info.mode & 0o777) !== 0o600) {
141
+ return yield* storageError(targetPath, new Error('Pending state file mode is not 600'))
142
+ }
143
+ const encoded = yield* onStorage(targetPath, fileSystem.readFileString(targetPath))
144
+ return Option.some(yield* decodeRecord(targetPath, encoded))
145
+ })
146
+
147
+ const readRecord = (key: PendingInitKey) => readRecordPath(recordPath(key))
148
+
149
+ const isExpired = Effect.fnUntraced(function* (record: PendingInitRecord) {
150
+ const now = DateTime.toEpochMillis(yield* DateTime.now)
151
+ return DateTime.toEpochMillis(record.approvalExpiresAt) + COMPLETION_CODE_RETENTION_GRACE_MS <= now
152
+ })
153
+
154
+ const writeExclusive = Effect.fnUntraced(function* (record: PendingInitRecord) {
155
+ yield* ensureDirectory()
156
+ const targetPath = recordPath(record.key)
157
+ const encoded = yield* Schema.encode(PendingInitRecordJson)(record).pipe(
158
+ Effect.mapError((error) => storageError(targetPath, error)),
159
+ )
160
+ const created = yield* Effect.either(
161
+ Effect.scoped(
162
+ Effect.gen(function* () {
163
+ const file = yield* fileSystem.open(targetPath, { flag: 'wx', mode: 0o600 })
164
+ yield* file.writeAll(new TextEncoder().encode(encoded))
165
+ yield* file.sync
166
+ }),
167
+ ),
168
+ )
169
+ if (Either.isLeft(created)) {
170
+ // `wx` means an existing file belongs to another attempt — leave it.
171
+ if (isAlreadyExists(created.left)) return false
172
+ // Anything else failed *after* we created the file, so a zero-byte or
173
+ // half-written record is now sitting at the final path. Left there it
174
+ // fails every later read of this key, and interrupting between `open`
175
+ // and `writeAll` is enough to cause it.
176
+ yield* fileSystem.remove(targetPath).pipe(Effect.ignore)
177
+ return yield* storageError(targetPath, created.left)
178
+ }
179
+ if (process.platform !== 'win32') {
180
+ const chmodResult = yield* Effect.either(fileSystem.chmod(targetPath, 0o600))
181
+ if (Either.isLeft(chmodResult)) {
182
+ yield* fileSystem.remove(targetPath).pipe(Effect.ignore)
183
+ return yield* storageError(targetPath, chmodResult.left)
184
+ }
185
+ }
186
+ return true
187
+ })
188
+
189
+ /**
190
+ * Publishes `next` over the record for the same key, atomically.
191
+ *
192
+ * The caller used to do `removeIfMatch` then `putIfAbsent`. An interrupt
193
+ * between those two — Ctrl-C during the poll that runs on *every* `expandai
194
+ * init` while authorization is pending — deleted the pending record and
195
+ * wrote nothing back, so the next run minted a fresh code and asked the user
196
+ * to approve again with no error to explain it.
197
+ *
198
+ * `rename` over the target is atomic on POSIX, so an interrupt either leaves
199
+ * the old record or completes the new one. It is **not** a cross-process
200
+ * compare-and-swap: another process can publish between our read and our
201
+ * rename, and ours wins. That race is pre-existing and unaddressed here —
202
+ * closing it needs a per-key lock, and Windows replacement semantics need
203
+ * checking first. The name says `IfMatch` because it verifies before
204
+ * writing, not because it is a CAS.
205
+ */
206
+ const replaceIfMatch = Effect.fn('PendingInitStore.replaceIfMatch')(function* (
207
+ previous: PendingInitRecord,
208
+ next: PendingInitRecord,
209
+ ) {
210
+ yield* ensureDirectory()
211
+ const targetPath = recordPath(next.key)
212
+ if (recordPath(previous.key) !== targetPath) {
213
+ return yield* storageError(targetPath, new Error('Pending authorization replacement changed its key'))
214
+ }
215
+ const current = yield* readRecordPath(targetPath)
216
+ if (Option.isNone(current) || current.value.userCode !== previous.userCode) return false
217
+
218
+ const encoded = yield* Schema.encode(PendingInitRecordJson)(next).pipe(
219
+ Effect.mapError((error) => storageError(targetPath, error)),
220
+ )
221
+ // Same directory, so `rename` stays on one filesystem and is atomic.
222
+ //
223
+ // `acquireRelease` rather than manual cleanup on the typed-failure branches:
224
+ // a defect or an interrupt bypasses those branches entirely, and an
225
+ // abandoned `.tmp` is worse than it looks — it is a second copy of a live
226
+ // credential, `pruneExpired` only scans `.json` records so it never reaps
227
+ // one, and a fixed name made the next attempt fail on its own leftovers.
228
+ const staging = `${targetPath}.${process.pid}.${Math.random().toString(36).slice(2, 10)}.tmp`
229
+ const published = yield* Effect.scoped(
230
+ Effect.acquireRelease(Effect.succeed(staging), () => fileSystem.remove(staging).pipe(Effect.ignore)).pipe(
231
+ Effect.zipRight(
232
+ Effect.gen(function* () {
233
+ yield* assertNotSymbolicLink(staging)
234
+ yield* Effect.scoped(
235
+ Effect.gen(function* () {
236
+ const file = yield* fileSystem.open(staging, { flag: 'wx', mode: 0o600 })
237
+ yield* file.writeAll(new TextEncoder().encode(encoded))
238
+ yield* file.sync
239
+ }),
240
+ )
241
+ yield* fileSystem.rename(staging, targetPath)
242
+ }),
243
+ ),
244
+ ),
245
+ ).pipe(Effect.either)
246
+ if (Either.isLeft(published)) return yield* storageError(targetPath, published.left)
247
+ return true
248
+ })
249
+
250
+ const removeIfCurrent = Effect.fnUntraced(function* (record: PendingInitRecord) {
251
+ const targetPath = recordPath(record.key)
252
+ const current = yield* readRecordPath(targetPath)
253
+ if (Option.isNone(current) || current.value.userCode !== record.userCode) return false
254
+ yield* onStorage(targetPath, fileSystem.remove(targetPath))
255
+ return true
256
+ })
257
+
258
+ const get = Effect.fn('PendingInitStore.get')(function* (key: PendingInitKey) {
259
+ const record = yield* readRecord(key)
260
+ if (Option.isNone(record) || !(yield* isExpired(record.value))) return record
261
+ yield* removeIfCurrent(record.value)
262
+ return Option.none<PendingInitRecord>()
263
+ })
264
+
265
+ const peek = Effect.fn('PendingInitStore.peek')(function* (key: PendingInitKey) {
266
+ return yield* readRecord(key)
267
+ })
268
+
269
+ const putIfAbsent = Effect.fn('PendingInitStore.putIfAbsent')(function* (record: PendingInitRecord) {
270
+ const existing = yield* readRecord(record.key)
271
+ if (Option.isSome(existing) && !(yield* isExpired(existing.value))) return existing.value
272
+ if (Option.isSome(existing)) yield* removeIfCurrent(existing.value)
273
+ if (yield* writeExclusive(record)) return record
274
+ const winner = yield* readRecord(record.key)
275
+ return yield* Option.match(winner, {
276
+ onNone: () => storageError(recordPath(record.key), new Error('Pending record creation lost without a winner')),
277
+ onSome: Effect.succeed,
278
+ })
279
+ })
280
+
281
+ const removeIfMatch = Effect.fn('PendingInitStore.removeIfMatch')((record: PendingInitRecord) =>
282
+ removeIfCurrent(record),
283
+ )
284
+
285
+ const pruneExpired = Effect.fn('PendingInitStore.pruneExpired')(function* () {
286
+ yield* assertNotSymbolicLink(pendingPath)
287
+ const exists = yield* onStorage(pendingPath, fileSystem.exists(pendingPath))
288
+ if (!exists) {
289
+ return 0
290
+ }
291
+ const entries = yield* onStorage(pendingPath, fileSystem.readDirectory(pendingPath))
292
+ const removed = yield* Effect.forEach(
293
+ entries.filter((entry) => entry.endsWith('.json')),
294
+ (entry) =>
295
+ Effect.gen(function* () {
296
+ const record = yield* readRecordPath(path.join(pendingPath, entry))
297
+ if (Option.isNone(record) || !(yield* isExpired(record.value))) {
298
+ return 0
299
+ }
300
+ return (yield* removeIfCurrent(record.value)) ? 1 : 0
301
+ // One unreadable entry must not fail the sweep. Pruning runs
302
+ // on every begin, resume and refreshStatus, so a single
303
+ // corrupt or newer-format file would otherwise block all
304
+ // three — including the resume that would have recovered.
305
+ }).pipe(Effect.orElseSucceed(() => 0)),
306
+ )
307
+ return removed.reduce<number>((total, count) => total + count, 0)
308
+ })
309
+
310
+ const canonicalScopeRoot = Effect.fn('PendingInitStore.canonicalScopeRoot')(function* (
311
+ scope: PendingInitKey['scope'],
312
+ cwd = process.cwd(),
313
+ ) {
314
+ if (scope === 'global') return 'global'
315
+ const canonicalCwd = yield* onStorage(cwd, fileSystem.realPath(cwd))
316
+ const inspected = yield* Effect.forEach(ancestorPaths(path, canonicalCwd), (candidate) =>
317
+ onStorage(candidate, fileSystem.exists(path.join(candidate, '.git'))).pipe(
318
+ Effect.map((exists) => ({ candidate, exists })),
319
+ ),
320
+ )
321
+ const repositoryRoot = inspected.find(({ exists }) => exists)?.candidate
322
+ return repositoryRoot === undefined
323
+ ? canonicalCwd
324
+ : yield* onStorage(repositoryRoot, fileSystem.realPath(repositoryRoot))
325
+ })
326
+
327
+ return {
328
+ pendingPath,
329
+ get,
330
+ peek,
331
+ putIfAbsent,
332
+ replaceIfMatch,
333
+ removeIfMatch,
334
+ pruneExpired,
335
+ canonicalScopeRoot,
336
+ } as const
337
+ }),
338
+ }) {}
@@ -0,0 +1,26 @@
1
+ import { createHash, randomBytes } from 'node:crypto'
2
+ import { Redacted } from 'effect'
3
+
4
+ /**
5
+ * RFC 7636 requires 43–128 characters of unreserved alphabet; 32 random bytes
6
+ * encode to 43 base64url characters, which is also what the API's
7
+ * `^[A-Za-z0-9_-]{43}$` challenge check expects.
8
+ */
9
+ const VERIFIER_BYTES = 32
10
+
11
+ /** PKCE code verifier. Redacted so it cannot reach a log or a JSON result. */
12
+ export function createCodeVerifier(): Redacted.Redacted<string> {
13
+ return Redacted.make(randomBytes(VERIFIER_BYTES).toString('base64url'))
14
+ }
15
+
16
+ export function codeChallengeFor(verifier: Redacted.Redacted<string>): string {
17
+ return createHash('sha256').update(Redacted.value(verifier)).digest('base64url')
18
+ }
19
+
20
+ /**
21
+ * Opaque high-entropy value for non-PKCE uses such as the OAuth `state`
22
+ * parameter. Same entropy and encoding, different purpose.
23
+ */
24
+ export function createHighEntropySecret(): string {
25
+ return randomBytes(VERIFIER_BYTES).toString('base64url')
26
+ }
@@ -0,0 +1,116 @@
1
+ import { Effect, Redacted, Schema } from 'effect'
2
+ import { ConfigManager } from '../Config.js'
3
+ import {
4
+ ManualAuthorization,
5
+ ManualAuthorizationCredentialSaveFailed,
6
+ ManualAuthorizationDenied,
7
+ ManualAuthorizationRefused,
8
+ } from './ManualAuthorization.js'
9
+
10
+ interface SetupGrantAuthorizationInput {
11
+ readonly setupToken: Redacted.Redacted<string>
12
+ readonly harness: 'agent-harnesses'
13
+ readonly scope: 'project' | 'global'
14
+ }
15
+
16
+ export class SetupGrantAuthorizationError extends Schema.TaggedError<SetupGrantAuthorizationError>()(
17
+ 'SetupGrantAuthorizationError',
18
+ {
19
+ code: Schema.Literal(
20
+ 'invalid_or_expired',
21
+ 'stored_credential_conflict',
22
+ 'request_failed',
23
+ 'denied',
24
+ 'credential_save_failed',
25
+ 'refused',
26
+ 'config_unreadable',
27
+ ),
28
+ recoverable: Schema.Boolean,
29
+ },
30
+ ) {
31
+ get message() {
32
+ switch (this.code) {
33
+ // Checked before redemption, so the token is untouched and the user can
34
+ // retry with the same one after clearing the stored credential.
35
+ case 'stored_credential_conflict':
36
+ return 'An Expand API key is already stored on this machine, and completing this setup would replace it with no way to recover it. Nothing was changed and your setup prompt is still valid. Run `expandai logout` to clear the stored key, then run this setup command again.'
37
+ case 'request_failed':
38
+ return 'Could not reach Expand to redeem the setup token. Nothing was sent, so the same token is still good — check the network and try again.'
39
+ case 'denied':
40
+ return 'This setup authorization was denied. Copy a fresh setup prompt from the Expand dashboard.'
41
+ // Checked before redemption, so like stored_credential_conflict the token is
42
+ // untouched and the same prompt works once the file is dealt with.
43
+ case 'config_unreadable':
44
+ return 'The Expand config file on this machine could not be read, so setup cannot tell whether completing it would overwrite an existing API key. Nothing was redeemed and your setup prompt is still valid. Run `expandai whoami` to see which file it is, fix or delete it, then run this setup command again.'
45
+ // Server-side misconfiguration: a fresh prompt is refused identically.
46
+ case 'refused':
47
+ return 'Expand refused to redeem this setup token for a reason a fresh prompt cannot fix — most likely an OAuth client, resource, or scope misconfiguration on the server. Do not request another prompt; report this.'
48
+ // The token redeemed — it is spent — but the credentials could not be
49
+ // written locally. A fresh prompt hits the same wall until the local
50
+ // storage problem is fixed, so say that instead of blaming the token.
51
+ case 'credential_save_failed':
52
+ return 'The setup token was redeemed, but the credentials could not be saved on this machine. Fix credential storage — run `expandai whoami` to see the path it uses, and check its permissions — then copy a fresh setup prompt from the Expand dashboard.'
53
+ default:
54
+ return 'The setup token is invalid, expired, or already used. Copy a fresh setup prompt from the Expand dashboard.'
55
+ }
56
+ }
57
+ }
58
+
59
+ function setupGrantError(code: typeof SetupGrantAuthorizationError.fields.code.Type): SetupGrantAuthorizationError {
60
+ return new SetupGrantAuthorizationError({
61
+ code,
62
+ recoverable: code !== 'denied' && code !== 'credential_save_failed' && code !== 'refused',
63
+ })
64
+ }
65
+
66
+ /**
67
+ * Dashboard-minted setup: the "token" in the prompt is a pre-approved RFC 8628
68
+ * device code, already bound to the minting user and pinned to their
69
+ * organization server-side. Redeeming is a single poll of the OAuth token
70
+ * endpoint — better-auth owns generation, expiry and the single-use burn, so
71
+ * there is no redemption protocol of ours left to get wrong.
72
+ */
73
+ export class SetupGrantAuthorization extends Effect.Service<SetupGrantAuthorization>()(
74
+ '@expandai/cli/Auth/SetupGrantAuthorization',
75
+ {
76
+ dependencies: [ConfigManager.Default, ManualAuthorization.Default],
77
+ effect: Effect.gen(function* () {
78
+ const configManager = yield* ConfigManager
79
+ const manualAuthorization = yield* ManualAuthorization
80
+ const authorize = Effect.fn('SetupGrantAuthorization.authorize')(function* (input: SetupGrantAuthorizationInput) {
81
+ // The *file*, specifically. `loadConfig` collapses env and file into one
82
+ // value, so it cannot tell an ambient `EXPAND_API_KEY` — which must
83
+ // never block setup — from a key written by `expandai login`, which
84
+ // saving new credentials would overwrite with no way to recover it.
85
+ //
86
+ // Refused before redemption: nothing has been spent, so the same prompt
87
+ // still works once the user clears the stored key.
88
+ // `readConfigFile` never fails — it reports an unreadable file through
89
+ // `parseFailed` and hands back an empty config — so `Effect.either` here was
90
+ // always Right and the ApiKey check silently passed on a corrupt file. That
91
+ // matters: redemption is single-use, so proceeding would spend the token and
92
+ // *then* fail to save. Refuse first, while the prompt is still good.
93
+ const storedFile = yield* configManager.readConfigFile()
94
+ if (storedFile.parseFailed) return yield* setupGrantError('config_unreadable')
95
+ if (storedFile.config.authMethod?._tag === 'ApiKey') {
96
+ return yield* setupGrantError('stored_credential_conflict')
97
+ }
98
+ yield* Effect.annotateCurrentSpan({ harness: input.harness, scope: input.scope })
99
+ yield* manualAuthorization.redeemPreApproved(input.setupToken).pipe(
100
+ Effect.mapError((error) => {
101
+ if (error instanceof ManualAuthorizationDenied) return setupGrantError('denied')
102
+ if (error instanceof ManualAuthorizationCredentialSaveFailed) {
103
+ return setupGrantError('credential_save_failed')
104
+ }
105
+ if (error instanceof ManualAuthorizationRefused) return setupGrantError('refused')
106
+ if (error._tag === 'ManualAuthorizationApiError' && error.kind === 'request_failed') {
107
+ return setupGrantError('request_failed')
108
+ }
109
+ return setupGrantError('invalid_or_expired')
110
+ }),
111
+ )
112
+ })
113
+ return { authorize } as const
114
+ }),
115
+ },
116
+ ) {}
@@ -2,10 +2,13 @@ import { Command, Prompt } from '@effect/cli'
2
2
  import { Console, DateTime, Duration, Effect, Either, Match, Schema, String } from 'effect'
3
3
  import open from 'open'
4
4
  import { BrowserOAuthService } from './BrowserOAuth.js'
5
- import { ApiKey, ApiKeyConfig, ConfigManager, OAuthConfig } from './Config.js'
6
- import { Uninstall } from './Install/Uninstall.js'
5
+ import { ApiKey, ApiKeyConfig, type AuthMethod, ConfigManager, isAuthMethodLocallyUsable } from './Config.js'
6
+
7
+ // Re-exported: these moved to Config.ts, where the credential types live, so
8
+ // that credential precedence can consult usability without a cycle.
9
+ export { type AuthMethodState, authMethodState, isAuthMethodLocallyUsable } from './Config.js'
7
10
 
8
- type AuthMethod = typeof ApiKeyConfig.Type | typeof OAuthConfig.Type
11
+ import { Uninstall } from './Install/Uninstall.js'
9
12
 
10
13
  /** Render a user-facing description of the current auth state. Pure given DateTime.now. */
11
14
  export const formatAuthStatus = Effect.fn('Authentication.formatAuthStatus')(function* (authMethod: AuthMethod) {
@@ -32,6 +35,17 @@ export class Authentication extends Effect.Service<Authentication>()('@expandai/
32
35
  const browserOAuth = yield* BrowserOAuthService
33
36
  const uninstall = yield* Uninstall
34
37
 
38
+ const hasLocallyUsableCredentials = Effect.fn('Authentication.hasLocallyUsableCredentials')(function* () {
39
+ yield* configManager.ensureSecureStorage()
40
+ const loaded = yield* Effect.either(configManager.loadConfig())
41
+ if (Either.isLeft(loaded)) {
42
+ if (loaded.left._tag === 'NotAuthenticated') return false
43
+ return yield* Effect.fail(loaded.left)
44
+ }
45
+ const now = yield* DateTime.now
46
+ return isAuthMethodLocallyUsable(loaded.right.authMethod, now)
47
+ })
48
+
35
49
  const apiKeyLogin = Effect.fn('Authentication.apiKeyLogin')(function* () {
36
50
  const apiKey = yield* Prompt.password({ message: 'Enter your API Key' })
37
51
  yield* configManager.updateConfig({
@@ -40,13 +54,41 @@ export class Authentication extends Effect.Service<Authentication>()('@expandai/
40
54
  yield* Console.log('API key saved successfully!')
41
55
  })
42
56
 
43
- const oauthLogin = Effect.fn('Authentication.oauthLogin')(function* () {
57
+ const browserLogin = Effect.fnUntraced(function* <R>(
58
+ showAuthorizeUrl: (authorizeUrl: URL) => Effect.Effect<void, unknown, R>,
59
+ ) {
44
60
  yield* Console.log(
45
61
  String.stripMargin(`
46
62
  |
47
63
  |Starting browser authorization...`),
48
64
  )
49
- yield* browserOAuth.login((authorizeUrl) =>
65
+ yield* browserOAuth.login(showAuthorizeUrl)
66
+ yield* Console.log(
67
+ String.stripMargin(`
68
+ |
69
+ |Successfully authenticated!`),
70
+ )
71
+ })
72
+
73
+ const printAuthorizeUrl = Effect.fnUntraced(function* (authorizeUrl: URL) {
74
+ yield* Console.log(
75
+ String.stripMargin(`
76
+ |
77
+ |Open this URL in a browser:
78
+ | ${authorizeUrl.toString()}
79
+ |
80
+ |Waiting for browser authorization...`),
81
+ )
82
+ })
83
+
84
+ // `init` already asks for harness and scope. Keep browser login on the
85
+ // existing loopback OAuth path without introducing a third Prompt choice.
86
+ const loginWithBrowser = Effect.fn('Authentication.loginWithBrowser')(function* () {
87
+ yield* browserLogin(printAuthorizeUrl)
88
+ })
89
+
90
+ const oauthLogin = Effect.fn('Authentication.oauthLogin')(function* () {
91
+ yield* browserLogin((authorizeUrl) =>
50
92
  Effect.gen(function* () {
51
93
  yield* Console.log(
52
94
  String.stripMargin(`
@@ -70,14 +112,10 @@ export class Authentication extends Effect.Service<Authentication>()('@expandai/
70
112
  )
71
113
  }),
72
114
  )
73
- yield* Console.log(
74
- String.stripMargin(`
75
- |
76
- |Successfully authenticated!`),
77
- )
78
115
  })
79
116
 
80
117
  const login = Effect.fn('Authentication.login')(function* () {
118
+ yield* configManager.ensureSecureStorage()
81
119
  const existing = yield* Effect.either(configManager.loadConfig())
82
120
 
83
121
  if (Either.isRight(existing)) {
@@ -144,7 +182,7 @@ export class Authentication extends Effect.Service<Authentication>()('@expandai/
144
182
  yield* Console.log('Logged out.')
145
183
  })
146
184
 
147
- return { login, whoami, logout } as const
185
+ return { hasLocallyUsableCredentials, loginWithBrowser, login, whoami, logout } as const
148
186
  }),
149
187
  }) {}
150
188
 
@@ -1,8 +1,8 @@
1
- import { createHash, randomBytes } from 'node:crypto'
2
1
  import { createServer, type IncomingMessage, type Server, type ServerResponse } from 'node:http'
3
2
  import { HttpClient, HttpClientRequest, HttpClientResponse } from '@effect/platform'
4
3
  import { NodeHttpClient } from '@effect/platform-node'
5
4
  import { DateTime, Duration, Effect, Inspectable, Redacted, Schema } from 'effect'
5
+ import { codeChallengeFor, createHighEntropySecret } from './Auth/Pkce.js'
6
6
  import { ConfigManager, OAuthConfig } from './Config.js'
7
7
 
8
8
  const CLIENT_ID = 'expandai-cli'
@@ -107,16 +107,8 @@ interface LoopbackServer {
107
107
  readonly close: Effect.Effect<void>
108
108
  }
109
109
 
110
- function base64Url(bytes: Uint8Array): string {
111
- return Buffer.from(bytes).toString('base64').replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', '')
112
- }
113
-
114
- function createHighEntropySecret(): string {
115
- return base64Url(randomBytes(32))
116
- }
117
-
118
110
  export const createCodeChallenge = Effect.fn('BrowserOAuth.createCodeChallenge')(function* (codeVerifier: string) {
119
- return base64Url(createHash('sha256').update(codeVerifier).digest())
111
+ return codeChallengeFor(Redacted.make(codeVerifier))
120
112
  })
121
113
 
122
114
  export const buildAuthorizeUrl = Effect.fn('BrowserOAuth.buildAuthorizeUrl')(function* ({
@@ -253,6 +245,7 @@ export class BrowserOAuthService extends Effect.Service<BrowserOAuthService>()('
253
245
  const exchangeToken = Effect.fn('BrowserOAuthService.exchangeToken')(function* (
254
246
  form: ReadonlyArray<readonly [string, string]>,
255
247
  ) {
248
+ yield* configManager.ensureSecureStorage()
256
249
  const apiUrl = yield* configManager.getApiUrl()
257
250
  const resource = apiUrl.toString()
258
251
  const request = HttpClientRequest.post(new URL(OAUTH_TOKEN_ENDPOINT, apiUrl)).pipe(
@@ -301,10 +294,13 @@ export class BrowserOAuthService extends Effect.Service<BrowserOAuthService>()('
301
294
  ])
302
295
  })
303
296
 
304
- const refreshToken = Effect.fn('BrowserOAuthService.refreshToken')(function* (refreshToken: string) {
297
+ const refreshToken = Effect.fn('BrowserOAuthService.refreshToken')(function* (
298
+ refreshToken: string,
299
+ clientId: string = CLIENT_ID,
300
+ ) {
305
301
  return yield* exchangeToken([
306
302
  ['grant_type', 'refresh_token'],
307
- ['client_id', CLIENT_ID],
303
+ ['client_id', clientId],
308
304
  ['refresh_token', refreshToken],
309
305
  ])
310
306
  })
@@ -319,6 +315,7 @@ export class BrowserOAuthService extends Effect.Service<BrowserOAuthService>()('
319
315
  refreshToken:
320
316
  tokenResponse.refresh_token === undefined ? undefined : Redacted.make(tokenResponse.refresh_token),
321
317
  expiresAt,
318
+ clientId: CLIENT_ID,
322
319
  }),
323
320
  })
324
321
  })
@@ -326,6 +323,7 @@ export class BrowserOAuthService extends Effect.Service<BrowserOAuthService>()('
326
323
  const login = Effect.fn('BrowserOAuthService.login')(function* <R>(
327
324
  openAuthorizeUrl: (authorizeUrl: URL) => Effect.Effect<void, unknown, R>,
328
325
  ) {
326
+ yield* configManager.ensureSecureStorage()
329
327
  const codeVerifier = createHighEntropySecret()
330
328
  const state = createHighEntropySecret()
331
329
  const codeChallenge = yield* createCodeChallenge(codeVerifier)
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Telemetry-safe command-path extraction. Only tokens that sit in legal
3
+ * command-path positions of the tree below are ever reported — never
4
+ * free-form args, URLs, or queries. The walk stops at the first token that
5
+ * isn't a subcommand of the current node, so positional user input can't
6
+ * leak even when it happens to equal a command word
7
+ * (`expandai search snap_abc login` reports just `search`). Choice-arg
8
+ * values (hosts, scopes) are positional data and deliberately absent.
9
+ */
10
+ const COMMAND_TREE = new Map<string, ReadonlySet<string>>([
11
+ ['fetch', new Set()],
12
+ ['search', new Set()],
13
+ ['login', new Set()],
14
+ ['whoami', new Set()],
15
+ ['logout', new Set()],
16
+ ['init', new Set()],
17
+ ['status', new Set()],
18
+ ['uninstall', new Set()],
19
+ ['mcp', new Set(['run', 'install', 'uninstall'])],
20
+ ['skill', new Set(['install', 'uninstall'])],
21
+ ['hook', new Set(['claude-code', 'opencode', 'install', 'uninstall'])],
22
+ ['telemetry', new Set(['status', 'enable', 'disable'])],
23
+ ])
24
+
25
+ export function commandFromArgv(argv: readonly string[]): string {
26
+ const [first, second] = argv.slice(2)
27
+ const subcommands = first === undefined ? undefined : COMMAND_TREE.get(first)
28
+ if (first === undefined || subcommands === undefined) return '(none)'
29
+ return second !== undefined && subcommands.has(second) ? `${first} ${second}` : first
30
+ }