@santori/station 0.9.9 → 0.9.11

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.
package/dist/login.js CHANGED
@@ -1,76 +1,46 @@
1
1
  // `station login`: sign this computer in through the website.
2
2
  //
3
- // The CLI makes a secret and opens the website's /cli/login with the
4
- // secret's sha256. The person, signed in there (or signing up first),
5
- // approves; the website sends the browser back to 127.0.0.1 on this
6
- // computer with a one-time code; the CLI trades the code and its secret for
7
- // a token (relay: cliAuth.ts). The code alone is useless, so a browser
8
- // history leaks nothing, and the code only ever reaches this computer, so a
9
- // login link someone else sends you gets them nothing.
3
+ // The CLI asks the relay for a device link (/api/device/start): a short
4
+ // code the person sees on the page, and a private proof only this
5
+ // computer holds. The person opens the link on any computer, signed in or
6
+ // signing up first, sees the agent, the computer and the code, and
7
+ // approves. The CLI polls /api/device/token with its proof and saves the
8
+ // sign-in: the person's token, or with --agent that one agent's own secret
9
+ // for this computer. The code alone signs nothing in.
10
10
  //
11
- // The command does not have to wait for the browser. A small helper,
12
- // started detached (`station login-helper`), listens for the code for ten
13
- // minutes and saves the sign-in. `station login` prints the link and exits;
14
- // in a terminal it also waits and says who signed in. An agent posts the
15
- // link and carries on: the next command that needs the sign-in waits a
16
- // moment for the helper (`finishLogin`). The secret sits in
17
- // ~/.station/login.json, readable only by this user, until the helper is
18
- // done with it.
11
+ // The person's own sign-in also sends the local agents installed here
12
+ // (Claude Code, Codex): the page shows them, and approving makes each the
13
+ // person's agent, running on this computer.
19
14
  //
20
- // An agent on another computer than the person's browser (a cloud agent, a
21
- // container, a machine reached over ssh) cannot be reached at 127.0.0.1:
22
- // the browser would look on the person's own computer. There the link
23
- // carries no port, the website shows the person the code after Connect
24
- // instead, they give it to the agent, and `station login --code` hands it
25
- // to the helper. The code is still useless without the secret here. A
26
- // wrong code is refused and the helper keeps waiting, up to MAX_TRIES.
15
+ // The command does not have to wait for the browser. A small helper,
16
+ // started detached (`station login-helper`), polls for ten minutes and
17
+ // saves the sign-in. `station login` prints the link and exits; in a
18
+ // terminal it also waits and says who signed in. An agent posts the link
19
+ // and carries on: the next command that needs the sign-in waits a moment
20
+ // for the helper (`finishLogin`). The proof sits in ~/.station/login.json,
21
+ // readable only by this user, until the helper is done with it.
27
22
  import { execFile, spawn } from "node:child_process";
28
- import { createHash, randomBytes } from "node:crypto";
23
+ import { randomBytes } from "node:crypto";
29
24
  import { openSync } from "node:fs";
30
- import { createServer } from "node:http";
31
25
  import { hostname } from "node:os";
26
+ import { foundHere } from "./agents.js";
32
27
  import { DEFAULT_WEB, files, readCredentials, readJson, remove, writeJson } from "./home.js";
33
- import { callingAgentName } from "./caller.js";
34
28
  import { carryGuest } from "./guest.js";
35
- import { call, siteOf } from "./relay.js";
36
- /** How long the helper listens for the website's answer. */
29
+ import { call, RelayError, siteOf } from "./relay.js";
30
+ import { loadSeats } from "./seats.js";
31
+ /** How long a sign-in link works: the relay's DEVICE_MS. */
37
32
  export const LISTEN_MS = 10 * 60_000;
38
- /** A person on another computer brings the code back by hand, often long
39
- * after the agent posted the link, so that helper listens for a day. */
40
- export const REMOTE_LISTEN_MS = 24 * 60 * 60_000;
41
- /** How long the helper listens, and so how long a sign-in link works. */
42
- export function listenFor(remote) {
43
- return remote ? REMOTE_LISTEN_MS : LISTEN_MS;
44
- }
45
- /** The same, in words. */
46
- export function linkLasts(remote) {
47
- return remote ? "a day" : "ten minutes";
48
- }
49
33
  export function newVerifier() {
50
34
  return randomBytes(32).toString("base64url");
51
35
  }
52
- export function challengeOf(verifier) {
53
- return createHash("sha256").update(verifier, "utf8").digest("base64url");
54
- }
55
36
  /** Whether the person's browser is likely on another computer than this
56
37
  * one: reached over ssh, or a Linux with no screen (a container, a cloud
57
- * agent). A wrong guess still signs in, with `station login --code`. */
38
+ * agent). */
58
39
  export function elsewhere(env = process.env, platform = process.platform) {
59
40
  if (env.SSH_CONNECTION || env.SSH_TTY)
60
41
  return true;
61
42
  return platform === "linux" && !env.DISPLAY && !env.WAYLAND_DISPLAY;
62
43
  }
63
- /** The link the person opens. With no port, the website shows them the
64
- * code to give the agent instead of sending the browser to 127.0.0.1.
65
- * `agent` names the agent that asked, so the page can show its mark. */
66
- export function loginUrl(webUrl, port, state, challenge, label, signUp = false, agent = null) {
67
- const params = new URLSearchParams(port === null ? { challenge, host: label } : { port: String(port), state, challenge, host: label });
68
- if (agent)
69
- params.set("agent", agent);
70
- const connect = `/cli/login?${params}`;
71
- // Someone with no account yet: the sign-up page, which comes back here.
72
- return signUp ? `${webUrl}/signup?next=${encodeURIComponent(connect)}` : `${webUrl}${connect}`;
73
- }
74
44
  /** The computer's name on the page ("Codex on <label> wants to connect").
75
45
  * Elsewhere it is often a container's random id, which the person cannot
76
46
  * place, so the page says it is another computer than theirs. */
@@ -97,133 +67,137 @@ export function openBrowser(url) {
97
67
  const args = process.platform === "win32" ? ["/c", "start", "", url] : [url];
98
68
  execFile(command, args, () => { });
99
69
  }
100
- const page = (title, body) => `<!doctype html><meta charset="utf-8"><title>${title}</title><body style="font-family:system-ui;max-width:420px;margin:120px auto;color:#141516"><h2 style="font-weight:500">${title}</h2><p style="color:#5c5f62">${body}</p></body>`;
101
- /** How many codes the helper tries before the login ends. */
102
- export const MAX_TRIES = 5;
103
- /** Listens on 127.0.0.1 for the code: the website sends the browser here
104
- * with it, or `station login --code` brings it. Each code goes to `trade`.
105
- * A refused code is answered with why, and the helper keeps listening for
106
- * the right one, up to MAX_TRIES. `--code` asks for JSON; a browser gets a
107
- * page. */
108
- function listen(state, waitMs, lasts, trade) {
109
- return new Promise((resolveStart, rejectStart) => {
110
- let settle;
111
- const done = new Promise((resolve, reject) => {
112
- settle = { resolve, reject };
113
- });
114
- let tries = 0;
115
- let queue = Promise.resolve();
116
- const end = (error) => {
117
- server.close();
118
- clearTimeout(timer);
119
- if (error)
120
- settle.reject(error);
121
- else
122
- settle.resolve();
123
- };
124
- const server = createServer((request, response) => {
125
- const url = new URL(request.url ?? "/", "http://127.0.0.1");
126
- if (url.pathname !== "/callback") {
127
- response.writeHead(404).end();
70
+ /** The helper: polls the relay until the person answers the link, then
71
+ * saves the sign-in. `station login-helper` runs it in its own process;
72
+ * tests call it here. */
73
+ export async function runHelper(home) {
74
+ const pending = readPending(home);
75
+ // A login.json with no device link is an older CLI's: its own helper finishes it.
76
+ if (pending?.device)
77
+ await runDeviceHelper(home, pending);
78
+ }
79
+ const pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
80
+ async function runDeviceHelper(home, pending) {
81
+ const device = pending.device;
82
+ const file = files(home);
83
+ const mine = () => readPending(home)?.verifier === pending.verifier;
84
+ const replyState = () => readJson(file.loginReply, null);
85
+ const tracking = { id: pending.verifier, pid: process.pid };
86
+ const deadline = Date.parse(device.expires_at);
87
+ // Why the relay last failed to answer, while it still does not.
88
+ let down = null;
89
+ const poll = (path, more = {}) => call(pending.relayUrl, path, null, { body: { proof: device.proof, ...more } }).then((result) => {
90
+ down = null;
91
+ return result;
92
+ }, (error) => {
93
+ if (!(error instanceof RelayError && (error.status === 0 || error.status >= 500)))
94
+ throw error;
95
+ if (!down)
96
+ console.error(`station login: ${pending.relayUrl}${path} did not answer: ${error.message}`);
97
+ down = error.message;
98
+ return null;
99
+ });
100
+ if (!mine())
101
+ return;
102
+ writeJson(file.login, { ...readPending(home), pid: process.pid });
103
+ try {
104
+ while (mine() && Date.now() < deadline) {
105
+ // The seats this computer joined with no sign-in go with it: once the person approves, the relay makes them theirs.
106
+ const seats = claimsFor(home, pending.relayUrl, readPending(home)?.claims).map((claim) => claim.key);
107
+ const answer = await poll("/api/device/token", { seats });
108
+ if (!mine())
128
109
  return;
110
+ if (!answer || answer.status === "pending") {
111
+ await pause(1500);
112
+ continue;
129
113
  }
130
- const json = (request.headers.accept ?? "").includes("application/json");
131
- const answer = (error, forBrowser) => {
132
- response.writeHead(error ? 400 : 200, { "Content-Type": json ? "application/json" : "text/html; charset=utf-8" });
133
- if (json)
134
- response.end(JSON.stringify(error ? { error } : { ok: true }));
135
- else
136
- response.end(error ? page("That did not work", forBrowser) : page("Station CLI connected", "You can close this tab and go back to your agent."));
114
+ if (answer.status === "declined")
115
+ throw new Error("The person declined this sign-in. Run station login to ask again.");
116
+ if (pending.asAgent ? !answer.secret : !answer.token)
117
+ throw new Error("Station did not return the approved sign-in. Run station login again.");
118
+ const credentials = {
119
+ relayUrl: pending.relayUrl,
120
+ ...(pending.webUrl === DEFAULT_WEB ? {} : { webUrl: pending.webUrl }),
121
+ token: answer.token ?? "",
122
+ userId: answer.user_id,
123
+ name: answer.agent?.name ?? answer.name ?? "",
124
+ ...(answer.secret ? { agent: true, secret: answer.secret, allowHooks: answer.allow_hooks === true } : {}),
137
125
  };
138
- const code = url.searchParams.get("code");
139
- if (url.searchParams.get("state") !== state || !code) {
140
- const error = "The website sent back something Station did not ask for. Run station login again.";
141
- answer(error, "Run station login again.");
142
- end(new Error(error));
126
+ const waited = readPending(home)?.claims ?? [];
127
+ writeJson(file.credentials, credentials);
128
+ if (!waited.length)
129
+ writeJson(file.loginReply, tracking);
130
+ remove(file.login);
131
+ if (answer.token)
132
+ await carryGuest(home, pending.relayUrl, answer.token);
133
+ else if (answer.secret)
134
+ await carryGuest(home, pending.relayUrl, answer.secret, true);
135
+ if (waited.length)
143
136
  return;
144
- }
145
- // One code at a time, in the order they came.
146
- queue = queue.then(async () => {
147
- try {
148
- await trade(code);
149
- answer(null, "");
150
- end();
151
- }
152
- catch (failed) {
153
- tries += 1;
154
- const why = failed instanceof Error ? failed.message : String(failed);
155
- if (tries < MAX_TRIES)
156
- return answer(why, "Open the sign-in link again and click Connect.");
157
- const last = `${why.split(/(?<=\.) /)[0]} That was the last try for this sign-in: run station login again.`;
158
- answer(last, "Run station login again.");
159
- end(new Error(last));
137
+ try {
138
+ while (replyState()?.id === tracking.id && Date.now() < deadline) {
139
+ const result = await poll("/api/device/hello");
140
+ if (replyState()?.id !== tracking.id)
141
+ return;
142
+ if (result?.reply) {
143
+ writeJson(file.loginReply, { ...tracking, reply: result.reply });
144
+ return;
145
+ }
146
+ await pause(1500);
160
147
  }
161
- });
162
- });
163
- const timer = setTimeout(() => end(new Error(`Nobody finished signing in within ${lasts}. Run station login again.`)), waitMs);
164
- server.on("error", rejectStart);
165
- server.listen(0, "127.0.0.1", () => {
166
- const address = server.address();
167
- if (!address || typeof address === "string")
168
- return rejectStart(new Error("Could not listen for the website's answer."));
169
- resolveStart({ port: address.port, done });
170
- });
171
- });
172
- }
173
- /** The helper: listens, then trades each code it gets for a token and
174
- * saves it. `station login-helper` runs it in its own process; tests call
175
- * it here. */
176
- export async function runHelper(home, waitMs) {
177
- const pending = readPending(home);
178
- if (!pending)
179
- return;
180
- const remote = Boolean(pending.remote);
181
- const mine = () => readPending(home)?.verifier === pending.verifier;
182
- // Only while the file is still this sign-in's: a newer login replaces it.
183
- const report = (more) => {
184
- if (mine())
185
- writeJson(files(home).login, { ...readPending(home), ...more });
186
- };
187
- const trade = async (code) => {
188
- // Logged out, or a newer login, since this one started: save nothing.
189
- if (!mine())
148
+ }
149
+ finally {
150
+ const last = replyState();
151
+ if (last?.id === tracking.id && !last.reply)
152
+ remove(file.loginReply);
153
+ }
190
154
  return;
191
- report({ trading: true });
192
- let answer;
193
- try {
194
- answer = await call(pending.relayUrl, "/cli/token", null, {
195
- body: { code, verifier: pending.verifier },
196
- });
197
- }
198
- catch (error) {
199
- report({ trading: false });
200
- throw error;
201
155
  }
202
- // Station's own site is not saved, so a sign-in follows DEFAULT_WEB when the domain moves.
203
- const site = pending.webUrl === DEFAULT_WEB ? {} : { webUrl: pending.webUrl };
204
- const credentials = { relayUrl: pending.relayUrl, ...site, token: answer.token, userId: answer.user_id, name: answer.name };
205
156
  if (!mine())
206
157
  return;
207
- // Seats that joined while this link waited were added to it (join.ts).
208
- const claims = readPending(home)?.claims ?? [];
209
- writeJson(files(home).credentials, credentials);
210
- remove(files(home).login);
211
- for (const claim of claims)
212
- await claimSeat(pending.relayUrl, claim, answer.token);
213
- // Rooms this computer opened with no sign-in become the person's.
214
- await carryGuest(home, pending.relayUrl, answer.token);
215
- };
216
- try {
217
- const { port, done } = await listen(pending.state, waitMs ?? listenFor(remote), linkLasts(remote), trade);
218
- report({ pid: process.pid, port, url: loginUrl(pending.webUrl, remote ? null : port, pending.state, challengeOf(pending.verifier), pending.label, pending.signUp, pending.agent ?? null) });
219
- await done;
158
+ if (down)
159
+ throw new Error(`Station could not be reached at ${pending.relayUrl} (${down}), so this sign-in did not finish. Run station login again once it answers.`);
160
+ throw new Error("This sign-in link expired. Run station login again.");
220
161
  }
221
162
  catch (error) {
222
- report({ error: error instanceof Error ? error.message : String(error) });
163
+ if (mine())
164
+ writeJson(file.login, { ...readPending(home), error: error instanceof Error ? error.message : String(error) });
165
+ }
166
+ }
167
+ export function takeDeviceReply(home, id) {
168
+ const path = files(home).loginReply;
169
+ const state = readJson(path, null);
170
+ if (!state?.reply || (id && state.id !== id))
171
+ return null;
172
+ remove(path);
173
+ return state.reply;
174
+ }
175
+ export async function waitForDeviceReply(home, id, deadline) {
176
+ for (;;) {
177
+ const state = readJson(files(home).loginReply, null);
178
+ if (state?.id !== id)
179
+ return null;
180
+ if (state.reply)
181
+ return takeDeviceReply(home, id);
182
+ if (!alive(state.pid) || Date.now() >= deadline)
183
+ return null;
184
+ await pause(250);
223
185
  }
224
186
  }
187
+ /** The seats a device sign-in on `relayUrl` sends with it, each once: the
188
+ * seats a waiting link was given (join.ts), then every seat this computer
189
+ * still holds there that joined with no sign-in and that, as far as it
190
+ * knows, is nobody's yet. The relay claims only those still nobody's else. */
191
+ export function claimsFor(home, relayUrl, waited = []) {
192
+ const unsigned = loadSeats(files(home).seats)
193
+ .filter((seat) => seat.via === "room" && !seat.left && !seat.own && !seat.ownerSeat && seat.relayUrl === relayUrl && seat.roomToken)
194
+ .map((seat) => ({ roomId: seat.roomId, key: seat.roomToken }));
195
+ const all = [...waited, ...unsigned];
196
+ return all.filter((one, at) => all.findIndex((it) => it.key === one.key) === at);
197
+ }
225
198
  /** Makes a seat this computer took with no sign-in the signed-in person's:
226
- * the seat asks for its claim link and the person's new token answers it.
199
+ * the seat asks for its claim link and the new sign-in (the person's token,
200
+ * or the agent's own secret from a device link) answers it.
227
201
  * One that cannot be claimed (let go, or a private room the person cannot
228
202
  * open) stays as it was. */
229
203
  export async function claimSeat(relayUrl, claim, token) {
@@ -240,41 +214,38 @@ export async function claimSeat(relayUrl, claim, token) {
240
214
  }
241
215
  /** Starts a sign-in: the helper listens, and this returns its link. The
242
216
  * link is on `webUrl` when one is given, else on the relay's own site. */
243
- export async function startLogin(home, relayUrl, webUrl, signUp, launch = spawnHelper, remote = false, claims = [], agent = callingAgentName()) {
217
+ export async function startLogin(home, relayUrl, webUrl, signUp, launch = spawnHelper, remote = false, claims = [], asAgent = null) {
244
218
  const site = await siteOf(relayUrl, webUrl);
245
- // A newer login replaces one still listening.
219
+ // A newer login replaces one still polling.
246
220
  const before = readPending(home);
247
221
  if (before?.pid && before.pid !== process.pid && alive(before.pid))
248
222
  process.kill(before.pid, "SIGTERM");
249
223
  // Seats an earlier link was to make the person's stay on the new one.
250
- if (before?.relayUrl === relayUrl)
224
+ if (!asAgent && before?.relayUrl === relayUrl)
251
225
  claims = [...(before.claims ?? []).filter((one) => !claims.some((it) => it.key === one.key)), ...claims];
252
226
  const pending = {
253
227
  relayUrl,
254
228
  webUrl: site,
255
229
  verifier: newVerifier(),
256
- state: randomBytes(16).toString("base64url"),
257
230
  label: loginLabel(hostname(), remote),
258
231
  signUp,
259
232
  startedAt: Date.now(),
260
- ...(remote ? { remote } : {}),
261
- ...(agent ? { agent } : {}),
233
+ ...(asAgent ? { asAgent } : {}),
262
234
  ...(claims.length ? { claims } : {}),
263
235
  };
236
+ const device = await call(relayUrl, "/api/device/start", null, {
237
+ body: { label: pending.label, agent: asAgent, ...(asAgent ? {} : { agents: foundHere() }) },
238
+ });
239
+ const link = new URL("/cli/login", site);
240
+ link.searchParams.set("code", device.code);
241
+ if (signUp)
242
+ link.searchParams.set("signup", "1");
243
+ remove(files(home).loginReply);
244
+ pending.device = { proof: device.proof, expires_at: device.expires_at };
245
+ pending.url = link.toString();
264
246
  writeJson(files(home).login, pending);
265
247
  launch(home);
266
- // Up to 20 seconds: a new container's first run takes more than 5 to start the helper.
267
- for (let i = 0; i < 400; i++) {
268
- const now = readPending(home);
269
- if (now?.verifier !== pending.verifier)
270
- break;
271
- if (now.url)
272
- return now;
273
- if (now.error)
274
- throw new Error(now.error);
275
- await new Promise((resolve) => setTimeout(resolve, 50));
276
- }
277
- throw new Error(`Could not start the sign-in. See ${files(home).log}.`);
248
+ return { ...pending, url: pending.url };
278
249
  }
279
250
  function spawnHelper(home) {
280
251
  const log = openSync(files(home).log, "a", 0o600);
@@ -291,8 +262,7 @@ function spawnHelper(home) {
291
262
  * up to `waitMs` for it to end, even when an older sign-in is saved (the
292
263
  * login may be switching accounts). The sign-in on disk once no login is
293
264
  * under way, or null while one still is. A failed login is cleared and
294
- * says why. With `waitForCode` false, only an exchange already under way
295
- * gets time to finish, not a link still waiting for the person. */
265
+ * says why. With `waitForCode` false, it does not wait for the person. */
296
266
  export async function finishLogin(home, waitMs, waitForCode = true) {
297
267
  const deadline = Date.now() + waitMs;
298
268
  for (;;) {
@@ -304,66 +274,23 @@ export async function finishLogin(home, waitMs, waitForCode = true) {
304
274
  // The helper's own words are a whole sentence already.
305
275
  throw new Error(pending.error);
306
276
  }
307
- if (!alive(pending.pid)) {
277
+ if (!alive(pending.pid) && (pending.pid || !pending.device || Date.now() - pending.startedAt >= 20_000)) {
308
278
  // The helper is gone without a word: the login is over.
309
279
  if (readPending(home)?.verifier === pending.verifier)
310
280
  remove(files(home).login);
311
281
  continue;
312
282
  }
313
- if ((!waitForCode && !pending.trading) || Date.now() >= deadline)
283
+ if (!waitForCode || Date.now() >= deadline)
314
284
  return null;
315
285
  await new Promise((resolve) => setTimeout(resolve, 250));
316
286
  }
317
287
  }
318
- /** The code in what the person gave: the code itself, or the address
319
- * their browser ended on (http://127.0.0.1:<port>/callback?code=...). */
320
- export function codeIn(given) {
321
- const text = given.trim();
322
- const code = /[?&]code=([^&#\s]+)/.exec(text)?.[1] ?? text;
323
- return /^[A-Za-z0-9_-]{16,64}$/.test(code) ? code : null;
324
- }
325
- /** `station login --code`: hands the helper the code the person brought
326
- * back from the website. The helper trades it, as if the browser had come. */
327
- export async function giveCode(home, given, command = "station") {
328
- const pending = readPending(home);
329
- if (!pending || pending.error || !pending.port || !alive(pending.pid)) {
330
- // Often the browser reached this computer after all, and that code signed it in.
331
- const saved = pending ? null : readCredentials(home);
332
- if (saved)
333
- throw new Error(`No sign-in is waiting for a code: this computer is already signed in as ${saved.name}. Nothing more to do.`);
334
- throw new Error(`No sign-in is waiting for a code here: its link ran out or a newer one replaced it. Run ${command} login again.`);
335
- }
336
- const code = codeIn(given);
337
- if (!code)
338
- throw new Error("That is not a Station sign-in code. Give the code from the page, or the whole address the browser ended on.");
339
- // An address carries its link's state. One from a link a newer login
340
- // replaced cannot sign in: its secret is gone, so it is not sent at all.
341
- const state = /[?&]state=([^&#\s]+)/.exec(given)?.[1];
342
- if (state && decodeURIComponent(state) !== pending.state) {
343
- throw new Error("That address is from an older sign-in link. A newer station login replaced it. Give the person the newest link, and after they click Connect, ask for the address it ends on.");
344
- }
345
- const response = await fetch(`http://127.0.0.1:${pending.port}/callback?${new URLSearchParams({ code, state: pending.state })}`, {
346
- headers: { Accept: "application/json" },
347
- });
348
- // A refused code: the helper says why and, unless that was the last try, keeps waiting.
349
- if (!response.ok)
350
- throw new Error((await response.json().catch(() => ({}))).error ?? `That code did not sign this computer in. Run ${command} login again.`);
351
- }
352
- /** What the agent does with the code, while a login waits for it. */
353
- export function codeStep(command, remote) {
354
- return remote
355
- ? `After Connect, ask them for the code on the page. It works for five minutes; run this as soon as it arrives: ${command} login --code=<the code>`
356
- : `If their browser cannot reach the final 127.0.0.1 page, it is on another computer. Ask for that page's whole address. It works for five minutes; run this as soon as it arrives: ${command} login --code='<that address>'`;
357
- }
358
- /** Whether the login under way is one where the person brings a code back. */
359
- export function waitingForCode(home) {
360
- return Boolean(waitingAt(home) && readPending(home)?.remote);
361
- }
362
288
  /** Stops a login under way: `station logout`, so a Connect clicked later
363
289
  * signs nobody back in. */
364
290
  export function cancelLogin(home) {
365
291
  const pending = readPending(home);
366
292
  remove(files(home).login);
293
+ remove(files(home).loginReply);
367
294
  if (pending?.pid && pending.pid !== process.pid && alive(pending.pid))
368
295
  process.kill(pending.pid, "SIGTERM");
369
296
  }
@@ -372,7 +299,7 @@ export function cancelLogin(home) {
372
299
  export function addClaim(home, relayUrl, claim) {
373
300
  const pending = readPending(home);
374
301
  const url = waitingAt(home);
375
- if (!pending || !url || pending.relayUrl !== relayUrl)
302
+ if (!pending || !url || pending.relayUrl !== relayUrl || pending.asAgent)
376
303
  return null;
377
304
  const claims = [...(pending.claims ?? []).filter((one) => one.key !== claim.key), claim];
378
305
  writeJson(files(home).login, { ...pending, claims });
@@ -381,5 +308,5 @@ export function addClaim(home, relayUrl, claim) {
381
308
  /** The link of a login still waiting for the person, if there is one. */
382
309
  export function waitingAt(home) {
383
310
  const pending = readPending(home);
384
- return pending && !pending.error && alive(pending.pid) && pending.url ? pending.url : null;
311
+ return pending && !pending.error && (alive(pending.pid) || (!pending.pid && pending.device && Date.now() - pending.startedAt < 20_000)) && pending.url ? pending.url : null;
385
312
  }