@agent-watch-ai/edge 0.2.5 → 0.4.0

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 (348) hide show
  1. package/CHANGELOG.md +558 -0
  2. package/README.md +222 -97
  3. package/SECURITY.md +72 -0
  4. package/dist/billing/session-billing.d.ts +19 -0
  5. package/dist/billing/session-billing.js +52 -0
  6. package/dist/cli/args.d.ts +10 -0
  7. package/dist/cli/args.js +20 -0
  8. package/dist/cli/constants/cli.constants.d.ts +52 -4
  9. package/dist/cli/constants/cli.constants.js +56 -5
  10. package/dist/cli/context.d.ts +33 -2
  11. package/dist/cli/context.js +84 -14
  12. package/dist/cli/doctor.js +321 -33
  13. package/dist/cli/hook-check.d.ts +23 -0
  14. package/dist/cli/hook-check.js +114 -0
  15. package/dist/cli/hook.js +118 -7
  16. package/dist/cli/index.d.ts +3 -1
  17. package/dist/cli/index.js +3 -1
  18. package/dist/cli/misc.d.ts +11 -0
  19. package/dist/cli/misc.js +80 -4
  20. package/dist/cli/npx-install.d.ts +37 -0
  21. package/dist/cli/npx-install.js +79 -0
  22. package/dist/cli/open-browser.d.ts +39 -0
  23. package/dist/cli/open-browser.js +62 -0
  24. package/dist/cli/setup.d.ts +17 -8
  25. package/dist/cli/setup.js +553 -103
  26. package/dist/cli/status.js +82 -13
  27. package/dist/cli/toggle.d.ts +9 -0
  28. package/dist/cli/toggle.js +117 -0
  29. package/dist/cli/types/cli.types.d.ts +43 -3
  30. package/dist/cli/ui.d.ts +7 -0
  31. package/dist/cli/ui.js +10 -1
  32. package/dist/cli/uninstall.js +39 -2
  33. package/dist/cli/update.d.ts +17 -0
  34. package/dist/cli/update.js +76 -0
  35. package/dist/cli.js +110 -12
  36. package/dist/config/config-store.d.ts +57 -0
  37. package/dist/config/config-store.js +250 -12
  38. package/dist/config/config.d.ts +53 -6
  39. package/dist/config/config.js +66 -6
  40. package/dist/config/constants/config.constants.d.ts +116 -6
  41. package/dist/config/constants/config.constants.js +131 -8
  42. package/dist/config/destination.d.ts +24 -0
  43. package/dist/config/destination.js +33 -0
  44. package/dist/config/index.d.ts +7 -4
  45. package/dist/config/index.js +5 -3
  46. package/dist/config/repo-config.d.ts +11 -7
  47. package/dist/config/repo-config.js +64 -15
  48. package/dist/config/root-config.d.ts +72 -0
  49. package/dist/config/root-config.js +170 -0
  50. package/dist/config/schemas/config.schema.d.ts +831 -84
  51. package/dist/config/schemas/config.schema.js +398 -16
  52. package/dist/config/types/config.types.d.ts +15 -1
  53. package/dist/config/types/destination.types.d.ts +8 -0
  54. package/dist/core/async.d.ts +36 -0
  55. package/dist/core/async.js +68 -0
  56. package/dist/core/index.d.ts +1 -1
  57. package/dist/core/index.js +1 -1
  58. package/dist/core/object.d.ts +5 -0
  59. package/dist/core/object.js +9 -4
  60. package/dist/core/pipe.d.ts +0 -13
  61. package/dist/core/pipe.js +1 -9
  62. package/dist/core/types/core.types.d.ts +9 -0
  63. package/dist/core/types/core.types.js +0 -3
  64. package/dist/core/which.d.ts +14 -0
  65. package/dist/core/which.js +43 -3
  66. package/dist/credentials/budget.d.ts +9 -0
  67. package/dist/credentials/budget.js +16 -0
  68. package/dist/credentials/command-runner.d.ts +16 -0
  69. package/dist/credentials/command-runner.js +37 -0
  70. package/dist/credentials/constants/credentials.constants.d.ts +119 -0
  71. package/dist/credentials/constants/credentials.constants.js +120 -0
  72. package/dist/credentials/credential-status.d.ts +14 -0
  73. package/dist/credentials/credential-status.js +38 -0
  74. package/dist/credentials/credentials.d.ts +86 -0
  75. package/dist/credentials/credentials.js +278 -0
  76. package/dist/credentials/device-api.d.ts +73 -0
  77. package/dist/credentials/device-api.js +161 -0
  78. package/dist/credentials/device-state.d.ts +31 -0
  79. package/dist/credentials/device-state.js +51 -0
  80. package/dist/credentials/identity.d.ts +73 -0
  81. package/dist/credentials/identity.js +101 -0
  82. package/dist/credentials/index.d.ts +7 -0
  83. package/dist/credentials/index.js +5 -0
  84. package/dist/credentials/migration.d.ts +46 -0
  85. package/dist/credentials/migration.js +164 -0
  86. package/dist/credentials/schemas/device-api.schema.d.ts +77 -0
  87. package/dist/credentials/schemas/device-api.schema.js +33 -0
  88. package/dist/credentials/schemas/device-state.schema.d.ts +51 -0
  89. package/dist/credentials/schemas/device-state.schema.js +20 -0
  90. package/dist/credentials/secret-store.d.ts +54 -0
  91. package/dist/credentials/secret-store.js +217 -0
  92. package/dist/credentials/sign-in.d.ts +31 -0
  93. package/dist/credentials/sign-in.js +105 -0
  94. package/dist/credentials/token-refresher.d.ts +39 -0
  95. package/dist/credentials/token-refresher.js +185 -0
  96. package/dist/credentials/types/credentials.types.d.ts +206 -0
  97. package/dist/credentials/types/credentials.types.js +1 -0
  98. package/dist/enforcement/constants/enforcement.constants.d.ts +47 -1
  99. package/dist/enforcement/constants/enforcement.constants.js +56 -0
  100. package/dist/enforcement/decision-cache.d.ts +20 -1
  101. package/dist/enforcement/decision-cache.js +65 -2
  102. package/dist/enforcement/decision-client.d.ts +9 -8
  103. package/dist/enforcement/decision-client.js +64 -17
  104. package/dist/enforcement/enforcement.d.ts +23 -2
  105. package/dist/enforcement/enforcement.js +107 -17
  106. package/dist/enforcement/index.d.ts +4 -3
  107. package/dist/enforcement/index.js +3 -2
  108. package/dist/enforcement/types/enforcement.types.d.ts +66 -2
  109. package/dist/enrollment/constants/enrollment.constants.d.ts +2 -6
  110. package/dist/enrollment/constants/enrollment.constants.js +2 -6
  111. package/dist/enrollment/enrollment.d.ts +16 -0
  112. package/dist/enrollment/enrollment.js +54 -0
  113. package/dist/enrollment/index.d.ts +3 -7
  114. package/dist/enrollment/index.js +1 -1
  115. package/dist/enrollment/types/enrollment.types.d.ts +9 -13
  116. package/dist/events/constants/enrich.constants.d.ts +15 -0
  117. package/dist/events/constants/enrich.constants.js +15 -0
  118. package/dist/events/constants/events.constants.d.ts +6 -2
  119. package/dist/events/constants/events.constants.js +5 -1
  120. package/dist/events/enrich.js +92 -10
  121. package/dist/events/event-id.d.ts +0 -8
  122. package/dist/events/event-id.js +0 -10
  123. package/dist/events/index.d.ts +2 -2
  124. package/dist/events/index.js +1 -1
  125. package/dist/events/product-event.d.ts +9 -6
  126. package/dist/events/types/repo-snapshot.types.d.ts +7 -0
  127. package/dist/events/types/session-billing.types.d.ts +16 -0
  128. package/dist/events/types/session-billing.types.js +1 -0
  129. package/dist/feature/constants/feature.constants.d.ts +7 -0
  130. package/dist/feature/constants/feature.constants.js +7 -0
  131. package/dist/feature/index.d.ts +1 -1
  132. package/dist/feature/index.js +1 -1
  133. package/dist/feature/ticket-candidates.d.ts +14 -0
  134. package/dist/feature/ticket-candidates.js +26 -8
  135. package/dist/git/blob-hash.d.ts +21 -0
  136. package/dist/git/blob-hash.js +69 -0
  137. package/dist/git/checkout-root.d.ts +27 -0
  138. package/dist/git/checkout-root.js +75 -0
  139. package/dist/git/constants/git.constants.d.ts +160 -0
  140. package/dist/git/constants/git.constants.js +181 -0
  141. package/dist/git/fingerprint.d.ts +74 -0
  142. package/dist/git/fingerprint.js +219 -0
  143. package/dist/git/gate-checkout.d.ts +44 -0
  144. package/dist/git/gate-checkout.js +201 -0
  145. package/dist/git/git-context.d.ts +45 -0
  146. package/dist/git/git-context.js +61 -3
  147. package/dist/git/index.d.ts +4 -2
  148. package/dist/git/index.js +2 -1
  149. package/dist/git/manifest-repository.d.ts +13 -0
  150. package/dist/git/manifest-repository.js +92 -0
  151. package/dist/git/repo-snapshot.d.ts +29 -3
  152. package/dist/git/repo-snapshot.js +110 -7
  153. package/dist/git/repository-root.d.ts +39 -0
  154. package/dist/git/repository-root.js +131 -0
  155. package/dist/git/types/git.types.d.ts +55 -0
  156. package/dist/git/types/repository-root.types.d.ts +11 -0
  157. package/dist/git/types/repository-root.types.js +1 -0
  158. package/dist/git/types/snapshot.types.d.ts +9 -0
  159. package/dist/pipeline/constants/pipeline.constants.d.ts +10 -0
  160. package/dist/pipeline/constants/pipeline.constants.js +10 -0
  161. package/dist/pipeline/hook-pipeline.js +410 -33
  162. package/dist/pipeline/types/pipeline.types.d.ts +39 -4
  163. package/dist/privacy/constants/privacy.constants.js +15 -1
  164. package/dist/privacy/index.d.ts +1 -0
  165. package/dist/privacy/index.js +1 -0
  166. package/dist/privacy/product-capture.d.ts +12 -0
  167. package/dist/privacy/product-capture.js +75 -0
  168. package/dist/privacy/sanitizer.d.ts +21 -3
  169. package/dist/privacy/sanitizer.js +52 -8
  170. package/dist/process/ancestors.d.ts +39 -0
  171. package/dist/process/ancestors.js +121 -0
  172. package/dist/process/constants/process.constants.d.ts +34 -0
  173. package/dist/process/constants/process.constants.js +34 -0
  174. package/dist/process/index.d.ts +7 -0
  175. package/dist/process/index.js +2 -0
  176. package/dist/process/types/process.types.d.ts +23 -0
  177. package/dist/process/types/process.types.js +1 -0
  178. package/dist/providers/antigravity/antigravity.adapter.d.ts +12 -1
  179. package/dist/providers/antigravity/antigravity.adapter.js +21 -3
  180. package/dist/providers/antigravity/antigravity.detect.d.ts +0 -9
  181. package/dist/providers/antigravity/antigravity.detect.js +1 -1
  182. package/dist/providers/antigravity/antigravity.provider.js +3 -2
  183. package/dist/providers/antigravity/constants/antigravity.constants.d.ts +2 -0
  184. package/dist/providers/antigravity/constants/antigravity.constants.js +2 -0
  185. package/dist/providers/claude/claude.adapter.d.ts +11 -1
  186. package/dist/providers/claude/claude.adapter.js +26 -5
  187. package/dist/providers/claude/claude.otel.d.ts +32 -18
  188. package/dist/providers/claude/claude.otel.js +81 -6
  189. package/dist/providers/claude/claude.provider.js +5 -2
  190. package/dist/providers/claude/constants/claude.constants.d.ts +2 -0
  191. package/dist/providers/claude/constants/claude.constants.js +2 -0
  192. package/dist/providers/claude/constants/claude.otel.constants.d.ts +4 -0
  193. package/dist/providers/claude/constants/claude.otel.constants.js +8 -0
  194. package/dist/providers/codex/codex.adapter.d.ts +15 -1
  195. package/dist/providers/codex/codex.adapter.js +29 -5
  196. package/dist/providers/codex/codex.otel.d.ts +36 -3
  197. package/dist/providers/codex/codex.otel.js +199 -32
  198. package/dist/providers/codex/codex.provider.js +5 -2
  199. package/dist/providers/codex/constants/codex.constants.d.ts +2 -0
  200. package/dist/providers/codex/constants/codex.constants.js +16 -0
  201. package/dist/providers/codex/constants/codex.otel.constants.d.ts +10 -0
  202. package/dist/providers/codex/constants/codex.otel.constants.js +10 -0
  203. package/dist/providers/constants/provider.constants.d.ts +8 -3
  204. package/dist/providers/constants/provider.constants.js +8 -3
  205. package/dist/providers/cursor/constants/cursor.constants.d.ts +9 -0
  206. package/dist/providers/cursor/constants/cursor.constants.js +9 -0
  207. package/dist/providers/cursor/cursor.adapter.d.ts +33 -1
  208. package/dist/providers/cursor/cursor.adapter.js +129 -4
  209. package/dist/providers/cursor/cursor.detect.d.ts +0 -7
  210. package/dist/providers/cursor/cursor.detect.js +1 -1
  211. package/dist/providers/cursor/cursor.provider.js +5 -2
  212. package/dist/providers/gemini/constants/gemini.constants.d.ts +9 -0
  213. package/dist/providers/gemini/constants/gemini.constants.js +9 -0
  214. package/dist/providers/gemini/constants/gemini.otel.constants.d.ts +9 -1
  215. package/dist/providers/gemini/constants/gemini.otel.constants.js +9 -0
  216. package/dist/providers/gemini/gemini.adapter.d.ts +14 -1
  217. package/dist/providers/gemini/gemini.adapter.js +25 -5
  218. package/dist/providers/gemini/gemini.detect.d.ts +0 -7
  219. package/dist/providers/gemini/gemini.detect.js +1 -1
  220. package/dist/providers/gemini/gemini.otel.d.ts +30 -21
  221. package/dist/providers/gemini/gemini.otel.js +166 -22
  222. package/dist/providers/gemini/gemini.provider.js +2 -1
  223. package/dist/providers/index.d.ts +1 -1
  224. package/dist/providers/index.js +1 -1
  225. package/dist/providers/loaders.d.ts +10 -0
  226. package/dist/providers/loaders.js +40 -0
  227. package/dist/providers/provider.d.ts +11 -0
  228. package/dist/providers/provider.js +1 -1
  229. package/dist/providers/registry.d.ts +11 -8
  230. package/dist/providers/registry.js +11 -15
  231. package/dist/providers/shared/bearer-rewrite.d.ts +19 -0
  232. package/dist/providers/shared/bearer-rewrite.js +46 -0
  233. package/dist/providers/shared/constants/hook-refusal.constants.d.ts +7 -0
  234. package/dist/providers/shared/constants/hook-refusal.constants.js +7 -0
  235. package/dist/providers/shared/constants/shell-directories.constants.d.ts +30 -0
  236. package/dist/providers/shared/constants/shell-directories.constants.js +39 -0
  237. package/dist/providers/shared/constants/tooling.constants.d.ts +24 -2
  238. package/dist/providers/shared/constants/tooling.constants.js +25 -3
  239. package/dist/providers/shared/event-builder.d.ts +12 -14
  240. package/dist/providers/shared/event-builder.js +20 -14
  241. package/dist/providers/shared/exporter-allowlist.d.ts +20 -0
  242. package/dist/providers/shared/exporter-allowlist.js +49 -0
  243. package/dist/providers/shared/hook-config.d.ts +2 -21
  244. package/dist/providers/shared/hook-config.js +5 -4
  245. package/dist/providers/shared/hook-refusal.d.ts +12 -0
  246. package/dist/providers/shared/hook-refusal.js +17 -1
  247. package/dist/providers/shared/install-record.d.ts +12 -2
  248. package/dist/providers/shared/install-record.js +5 -2
  249. package/dist/providers/shared/shell-directories.d.ts +24 -0
  250. package/dist/providers/shared/shell-directories.js +90 -0
  251. package/dist/providers/shared/tooling.d.ts +40 -1
  252. package/dist/providers/shared/tooling.js +70 -1
  253. package/dist/providers/shared/types/adapter.types.d.ts +1 -2
  254. package/dist/providers/types/provider.types.d.ts +81 -1
  255. package/dist/snapshot/constants/snapshot.constants.d.ts +32 -0
  256. package/dist/snapshot/constants/snapshot.constants.js +33 -0
  257. package/dist/snapshot/snapshot-event.js +52 -11
  258. package/dist/snapshot/snapshot-pipeline.js +1 -1
  259. package/dist/snapshot/types/snapshot.types.d.ts +2 -0
  260. package/dist/storage/atomic-file.d.ts +21 -0
  261. package/dist/storage/atomic-file.js +20 -1
  262. package/dist/storage/constants/storage.constants.d.ts +19 -0
  263. package/dist/storage/constants/storage.constants.js +19 -0
  264. package/dist/storage/disabled.d.ts +13 -0
  265. package/dist/storage/disabled.js +24 -0
  266. package/dist/storage/index.d.ts +2 -0
  267. package/dist/storage/index.js +2 -0
  268. package/dist/storage/paths.js +3 -2
  269. package/dist/storage/schemas/storage.schema.d.ts +72 -0
  270. package/dist/storage/schemas/storage.schema.js +6 -0
  271. package/dist/storage/sweep-marker.d.ts +19 -0
  272. package/dist/storage/sweep-marker.js +55 -0
  273. package/dist/storage/types/storage.types.d.ts +2 -0
  274. package/dist/storage/uninstalled.d.ts +58 -0
  275. package/dist/storage/uninstalled.js +107 -0
  276. package/dist/transport/auth-block.d.ts +66 -0
  277. package/dist/transport/auth-block.js +129 -0
  278. package/dist/transport/constants/transport.constants.d.ts +82 -3
  279. package/dist/transport/constants/transport.constants.js +83 -4
  280. package/dist/transport/cooldown.js +8 -1
  281. package/dist/transport/delivery.d.ts +14 -6
  282. package/dist/transport/delivery.js +80 -55
  283. package/dist/transport/http-transport.d.ts +1 -0
  284. package/dist/transport/http-transport.js +52 -10
  285. package/dist/transport/index.d.ts +6 -3
  286. package/dist/transport/index.js +3 -0
  287. package/dist/transport/queue-partition.d.ts +91 -0
  288. package/dist/transport/queue-partition.js +143 -0
  289. package/dist/transport/queue.d.ts +99 -20
  290. package/dist/transport/queue.js +210 -69
  291. package/dist/transport/response-body.d.ts +25 -0
  292. package/dist/transport/response-body.js +64 -0
  293. package/dist/transport/send.d.ts +11 -0
  294. package/dist/transport/send.js +17 -0
  295. package/dist/transport/types/delivery-flow.types.d.ts +19 -0
  296. package/dist/transport/types/delivery-flow.types.js +1 -0
  297. package/dist/transport/types/transport.types.d.ts +45 -0
  298. package/dist/turns/claude-transcript.d.ts +19 -1
  299. package/dist/turns/claude-transcript.js +46 -1
  300. package/dist/turns/codex-originator.d.ts +11 -0
  301. package/dist/turns/codex-originator.js +31 -0
  302. package/dist/turns/codex-transcript.d.ts +30 -0
  303. package/dist/turns/codex-transcript.js +88 -0
  304. package/dist/turns/constants/turns.constants.d.ts +141 -5
  305. package/dist/turns/constants/turns.constants.js +155 -5
  306. package/dist/turns/file-identity.d.ts +27 -0
  307. package/dist/turns/file-identity.js +48 -0
  308. package/dist/turns/gemini-transcript.d.ts +30 -0
  309. package/dist/turns/gemini-transcript.js +96 -0
  310. package/dist/turns/index.d.ts +3 -3
  311. package/dist/turns/index.js +1 -1
  312. package/dist/turns/inherited-checkout.d.ts +54 -0
  313. package/dist/turns/inherited-checkout.js +155 -0
  314. package/dist/turns/native-session-titles.d.ts +26 -0
  315. package/dist/turns/native-session-titles.js +102 -0
  316. package/dist/turns/transcript.d.ts +3 -2
  317. package/dist/turns/transcript.js +5 -1
  318. package/dist/turns/turn-state.d.ts +224 -3
  319. package/dist/turns/turn-state.js +456 -21
  320. package/dist/turns/turn-summary.d.ts +1 -14
  321. package/dist/turns/turn-summary.js +87 -51
  322. package/dist/turns/turn-tracker.d.ts +21 -2
  323. package/dist/turns/turn-tracker.js +379 -56
  324. package/dist/turns/types/transcript.types.d.ts +5 -0
  325. package/dist/turns/types/turn-state.types.d.ts +116 -5
  326. package/dist/turns/types/turn-summary.types.d.ts +64 -14
  327. package/dist/turns/types/turn-tracker.types.d.ts +27 -1
  328. package/dist/turns/work-checkout.d.ts +67 -0
  329. package/dist/turns/work-checkout.js +700 -0
  330. package/dist/untraced/constants/untraced.constants.d.ts +31 -0
  331. package/dist/untraced/constants/untraced.constants.js +63 -0
  332. package/dist/untraced/untraced.d.ts +35 -0
  333. package/dist/untraced/untraced.js +105 -0
  334. package/dist/update/constants/update.constants.d.ts +18 -0
  335. package/dist/update/constants/update.constants.js +20 -0
  336. package/dist/update/update-check.d.ts +52 -0
  337. package/dist/update/update-check.js +113 -0
  338. package/docs/AUDIT_PROMPT.md +129 -0
  339. package/docs/DATA_HANDLING.md +655 -0
  340. package/docs/ENTERPRISE_DEPLOYMENT.md +194 -0
  341. package/docs/PERFORMANCE.md +81 -0
  342. package/package.json +14 -4
  343. package/dist/enrollment/enrollment-provider.d.ts +0 -5
  344. package/dist/enrollment/manual-enrollment.d.ts +0 -32
  345. package/dist/enrollment/manual-enrollment.js +0 -72
  346. package/example/README.md +0 -43
  347. package/example/server.mjs +0 -240
  348. /package/dist/{enrollment/enrollment-provider.js → config/types/destination.types.js} +0 -0
@@ -0,0 +1,54 @@
1
+ import type { CredentialStoreKind, SecretStore, StoreDeps } from './types/credentials.types.js';
2
+ export type { SecretStore, StoreDeps } from './types/credentials.types.js';
3
+ /**
4
+ * Keep a device secret in the best store this machine has, and say which.
5
+ *
6
+ * The OS keychain first; a write is read back before it counts, because
7
+ * `security -i` answers 0 whatever its command did. Anything short of a proven
8
+ * write — no tool, no session bus, a locked keychain, a secret with characters a
9
+ * tool could misread — lands in a 0600 file instead, and the returned kind is
10
+ * what `status` and `doctor` report.
11
+ *
12
+ * Not bound by a hook's credential deadline: by now the gateway has issued the
13
+ * secret, and a keychain write cut short by a slow enrollment would put it in
14
+ * the plaintext file for good. Each tool run still has its own timeout.
15
+ *
16
+ * @param deps - Environment, paths, timeout and runner.
17
+ * @param id - Device id; the keychain account name.
18
+ * @param secret - The device secret.
19
+ * @returns The store that holds it now.
20
+ */
21
+ export declare function saveSecret(deps: StoreDeps, id: string, secret: string): Promise<CredentialStoreKind>;
22
+ /**
23
+ * The OS keychain this machine offers, or the private file when it offers none.
24
+ *
25
+ * @param deps - Environment, paths, timeout and runner.
26
+ * @returns The store a new secret should go to.
27
+ */
28
+ export declare function preferredStore(deps: StoreDeps): SecretStore;
29
+ /**
30
+ * The store a config names. A tool that has since disappeared reads as an
31
+ * absent secret, never as an error.
32
+ *
33
+ * @param kind - What the config recorded.
34
+ * @param deps - Environment, paths, timeout and runner.
35
+ * @returns The store.
36
+ */
37
+ export declare function secretStoreFor(kind: CredentialStoreKind, deps: StoreDeps): SecretStore;
38
+ /**
39
+ * How a store is named to a person.
40
+ *
41
+ * @param kind - The store.
42
+ * @returns A phrase for `status`, `doctor` and setup.
43
+ */
44
+ export declare function storeLabel(kind: CredentialStoreKind): string;
45
+ /**
46
+ * Where a store keeps one device's secret, said to a person who has to remove
47
+ * it by hand. Never the secret.
48
+ *
49
+ * @param kind - The store.
50
+ * @param deps - Paths.
51
+ * @param id - Device id.
52
+ * @returns A phrase naming the keychain entry or the file.
53
+ */
54
+ export declare function secretLocation(kind: CredentialStoreKind, deps: Pick<StoreDeps, 'paths'>, id: string): string;
@@ -0,0 +1,217 @@
1
+ import { existsSync } from 'node:fs';
2
+ import fs from 'node:fs/promises';
3
+ import path from 'node:path';
4
+ import { findSystemExecutable } from '../core/which.js';
5
+ import { writeFileAtomic } from '../storage/atomic-file.js';
6
+ import { SECRET_FILE_MODE } from '../storage/constants/storage.constants.js';
7
+ import { withinBudget } from './budget.js';
8
+ import { runCommand } from './command-runner.js';
9
+ import { CREDENTIALS_DIR_NAME, DBUS_SESSION_VAR, DPAPI_FILE_SUFFIX, DPAPI_PROTECT_SCRIPT, DPAPI_UNPROTECT_SCRIPT, KEYCHAIN_LABEL, KEYCHAIN_SERVICE, MACOS_KEYCHAINS_DIR, RE_SECRET_CHARS, SECRET_FILE_SUFFIX, STORE_LABELS } from './constants/credentials.constants.js';
10
+ /**
11
+ * Keep a device secret in the best store this machine has, and say which.
12
+ *
13
+ * The OS keychain first; a write is read back before it counts, because
14
+ * `security -i` answers 0 whatever its command did. Anything short of a proven
15
+ * write — no tool, no session bus, a locked keychain, a secret with characters a
16
+ * tool could misread — lands in a 0600 file instead, and the returned kind is
17
+ * what `status` and `doctor` report.
18
+ *
19
+ * Not bound by a hook's credential deadline: by now the gateway has issued the
20
+ * secret, and a keychain write cut short by a slow enrollment would put it in
21
+ * the plaintext file for good. Each tool run still has its own timeout.
22
+ *
23
+ * @param deps - Environment, paths, timeout and runner.
24
+ * @param id - Device id; the keychain account name.
25
+ * @param secret - The device secret.
26
+ * @returns The store that holds it now.
27
+ */
28
+ export async function saveSecret(deps, id, secret) {
29
+ const unhurried = { ...deps, deadline: undefined };
30
+ const preferred = preferredStore(unhurried);
31
+ if (preferred.kind !== 'file' && (await preferred.set(id, secret)) && (await preferred.get(id)) === secret)
32
+ return preferred.kind;
33
+ await fileStore(unhurried).set(id, secret);
34
+ return 'file';
35
+ }
36
+ /**
37
+ * The OS keychain this machine offers, or the private file when it offers none.
38
+ *
39
+ * @param deps - Environment, paths, timeout and runner.
40
+ * @returns The store a new secret should go to.
41
+ */
42
+ export function preferredStore(deps) {
43
+ const { env } = deps;
44
+ if (env.platform === 'darwin' && existsSync(path.join(env.home, ...MACOS_KEYCHAINS_DIR)) && findSystemExecutable(env, 'security'))
45
+ return secretStoreFor('macos-keychain', deps);
46
+ if (env.platform === 'linux' && env.vars[DBUS_SESSION_VAR] && findSystemExecutable(env, 'secret-tool'))
47
+ return secretStoreFor('libsecret', deps);
48
+ if (env.platform === 'win32' && findSystemExecutable(env, 'powershell'))
49
+ return secretStoreFor('windows-dpapi', deps);
50
+ return fileStore(deps);
51
+ }
52
+ /**
53
+ * The store a config names. A tool that has since disappeared reads as an
54
+ * absent secret, never as an error.
55
+ *
56
+ * @param kind - What the config recorded.
57
+ * @param deps - Environment, paths, timeout and runner.
58
+ * @returns The store.
59
+ */
60
+ export function secretStoreFor(kind, deps) {
61
+ if (kind === 'macos-keychain')
62
+ return macosKeychain(deps);
63
+ if (kind === 'libsecret')
64
+ return libsecret(deps);
65
+ if (kind === 'windows-dpapi')
66
+ return windowsDpapi(deps);
67
+ return fileStore(deps);
68
+ }
69
+ /**
70
+ * How a store is named to a person.
71
+ *
72
+ * @param kind - The store.
73
+ * @returns A phrase for `status`, `doctor` and setup.
74
+ */
75
+ export function storeLabel(kind) {
76
+ return STORE_LABELS[kind];
77
+ }
78
+ /**
79
+ * Where a store keeps one device's secret, said to a person who has to remove
80
+ * it by hand. Never the secret.
81
+ *
82
+ * @param kind - The store.
83
+ * @param deps - Paths.
84
+ * @param id - Device id.
85
+ * @returns A phrase naming the keychain entry or the file.
86
+ */
87
+ export function secretLocation(kind, deps, id) {
88
+ if (kind === 'macos-keychain' || kind === 'libsecret')
89
+ return `${storeLabel(kind)}, service ${KEYCHAIN_SERVICE}, account ${id}`;
90
+ return credentialFile(deps, id, kind === 'windows-dpapi' ? DPAPI_FILE_SUFFIX : SECRET_FILE_SUFFIX);
91
+ }
92
+ /**
93
+ * The private file a store keeps for one device id.
94
+ *
95
+ * @param deps - Paths.
96
+ * @param id - Device id.
97
+ * @param suffix - File kind.
98
+ * @returns Absolute path.
99
+ */
100
+ function credentialFile(deps, id, suffix) {
101
+ return path.join(deps.paths.configDir, CREDENTIALS_DIR_NAME, `${id}${suffix}`);
102
+ }
103
+ /**
104
+ * Run a keychain tool from the OS's own directories, never one PATH offers.
105
+ *
106
+ * @param deps - Environment, timeout and runner.
107
+ * @param tool - Executable name.
108
+ * @param args - Arguments; never a secret.
109
+ * @param input - Standard input.
110
+ * @returns The result, or undefined when the tool is not installed or the
111
+ * credential budget is spent (a store reads that as "absent").
112
+ */
113
+ async function runTool(deps, tool, args, input) {
114
+ const file = findSystemExecutable(deps.env, tool);
115
+ const budget = withinBudget(deps);
116
+ if (!file || !budget)
117
+ return undefined;
118
+ return (deps.run ?? runCommand)(file, args, { input, timeoutMs: budget.timeoutMs, env: deps.env.vars });
119
+ }
120
+ function macosKeychain(deps) {
121
+ const target = (id) => ['-s', KEYCHAIN_SERVICE, '-a', id];
122
+ return {
123
+ kind: 'macos-keychain',
124
+ async get(id) {
125
+ const result = await runTool(deps, 'security', ['find-generic-password', ...target(id), '-w']);
126
+ // Exit 44 is "no such item"; any other failure (a locked keychain) reads the same way here.
127
+ if (result?.code !== 0)
128
+ return undefined;
129
+ return result.stdout.trim() || undefined;
130
+ },
131
+ async set(id, secret) {
132
+ // The one check of the secret's characters: only here does a space or a
133
+ // quote become syntax (`security -i` parses its stdin as a command line).
134
+ // Any other store that misreads a secret fails the read-back in `saveSecret`.
135
+ if (!RE_SECRET_CHARS.test(secret))
136
+ return false;
137
+ // `-i` reads the command from stdin, so the secret never reaches argv.
138
+ const result = await runTool(deps, 'security', ['-i'], `add-generic-password -U -s ${KEYCHAIN_SERVICE} -l "${KEYCHAIN_LABEL}" -a ${id} -w ${secret}\n`);
139
+ return result?.code === 0;
140
+ },
141
+ async remove(id) {
142
+ await runTool(deps, 'security', ['delete-generic-password', ...target(id)]);
143
+ }
144
+ };
145
+ }
146
+ function libsecret(deps) {
147
+ const attributes = (id) => ['service', KEYCHAIN_SERVICE, 'account', id];
148
+ return {
149
+ kind: 'libsecret',
150
+ async get(id) {
151
+ const result = await runTool(deps, 'secret-tool', ['lookup', ...attributes(id)]);
152
+ return result?.code === 0 ? result.stdout.trim() || undefined : undefined;
153
+ },
154
+ async set(id, secret) {
155
+ const result = await runTool(deps, 'secret-tool', ['store', `--label=${KEYCHAIN_LABEL}`, ...attributes(id)], secret);
156
+ return result?.code === 0;
157
+ },
158
+ async remove(id) {
159
+ await runTool(deps, 'secret-tool', ['clear', ...attributes(id)]);
160
+ }
161
+ };
162
+ }
163
+ function windowsDpapi(deps) {
164
+ const powershell = (script, input) => runTool(deps, 'powershell', ['-NoProfile', '-NonInteractive', '-Command', script], input);
165
+ return {
166
+ kind: 'windows-dpapi',
167
+ async get(id) {
168
+ const blob = await readOrUndefined(credentialFile(deps, id, DPAPI_FILE_SUFFIX));
169
+ if (!blob)
170
+ return undefined;
171
+ const result = await powershell(DPAPI_UNPROTECT_SCRIPT, blob);
172
+ return result?.code === 0 ? result.stdout.trim() || undefined : undefined;
173
+ },
174
+ async set(id, secret) {
175
+ const result = await powershell(DPAPI_PROTECT_SCRIPT, secret);
176
+ const blob = result?.code === 0 ? result.stdout.trim() : '';
177
+ if (!blob)
178
+ return false;
179
+ // The blob only opens for this Windows user; 0600 is the same rule every
180
+ // other credential-bearing file here follows.
181
+ await writeFileAtomic(credentialFile(deps, id, DPAPI_FILE_SUFFIX), blob, SECRET_FILE_MODE);
182
+ return true;
183
+ },
184
+ async remove(id) {
185
+ await fs.rm(credentialFile(deps, id, DPAPI_FILE_SUFFIX), { force: true });
186
+ }
187
+ };
188
+ }
189
+ function fileStore(deps) {
190
+ return {
191
+ kind: 'file',
192
+ async get(id) {
193
+ return (await readOrUndefined(credentialFile(deps, id, SECRET_FILE_SUFFIX)))?.trim() || undefined;
194
+ },
195
+ async set(id, secret) {
196
+ await writeFileAtomic(credentialFile(deps, id, SECRET_FILE_SUFFIX), secret, SECRET_FILE_MODE);
197
+ return true;
198
+ },
199
+ async remove(id) {
200
+ await fs.rm(credentialFile(deps, id, SECRET_FILE_SUFFIX), { force: true });
201
+ }
202
+ };
203
+ }
204
+ /**
205
+ * A small file's text.
206
+ *
207
+ * @param file - Path.
208
+ * @returns Its contents, or undefined when it cannot be read.
209
+ */
210
+ async function readOrUndefined(file) {
211
+ try {
212
+ return await fs.readFile(file, 'utf8');
213
+ }
214
+ catch {
215
+ return undefined;
216
+ }
217
+ }
@@ -0,0 +1,31 @@
1
+ import type { CredentialContext, RedeemCodeInput, SignedIn, SignInInput } from './types/credentials.types.js';
2
+ /**
3
+ * Enroll this machine through the browser: show the verification code, wait
4
+ * for the developer to approve it, and keep the device credential it earns.
5
+ *
6
+ * No install key is read or sent on this path (SPEC R3). The device id is the
7
+ * fingerprint of the gateway's own id, which keeps it in the 12-hex shape the
8
+ * queue partitions and keychain accounts are named by. The secret is stored
9
+ * and the first token cached before the caller writes the config, so a crash
10
+ * in between costs one more sign-in, never a credential nobody can find.
11
+ *
12
+ * @param ctx - Paths, environment, timeout, fetch and keychain runner.
13
+ * @param input - Gateway, organization, installation, label, and where to print.
14
+ * @returns The device to name in the config and its secret (for undoing it if the config cannot be written), or the reason there is none.
15
+ */
16
+ export declare function signInDevice(ctx: CredentialContext, input: SignInInput): Promise<SignedIn | {
17
+ readonly error: string;
18
+ }>;
19
+ /**
20
+ * Enroll this machine with an admin-issued code, for one that has no browser
21
+ * (SPEC R4). No install key and no prompt: the code names the organization and
22
+ * the identity, and is spent by this one redeem. The credential is kept exactly
23
+ * as a sign-in's is.
24
+ *
25
+ * @param ctx - Paths, environment, timeout, fetch and keychain runner.
26
+ * @param input - Gateway, code, installation and label.
27
+ * @returns The device to name in the config and its secret, or the reason there is none.
28
+ */
29
+ export declare function enrollWithCode(ctx: CredentialContext, input: Omit<RedeemCodeInput, 'timeoutMs' | 'fetchFn'>): Promise<SignedIn | {
30
+ readonly error: string;
31
+ }>;
@@ -0,0 +1,105 @@
1
+ import { sleep } from '../core/async.js';
2
+ import { identityPaths } from '../transport/queue-partition.js';
3
+ import { DEVICE_SOURCE_BATCH_CODE, POLL_DENIED, POLL_EXPIRED, POLL_PENDING, POLL_SLOW_DOWN, RE_PLAIN_EMAIL, SLOW_DOWN_STEP_MS } from './constants/credentials.constants.js';
4
+ import { pollEnrollmentSession, redeemEnrollmentCode, revokeDevice, startEnrollmentSession } from './device-api.js';
5
+ import { writeAccessToken } from './device-state.js';
6
+ import { credentialId } from './identity.js';
7
+ import { saveSecret } from './secret-store.js';
8
+ /** Why a sign-in ended without a device, phrased for the developer. */
9
+ const REFUSED_MESSAGES = {
10
+ [POLL_DENIED]: 'sign-in was denied; nothing was enrolled',
11
+ [POLL_EXPIRED]: 'the sign-in code expired before it was approved; run setup again'
12
+ };
13
+ /**
14
+ * Enroll this machine through the browser: show the verification code, wait
15
+ * for the developer to approve it, and keep the device credential it earns.
16
+ *
17
+ * No install key is read or sent on this path (SPEC R3). The device id is the
18
+ * fingerprint of the gateway's own id, which keeps it in the 12-hex shape the
19
+ * queue partitions and keychain accounts are named by. The secret is stored
20
+ * and the first token cached before the caller writes the config, so a crash
21
+ * in between costs one more sign-in, never a credential nobody can find.
22
+ *
23
+ * @param ctx - Paths, environment, timeout, fetch and keychain runner.
24
+ * @param input - Gateway, organization, installation, label, and where to print.
25
+ * @returns The device to name in the config and its secret (for undoing it if the config cannot be written), or the reason there is none.
26
+ */
27
+ export async function signInDevice(ctx, input) {
28
+ const route = { endpoint: input.endpoint, timeoutMs: ctx.timeoutMs, fetchFn: ctx.fetchFn };
29
+ const started = await startEnrollmentSession({ ...route, organizationId: input.organizationId, installationId: input.installationId, name: input.name });
30
+ if (!started.ok)
31
+ return { error: `could not start sign-in with ${input.endpoint} (${started.status ?? 'no response'}); nothing was written` };
32
+ const { deviceCode, userCode, verificationUri, verificationUriComplete, expiresIn, interval } = started.value;
33
+ input.print(`Open ${verificationUriComplete}`);
34
+ input.print(`and confirm the code ${userCode} (${verificationUri}) to enroll this machine. Waiting up to ${Math.round(expiresIn / 60)} min...`);
35
+ try {
36
+ input.open?.(verificationUriComplete);
37
+ }
38
+ catch {
39
+ // The link is printed above; a browser that cannot open must not end the sign-in.
40
+ }
41
+ const wait = input.sleep ?? sleep;
42
+ const deadline = ctx.env.now().getTime() + expiresIn * 1000;
43
+ let pauseMs = interval * 1000;
44
+ while (ctx.env.now().getTime() < deadline) {
45
+ await wait(pauseMs);
46
+ const polled = await pollEnrollmentSession({ ...route, deviceCode, installationId: input.installationId });
47
+ if (polled.ok) {
48
+ return keep(ctx, input.endpoint, polled.value);
49
+ }
50
+ // Approved but unreadable: the code may be spent, so polling on would only time out.
51
+ if (polled.status === 200)
52
+ return { error: 'the gateway approved the sign-in but sent a credential this version cannot read; update agentwatch and run setup again' };
53
+ if (polled.error === POLL_SLOW_DOWN)
54
+ pauseMs += SLOW_DOWN_STEP_MS;
55
+ // Anything else short of a named end (a 429, a dropped connection) is waited out like a pending poll.
56
+ const refused = polled.error === undefined ? undefined : REFUSED_MESSAGES[polled.error];
57
+ if (refused)
58
+ return { error: refused };
59
+ if (polled.error !== undefined && polled.error !== POLL_PENDING && polled.error !== POLL_SLOW_DOWN)
60
+ return { error: `sign-in refused (${polled.error})` };
61
+ }
62
+ return { error: 'the sign-in code expired before it was approved; run setup again' };
63
+ }
64
+ /**
65
+ * Enroll this machine with an admin-issued code, for one that has no browser
66
+ * (SPEC R4). No install key and no prompt: the code names the organization and
67
+ * the identity, and is spent by this one redeem. The credential is kept exactly
68
+ * as a sign-in's is.
69
+ *
70
+ * @param ctx - Paths, environment, timeout, fetch and keychain runner.
71
+ * @param input - Gateway, code, installation and label.
72
+ * @returns The device to name in the config and its secret, or the reason there is none.
73
+ */
74
+ export async function enrollWithCode(ctx, input) {
75
+ const redeemed = await redeemEnrollmentCode({ ...input, timeoutMs: ctx.timeoutMs, fetchFn: ctx.fetchFn });
76
+ if (redeemed.ok)
77
+ return keep(ctx, input.endpoint, redeemed.value, { source: DEVICE_SOURCE_BATCH_CODE, codeId: credentialId(input.code) });
78
+ if (redeemed.refusal)
79
+ return { error: `the enrollment code was refused (${redeemed.refusal}): it is unknown, used, expired or revoked; ask your admin for a new one. Nothing was written` };
80
+ return { error: `could not redeem the enrollment code with ${input.endpoint} (${redeemed.status ?? 'no response'}); nothing was written` };
81
+ }
82
+ /**
83
+ * Store an approved credential. The gateway has issued it by now, so a store
84
+ * that fails is undone on the platform too: nothing would name the device, and
85
+ * neither uninstall nor a retry could find it.
86
+ *
87
+ * @param ctx - Paths, environment, timeout, fetch and keychain runner.
88
+ * @param endpoint - The gateway that issued it.
89
+ * @param issued - The credential the poll or the redeem returned.
90
+ * @param enrolledBy - How it was enrolled, when not by sign-in, and the code's fingerprint.
91
+ * @returns The device and its secret, or the reason it could not be kept.
92
+ */
93
+ async function keep(ctx, endpoint, issued, enrolledBy) {
94
+ const id = credentialId(issued.deviceId);
95
+ const files = identityPaths(ctx.paths, `device:${id}`);
96
+ try {
97
+ const store = await saveSecret(ctx, id, issued.deviceSecret);
98
+ await writeAccessToken(files.accessTokenFile, { accessToken: issued.accessToken, obtainedAt: ctx.env.now().toISOString(), expiresAt: issued.accessTokenExpiresAt });
99
+ return { device: { id, store, endpoint, ...enrolledBy }, deviceSecret: issued.deviceSecret, developerEmail: typeof issued.developerEmail === 'string' && RE_PLAIN_EMAIL.test(issued.developerEmail) ? issued.developerEmail : undefined };
100
+ }
101
+ catch {
102
+ await revokeDevice({ endpoint, deviceSecret: issued.deviceSecret, timeoutMs: ctx.timeoutMs, fetchFn: ctx.fetchFn });
103
+ return { error: 'the device credential could not be stored on this machine; it was revoked' };
104
+ }
105
+ }
@@ -0,0 +1,39 @@
1
+ import type { AgentWatchConfig } from '../config/types/config.types.js';
2
+ import type { AccessTokenCache, CredentialContext } from './types/credentials.types.js';
3
+ /**
4
+ * Whether a cached token is due for refresh: under a quarter of its life left,
5
+ * or less than the caller needs it to last.
6
+ *
7
+ * @param cache - The cached token.
8
+ * @param now - The clock.
9
+ * @param minRemainingMs - How long the caller will keep using what it gets.
10
+ * @returns True when it should be refreshed.
11
+ */
12
+ export declare function needsRefresh(cache: AccessTokenCache, now: Date, minRemainingMs?: number): boolean;
13
+ /**
14
+ * The cached access token while it is still valid. No network and no keychain:
15
+ * this is what the prompt path may afford.
16
+ *
17
+ * @param ctx - Paths and clock.
18
+ * @param config - Effective config holding a device credential.
19
+ * @returns The token, or undefined.
20
+ */
21
+ export declare function cachedAccessToken(ctx: CredentialContext, config: AgentWatchConfig): Promise<string | undefined>;
22
+ /**
23
+ * The access token to send now, refreshed when it is due.
24
+ *
25
+ * One refresher per machine, because the gateway keeps only the current and
26
+ * the previous token valid: a refresh happens under a cross-process lock, and a
27
+ * process that finds the lock taken uses the token it has, which under the 25%
28
+ * rule is still good for a quarter of an hour. The keychain is read only on an
29
+ * actual refresh, and neither it nor the gateway is asked while the backend
30
+ * cooldown stands. Only the refresh route's own refusals end refreshing until
31
+ * the machine is enrolled again (said once on stderr); any other failure trips
32
+ * the cooldown and is retried after it. Until a token comes back the caller
33
+ * sends nothing and its records queue.
34
+ *
35
+ * @param ctx - Paths, clock, timeout, deadline, fetch and keychain runner.
36
+ * @param config - Effective config holding a device credential.
37
+ * @returns The token, or undefined when there is none to send.
38
+ */
39
+ export declare function currentAccessToken(ctx: CredentialContext, config: AgentWatchConfig): Promise<string | undefined>;
@@ -0,0 +1,185 @@
1
+ import { spawn } from 'node:child_process';
2
+ import fs from 'node:fs';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { eventsUrl } from '../config/config.js';
5
+ import { debugLog, warnLog } from '../core/logger.js';
6
+ import { acquireLock } from '../storage/lock.js';
7
+ import { isUninstalled } from '../storage/uninstalled.js';
8
+ import { BackendAuthBlock } from '../transport/auth-block.js';
9
+ import { BACKEND_COOLDOWN_MS } from '../transport/constants/transport.constants.js';
10
+ import { BackendCooldown } from '../transport/cooldown.js';
11
+ import { identityPaths } from '../transport/queue-partition.js';
12
+ import { withinBudget } from './budget.js';
13
+ import { BACKGROUND_REFRESH_RETRY_MS, DEVICE_REFUSALS, REFRESH_COMMAND, REFRESH_REMAINING_FRACTION, REFUSAL_SECRET_EXPIRED, REFUSAL_TOKEN_EXPIRED, TOKEN_LOCK_PREFIX } from './constants/credentials.constants.js';
14
+ import { refreshAccessToken } from './device-api.js';
15
+ import { readAccessToken, readDeviceState, writeAccessToken, writeDeviceState } from './device-state.js';
16
+ import { identityOf } from './identity.js';
17
+ import { secretStoreFor } from './secret-store.js';
18
+ /**
19
+ * Whether a cached token is due for refresh: under a quarter of its life left,
20
+ * or less than the caller needs it to last.
21
+ *
22
+ * @param cache - The cached token.
23
+ * @param now - The clock.
24
+ * @param minRemainingMs - How long the caller will keep using what it gets.
25
+ * @returns True when it should be refreshed.
26
+ */
27
+ export function needsRefresh(cache, now, minRemainingMs = 0) {
28
+ const expires = Date.parse(cache.expiresAt);
29
+ const life = expires - Date.parse(cache.obtainedAt);
30
+ const left = expires - now.getTime();
31
+ return left < life * REFRESH_REMAINING_FRACTION || left < minRemainingMs;
32
+ }
33
+ /**
34
+ * The cached access token while it is still valid. No network and no keychain:
35
+ * this is what the prompt path may afford.
36
+ *
37
+ * @param ctx - Paths and clock.
38
+ * @param config - Effective config holding a device credential.
39
+ * @returns The token, or undefined.
40
+ */
41
+ export async function cachedAccessToken(ctx, config) {
42
+ if (!config.device)
43
+ return undefined;
44
+ return usable(await readAccessToken(identityPaths(ctx.paths, identityOf(config)).accessTokenFile), ctx.env.now());
45
+ }
46
+ /**
47
+ * The access token to send now, refreshed when it is due.
48
+ *
49
+ * One refresher per machine, because the gateway keeps only the current and
50
+ * the previous token valid: a refresh happens under a cross-process lock, and a
51
+ * process that finds the lock taken uses the token it has, which under the 25%
52
+ * rule is still good for a quarter of an hour. The keychain is read only on an
53
+ * actual refresh, and neither it nor the gateway is asked while the backend
54
+ * cooldown stands. Only the refresh route's own refusals end refreshing until
55
+ * the machine is enrolled again (said once on stderr); any other failure trips
56
+ * the cooldown and is retried after it. Until a token comes back the caller
57
+ * sends nothing and its records queue.
58
+ *
59
+ * @param ctx - Paths, clock, timeout, deadline, fetch and keychain runner.
60
+ * @param config - Effective config holding a device credential.
61
+ * @returns The token, or undefined when there is none to send.
62
+ */
63
+ export async function currentAccessToken(ctx, config) {
64
+ const device = config.device;
65
+ if (!device)
66
+ return undefined;
67
+ const files = identityPaths(ctx.paths, identityOf(config));
68
+ const destination = eventsUrl(config);
69
+ const [block, cached] = await Promise.all([
70
+ destination ? new BackendAuthBlock(files.authBlockFile, ctx.env.now).active(destination) : undefined,
71
+ readAccessToken(files.accessTokenFile)
72
+ ]);
73
+ const expired = block?.reason === REFUSAL_TOKEN_EXPIRED;
74
+ if (cached && !expired && !needsRefresh(cached, ctx.env.now(), ctx.minRemainingMs))
75
+ return cached.accessToken;
76
+ const fallback = expired ? undefined : usable(cached, ctx.env.now());
77
+ if (!config.endpoint)
78
+ return fallback;
79
+ const cooldown = new BackendCooldown(files.cooldownFile, ctx.env.now);
80
+ if ((await cooldown.active()) || (await readDeviceState(files.deviceStateFile)).refusal)
81
+ return fallback;
82
+ // DPAPI is PowerShell, which does not fit a hook's budget: a detached
83
+ // `agentwatch refresh-credential` refreshes under the same lock, and this
84
+ // hook sends what it has (or queues).
85
+ if (ctx.hookPath && device.store === 'windows-dpapi') {
86
+ await startBackgroundRefresh(ctx, files.deviceStateFile);
87
+ return fallback;
88
+ }
89
+ const release = await acquireLock(ctx.paths.locksDir, TOKEN_LOCK_PREFIX + device.id, ctx.env.now).catch(() => undefined);
90
+ if (!release)
91
+ return fallback;
92
+ try {
93
+ // Another process may have refreshed between our read and our lock.
94
+ const fresh = await readAccessToken(files.accessTokenFile);
95
+ if (fresh && fresh.obtainedAt !== cached?.obtainedAt && !needsRefresh(fresh, ctx.env.now(), ctx.minRemainingMs))
96
+ return fresh.accessToken;
97
+ const secret = await secretStoreFor(device.store, ctx).get(device.id);
98
+ const budget = withinBudget(ctx);
99
+ // Unreadable is not refused: a locked keychain opens again.
100
+ if (!secret || !budget)
101
+ return fallback;
102
+ const result = await refreshAccessToken({ endpoint: config.endpoint, deviceSecret: secret, timeoutMs: budget.timeoutMs, fetchFn: ctx.fetchFn });
103
+ // Uninstall may have marked this scope while the refresh was out: a token
104
+ // cached now would outlive the credential uninstall is removing.
105
+ if (result.ok && (await isUninstalled(ctx.paths, ctx.scope)))
106
+ return undefined;
107
+ if (result.ok) {
108
+ await writeAccessToken(files.accessTokenFile, { accessToken: result.value.accessToken, obtainedAt: ctx.env.now().toISOString(), expiresAt: result.value.accessTokenExpiresAt });
109
+ if (expired)
110
+ await new BackendAuthBlock(files.authBlockFile, ctx.env.now).clear();
111
+ return result.value.accessToken;
112
+ }
113
+ if (result.refusal && DEVICE_REFUSALS.has(result.refusal)) {
114
+ await recordRefusal(files.deviceStateFile, result.refusal, ctx);
115
+ return undefined;
116
+ }
117
+ await cooldown.trip(BACKEND_COOLDOWN_MS);
118
+ return fallback;
119
+ }
120
+ finally {
121
+ await release();
122
+ }
123
+ }
124
+ /**
125
+ * Remember that the gateway refused the device secret, and say so once.
126
+ *
127
+ * @param file - The identity's device state file.
128
+ * @param reason - What the gateway said.
129
+ * @param ctx - Clock.
130
+ */
131
+ async function recordRefusal(file, reason, ctx) {
132
+ const state = await readDeviceState(file);
133
+ await writeDeviceState(file, { ...state, refusal: { reason, since: ctx.env.now().toISOString() } });
134
+ if (reason === REFUSAL_SECRET_EXPIRED) {
135
+ warnLog('this machine\'s device secret expired; it is enrolled again with its install key, and events queue until then.');
136
+ return;
137
+ }
138
+ warnLog(`the backend refused this machine's device credential (${reason}); events are queued, not sent. Enroll it again with \`agentwatch setup --token <install key>\`.`);
139
+ }
140
+ /**
141
+ * Start one detached refresher for a Windows hook, unless one started recently.
142
+ *
143
+ * Bounded twice: at most one per `BACKGROUND_REFRESH_RETRY_MS`, and the child
144
+ * itself refreshes under the token lock with its own timeouts, so a burst of
145
+ * hooks costs one PowerShell, not one each.
146
+ *
147
+ * @param ctx - Clock, cwd and, in tests, the starter.
148
+ * @param stateFile - The identity's device state file.
149
+ */
150
+ async function startBackgroundRefresh(ctx, stateFile) {
151
+ const state = await readDeviceState(stateFile);
152
+ const now = ctx.env.now();
153
+ if (state.backgroundRefreshAt && now.getTime() - Date.parse(state.backgroundRefreshAt) < BACKGROUND_REFRESH_RETRY_MS)
154
+ return;
155
+ await writeDeviceState(stateFile, { ...state, backgroundRefreshAt: now.toISOString() });
156
+ try {
157
+ (ctx.startBackgroundRefresh ?? spawnRefresher)(ctx.env.cwd);
158
+ }
159
+ catch (error) {
160
+ debugLog('credentials: starting the background refresh failed:', error);
161
+ }
162
+ }
163
+ /**
164
+ * Start `agentwatch refresh-credential` detached, in the hook's directory so
165
+ * it refreshes the same identity, with nothing tying it to the hook process.
166
+ *
167
+ * @param cwd - The hook's working directory.
168
+ */
169
+ function spawnRefresher(cwd) {
170
+ const cli = fileURLToPath(new URL('../cli.js', import.meta.url));
171
+ // Only from the built CLI: run from source there is nothing to start.
172
+ if (!fs.existsSync(cli))
173
+ return;
174
+ spawn(process.execPath, [cli, REFRESH_COMMAND], { cwd, detached: true, stdio: 'ignore', windowsHide: true }).unref();
175
+ }
176
+ /**
177
+ * A cached token's value while it has not expired.
178
+ *
179
+ * @param cache - The cached token.
180
+ * @param now - The clock.
181
+ * @returns The token, or undefined.
182
+ */
183
+ function usable(cache, now) {
184
+ return cache && Date.parse(cache.expiresAt) > now.getTime() ? cache.accessToken : undefined;
185
+ }