expandai 0.0.2 → 0.0.3

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 +78 -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 +85 -25
  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 +380 -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 +182 -50
  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 +26 -3
  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 +496 -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 +234 -81
  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
package/src/Config.ts CHANGED
@@ -1,17 +1,46 @@
1
1
  /**
2
2
  * CLI configuration. Persisted at `$XDG_CONFIG_HOME/expandai/config.json`
3
- * (default `~/.config/expandai/config.json`). The `EXPAND_API_KEY` and
4
- * `EXPAND_API_URL` environment variables override the file.
3
+ * (default `~/.config/expandai/config.json`). `EXPAND_API_URL` overrides the
4
+ * file. `EXPAND_API_KEY` overrides an API key stored in the file, but not
5
+ * credentials established by `expandai login` or agent setup — signing in is a
6
+ * deliberate act, and an exported API key usually is not. `EXPAND_APP_URL`
7
+ * points guide links at the web app serving them.
5
8
  */
6
- import { homedir } from 'node:os'
7
- import { FileSystem, Path } from '@effect/platform'
8
- import { NodeFileSystem, NodePath } from '@effect/platform-node'
9
+ import { Command, CommandExecutor, FileSystem, Path, Error as PlatformError } from '@effect/platform'
10
+ import { NodeContext } from '@effect/platform-node'
9
11
  import { DEFAULT_PLAYGROUND_HOST } from '@expandai/sdk/Playground'
10
- import { Config, DateTime, Effect, Option, Schema } from 'effect'
12
+ import { Config, DateTime, Effect, Either, Exit, Option, Random, Redacted, Schema } from 'effect'
13
+ import { type CreatedFileIdentity, createExclusiveFile, matchesCreatedFile } from './SecureFile.js'
14
+ import { xdgConfigDirectory } from './Xdg.js'
11
15
 
12
16
  /** Production API endpoint used when neither `EXPAND_API_URL` nor the config file overrides it. */
13
17
  export const DEFAULT_API_URL = 'https://api.expand.ai'
14
18
 
19
+ /** Production web app used when `EXPAND_APP_URL` does not override it. */
20
+ export const DEFAULT_APP_URL = 'https://expand.ai'
21
+
22
+ /**
23
+ * Lenient env readers. `Config.option` / `Config.withDefault` only absorb
24
+ * missing data — a present-but-malformed value (`CLAUDECODE=banana`,
25
+ * `EXPANDAI_HARNESS=bogus`) fails as InvalidData and would crash the CLI at
26
+ * layer construction. These read the raw string and degrade gracefully:
27
+ * flags follow the DO_NOT_TRACK convention (set unless an explicit off),
28
+ * literals decode to None instead of failing.
29
+ */
30
+ export const envFlag = (name: string) =>
31
+ Config.string(name).pipe(
32
+ Config.option,
33
+ Config.map(
34
+ Option.match({
35
+ onNone: () => false,
36
+ onSome: (value) => value !== '' && value !== '0' && value !== 'false',
37
+ }),
38
+ ),
39
+ )
40
+
41
+ export const envLiteral = <A extends string>(name: string, schema: Schema.Schema<A, A>) =>
42
+ Config.string(name).pipe(Config.option, Config.map(Option.flatMap(Schema.decodeUnknownOption(schema))))
43
+
15
44
  export const ApiKey = Schema.Redacted(Schema.NonEmptyTrimmedString.pipe(Schema.brand('ApiKey')))
16
45
 
17
46
  export const ApiKeyConfig = Schema.TaggedStruct('ApiKey', { apiKey: ApiKey })
@@ -19,15 +48,109 @@ export const OAuthConfig = Schema.TaggedStruct('OAuth', {
19
48
  accessToken: Schema.Redacted(Schema.String),
20
49
  refreshToken: Schema.optional(Schema.Redacted(Schema.String)),
21
50
  expiresAt: Schema.DateTimeUtc,
51
+ // Refresh tokens are bound to their issuing client, so a credential minted by
52
+ // browser-approved setup cannot be refreshed as `expandai-cli`. Optional because
53
+ // configs written before this existed all came from `expandai login`.
54
+ clientId: Schema.optional(Schema.String),
55
+ })
56
+
57
+ export const TelemetrySettings = Schema.Struct({
58
+ enabled: Schema.optional(Schema.Boolean),
59
+ distinctId: Schema.optional(Schema.String),
60
+ noticeShown: Schema.optional(Schema.Boolean),
22
61
  })
23
62
 
24
63
  export class ExpandCliConfig extends Schema.Class<ExpandCliConfig>('ExpandCliConfig')({
25
64
  apiUrl: Schema.optional(Schema.URL),
26
65
  authMethod: Schema.optional(Schema.Union(ApiKeyConfig, OAuthConfig)),
66
+ telemetry: Schema.optional(TelemetrySettings),
27
67
  }) {
28
68
  static readonly Json = Schema.parseJson(ExpandCliConfig)
29
69
  }
30
70
 
71
+ export type AuthMethod = typeof ApiKeyConfig.Type | typeof OAuthConfig.Type
72
+
73
+ /**
74
+ * How a stored credential stands right now.
75
+ *
76
+ * `refresh_required` is deliberately distinct from `healthy`: an expired access
77
+ * token with a refresh token on disk is only a credential we *could* renew, and
78
+ * renewal can fail. Reporting it as healthy told agents a machine was authorized
79
+ * when the next call would fail.
80
+ */
81
+ export type AuthMethodState = 'healthy' | 'refresh_required' | 'unusable'
82
+
83
+ export function authMethodState(authMethod: AuthMethod, now: DateTime.Utc): AuthMethodState {
84
+ if (authMethod._tag === 'ApiKey') return 'healthy'
85
+ if (DateTime.lessThan(now, authMethod.expiresAt)) {
86
+ return Redacted.value(authMethod.accessToken).trim().length > 0 ? 'healthy' : 'unusable'
87
+ }
88
+ const refreshToken = authMethod.refreshToken
89
+ return refreshToken !== undefined && Redacted.value(refreshToken).trim().length > 0 ? 'refresh_required' : 'unusable'
90
+ }
91
+
92
+ /** Returns whether a local credential can be used now or renewed on first API use. */
93
+ export function isAuthMethodLocallyUsable(authMethod: AuthMethod, now: DateTime.Utc): boolean {
94
+ return authMethodState(authMethod, now) !== 'unusable'
95
+ }
96
+
97
+ const RawConfigRecord = Schema.Record({ key: Schema.String, value: Schema.Unknown })
98
+ const RawConfigJson = Schema.parseJson(RawConfigRecord)
99
+
100
+ // Unknown top-level keys survive a write, so a config written by a newer CLI
101
+ // is not silently truncated by an older one.
102
+ function mergeRawConfig(
103
+ existing: typeof RawConfigRecord.Type,
104
+ known: typeof RawConfigRecord.Type,
105
+ ): typeof RawConfigRecord.Type {
106
+ return { ...existing, ...known }
107
+ }
108
+
109
+ interface ConfigFileContents {
110
+ readonly config: ExpandCliConfig
111
+ readonly raw: typeof RawConfigRecord.Type
112
+ }
113
+
114
+ interface PathIdentity {
115
+ readonly exists: boolean
116
+ readonly dev?: number
117
+ readonly ino?: number
118
+ readonly realPath?: string
119
+ readonly type?: FileSystem.File.Type
120
+ }
121
+
122
+ function isErrnoCode(input: unknown, code: string): boolean {
123
+ return typeof input === 'object' && input !== null && 'code' in input && input.code === code
124
+ }
125
+
126
+ function powerShellLiteral(value: string): string {
127
+ return `'${value.replaceAll("'", "''")}'`
128
+ }
129
+
130
+ function scriptWithTargetPaths(script: string, targetPaths: ReadonlyArray<string>): string {
131
+ return `$targetPaths = @(${targetPaths.map((targetPath) => powerShellLiteral(targetPath)).join(', ')})
132
+ try {
133
+ Import-Module (Join-Path $PSHOME 'Modules/Microsoft.PowerShell.Security/Microsoft.PowerShell.Security.psd1') -ErrorAction Stop
134
+ $null = & {
135
+ ${script}
136
+ }
137
+ exit 0
138
+ } catch {
139
+ [Console]::Error.WriteLine($_.Exception.Message)
140
+ exit 1
141
+ }`
142
+ }
143
+
144
+ function sameIdentity(left: PathIdentity, right: PathIdentity): boolean {
145
+ return (
146
+ left.exists === right.exists &&
147
+ left.dev === right.dev &&
148
+ left.ino === right.ino &&
149
+ left.realPath === right.realPath &&
150
+ left.type === right.type
151
+ )
152
+ }
153
+
31
154
  export class ConfigNotWritable extends Schema.TaggedError<ConfigNotWritable>()('ConfigNotWritable', {
32
155
  path: Schema.String,
33
156
  }) {
@@ -36,6 +159,17 @@ export class ConfigNotWritable extends Schema.TaggedError<ConfigNotWritable>()('
36
159
  }
37
160
  }
38
161
 
162
+ export class ConfigCleanupError extends Schema.TaggedError<ConfigCleanupError>()('ConfigCleanupError', {
163
+ path: Schema.String,
164
+ temporaryPath: Schema.String,
165
+ error: Schema.Defect,
166
+ operationError: Schema.Defect,
167
+ }) {
168
+ get message() {
169
+ return `Could not safely clean up config temporary state at ${this.temporaryPath}; it was left unchanged.`
170
+ }
171
+ }
172
+
39
173
  export class ConfigParseError extends Schema.TaggedError<ConfigParseError>()('ConfigParseError', {
40
174
  path: Schema.String,
41
175
  error: Schema.Defect,
@@ -45,6 +179,16 @@ export class ConfigParseError extends Schema.TaggedError<ConfigParseError>()('Co
45
179
  }
46
180
  }
47
181
 
182
+ export class CredentialStoreInsecure extends Schema.TaggedError<CredentialStoreInsecure>()('CredentialStoreInsecure', {
183
+ path: Schema.String,
184
+ reason: Schema.String,
185
+ error: Schema.Defect,
186
+ }) {
187
+ get message() {
188
+ return `Credential storage at ${this.path} is insecure: ${this.reason}`
189
+ }
190
+ }
191
+
48
192
  export class NotAuthenticated extends Schema.TaggedError<NotAuthenticated>()('NotAuthenticated', {}) {
49
193
  get message() {
50
194
  return 'Not authenticated. Run `expandai login` to authenticate.'
@@ -70,28 +214,478 @@ const Environment = Effect.gen(function* () {
70
214
  })
71
215
 
72
216
  export class ConfigManager extends Effect.Service<ConfigManager>()('@expandai/cli/Config/ConfigManager', {
73
- dependencies: [NodeFileSystem.layer, NodePath.layer],
217
+ dependencies: [NodeContext.layer],
74
218
  effect: Effect.gen(function* () {
219
+ const commandExecutor = yield* CommandExecutor.CommandExecutor
75
220
  const fs = yield* FileSystem.FileSystem
76
221
  const path = yield* Path.Path
77
222
 
78
- const configPath = yield* Config.string('XDG_CONFIG_HOME').pipe(
79
- Config.withDefault(path.join(homedir(), '.config')),
80
- Config.map((dir) => path.join(dir, 'expandai', 'config.json')),
81
- )
223
+ const configPath = path.join(yield* xdgConfigDirectory, 'expandai', 'config.json')
224
+ const configDirectory = path.dirname(configPath)
225
+
226
+ const insecure = (targetPath: string, reason: string, error: unknown) =>
227
+ new CredentialStoreInsecure({ path: targetPath, reason, error })
228
+
229
+ const assertNotSymbolicLink = Effect.fnUntraced(function* (targetPath: string) {
230
+ const result = yield* Effect.either(fs.readLink(targetPath))
231
+ if (Either.isRight(result)) {
232
+ return yield* insecure(
233
+ targetPath,
234
+ 'symbolic links are not allowed for credential storage',
235
+ new Error(result.right),
236
+ )
237
+ }
238
+ const error = result.left
239
+ if (
240
+ error instanceof PlatformError.SystemError &&
241
+ (error.reason === 'InvalidData' ||
242
+ error.reason === 'NotFound' ||
243
+ (error.method === 'readLink' && isErrnoCode(error.cause, 'EINVAL')))
244
+ ) {
245
+ return
246
+ }
247
+ return yield* insecure(targetPath, 'could not inspect the credential path without following links', error)
248
+ })
249
+
250
+ const inspectPath = Effect.fnUntraced(function* (targetPath: string) {
251
+ yield* assertNotSymbolicLink(targetPath)
252
+ const exists = yield* fs
253
+ .exists(targetPath)
254
+ .pipe(Effect.mapError((error) => insecure(targetPath, 'could not inspect the credential path', error)))
255
+ if (!exists) {
256
+ const missing: PathIdentity = { exists: false }
257
+ return missing
258
+ }
259
+ const info = yield* fs
260
+ .stat(targetPath)
261
+ .pipe(Effect.mapError((error) => insecure(targetPath, 'could not inspect the credential path', error)))
262
+ const realPath = yield* fs
263
+ .realPath(targetPath)
264
+ .pipe(Effect.mapError((error) => insecure(targetPath, 'could not resolve the credential path', error)))
265
+ const identity: PathIdentity = {
266
+ exists: true,
267
+ dev: info.dev,
268
+ ino: Option.getOrUndefined(info.ino),
269
+ realPath,
270
+ type: info.type,
271
+ }
272
+ return identity
273
+ })
274
+
275
+ const assertStable = (targetPath: string, before: PathIdentity, after: PathIdentity) =>
276
+ sameIdentity(before, after)
277
+ ? Effect.void
278
+ : Effect.fail(
279
+ insecure(
280
+ targetPath,
281
+ 'credential path identity changed during the operation',
282
+ new Error('Path swap detected'),
283
+ ),
284
+ )
285
+
286
+ const inspectParentAndFile = Effect.fnUntraced(function* (targetPath: string) {
287
+ const parentPath = path.dirname(targetPath)
288
+ const parent = yield* inspectPath(parentPath)
289
+ if (!parent.exists || parent.type !== 'Directory') {
290
+ return yield* insecure(parentPath, 'credential parent is not a directory', new Error('Invalid parent'))
291
+ }
292
+ return { parentPath, parent, file: yield* inspectPath(targetPath) } as const
293
+ })
294
+
295
+ const readCredentialFile = Effect.fnUntraced(function* (targetPath: string) {
296
+ const before = yield* inspectParentAndFile(targetPath)
297
+ if (!before.file.exists || before.file.type !== 'File') {
298
+ return yield* insecure(targetPath, 'credential path is not a regular file', new Error('Invalid file'))
299
+ }
300
+ const contents = yield* fs
301
+ .readFileString(targetPath)
302
+ .pipe(Effect.mapError((error) => insecure(targetPath, 'could not read the credential file', error)))
303
+ const after = yield* inspectParentAndFile(targetPath)
304
+ yield* assertStable(before.parentPath, before.parent, after.parent)
305
+ yield* assertStable(targetPath, before.file, after.file)
306
+ return contents
307
+ })
82
308
 
83
- const EnvironmentFromConfigFile = Effect.gen(function* () {
309
+ const ensurePosixMode = Effect.fnUntraced(function* (
310
+ targetPath: string,
311
+ mode: number,
312
+ expectedType: 'Directory' | 'File',
313
+ ) {
314
+ const before = yield* inspectPath(targetPath)
315
+ if (!before.exists || before.type !== expectedType) {
316
+ return yield* insecure(targetPath, `expected a ${expectedType.toLowerCase()}`, new Error('Invalid path type'))
317
+ }
318
+ yield* fs
319
+ .chmod(targetPath, mode)
320
+ .pipe(Effect.mapError((error) => insecure(targetPath, `could not set mode ${mode.toString(8)}`, error)))
321
+ const info = yield* fs
322
+ .stat(targetPath)
323
+ .pipe(Effect.mapError((error) => insecure(targetPath, 'could not verify permissions', error)))
324
+ const actualMode = info.mode & 0o7777
325
+ if (info.type !== expectedType || actualMode !== mode) {
326
+ return yield* insecure(
327
+ targetPath,
328
+ `expected ${expectedType.toLowerCase()} mode ${mode.toString(8)}, found ${info.type.toLowerCase()} mode ${actualMode.toString(8)}`,
329
+ new Error('Permission verification failed'),
330
+ )
331
+ }
332
+ const after = yield* inspectPath(targetPath)
333
+ yield* assertStable(targetPath, before, after)
334
+ })
335
+
336
+ const WINDOWS_ACL_SCRIPT = String.raw`
337
+ $ErrorActionPreference = 'Stop'
338
+ $currentSid = [System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value
339
+ $allowedSids = @($currentSid, 'S-1-5-18', 'S-1-5-32-544')
340
+ foreach ($targetPath in $targetPaths) {
341
+ if (-not (Test-Path -LiteralPath $targetPath)) { throw "Missing credential path: $targetPath" }
342
+ $item = Get-Item -LiteralPath $targetPath -Force
343
+ $acl = Get-Acl -LiteralPath $targetPath
344
+ $acl.SetAccessRuleProtection($true, $false)
345
+ foreach ($rule in @($acl.Access)) { [void]$acl.RemoveAccessRuleSpecific($rule) }
346
+ $inheritance = if ($item.PSIsContainer) {
347
+ [System.Security.AccessControl.InheritanceFlags]'ContainerInherit, ObjectInherit'
348
+ } else {
349
+ [System.Security.AccessControl.InheritanceFlags]::None
350
+ }
351
+ foreach ($sidValue in $allowedSids) {
352
+ $sid = [System.Security.Principal.SecurityIdentifier]::new($sidValue)
353
+ $rule = [System.Security.AccessControl.FileSystemAccessRule]::new(
354
+ $sid,
355
+ [System.Security.AccessControl.FileSystemRights]::FullControl,
356
+ $inheritance,
357
+ [System.Security.AccessControl.PropagationFlags]::None,
358
+ [System.Security.AccessControl.AccessControlType]::Allow
359
+ )
360
+ [void]$acl.AddAccessRule($rule)
361
+ }
362
+ Set-Acl -LiteralPath $targetPath -AclObject $acl
363
+
364
+ $verified = Get-Acl -LiteralPath $targetPath
365
+ if (-not $verified.AreAccessRulesProtected) { throw "Inherited ACL remains enabled: $targetPath" }
366
+ $seenSids = @{}
367
+ foreach ($rule in @($verified.Access)) {
368
+ $sid = $rule.IdentityReference.Translate([System.Security.Principal.SecurityIdentifier]).Value
369
+ if ($allowedSids -notcontains $sid) { throw "Unexpected ACL principal $sid on $targetPath" }
370
+ if ($rule.AccessControlType -ne [System.Security.AccessControl.AccessControlType]::Allow) {
371
+ throw "Unexpected deny ACL for $sid on $targetPath"
372
+ }
373
+ $requiredRights = [System.Security.AccessControl.FileSystemRights]::FullControl
374
+ if (($rule.FileSystemRights -band $requiredRights) -ne $requiredRights) {
375
+ throw "ACL principal $sid lacks FullControl on $targetPath"
376
+ }
377
+ $seenSids[$sid] = $true
378
+ }
379
+ foreach ($allowedSid in $allowedSids) {
380
+ if (-not $seenSids.ContainsKey($allowedSid)) { throw "Missing ACL principal $allowedSid on $targetPath" }
381
+ }
382
+ }
383
+ 'SECURE'
384
+ `
385
+
386
+ const WINDOWS_ACL_INSPECTION_SCRIPT = String.raw`
387
+ $ErrorActionPreference = 'Stop'
388
+ $currentSid = [System.Security.Principal.WindowsIdentity]::GetCurrent().User.Value
389
+ $allowedSids = @($currentSid, 'S-1-5-18', 'S-1-5-32-544')
390
+ foreach ($targetPath in $targetPaths) {
391
+ if (-not (Test-Path -LiteralPath $targetPath)) { throw "Missing credential path: $targetPath" }
392
+ $acl = Get-Acl -LiteralPath $targetPath
393
+ if (-not $acl.AreAccessRulesProtected) { throw "Inherited ACL remains enabled: $targetPath" }
394
+ $seenSids = @{}
395
+ foreach ($rule in @($acl.Access)) {
396
+ $sid = $rule.IdentityReference.Translate([System.Security.Principal.SecurityIdentifier]).Value
397
+ if ($allowedSids -notcontains $sid) { throw "Unexpected ACL principal $sid on $targetPath" }
398
+ if ($rule.AccessControlType -ne [System.Security.AccessControl.AccessControlType]::Allow) {
399
+ throw "Unexpected deny ACL for $sid on $targetPath"
400
+ }
401
+ $requiredRights = [System.Security.AccessControl.FileSystemRights]::FullControl
402
+ if (($rule.FileSystemRights -band $requiredRights) -ne $requiredRights) {
403
+ throw "ACL principal $sid lacks FullControl on $targetPath"
404
+ }
405
+ $seenSids[$sid] = $true
406
+ }
407
+ foreach ($allowedSid in $allowedSids) {
408
+ if (-not $seenSids.ContainsKey($allowedSid)) { throw "Missing ACL principal $allowedSid on $targetPath" }
409
+ }
410
+ }
411
+ 'SECURE'
412
+ `
413
+
414
+ const ensureWindowsAcl = Effect.fnUntraced(function* (targetPaths: ReadonlyArray<string>) {
415
+ const exitCode = yield* Command.make(
416
+ 'powershell.exe',
417
+ '-NoLogo',
418
+ '-NoProfile',
419
+ '-NonInteractive',
420
+ '-Command',
421
+ scriptWithTargetPaths(WINDOWS_ACL_SCRIPT, targetPaths),
422
+ ).pipe(
423
+ Command.stderr('inherit'),
424
+ Command.exitCode,
425
+ Effect.provideService(CommandExecutor.CommandExecutor, commandExecutor),
426
+ Effect.mapError((error) =>
427
+ insecure(configDirectory, 'could not apply or verify the Windows ACL allowlist', error),
428
+ ),
429
+ )
430
+ if (exitCode !== 0) {
431
+ return yield* insecure(
432
+ configDirectory,
433
+ 'Windows ACL verification failed',
434
+ new Error(`PowerShell exited with status ${exitCode}`),
435
+ )
436
+ }
437
+ })
438
+
439
+ const inspectWindowsAcl = Effect.fnUntraced(function* (targetPaths: ReadonlyArray<string>) {
440
+ const exitCode = yield* Command.make(
441
+ 'powershell.exe',
442
+ '-NoLogo',
443
+ '-NoProfile',
444
+ '-NonInteractive',
445
+ '-Command',
446
+ scriptWithTargetPaths(WINDOWS_ACL_INSPECTION_SCRIPT, targetPaths),
447
+ ).pipe(
448
+ Command.stderr('inherit'),
449
+ Command.exitCode,
450
+ Effect.provideService(CommandExecutor.CommandExecutor, commandExecutor),
451
+ Effect.mapError((error) => insecure(configDirectory, 'could not inspect the Windows ACL allowlist', error)),
452
+ )
453
+ if (exitCode !== 0) {
454
+ return yield* insecure(
455
+ configDirectory,
456
+ 'Windows ACL inspection failed',
457
+ new Error(`PowerShell exited with status ${exitCode}`),
458
+ )
459
+ }
460
+ })
461
+
462
+ const inspectSecureStorage = Effect.fn('ConfigManager.inspectSecureStorage')(function* () {
463
+ const directory = yield* inspectPath(configDirectory)
464
+ if (!directory.exists) return yield* Effect.void
465
+ if (directory.type !== 'Directory') {
466
+ return yield* insecure(
467
+ configDirectory,
468
+ 'config directory is not a regular directory',
469
+ new Error('Invalid config directory'),
470
+ )
471
+ }
472
+
473
+ const file = yield* inspectPath(configPath)
474
+ if (file.exists && file.type !== 'File') {
475
+ return yield* insecure(configPath, 'credential path is not a regular file', new Error('Invalid file'))
476
+ }
477
+
478
+ if (process.platform === 'win32') {
479
+ const targets = file.exists ? [configDirectory, configPath] : [configDirectory]
480
+ const before = yield* Effect.forEach(targets, inspectPath)
481
+ yield* inspectWindowsAcl(targets)
482
+ const after = yield* Effect.forEach(targets, inspectPath)
483
+ yield* Effect.forEach(
484
+ targets,
485
+ (targetPath, index) =>
486
+ assertStable(targetPath, before[index] ?? { exists: false }, after[index] ?? { exists: false }),
487
+ { discard: true },
488
+ )
489
+ return yield* Effect.void
490
+ }
491
+
492
+ const directoryInfo = yield* fs
493
+ .stat(configDirectory)
494
+ .pipe(Effect.mapError((error) => insecure(configDirectory, 'could not inspect directory mode', error)))
495
+ if ((directoryInfo.mode & 0o7777) !== 0o700) {
496
+ return yield* insecure(configDirectory, 'config directory mode is not 700', new Error('Invalid directory mode'))
497
+ }
498
+ if (file.exists) {
499
+ const fileInfo = yield* fs
500
+ .stat(configPath)
501
+ .pipe(Effect.mapError((error) => insecure(configPath, 'could not inspect credential file mode', error)))
502
+ if ((fileInfo.mode & 0o7777) !== 0o600) {
503
+ return yield* insecure(configPath, 'credential file mode is not 600', new Error('Invalid file mode'))
504
+ }
505
+ }
506
+ return yield* Effect.void
507
+ })
508
+
509
+ const ensureSecureStorage = Effect.fn('ConfigManager.ensureSecureStorage')(function* () {
510
+ yield* fs
511
+ .makeDirectory(configDirectory, { recursive: true, mode: 0o700 })
512
+ .pipe(Effect.mapError((error) => insecure(configDirectory, 'could not create the config directory', error)))
513
+ const directory = yield* inspectPath(configDirectory)
514
+ if (!directory.exists || directory.type !== 'Directory') {
515
+ return yield* insecure(
516
+ configDirectory,
517
+ 'config directory is not a regular directory',
518
+ new Error('Invalid config directory'),
519
+ )
520
+ }
521
+
522
+ const exists = yield* fs
523
+ .exists(configPath)
524
+ .pipe(Effect.mapError((error) => insecure(configPath, 'could not inspect the credential file', error)))
525
+ if (!exists) {
526
+ const creation = yield* Effect.either(fs.writeFileString(configPath, '{}', { flag: 'wx', mode: 0o600 }))
527
+ if (
528
+ Either.isLeft(creation) &&
529
+ (!(creation.left instanceof PlatformError.SystemError) || creation.left.reason !== 'AlreadyExists')
530
+ ) {
531
+ return yield* insecure(configPath, 'could not create the credential file', creation.left)
532
+ }
533
+ }
534
+ yield* inspectParentAndFile(configPath)
535
+
536
+ if (process.platform === 'win32') {
537
+ const targets = [configDirectory, configPath]
538
+ const before = yield* Effect.forEach(targets, (targetPath) => inspectPath(targetPath))
539
+ yield* ensureWindowsAcl(targets)
540
+ const after = yield* Effect.forEach(targets, (targetPath) => inspectPath(targetPath))
541
+ yield* Effect.forEach(
542
+ targets,
543
+ (targetPath, index) =>
544
+ assertStable(targetPath, before[index] ?? { exists: false }, after[index] ?? { exists: false }),
545
+ { discard: true },
546
+ )
547
+ } else {
548
+ yield* ensurePosixMode(configDirectory, 0o700, 'Directory')
549
+ yield* ensurePosixMode(configPath, 0o600, 'File')
550
+ }
551
+ return yield* Effect.void
552
+ })
553
+
554
+ const atomicWriteConfig = Effect.fnUntraced(function* (encoded: string) {
555
+ yield* ensureSecureStorage()
556
+ const before = yield* inspectParentAndFile(configPath)
557
+ const nonce = yield* Random.nextIntBetween(0, 0x7fffffff)
558
+ const temporaryPath = path.join(configDirectory, `.config.json.${process.pid}.${nonce.toString(16)}.tmp`)
559
+
560
+ const cleanupTemporary = Effect.fnUntraced(function* (created: CreatedFileIdentity, operationError: unknown) {
561
+ const inspected = yield* Effect.either(inspectParentAndFile(temporaryPath))
562
+ if (Either.isLeft(inspected)) {
563
+ return yield* new ConfigCleanupError({
564
+ path: configPath,
565
+ temporaryPath,
566
+ error: inspected.left,
567
+ operationError,
568
+ })
569
+ }
570
+ if (!sameIdentity(before.parent, inspected.right.parent)) {
571
+ return yield* new ConfigCleanupError({
572
+ path: configPath,
573
+ temporaryPath,
574
+ error: new Error('Config temp parent identity changed; refusing cleanup'),
575
+ operationError,
576
+ })
577
+ }
578
+ if (!matchesCreatedFile(created, inspected.right.file)) {
579
+ return yield* new ConfigCleanupError({
580
+ path: configPath,
581
+ temporaryPath,
582
+ error: new Error('Config temp identity changed or disappeared; refusing cleanup'),
583
+ operationError,
584
+ })
585
+ }
586
+ const removed = yield* Effect.either(fs.remove(temporaryPath))
587
+ if (Either.isLeft(removed)) {
588
+ return yield* new ConfigCleanupError({
589
+ path: configPath,
590
+ temporaryPath,
591
+ error: removed.left,
592
+ operationError,
593
+ })
594
+ }
595
+ })
596
+
597
+ const creation = yield* createExclusiveFile(fs, temporaryPath, encoded, 0o600).pipe(
598
+ Effect.mapError(() => new ConfigNotWritable({ path: temporaryPath })),
599
+ )
600
+ if (Exit.isFailure(creation.writeExit)) {
601
+ const primary = new ConfigNotWritable({ path: temporaryPath })
602
+ yield* cleanupTemporary(creation.identity, primary)
603
+ return yield* primary
604
+ }
605
+ if (!creation.pathMatchesHandle) {
606
+ const primary = new ConfigNotWritable({ path: temporaryPath })
607
+ yield* cleanupTemporary(creation.identity, primary)
608
+ return yield* primary
609
+ }
610
+
611
+ const installResult = yield* Effect.either(
612
+ Effect.gen(function* () {
613
+ const temporary = yield* inspectParentAndFile(temporaryPath)
614
+ yield* assertStable(before.parentPath, before.parent, temporary.parent)
615
+ if (!matchesCreatedFile(creation.identity, temporary.file)) {
616
+ return yield* insecure(
617
+ temporaryPath,
618
+ 'config temp identity differs from its creating handle',
619
+ new Error('Config temp replacement detected'),
620
+ )
621
+ }
622
+ if (process.platform === 'win32') {
623
+ yield* ensureWindowsAcl([temporaryPath])
624
+ const hardened = yield* inspectParentAndFile(temporaryPath)
625
+ yield* assertStable(before.parentPath, before.parent, hardened.parent)
626
+ if (!matchesCreatedFile(creation.identity, hardened.file)) {
627
+ return yield* insecure(
628
+ temporaryPath,
629
+ 'config temp changed while applying its ACL',
630
+ new Error('Config temp replacement detected'),
631
+ )
632
+ }
633
+ } else {
634
+ const info = yield* fs
635
+ .stat(temporaryPath)
636
+ .pipe(Effect.mapError((error) => insecure(temporaryPath, 'could not verify config temp mode', error)))
637
+ if ((info.mode & 0o7777) !== 0o600) {
638
+ return yield* insecure(
639
+ temporaryPath,
640
+ 'config temp mode is not 600',
641
+ new Error('Invalid config temp mode'),
642
+ )
643
+ }
644
+ }
645
+ const current = yield* inspectParentAndFile(configPath)
646
+ yield* assertStable(before.parentPath, before.parent, current.parent)
647
+ yield* assertStable(configPath, before.file, current.file)
648
+ yield* fs
649
+ .rename(temporaryPath, configPath)
650
+ .pipe(Effect.mapError(() => new ConfigNotWritable({ path: configPath })))
651
+ }),
652
+ )
653
+ if (Either.isLeft(installResult)) {
654
+ yield* cleanupTemporary(creation.identity, installResult.left)
655
+ return yield* installResult.left
656
+ }
657
+
658
+ const installed = yield* inspectParentAndFile(configPath)
659
+ yield* assertStable(before.parentPath, before.parent, installed.parent)
660
+ if (!matchesCreatedFile(creation.identity, installed.file)) {
661
+ return yield* insecure(
662
+ configPath,
663
+ 'atomic credential installation identity could not be verified',
664
+ new Error('Installed file identity mismatch'),
665
+ )
666
+ }
667
+ })
668
+
669
+ const ConfigFileFromDisk = Effect.gen(function* () {
84
670
  const exists = yield* fs.exists(configPath)
85
671
  if (!exists) {
86
- return ExpandCliConfig.make({})
672
+ const empty: ConfigFileContents = { config: ExpandCliConfig.make({}), raw: {} }
673
+ return empty
87
674
  }
88
675
 
89
- const string = yield* fs.readFileString(configPath)
90
- return yield* Schema.decode(ExpandCliConfig.Json)(string).pipe(
676
+ const string = yield* readCredentialFile(configPath)
677
+ const raw = yield* Schema.decode(RawConfigJson)(string).pipe(
678
+ Effect.mapError((error) => new ConfigParseError({ path: configPath, error })),
679
+ )
680
+ const config = yield* Schema.decodeUnknown(ExpandCliConfig)(raw).pipe(
91
681
  Effect.mapError((error) => new ConfigParseError({ path: configPath, error })),
92
682
  )
683
+ const contents: ConfigFileContents = { config, raw }
684
+ return contents
93
685
  })
94
686
 
687
+ const EnvironmentFromConfigFile = ConfigFileFromDisk.pipe(Effect.map(({ config }) => config))
688
+
95
689
  const loadConfig = Effect.fn('loadConfig')(function* () {
96
690
  const env = yield* Environment
97
691
  const file = yield* EnvironmentFromConfigFile
@@ -112,54 +706,94 @@ export class ConfigManager extends Effect.Service<ConfigManager>()('@expandai/cl
112
706
  ),
113
707
  ),
114
708
  )
115
- yield* Effect.logWarning(`EXPAND_API_KEY overrides the auth method stored in ${configPath}`).pipe(
116
- Effect.when(() => Option.isSome(authMethod.env) && Option.isSome(authMethod.file)),
709
+ // Credentials signed in through Expand's own authorization flow win over
710
+ // an ambient `EXPAND_API_KEY`. Someone who just approved this machine in
711
+ // a browser means those credentials; the environment variable is a
712
+ // default for shells and CI, and it is frequently exported machine-wide
713
+ // by tooling nobody is thinking about at the time. It still beats an API
714
+ // key stored in the file, which is the same kind of credential.
715
+ // Usable, not merely present. A stored OAuth credential that expired with
716
+ // no refresh token can never succeed, and outranking the environment with
717
+ // it left `EXPAND_API_KEY` permanently shadowed on exactly the CI and
718
+ // agent machines this is meant to serve, with `expandai logout` the only
719
+ // way out.
720
+ const now = yield* DateTime.now
721
+ const storedOAuth = authMethod.file.pipe(
722
+ Option.filter((method) => method._tag === 'OAuth' && isAuthMethodLocallyUsable(method, now)),
117
723
  )
724
+ const effectiveAuthMethod = Option.firstSomeOf([storedOAuth, authMethod.env, authMethod.file])
118
725
 
119
- return yield* Option.match(
120
- Option.orElse(authMethod.env, () => authMethod.file),
121
- {
122
- onNone: () => Effect.fail(new NotAuthenticated()),
123
- onSome: (authMethod) =>
124
- Effect.succeed({
125
- apiUrl: Option.firstSomeOf([apiUrl.env, apiUrl.file]).pipe(
126
- Option.getOrElse(() => new URL(DEFAULT_API_URL)),
127
- ),
128
- authMethod,
129
- }),
130
- },
726
+ yield* Effect.logWarning(
727
+ `EXPAND_API_KEY is set but ${configPath} holds credentials from \`expandai login\` or agent setup, which take precedence. Unset EXPAND_API_KEY to silence this, or run \`expandai logout\` to use the API key.`,
728
+ ).pipe(Effect.when(() => Option.isSome(authMethod.env) && Option.isSome(storedOAuth)))
729
+ yield* Effect.logWarning(`EXPAND_API_KEY overrides the API key stored in ${configPath}`).pipe(
730
+ Effect.when(
731
+ () => Option.isSome(authMethod.env) && Option.isSome(authMethod.file) && Option.isNone(storedOAuth),
732
+ ),
131
733
  )
734
+
735
+ return yield* Option.match(effectiveAuthMethod, {
736
+ onNone: () => Effect.fail(new NotAuthenticated()),
737
+ onSome: (authMethod) =>
738
+ Effect.succeed({
739
+ apiUrl: Option.firstSomeOf([apiUrl.env, apiUrl.file]).pipe(
740
+ Option.getOrElse(() => new URL(DEFAULT_API_URL)),
741
+ ),
742
+ authMethod,
743
+ }),
744
+ })
132
745
  })
133
746
 
134
747
  const saveConfig = Effect.fn('saveConfig')(function* (config: ExpandCliConfig) {
135
- yield* fs
136
- .makeDirectory(path.dirname(configPath), { recursive: true })
137
- .pipe(Effect.mapError(() => new ConfigNotWritable({ path: configPath })))
138
748
  const encoded = yield* Schema.encode(ExpandCliConfig.Json)(config)
139
- yield* fs
140
- .writeFileString(configPath, encoded, { mode: 0o600 })
141
- .pipe(Effect.mapError(() => new ConfigNotWritable({ path: configPath })))
142
- // `mode` only applies on creation; chmod handles a pre-existing file.
143
- // Failures are non-fatal (e.g. chmod is a no-op on Windows, or the file
144
- // is owned by another user) but surfaced at debug level so they're
145
- // inspectable when DEBUG=true.
146
- yield* fs.chmod(configPath, 0o600).pipe(
147
- Effect.tapErrorCause((cause) =>
148
- Effect.logDebug(`chmod 0o600 ${configPath} failed (file mode may not enforce 0600)`).pipe(
149
- Effect.annotateLogs({ cause }),
150
- ),
151
- ),
152
- Effect.ignore,
153
- )
749
+ yield* atomicWriteConfig(encoded)
154
750
  })
155
751
 
752
+ // Propagates ConfigParseError: merging onto an empty fallback would
753
+ // serialize `{}` over a file that failed to decode (corrupt, or written
754
+ // by a newer CLI version) and destroy the credentials stored in it. No
755
+ // write may ever follow a parse failure.
156
756
  const updateConfig = Effect.fn('updateConfig')(function* (patch: Partial<ExpandCliConfig>) {
157
- const existing = yield* EnvironmentFromConfigFile.pipe(Effect.orElseSucceed(() => ExpandCliConfig.make({})))
158
- yield* saveConfig(ExpandCliConfig.make({ ...existing, ...patch }))
757
+ const existing = yield* ConfigFileFromDisk
758
+ const updated = ExpandCliConfig.make({ ...existing.config, ...patch })
759
+ const known = yield* Schema.encode(ExpandCliConfig.Json)(updated).pipe(
760
+ Effect.flatMap(Schema.decode(RawConfigJson)),
761
+ )
762
+ const encoded = yield* Schema.encode(RawConfigJson)(mergeRawConfig(existing.raw, known))
763
+ yield* atomicWriteConfig(encoded)
764
+ })
765
+
766
+ // The config file alone, without the env overrides or the NotAuthenticated
767
+ // failure of loadConfig — telemetry settings must be readable before the
768
+ // user has ever logged in. An unreadable or undecodable file is tolerated
769
+ // but surfaced via `parseFailed` so callers never mistake it for an empty
770
+ // one (and never write over it).
771
+ const readConfigFile = Effect.fn('readConfigFile')(function* () {
772
+ return yield* ConfigFileFromDisk.pipe(
773
+ Effect.map(({ config }) => ({ config, parseFailed: false })),
774
+ Effect.orElseSucceed(() => ({ config: ExpandCliConfig.make({}), parseFailed: true })),
775
+ )
159
776
  })
160
777
 
778
+ // Clears only authentication state: telemetry preferences (an explicit
779
+ // opt-out, the distinct id, the notice flag) and a configured apiUrl
780
+ // survive logout. An undecodable file is deleted instead of rewritten —
781
+ // nothing in it can be preserved, and writing `{}` would break the
782
+ // no-write-after-parse-failure rule updateConfig upholds.
161
783
  const clearConfig = Effect.fn('clearConfig')(function* () {
162
- yield* saveConfig(ExpandCliConfig.make({}))
784
+ const result = yield* Effect.either(ConfigFileFromDisk)
785
+ if (Either.isLeft(result)) {
786
+ if (!(result.left instanceof ConfigParseError)) return yield* result.left
787
+ yield* Effect.logWarning(
788
+ `Could not parse ${configPath}; removing it. Telemetry preferences and apiUrl were not preserved.`,
789
+ )
790
+ yield* fs.remove(configPath).pipe(Effect.mapError(() => new ConfigNotWritable({ path: configPath })))
791
+ return
792
+ }
793
+ const raw = { ...result.right.raw }
794
+ delete raw.authMethod
795
+ const encoded = yield* Schema.encode(RawConfigJson)(raw)
796
+ yield* atomicWriteConfig(encoded)
163
797
  })
164
798
 
165
799
  const getApiUrl = Effect.fn('getApiUrl')(function* () {
@@ -174,6 +808,13 @@ export class ConfigManager extends Effect.Service<ConfigManager>()('@expandai/cl
174
808
  return Option.firstSomeOf([apiUrl.env, apiUrl.file]).pipe(Option.getOrElse(() => new URL(DEFAULT_API_URL)))
175
809
  })
176
810
 
811
+ // Web app origin for guide links the CLI hands to an agent. Reads `EXPAND_APP_URL` — the
812
+ // counterpart to `EXPAND_API_URL` — so a local or self-hosted stack points agents at the
813
+ // app actually serving `/start.md` instead of production.
814
+ const getAppUrl = Effect.fn('getAppUrl')(function* () {
815
+ return yield* Config.string('EXPAND_APP_URL').pipe(Config.withDefault(DEFAULT_APP_URL))
816
+ })
817
+
177
818
  // Public playground host for citation links. Reads `EXPAND_PLAYGROUND_HOST` — the same env
178
819
  // var the API / cdp-server bake into `meta.playground` — so local/staging set one host for
179
820
  // both server and CLI. The fetch path prefers the server-resolved `meta.playground` origin;
@@ -184,11 +825,15 @@ export class ConfigManager extends Effect.Service<ConfigManager>()('@expandai/cl
184
825
 
185
826
  return {
186
827
  configPath,
828
+ inspectSecureStorage,
829
+ ensureSecureStorage,
187
830
  loadConfig,
188
831
  saveConfig,
189
832
  updateConfig,
190
833
  clearConfig,
834
+ readConfigFile,
191
835
  getApiUrl,
836
+ getAppUrl,
192
837
  getPlaygroundHost,
193
838
  } as const
194
839
  }),