@santori/station 0.9.10 → 0.9.12

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,78 +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
29
  import { call, RelayError, siteOf } from "./relay.js";
36
- /** How long the helper listens for the website's answer. */
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, asAgent = 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
- if (asAgent)
71
- params.set("as", asAgent);
72
- const connect = `/cli/login?${params}`;
73
- // Someone with no account yet: the sign-up page, which comes back here.
74
- return signUp ? `${webUrl}/signup?next=${encodeURIComponent(connect)}` : `${webUrl}${connect}`;
75
- }
76
44
  /** The computer's name on the page ("Codex on <label> wants to connect").
77
45
  * Elsewhere it is often a container's random id, which the person cannot
78
46
  * place, so the page says it is another computer than theirs. */
@@ -99,167 +67,44 @@ export function openBrowser(url) {
99
67
  const args = process.platform === "win32" ? ["/c", "start", "", url] : [url];
100
68
  execFile(command, args, () => { });
101
69
  }
102
- 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>`;
103
- /** How many codes the helper tries before the login ends. */
104
- export const MAX_TRIES = 5;
105
- /** Listens on 127.0.0.1 for the code: the website sends the browser here
106
- * with it, or `station login --code` brings it. Each code goes to `trade`.
107
- * A refused code is answered with why, and the helper keeps listening for
108
- * the right one, up to MAX_TRIES. `--code` asks for JSON; a browser gets a
109
- * page. */
110
- function listen(state, waitMs, lasts, trade) {
111
- return new Promise((resolveStart, rejectStart) => {
112
- let settle;
113
- const done = new Promise((resolve, reject) => {
114
- settle = { resolve, reject };
115
- });
116
- let tries = 0;
117
- let queue = Promise.resolve();
118
- const end = (error) => {
119
- server.close();
120
- clearTimeout(timer);
121
- if (error)
122
- settle.reject(error);
123
- else
124
- settle.resolve();
125
- };
126
- const server = createServer((request, response) => {
127
- const url = new URL(request.url ?? "/", "http://127.0.0.1");
128
- if (url.pathname !== "/callback") {
129
- response.writeHead(404).end();
130
- return;
131
- }
132
- const json = (request.headers.accept ?? "").includes("application/json");
133
- const answer = (error, forBrowser) => {
134
- response.writeHead(error ? 400 : 200, { "Content-Type": json ? "application/json" : "text/html; charset=utf-8" });
135
- if (json)
136
- response.end(JSON.stringify(error ? { error } : { ok: true }));
137
- else
138
- response.end(error ? page("That did not work", forBrowser) : page("Station CLI connected", "You can close this tab and go back to your agent."));
139
- };
140
- const code = url.searchParams.get("code");
141
- if (url.searchParams.get("state") !== state || !code) {
142
- const error = "The website sent back something Station did not ask for. Run station login again.";
143
- answer(error, "Run station login again.");
144
- end(new Error(error));
145
- return;
146
- }
147
- // One code at a time, in the order they came.
148
- queue = queue.then(async () => {
149
- try {
150
- await trade(code);
151
- answer(null, "");
152
- end();
153
- }
154
- catch (failed) {
155
- tries += 1;
156
- const why = failed instanceof Error ? failed.message : String(failed);
157
- if (tries < MAX_TRIES)
158
- return answer(why, "Open the sign-in link again and click Connect.");
159
- const last = `${why.split(/(?<=\.) /)[0]} That was the last try for this sign-in: run station login again.`;
160
- answer(last, "Run station login again.");
161
- end(new Error(last));
162
- }
163
- });
164
- });
165
- const timer = setTimeout(() => end(new Error(`Nobody finished signing in within ${lasts}. Run station login again.`)), waitMs);
166
- server.on("error", rejectStart);
167
- server.listen(0, "127.0.0.1", () => {
168
- const address = server.address();
169
- if (!address || typeof address === "string")
170
- return rejectStart(new Error("Could not listen for the website's answer."));
171
- resolveStart({ port: address.port, done });
172
- });
173
- });
174
- }
175
- /** The helper: listens, then trades each code it gets for a token and
176
- * saves it. `station login-helper` runs it in its own process; tests call
177
- * it here. */
178
- export async function runHelper(home, waitMs) {
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, startStation = async () => { }) {
179
74
  const pending = readPending(home);
180
- if (!pending)
181
- return;
182
- if (pending.device)
183
- return runDeviceHelper(home, pending);
184
- const remote = Boolean(pending.remote);
185
- const mine = () => readPending(home)?.verifier === pending.verifier;
186
- // Only while the file is still this sign-in's: a newer login replaces it.
187
- const report = (more) => {
188
- if (mine())
189
- writeJson(files(home).login, { ...readPending(home), ...more });
190
- };
191
- const trade = async (code) => {
192
- // Logged out, or a newer login, since this one started: save nothing.
193
- if (!mine())
194
- return;
195
- report({ trading: true });
196
- let answer;
197
- try {
198
- answer = await call(pending.relayUrl, "/cli/token", null, {
199
- body: { code, verifier: pending.verifier, ...(pending.asAgent ? { agent: pending.asAgent } : {}) },
200
- });
201
- }
202
- catch (error) {
203
- report({ trading: false });
204
- throw error;
205
- }
206
- // Station's own site is not saved, so a sign-in follows DEFAULT_WEB when the domain moves.
207
- const site = pending.webUrl === DEFAULT_WEB ? {} : { webUrl: pending.webUrl };
208
- if (answer.secret) {
209
- // One agent's own secret: every session on this computer is that agent.
210
- if (!mine())
211
- return;
212
- writeJson(files(home).credentials, { relayUrl: pending.relayUrl, ...site, token: "", userId: answer.user_id, name: answer.agent?.name ?? pending.asAgent ?? "", agent: true, secret: answer.secret });
213
- remove(files(home).login);
214
- return;
215
- }
216
- // Asked to sign in as one agent: never keep the person's token instead.
217
- if (pending.asAgent || !answer.token) {
218
- if (answer.token)
219
- await call(pending.relayUrl, "/me/cli-token", { token: answer.token }, { method: "DELETE" }).catch(() => { });
220
- throw new Error(pending.asAgent ? "Station gave this computer a sign-in as your person, not as the agent. Nothing was saved. Update the Station relay, or run station login --agent again." : "Station answered with no sign-in. Run station login again.");
221
- }
222
- const token = answer.token;
223
- const credentials = { relayUrl: pending.relayUrl, ...site, token, userId: answer.user_id, name: answer.name ?? "" };
224
- if (!mine())
225
- return;
226
- // Seats that joined while this link waited were added to it (join.ts).
227
- const claims = readPending(home)?.claims ?? [];
228
- writeJson(files(home).credentials, credentials);
229
- remove(files(home).login);
230
- for (const claim of claims)
231
- await claimSeat(pending.relayUrl, claim, token);
232
- // Rooms this computer opened with no sign-in become the person's.
233
- await carryGuest(home, pending.relayUrl, token);
234
- };
235
- try {
236
- const { port, done } = await listen(pending.state, waitMs ?? listenFor(remote), linkLasts(remote), trade);
237
- report({ pid: process.pid, port, url: loginUrl(pending.webUrl, remote ? null : port, pending.state, challengeOf(pending.verifier), pending.label, pending.signUp, pending.agent ?? null, pending.asAgent ?? null) });
238
- await done;
239
- }
240
- catch (error) {
241
- report({ error: error instanceof Error ? error.message : String(error) });
242
- }
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, startStation);
243
78
  }
244
79
  const pause = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
245
- async function runDeviceHelper(home, pending) {
80
+ async function runDeviceHelper(home, pending, startStation) {
246
81
  const device = pending.device;
247
82
  const file = files(home);
248
83
  const mine = () => readPending(home)?.verifier === pending.verifier;
249
84
  const replyState = () => readJson(file.loginReply, null);
250
85
  const tracking = { id: pending.verifier, pid: process.pid };
251
- const body = { proof: device.proof };
252
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
+ });
253
100
  if (!mine())
254
101
  return;
255
102
  writeJson(file.login, { ...readPending(home), pid: process.pid });
256
103
  try {
257
104
  while (mine() && Date.now() < deadline) {
258
- const answer = await call(pending.relayUrl, "/api/device/token", null, { body }).catch((error) => {
259
- if (error instanceof RelayError && (error.status === 0 || error.status >= 500))
260
- return null;
261
- throw error;
262
- });
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 });
263
108
  if (!mine())
264
109
  return;
265
110
  if (!answer || answer.status === "pending") {
@@ -278,27 +123,24 @@ async function runDeviceHelper(home, pending) {
278
123
  name: answer.agent?.name ?? answer.name ?? "",
279
124
  ...(answer.secret ? { agent: true, secret: answer.secret, allowHooks: answer.allow_hooks === true } : {}),
280
125
  };
281
- const claims = readPending(home)?.claims ?? [];
126
+ const waited = readPending(home)?.claims ?? [];
282
127
  writeJson(file.credentials, credentials);
283
- if (!claims.length)
128
+ if (!waited.length)
284
129
  writeJson(file.loginReply, tracking);
285
130
  remove(file.login);
286
- if (answer.token) {
287
- for (const claim of claims)
288
- await claimSeat(pending.relayUrl, claim, answer.token);
131
+ if (answer.token)
289
132
  await carryGuest(home, pending.relayUrl, answer.token);
290
- }
291
133
  else if (answer.secret)
292
134
  await carryGuest(home, pending.relayUrl, answer.secret, true);
293
- if (claims.length)
135
+ // The person's own sign-in made the agents found here theirs: Station runs here so it can start them for a message.
136
+ if (answer.token && foundHere().length) {
137
+ await startStation(home).catch((error) => console.error(`station login: Station did not start on this computer, so it cannot start your agents yet: ${error instanceof Error ? error.message : String(error)}`));
138
+ }
139
+ if (waited.length)
294
140
  return;
295
141
  try {
296
142
  while (replyState()?.id === tracking.id && Date.now() < deadline) {
297
- const result = await call(pending.relayUrl, "/api/device/hello", null, { body }).catch((error) => {
298
- if (error instanceof RelayError && (error.status === 0 || error.status >= 500))
299
- return null;
300
- throw error;
301
- });
143
+ const result = await poll("/api/device/hello");
302
144
  if (replyState()?.id !== tracking.id)
303
145
  return;
304
146
  if (result?.reply) {
@@ -315,8 +157,11 @@ async function runDeviceHelper(home, pending) {
315
157
  }
316
158
  return;
317
159
  }
318
- if (mine())
319
- throw new Error("This sign-in link expired. Run station login again.");
160
+ if (!mine())
161
+ return;
162
+ if (down)
163
+ 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.`);
164
+ throw new Error("This sign-in link expired. Run station login again.");
320
165
  }
321
166
  catch (error) {
322
167
  if (mine())
@@ -343,8 +188,20 @@ export async function waitForDeviceReply(home, id, deadline) {
343
188
  await pause(250);
344
189
  }
345
190
  }
191
+ /** The seats a device sign-in on `relayUrl` sends with it, each once: the
192
+ * seats a waiting link was given (join.ts), then every seat this computer
193
+ * still holds there that joined with no sign-in and that, as far as it
194
+ * knows, is nobody's yet. The relay claims only those still nobody's else. */
195
+ export function claimsFor(home, relayUrl, waited = []) {
196
+ const unsigned = loadSeats(files(home).seats)
197
+ .filter((seat) => seat.via === "room" && !seat.left && !seat.own && !seat.ownerSeat && seat.relayUrl === relayUrl && seat.roomToken)
198
+ .map((seat) => ({ roomId: seat.roomId, key: seat.roomToken }));
199
+ const all = [...waited, ...unsigned];
200
+ return all.filter((one, at) => all.findIndex((it) => it.key === one.key) === at);
201
+ }
346
202
  /** Makes a seat this computer took with no sign-in the signed-in person's:
347
- * the seat asks for its claim link and the person's new token answers it.
203
+ * the seat asks for its claim link and the new sign-in (the person's token,
204
+ * or the agent's own secret from a device link) answers it.
348
205
  * One that cannot be claimed (let go, or a private room the person cannot
349
206
  * open) stays as it was. */
350
207
  export async function claimSeat(relayUrl, claim, token) {
@@ -361,9 +218,9 @@ export async function claimSeat(relayUrl, claim, token) {
361
218
  }
362
219
  /** Starts a sign-in: the helper listens, and this returns its link. The
363
220
  * link is on `webUrl` when one is given, else on the relay's own site. */
364
- export async function startLogin(home, relayUrl, webUrl, signUp, launch = spawnHelper, remote = false, claims = [], agent = callingAgentName(), asAgent = null) {
221
+ export async function startLogin(home, relayUrl, webUrl, signUp, launch = spawnHelper, remote = false, claims = [], asAgent = null) {
365
222
  const site = await siteOf(relayUrl, webUrl);
366
- // A newer login replaces one still listening.
223
+ // A newer login replaces one still polling.
367
224
  const before = readPending(home);
368
225
  if (before?.pid && before.pid !== process.pid && alive(before.pid))
369
226
  process.kill(before.pid, "SIGTERM");
@@ -374,17 +231,13 @@ export async function startLogin(home, relayUrl, webUrl, signUp, launch = spawnH
374
231
  relayUrl,
375
232
  webUrl: site,
376
233
  verifier: newVerifier(),
377
- state: randomBytes(16).toString("base64url"),
378
234
  label: loginLabel(hostname(), remote),
379
- signUp,
380
235
  startedAt: Date.now(),
381
- ...(remote ? { remote } : {}),
382
- ...(agent ? { agent } : {}),
383
236
  ...(asAgent ? { asAgent } : {}),
384
237
  ...(claims.length ? { claims } : {}),
385
238
  };
386
239
  const device = await call(relayUrl, "/api/device/start", null, {
387
- body: { label: pending.label, agent: asAgent },
240
+ body: { label: pending.label, agent: asAgent, ...(asAgent ? {} : { agents: foundHere() }) },
388
241
  });
389
242
  const link = new URL("/cli/login", site);
390
243
  link.searchParams.set("code", device.code);
@@ -412,8 +265,7 @@ function spawnHelper(home) {
412
265
  * up to `waitMs` for it to end, even when an older sign-in is saved (the
413
266
  * login may be switching accounts). The sign-in on disk once no login is
414
267
  * under way, or null while one still is. A failed login is cleared and
415
- * says why. With `waitForCode` false, only an exchange already under way
416
- * gets time to finish, not a link still waiting for the person. */
268
+ * says why. With `waitForCode` false, it does not wait for the person. */
417
269
  export async function finishLogin(home, waitMs, waitForCode = true) {
418
270
  const deadline = Date.now() + waitMs;
419
271
  for (;;) {
@@ -431,55 +283,11 @@ export async function finishLogin(home, waitMs, waitForCode = true) {
431
283
  remove(files(home).login);
432
284
  continue;
433
285
  }
434
- if ((!waitForCode && !pending.trading) || Date.now() >= deadline)
286
+ if (!waitForCode || Date.now() >= deadline)
435
287
  return null;
436
288
  await new Promise((resolve) => setTimeout(resolve, 250));
437
289
  }
438
290
  }
439
- /** The code in what the person gave: the code itself, or the address
440
- * their browser ended on (http://127.0.0.1:<port>/callback?code=...). */
441
- export function codeIn(given) {
442
- const text = given.trim();
443
- const code = /[?&]code=([^&#\s]+)/.exec(text)?.[1] ?? text;
444
- return /^[A-Za-z0-9_-]{16,64}$/.test(code) ? code : null;
445
- }
446
- /** `station login --code`: hands the helper the code the person brought
447
- * back from the website. The helper trades it, as if the browser had come. */
448
- export async function giveCode(home, given, command = "station") {
449
- const pending = readPending(home);
450
- if (!pending || pending.error || !pending.port || !alive(pending.pid)) {
451
- // Often the browser reached this computer after all, and that code signed it in.
452
- const saved = pending ? null : readCredentials(home);
453
- if (saved)
454
- throw new Error(`No sign-in is waiting for a code: this computer is already signed in as ${saved.name}. Nothing more to do.`);
455
- 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.`);
456
- }
457
- const code = codeIn(given);
458
- if (!code)
459
- 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.");
460
- // An address carries its link's state. One from a link a newer login
461
- // replaced cannot sign in: its secret is gone, so it is not sent at all.
462
- const state = /[?&]state=([^&#\s]+)/.exec(given)?.[1];
463
- if (state && decodeURIComponent(state) !== pending.state) {
464
- 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.");
465
- }
466
- const response = await fetch(`http://127.0.0.1:${pending.port}/callback?${new URLSearchParams({ code, state: pending.state })}`, {
467
- headers: { Accept: "application/json" },
468
- });
469
- // A refused code: the helper says why and, unless that was the last try, keeps waiting.
470
- if (!response.ok)
471
- throw new Error((await response.json().catch(() => ({}))).error ?? `That code did not sign this computer in. Run ${command} login again.`);
472
- }
473
- /** What the agent does with the code, while a login waits for it. */
474
- export function codeStep(command, remote) {
475
- return remote
476
- ? `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>`
477
- : `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>'`;
478
- }
479
- /** Whether the login under way is one where the person brings a code back. */
480
- export function waitingForCode(home) {
481
- return Boolean(waitingAt(home) && readPending(home)?.remote);
482
- }
483
291
  /** Stops a login under way: `station logout`, so a Connect clicked later
484
292
  * signs nobody back in. */
485
293
  export function cancelLogin(home) {