@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/README.md +59 -31
- package/dist/agentToken.js +14 -5
- package/dist/agents.js +14 -9
- package/dist/args.js +139 -6
- package/dist/caller.js +0 -7
- package/dist/claude.js +4 -1
- package/dist/cli.js +256 -145
- package/dist/codex.js +80 -16
- package/dist/commands.js +89 -18
- package/dist/daemon.js +385 -29
- package/dist/frame.js +17 -26
- package/dist/guard.js +11 -8
- package/dist/guest.js +10 -5
- package/dist/handover.js +19 -6
- package/dist/home.js +3 -1
- package/dist/hooks.js +169 -0
- package/dist/join.js +250 -125
- package/dist/login.js +161 -234
- package/dist/mark.js +116 -14
- package/dist/mcp.js +14 -5
- package/dist/node.js +14 -0
- package/dist/own.js +42 -0
- package/dist/programs.js +50 -0
- package/dist/relay.js +1 -1
- package/dist/rooms.js +2 -4
- package/dist/seats.js +14 -2
- package/dist/sessions.js +37 -7
- package/dist/starts.js +21 -14
- package/dist/tool.js +14 -5
- package/dist/waking.js +57 -20
- package/dist/webhooks.js +30 -42
- package/hook/hook.mjs +149 -0
- package/package.json +3 -2
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
|
|
4
|
-
//
|
|
5
|
-
//
|
|
6
|
-
//
|
|
7
|
-
//
|
|
8
|
-
//
|
|
9
|
-
//
|
|
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
|
|
12
|
-
//
|
|
13
|
-
//
|
|
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
|
-
//
|
|
21
|
-
//
|
|
22
|
-
// the
|
|
23
|
-
//
|
|
24
|
-
//
|
|
25
|
-
//
|
|
26
|
-
//
|
|
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 {
|
|
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
|
-
|
|
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).
|
|
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
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
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
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
136
|
-
|
|
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
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
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
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
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
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
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
|
-
|
|
208
|
-
|
|
209
|
-
|
|
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
|
-
|
|
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
|
|
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 = [],
|
|
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
|
|
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
|
-
...(
|
|
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
|
-
|
|
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,
|
|
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 (
|
|
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
|
}
|