shapewall 0.0.0-stage → 0.2.2

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 (304) hide show
  1. package/CHANGELOG.md +139 -0
  2. package/Dockerfile.agent +45 -0
  3. package/LICENSE +202 -0
  4. package/NOTICE +12 -0
  5. package/README.md +651 -2
  6. package/THIRD_PARTY.md +165 -0
  7. package/bin/shapewall.js +29 -0
  8. package/dist/agent/package-lock.json +8384 -0
  9. package/dist/client/assets/BoardChat-D5SFd8HE.js +28 -0
  10. package/dist/client/assets/BuzzDialog-HWXBy52W.js +1 -0
  11. package/dist/client/assets/ChecksPanel-DTdImWoD.js +1 -0
  12. package/dist/client/assets/History-CEv6b-av.js +1 -0
  13. package/dist/client/assets/LocalSettings-C4vriEVQ.js +1 -0
  14. package/dist/client/assets/Management-DCfhcEUY.js +1 -0
  15. package/dist/client/assets/QuickConnect-DQGgUsl1.js +1 -0
  16. package/dist/client/assets/ShareDialog-C_plIto0.js +2 -0
  17. package/dist/client/assets/app-update-dialog-2hPz_N9G.js +1 -0
  18. package/dist/client/assets/circle-x-BZMPi8Zf.js +1 -0
  19. package/dist/client/assets/index-ByQRKVit.css +2 -0
  20. package/dist/client/assets/index-DweQ8Qtu.js +29 -0
  21. package/dist/client/assets/refresh-cw-CRow0Nbq.js +1 -0
  22. package/dist/client/assets/runtime-Bft6x_6E.js +4 -0
  23. package/dist/client/assets/square-A8EnIYLR.js +1 -0
  24. package/dist/client/assets/tts-dist-DYlBQmwG.js +18 -0
  25. package/dist/client/assets/tts-en-g2p-BPUtBFGG.js +1 -0
  26. package/dist/client/assets/tts-ort-wasm-simd-threaded-qh98TCA_.wasm +0 -0
  27. package/dist/client/assets/tts-ort.wasm.bundle.min-rEkcs_ow.js +12 -0
  28. package/dist/client/assets/tts-rolldown-runtime-D8NudN84.js +1 -0
  29. package/dist/client/assets/tts-spacy-en-tokenizer-6SNMl--A.json +1 -0
  30. package/dist/client/assets/tts-tts.worker-Bzm6aWbv.js +1 -0
  31. package/dist/client/assets/tts-us_gold-DcjeNMH1.json +92589 -0
  32. package/dist/client/assets/tts-us_silver-C964mEB5.json +93363 -0
  33. package/dist/client/assets/ui-CLbws0rx.js +41 -0
  34. package/dist/client/build-info.json +1 -0
  35. package/dist/client/favicon.svg +7 -0
  36. package/dist/client/icons/apple-touch-icon.png +0 -0
  37. package/dist/client/icons/icon-192.png +0 -0
  38. package/dist/client/icons/icon-512.png +0 -0
  39. package/dist/client/icons/maskable-512.png +0 -0
  40. package/dist/client/index.html +25 -0
  41. package/dist/client/manifest.webmanifest +15 -0
  42. package/dist/client/sw.js +53 -0
  43. package/dist/client/theme-boot.js +27 -0
  44. package/dist/console/assets/LocalAccountsApp-BQCcmj3x.js +1 -0
  45. package/dist/console/assets/LocalConsole-Bb2FUDs7.js +1 -0
  46. package/dist/console/assets/app-update-dialog-DIeYepLZ.js +1 -0
  47. package/dist/console/assets/console-C7uJLLOn.js +51 -0
  48. package/dist/console/assets/console-R8IBY3Am.css +2 -0
  49. package/dist/console/build-info.json +1 -0
  50. package/dist/console/console.html +21 -0
  51. package/dist/console/favicon.svg +7 -0
  52. package/dist/console/icons/apple-touch-icon.png +0 -0
  53. package/dist/console/icons/icon-192.png +0 -0
  54. package/dist/console/icons/icon-512.png +0 -0
  55. package/dist/console/icons/maskable-512.png +0 -0
  56. package/dist/console/manifest.webmanifest +15 -0
  57. package/dist/console/theme-boot.js +27 -0
  58. package/docs/agent-hardening.md +342 -0
  59. package/docs/agent-recipes.md +187 -0
  60. package/docs/agent-workflow.md +320 -0
  61. package/docs/agents.md +894 -0
  62. package/docs/architecture.md +242 -0
  63. package/docs/buzz.md +140 -0
  64. package/docs/capture-warnings.md +57 -0
  65. package/docs/config.md +489 -0
  66. package/docs/deployment.md +289 -0
  67. package/docs/design-system.md +162 -0
  68. package/docs/github.md +107 -0
  69. package/docs/hosted.md +764 -0
  70. package/docs/images/board-overview.png +0 -0
  71. package/docs/images/journeys.png +0 -0
  72. package/docs/images/live-comment.png +0 -0
  73. package/docs/images/phone-comment.png +0 -0
  74. package/docs/images/phone-overview.png +0 -0
  75. package/docs/images/variant.png +0 -0
  76. package/docs/interaction-audits.md +40 -0
  77. package/docs/journeys.md +137 -0
  78. package/docs/local-accounts.md +80 -0
  79. package/docs/notifications.md +237 -0
  80. package/docs/page-checks.md +69 -0
  81. package/docs/performance.md +174 -0
  82. package/docs/starter-agent.md +325 -0
  83. package/docs/updates.md +87 -0
  84. package/examples/audits/interaction.audit.json +17 -0
  85. package/package.json +132 -4
  86. package/src/accounts/avatar.js +121 -0
  87. package/src/accounts/local.js +464 -0
  88. package/src/agent/acp/command.js +204 -0
  89. package/src/agent/acp/detect.js +75 -0
  90. package/src/agent/acp/sandbox.js +160 -0
  91. package/src/agent/agent-health.js +75 -0
  92. package/src/agent/backends/acp.js +1297 -0
  93. package/src/agent/backends/index.js +61 -0
  94. package/src/agent/backends/openai.js +308 -0
  95. package/src/agent/composer.js +221 -0
  96. package/src/agent/config.js +338 -0
  97. package/src/agent/context.js +191 -0
  98. package/src/agent/control.js +122 -0
  99. package/src/agent/errors.js +17 -0
  100. package/src/agent/feedback-loop.js +137 -0
  101. package/src/agent/manage.js +94 -0
  102. package/src/agent/next-steps.js +51 -0
  103. package/src/agent/owner-mcp.js +38 -0
  104. package/src/agent/plain-text.js +52 -0
  105. package/src/agent/ratings-core.js +213 -0
  106. package/src/agent/ratings.js +100 -0
  107. package/src/agent/reply-text.js +67 -0
  108. package/src/agent/routes.js +1065 -0
  109. package/src/agent/run.js +326 -0
  110. package/src/agent/settings-routes.js +704 -0
  111. package/src/agent/showable.js +23 -0
  112. package/src/agent/starter/approvals.js +181 -0
  113. package/src/agent/starter/build-image.js +90 -0
  114. package/src/agent/starter/cli.js +163 -0
  115. package/src/agent/starter/disk.js +53 -0
  116. package/src/agent/starter/doctor.js +180 -0
  117. package/src/agent/starter/egress-proxy.js +351 -0
  118. package/src/agent/starter/gate.js +90 -0
  119. package/src/agent/starter/loop.js +114 -0
  120. package/src/agent/starter/model-relay.js +289 -0
  121. package/src/agent/starter/pause.js +14 -0
  122. package/src/agent/starter/probe.js +272 -0
  123. package/src/agent/starter/prompt.js +41 -0
  124. package/src/agent/starter/push-guard.js +146 -0
  125. package/src/agent/starter/rpc.js +164 -0
  126. package/src/agent/starter/runtime.js +287 -0
  127. package/src/agent/starter/sandbox-main.js +121 -0
  128. package/src/agent/starter/settings.js +290 -0
  129. package/src/agent/starter/source.js +69 -0
  130. package/src/agent/starter/supervisor.js +755 -0
  131. package/src/agent/starter/sweep.js +46 -0
  132. package/src/agent/starter/tools.js +524 -0
  133. package/src/agent/starter/watch.js +84 -0
  134. package/src/agent/starter/worktree.js +409 -0
  135. package/src/agent/text-diff.js +210 -0
  136. package/src/agent/thread-history.js +223 -0
  137. package/src/agent/threads.js +399 -0
  138. package/src/agent/tools.js +200 -0
  139. package/src/agent/turn-changes.js +424 -0
  140. package/src/agent/undo-state.js +26 -0
  141. package/src/agent/user-settings.js +308 -0
  142. package/src/auth/record.js +375 -0
  143. package/src/broken-links.js +164 -0
  144. package/src/buzz/client.js +75 -0
  145. package/src/buzz/config.js +151 -0
  146. package/src/buzz/environment.js +13 -0
  147. package/src/buzz/gateway.js +192 -0
  148. package/src/buzz/routes.js +61 -0
  149. package/src/buzz/signer-child.js +205 -0
  150. package/src/buzz/store.js +89 -0
  151. package/src/buzz/transport.js +60 -0
  152. package/src/buzz/verify.js +140 -0
  153. package/src/capture/actions.js +159 -0
  154. package/src/capture/capture.js +776 -0
  155. package/src/capture/dom-names.js +189 -0
  156. package/src/capture/element-map.js +509 -0
  157. package/src/capture/live.js +827 -0
  158. package/src/capture/media-scheme.js +317 -0
  159. package/src/capture/network-summary.js +86 -0
  160. package/src/capture/pacing.js +34 -0
  161. package/src/capture/requests.js +167 -0
  162. package/src/capture/sanitize.js +752 -0
  163. package/src/checks/accessibility.js +134 -0
  164. package/src/checks/budgets.js +58 -0
  165. package/src/checks/cli.js +55 -0
  166. package/src/checks/comparison.js +113 -0
  167. package/src/checks/environments.js +32 -0
  168. package/src/checks/flow-config.js +82 -0
  169. package/src/checks/flow-origin.js +53 -0
  170. package/src/checks/flows.js +398 -0
  171. package/src/checks/lighthouse-auth.js +145 -0
  172. package/src/checks/lighthouse-findings.js +130 -0
  173. package/src/checks/lighthouse.js +395 -0
  174. package/src/checks/robots.js +85 -0
  175. package/src/checks/routes.js +52 -0
  176. package/src/checks/run-control.js +259 -0
  177. package/src/checks/runner.js +724 -0
  178. package/src/checks/schema.js +133 -0
  179. package/src/checks/seo-analysis.js +443 -0
  180. package/src/checks/seo-probe.js +190 -0
  181. package/src/checks/seo-snapshot.js +99 -0
  182. package/src/checks/store.js +214 -0
  183. package/src/checks/transport.js +47 -0
  184. package/src/cli/args.js +319 -0
  185. package/src/cli/capture.js +79 -0
  186. package/src/cli/commands.js +92 -0
  187. package/src/cli/comments.js +84 -0
  188. package/src/cli/help.js +243 -0
  189. package/src/cli/init.js +214 -0
  190. package/src/cli/misc.js +64 -0
  191. package/src/cli/notify.js +87 -0
  192. package/src/cli/open.js +22 -0
  193. package/src/cli/serve.js +274 -0
  194. package/src/cli/variant.js +82 -0
  195. package/src/cli/watch.js +70 -0
  196. package/src/cli.js +130 -0
  197. package/src/comment-fields.js +76 -0
  198. package/src/comments-cli.js +208 -0
  199. package/src/config-reload.js +100 -0
  200. package/src/config.js +1061 -0
  201. package/src/devices-cli.js +21 -0
  202. package/src/diff.js +95 -0
  203. package/src/discover.js +284 -0
  204. package/src/doctor.js +295 -0
  205. package/src/event-log.js +268 -0
  206. package/src/events-cli.js +102 -0
  207. package/src/events.js +113 -0
  208. package/src/export.js +119 -0
  209. package/src/feedback.js +246 -0
  210. package/src/github.js +551 -0
  211. package/src/hosted/LICENSE.md +105 -0
  212. package/src/hosted/access-cli.js +78 -0
  213. package/src/hosted/admin.js +682 -0
  214. package/src/hosted/agent-approvals.js +163 -0
  215. package/src/hosted/agent-policy.js +189 -0
  216. package/src/hosted/app.js +510 -0
  217. package/src/hosted/auth-routes.js +540 -0
  218. package/src/hosted/auth.js +536 -0
  219. package/src/hosted/backup.js +483 -0
  220. package/src/hosted/board-context.js +35 -0
  221. package/src/hosted/board-routes.js +486 -0
  222. package/src/hosted/board-view.js +94 -0
  223. package/src/hosted/clean-worker.js +24 -0
  224. package/src/hosted/cleaner.js +89 -0
  225. package/src/hosted/comments.js +355 -0
  226. package/src/hosted/console-routes.js +401 -0
  227. package/src/hosted/cookies.js +18 -0
  228. package/src/hosted/crypto.js +80 -0
  229. package/src/hosted/db.js +496 -0
  230. package/src/hosted/device-routes.js +175 -0
  231. package/src/hosted/device.js +233 -0
  232. package/src/hosted/events.js +63 -0
  233. package/src/hosted/guards.js +172 -0
  234. package/src/hosted/guest-view.js +65 -0
  235. package/src/hosted/http.js +39 -0
  236. package/src/hosted/import.js +300 -0
  237. package/src/hosted/mail.js +73 -0
  238. package/src/hosted/mcp-http.js +71 -0
  239. package/src/hosted/membership.js +114 -0
  240. package/src/hosted/operator.js +478 -0
  241. package/src/hosted/ops-cli.js +345 -0
  242. package/src/hosted/pages.js +146 -0
  243. package/src/hosted/permissions.js +113 -0
  244. package/src/hosted/presence.js +372 -0
  245. package/src/hosted/projects.js +124 -0
  246. package/src/hosted/public.js +109 -0
  247. package/src/hosted/push.js +622 -0
  248. package/src/hosted/quotas.js +115 -0
  249. package/src/hosted/ratelimit.js +96 -0
  250. package/src/hosted/rebind.js +316 -0
  251. package/src/hosted/retention.js +128 -0
  252. package/src/hosted/server.js +260 -0
  253. package/src/hosted/setup-link.js +64 -0
  254. package/src/hosted/setup.js +323 -0
  255. package/src/hosted/shares.js +444 -0
  256. package/src/hosted/tailscale.js +204 -0
  257. package/src/hosted/tenancy.js +301 -0
  258. package/src/hosted/token-api.js +455 -0
  259. package/src/hosted/token-events.js +60 -0
  260. package/src/hosted/tokens.js +57 -0
  261. package/src/hosted/turnstile.js +49 -0
  262. package/src/hosted/usercontent.js +154 -0
  263. package/src/hosted/zip.js +155 -0
  264. package/src/invocation.js +58 -0
  265. package/src/journey-paths.js +282 -0
  266. package/src/journeys.js +189 -0
  267. package/src/links.js +106 -0
  268. package/src/local-projects.js +182 -0
  269. package/src/lock.js +193 -0
  270. package/src/mcp.js +417 -0
  271. package/src/mentions.js +151 -0
  272. package/src/net.js +15 -0
  273. package/src/notify/config.js +275 -0
  274. package/src/notify/index.js +301 -0
  275. package/src/notify/lease.js +73 -0
  276. package/src/notify/messages.js +212 -0
  277. package/src/notify/run.js +174 -0
  278. package/src/pixeldiff.js +49 -0
  279. package/src/png.js +143 -0
  280. package/src/reactions.js +111 -0
  281. package/src/remote/cli.js +133 -0
  282. package/src/remote/credentials.js +62 -0
  283. package/src/remote/ids.js +12 -0
  284. package/src/remote/login.js +155 -0
  285. package/src/remote/remote-mcp.js +237 -0
  286. package/src/remote/remote-watch.js +291 -0
  287. package/src/remote/remote.js +313 -0
  288. package/src/remote/share-state.js +78 -0
  289. package/src/remote/share.js +369 -0
  290. package/src/remote/terminal.js +13 -0
  291. package/src/serve-state.js +64 -0
  292. package/src/server/app.js +824 -0
  293. package/src/server/devices.js +186 -0
  294. package/src/server/local-console.js +28 -0
  295. package/src/server/local-user.js +59 -0
  296. package/src/server/pairing-routes.js +159 -0
  297. package/src/server/share-routes.js +89 -0
  298. package/src/server/tailscale.js +97 -0
  299. package/src/sitemap.js +431 -0
  300. package/src/store.js +983 -0
  301. package/src/tokens.js +11 -0
  302. package/src/update/routes.js +245 -0
  303. package/src/watch.js +403 -0
  304. package/src/which.js +58 -0
@@ -0,0 +1,308 @@
1
+ // Agent settings saved from the board (Settings > Agent).
2
+ //
3
+ // They live in a file of the person's own, outside every repo:
4
+ // $XDG_CONFIG_HOME/shapewall/agents.json (~/.config/shapewall/agents.json, or
5
+ // %APPDATA%\shapewall\agents.json on Windows), one entry per project, keyed
6
+ // by the real path of the project folder. Never shapewall.config.json: a repo
7
+ // is usually shared, and a cloned one must not be able to choose a command
8
+ // that runs on your machine or a host your API key goes to.
9
+ //
10
+ // No key is ever stored here, only the name of the environment variable that
11
+ // holds it. SHAPEWALL_AGENT_SETTINGS_FILE points at another file (tests, or
12
+ // a second set of settings).
13
+ //
14
+ // Precedence (src/agent/config.js agentSettings): the --agent-acp flag and
15
+ // the environment, then this file, then shapewall.config.json.
16
+
17
+ import crypto from 'node:crypto'
18
+ import fs from 'node:fs'
19
+ import path from 'node:path'
20
+ import { splitCommand } from '../watch.js'
21
+ import { SETTINGS_SOURCE } from './acp/command.js'
22
+ import { DENIED_KEY_VARS, KEY_VAR_RE, validateAgent } from './config.js'
23
+
24
+ export const SETTINGS_FILE_VAR = 'SHAPEWALL_AGENT_SETTINGS_FILE'
25
+ export const ENTRY_KEYS = ['backend', 'baseUrl', 'model', 'apiKeyEnv', 'label', 'vision', 'keyHosts', 'acpCommand', 'profiles']
26
+ const SECRET_KEYS = ['apiKey', 'key', 'token', 'secret', 'password']
27
+ const ACP_COMMAND_MAX = 2000
28
+ const KEY_HOSTS_MAX = 20
29
+ // host or host:port, a DNS name or a bracketed IPv6 address.
30
+ const HOST_RE = /^(?:[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?(?:\.[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?)*|\[[0-9a-f:.]+\])(?::\d{1,5})?$/
31
+
32
+ const isObject = (value) => Boolean(value) && typeof value === 'object' && !Array.isArray(value)
33
+
34
+ // The settings file, or null when there is no home to put it in.
35
+ export function userSettingsFile(env = process.env) {
36
+ if (typeof env[SETTINGS_FILE_VAR] === 'string' && env[SETTINGS_FILE_VAR].trim()) return path.resolve(env[SETTINGS_FILE_VAR].trim())
37
+ const absolute = (value) => (typeof value === 'string' && path.isAbsolute(value) ? value : null)
38
+ const base =
39
+ absolute(env.XDG_CONFIG_HOME) ||
40
+ (process.platform === 'win32' ? absolute(env.APPDATA) : null) ||
41
+ (absolute(env.HOME) ? path.join(env.HOME, '.config') : null)
42
+ return base ? path.join(base, 'shapewall', 'agents.json') : null
43
+ }
44
+
45
+ // The key of a project in the file: its folder's real path, so two spellings
46
+ // of one folder (a symlink, a relative path) share their settings.
47
+ export function projectKey(root) {
48
+ try {
49
+ return fs.realpathSync.native(path.resolve(root))
50
+ } catch {
51
+ return path.resolve(root)
52
+ }
53
+ }
54
+
55
+ // Checks one project's entry, from the file or from a save on the board.
56
+ // Empty strings and null mean "not set". { entry, problems }
57
+ export function validateUserEntry(raw) {
58
+ const problems = []
59
+ if (!isObject(raw)) return { entry: null, problems: ['the settings must be an object'] }
60
+ const given = Object.fromEntries(Object.entries(raw).filter(([, value]) => value !== null && value !== undefined && value !== ''))
61
+ for (const key of Object.keys(given)) {
62
+ if (SECRET_KEYS.includes(key))
63
+ problems.push(`${key}: keys are never saved; set the key in the environment and name its variable in apiKeyEnv`)
64
+ else if (!ENTRY_KEYS.includes(key) && key !== 'updatedAt') problems.push(`${key}: not an agent setting`)
65
+ }
66
+ const { keyHosts, acpCommand, profiles, updatedAt, ...rest } = given
67
+ const fields = {}
68
+ for (const key of ['backend', 'baseUrl', 'model', 'apiKeyEnv', 'label', 'vision']) if (rest[key] !== undefined) fields[key] = rest[key]
69
+ const agentProblems = []
70
+ const checked = validateAgent(fields, agentProblems)
71
+ problems.push(...agentProblems.map((problem) => problem.replace(/^agent\./, '')))
72
+ const entry = {}
73
+ if (checked) {
74
+ if (fields.backend !== undefined) entry.backend = checked.backend
75
+ if (checked.baseUrl) entry.baseUrl = checked.baseUrl.trim().replace(/\/+$/, '')
76
+ if (checked.model) entry.model = checked.model
77
+ if (checked.apiKeyEnv) entry.apiKeyEnv = checked.apiKeyEnv
78
+ if (checked.label) entry.label = checked.label
79
+ // Does the model take images? Unset: assume yes (an ACP agent says so itself).
80
+ if (typeof fields.vision === 'boolean') entry.vision = fields.vision
81
+ }
82
+ // keyHosts: [{ host, apiKeyEnv }]. A host is allowed for one key variable:
83
+ // pointing another key at it asks again.
84
+ if (keyHosts !== undefined) {
85
+ if (!Array.isArray(keyHosts) || keyHosts.length > KEY_HOSTS_MAX) {
86
+ problems.push(`keyHosts: a list of at most ${KEY_HOSTS_MAX} { host, apiKeyEnv } pairs`)
87
+ } else {
88
+ const pairs = []
89
+ for (const item of keyHosts) {
90
+ const host = isObject(item) && typeof item.host === 'string' ? item.host.trim().toLowerCase() : ''
91
+ const keyVar = isObject(item) && typeof item.apiKeyEnv === 'string' ? item.apiKeyEnv : ''
92
+ if (!HOST_RE.test(host) || host.length > 260) problems.push(`keyHosts: not a host name: ${JSON.stringify(item?.host ?? item)}`)
93
+ else if (!KEY_VAR_RE.test(keyVar) || DENIED_KEY_VARS.has(keyVar)) problems.push(`keyHosts: ${host}: not a model key variable`)
94
+ else if (!pairs.some((pair) => pair.host === host && pair.apiKeyEnv === keyVar)) pairs.push({ host, apiKeyEnv: keyVar })
95
+ }
96
+ if (pairs.length) entry.keyHosts = pairs
97
+ }
98
+ }
99
+ if (acpCommand !== undefined) {
100
+ if (typeof acpCommand !== 'string' || acpCommand.length > ACP_COMMAND_MAX || /[\r\n\0]/.test(acpCommand)) {
101
+ problems.push(`acpCommand: one line, at most ${ACP_COMMAND_MAX} characters`)
102
+ } else {
103
+ try {
104
+ if (splitCommand(acpCommand, SETTINGS_SOURCE).length) entry.acpCommand = acpCommand.trim()
105
+ } catch (error) {
106
+ problems.push(`acpCommand: ${error.message}`)
107
+ }
108
+ }
109
+ }
110
+ if (profiles !== undefined) {
111
+ if (!Array.isArray(profiles) || profiles.length > 8) problems.push('profiles: a list of at most 8 native agent profiles')
112
+ else {
113
+ const ids = new Set()
114
+ const checkedProfiles = []
115
+ for (const profile of profiles) {
116
+ if (
117
+ !isObject(profile) ||
118
+ Object.keys(profile).some((key) => !['id', 'label', 'acpCommand'].includes(key)) ||
119
+ !/^[a-z][a-z0-9-]{0,39}$/.test(profile.id || '') ||
120
+ profile.id === 'default' ||
121
+ ids.has(profile.id) ||
122
+ typeof profile.label !== 'string' ||
123
+ !profile.label.trim() ||
124
+ profile.label.length > 80 ||
125
+ /[\r\n\0]/.test(profile.label)
126
+ ) {
127
+ problems.push('profiles: each profile needs a unique id and a short label')
128
+ continue
129
+ }
130
+ const validated = validateUserEntry({ acpCommand: profile.acpCommand })
131
+ if (!validated.entry?.acpCommand) problems.push('profiles: each profile needs a valid ACP command')
132
+ else checkedProfiles.push({ id: profile.id, label: profile.label.trim(), acpCommand: validated.entry.acpCommand })
133
+ ids.add(profile.id)
134
+ }
135
+ if (checkedProfiles.length) entry.profiles = checkedProfiles
136
+ }
137
+ }
138
+ if (typeof updatedAt === 'string') entry.updatedAt = updatedAt
139
+ return { entry: problems.length ? null : entry, problems }
140
+ }
141
+
142
+ // Native profiles are the one list of connected agents. The default
143
+ // connection (backend "acp" with acpCommand) is what new chats use; it is
144
+ // either one of the profiles (the same command) or, in settings saved before
145
+ // profiles existed (one-click Connect saved only that), a command of its own,
146
+ // which is shown and kept as a profile from then on (legacyProfile).
147
+
148
+ // Which agent is the default is stored as the default connection itself
149
+ // (backend "acp" and the profile's acpCommand, or an endpoint): there is no
150
+ // separate marker to fall out of step with it. Settings that hold profiles
151
+ // but no default connection of their own (hand-edited, or from a version
152
+ // that only kept the list) use the first profile, unless the config's own
153
+ // endpoint is in effect (config.js agentSettings, `defaultProfile`).
154
+ export function implicitDefault(entry) {
155
+ if (!entry?.profiles?.length) return null
156
+ if (['backend', 'acpCommand', 'baseUrl', 'model'].some((key) => entry[key] !== undefined)) return null
157
+ return entry.profiles[0]
158
+ }
159
+
160
+ // The saved profile that runs the default connection's command, or null.
161
+ export function profileForDefault(entry) {
162
+ if (entry?.backend !== 'acp' || !entry.acpCommand) return null
163
+ return (entry.profiles || []).find((profile) => profile.acpCommand === entry.acpCommand) || null
164
+ }
165
+
166
+ // The default ACP command as a profile, when no saved profile runs it.
167
+ // `known`: [{ id, label, command }] (the agents Shapewall knows, acp/detect.js)
168
+ // names it; else it is "Agent command". The id never clashes with a saved one.
169
+ export function legacyProfile(entry, known = []) {
170
+ if (entry?.backend !== 'acp' || !entry.acpCommand || profileForDefault(entry)) return null
171
+ const agent = known.find((item) => item.command === entry.acpCommand)
172
+ const taken = new Set((entry.profiles || []).map((profile) => profile.id))
173
+ const base = agent?.id || 'agent-command'
174
+ let id = base
175
+ for (let n = 2; taken.has(id); n += 1) id = `${base}-${n}`
176
+ const label = (agent?.label || entry.label || 'Agent command').slice(0, 80)
177
+ return { id, label, acpCommand: entry.acpCommand }
178
+ }
179
+
180
+ // A file anyone else may write could redirect your key or start a command:
181
+ // on POSIX the file and its folder must be yours and not group/world-writable.
182
+ function unsafeOwnership(file) {
183
+ if (process.platform === 'win32' || typeof process.getuid !== 'function') return null
184
+ for (const target of [path.dirname(file), file]) {
185
+ let stat
186
+ try {
187
+ stat = fs.statSync(target)
188
+ } catch {
189
+ continue
190
+ }
191
+ if (stat.uid !== process.getuid()) return `${target} belongs to another user`
192
+ if (stat.mode & 0o022) return `${target} is writable by other users (chmod go-w it)`
193
+ }
194
+ return null
195
+ }
196
+
197
+ let cache = null
198
+
199
+ // The whole file: { file, data, problem }. A missing file is empty settings.
200
+ export function readUserSettings(env = process.env) {
201
+ const file = userSettingsFile(env)
202
+ if (!file) return { file: null, data: { version: 1, projects: {} }, problem: null }
203
+ let stat
204
+ try {
205
+ stat = fs.statSync(file)
206
+ } catch (error) {
207
+ if (error.code === 'ENOENT') return { file, data: { version: 1, projects: {} }, problem: null }
208
+ return { file, data: null, problem: `${file}: ${error.code || error.message}` }
209
+ }
210
+ // The inode too: a rename over the file (another save) within one mtime tick
211
+ // with the same size is still a different file.
212
+ const stamp = `${file}:${stat.ino}:${stat.mtimeMs}:${stat.ctimeMs}:${stat.size}:${stat.mode}:${stat.uid}`
213
+ if (cache?.stamp === stamp) return cache.result
214
+ let result
215
+ const unsafe = unsafeOwnership(file)
216
+ if (unsafe) result = { file, data: null, problem: `the agent settings file is not used: ${unsafe}` }
217
+ else {
218
+ try {
219
+ const data = JSON.parse(fs.readFileSync(file, 'utf8'))
220
+ if (!isObject(data) || (data.projects !== undefined && !isObject(data.projects))) throw new Error('not a settings file')
221
+ result = { file, data: { version: 1, ...data, projects: data.projects || {} }, problem: null }
222
+ } catch (error) {
223
+ result = { file, data: null, problem: `${file} is not valid (${error.message}); fix it or delete it` }
224
+ }
225
+ }
226
+ cache = { stamp, result }
227
+ return result
228
+ }
229
+
230
+ // This project's saved settings: { file, entry, problem }. `entry` is null
231
+ // when nothing is saved or the file has a problem.
232
+ export function userAgentEntry(root, env = process.env) {
233
+ const { file, data, problem } = readUserSettings(env)
234
+ if (problem) return { file, entry: null, problem }
235
+ const raw = data.projects[projectKey(root)]
236
+ if (raw === undefined) return { file, entry: null, problem: null }
237
+ const { entry, problems } = validateUserEntry(raw)
238
+ if (!entry) return { file, entry: null, problem: `${file}: the settings for this project are not valid: ${problems.join('; ')}` }
239
+ return { file, entry, problem: null }
240
+ }
241
+
242
+ const LOCK_WAIT_MS = 3000
243
+ const LOCK_STALE_MS = 15000
244
+ const pause = (ms) => Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms)
245
+
246
+ // An exclusive lock file next to the settings, so two servers (or boards)
247
+ // saving at once do not lose each other's change: each reads the file inside
248
+ // the lock. A lock left by a crashed process is taken over after 15 s.
249
+ export function withSettingsLock(file, work) {
250
+ const lock = `${file}.lock`
251
+ const end = Date.now() + LOCK_WAIT_MS
252
+ let fd = null
253
+ while (fd === null) {
254
+ try {
255
+ fd = fs.openSync(lock, fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_WRONLY | (fs.constants.O_NOFOLLOW || 0), 0o600)
256
+ } catch (error) {
257
+ if (error.code !== 'EEXIST') throw error
258
+ try {
259
+ if (Date.now() - fs.statSync(lock).mtimeMs > LOCK_STALE_MS) fs.rmSync(lock, { force: true })
260
+ } catch {
261
+ // gone meanwhile: try again
262
+ }
263
+ if (Date.now() > end) throw Object.assign(new Error(`${lock} is held by another save; try again`), { code: 'settings_locked' })
264
+ pause(25)
265
+ }
266
+ }
267
+ try {
268
+ fs.writeSync(fd, String(process.pid))
269
+ return work()
270
+ } finally {
271
+ fs.closeSync(fd)
272
+ fs.rmSync(lock, { force: true })
273
+ }
274
+ }
275
+
276
+ // Saves this project's settings (an empty entry removes them). The folder is
277
+ // made private (0700) and the file written 0600, through a temporary file
278
+ // renamed over it, so a reader never sees half a file; the read and the
279
+ // rename happen inside withSettingsLock.
280
+ export function saveUserAgentEntry(root, entry, env = process.env) {
281
+ const file = userSettingsFile(env)
282
+ if (!file)
283
+ throw Object.assign(new Error('There is no home folder to save agent settings in (set XDG_CONFIG_HOME or HOME).'), {
284
+ code: 'no_settings_file',
285
+ })
286
+ fs.mkdirSync(path.dirname(file), { recursive: true, mode: 0o700 })
287
+ const key = projectKey(root)
288
+ return withSettingsLock(file, () => {
289
+ cache = null
290
+ const current = readUserSettings(env)
291
+ if (current.problem) throw Object.assign(new Error(current.problem), { code: 'settings_file_invalid' })
292
+ const data = { ...current.data, version: 1, projects: { ...current.data.projects } }
293
+ const fields = { ...entry }
294
+ delete fields.updatedAt
295
+ if (Object.keys(fields).length) data.projects[key] = { ...fields, updatedAt: new Date().toISOString() }
296
+ else delete data.projects[key]
297
+ const temp = `${file}.${process.pid}.${crypto.randomBytes(4).toString('hex')}.tmp`
298
+ try {
299
+ fs.writeFileSync(temp, `${JSON.stringify(data, null, 2)}\n`, { mode: 0o600, flag: 'wx' })
300
+ fs.renameSync(temp, file)
301
+ } catch (error) {
302
+ fs.rmSync(temp, { force: true })
303
+ throw error
304
+ }
305
+ cache = null
306
+ return data.projects[key] || null
307
+ })
308
+ }
@@ -0,0 +1,375 @@
1
+ // Manual capture sign-in. Always a fresh browser profile, never a login script.
2
+ import fs from 'node:fs'
3
+ import path from 'node:path'
4
+ import { randomBytes } from 'node:crypto'
5
+ import { spawnSync } from 'node:child_process'
6
+ import { createInterface } from 'node:readline'
7
+ import { getBoard, getEnvironment, ID_RE } from '../config.js'
8
+ import { cliCommand } from '../invocation.js'
9
+ import { absoluteProgram } from '../which.js'
10
+ import { SAFE_GIT_FLAGS } from '../agent/starter/worktree.js'
11
+
12
+ export const AUTH_FLAGS = ['board', 'env', 'url', 'timeout', 'overwrite']
13
+ export const AUTH_BOOLEAN_FLAGS = ['overwrite']
14
+ export const AUTH_HELP = ` auth record open a fresh browser for manual capture sign-in
15
+ --board ID board to sign in to (default: the first)
16
+ --env ID environment to sign in to (default: the first)
17
+ --url URL optional sign-in page (never printed)
18
+ --timeout SECONDS time to finish (default 600, maximum 1800)
19
+ --overwrite explicitly replace this board/environment's saved state
20
+ press Enter to save; Ctrl-C, browser close or timeout discards
21
+ saves a private .shapewall-auth/*.auth.json; config stays unchanged`
22
+ const DIRECTORY = '.shapewall-auth'
23
+ const STATE_BYTES_MAX = 10 * 1024 * 1024
24
+ const fail = (code, message) => Object.assign(new Error(message), { code })
25
+ const sameFile = (a, b) => a.dev === b.dev && a.ino === b.ino && a.size === b.size && a.mtimeMs === b.mtimeMs && a.ctimeMs === b.ctimeMs
26
+ const privateOwned = (stat) => typeof process.getuid !== 'function' || (stat.uid === process.getuid() && !(stat.mode & 0o077))
27
+
28
+ function lstat(file) {
29
+ try {
30
+ return fs.lstatSync(file)
31
+ } catch (error) {
32
+ if (error.code === 'ENOENT') return null
33
+ throw error
34
+ }
35
+ }
36
+
37
+ function gitCheck(root) {
38
+ let current = root
39
+ let repository = false
40
+ while (true) {
41
+ if (lstat(path.join(current, '.git'))) {
42
+ repository = true
43
+ break
44
+ }
45
+ const parent = path.dirname(current)
46
+ if (parent === current) break
47
+ current = parent
48
+ }
49
+ if (!repository) return
50
+ const env = Object.fromEntries(Object.entries(process.env).filter(([key]) => !key.startsWith('GIT_')))
51
+ const git = absoluteProgram('git', env)
52
+ if (!git) throw fail('auth_git_check', 'Git must be available in an absolute PATH directory to verify private sign-in storage.')
53
+ const checked = spawnSync(git, [...SAFE_GIT_FLAGS, '-C', root, 'ls-files', '-z', '--', DIRECTORY], {
54
+ env,
55
+ encoding: 'utf8',
56
+ timeout: 5000,
57
+ maxBuffer: 1024 * 1024,
58
+ })
59
+ if (checked.status !== 0) throw fail('auth_git_check', 'Could not verify the private recording directory with Git. Nothing was saved.')
60
+ if (
61
+ checked.stdout
62
+ .split('\0')
63
+ .filter(Boolean)
64
+ .some((file) => file !== `${DIRECTORY}/.gitignore`)
65
+ )
66
+ throw fail('auth_tracked', 'The recording directory contains Git-tracked files. Remove those files from Git before recording sign-in.')
67
+ }
68
+
69
+ function protectedAncestors(root) {
70
+ for (let current = root; ; current = path.dirname(current)) {
71
+ const stat = lstat(current)
72
+ if (
73
+ !stat?.isDirectory() ||
74
+ stat.isSymbolicLink() ||
75
+ (typeof process.getuid === 'function' && (stat.mode & 0o022 || ![0, process.getuid()].includes(stat.uid)))
76
+ )
77
+ throw fail(
78
+ 'auth_private_directory',
79
+ 'The recording project and its parent directories must not be writable by other users or replaced by symlinks.',
80
+ )
81
+ if (path.dirname(current) === current) break
82
+ }
83
+ }
84
+
85
+ function resolvedLocation(file) {
86
+ const missing = []
87
+ let existing = path.resolve(file)
88
+ while (!lstat(existing)) {
89
+ missing.unshift(path.basename(existing))
90
+ existing = path.dirname(existing)
91
+ }
92
+ return path.join(fs.realpathSync(existing), ...missing)
93
+ }
94
+
95
+ const contains = (parent, child) => {
96
+ const relative = path.relative(parent, child)
97
+ return !relative || (!relative.startsWith(`..${path.sep}`) && relative !== '..' && !path.isAbsolute(relative))
98
+ }
99
+
100
+ // A fixed destination, outside capture/export data. Repo config cannot redirect writes.
101
+ function destination(config, board, environment, overwrite) {
102
+ if (!ID_RE.test(board.id) || !ID_RE.test(environment.id)) throw fail('auth_config', 'Choose a configured board and environment.')
103
+ const root = fs.realpathSync(config.dir)
104
+ protectedAncestors(root)
105
+ const rootStat = fs.statSync(root)
106
+ if (typeof process.getuid === 'function' && (rootStat.uid !== process.getuid() || rootStat.mode & 0o022))
107
+ throw fail('auth_private_directory', 'Record sign-in from a project directory owned by you and not writable by other users.')
108
+ gitCheck(root)
109
+ const directory = path.join(root, DIRECTORY)
110
+ if (
111
+ config.outputDir &&
112
+ (contains(resolvedLocation(config.outputDir), directory) || contains(directory, resolvedLocation(config.outputDir)))
113
+ )
114
+ throw fail('auth_output_overlap', 'The private recording directory must stay outside the configured capture output directory.')
115
+ if (!lstat(directory)) fs.mkdirSync(directory, { mode: 0o700 })
116
+ const dirStat = lstat(directory)
117
+ if (!dirStat?.isDirectory() || dirStat.isSymbolicLink() || !privateOwned(dirStat))
118
+ throw fail('auth_private_directory', 'The recording directory must be a private directory owned by you, with mode 0700 and no symlink.')
119
+ const ignore = path.join(directory, '.gitignore')
120
+ if (!lstat(ignore)) fs.writeFileSync(ignore, '*\n', { mode: 0o600, flag: 'wx' })
121
+ const ignoreStat = lstat(ignore)
122
+ if (
123
+ !ignoreStat?.isFile() ||
124
+ ignoreStat.isSymbolicLink() ||
125
+ ignoreStat.nlink !== 1 ||
126
+ !privateOwned(ignoreStat) ||
127
+ fs.readFileSync(ignore, 'utf8') !== '*\n'
128
+ )
129
+ throw fail('auth_git_ignore', 'The private recording directory must contain an unchanged ignore-all .gitignore file.')
130
+ const name = `${board.id}${environment.id === 'default' ? '' : `.${environment.id}`}.auth.json`
131
+ const file = path.join(directory, name)
132
+ const before = lstat(file)
133
+ if (before && (!before.isFile() || before.isSymbolicLink() || before.nlink !== 1 || !privateOwned(before)))
134
+ throw fail('auth_unsafe_file', 'The saved sign-in file must be a private regular file owned by you, without symlinks or hard links.')
135
+ if (before && !overwrite)
136
+ throw fail('auth_exists', 'Saved sign-in already exists for this board/environment. Use --overwrite to replace it explicitly.')
137
+ const lock = path.join(directory, '.record.lock')
138
+ let lockFd
139
+ try {
140
+ lockFd = fs.openSync(lock, fs.constants.O_CREAT | fs.constants.O_EXCL | fs.constants.O_WRONLY | (fs.constants.O_NOFOLLOW || 0), 0o600)
141
+ } catch (error) {
142
+ if (error.code === 'EEXIST')
143
+ throw fail(
144
+ 'auth_locked',
145
+ 'Another sign-in recording may be open. Close it first; remove .shapewall-auth/.record.lock only after confirming it is stale.',
146
+ )
147
+ throw error
148
+ }
149
+ const lockStat = fs.fstatSync(lockFd)
150
+ return {
151
+ file,
152
+ relativeFile: `./${DIRECTORY}/${name}`,
153
+ save(state) {
154
+ protectedAncestors(root)
155
+ const directoryNow = lstat(directory)
156
+ const projectNow = lstat(root)
157
+ if (
158
+ !directoryNow?.isDirectory() ||
159
+ directoryNow.isSymbolicLink() ||
160
+ directoryNow.dev !== dirStat.dev ||
161
+ directoryNow.ino !== dirStat.ino ||
162
+ !privateOwned(directoryNow) ||
163
+ !projectNow?.isDirectory() ||
164
+ projectNow.isSymbolicLink() ||
165
+ projectNow.dev !== rootStat.dev ||
166
+ projectNow.ino !== rootStat.ino ||
167
+ (typeof process.getuid === 'function' && (projectNow.uid !== process.getuid() || projectNow.mode & 0o022))
168
+ )
169
+ throw fail('auth_destination_changed', 'The private recording directory changed. Nothing was saved.')
170
+ const ignored = lstat(ignore)
171
+ if (!ignored || !sameFile(ignored, ignoreStat))
172
+ throw fail('auth_destination_changed', 'The private ignore file changed. Nothing was saved.')
173
+ gitCheck(root)
174
+ const now = lstat(file)
175
+ if (before ? !now || !sameFile(now, before) : now)
176
+ throw fail('auth_destination_changed', 'The saved sign-in file changed during recording. Nothing was saved.')
177
+ const json = `${JSON.stringify(state)}\n`
178
+ if (Buffer.byteLength(json) > STATE_BYTES_MAX) throw fail('auth_state_large', 'Sign-in storage is too large to save (maximum 10 MB).')
179
+ const temporary = path.join(directory, `.state-${randomBytes(12).toString('hex')}.tmp`)
180
+ let fd
181
+ try {
182
+ fd = fs.openSync(
183
+ temporary,
184
+ fs.constants.O_WRONLY | fs.constants.O_CREAT | fs.constants.O_EXCL | (fs.constants.O_NOFOLLOW || 0),
185
+ 0o600,
186
+ )
187
+ fs.writeFileSync(fd, json)
188
+ fs.fsyncSync(fd)
189
+ fs.closeSync(fd)
190
+ fd = null
191
+ if (before) fs.renameSync(temporary, file)
192
+ else {
193
+ fs.linkSync(temporary, file)
194
+ fs.unlinkSync(temporary)
195
+ }
196
+ } finally {
197
+ if (fd !== undefined && fd !== null) fs.closeSync(fd)
198
+ if (lstat(temporary)) fs.unlinkSync(temporary)
199
+ }
200
+ },
201
+ close() {
202
+ fs.closeSync(lockFd)
203
+ const now = lstat(lock)
204
+ if (now?.dev === lockStat.dev && now.ino === lockStat.ino) fs.unlinkSync(lock)
205
+ },
206
+ }
207
+ }
208
+
209
+ function terminalFinish(input, signal, out) {
210
+ return new Promise((resolve, reject) => {
211
+ if (signal.aborted) {
212
+ reject(signal.reason)
213
+ return
214
+ }
215
+ const reader = createInterface({ input, terminal: false })
216
+ let settled = false
217
+ const settle = (error) => {
218
+ if (settled) return
219
+ settled = true
220
+ signal.removeEventListener('abort', stop)
221
+ reader.close()
222
+ if (error) reject(error)
223
+ else resolve()
224
+ }
225
+ const stop = () => settle(signal.reason)
226
+ signal.addEventListener('abort', stop, { once: true })
227
+ reader.on('line', (line) => {
228
+ if (!line.trim()) settle()
229
+ else if (/^(cancel|q)$/i.test(line.trim())) settle(fail('auth_cancelled', 'Sign-in recording cancelled. Nothing was saved.'))
230
+ else out('Press Enter to save, or type cancel to discard. Your input is not used as a password.')
231
+ })
232
+ reader.on('close', () => settle(fail('auth_cancelled', 'Sign-in recording cancelled. Nothing was saved.')))
233
+ reader.on('error', () => settle(fail('auth_terminal', 'The input terminal failed. Nothing was saved.')))
234
+ })
235
+ }
236
+
237
+ export async function recordCaptureAuth({
238
+ config,
239
+ boardId,
240
+ envId,
241
+ url,
242
+ timeoutMs = 600000,
243
+ overwrite = false,
244
+ input = process.stdin,
245
+ out = () => {},
246
+ signal,
247
+ finish,
248
+ launch,
249
+ headless = false,
250
+ env = process.env,
251
+ } = {}) {
252
+ if (!finish && !input?.isTTY)
253
+ throw fail('auth_terminal', 'Run auth record in an interactive terminal on the desktop where you will sign in.')
254
+ if (!Number.isInteger(timeoutMs) || timeoutMs < 1 || timeoutMs > 1800000)
255
+ throw fail('auth_timeout', 'Recording timeout must be between 1 and 1800000 milliseconds.')
256
+ const board = getBoard(config, boardId)
257
+ const environment = getEnvironment(board, envId)
258
+ let target
259
+ try {
260
+ target = new URL(url || environment.baseUrl || board.baseUrl)
261
+ if (!['http:', 'https:'].includes(target.protocol) || target.username || target.password) throw new Error()
262
+ } catch {
263
+ throw fail('auth_url', 'Choose an HTTP(S) sign-in page without credentials in its URL.')
264
+ }
265
+ let saved
266
+ try {
267
+ saved = destination(config, board, environment, overwrite)
268
+ } catch (error) {
269
+ if (typeof error.code === 'string' && error.code.startsWith('auth_')) throw error
270
+ throw fail('auth_destination', 'Could not prepare the private recording directory. Check project permissions. Nothing was saved.')
271
+ }
272
+ const controller = new AbortController()
273
+ const cancel = () => controller.abort(fail('auth_cancelled', 'Sign-in recording cancelled. Nothing was saved.'))
274
+ if (signal?.aborted) cancel()
275
+ else signal?.addEventListener('abort', cancel, { once: true })
276
+ const timer = setTimeout(() => controller.abort(fail('auth_timeout', 'Sign-in recording timed out. Nothing was saved.')), timeoutMs)
277
+ let browser
278
+ let context
279
+ let disconnected
280
+ try {
281
+ const chromium = launch ? null : (await import('playwright')).chromium
282
+ const engine = launch || chromium.launch.bind(chromium)
283
+ const options = { headless, timeout: Math.min(timeoutMs, 30000), args: ['--disable-dev-shm-usage'] }
284
+ const executablePath = env.SHAPEWALL_BROWSER_PATH || config.browser?.executablePath
285
+ const channel = env.SHAPEWALL_BROWSER_CHANNEL || config.browser?.channel
286
+ if (executablePath) options.executablePath = executablePath
287
+ else if (channel) options.channel = channel
288
+ const aborted = new Promise((resolve, reject) => {
289
+ if (controller.signal.aborted) reject(controller.signal.reason)
290
+ else controller.signal.addEventListener('abort', () => reject(controller.signal.reason), { once: true })
291
+ })
292
+ const work = async () => {
293
+ if (controller.signal.aborted) throw controller.signal.reason
294
+ browser = await engine(options)
295
+ if (controller.signal.aborted) {
296
+ await browser.close()
297
+ throw controller.signal.reason
298
+ }
299
+ disconnected = () => controller.abort(fail('auth_cancelled', 'The sign-in browser closed. Nothing was saved.'))
300
+ browser.once('disconnected', disconnected)
301
+ context = await browser.newContext()
302
+ const page = await context.newPage()
303
+ await page.goto(target.href, { waitUntil: 'domcontentloaded', timeout: Math.min(timeoutMs, config.timeouts?.page || 45000) })
304
+ out('Sign in manually in the fresh browser. Return here and press Enter to save, or type cancel to discard.')
305
+ await (finish ? finish({ page, context, signal: controller.signal }) : terminalFinish(input, controller.signal, out))
306
+ if (controller.signal.aborted) throw controller.signal.reason
307
+ const state = await context.storageState({ indexedDB: true })
308
+ if (controller.signal.aborted) throw controller.signal.reason
309
+ saved.save(state)
310
+ return {
311
+ file: saved.file,
312
+ relativeFile: saved.relativeFile,
313
+ boardId: board.id,
314
+ envId: environment.id,
315
+ loginScriptOverrides: Boolean(config.auth?.loginScript),
316
+ }
317
+ }
318
+ return await Promise.race([work(), aborted])
319
+ } catch (error) {
320
+ if (controller.signal.aborted) throw controller.signal.reason
321
+ if (typeof error.code === 'string' && error.code.startsWith('auth_')) throw error
322
+ // Browser errors often contain full URLs, queries, headers or request bodies.
323
+ throw fail(
324
+ 'auth_record_failed',
325
+ 'Could not complete sign-in recording. Check that the desktop browser and site are available. Nothing was saved.',
326
+ )
327
+ } finally {
328
+ clearTimeout(timer)
329
+ signal?.removeEventListener('abort', cancel)
330
+ if (disconnected) browser?.removeListener('disconnected', disconnected)
331
+ await context?.close().catch(() => {})
332
+ await browser?.close().catch(() => {})
333
+ try {
334
+ saved.close()
335
+ } catch {
336
+ out('Recording ended, but its private lock could not be removed. Check .shapewall-auth/.record.lock before recording again.')
337
+ }
338
+ }
339
+ }
340
+
341
+ const quote = (value) => `'${String(value).replaceAll("'", "'\\''")}'`
342
+ export async function authCommand(config, positional, flags, out, options = {}) {
343
+ if ((positional[0] || 'record') !== 'record' || positional.length > 1)
344
+ throw fail('auth_command', 'Use auth record to save a manual capture sign-in.')
345
+ const timeout = flags.timeout === undefined ? 600 : Number(flags.timeout)
346
+ if (!Number.isInteger(timeout) || timeout < 1 || timeout > 1800)
347
+ throw fail('auth_timeout', '--timeout is a whole number of seconds between 1 and 1800.')
348
+ const controller = new AbortController()
349
+ const cancel = () => controller.abort()
350
+ process.once('SIGINT', cancel)
351
+ process.once('SIGTERM', cancel)
352
+ try {
353
+ const result = await recordCaptureAuth({
354
+ ...options,
355
+ config,
356
+ boardId: flags.board,
357
+ envId: flags.env,
358
+ url: flags.url,
359
+ timeoutMs: timeout * 1000,
360
+ overwrite: Boolean(flags.overwrite),
361
+ out,
362
+ signal: options.signal ? AbortSignal.any([options.signal, controller.signal]) : controller.signal,
363
+ })
364
+ out(`Saved private browser state: ${result.relativeFile}`)
365
+ out('Add this to your config (the config was not changed):')
366
+ out(JSON.stringify({ auth: { storageState: result.relativeFile } }, null, 2))
367
+ if (result.loginScriptOverrides) out('Your auth.loginScript still takes priority. Remove it to use the recorded storage state.')
368
+ const configFlag = config.file ? ` --config ${quote(config.file)}` : ''
369
+ out(`Next capture: ${cliCommand(`capture${configFlag} --board ${result.boardId} --env ${result.envId}`)}`)
370
+ return 0
371
+ } finally {
372
+ process.removeListener('SIGINT', cancel)
373
+ process.removeListener('SIGTERM', cancel)
374
+ }
375
+ }