@mmerterden/multi-agent-pipeline 23.7.0 → 24.0.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 (142) hide show
  1. package/CHANGELOG.md +38 -1
  2. package/README.md +57 -24
  3. package/README.tr.md +41 -8
  4. package/SECURITY.md +3 -3
  5. package/docs/architecture.md +41 -4
  6. package/docs/ecosystem.md +15 -13
  7. package/docs/facts.json +5 -4
  8. package/docs/features.md +59 -15
  9. package/install/_codex-agents.mjs +13 -8
  10. package/install/_common.mjs +24 -0
  11. package/install/_dev-only-files.mjs +4 -0
  12. package/install/_mcp-register.mjs +6 -2
  13. package/install/_rewrite-tree.mjs +197 -0
  14. package/install/codex.mjs +96 -180
  15. package/install/copilot.mjs +24 -54
  16. package/install/index.mjs +29 -11
  17. package/install/templates/codex-instructions.md +21 -5
  18. package/install/templates/copilot-instructions.md +21 -14
  19. package/manifest.json +2082 -0
  20. package/package.json +6 -2
  21. package/pipeline/commands/multi-agent/SKILL.md +5 -4
  22. package/pipeline/commands/multi-agent/analysis/SKILL.md +4 -0
  23. package/pipeline/commands/multi-agent/autopilot-on/SKILL.md +31 -3
  24. package/pipeline/commands/multi-agent/autopilot-status/SKILL.md +5 -1
  25. package/pipeline/commands/multi-agent/channels/SKILL.md +16 -8
  26. package/pipeline/commands/multi-agent/log/SKILL.md +2 -0
  27. package/pipeline/commands/multi-agent/stack/SKILL.md +1 -1
  28. package/pipeline/contract/manifest.json +1 -1
  29. package/pipeline/contract/types/index.d.ts +1 -0
  30. package/pipeline/lib/_jira-auth.sh +50 -78
  31. package/pipeline/lib/_service-account.sh +191 -0
  32. package/pipeline/lib/credential-inventory.sh +49 -37
  33. package/pipeline/lib/credential-store.sh +48 -3
  34. package/pipeline/lib/fetch-confluence.sh +76 -92
  35. package/pipeline/lib/fetch-crashlytics.sh +30 -59
  36. package/pipeline/lib/fetch-figma-annotations.sh +9 -9
  37. package/pipeline/lib/fetch-fortify.sh +77 -81
  38. package/pipeline/lib/fetch-graylog.sh +38 -77
  39. package/pipeline/lib/figma-mcp-refresh.sh +23 -4
  40. package/pipeline/lib/figma-screenshot.sh +7 -8
  41. package/pipeline/lib/figma-token.sh +39 -46
  42. package/pipeline/lib/host.mjs +138 -0
  43. package/pipeline/lib/host.sh +48 -0
  44. package/pipeline/lib/issue-fetcher.sh +25 -41
  45. package/pipeline/lib/jira-publish.sh +23 -21
  46. package/pipeline/lib/local-model.mjs +93 -0
  47. package/pipeline/lib/md2confluence-v3.py +37 -30
  48. package/pipeline/lib/model-dispatch.sh +41 -4
  49. package/pipeline/lib/model-resolve.mjs +58 -0
  50. package/pipeline/lib/post-pr-review.sh +38 -53
  51. package/pipeline/lib/reviewer-families.mjs +70 -0
  52. package/pipeline/lib/service-account.mjs +2131 -0
  53. package/pipeline/lib/service-account.sh +35 -0
  54. package/pipeline/lib/usage-token.mjs +64 -24
  55. package/pipeline/lib/usage-vocab.mjs +1 -1
  56. package/pipeline/lib/user-facing.mjs +11 -3
  57. package/pipeline/lib/vercel-deploy.sh +17 -26
  58. package/pipeline/multi-agent-refs/_entry-picker.md +62 -0
  59. package/pipeline/multi-agent-refs/analysis/intake.md +2 -0
  60. package/pipeline/multi-agent-refs/analysis/reusable-refs.md +1 -0
  61. package/pipeline/multi-agent-refs/analysis/unattended.md +135 -0
  62. package/pipeline/multi-agent-refs/autopilot-on/details.md +16 -0
  63. package/pipeline/multi-agent-refs/channels/generator.md +10 -2
  64. package/pipeline/multi-agent-refs/channels/menu.md +3 -1
  65. package/pipeline/multi-agent-refs/channels/preview.md +3 -1
  66. package/pipeline/multi-agent-refs/channels/reference.md +16 -2
  67. package/pipeline/multi-agent-refs/channels/report-file.md +188 -0
  68. package/pipeline/multi-agent-refs/cross-cli-contract.md +35 -27
  69. package/pipeline/multi-agent-refs/features/doctor.md +37 -11
  70. package/pipeline/multi-agent-refs/features/free-models.md +3 -3
  71. package/pipeline/multi-agent-refs/features/local-model.md +87 -0
  72. package/pipeline/multi-agent-refs/features/model-fallback.md +25 -10
  73. package/pipeline/multi-agent-refs/features/product-context.md +6 -5
  74. package/pipeline/multi-agent-refs/features/service-accounts.md +233 -0
  75. package/pipeline/multi-agent-refs/features/unattended-security.md +10 -1
  76. package/pipeline/multi-agent-refs/help/en.md +28 -1
  77. package/pipeline/multi-agent-refs/help/tr.md +28 -1
  78. package/pipeline/multi-agent-refs/orchestrator/copilot-pipeline.md +2 -1
  79. package/pipeline/multi-agent-refs/orchestrator/dispatcher.md +2 -1
  80. package/pipeline/multi-agent-refs/phases/modes.md +20 -1
  81. package/pipeline/multi-agent-refs/phases/phase-5-report.md +12 -10
  82. package/pipeline/multi-agent-refs/phases.md +4 -3
  83. package/pipeline/multi-agent-refs/review/panel.md +30 -18
  84. package/pipeline/multi-agent-refs/setup/discovery.md +17 -5
  85. package/pipeline/multi-agent-refs/setup/token-save-flow.md +21 -2
  86. package/pipeline/multi-agent-refs/sync/overview.md +11 -5
  87. package/pipeline/multi-agent-refs/tracker-contract.md +28 -10
  88. package/pipeline/office/index.html +3 -3
  89. package/pipeline/schemas/autopilot-config.schema.json +29 -4
  90. package/pipeline/schemas/hosts.json +512 -0
  91. package/pipeline/schemas/hosts.schema.json +310 -0
  92. package/pipeline/schemas/launch.json +22 -2
  93. package/pipeline/schemas/launch.schema.json +2 -1
  94. package/pipeline/schemas/phases.json +19 -1
  95. package/pipeline/schemas/phases.schema.json +8 -0
  96. package/pipeline/schemas/prefs.schema.json +331 -4
  97. package/pipeline/scripts/.doctor-mut.47076.mjs +2253 -0
  98. package/pipeline/scripts/_autopilot-config.mjs +67 -4
  99. package/pipeline/scripts/_autopilot-item.mjs +67 -0
  100. package/pipeline/scripts/_autopilot-outcomes.mjs +6 -0
  101. package/pipeline/scripts/_cost.mjs +75 -3
  102. package/pipeline/scripts/analysis-sources.mjs +22 -5
  103. package/pipeline/scripts/analysis-unattended.mjs +360 -0
  104. package/pipeline/scripts/anonymize-findings.mjs +3 -7
  105. package/pipeline/scripts/autopilot-arming.mjs +19 -10
  106. package/pipeline/scripts/autopilot-intake.mjs +124 -27
  107. package/pipeline/scripts/autopilot-menubar.swift +7 -0
  108. package/pipeline/scripts/autopilot-runner.mjs +77 -48
  109. package/pipeline/scripts/autopilot-status.sh +32 -9
  110. package/pipeline/scripts/bulk-read.sh +37 -5
  111. package/pipeline/scripts/confluence-readback.mjs +15 -7
  112. package/pipeline/scripts/cost-table.json +65 -25
  113. package/pipeline/scripts/doctor.mjs +119 -32
  114. package/pipeline/scripts/entry-mode.mjs +101 -0
  115. package/pipeline/scripts/estimate.mjs +30 -16
  116. package/pipeline/scripts/feedback-send.mjs +11 -8
  117. package/pipeline/scripts/gen-facts.mjs +7 -9
  118. package/pipeline/scripts/jira-attach.sh +23 -28
  119. package/pipeline/scripts/jira-search.sh +5 -21
  120. package/pipeline/scripts/launch-request.mjs +15 -9
  121. package/pipeline/scripts/migrate-prefs.mjs +56 -0
  122. package/pipeline/scripts/phase-tracker.sh +146 -38
  123. package/pipeline/scripts/priority-review.mjs +14 -7
  124. package/pipeline/scripts/product-context.mjs +26 -7
  125. package/pipeline/scripts/prune-logs.sh +4 -2
  126. package/pipeline/scripts/report-file.mjs +285 -0
  127. package/pipeline/scripts/rework-escalation.mjs +19 -4
  128. package/pipeline/scripts/service-read.mjs +19 -17
  129. package/pipeline/scripts/skill-siblings.mjs +17 -1
  130. package/pipeline/scripts/status-overview.mjs +20 -10
  131. package/pipeline/scripts/uninstall.mjs +145 -57
  132. package/pipeline/scripts/usage-register.mjs +34 -11
  133. package/pipeline/scripts/usage-report.mjs +31 -26
  134. package/pipeline/scripts/validate-triage.mjs +11 -1
  135. package/pipeline/scripts/work-items.mjs +25 -28
  136. package/pipeline/scripts/write-store-config.mjs +37 -11
  137. package/pipeline/skills/.skill-manifest.json +4 -4
  138. package/pipeline/skills/.skills-index.json +1 -1
  139. package/pipeline/skills/shared/core/multi-agent/SKILL.md +11 -3
  140. package/pipeline/skills/shared/core/multi-agent-analysis/SKILL.md +2 -0
  141. package/pipeline/skills/shared/core/multi-agent-channels/SKILL.md +11 -8
  142. package/pipeline/lib/credential-resolve.mjs +0 -75
@@ -0,0 +1,2131 @@
1
+ /**
2
+ * service-account.mjs - which credential may be sent where, decided in one place.
3
+ *
4
+ * Before this module a credential was three unrelated lookups: a host from
5
+ * `global.hosts`, an item name from `global.keychainMapping`, and sometimes an
6
+ * identity from `global.identities[].servicePatMap`. Nothing joined them, so
7
+ * one account's host could be handed another account's token and no code was
8
+ * in a position to notice. A person with two GitHub accounts or two Jira
9
+ * instances had no way to say which token belonged to which.
10
+ *
11
+ * `serviceAccounts[]` is that join: one entry carries the service, where it may
12
+ * be sent, and the store items that hold the secret. This module is the only
13
+ * reader of it, and the only place that decides a destination is allowed.
14
+ *
15
+ * Two rules shape everything below.
16
+ *
17
+ * 1. A secret is never produced without a destination that was checked against
18
+ * the account that holds it. A miss is a refusal, never a fall back to the
19
+ * default account: "I do not know which token this host wants" and "here is
20
+ * the token I had" are different answers, and the second one is how a token
21
+ * reaches a host it was never issued for.
22
+ * 2. While `serviceAccounts[]` is absent the same entries are derived in memory
23
+ * from the flat keys, so a file nobody has migrated resolves identically.
24
+ * A missing array is not a refusal; it is the old shape, read the new way.
25
+ */
26
+
27
+ import { execFile, execFileSync } from "node:child_process";
28
+ import { createHash } from "node:crypto";
29
+ import { existsSync, statSync } from "node:fs";
30
+ import { dirname, join } from "node:path";
31
+ import { fileURLToPath } from "node:url";
32
+ import { lockTimeoutFrom, withFileLockSync, writeJsonAtomicSync } from "./json-file-lock.mjs";
33
+ import { prefsPath, readPrefsFile } from "./prefs-value.mjs";
34
+ import { slugify } from "./slug.mjs";
35
+
36
+ const HERE = dirname(fileURLToPath(import.meta.url));
37
+
38
+ /**
39
+ * One row per service: what kind of thing it is, which secret slots it accepts
40
+ * (the first is what a request with no slot means), and the hostnames a secret
41
+ * for it may reach.
42
+ *
43
+ * `kind` decides how a destination is judged:
44
+ * hosted the person's own instance; the host is on the account
45
+ * vendor the vendor's host by default, another instance when named
46
+ * vendor-fixed always the vendor's hosts, which the account cannot widen
47
+ * local handed to a local tool, never sent by the pipeline itself
48
+ * endpoint the host comes from another preference, read when asked
49
+ */
50
+ export const SERVICES = Object.freeze({
51
+ jira: { kind: "hosted", slots: ["token"] },
52
+ confluence: { kind: "hosted", slots: ["token"] },
53
+ bitbucket: { kind: "hosted", slots: ["token", "username"] },
54
+ fortify: { kind: "hosted", slots: ["token"] },
55
+ graylog: { kind: "hosted", slots: ["token"], environments: true },
56
+ jenkins: { kind: "hosted", slots: ["token"] },
57
+ github: {
58
+ kind: "vendor",
59
+ slots: ["token"],
60
+ hosts: ["github.com", "api.github.com"],
61
+ owners: true,
62
+ },
63
+ npm: { kind: "vendor", slots: ["token"], hosts: ["registry.npmjs.org"] },
64
+ figma: { kind: "vendor-fixed", slots: ["token"], hosts: ["api.figma.com"] },
65
+ firebase: {
66
+ kind: "vendor-fixed",
67
+ slots: ["service_account_json"],
68
+ hosts: [
69
+ "oauth2.googleapis.com",
70
+ "firebase.googleapis.com",
71
+ "firebasecrashlytics.googleapis.com",
72
+ "cloudresourcemanager.googleapis.com",
73
+ ],
74
+ projects: true,
75
+ },
76
+ google_play: {
77
+ kind: "vendor-fixed",
78
+ slots: ["service_account_json"],
79
+ hosts: ["oauth2.googleapis.com", "www.googleapis.com", "playdeveloperreporting.googleapis.com"],
80
+ projects: true,
81
+ },
82
+ appstore_connect: {
83
+ kind: "vendor-fixed",
84
+ slots: ["key_id", "issuer_id", "private_key", "apple_id", "password_item"],
85
+ hosts: ["api.appstoreconnect.apple.com"],
86
+ },
87
+ figma_mcp: { kind: "local", slots: ["token", "refresh_token"] },
88
+ vercel: { kind: "local", slots: ["token"] },
89
+ claude_oauth: { kind: "local", slots: ["token", "fallback_token"] },
90
+ supabase: { kind: "local", slots: ["access_token", "service_role"] },
91
+ usage_ingest: { kind: "endpoint", slots: ["token"] },
92
+ });
93
+
94
+ const SERVICE_IDS = Object.freeze(Object.keys(SERVICES));
95
+ const HOSTNAME_RE = /^[a-z0-9]([a-z0-9.-]{0,251}[a-z0-9])?$/;
96
+ const HANDLE_RE = /^[a-z0-9][a-z0-9-]{0,62}$/;
97
+
98
+ /** Loopback, by the three names it answers to: a request here cannot leave the machine. */
99
+ const LOOPBACK = Object.freeze(["127.0.0.1", "::1", "localhost"]);
100
+
101
+ /**
102
+ * The environment variables that stand in for a stored secret, per slot.
103
+ *
104
+ * A credential in the environment is how a CI job, a container, and a person
105
+ * trying the pipeline before running setup all supply one. It is not a worse
106
+ * secret, but it is a differently bound one: nobody said which host it belongs
107
+ * to, so it goes only where a configured account already goes, where its own
108
+ * host variable says, or to loopback. `host` is not a slot; it names the
109
+ * variables that say where this credential's instance lives.
110
+ */
111
+ const ENV_SLOTS = Object.freeze({
112
+ jira: { token: ["JIRA_TOKEN", "MA_JIRA_TOKEN"], host: ["JIRA_HOST", "MA_JIRA_HOST"] },
113
+ confluence: {
114
+ token: ["CONFLUENCE_TOKEN", "MA_CONFLUENCE_TOKEN"],
115
+ host: ["CONFLUENCE_HOST", "MA_CONFLUENCE_HOST"],
116
+ },
117
+ bitbucket: {
118
+ token: ["BITBUCKET_TOKEN", "MA_BITBUCKET_TOKEN"],
119
+ username: ["BITBUCKET_USER", "MA_BITBUCKET_USER"],
120
+ host: ["BITBUCKET_HOST", "MA_BITBUCKET_HOST"],
121
+ },
122
+ graylog: {
123
+ token: ["GRAYLOG_TOKEN", "MA_GRAYLOG_TOKEN"],
124
+ host: ["GRAYLOG_HOST", "MA_GRAYLOG_HOST"],
125
+ },
126
+ fortify: {
127
+ token: ["FORTIFY_TOKEN", "MA_FORTIFY_TOKEN"],
128
+ host: ["FORTIFY_HOST", "MA_FORTIFY_HOST"],
129
+ },
130
+ jenkins: {
131
+ token: ["JENKINS_TOKEN", "MA_JENKINS_TOKEN"],
132
+ host: ["JENKINS_HOST", "MA_JENKINS_HOST"],
133
+ },
134
+ github: { token: ["GITHUB_TOKEN", "GH_TOKEN", "MA_GITHUB_TOKEN"] },
135
+ npm: { token: ["NPM_TOKEN", "MA_NPM_TOKEN"] },
136
+ figma: { token: ["FIGMA_PAT", "FIGMA_TOKEN", "MA_FIGMA_TOKEN"] },
137
+ usage_ingest: { token: ["MULTI_AGENT_USAGE_TOKEN"] },
138
+ });
139
+
140
+ /** Which flat `keychainMapping` key fills which slot of which service. */
141
+ const LEGACY_SLOTS = Object.freeze({
142
+ jira: ["jira", "token"],
143
+ confluence: ["confluence", "token"],
144
+ fortify: ["fortify", "token"],
145
+ jenkins: ["jenkins", "token"],
146
+ github: ["github", "token"],
147
+ figma: ["figma", "token"],
148
+ figma_mcp: ["figma_mcp", "token"],
149
+ npm: ["npm", "token"],
150
+ vercel: ["vercel", "token"],
151
+ usage_ingest: ["usage_ingest", "token"],
152
+ firebase: ["firebase", "service_account_json"],
153
+ google_play: ["google_play", "service_account_json"],
154
+ bitbucket_token: ["bitbucket", "token"],
155
+ bitbucket_user: ["bitbucket", "username"],
156
+ graylog: ["graylog", "token"],
157
+ claude_oauth_token: ["claude_oauth", "token"],
158
+ claude_oauth_token_fallback: ["claude_oauth", "fallback_token"],
159
+ supabase_access: ["supabase", "access_token"],
160
+ supabase_service_role: ["supabase", "service_role"],
161
+ appstore_connect_key_id: ["appstore_connect", "key_id"],
162
+ appstore_connect_issuer_id: ["appstore_connect", "issuer_id"],
163
+ appstore_connect_private_key: ["appstore_connect", "private_key"],
164
+ appstore_connect_apple_id: ["appstore_connect", "apple_id"],
165
+ appstore_connect_password_item: ["appstore_connect", "password_item"],
166
+ });
167
+
168
+ /** Which `global.hosts` key names the host of which service. */
169
+ const LEGACY_HOSTS = Object.freeze({
170
+ jira: "jira",
171
+ confluence: "confluence",
172
+ bitbucket: "bitbucket",
173
+ fortify: "fortify",
174
+ graylog: "graylog",
175
+ jenkins: "jenkins",
176
+ });
177
+
178
+ /**
179
+ * How a per-account entry names a service's host, and how a store item names
180
+ * the account it belongs to.
181
+ *
182
+ * `global.accounts[]` keys a host by a short id; a store item carries that id
183
+ * as the first segment of its own name, ahead of the provider segment. The
184
+ * file pairs neither to the other, so one entry here says how both are read.
185
+ */
186
+ const ACCOUNT_HOSTS = Object.freeze({
187
+ jira: { field: "jiraHost", segment: "Jira" },
188
+ bitbucket: { field: "bitbucketHost", segment: "Bitbucket" },
189
+ confluence: { field: "confluenceHost", segment: "Confluence" },
190
+ });
191
+
192
+ /**
193
+ * Whether a string carries a character that changes meaning between readers.
194
+ *
195
+ * C0, DEL and backslash. The URL parser silently removes tab, CR and LF and
196
+ * rewrites a backslash as a slash, so a string carrying any of them can name
197
+ * one host to a check and another to whatever reads the string afterwards.
198
+ * Written as a character scan rather than a pattern because a literal control
199
+ * character inside a regular expression is itself hard to read and to review.
200
+ *
201
+ * @param {string} text
202
+ * @param {boolean} [backslash] - count a backslash too
203
+ */
204
+ function hasUnsafeChar(text, backslash = false) {
205
+ for (const ch of String(text)) {
206
+ const code = ch.codePointAt(0);
207
+ if (code < 0x20 || code === 0x7f) return true;
208
+ if (backslash && ch === "\\") return true;
209
+ }
210
+ return false;
211
+ }
212
+
213
+ /**
214
+ * A hostname, or null when the input is not one.
215
+ *
216
+ * Accepts a bare name or a URL, lowercases it and drops a single trailing dot.
217
+ * A URL must be https and carry no userinfo: `https://a.example@b.example/`
218
+ * names `b.example` to a browser and `a.example` to a careless reader, and a
219
+ * token handed out on that reading goes to the wrong place.
220
+ *
221
+ * @param {string} input
222
+ * @returns {string|null}
223
+ */
224
+ export function normalizeHost(input) {
225
+ const raw = String(input ?? "").trim();
226
+ if (!raw) return null;
227
+ // Refused before anything parses it. `https://good.example/x\nurl =
228
+ // https://evil.example/` parses as good.example and is two directives in a
229
+ // curl config. No legitimate URL or hostname carries these, so the answer is
230
+ // no rather than an escape.
231
+ if (hasUnsafeChar(raw, true)) return null;
232
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(raw)) {
233
+ let url;
234
+ try {
235
+ url = new URL(raw);
236
+ } catch {
237
+ return null;
238
+ }
239
+ if (url.protocol !== "https:") return null;
240
+ if (url.username || url.password) return null;
241
+ return normalizeHost(url.hostname);
242
+ }
243
+ if (raw.includes("/") || raw.includes("@") || raw.includes(":")) return null;
244
+ const host = raw.toLowerCase().replace(/\.$/, "");
245
+ return HOSTNAME_RE.test(host) ? host : null;
246
+ }
247
+
248
+ /**
249
+ * The hostname inside a value a person configured, which is not the same job as
250
+ * checking a destination.
251
+ *
252
+ * `global.hosts.jira` is written by hand and by setup, and both accept the forms
253
+ * a person copies out of a browser: `jira.corp:8443`, `corp.example/jira`,
254
+ * `https://jira.corp:8443/jira`. `normalizeHost` refuses all but the last,
255
+ * because for a destination those characters are how one string names two hosts.
256
+ * For a value out of the person's own preferences there is no such ambiguity -
257
+ * refusing it would turn a working configuration into an account with no host,
258
+ * and every call on it into a refusal.
259
+ *
260
+ * The scope it produces is still a bare hostname: a port and a path say where on
261
+ * a host to knock, not which host it is.
262
+ *
263
+ * @param {string} input
264
+ * @returns {string|null}
265
+ */
266
+ function normalizeLoopback(hostname) {
267
+ const host = String(hostname ?? "")
268
+ .toLowerCase()
269
+ .replace(/^\[|\]$/g, "")
270
+ .replace(/\.$/, "");
271
+ return LOOPBACK.includes(host) ? host : null;
272
+ }
273
+
274
+ /**
275
+ * The destination a request names, as a host and the transport it is reached over.
276
+ *
277
+ * https to anywhere, http to loopback only. A local model server, a mock and a
278
+ * dev instance all live at 127.0.0.1 with no certificate, and refusing them
279
+ * outright is what pushes people to disable the check for everything. Loopback
280
+ * is the one destination with no network to carry the request, so there is
281
+ * nothing on the wire to protect; everywhere else http is refused, and the
282
+ * caller gets a reason rather than a request that quietly went out in the
283
+ * clear. That line - loopback or nothing - is the one the fetchers already
284
+ * drew for themselves, in each of their own ways.
285
+ *
286
+ * @param {string} input - a URL or a bare hostname
287
+ * @returns {{host: string, scheme: "https"|"http"}|null}
288
+ */
289
+ function normalizeTarget(input) {
290
+ const raw = String(input ?? "").trim();
291
+ if (!raw) return null;
292
+ if (hasUnsafeChar(raw, true)) return null;
293
+ const scheme = /^(https?):\/\//i.exec(raw)?.[1]?.toLowerCase();
294
+ if (scheme) {
295
+ let url;
296
+ try {
297
+ url = new URL(raw);
298
+ } catch {
299
+ return null;
300
+ }
301
+ if (url.username || url.password) return null;
302
+ const loop = normalizeLoopback(url.hostname);
303
+ if (loop) return { host: loop, scheme };
304
+ if (scheme !== "https") return null;
305
+ const host = normalizeHost(url.hostname);
306
+ return host ? { host, scheme } : null;
307
+ }
308
+ const loop = normalizeLoopback(raw);
309
+ if (loop) return { host: loop, scheme: "https" };
310
+ const host = normalizeHost(raw);
311
+ return host ? { host, scheme: "https" } : null;
312
+ }
313
+
314
+ /**
315
+ * The origin a configured value names: scheme, host and port, nothing after.
316
+ *
317
+ * `hosts` are hostnames, so a port written into a host setting is lost by the
318
+ * time a caller builds a URL from one - and a local server on a port is the
319
+ * common case where that matters. This keeps the origin beside the host so a
320
+ * caller has a base URL to use rather than one to reconstruct.
321
+ */
322
+ function originOf(input) {
323
+ const text = String(input ?? "").trim();
324
+ if (!text) return null;
325
+ if (hasUnsafeChar(text, true)) return null;
326
+ let url;
327
+ try {
328
+ url = new URL(/^https?:\/\//i.test(text) ? text : `https://${text}`);
329
+ } catch {
330
+ return null;
331
+ }
332
+ if (url.username || url.password) return null;
333
+ return normalizeTarget(url.origin) ? url.origin : null;
334
+ }
335
+
336
+ function hostFromConfigured(input) {
337
+ const raw = String(input ?? "").trim();
338
+ if (!raw) return null;
339
+ if (hasUnsafeChar(raw, true)) return null;
340
+ const direct = normalizeHost(raw);
341
+ if (direct) return direct;
342
+ // No scheme, so the authority runs to the first `/`; a port follows the last
343
+ // `:` of it. Written out rather than handed to `new URL` with an invented
344
+ // scheme, which would also accept userinfo and quietly take the wrong half.
345
+ const authority = raw.replace(/^[a-z][a-z0-9+.-]*:\/\//i, "").split("/")[0];
346
+ if (authority.includes("@")) return null;
347
+ return normalizeHost(authority.replace(/:\d{1,5}$/, ""));
348
+ }
349
+
350
+ /** A lowercase handle derived from free text, for a generated id. */
351
+ /**
352
+ * An account id fragment: the shared slug, then checked against what an id
353
+ * may be. `slugify` already folds accents, so a name written in any Latin
354
+ * script gives an id rather than a row of dashes.
355
+ */
356
+ function handle(text, fallback = "x") {
357
+ const s = slugify(text, { maxLength: 63, fallback: "" });
358
+ return HANDLE_RE.test(s) ? s : fallback;
359
+ }
360
+
361
+ /** The hostnames a secret on this account may be sent to. */
362
+ function hostsOf(account, { usageEndpoint } = {}) {
363
+ // An environment account carries its destinations outright: they were
364
+ // gathered from the configured accounts and the environment, not declared.
365
+ if (account.fromEnv) return [...(account.hosts ?? [])];
366
+ const row = SERVICES[account.service];
367
+ if (!row) return [];
368
+ const extra = account.scope?.extraHosts ?? [];
369
+ switch (row.kind) {
370
+ case "hosted":
371
+ return account.scope?.host ? [account.scope.host, ...extra] : [];
372
+ case "vendor":
373
+ return account.scope?.host ? [account.scope.host, ...extra] : [...row.hosts, ...extra];
374
+ case "vendor-fixed":
375
+ return [...row.hosts];
376
+ case "endpoint": {
377
+ // The endpoint is a full URL with a path and often a port, and on a test
378
+ // or development machine it is a loopback one over http. Read it the way
379
+ // a destination is read, not the way a bare hostname is.
380
+ const host = normalizeTarget(usageEndpoint ?? "")?.host ?? null;
381
+ return host ? [host] : [];
382
+ }
383
+ default:
384
+ return [];
385
+ }
386
+ }
387
+
388
+ /**
389
+ * Entries derived from the flat keys, as they would be written.
390
+ *
391
+ * Pure: it reads the preference object and nothing else, never the store, and
392
+ * running it twice over its own output changes nothing. The pairing rule is
393
+ * the whole point - it writes a host onto a secret only where the file already
394
+ * says they belong together, and marks every other case `unresolved` for a
395
+ * person to answer rather than guessing.
396
+ *
397
+ * @param {object} prefs - the whole preferences object
398
+ * @returns {{accounts: object[], notes: string[]}}
399
+ */
400
+ export function reconcileAccounts(prefs) {
401
+ const g = prefs?.global ?? {};
402
+ const mapping = g.keychainMapping ?? {};
403
+ const legacyHosts = g.hosts ?? {};
404
+ const notes = [];
405
+ const existing = Array.isArray(g.serviceAccounts) ? g.serviceAccounts : [];
406
+
407
+ // Secrets the file names, grouped by service: service -> slot -> item name.
408
+ const found = new Map();
409
+ const put = (service, slot, item) => {
410
+ const name = typeof item === "string" ? item.trim() : "";
411
+ if (!name) return;
412
+ if (!found.has(service)) found.set(service, new Map());
413
+ const slots = found.get(service);
414
+ if (!slots.has(slot)) slots.set(slot, name);
415
+ };
416
+
417
+ for (const [key, [service, slot]] of Object.entries(LEGACY_SLOTS)) {
418
+ put(service, slot, mapping[key]);
419
+ }
420
+ // `bitbucket` is the older name for `bitbucket_token`. It fills the slot only
421
+ // when the newer key is empty; when both are set and differ, the file holds
422
+ // two secrets and nothing says which host either belongs to.
423
+ const bbAlias = typeof mapping.bitbucket === "string" ? mapping.bitbucket.trim() : "";
424
+ const bbToken = typeof mapping.bitbucket_token === "string" ? mapping.bitbucket_token.trim() : "";
425
+ if (bbAlias && !bbToken) put("bitbucket", "token", bbAlias);
426
+
427
+ const accounts = [];
428
+ const used = new Set(existing.map((a) => a.id).filter(Boolean));
429
+ const takeId = (want) => {
430
+ let id = want;
431
+ for (let n = 2; used.has(id); n++) id = `${want}-${n}`;
432
+ used.add(id);
433
+ return id;
434
+ };
435
+
436
+ /** An account already written for this (service, primary item) keeps its id and anything a person set. */
437
+ const carryOver = (service, primaryItem, extra = {}) =>
438
+ existing.find(
439
+ (a) =>
440
+ a.service === service &&
441
+ a.secrets?.[SERVICES[service].slots[0]] === primaryItem &&
442
+ (extra.projectId === undefined || a.scope?.projectId === extra.projectId) &&
443
+ (extra.environment === undefined || a.scope?.environment === extra.environment),
444
+ );
445
+
446
+ const push = (account) => {
447
+ const prior = carryOver(account.service, account.secrets[SERVICES[account.service].slots[0]], {
448
+ projectId: account.scope?.projectId,
449
+ environment: account.scope?.environment,
450
+ });
451
+ if (prior) {
452
+ // The id and the label are the person's: one is what everything else
453
+ // calls this account, the other is what they chose to call it. The scope
454
+ // is the data's, because the flat keys are kept in step with the array on
455
+ // every write, so a value that differs there is the newer of the two -
456
+ // except for the keys derivation has nothing to say about, which only a
457
+ // person ever sets.
458
+ const scope = { ...prior.scope, ...account.scope };
459
+ const merged = {
460
+ ...account,
461
+ id: prior.id,
462
+ label: prior.label ?? account.label,
463
+ ...(prior.identityId ? { identityId: prior.identityId } : {}),
464
+ ...(Object.keys(scope).length ? { scope } : {}),
465
+ };
466
+ // An open pairing question stays open only while it is still a question.
467
+ // Once the data names a host for this secret, that is the answer, and
468
+ // carrying the refusal forward would leave an account the resolver
469
+ // refuses for a reason that no longer holds.
470
+ if (!scope.host && (prior.unresolved || account.unresolved)) {
471
+ merged.unresolved = prior.unresolved ?? account.unresolved;
472
+ } else {
473
+ delete merged.unresolved;
474
+ }
475
+ accounts.push(merged);
476
+ return;
477
+ }
478
+ accounts.push({ ...account, id: takeId(account.id) });
479
+ };
480
+
481
+ for (const service of SERVICE_IDS) {
482
+ const slots = found.get(service);
483
+ if (!slots || slots.size === 0) continue;
484
+ const row = SERVICES[service];
485
+ const secrets = Object.fromEntries(slots);
486
+
487
+ if (service === "graylog") {
488
+ const prod = mapping.graylog?.trim?.() || "";
489
+ const test = mapping.graylog_test?.trim?.() || "";
490
+ const prodHost = hostFromConfigured(legacyHosts.graylog ?? "");
491
+ const testHost = hostFromConfigured(legacyHosts.graylogTest ?? "");
492
+ if (prod) {
493
+ push(
494
+ scoped(
495
+ "graylog",
496
+ "graylog",
497
+ `Graylog${prodHost ? ` (${prodHost})` : ""}`,
498
+ { token: prod },
499
+ prodHost,
500
+ { environment: "production" },
501
+ true,
502
+ ),
503
+ );
504
+ }
505
+ if (testHost) {
506
+ // A test instance with no key of its own shares the production item:
507
+ // that is what the schema says a null `graylog_test` means, and the
508
+ // two entries naming one item is how sharing is stated here.
509
+ const item = test || prod;
510
+ if (item) {
511
+ push(
512
+ scoped(
513
+ "graylog-test",
514
+ "graylog",
515
+ `Graylog test (${testHost})`,
516
+ { token: item },
517
+ testHost,
518
+ { environment: "test" },
519
+ false,
520
+ ),
521
+ );
522
+ if (!test)
523
+ notes.push(
524
+ "graylog-test names the production item, which is what an empty graylog_test meant",
525
+ );
526
+ }
527
+ } else if (test) {
528
+ push(
529
+ unresolvedAccount(
530
+ "graylog-test",
531
+ "graylog",
532
+ "Graylog test",
533
+ { token: test },
534
+ "host-unknown",
535
+ [],
536
+ ),
537
+ );
538
+ }
539
+ continue;
540
+ }
541
+
542
+ if (service === "firebase") {
543
+ const projects = Array.isArray(g.firebase?.accounts) ? g.firebase.accounts : [];
544
+ const base = secrets.service_account_json;
545
+ if (base)
546
+ push(
547
+ scoped(
548
+ "firebase",
549
+ "firebase",
550
+ "Firebase",
551
+ { service_account_json: base },
552
+ null,
553
+ {},
554
+ true,
555
+ ),
556
+ );
557
+ for (const entry of projects) {
558
+ const item = typeof entry?.keychainKey === "string" ? entry.keychainKey.trim() : "";
559
+ const projectId = typeof entry?.projectId === "string" ? entry.projectId.trim() : "";
560
+ if (!item || !projectId) continue;
561
+ if (item === base) continue;
562
+ push(
563
+ scoped(
564
+ `firebase-${handle(projectId, "project")}`,
565
+ "firebase",
566
+ entry.label || projectId,
567
+ { service_account_json: item },
568
+ null,
569
+ { projectId },
570
+ !base,
571
+ ),
572
+ );
573
+ }
574
+ continue;
575
+ }
576
+
577
+ const hostKey = LEGACY_HOSTS[service];
578
+ const host = hostKey ? hostFromConfigured(legacyHosts[hostKey] ?? "") : null;
579
+
580
+ if (row.kind === "hosted" && !host) {
581
+ push(
582
+ unresolvedAccount(service, service, labelFor(service, null), secrets, "host-unknown", []),
583
+ );
584
+ notes.push(`${service} has a secret but no host, so it is left for a person to pair`);
585
+ continue;
586
+ }
587
+ push(scoped(service, service, labelFor(service, host), secrets, host, {}, true));
588
+ }
589
+
590
+ // A second secret for a service the file cannot place. The alias case is the
591
+ // only one the flat keys can produce today; it is written as a refusal rather
592
+ // than silently dropped, so the person is asked instead of guessed at.
593
+ if (bbAlias && bbToken && bbAlias !== bbToken) {
594
+ const candidates = [hostFromConfigured(legacyHosts.bitbucket ?? "")].filter(Boolean);
595
+ push(
596
+ unresolvedAccount(
597
+ "bitbucket-2",
598
+ "bitbucket",
599
+ "Bitbucket (second token)",
600
+ { token: bbAlias },
601
+ "host-ambiguous",
602
+ candidates,
603
+ ),
604
+ );
605
+ notes.push(
606
+ "keychainMapping.bitbucket and .bitbucket_token name different items; the second is unpaired",
607
+ );
608
+ }
609
+
610
+ // Hosts a person confirmed for a logical key widen that key's account.
611
+ for (const [logical, hostList] of Object.entries(g.credentialHosts ?? {})) {
612
+ const pair = LEGACY_SLOTS[logical];
613
+ if (!pair) continue;
614
+ const [service, slot] = pair;
615
+ const item = typeof mapping[logical] === "string" ? mapping[logical].trim() : "";
616
+ if (!item) continue;
617
+ const account = accounts.find((a) => a.service === service && a.secrets?.[slot] === item);
618
+ if (!account) continue;
619
+ const extra = [hostList].flat().map(hostFromConfigured).filter(Boolean);
620
+ const already = new Set(
621
+ [account.scope?.host, ...(account.scope?.extraHosts ?? [])].filter(Boolean),
622
+ );
623
+ const add = extra.filter((h) => !already.has(h));
624
+ if (!add.length) continue;
625
+ account.scope = {
626
+ ...account.scope,
627
+ extraHosts: [...(account.scope?.extraHosts ?? []), ...add],
628
+ };
629
+ }
630
+
631
+ // Identity-owned tokens. An item one identity alone names belongs to it; an
632
+ // item several identities name belongs to none of them in particular.
633
+ const identities = withIdentityIds(g.identities ?? []);
634
+ const namedBy = new Map();
635
+ for (const identity of identities) {
636
+ for (const [service, item] of Object.entries(identity.servicePatMap ?? {})) {
637
+ const name = typeof item === "string" ? item.trim() : "";
638
+ if (!name || !SERVICES[service]) continue;
639
+ const key = `${service}\u0000${name}`;
640
+ namedBy.set(key, [...(namedBy.get(key) ?? []), identity.id]);
641
+ }
642
+ }
643
+ for (const [key, owners] of namedBy) {
644
+ const [service, item] = key.split("\u0000");
645
+ const slot = SERVICES[service].slots[0];
646
+ const mine = accounts.find((a) => a.service === service && a.secrets?.[slot] === item);
647
+ if (mine) {
648
+ if (owners.length === 1 && !mine.identityId) mine.identityId = owners[0];
649
+ continue;
650
+ }
651
+ const host = LEGACY_HOSTS[service]
652
+ ? hostFromConfigured(legacyHosts[LEGACY_HOSTS[service]] ?? "")
653
+ : null;
654
+ const owner = owners.length === 1 ? owners[0] : null;
655
+ const id = owner ? `${service}-${owner}` : `${service}-2`;
656
+ if (
657
+ SERVICES[service].kind === "hosted" &&
658
+ (!host || accounts.some((a) => a.service === service))
659
+ ) {
660
+ // Another account of this service already claims the only host the file
661
+ // names. Which of the two the host belongs to is exactly what the data
662
+ // does not say.
663
+ push(
664
+ unresolvedAccount(
665
+ id,
666
+ service,
667
+ labelFor(service, null),
668
+ { [slot]: item },
669
+ "host-ambiguous",
670
+ [host].filter(Boolean),
671
+ ),
672
+ );
673
+ notes.push(`${service} has more than one token and one host; the extra one is unpaired`);
674
+ } else {
675
+ const account = scoped(
676
+ id,
677
+ service,
678
+ labelFor(service, host),
679
+ { [slot]: item },
680
+ host,
681
+ {},
682
+ false,
683
+ );
684
+ if (owner) account.identityId = owner;
685
+ push(account);
686
+ }
687
+ }
688
+
689
+ // GitHub owners a routing rule already states.
690
+ for (const [identityId, patterns] of Object.entries(g.platformIdentityRouting ?? {})) {
691
+ const identity = identities.find((i) => i.id === identityId || i.name === identityId);
692
+ for (const pattern of [patterns].flat()) {
693
+ const m = /^github\.com\/([A-Za-z0-9-]{1,39})\/\*?$/.exec(String(pattern ?? "").trim());
694
+ if (!m) {
695
+ if (pattern)
696
+ notes.push(`platformIdentityRouting pattern not understood, nothing written: ${pattern}`);
697
+ continue;
698
+ }
699
+ // Only onto an account that identity actually owns. Declaring an owner
700
+ // narrows what the account answers for, so putting one on a shared
701
+ // account would turn a rule about who works where into a rule about
702
+ // which token is allowed - a restriction nobody asked for.
703
+ const account = accounts.find(
704
+ (a) => a.service === "github" && (!identity || a.identityId === identity.id),
705
+ );
706
+ if (!account) {
707
+ notes.push(
708
+ `platformIdentityRouting names ${m[1]} for ${identityId}, who has no github token of their own; nothing written`,
709
+ );
710
+ continue;
711
+ }
712
+ const owners = new Set(account.scope?.owners ?? []);
713
+ owners.add(m[1]);
714
+ account.scope = { ...account.scope, owners: [...owners] };
715
+ }
716
+ }
717
+
718
+ for (const account of accounts) {
719
+ if (account.scope && Object.keys(account.scope).length === 0) delete account.scope;
720
+ }
721
+ return { accounts, notes };
722
+ }
723
+
724
+ /**
725
+ * The account a prefixed store item belongs to, from the per-account entries.
726
+ *
727
+ * A team with one credential per instance keeps them apart by naming the store
728
+ * item after the account - the id, then the provider, then the rest - and puts
729
+ * that account's host in `global.accounts[]`. Neither half names the other, so
730
+ * the two are only ever in hand together at the moment a caller asks by item:
731
+ * the id read out of the name picks the entry, and the entry supplies the one
732
+ * host that item may be sent to. Without it the item resolves to whichever
733
+ * account the file lists first, which is the pairing this module exists to
734
+ * refuse.
735
+ */
736
+ function namedAccount(service, itemName, g) {
737
+ const row = SERVICES[service];
738
+ const map = ACCOUNT_HOSTS[service];
739
+ if (!row || !map || typeof itemName !== "string") return null;
740
+ const match = new RegExp(`^(.+?)_${map.segment}_`, "i").exec(itemName.trim());
741
+ if (!match) return null;
742
+ const wanted = handle(match[1], "account");
743
+ const entry = [g?.accounts ?? []]
744
+ .flat()
745
+ .find((a) => a && handle(String(a.id ?? ""), "account") === wanted);
746
+ if (!entry) return null;
747
+ // An entry that names no host for this service is still a known account; it
748
+ // is reached where the file says this service lives. Refusing it would make
749
+ // a credential named after an account resolve worse than an unnamed one.
750
+ const raw = entry[map.field] ?? g?.hosts?.[LEGACY_HOSTS[service]];
751
+ const host = hostFromConfigured(raw ?? "");
752
+ if (!host) return null;
753
+ return {
754
+ id: `${service}-${wanted}`,
755
+ service,
756
+ label:
757
+ typeof entry.label === "string" && entry.label.trim()
758
+ ? entry.label.trim()
759
+ : labelFor(service, host),
760
+ baseUrl: originOf(raw),
761
+ scope: { host },
762
+ secrets: { [row.slots[0]]: itemName.trim() },
763
+ };
764
+ }
765
+
766
+ /** An account whose destination is known. */
767
+ function scoped(id, service, label, secrets, host, extraScope, isDefault) {
768
+ const scope = { ...(host ? { host } : {}), ...extraScope };
769
+ return {
770
+ id,
771
+ service,
772
+ label,
773
+ ...(isDefault ? { default: true } : {}),
774
+ ...(Object.keys(scope).length ? { scope } : {}),
775
+ secrets,
776
+ };
777
+ }
778
+
779
+ /** An account the data cannot place, written so a person is asked rather than guessed at. */
780
+ function unresolvedAccount(id, service, label, secrets, reason, candidateHosts) {
781
+ return {
782
+ id,
783
+ service,
784
+ label,
785
+ secrets,
786
+ unresolved: { reason, ...(candidateHosts.length ? { candidateHosts } : {}) },
787
+ };
788
+ }
789
+
790
+ /** What a person sees for a service they have not named themselves. */
791
+ function labelFor(service, host) {
792
+ const pretty = service.replace(/_/g, " ").replace(/\b[a-z]/g, (c) => c.toUpperCase());
793
+ return host ? `${pretty} (${host})` : pretty;
794
+ }
795
+
796
+ /** identities[] with an id on every entry, derived from the name when absent. */
797
+ export function withIdentityIds(identities) {
798
+ const used = new Set(identities.map((i) => i?.id).filter(Boolean));
799
+ return identities.map((identity) => {
800
+ if (identity?.id) return identity;
801
+ const want = handle(identity?.name, "identity");
802
+ let id = want;
803
+ for (let n = 2; used.has(id); n++) id = `${want}-${n}`;
804
+ used.add(id);
805
+ return { ...identity, id };
806
+ });
807
+ }
808
+
809
+ /**
810
+ * The accounts in force, whether or not the file has been migrated.
811
+ *
812
+ * @param {object} prefs
813
+ * @returns {{accounts: object[], source: "stored"|"reconciled", notes: string[]}}
814
+ */
815
+ export function effectiveAccounts(prefs) {
816
+ const stored = prefs?.global?.serviceAccounts;
817
+ // An EMPTY array derives, rather than meaning "no accounts". The migration
818
+ // writes the key on every machine, including one whose credential map is all
819
+ // nulls; treating that as a stored answer would mean a credential added to
820
+ // the flat map by hand afterwards is never seen, and the person is told the
821
+ // service is not configured while looking at the entry they just wrote.
822
+ if (Array.isArray(stored) && stored.length) {
823
+ return { accounts: stored, source: "stored", notes: [] };
824
+ }
825
+ const { accounts, notes } = reconcileAccounts(prefs);
826
+ return { accounts, source: "reconciled", notes };
827
+ }
828
+
829
+ /**
830
+ * The rules JSON Schema cannot state, because each one is about the array as a
831
+ * whole rather than one entry.
832
+ *
833
+ * @param {object[]} accounts
834
+ * @param {object[]} [identities]
835
+ * @returns {{ok: true}|{ok: false, problems: {id: string, problem: string}[]}}
836
+ */
837
+ export function validateAccounts(accounts, identities = []) {
838
+ const problems = [];
839
+ const seenIds = new Set();
840
+ const seenLabels = new Set();
841
+ const defaults = new Map();
842
+ const identityIds = new Set(withIdentityIds(identities).map((i) => i.id));
843
+
844
+ for (const account of accounts ?? []) {
845
+ const id = account?.id ?? "(no id)";
846
+ const row = SERVICES[account?.service];
847
+ if (!row) {
848
+ problems.push({ id, problem: `unknown service ${account?.service}` });
849
+ continue;
850
+ }
851
+ if (seenIds.has(account.id)) problems.push({ id, problem: "id is used more than once" });
852
+ seenIds.add(account.id);
853
+
854
+ const labelKey = `${account.service}\u0000${String(account.label ?? "").toLowerCase()}`;
855
+ if (seenLabels.has(labelKey))
856
+ problems.push({ id, problem: "label is used twice within one service" });
857
+ seenLabels.add(labelKey);
858
+
859
+ if (account.default) {
860
+ if (defaults.has(account.service)) {
861
+ problems.push({ id, problem: `${account.service} already has a default account` });
862
+ }
863
+ defaults.set(account.service, id);
864
+ }
865
+ if (account.identityId && !identityIds.has(account.identityId)) {
866
+ problems.push({
867
+ id,
868
+ problem: `identityId ${account.identityId} is in no identities[] entry`,
869
+ });
870
+ }
871
+ for (const slot of Object.keys(account.secrets ?? {})) {
872
+ if (!row.slots.includes(slot)) {
873
+ problems.push({ id, problem: `${account.service} has no slot named ${slot}` });
874
+ }
875
+ }
876
+ for (const host of [account.scope?.host, ...(account.scope?.extraHosts ?? [])].filter(
877
+ Boolean,
878
+ )) {
879
+ if (normalizeHost(host) !== host) {
880
+ problems.push({ id, problem: `${host} is not a bare lowercase hostname` });
881
+ }
882
+ }
883
+ }
884
+ return problems.length ? { ok: false, problems } : { ok: true };
885
+ }
886
+
887
+ /**
888
+ * The account a credential in the environment stands for, if there is one.
889
+ *
890
+ * It exists only while a variable actually holds something, it is never the
891
+ * default when a configured account also fits, and its destinations are the
892
+ * union of what the configured accounts already cover, the vendor's own hosts,
893
+ * whatever its host variable names, and loopback. Nothing else: an unbound
894
+ * secret with an unbound destination is the pair this module exists to refuse.
895
+ *
896
+ * @param {string} service
897
+ * @param {object[]} configured - the stored or derived accounts for this service
898
+ * @param {object} env
899
+ * @param {object} g - `prefs.global`, for the usage endpoint
900
+ */
901
+ function envAccounts(service, configured, env, g) {
902
+ const row = SERVICES[service];
903
+ const table = ENV_SLOTS[service];
904
+ if (!row || !table || !env) return [];
905
+
906
+ const secrets = {};
907
+ for (const slot of row.slots) {
908
+ const name = (table[slot] ?? []).find((n) => String(env[n] ?? "").trim());
909
+ if (name) secrets[slot] = name;
910
+ }
911
+ if (!secrets[row.slots[0]]) return [];
912
+
913
+ const hosts = new Set();
914
+ for (const account of configured) {
915
+ for (const host of hostsOf(account, { usageEndpoint: g?.usageLog?.endpoint })) hosts.add(host);
916
+ }
917
+ if (row.kind === "vendor" || row.kind === "vendor-fixed") {
918
+ for (const host of row.hosts ?? []) hosts.add(host);
919
+ }
920
+ if (row.kind === "endpoint") {
921
+ const host = normalizeHost(g?.usageLog?.endpoint ?? "");
922
+ if (host) hosts.add(host);
923
+ }
924
+ // A host variable that was set and cannot be read is not an absence: it is
925
+ // an answer that does not work, and the common case is `http://` somewhere
926
+ // that is not loopback. Upgrading it to https silently would send the token
927
+ // to a host the person did not name; ignoring it would send it to whatever
928
+ // else the account covers. Both are worse than saying so.
929
+ let baseUrl = null;
930
+ let unusableHost = null;
931
+ for (const name of table.host ?? []) {
932
+ const raw = String(env[name] ?? "").trim();
933
+ if (!raw) continue;
934
+ const host = hostFromConfigured(raw);
935
+ if (host) hosts.add(host);
936
+ baseUrl ??= originOf(raw);
937
+ if (!host && !unusableHost) unusableHost = name;
938
+ }
939
+ if (unusableHost && !baseUrl) {
940
+ return [
941
+ {
942
+ id: `env:${service}`,
943
+ service,
944
+ label: `${service} from the environment`,
945
+ hosts: [],
946
+ secrets,
947
+ fromEnv: true,
948
+ unresolved: true,
949
+ unusableHost,
950
+ },
951
+ ];
952
+ }
953
+ // The file says where this service lives even when it holds no secret for
954
+ // it; that is an explicit enough pairing to send an environment token to.
955
+ const declared = hostFromConfigured(g?.hosts?.[service]);
956
+ if (declared) hosts.add(declared);
957
+ for (const host of LOOPBACK) hosts.add(host);
958
+
959
+ return [
960
+ {
961
+ id: `env:${service}`,
962
+ service,
963
+ label: `${service} from the environment`,
964
+ hosts: [...hosts],
965
+ baseUrl: baseUrl ?? originOf(g?.hosts?.[service]),
966
+ secrets,
967
+ fromEnv: true,
968
+ },
969
+ ];
970
+ }
971
+
972
+ /**
973
+ * A fingerprint of the variables that could change an answer for this service.
974
+ *
975
+ * The selection cache is keyed on the preferences file, which says nothing
976
+ * about the environment; a process that exported a token after its first
977
+ * lookup would otherwise keep being told the service is not configured. The
978
+ * values are hashed rather than kept, so no secret sits in a cache key.
979
+ */
980
+ function envStamp(service, env) {
981
+ const table = ENV_SLOTS[service];
982
+ if (!table || !env) return "none";
983
+ const hash = createHash("sha256");
984
+ for (const names of Object.values(table)) {
985
+ for (const name of names) hash.update(`${name}\u0000${env[name] ?? ""}\u0000`);
986
+ }
987
+ return hash.digest("hex").slice(0, 16);
988
+ }
989
+
990
+ /** A refusal, in the one shape every caller reads. */
991
+ function no(reason, service, message, remedy, extra = {}) {
992
+ return { ok: false, reason, service, message, remedy, ...extra };
993
+ }
994
+
995
+ /** Exit status per refusal reason; the shell entry hands these back to its caller. */
996
+ export const EXIT = Object.freeze({
997
+ "invalid-request": 3,
998
+ "prefs-unreadable": 6,
999
+ "invalid-config": 6,
1000
+ "not-configured": 1,
1001
+ "unknown-account": 1,
1002
+ "slot-missing": 1,
1003
+ "secret-missing": 1,
1004
+ "store-unavailable": 2,
1005
+ "store-error": 4,
1006
+ "secret-locked": 5,
1007
+ "destination-required": 7,
1008
+ "insecure-url": 7,
1009
+ "host-mismatch": 7,
1010
+ "no-account-for-target": 7,
1011
+ "identity-mismatch": 7,
1012
+ "not-sendable": 7,
1013
+ ambiguous: 8,
1014
+ "needs-pairing": 8,
1015
+ });
1016
+
1017
+ // Selections only, never secrets, and only for as long as the process lives.
1018
+ // The key carries the preferences file's own timestamp and length, so any edit
1019
+ // to it invalidates every entry at once - a selection that outlived a change to
1020
+ // the file is exactly how a token would go to a host nobody re-checked.
1021
+ const selectionCache = new Map();
1022
+ const SELECTION_CACHE_MAX = 256;
1023
+
1024
+ /** Remember an answer, oldest first out, so a long-lived process stays bounded. */
1025
+ function remember(key, answer) {
1026
+ if (selectionCache.size >= SELECTION_CACHE_MAX) {
1027
+ selectionCache.delete(selectionCache.keys().next().value);
1028
+ }
1029
+ selectionCache.set(key, answer);
1030
+ return answer;
1031
+ }
1032
+
1033
+ /** The preferences, with the status that says why they are not there. */
1034
+ function loadFor(opts) {
1035
+ const env = opts?.env ?? process.env;
1036
+ if (opts?.prefs) return { prefs: opts.prefs, file: null, stamp: null, env };
1037
+ const file = prefsPath(opts?.env ?? process.env);
1038
+ const r = readPrefsFile(file);
1039
+ let stamp;
1040
+ try {
1041
+ // Nanoseconds, not milliseconds: two writes inside one millisecond that
1042
+ // happen to leave the file the same length would otherwise share a stamp,
1043
+ // and the second one would be answered from the first one's entry.
1044
+ const s = statSync(file, { bigint: true });
1045
+ stamp = `${s.mtimeNs}:${s.size}`;
1046
+ } catch {
1047
+ stamp = "none";
1048
+ }
1049
+ return { prefs: r.prefs, status: r.status, file, stamp, env };
1050
+ }
1051
+
1052
+ /**
1053
+ * Which account answers a request, without reading any secret.
1054
+ *
1055
+ * @param {{service: string, accountId?: string, url?: string, host?: string,
1056
+ * environment?: string, projectId?: string, owner?: string,
1057
+ * identityId?: string}} request
1058
+ * @param {{env?: object, prefs?: object}} [opts]
1059
+ */
1060
+ export function selectAccount(request, opts = {}) {
1061
+ const service = request?.service;
1062
+ if (!SERVICES[service]) {
1063
+ return no(
1064
+ "invalid-request",
1065
+ service ?? null,
1066
+ `No service named ${service}.`,
1067
+ "Name one of: " + SERVICE_IDS.join(", "),
1068
+ );
1069
+ }
1070
+
1071
+ const loaded = loadFor(opts);
1072
+ const key =
1073
+ loaded.stamp &&
1074
+ `${loaded.file}\u0000${loaded.stamp}\u0000${envStamp(service, loaded.env)}\u0000${JSON.stringify(request)}`;
1075
+ if (key && selectionCache.has(key)) return selectionCache.get(key);
1076
+
1077
+ const answer = decide(request, loaded);
1078
+ return key ? remember(key, answer) : answer;
1079
+ }
1080
+
1081
+ function decide(request, loaded) {
1082
+ const { service } = request;
1083
+
1084
+ // A machine with no preferences file still has an environment, and a CI job
1085
+ // that exports a token and a host has said everything an account would say.
1086
+ // Refusing here would make "not set up yet" and "nothing to go on" the same
1087
+ // answer, and only the second one is true.
1088
+ if (loaded.status === "missing") {
1089
+ const fromEnv = envAccounts(service, [], loaded.env, {});
1090
+ if (!fromEnv.length) {
1091
+ return no(
1092
+ "not-configured",
1093
+ service,
1094
+ `No preferences file, so no ${service} account.`,
1095
+ `Run /multi-agent:setup to add a ${service} account.`,
1096
+ { optedOut: false },
1097
+ );
1098
+ }
1099
+ return decideAmong(request, fromEnv, {}, "environment");
1100
+ }
1101
+ if (loaded.status === "unreadable" || loaded.status === "invalid") {
1102
+ return no(
1103
+ "prefs-unreadable",
1104
+ service,
1105
+ "The preferences file could not be read.",
1106
+ `Fix or restore ${loaded.file}.`,
1107
+ );
1108
+ }
1109
+
1110
+ const g = loaded.prefs?.global ?? {};
1111
+ const { accounts, source } = effectiveAccounts(loaded.prefs);
1112
+ const mine = accounts.filter((a) => a?.service === service);
1113
+
1114
+ const check = validateAccounts(accounts, g.identities ?? []);
1115
+ if (!check.ok) {
1116
+ const touching = check.problems.filter(
1117
+ (p) => mine.some((a) => a.id === p.id) || p.problem.includes("more than once"),
1118
+ );
1119
+ if (touching.length) {
1120
+ return no(
1121
+ "invalid-config",
1122
+ service,
1123
+ `The ${service} accounts do not hold together: ${touching[0].problem}.`,
1124
+ "Run /multi-agent:doctor, then fix the entry it names.",
1125
+ );
1126
+ }
1127
+ }
1128
+
1129
+ // A credential in the environment widens the pool, never the default: it is
1130
+ // dropped wherever a configured account fits the same request.
1131
+ const pool = mine.concat(envAccounts(service, mine, loaded.env, g));
1132
+ return decideAmong(request, pool, g, source, accounts);
1133
+ }
1134
+
1135
+ /**
1136
+ * Which of these accounts answers the request, and why.
1137
+ *
1138
+ * Split out so a machine with no preferences file reaches exactly the same
1139
+ * matching as one with them: the pool is different, the rules are not.
1140
+ */
1141
+ function decideAmong(request, pool, g, source, everyAccount = pool) {
1142
+ const { service } = request;
1143
+ const row = SERVICES[service];
1144
+
1145
+ if (!pool.length) {
1146
+ const optedOut = [g.serviceOptOuts ?? []].flat().includes(service);
1147
+ // Whether anything says where this service lives, which is a different
1148
+ // question from whether a credential for it exists. A caller that has to
1149
+ // choose between asking for a credential and refusing a link outright
1150
+ // cannot tell those apart from the absence of an account alone.
1151
+ const hostKnown = Boolean(hostFromConfigured(g?.hosts?.[service]) || row?.hosts?.length);
1152
+ return no(
1153
+ "not-configured",
1154
+ service,
1155
+ `No ${service} account is configured.`,
1156
+ optedOut
1157
+ ? `You chose not to be asked about ${service}; run /multi-agent:setup to add one.`
1158
+ : `Run /multi-agent:setup to add a ${service} account.`,
1159
+ { optedOut, hostKnown },
1160
+ );
1161
+ }
1162
+
1163
+ // The destination, normalized once. A URL that is not https, or that carries
1164
+ // userinfo, is refused here rather than anywhere further in.
1165
+ let target = null;
1166
+ let transport = null;
1167
+ if (request.url || request.host) {
1168
+ const named = normalizeTarget(request.url ?? request.host);
1169
+ if (!named) {
1170
+ return no(
1171
+ "insecure-url",
1172
+ service,
1173
+ "That destination is not a host this module will hand a secret to.",
1174
+ "Pass an https URL with no username or password, a bare hostname, or an http URL at loopback.",
1175
+ { requested: { host: request.url ?? request.host } },
1176
+ );
1177
+ }
1178
+ target = named.host;
1179
+ transport = named.scheme;
1180
+ }
1181
+
1182
+ const usageEndpoint = g.usageLog?.endpoint;
1183
+ const hostsFor = (a) => hostsOf(a, { usageEndpoint });
1184
+
1185
+ // Where this account is reached, with the port and the scheme the file wrote.
1186
+ //
1187
+ // An account's host is a name, because that is what a destination is matched
1188
+ // on, and `hosts.jira = "http://127.0.0.1:9"` would otherwise come back as
1189
+ // `https://127.0.0.1`: a different port, a different scheme, and a request
1190
+ // nobody meant to send. The origin is taken from the entry whose host is
1191
+ // this account's, so a second account of the same service never inherits the
1192
+ // first one's port.
1193
+ const configuredOrigin = (a) => {
1194
+ const want = a.scope?.host;
1195
+ if (!want) return null;
1196
+ for (const raw of Object.values(g?.hosts ?? {})) {
1197
+ const origin = originOf(raw);
1198
+ if (origin && normalizeTarget(origin)?.host === want) return origin;
1199
+ }
1200
+ return null;
1201
+ };
1202
+ const describe = (a) => ({ id: a.id, label: a.label, hosts: hostsFor(a) });
1203
+
1204
+ // An identity the request names rules out accounts bound to another one.
1205
+ let eligible = pool;
1206
+ if (request.identityId) {
1207
+ const free = pool.filter((a) => !a.identityId || a.identityId === request.identityId);
1208
+ if (!free.length) {
1209
+ return no(
1210
+ "identity-mismatch",
1211
+ service,
1212
+ `Every ${service} account belongs to another identity.`,
1213
+ `Add a ${service} account for this identity, or run without one.`,
1214
+ { candidates: pool.map(describe) },
1215
+ );
1216
+ }
1217
+ eligible = free;
1218
+ }
1219
+
1220
+ // A caller that already holds a store item name - a migration, an audit, a
1221
+ // script written before accounts existed - asks by it rather than guessing
1222
+ // which account it belongs to.
1223
+ if (request.itemName) {
1224
+ let holders = eligible.filter((a) => Object.values(a.secrets ?? {}).includes(request.itemName));
1225
+ if (!holders.length) {
1226
+ const named = namedAccount(service, request.itemName, g);
1227
+ if (named) holders = [named];
1228
+ }
1229
+ if (!holders.length) {
1230
+ return no(
1231
+ "unknown-account",
1232
+ service,
1233
+ `No ${service} account names ${request.itemName}.`,
1234
+ "Run /multi-agent:setup, or name the account instead of the item.",
1235
+ { candidates: eligible.map(describe) },
1236
+ );
1237
+ }
1238
+ if (holders.length > 1 && !breakTie(holders, request)) {
1239
+ return no(
1240
+ "ambiguous",
1241
+ service,
1242
+ `More than one ${service} account names ${request.itemName}.`,
1243
+ "Name the account you mean.",
1244
+ { candidates: holders.map(describe) },
1245
+ );
1246
+ }
1247
+ eligible = holders.length === 1 ? holders : [breakTie(holders, request)];
1248
+ }
1249
+
1250
+ const answer = (account, matchedBy) => {
1251
+ if (account.unresolved) {
1252
+ return account.unusableHost
1253
+ ? no(
1254
+ "insecure-url",
1255
+ service,
1256
+ `${account.unusableHost} does not name a host a secret may be sent to.`,
1257
+ "Write it as an https host, or as an http one at loopback.",
1258
+ { candidates: [describe(account)] },
1259
+ )
1260
+ : no(
1261
+ "needs-pairing",
1262
+ service,
1263
+ `${account.label} has a secret but no host it may be sent to.`,
1264
+ "Run /multi-agent:setup and say which host this credential belongs to.",
1265
+ { candidates: [describe(account)] },
1266
+ );
1267
+ }
1268
+ return {
1269
+ ok: true,
1270
+ account: {
1271
+ ...account,
1272
+ hosts: hostsFor(account),
1273
+ baseUrl: account.baseUrl ?? configuredOrigin(account) ?? originOf(account.scope?.host),
1274
+ slots: row.slots,
1275
+ },
1276
+ matchedBy,
1277
+ source: account.fromEnv ? "environment" : source,
1278
+ boundHost: target,
1279
+ transport,
1280
+ };
1281
+ };
1282
+
1283
+ if (request.accountId) {
1284
+ const account = pool.find((a) => a.id === request.accountId);
1285
+ if (!account) {
1286
+ const elsewhere = everyAccount.find((a) => a.id === request.accountId);
1287
+ if (elsewhere) {
1288
+ return no(
1289
+ "invalid-request",
1290
+ service,
1291
+ `Account ${request.accountId} is a ${elsewhere.service} account, not a ${service} one.`,
1292
+ `Name a ${service} account: ` + pool.map((a) => a.id).join(", "),
1293
+ );
1294
+ }
1295
+ return no(
1296
+ "unknown-account",
1297
+ service,
1298
+ `No account named ${request.accountId}.`,
1299
+ "Name one of: " + pool.map((a) => a.id).join(", "),
1300
+ { candidates: pool.map(describe) },
1301
+ );
1302
+ }
1303
+ if (target && !hostsFor(account).includes(target)) {
1304
+ return no(
1305
+ "host-mismatch",
1306
+ service,
1307
+ `${account.label} is not for ${target}.`,
1308
+ `Send this to ${hostsFor(account).join(" or ") || "the host this account names"}, or pick another account.`,
1309
+ { requested: { host: target }, candidates: [describe(account)] },
1310
+ );
1311
+ }
1312
+ return answer(account, "account-id");
1313
+ }
1314
+
1315
+ const fields = [
1316
+ ["environment", (a) => a.scope?.environment],
1317
+ ["projectId", (a) => a.scope?.projectId],
1318
+ ["owner", (a) => (a.scope?.owners?.length ? a.scope.owners : undefined)],
1319
+ ];
1320
+ const asked = fields.filter(([name]) => request[name] != null && request[name] !== "");
1321
+
1322
+ if (target || asked.length) {
1323
+ let candidates = eligible.filter((a) => {
1324
+ if (target && !hostsFor(a).includes(target)) return false;
1325
+ for (const [name, read] of asked) {
1326
+ const declared = read(a);
1327
+ if (declared === undefined) continue;
1328
+ const values = Array.isArray(declared) ? declared : [declared];
1329
+ if (!values.includes(request[name])) return false;
1330
+ }
1331
+ return true;
1332
+ });
1333
+ if (!candidates.length) {
1334
+ return no(
1335
+ "no-account-for-target",
1336
+ service,
1337
+ `No ${service} account covers ${target ?? asked.map(([n]) => `${n}=${request[n]}`).join(", ")}.`,
1338
+ `Add an account for it in /multi-agent:setup, or name the account you mean.`,
1339
+ {
1340
+ requested: target
1341
+ ? { host: target }
1342
+ : Object.fromEntries(asked.map(([n]) => [n, request[n]])),
1343
+ candidates: eligible.map(describe),
1344
+ },
1345
+ );
1346
+ }
1347
+ if (candidates.length > 1 && candidates.some((a) => !a.fromEnv)) {
1348
+ candidates = candidates.filter((a) => !a.fromEnv);
1349
+ }
1350
+ if (candidates.length > 1) {
1351
+ // The account that declares the most of what was asked wins; a declared
1352
+ // field is evidence, an undeclared one is only an absence of objection.
1353
+ const score = (a) => asked.filter(([, read]) => read(a) !== undefined).length;
1354
+ const best = Math.max(...candidates.map(score));
1355
+ candidates = candidates.filter((a) => score(a) === best);
1356
+ }
1357
+ const picked = breakTie(candidates, request);
1358
+ if (!picked) {
1359
+ return no(
1360
+ "ambiguous",
1361
+ service,
1362
+ `More than one ${service} account fits, and nothing in the request tells them apart.`,
1363
+ "Name the account you mean.",
1364
+ { candidates: candidates.map(describe) },
1365
+ );
1366
+ }
1367
+ return answer(picked, target ? "target" : "scope");
1368
+ }
1369
+
1370
+ if (eligible.length > 1 && eligible.some((a) => !a.fromEnv)) {
1371
+ eligible = eligible.filter((a) => !a.fromEnv);
1372
+ }
1373
+ if (eligible.length === 1)
1374
+ return answer(eligible[0], eligible[0].fromEnv ? "environment" : "sole");
1375
+ const picked = breakTie(eligible, request);
1376
+ if (!picked) {
1377
+ return no(
1378
+ "ambiguous",
1379
+ service,
1380
+ `There is more than one ${service} account and the request names none.`,
1381
+ "Name the account you mean, or mark one as the default.",
1382
+ { candidates: eligible.map(describe) },
1383
+ );
1384
+ }
1385
+ return answer(
1386
+ picked,
1387
+ picked.identityId && picked.identityId === request.identityId ? "identity" : "default",
1388
+ );
1389
+ }
1390
+
1391
+ /** The identity's own account first, then the default; otherwise nothing. */
1392
+ function breakTie(candidates, request) {
1393
+ if (candidates.length === 1) return candidates[0];
1394
+ if (request.identityId) {
1395
+ const own = candidates.filter((a) => a.identityId === request.identityId);
1396
+ if (own.length === 1) return own[0];
1397
+ if (own.length > 1) candidates = own;
1398
+ }
1399
+ const defaults = candidates.filter((a) => a.default);
1400
+ return defaults.length === 1 ? defaults[0] : null;
1401
+ }
1402
+
1403
+ /** The store script this module speaks to. */
1404
+ function storePath(env) {
1405
+ const given = env?.CRED_STORE;
1406
+ if (given && existsSync(given)) return given;
1407
+ // The installed store is the one bound to this machine. When the module
1408
+ // runs from a checkout, the copy beside it is the source file, not the
1409
+ // store the rest of the pipeline talks to - and reading the wrong one is
1410
+ // how a run reports "not in the store" about a secret that is in it.
1411
+ const home = env?.HOME;
1412
+ if (home) {
1413
+ const installed = join(home, ".claude", "lib", "credential-store.sh");
1414
+ if (existsSync(installed)) return installed;
1415
+ }
1416
+ return join(HERE, "credential-store.sh");
1417
+ }
1418
+
1419
+ /**
1420
+ * The secret on an account, for a destination that was checked.
1421
+ *
1422
+ * The value is attached as a non-enumerable property: logging the answer, or
1423
+ * putting it through `JSON.stringify`, must not print it, and the only way to
1424
+ * make that true for every caller at once is to make it invisible to both.
1425
+ *
1426
+ * @param {object} request - as `selectAccount`, plus an optional `slot`
1427
+ * @param {{env?: object, prefs?: object}} [opts]
1428
+ */
1429
+ export function resolveSecret(request, opts = {}) {
1430
+ const ready = prepareSecret(request, opts);
1431
+ if (!ready.ok) return ready;
1432
+ if (ready.fromEnv) return finishSecret(ready, readEnvSecret(ready, opts));
1433
+
1434
+ let secret;
1435
+ try {
1436
+ secret = execFileSync("bash", storeArgv(ready, opts), {
1437
+ encoding: "utf8",
1438
+ env: opts.env ?? process.env,
1439
+ timeout: 10_000,
1440
+ killSignal: "SIGKILL",
1441
+ stdio: ["ignore", "pipe", "pipe"],
1442
+ });
1443
+ } catch (error) {
1444
+ return storeFailure(ready, error?.status);
1445
+ }
1446
+ return finishSecret(ready, secret);
1447
+ }
1448
+
1449
+ /**
1450
+ * `resolveSecret` for a caller that must not block.
1451
+ *
1452
+ * The decision, the host check and the refusal shapes are the synchronous
1453
+ * ones: only the read of the store is different, so there is no second set of
1454
+ * rules to keep in step with the first.
1455
+ */
1456
+ export async function resolveSecretAsync(request, opts = {}) {
1457
+ const ready = prepareSecret(request, opts);
1458
+ if (!ready.ok) return ready;
1459
+ if (ready.fromEnv) return finishSecret(ready, readEnvSecret(ready, opts));
1460
+
1461
+ const secret = await new Promise((resolve) => {
1462
+ execFile(
1463
+ "bash",
1464
+ storeArgv(ready, opts),
1465
+ {
1466
+ encoding: "utf8",
1467
+ env: opts.env ?? process.env,
1468
+ timeout: 10_000,
1469
+ killSignal: "SIGKILL",
1470
+ },
1471
+ (error, stdout) => resolve(error ? { error } : { stdout }),
1472
+ );
1473
+ });
1474
+ if (secret.error) return storeFailure(ready, secret.error?.code);
1475
+ return finishSecret(ready, secret.stdout);
1476
+ }
1477
+
1478
+ /**
1479
+ * Everything decided before any secret is read: which account answers, which
1480
+ * slot was asked for, whether the destination is one it may reach, and the
1481
+ * name that holds the value - a store item, or an environment variable.
1482
+ *
1483
+ * Nothing here touches the store, so every refusal below is one the caller
1484
+ * gets without a credential having been read at all.
1485
+ */
1486
+ function prepareSecret(request, opts) {
1487
+ const chosen = selectAccount(request, opts);
1488
+ if (!chosen.ok) return chosen;
1489
+
1490
+ const { account } = chosen;
1491
+ const row = SERVICES[account.service];
1492
+ const slot = request.slot ?? row.slots[0];
1493
+ if (!row.slots.includes(slot)) {
1494
+ return no(
1495
+ "invalid-request",
1496
+ account.service,
1497
+ `${account.service} has no slot named ${slot}.`,
1498
+ "Ask for one of: " + row.slots.join(", "),
1499
+ );
1500
+ }
1501
+
1502
+ const target = chosen.boundHost ?? null;
1503
+ if (row.kind !== "local" && !target) {
1504
+ return no(
1505
+ "destination-required",
1506
+ account.service,
1507
+ `A ${account.service} secret is only handed out for a destination.`,
1508
+ "Pass the URL or host this secret is about to be sent to.",
1509
+ );
1510
+ }
1511
+ if (target && !account.hosts.includes(target)) {
1512
+ return no(
1513
+ "host-mismatch",
1514
+ account.service,
1515
+ `${account.label} is not for ${target}.`,
1516
+ `Send this to ${account.hosts.join(" or ")}, or pick another account.`,
1517
+ { requested: { host: target } },
1518
+ );
1519
+ }
1520
+ const item = account.secrets?.[slot];
1521
+ if (!item) {
1522
+ return no(
1523
+ "slot-missing",
1524
+ account.service,
1525
+ `${account.label} has nothing in its ${slot} slot.`,
1526
+ account.fromEnv
1527
+ ? `Export the ${slot} for ${account.service}, or run /multi-agent:setup.`
1528
+ : `Run /multi-agent:setup and add the ${slot} for ${account.label}.`,
1529
+ );
1530
+ }
1531
+ return { ok: true, chosen, account, slot, item, target, fromEnv: account.fromEnv === true };
1532
+ }
1533
+
1534
+ /** The store call for a prepared request. The item name is an argument, never interpolated. */
1535
+ function storeArgv(ready, opts) {
1536
+ return [
1537
+ storePath(opts.env ?? process.env),
1538
+ "get-item",
1539
+ ready.item,
1540
+ `account:${ready.account.id}/${ready.slot}`,
1541
+ ];
1542
+ }
1543
+
1544
+ /** The value an environment-supplied credential holds, by the variable the account named. */
1545
+ function readEnvSecret(ready, opts) {
1546
+ return String((opts.env ?? process.env)[ready.item] ?? "");
1547
+ }
1548
+
1549
+ /** What the store's exit status meant, in the one refusal shape. */
1550
+ function storeFailure(ready, status) {
1551
+ const { account, slot } = ready;
1552
+ const reason =
1553
+ status === 2
1554
+ ? "store-unavailable"
1555
+ : status === 4
1556
+ ? "store-error"
1557
+ : status === 5
1558
+ ? "secret-locked"
1559
+ : "secret-missing";
1560
+ const message = {
1561
+ "store-unavailable": "The credential store is not available on this machine.",
1562
+ "store-error": "The credential store failed while reading this secret.",
1563
+ "secret-locked": "The credential store is locked.",
1564
+ "secret-missing": `${account.label} names a ${slot} that is not in the store.`,
1565
+ }[reason];
1566
+ const remedy = {
1567
+ "store-unavailable": "This part of the pipeline needs macOS.",
1568
+ "store-error": "Run /multi-agent:doctor for what the store reported.",
1569
+ "secret-locked": "Unlock the login keychain and try again.",
1570
+ "secret-missing": `Run /multi-agent:setup and save the ${slot} for ${account.label}.`,
1571
+ }[reason];
1572
+ return no(reason, account.service, message, remedy);
1573
+ }
1574
+
1575
+ /** The answer, with the secret attached where it cannot be serialized or printed. */
1576
+ function finishSecret(ready, secret) {
1577
+ const { account, chosen, slot, target } = ready;
1578
+ if (!secret) {
1579
+ return no(
1580
+ "secret-missing",
1581
+ account.service,
1582
+ ready.fromEnv
1583
+ ? `${account.label} names ${ready.item}, which is not set.`
1584
+ : `${account.label} names a ${slot} that is not in the store.`,
1585
+ ready.fromEnv
1586
+ ? `Export ${ready.item}, or run /multi-agent:setup.`
1587
+ : `Run /multi-agent:setup and save the ${slot} for ${account.label}.`,
1588
+ );
1589
+ }
1590
+ const out = {
1591
+ ok: true,
1592
+ account,
1593
+ matchedBy: chosen.matchedBy,
1594
+ source: chosen.source,
1595
+ slot,
1596
+ boundHost: target,
1597
+ transport: chosen.transport ?? null,
1598
+ fromEnv: ready.fromEnv,
1599
+ };
1600
+ Object.defineProperty(out, "secret", { value: secret, enumerable: false, writable: false });
1601
+ return out;
1602
+ }
1603
+
1604
+ /**
1605
+ * The store item name behind a slot, for the one caller that needs a name
1606
+ * rather than a value: App Store Connect hands `xcrun` a keychain item to read
1607
+ * for itself.
1608
+ */
1609
+ export function resolveItemRef(request, opts = {}) {
1610
+ const chosen = selectAccount(request, opts);
1611
+ if (!chosen.ok) return chosen;
1612
+ const slot = request.slot;
1613
+ if (slot !== "password_item") {
1614
+ return no(
1615
+ "invalid-request",
1616
+ chosen.account.service,
1617
+ "Only the password_item slot is handed out as a name.",
1618
+ "Ask for the secret instead.",
1619
+ );
1620
+ }
1621
+ const itemName = chosen.account.secrets?.[slot];
1622
+ if (!itemName) {
1623
+ return no(
1624
+ "slot-missing",
1625
+ chosen.account.service,
1626
+ `${chosen.account.label} has nothing in its ${slot} slot.`,
1627
+ `Run /multi-agent:setup and add the ${slot} for ${chosen.account.label}.`,
1628
+ );
1629
+ }
1630
+ return { ok: true, account: chosen.account, slot, itemName };
1631
+ }
1632
+
1633
+ /**
1634
+ * A curl config that sends the secret to the checked URL and nowhere else.
1635
+ *
1636
+ * The URL, the scheme lock and the header live in one config so curl cannot be
1637
+ * pointed somewhere else between the check and the request, and redirects are
1638
+ * refused outright: a 301 is the cheapest way to make a client carry a header
1639
+ * to a host nobody authorized.
1640
+ */
1641
+ export function curlConfig(request, opts = {}) {
1642
+ const answer = resolveSecret(request, opts);
1643
+ if (!answer.ok) return answer;
1644
+ const row = SERVICES[answer.account.service];
1645
+ if (row.kind === "local") {
1646
+ return no(
1647
+ "not-sendable",
1648
+ answer.account.service,
1649
+ `A ${answer.account.service} credential is for a local tool, not for an outbound request.`,
1650
+ "Hand it to the tool that needs it instead.",
1651
+ );
1652
+ }
1653
+ const url = request.url;
1654
+ if (!url) {
1655
+ return no(
1656
+ "destination-required",
1657
+ answer.account.service,
1658
+ "A curl config needs the URL it is for.",
1659
+ "Pass the full https URL.",
1660
+ );
1661
+ }
1662
+ const scheme = request.scheme ?? "bearer";
1663
+ const bad = checkedScheme(scheme, answer.account.service);
1664
+ if (bad) return bad;
1665
+
1666
+ let username;
1667
+ if (wantsUsername(scheme, answer.account)) {
1668
+ const user = resolveSecret({ ...request, slot: "username" }, opts);
1669
+ if (!user.ok) return user;
1670
+ username = user.secret;
1671
+ }
1672
+ const header = headerAnswer(answer, scheme, username);
1673
+
1674
+ // The URL written here is one this module produced, never the caller's own
1675
+ // string. `normalizeHost` reads a hostname out of the input; it does not
1676
+ // certify the rest of it, and a config line is read by curl, not by the URL
1677
+ // parser. Re-parsing and serializing collapses the two readings into one.
1678
+ let parsed;
1679
+ try {
1680
+ parsed = new URL(url);
1681
+ } catch {
1682
+ return no(
1683
+ "insecure-url",
1684
+ answer.account.service,
1685
+ "That is not a URL this module will send a secret to.",
1686
+ "Pass a full https URL.",
1687
+ );
1688
+ }
1689
+ const expected = answer.transport === "http" ? "http:" : "https:";
1690
+ const named = normalizeTarget(parsed.href);
1691
+ if (
1692
+ parsed.protocol !== expected ||
1693
+ parsed.username ||
1694
+ parsed.password ||
1695
+ named?.host !== answer.boundHost ||
1696
+ named?.scheme !== answer.transport
1697
+ ) {
1698
+ return no(
1699
+ "host-mismatch",
1700
+ answer.account.service,
1701
+ `That URL does not resolve to ${answer.boundHost}.`,
1702
+ `Send this to ${answer.account.hosts.join(" or ")}.`,
1703
+ { requested: { host: parsed.hostname } },
1704
+ );
1705
+ }
1706
+
1707
+ // A curl config quotes with backslash escapes, but it is read a line at a
1708
+ // time: a quoted string cannot span lines, so a newline inside one does not
1709
+ // escape to anything - it ends the directive and starts another. Nothing is
1710
+ // written rather than something wrong being escaped.
1711
+ const quoted = (value) => `"${String(value).replace(/\\/g, "\\\\").replace(/"/g, '\\"')}"`;
1712
+ // Checked, not escaped: a config is read a line at a time, so a quoted
1713
+ // string cannot span lines and a newline inside one escapes to nothing. The
1714
+ // URL is already a serialization this module produced; the credential comes
1715
+ // from the store and is the one value here nobody has looked at.
1716
+ if (hasUnsafeChar(parsed.href) || hasUnsafeChar(header.value) || hasUnsafeChar(header.name)) {
1717
+ return no(
1718
+ "insecure-url",
1719
+ answer.account.service,
1720
+ "A value for this request carries a control character, so no config can be written for it.",
1721
+ "Check the URL, and re-save the secret if that is what carries it.",
1722
+ );
1723
+ }
1724
+ const config = [
1725
+ `url = ${quoted(parsed.href)}`,
1726
+ `proto = ${quoted("=" + expected.slice(0, -1))}`,
1727
+ "max-redirs = 0",
1728
+ "silent",
1729
+ "show-error",
1730
+ `header = ${quoted(`${header.name}: ${header.value}`)}`,
1731
+ "",
1732
+ ].join("\n");
1733
+ return { ok: true, config, account: answer.account };
1734
+ }
1735
+
1736
+ const b64 = (text) => Buffer.from(text).toString("base64");
1737
+
1738
+ /**
1739
+ * How each service expects its credential to be presented.
1740
+ *
1741
+ * One table rather than a branch per caller: the header a service wants is a
1742
+ * fact about that service, and a fetcher that writes its own header is a
1743
+ * fetcher that can get it wrong in a way nothing here would catch.
1744
+ *
1745
+ * Each entry is given the values, never the means to read them, so one table
1746
+ * serves the blocking caller, the asynchronous one and the curl config alike.
1747
+ */
1748
+ const AUTH_SCHEMES = Object.freeze({
1749
+ bearer: ({ secret }) => ({ name: "Authorization", value: `Bearer ${secret}` }),
1750
+ // The username slot holds an item name like every other slot, so it is read
1751
+ // through the store too; sending the item name as the login would fail in
1752
+ // the way a wrong password does, which is the hardest kind to diagnose.
1753
+ basic: ({ secret, username }) => ({
1754
+ name: "Authorization",
1755
+ value: `Basic ${b64(`${username}:${secret}`)}`,
1756
+ }),
1757
+ // The token is the whole login, with an empty password: what a server that
1758
+ // takes a PAT over basic auth expects, and what a `user:token` pair would
1759
+ // get wrong by sending a username the token does not belong to.
1760
+ "basic-token-user": ({ secret }) => ({
1761
+ name: "Authorization",
1762
+ value: `Basic ${b64(`${secret}:`)}`,
1763
+ }),
1764
+ // One service, two deployments: the hosted one takes a username and an app
1765
+ // password, the self-hosted one a bearer token and no username at all. The
1766
+ // account says which it is by whether it carries a username.
1767
+ "basic-or-bearer": ({ secret, username }) =>
1768
+ username
1769
+ ? { name: "Authorization", value: `Basic ${b64(`${username}:${secret}`)}` }
1770
+ : { name: "Authorization", value: `Bearer ${secret}` },
1771
+ "figma-pat": ({ secret }) => ({ name: "X-Figma-Token", value: secret }),
1772
+ "fortify-token": ({ secret }) => ({
1773
+ name: "Authorization",
1774
+ value: `FortifyToken ${b64(secret)}`,
1775
+ }),
1776
+ // The token is the login and the word `token` is the password, which is what
1777
+ // a Graylog personal access token expects. Sending it as the password
1778
+ // instead, or with an empty one, fails as a wrong password does.
1779
+ "graylog-pat": ({ secret }) => ({
1780
+ name: "Authorization",
1781
+ value: `Basic ${b64(`${secret}:token`)}`,
1782
+ }),
1783
+ });
1784
+
1785
+ /** Whether this scheme, for this account, needs the username slot read as well. */
1786
+ function wantsUsername(scheme, account) {
1787
+ if (scheme === "basic") return true;
1788
+ if (scheme === "basic-or-bearer") return Boolean(account.secrets?.username);
1789
+ return false;
1790
+ }
1791
+
1792
+ /** The scheme name, checked, or a refusal naming the ones that exist. */
1793
+ function checkedScheme(scheme, service) {
1794
+ if (AUTH_SCHEMES[scheme]) return null;
1795
+ return no(
1796
+ "invalid-request",
1797
+ service,
1798
+ `No authorization scheme named ${scheme}.`,
1799
+ "Ask for one of: " + Object.keys(AUTH_SCHEMES).join(", "),
1800
+ );
1801
+ }
1802
+
1803
+ /**
1804
+ * The authorization header for a request, for a caller that speaks HTTP itself.
1805
+ *
1806
+ * `curl-config` is better where it fits, because the header and the URL cannot
1807
+ * be separated there. A `fetch` caller has no such file, so it gets the header
1808
+ * from the same table rather than assembling one: `redirect: "error"` is then
1809
+ * the caller's own part of the bargain.
1810
+ *
1811
+ * The value is attached where it cannot be serialized or printed, like a secret.
1812
+ */
1813
+ export async function authHeaderAsync(request, opts = {}) {
1814
+ const answer = await resolveSecretAsync(request, opts);
1815
+ if (!answer.ok) return answer;
1816
+ const scheme = request.scheme ?? "bearer";
1817
+ const bad = checkedScheme(scheme, answer.account.service);
1818
+ if (bad) return bad;
1819
+ let username;
1820
+ if (wantsUsername(scheme, answer.account)) {
1821
+ const user = await resolveSecretAsync({ ...request, slot: "username" }, opts);
1822
+ if (!user.ok) return user;
1823
+ username = user.secret;
1824
+ }
1825
+ return headerAnswer(answer, scheme, username);
1826
+ }
1827
+
1828
+ function headerAnswer(answer, scheme, username) {
1829
+ const built = AUTH_SCHEMES[scheme]({ secret: answer.secret, username, account: answer.account });
1830
+ const out = {
1831
+ ok: true,
1832
+ account: answer.account,
1833
+ boundHost: answer.boundHost,
1834
+ transport: answer.transport,
1835
+ name: built.name,
1836
+ };
1837
+ Object.defineProperty(out, "value", {
1838
+ value: built.value,
1839
+ enumerable: false,
1840
+ writable: false,
1841
+ });
1842
+ return out;
1843
+ }
1844
+
1845
+ /**
1846
+ * Every store item the accounts name, with what names it.
1847
+ *
1848
+ * The inventory and the doctor need to ask the store what it holds and say
1849
+ * which account each answer belongs to. Item names, never values: this is the
1850
+ * one listing that is safe to print, and it stays that way by never reading
1851
+ * the store at all. Environment-supplied accounts are left out - their names
1852
+ * are variables, and the store has nothing under them.
1853
+ *
1854
+ * @param {object} prefs - the whole preferences object
1855
+ * @returns {{item: string, service: string, accountId: string, slot: string}[]}
1856
+ */
1857
+ export function itemNames(prefs) {
1858
+ const { accounts } = effectiveAccounts(prefs ?? {});
1859
+ const out = [];
1860
+ for (const account of accounts) {
1861
+ if (!SERVICES[account.service] || account.fromEnv) continue;
1862
+ for (const [slot, item] of Object.entries(account.secrets ?? {})) {
1863
+ if (item) out.push({ item, service: account.service, accountId: account.id, slot });
1864
+ }
1865
+ }
1866
+ return out;
1867
+ }
1868
+
1869
+ /** The flat keys an account projects back into, for everything still reading them. */
1870
+ export function projectLegacy(accounts) {
1871
+ const keychainMapping = {};
1872
+ const hosts = {};
1873
+ const credentialHosts = {};
1874
+ const byService = new Map();
1875
+ for (const account of accounts ?? []) {
1876
+ if (!SERVICES[account.service]) continue;
1877
+ const current = byService.get(account.service);
1878
+ if (!current || (account.default && !current.default)) byService.set(account.service, account);
1879
+ }
1880
+ for (const [legacyKey, [service, slot]] of Object.entries(LEGACY_SLOTS)) {
1881
+ const account = byService.get(service);
1882
+ const item = account?.secrets?.[slot];
1883
+ if (item) keychainMapping[legacyKey] = item;
1884
+ }
1885
+ for (const [hostKey, service] of Object.entries(LEGACY_HOSTS)) {
1886
+ const host = byService.get(service)?.scope?.host;
1887
+ if (host) hosts[hostKey] = host;
1888
+ }
1889
+ const graylogTest = (accounts ?? []).find(
1890
+ (a) => a.service === "graylog" && a.scope?.environment === "test",
1891
+ );
1892
+ if (graylogTest?.scope?.host) hosts.graylogTest = graylogTest.scope.host;
1893
+ if (graylogTest?.secrets?.token) keychainMapping.graylog_test = graylogTest.secrets.token;
1894
+ for (const [legacyKey, [service, slot]] of Object.entries(LEGACY_SLOTS)) {
1895
+ const account = byService.get(service);
1896
+ const extra = account?.scope?.extraHosts;
1897
+ if (extra?.length && account.secrets?.[slot]) credentialHosts[legacyKey] = [...extra];
1898
+ }
1899
+ return { keychainMapping, hosts, credentialHosts };
1900
+ }
1901
+
1902
+ /**
1903
+ * The only writer of `serviceAccounts`.
1904
+ *
1905
+ * Accounts and the flat keys they project into are written in one replacement,
1906
+ * so the two are equal after every write this function makes. Anything that
1907
+ * differs later was written past this function, and is by construction the
1908
+ * newer of the two.
1909
+ *
1910
+ * @param {string} prefsFile
1911
+ * @param {(accounts: object[], prefs: object) => object[]} mutate
1912
+ */
1913
+ export function writeAccounts(prefsFile, mutate) {
1914
+ return withFileLockSync(
1915
+ prefsFile,
1916
+ () => {
1917
+ const r = readPrefsFile(prefsFile);
1918
+ if (r.status === "unreadable" || r.status === "invalid") {
1919
+ throw new Error(
1920
+ `refusing to write over a preferences file that does not parse: ${prefsFile}`,
1921
+ );
1922
+ }
1923
+ const prefs = r.status === "ok" && r.prefs != null ? r.prefs : {};
1924
+ prefs.global ??= {};
1925
+ const next = mutate(effectiveAccounts(prefs).accounts, prefs);
1926
+ const check = validateAccounts(next, prefs.global.identities ?? []);
1927
+ if (!check.ok) {
1928
+ throw new Error(
1929
+ "refusing to write accounts that do not hold together: " +
1930
+ check.problems.map((p) => `${p.id}: ${p.problem}`).join("; "),
1931
+ );
1932
+ }
1933
+ prefs.global.serviceAccounts = next;
1934
+ prefs.global.identities = withIdentityIds(prefs.global.identities ?? []);
1935
+ const legacy = projectLegacy(next);
1936
+ prefs.global.keychainMapping = { ...prefs.global.keychainMapping, ...legacy.keychainMapping };
1937
+ prefs.global.hosts = { ...prefs.global.hosts, ...legacy.hosts };
1938
+ if (Object.keys(legacy.credentialHosts).length) {
1939
+ prefs.global.credentialHosts = {
1940
+ ...prefs.global.credentialHosts,
1941
+ ...legacy.credentialHosts,
1942
+ };
1943
+ }
1944
+ writeJsonAtomicSync(prefsFile, prefs, { mode: 0o600, followSymlink: true });
1945
+ return next;
1946
+ },
1947
+ { timeoutMs: lockTimeoutFrom(process.env) },
1948
+ );
1949
+ }
1950
+
1951
+ // --- Command line ----------------------------------------------------------
1952
+ // Shell callers reach the same decisions through `service-account.sh`, which
1953
+ // execs this file. One implementation, two front doors: a second resolver
1954
+ // written in shell is a second set of rules to keep in step, and the rule that
1955
+ // matters here is the one that refuses.
1956
+
1957
+ /** `--flag value` pairs into an object, with `-` turned into camelCase. */
1958
+ function parseArgv(argv) {
1959
+ const out = {};
1960
+ for (let i = 0; i < argv.length; i++) {
1961
+ if (!argv[i].startsWith("--")) continue;
1962
+ const name = argv[i].slice(2).replace(/-([a-z])/g, (_, c) => c.toUpperCase());
1963
+ const value = argv[i + 1];
1964
+ if (value === undefined || value.startsWith("--")) {
1965
+ out[name] = true;
1966
+ continue;
1967
+ }
1968
+ out[name] = value;
1969
+ i++;
1970
+ }
1971
+ return out;
1972
+ }
1973
+
1974
+ const PUBLIC_ACCOUNT_FIELDS = [
1975
+ "id",
1976
+ "service",
1977
+ "label",
1978
+ "hosts",
1979
+ "baseUrl",
1980
+ "scope",
1981
+ "identityId",
1982
+ "default",
1983
+ "slots",
1984
+ ];
1985
+
1986
+ /** An account as it may be printed: never its secrets, which are item names. */
1987
+ function publicAccount(account) {
1988
+ const out = {};
1989
+ for (const field of PUBLIC_ACCOUNT_FIELDS) {
1990
+ if (account[field] !== undefined) out[field] = account[field];
1991
+ }
1992
+ out.identityId ??= null;
1993
+ out.default ??= false;
1994
+ return out;
1995
+ }
1996
+
1997
+ function cliMain(argv) {
1998
+ const [command, ...rest] = argv;
1999
+ const a = parseArgv(rest);
2000
+ const request = {
2001
+ service: a.service,
2002
+ accountId: a.account,
2003
+ url: a.url,
2004
+ host: a.host,
2005
+ environment: a.environment,
2006
+ projectId: a.projectId,
2007
+ owner: a.owner,
2008
+ identityId: a.identity,
2009
+ itemName: a.item,
2010
+ slot: a.slot,
2011
+ };
2012
+
2013
+ const fail = (answer) => {
2014
+ process.stderr.write(JSON.stringify(answer) + "\n");
2015
+ return EXIT[answer.reason] ?? 3;
2016
+ };
2017
+
2018
+ switch (command) {
2019
+ case "select": {
2020
+ const answer = selectAccount(request);
2021
+ if (!answer.ok) return fail(answer);
2022
+ process.stdout.write(
2023
+ JSON.stringify({ ...answer, account: publicAccount(answer.account) }) + "\n",
2024
+ );
2025
+ return 0;
2026
+ }
2027
+ case "token": {
2028
+ const answer = resolveSecret(request);
2029
+ if (!answer.ok) return fail(answer);
2030
+ process.stdout.write(answer.secret);
2031
+ return 0;
2032
+ }
2033
+ case "curl-config": {
2034
+ const answer = curlConfig({ ...request, scheme: a.scheme });
2035
+ if (!answer.ok) return fail(answer);
2036
+ process.stdout.write(answer.config);
2037
+ return 0;
2038
+ }
2039
+ case "item-ref": {
2040
+ const answer = resolveItemRef(request);
2041
+ if (!answer.ok) return fail(answer);
2042
+ process.stdout.write(
2043
+ JSON.stringify({
2044
+ ok: true,
2045
+ account: publicAccount(answer.account),
2046
+ slot: answer.slot,
2047
+ itemName: answer.itemName,
2048
+ }) + "\n",
2049
+ );
2050
+ return 0;
2051
+ }
2052
+ case "items": {
2053
+ const loaded = loadFor({});
2054
+ if (loaded.status === "unreadable" || loaded.status === "invalid") {
2055
+ return fail(
2056
+ no(
2057
+ "prefs-unreadable",
2058
+ null,
2059
+ "The preferences file could not be read.",
2060
+ `Fix or restore ${loaded.file}.`,
2061
+ ),
2062
+ );
2063
+ }
2064
+ const items = itemNames(loaded.prefs ?? {}).filter(
2065
+ (x) => !a.service || x.service === a.service,
2066
+ );
2067
+ process.stdout.write(JSON.stringify({ ok: true, items }) + "\n");
2068
+ return 0;
2069
+ }
2070
+ case "list": {
2071
+ const loaded = loadFor({});
2072
+ if (loaded.status === "unreadable" || loaded.status === "invalid") {
2073
+ return fail(
2074
+ no(
2075
+ "prefs-unreadable",
2076
+ null,
2077
+ "The preferences file could not be read.",
2078
+ `Fix or restore ${loaded.file}.`,
2079
+ ),
2080
+ );
2081
+ }
2082
+ const { accounts, source, notes } = effectiveAccounts(loaded.prefs ?? {});
2083
+ const shown = accounts
2084
+ .filter((x) => !a.service || x.service === a.service)
2085
+ .map((x) =>
2086
+ publicAccount({
2087
+ ...x,
2088
+ hosts: hostsOf(x, { usageEndpoint: loaded.prefs?.global?.usageLog?.endpoint }),
2089
+ slots: SERVICES[x.service]?.slots ?? [],
2090
+ }),
2091
+ );
2092
+ process.stdout.write(JSON.stringify({ ok: true, source, notes, accounts: shown }) + "\n");
2093
+ return 0;
2094
+ }
2095
+ case "check": {
2096
+ const loaded = loadFor({});
2097
+ if (loaded.status === "unreadable" || loaded.status === "invalid") {
2098
+ return fail(
2099
+ no(
2100
+ "prefs-unreadable",
2101
+ null,
2102
+ "The preferences file could not be read.",
2103
+ `Fix or restore ${loaded.file}.`,
2104
+ ),
2105
+ );
2106
+ }
2107
+ const { accounts, source, notes } = effectiveAccounts(loaded.prefs ?? {});
2108
+ const result = validateAccounts(accounts, loaded.prefs?.global?.identities ?? []);
2109
+ process.stdout.write(
2110
+ JSON.stringify({ ...result, source, notes, count: accounts.length }) + "\n",
2111
+ );
2112
+ return result.ok ? 0 : EXIT["invalid-config"];
2113
+ }
2114
+ default:
2115
+ process.stderr.write(
2116
+ JSON.stringify(
2117
+ no(
2118
+ "invalid-request",
2119
+ null,
2120
+ `No sub-command named ${command ?? "(none)"}.`,
2121
+ "Use one of: select, token, curl-config, item-ref, items, list, check.",
2122
+ ),
2123
+ ) + "\n",
2124
+ );
2125
+ return EXIT["invalid-request"];
2126
+ }
2127
+ }
2128
+
2129
+ if (process.argv[1] && process.argv[1].endsWith("service-account.mjs")) {
2130
+ process.exitCode = cliMain(process.argv.slice(2));
2131
+ }