passport-bridge 0.33.0 → 0.35.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 (94) hide show
  1. package/README.md +27 -3
  2. package/dist/cliArgs.d.ts +1 -1
  3. package/dist/cliArgs.js +5 -1
  4. package/dist/cliAutopilot.js +2 -1
  5. package/dist/cliAutopilotPolicy.d.ts +18 -2
  6. package/dist/cliAutopilotPolicy.js +32 -9
  7. package/dist/cliExec.d.ts +3 -2
  8. package/dist/cliExec.js +52 -32
  9. package/dist/cliGitCredential.d.ts +36 -0
  10. package/dist/cliGitCredential.js +432 -0
  11. package/dist/cliHook.js +10 -13
  12. package/dist/cliHookAfter.d.ts +2 -0
  13. package/dist/cliHookAfter.js +8 -1
  14. package/dist/cliHookDecide.d.ts +7 -23
  15. package/dist/cliHookDecide.js +117 -87
  16. package/dist/cliHookDeliver.js +5 -2
  17. package/dist/cliHookEarly.d.ts +10 -0
  18. package/dist/cliHookEarly.js +8 -0
  19. package/dist/cliHookRewrite.d.ts +31 -5
  20. package/dist/cliHookRewrite.js +51 -9
  21. package/dist/cliHookServerDecision.d.ts +30 -0
  22. package/dist/cliHookServerDecision.js +85 -0
  23. package/dist/cliKeys.js +17 -12
  24. package/dist/cliKeysShim.js +2 -1
  25. package/dist/cliMain.js +5 -1
  26. package/dist/cliOutput.js +6 -0
  27. package/dist/cliPolicyV2.js +32 -2
  28. package/dist/cliStatus.js +6 -1
  29. package/dist/cliWorkWords.js +1 -1
  30. package/dist/completion.js +2 -0
  31. package/dist/controlPlane.generated.d.ts +434 -0
  32. package/dist/controlPlane.generated.js +134 -0
  33. package/dist/controlPlaneExec.d.ts +68 -0
  34. package/dist/controlPlaneExec.js +135 -0
  35. package/dist/controlPlaneGithub.generated.d.ts +45 -0
  36. package/dist/controlPlaneGithub.generated.js +94 -0
  37. package/dist/controlPlaneGithubApi.generated.d.ts +15 -0
  38. package/dist/controlPlaneGithubApi.generated.js +117 -0
  39. package/dist/controlPlaneGithubCatalog.generated.d.ts +127 -0
  40. package/dist/controlPlaneGithubCatalog.generated.js +253 -0
  41. package/dist/controlPlaneGithubCli.generated.d.ts +94 -0
  42. package/dist/controlPlaneGithubCli.generated.js +287 -0
  43. package/dist/controlPlaneGithubWebhook.generated.d.ts +30 -0
  44. package/dist/controlPlaneGithubWebhook.generated.js +105 -0
  45. package/dist/controlPlaneGuard.d.ts +147 -0
  46. package/dist/controlPlaneGuard.js +277 -0
  47. package/dist/controlPlaneLate.d.ts +30 -0
  48. package/dist/controlPlaneLate.js +72 -0
  49. package/dist/controlPlaneLateHold.d.ts +20 -0
  50. package/dist/controlPlaneLateHold.js +101 -0
  51. package/dist/controlPlaneRailway.generated.d.ts +30 -0
  52. package/dist/controlPlaneRailway.generated.js +217 -0
  53. package/dist/controlPlaneRailwayCli.generated.d.ts +11 -0
  54. package/dist/controlPlaneRailwayCli.generated.js +436 -0
  55. package/dist/controlPlaneRailwayGuard.d.ts +172 -0
  56. package/dist/controlPlaneRailwayGuard.js +527 -0
  57. package/dist/controlPlaneRailwayModel.generated.d.ts +189 -0
  58. package/dist/controlPlaneRailwayModel.generated.js +355 -0
  59. package/dist/controlPlaneRailwayReach.d.ts +43 -0
  60. package/dist/controlPlaneRailwayReach.js +163 -0
  61. package/dist/credentialStorage.d.ts +3 -0
  62. package/dist/credentialStorage.js +13 -2
  63. package/dist/credentials.js +60 -6
  64. package/dist/designTokens.generated.d.ts +16 -0
  65. package/dist/designTokens.generated.js +11 -0
  66. package/dist/envLinksHosting.d.ts +16 -1
  67. package/dist/envLinksHosting.js +60 -21
  68. package/dist/execGit.d.ts +16 -0
  69. package/dist/execGit.js +31 -0
  70. package/dist/execShims.d.ts +12 -1
  71. package/dist/execShims.js +87 -6
  72. package/dist/gitCredentialSetup.d.ts +91 -0
  73. package/dist/gitCredentialSetup.js +338 -0
  74. package/dist/gitInvocation.d.ts +41 -0
  75. package/dist/gitInvocation.js +207 -0
  76. package/dist/gitPush.d.ts +27 -0
  77. package/dist/gitPush.js +172 -0
  78. package/dist/gitPushDecisions.d.ts +6 -0
  79. package/dist/gitPushDecisions.js +69 -0
  80. package/dist/gitReadOnly.d.ts +10 -0
  81. package/dist/gitReadOnly.js +57 -0
  82. package/dist/initAutopilotStep.d.ts +2 -1
  83. package/dist/initAutopilotStep.js +19 -7
  84. package/dist/initKeysStep.d.ts +6 -0
  85. package/dist/initKeysStep.js +43 -3
  86. package/dist/initPlan.js +7 -0
  87. package/dist/pluginPin.d.ts +1 -1
  88. package/dist/pluginPin.js +1 -1
  89. package/dist/railwayDecisions.d.ts +12 -0
  90. package/dist/railwayDecisions.js +112 -0
  91. package/dist/version.d.ts +1 -1
  92. package/dist/version.js +1 -1
  93. package/npm-shrinkwrap.json +2 -2
  94. package/package.json +1 -1
@@ -0,0 +1,432 @@
1
+ /**
2
+ * `passport git-credential`: git's credential helper for github.com, so a push
3
+ * is made with a token Passport issued and GitHub reports it as Passport's
4
+ * App: through Passport in the control plane.
5
+ *
6
+ * git push → git asks `passport git-credential get` (protocol, host, path)
7
+ * → which git command asked (gitInvocation.ts, read here, never sent)
8
+ * → a fetch: POST /api/my/github/git-credential {repo, access: read}
9
+ * → a push: every ref it moves, resolved as git will (gitPush.ts); the
10
+ * guard's decisions for exactly this push when it left them
11
+ * (gitPushDecisions.ts), else POST /api/cp/decide for each ref once
12
+ * Passport says it would issue a push token (409 "undecided"); a block
13
+ * on any ref prints the reason and `quit=1`, so git stops and never
14
+ * falls back to a personal sign-in; then the token request with the
15
+ * decision ids, which Passport spends once
16
+ * → username=x-access-token, password=<token>, password_expiry_utc
17
+ *
18
+ * Fail open, like the guard: a repository the App doesn't cover, Passport not
19
+ * answering within 5 seconds in all (1 second at most for each decision), a
20
+ * push it can't resolve, or a refusal (read-only access, an App without
21
+ * Contents write, an agent key) goes to the helpers git used before setup
22
+ * (gitCredentialSetup.ts), with one line on stderr for a push, so it works and
23
+ * counts as outside Passport. A write token exists only for a push Passport
24
+ * decided; `quit=1` only when Passport answered block. The token goes to git
25
+ * on stdout only: never to disk, a log or stderr.
26
+ *
27
+ * passport git-credential setup [--remove] point git at Passport for github.com (or undo it)
28
+ */
29
+ import { spawn } from "node:child_process";
30
+ import { askControlPlane } from "./controlPlaneGuard.js";
31
+ import { accessCachePath, cachedAccessApi } from "./accessTokenCache.js";
32
+ import { bool } from "./cliArgs.js";
33
+ import { memberApi } from "./cliClient.js";
34
+ import { callerFrom, failure, readBoundedJson, resolveCliAuth, sanitize, timeoutMs } from "./cliSupport.js";
35
+ import { defaultPassportCommand } from "./execShims.js";
36
+ import { askingGitCommand, execGitCommand, isPush } from "./gitInvocation.js";
37
+ import { MAX_PUSH_REFS, planKey, planPush } from "./gitPush.js";
38
+ import { takePushDecisions } from "./gitPushDecisions.js";
39
+ import { installGitCredential, readGitCredentialState, removeGitCredential } from "./gitCredentialSetup.js";
40
+ export const GIT_CREDENTIAL_PATH = "/api/my/github/git-credential";
41
+ export const TOKEN_USERNAME = "x-access-token";
42
+ const REPO_PATH = /^([A-Za-z0-9_.-]{1,100})\/([A-Za-z0-9_.-]{1,100}?)(?:\.git)?\/?$/;
43
+ const TOKEN = /^[A-Za-z0-9_.-]{1,512}$/;
44
+ const MAX_INPUT_BYTES = 64 * 1024;
45
+ /** git waits on us for every fetch and push: past this in all, the push uses this computer's own sign-in. */
46
+ export const MINT_TIMEOUT_MS = 5_000;
47
+ /** Each decision gets at most this long, within what's left of the whole. */
48
+ export const DECIDE_TIMEOUT_MS = 1_000;
49
+ export function parseCredentialRequest(text) {
50
+ const fields = new Map();
51
+ for (const line of text.split("\n")) {
52
+ if (line === "")
53
+ break;
54
+ const equals = line.indexOf("=");
55
+ if (equals > 0)
56
+ fields.set(line.slice(0, equals), line.slice(equals + 1));
57
+ }
58
+ return fields;
59
+ }
60
+ async function readInput(runtime) {
61
+ if (!runtime.stdin)
62
+ return "";
63
+ let text = "";
64
+ for await (const chunk of runtime.stdin) {
65
+ text += typeof chunk === "string" ? chunk : Buffer.from(chunk).toString("utf8");
66
+ if (text.length > MAX_INPUT_BYTES)
67
+ break;
68
+ if (/\n\n|^\n/.test(text))
69
+ break;
70
+ }
71
+ return text;
72
+ }
73
+ /** owner/name for https://github.com/<owner>/<name>(.git), else null. */
74
+ export function githubRepoOf(request) {
75
+ if (request.get("protocol") !== "https" || request.get("host")?.toLowerCase() !== "github.com")
76
+ return null;
77
+ const match = (request.get("path") ?? "").match(REPO_PATH);
78
+ return match ? `${match[1]}/${match[2]}` : null;
79
+ }
80
+ /* ------------------------------- fallback ------------------------------- */
81
+ /** How git runs a helper string (gitcredentials(7)): `!cmd` through the shell, an absolute path as is, else `git credential-<name>`. */
82
+ export function fallbackCommand(helper, operation) {
83
+ if (helper.startsWith("!"))
84
+ return `${helper.slice(1)} ${operation}`;
85
+ if (helper.startsWith("/"))
86
+ return `${helper} ${operation}`;
87
+ return `git credential-${helper} ${operation}`;
88
+ }
89
+ const runFallback = (helper, operation, input, env) => new Promise((resolve) => {
90
+ const child = spawn("/bin/sh", ["-c", fallbackCommand(helper, operation)], {
91
+ env: env,
92
+ stdio: ["pipe", "pipe", "inherit"]
93
+ });
94
+ let out = "";
95
+ const timer = setTimeout(() => child.kill(), 30_000);
96
+ child.stdout.on("data", (chunk) => {
97
+ if (out.length < MAX_INPUT_BYTES)
98
+ out += chunk.toString("utf8");
99
+ });
100
+ child.on("error", () => resolve(""));
101
+ child.on("close", () => {
102
+ clearTimeout(timer);
103
+ resolve(out);
104
+ });
105
+ // A helper that answers without reading the request closes its stdin first: EPIPE, not a crash.
106
+ child.stdin.on("error", () => undefined);
107
+ child.stdin.end(input);
108
+ });
109
+ /** Ask the helpers git used before setup, in order, as git would; the first that answers wins. */
110
+ async function delegate(operation, input, runtime, deps) {
111
+ const helpers = readGitCredentialState()?.fallback ?? [];
112
+ const run = deps.fallback ?? runFallback;
113
+ // The path is there for Passport (useHttpPath); the earlier helpers stored their
114
+ // passwords per host, so they get the request as git sent it before setup.
115
+ input = input
116
+ .split("\n")
117
+ .filter((line) => !line.startsWith("path="))
118
+ .join("\n");
119
+ if (operation !== "get") {
120
+ for (const helper of helpers)
121
+ await run(helper, operation, input, runtime.env);
122
+ return "";
123
+ }
124
+ for (const helper of helpers) {
125
+ const answer = await run(helper, operation, input, runtime.env);
126
+ if (/^(?:password|quit)=/m.test(answer))
127
+ return answer;
128
+ }
129
+ return "";
130
+ }
131
+ /**
132
+ * `work` with a signal aborted after `ms`. The timer holds the process open
133
+ * (`AbortSignal.timeout`'s doesn't), so git always gets an answer by the
134
+ * deadline even when nothing else is pending; cleared once `work` settles.
135
+ */
136
+ async function within(ms, signal, work) {
137
+ const controller = new AbortController();
138
+ const timer = setTimeout(() => controller.abort(), Math.max(1, Math.ceil(ms)));
139
+ try {
140
+ return await work(AbortSignal.any([signal, controller.signal]));
141
+ }
142
+ finally {
143
+ clearTimeout(timer);
144
+ }
145
+ }
146
+ async function mint(api, repo, access, signal, timeout, extra = {}) {
147
+ const { decisionIds, asker } = extra;
148
+ if (timeout <= 0)
149
+ return { kind: "unreachable" };
150
+ let response;
151
+ try {
152
+ response = await within(timeout, signal, (bounded) => api(GIT_CREDENTIAL_PATH, {
153
+ method: "POST",
154
+ headers: { "content-type": "application/json", accept: "application/json" },
155
+ body: JSON.stringify({
156
+ repo,
157
+ access,
158
+ ...(decisionIds?.length ? { decisionIds } : {}),
159
+ ...(asker ? { asker } : {})
160
+ }),
161
+ signal: bounded
162
+ }));
163
+ }
164
+ catch {
165
+ return { kind: "unreachable" };
166
+ }
167
+ let body = {};
168
+ try {
169
+ body = await readBoundedJson(response);
170
+ }
171
+ catch {
172
+ body = {};
173
+ }
174
+ if (response.ok) {
175
+ const { token, expiresAt, credentialId } = body;
176
+ if (typeof token === "string" &&
177
+ TOKEN.test(token) &&
178
+ typeof expiresAt === "number" &&
179
+ typeof credentialId === "string") {
180
+ return { kind: "token", minted: { token, expiresAt, credentialId } };
181
+ }
182
+ return { kind: "refused", code: "unavailable", message: "Passport returned a token git can't use." };
183
+ }
184
+ if (response.status === 404 && body.code === undefined) {
185
+ // An older Passport without this route: the computer's own sign-in, as before setup.
186
+ return { kind: "refused", code: "not_covered", message: "" };
187
+ }
188
+ if (response.status === 401)
189
+ return { kind: "refused", code: "signed_out", message: "Passport refused this sign-in. Run passport login." };
190
+ if (response.status >= 500)
191
+ return { kind: "unreachable" };
192
+ return {
193
+ kind: "refused",
194
+ code: typeof body.code === "string" ? body.code : "refused",
195
+ message: typeof body.error === "string" ? sanitize(body.error) : "Passport didn't issue a GitHub token."
196
+ };
197
+ }
198
+ function answer(minted) {
199
+ return [
200
+ `username=${TOKEN_USERNAME}`,
201
+ `password=${minted.token}`,
202
+ `password_expiry_utc=${Math.floor(minted.expiresAt / 1000)}`,
203
+ ""
204
+ ].join("\n");
205
+ }
206
+ /**
207
+ * Passport's API as this sign-in. `budgetMs`: what's left of git's deadline,
208
+ * which bounds the sign-in exchange too (git waits on it like any request).
209
+ */
210
+ function apiFor(args, runtime, budgetMs = 10_000) {
211
+ const auth = resolveCliAuth(args, runtime.env);
212
+ if (auth.kind === "profile") {
213
+ accessCachePath(auth.profile);
214
+ const budget = Math.max(1, Math.ceil(Math.min(timeoutMs(args), 10_000, budgetMs)));
215
+ return cachedAccessApi(auth.profile, { endpoint: auth.endpoint, refreshToken: auth.refreshToken }, AbortSignal.any([runtime.signal, AbortSignal.timeout(budget)]), fetch, budget);
216
+ }
217
+ const client = memberApi({
218
+ auth,
219
+ caller: callerFrom(args, runtime.env),
220
+ timeoutMs: timeoutMs(args),
221
+ signal: runtime.signal
222
+ });
223
+ return Promise.resolve(client.fetchApi);
224
+ }
225
+ async function get(args, runtime, deps, input) {
226
+ const clock = deps.clock ?? (() => performance.now());
227
+ // One deadline for everything git waits on: the token, the decisions, the token again.
228
+ const deadline = clock() + (deps.mintTimeoutMs ?? MINT_TIMEOUT_MS);
229
+ const left = () => deadline - clock();
230
+ const request = parseCredentialRequest(input);
231
+ const repo = githubRepoOf(request);
232
+ if (!repo)
233
+ return delegate("get", input, runtime, deps);
234
+ // What the parents say; else what `passport exec -- git …` said it ran.
235
+ const asking = (deps.asking ? deps.asking() : askingGitCommand(process.ppid, deps.readProcess)) ?? execGitCommand(runtime.env);
236
+ // Not knowing whether it's a push (a GUI running git its own way, an alias to a
237
+ // script, or the read ran out of time): a read-only token, so a fetch works and
238
+ // GitHub refuses a push, which never goes outside Passport unseen.
239
+ if (asking === null)
240
+ return readOnly(args, runtime, deps, input, repo, left);
241
+ const push = isPush(asking);
242
+ // Fail open, as the guard does: anything short of an answer leaves the push to
243
+ // this computer's own sign-in, which GitHub reports as the person (outside).
244
+ const ownSignIn = (why) => {
245
+ if (push)
246
+ runtime.stderr.write(`passport: ${why} git uses your own GitHub sign-in, outside Passport.\n`);
247
+ return delegate("get", input, runtime, deps);
248
+ };
249
+ let api;
250
+ try {
251
+ api = deps.api ?? (await apiFor(args, runtime, left()));
252
+ }
253
+ catch {
254
+ return ownSignIn("Not signed in to Passport (run passport login), so");
255
+ }
256
+ const refused = (got) => {
257
+ if (got.kind === "unreachable")
258
+ return ownSignIn("Passport didn't answer in time, so");
259
+ if (got.code === "not_covered")
260
+ return delegate("get", input, runtime, deps);
261
+ return ownSignIn(`${got.message.replace(/\.$/, "")}. So`);
262
+ };
263
+ if (!push) {
264
+ const got = await mint(api, repo, "read", runtime.signal, left());
265
+ return got.kind === "token" ? answer(got.minted) : refused(got);
266
+ }
267
+ // A push: what it changes, ref by ref. Only the classification leaves this computer.
268
+ const [owner, name] = repo.split("/");
269
+ const plan = planPush(asking, {
270
+ cwd: deps.cwd ?? process.cwd(),
271
+ env: runtime.env,
272
+ repo: { owner, repo: name },
273
+ ...(deps.run ? { run: deps.run } : {})
274
+ });
275
+ if (!plan)
276
+ return ownSignIn("Passport can't tell what this push changes, so");
277
+ const key = planKey(plan);
278
+ const fromGuard = takePushDecisions(key);
279
+ let got = await mint(api, repo, "write", runtime.signal, left(), { decisionIds: fromGuard ?? undefined });
280
+ if (got.kind !== "refused" || got.code !== "undecided")
281
+ return got.kind === "token" ? answer(got.minted) : refused(got);
282
+ // Passport would issue a push token once it decides the push: every ref, and
283
+ // a block on any stops git here.
284
+ const decisionIds = [];
285
+ for (const classification of plan.classifications.slice(0, MAX_PUSH_REFS)) {
286
+ const wait = Math.min(deps.decideTimeoutMs ?? DECIDE_TIMEOUT_MS, left());
287
+ if (wait <= 0)
288
+ return ownSignIn("Passport couldn't decide this push in time, so");
289
+ const decided = await within(wait, runtime.signal, (bounded) => askControlPlane(api, classification, {}, bounded));
290
+ if (decided.kind === "block") {
291
+ runtime.stderr.write(`passport: ${decided.message.replace(/\s*\n\s*/g, " ")}\n`);
292
+ // quit=1: git stops here, without trying another helper or asking for a password.
293
+ return "quit=1\n";
294
+ }
295
+ if (decided.kind !== "allow")
296
+ return ownSignIn("Passport couldn't decide this push in time, so");
297
+ if (!decided.decisionId)
298
+ return ownSignIn("Passport didn't record a decision for this push, so");
299
+ decisionIds.push(decided.decisionId);
300
+ }
301
+ got = await mint(api, repo, "write", runtime.signal, left(), { decisionIds });
302
+ return got.kind === "token" ? answer(got.minted) : refused(got);
303
+ }
304
+ /**
305
+ * The asker is unknown: a read-only token, which Passport records as an
306
+ * event (a push with it would fail, so nothing ran outside Passport). git's
307
+ * output says so, and so does the after-hook if GitHub refuses a push. Fails
308
+ * open as before only when Passport can't answer or doesn't cover the
309
+ * repository.
310
+ */
311
+ async function readOnly(args, runtime, deps, input, repo, left) {
312
+ let api;
313
+ try {
314
+ api = deps.api ?? (await apiFor(args, runtime, left()));
315
+ }
316
+ catch {
317
+ return delegate("get", input, runtime, deps);
318
+ }
319
+ const got = await mint(api, repo, "read", runtime.signal, left(), { asker: "unknown" });
320
+ if (got.kind !== "token")
321
+ return delegate("get", input, runtime, deps);
322
+ (await import("./gitReadOnly.js")).noteReadOnly(repo);
323
+ runtime.stderr.write(`passport: Passport couldn't tell which git command asked, so git has a read-only token for ${repo}. If this is a push, GitHub refuses it: run it again, or as \`passport exec -- git push …\`.\n`);
324
+ return answer(got.minted);
325
+ }
326
+ /* -------------------------------- setup --------------------------------- */
327
+ /** The accounts the App covers, from the keys view; none when Passport can't be asked. */
328
+ export async function coveredOwners(api, signal) {
329
+ if (!api)
330
+ return [];
331
+ try {
332
+ const response = await api("/api/my/keys", {
333
+ headers: { accept: "application/json" },
334
+ signal: AbortSignal.any([signal, AbortSignal.timeout(10_000)])
335
+ });
336
+ if (!response.ok)
337
+ return [];
338
+ const view = await readBoundedJson(response);
339
+ const owners = view.githubApp?.owners;
340
+ return Array.isArray(owners) ? owners.filter((owner) => typeof owner === "string") : [];
341
+ }
342
+ catch {
343
+ return [];
344
+ }
345
+ }
346
+ async function setup(args, runtime, deps) {
347
+ const env = runtime.env;
348
+ if (bool(args, "remove")) {
349
+ const removed = removeGitCredential({ env, ...(deps.run ? { run: deps.run } : {}) });
350
+ return {
351
+ json: { removed: removed.removed, file: removed.file },
352
+ human: removed.removed
353
+ ? `✓ git uses your own GitHub sign-in again (${removed.file}).`
354
+ : "Passport wasn't set up for git on this computer. Nothing changed."
355
+ };
356
+ }
357
+ let api = deps.api;
358
+ try {
359
+ api ??= await apiFor(args, runtime);
360
+ }
361
+ catch {
362
+ api = undefined;
363
+ }
364
+ const owners = await coveredOwners(api, runtime.signal);
365
+ const result = installGitCredential({
366
+ command: deps.command ?? defaultPassportCommand(),
367
+ env,
368
+ owners,
369
+ ...(deps.run ? { run: deps.run } : {}),
370
+ ...(deps.platform ? { platform: deps.platform } : {})
371
+ });
372
+ if (!result.ok) {
373
+ const messages = {
374
+ no_git: "git isn't installed here, so there's nothing to set up.",
375
+ no_launcher: "git needs a passport it can run every time. Run passport init first, then this again.",
376
+ write_failed: "Passport couldn't change your git config. Nothing was left half done; try again.",
377
+ windows: "git through Passport isn't available on Windows yet: it would stop Git Credential Manager answering for github.com. Nothing changed."
378
+ };
379
+ return failure(messages[result.reason], result.reason === "write_failed" ? 1 : 6, result.reason);
380
+ }
381
+ const lines = [
382
+ result.changed
383
+ ? `✓ git sends github.com to Passport: pushes use a token from Passport's GitHub App (${result.file}).`
384
+ : "Already set up: git sends github.com to Passport.",
385
+ result.fallback.length
386
+ ? ` Repositories the App doesn't cover keep using ${result.fallback.join(", ")}.`
387
+ : " Repositories the App doesn't cover will ask for your GitHub sign-in.",
388
+ ...(result.sshOwners.length
389
+ ? [
390
+ ` Pushes from SSH remotes of ${result.sshOwners.join(", ")} go over HTTPS so Passport sees them; fetches stay on SSH.`
391
+ ]
392
+ : []),
393
+ ...(result.backup ? [` Your old git config is in ${result.backup}.`] : []),
394
+ " Undo: passport git-credential setup --remove"
395
+ ];
396
+ return {
397
+ json: {
398
+ changed: result.changed,
399
+ file: result.file,
400
+ fallback: result.fallback,
401
+ sshOwners: result.sshOwners
402
+ },
403
+ human: lines.join("\n")
404
+ };
405
+ }
406
+ /* -------------------------------- entry --------------------------------- */
407
+ export async function gitCredential(args, runtime, deps = {}) {
408
+ const [operation] = args.positionals;
409
+ if (operation === "setup")
410
+ return setup(args, runtime, deps);
411
+ if (operation !== "get" && operation !== "store" && operation !== "erase") {
412
+ return failure(`Unknown: ${sanitize(operation ?? "")}. git runs passport git-credential get|store|erase; you run passport git-credential setup.`, 6, "usage");
413
+ }
414
+ const input = await readInput(runtime);
415
+ let out = "";
416
+ try {
417
+ if (operation === "get")
418
+ out = await get(args, runtime, deps, input);
419
+ // A token Passport issued is never stored: git would offer an expired one next time.
420
+ else if (parseCredentialRequest(input).get("username") !== TOKEN_USERNAME) {
421
+ out = await delegate(operation, input, runtime, deps);
422
+ }
423
+ }
424
+ catch (error) {
425
+ if (runtime.signal.aborted)
426
+ throw error;
427
+ // Fail open: nothing printed, so git asks the next helper or the person.
428
+ runtime.stderr.write("passport: Passport couldn't answer git just now.\n");
429
+ out = "";
430
+ }
431
+ return { json: {}, human: out, raw: true, essential: true };
432
+ }
package/dist/cliHook.js CHANGED
@@ -271,6 +271,9 @@ async function runAudit(args, runtime, deps) {
271
271
  const profile = localProfile(args, runtime.env);
272
272
  const policy = profile ? readCliPolicy(profile) : null;
273
273
  const now = (deps.now ?? Date.now)();
274
+ // It ran: a decision the guard couldn't wait for may still have been recorded as a block (controlPlaneLateHold).
275
+ if (profile)
276
+ await (await import("./controlPlaneLateHold.js")).releaseLate(profile, sessionOfInput(input), text(input.tool_use_id, 128), now);
274
277
  const declared = value(args, "client");
275
278
  const runtimeName = detectRuntime(input, runtime.env, declared);
276
279
  const after = await import("./cliHookAfter.js");
@@ -427,17 +430,6 @@ function startOf(deps) {
427
430
  const now = (deps.now ?? Date.now)();
428
431
  return deps.now ? now : Math.min(now, Math.round(performance.timeOrigin));
429
432
  }
430
- /** Before the guard decides as usual: a stuck agent's answer (`cliHookStuck.ts`, read only when it
431
- * can matter), then the sign-in and rewrite answers. */
432
- async function earlyAnswer(input, stuck, rewrite) {
433
- const sessionId = sessionOfInput(input);
434
- const claudeCode = stuck.client === "claude-code" && !stuck.cursorImported;
435
- const retryLoops = stuck.policy?.version === 2 && stuck.policy.autopilot.retryLoops === true;
436
- const told = sessionId && (retryLoops || !claudeCode)
437
- ? (await import("./cliHookStuck.js")).stuckAnswer({ ...stuck, sessionId, claudeCode })
438
- : null;
439
- return told ?? (await import("./cliHookRewrite.js")).guardEarlyAnswer(rewrite);
440
- }
441
433
  async function runGuard(args, runtime, deps) {
442
434
  if (runtime.env.PASSPORT_HOOK_DISABLED === "1")
443
435
  return;
@@ -476,7 +468,7 @@ async function runGuard(args, runtime, deps) {
476
468
  // A retry loop the person asked to stop, or a sign-in that expired here (Codex, Cursor); then a
477
469
  // sign-in for a CLI whose key Passport holds (any agent), or the rewrite to exec (Claude Code).
478
470
  const rewritten = profile
479
- ? await earlyAnswer(input, {
471
+ ? await (await import("./cliHookEarly.js")).earlyAnswer(sessionOfInput(input), {
480
472
  ...{ command: event.command, cursorImported: Boolean(event.cursorImported), client, mode, policy, decision },
481
473
  ...{ findings: line.findings, runtimeName: detectRuntime(input, runtime.env, declared), now: clock() }
482
474
  }, {
@@ -486,7 +478,11 @@ async function runGuard(args, runtime, deps) {
486
478
  named: value(args, "profile"),
487
479
  ...{ decision, profile, machine, env: runtime.env, invocation: deps.invocation, client, canReport, policy },
488
480
  cursorImported: Boolean(event.cursorImported),
489
- attended: mode === "attended"
481
+ attended: mode === "attended",
482
+ ask: {
483
+ openApi: () => profileApi(profile, budget, deps.fetch ?? fetch).catch(() => null),
484
+ ...{ budget, deadline: startedAt + HOOK_BUDGET_MS - PRINT_RESERVE_MS, now: clock }
485
+ }
490
486
  })
491
487
  : null;
492
488
  if (rewritten)
@@ -506,6 +502,7 @@ async function runGuard(args, runtime, deps) {
506
502
  report: base ?? context(input, runtime.env, declared),
507
503
  local,
508
504
  command: event.command,
505
+ cwd: machine.cwd,
509
506
  budget,
510
507
  deadline: startedAt + HOOK_BUDGET_MS - PRINT_RESERVE_MS,
511
508
  now: deps.now ?? Date.now,
@@ -7,6 +7,8 @@
7
7
  * 4 KB of output, read locally and never sent);
8
8
  * - what it created or removed that keeps running (`cliHookCreates.ts`);
9
9
  * - how many times in a row the same command failed (`cliHookSessionState.ts`);
10
+ * - a `git push` GitHub refused because `passport git-credential` gave git a
11
+ * read-only token, not knowing it was a push (`gitReadOnly.ts`);
10
12
  * - the non-default branch a `git push` that succeeded sent (`cliHookPushed.ts`),
11
13
  * for the session's title, to any server (an older one refuses it and the
12
14
  * report goes again without it);
@@ -7,6 +7,8 @@
7
7
  * 4 KB of output, read locally and never sent);
8
8
  * - what it created or removed that keeps running (`cliHookCreates.ts`);
9
9
  * - how many times in a row the same command failed (`cliHookSessionState.ts`);
10
+ * - a `git push` GitHub refused because `passport git-credential` gave git a
11
+ * read-only token, not knowing it was a push (`gitReadOnly.ts`);
10
12
  * - the non-default branch a `git push` that succeeded sent (`cliHookPushed.ts`),
11
13
  * for the session's title, to any server (an older one refuses it and the
12
14
  * report goes again without it);
@@ -68,13 +70,17 @@ async function learn(context, state) {
68
70
  const program = retry.state.retry?.program;
69
71
  const pushes = context.findings.some((finding) => finding.vendor === "git" && finding.verb === "push");
70
72
  const pushed = failed || !pushes ? undefined : (await import("./cliHookPushed.js")).pushedOf(context.findings);
73
+ const readOnly = failed && pushes
74
+ ? await Promise.all([import("./gitReadOnly.js"), import("./signInFailure.js")]).then(([{ readOnlyPushContext }, { outputTail }]) => readOnlyPushContext(context.findings, outputTail(context.input), exitCode, context.now))
75
+ : null;
71
76
  return {
72
77
  learned: {
73
78
  signIn,
74
79
  resources,
75
80
  streak: retry.streak,
76
81
  ...(program ? { program } : {}),
77
- ...(pushed ? { pushed } : {})
82
+ ...(pushed ? { pushed } : {}),
83
+ ...(readOnly ? { readOnly } : {})
78
84
  },
79
85
  state: retry.state
80
86
  };
@@ -145,6 +151,7 @@ export async function afterCommand(context) {
145
151
  // The loop's ask threshold (`cliHookStuck.ts`) matters only once the agent is told.
146
152
  const askAt = learned.streak >= RETRY_TELL_AT ? (await import("./cliHookStuck.js")).RETRY_ASK_AT : Infinity;
147
153
  const lines = [
154
+ ...(learned.readOnly ? [learned.readOnly] : []),
148
155
  ...(learned.signIn ? [signInContext(learned.signIn, key.held, key.rerouted && claude)] : []),
149
156
  ...(learned.streak >= RETRY_TELL_AT
150
157
  ? [retryContext(learned.streak, learned.program, asksNext && learned.streak >= askAt)]
@@ -16,35 +16,15 @@
16
16
  * Never the raw command line.
17
17
  */
18
18
  import type { LeaseNote } from "./leaseCommands.js";
19
- import { type ActionClass, type Cause } from "./cliAutopilotPolicy.js";
20
- import { type EnvKind } from "./cliHookEnvironment.js";
21
19
  import { type GuardClient, type GuardDecision } from "./cliHookGuard.js";
22
20
  import type { HookMode } from "./cliHookMode.js";
23
21
  import type { CachedCliPolicy } from "./cliPolicy.js";
24
22
  import { type OfflineNote } from "./cliGuardState.js";
25
23
  import { decideRequest, type CliDecideRequest } from "./cliHookDecideRequest.js";
26
24
  export { decideRequest, type CliDecideRequest };
27
- export declare const CLI_DECIDE_PATH = "/api/my/cli/decide";
28
- export type ServerDecision = {
29
- decision: "allow" | "ask" | "block" | "none";
30
- cause?: Cause;
31
- explanation?: string;
32
- environment?: EnvKind;
33
- actionClass?: ActionClass;
34
- approvalId?: string;
35
- /** What to tell the agent, e.g. "Waiting for approval from Ramish. …" */
36
- message?: string;
37
- /** A pending approval: when it expires, and who decides. */
38
- expiresAt?: number;
39
- waitingFor?: string;
40
- /** An attended ask's reason line, ending with its short link (≤ 240). */
41
- askLine?: string;
42
- };
25
+ import { type ServerDecision } from "./cliHookServerDecision.js";
26
+ export { CLI_DECIDE_PATH, decideOnServer, parseServerDecision, type ServerDecision } from "./cliHookServerDecision.js";
43
27
  type ApiCall = (path: string, init: RequestInit) => Promise<Response>;
44
- /** Validate what the server said. Anything unexpected is no answer at all. */
45
- export declare function parseServerDecision(raw: unknown): ServerDecision | null;
46
- /** Ask the server, or null when it couldn't answer in time. Never throws. */
47
- export declare function decideOnServer(api: ApiCall, request: CliDecideRequest, signal: AbortSignal): Promise<ServerDecision | null>;
48
28
  export type GuardPlan = {
49
29
  output: Record<string, unknown> | null;
50
30
  server: ServerDecision | null;
@@ -83,7 +63,7 @@ export declare function offlineVerdict(decision: GuardDecision, policy: CachedCl
83
63
  /** What an attended irreversible ask says when Passport can't be reached. */
84
64
  export declare const IRREVERSIBLE_UNREACHABLE = "Passport can't be reached. Irreversible commands need approval in Passport.";
85
65
  /** What an irreversible ask tells the agent while it waits in Passport. */
86
- export declare const IRREVERSIBLE_IN_PASSPORT = "Approve this in Passport. Irreversible actions need a passkey check.";
66
+ export declare const IRREVERSIBLE_IN_PASSPORT = "Approve this in Passport. Irreversible actions are approved there.";
87
67
  /**
88
68
  * Attended, or no v2 policy: the local decision, printed at once. Unattended
89
69
  * ask: the server decides within the budget, and an approval request replaces
@@ -114,6 +94,10 @@ declare function decidePlan(decision: GuardDecision | null, policy: CachedCliPol
114
94
  /** The server places everyday commands (cli-policy v2 `local`). */
115
95
  local?: boolean;
116
96
  command: string;
97
+ /** The command's folder, for the control plane's repository and branch, and Railway's link. */
98
+ cwd?: string | null;
99
+ /** The agent's environment (Railway's link from the shell; whether `passport exec` issued the credential). */
100
+ env?: Record<string, string | undefined>;
117
101
  budget: AbortSignal;
118
102
  deadline: number;
119
103
  now: () => number;