overvues 0.0.1 → 0.4.10
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 +58 -2
- package/dist/ansi.js +24 -0
- package/dist/attach-client.js +586 -0
- package/dist/auth-connect-browser.js +112 -0
- package/dist/auth-connect.js +306 -0
- package/dist/browser-bootstrap.js +190 -0
- package/dist/browser-loopback.js +289 -0
- package/dist/build-identity.js +6 -0
- package/dist/codex-reviewer-apparmor.json +4 -0
- package/dist/codex-reviewer-seccomp.json +1238 -0
- package/dist/codex-runtime-protocol.js +1 -0
- package/dist/codex-subscription.js +53 -0
- package/dist/config.js +297 -0
- package/dist/connect-comparison-code.js +26 -0
- package/dist/development-runner.js +109 -0
- package/dist/dns-doctor.js +390 -0
- package/dist/docker-names.js +47 -0
- package/dist/doctor.js +114 -0
- package/dist/gadget-job.js +804 -0
- package/dist/health-check.js +112 -0
- package/dist/help.js +71 -0
- package/dist/host-auth.js +22 -0
- package/dist/host-diagnostics.js +20 -0
- package/dist/host-runtime-identity.js +39 -0
- package/dist/host-runtime-metadata.js +56 -0
- package/dist/host-service.js +377 -0
- package/dist/host-stack.js +484 -0
- package/dist/host-supervisor.js +237 -0
- package/dist/host-update.js +387 -0
- package/dist/hub-address.js +100 -0
- package/dist/hub-client.js +459 -0
- package/dist/hub-kind.js +88 -0
- package/dist/identity.js +73 -0
- package/dist/index.js +185 -0
- package/dist/init.js +295 -0
- package/dist/isolated-run-cache.js +116 -0
- package/dist/local-stack.js +685 -0
- package/dist/machine-capacity.js +128 -0
- package/dist/managed-runner-image.js +13 -0
- package/dist/os-acted-record.js +49 -0
- package/dist/os-adapter.js +8190 -0
- package/dist/os-command.js +292 -0
- package/dist/os-handoff.js +274 -0
- package/dist/os-keychain.js +247 -0
- package/dist/os-machine.js +818 -0
- package/dist/os-owner.js +61 -0
- package/dist/os-private-file.js +98 -0
- package/dist/os-protocol.js +468 -0
- package/dist/os-session-store.js +133 -0
- package/dist/os-status.js +102 -0
- package/dist/picker.js +863 -0
- package/dist/portable-workspace-capability.js +60 -0
- package/dist/project-environment-capability.js +62 -0
- package/dist/project-environment.js +28 -0
- package/dist/project-preparation.js +134 -0
- package/dist/readiness.js +28 -0
- package/dist/redaction.js +27 -0
- package/dist/reviewer-isolation-capability.js +61 -0
- package/dist/runner-api-auth.js +80 -0
- package/dist/runner-command-fence.js +536 -0
- package/dist/runner-inspection.js +57 -0
- package/dist/runner-inventory.js +587 -0
- package/dist/runner-server.js +2520 -0
- package/dist/runner-session.js +470 -0
- package/dist/runner-slug-folder.js +39 -0
- package/dist/runner-slug.js +40 -0
- package/dist/setup.js +139 -0
- package/dist/shutdown.js +102 -0
- package/dist/splash.js +65 -0
- package/dist/staged-workspaces.js +441 -0
- package/dist/staging-disk.js +97 -0
- package/dist/terminal-lane.js +339 -0
- package/dist/terminal-recovery.js +502 -0
- package/licenses/capnweb.txt +23 -0
- package/licenses/moby-profiles.txt +212 -0
- package/licenses/ws.txt +22 -0
- package/package.json +28 -7
- package/cli.js +0 -2
|
@@ -0,0 +1,292 @@
|
|
|
1
|
+
// `tiller os connect | status | forget`: how a machine gets its OS session, and where it is kept.
|
|
2
|
+
//
|
|
3
|
+
// `connect` is the handoff (`os-handoff.ts`), and the only way: `tiller` opens the OS's confirm
|
|
4
|
+
// page in the person's browser, the OS sends a new 30-day session to a local port, and `tiller`
|
|
5
|
+
// checks whose it is (`os-owner.ts`) and keeps it in the Mac keychain, or, on a machine that is not
|
|
6
|
+
// a Mac, in a file only the owner can read. It is started only by a person at a terminal on this
|
|
7
|
+
// machine: nothing the Hub sends starts it. There is no paste or code fallback, and no link is
|
|
8
|
+
// printed to copy.
|
|
9
|
+
//
|
|
10
|
+
// The session is never taken from an environment variable or an argument, never printed, and
|
|
11
|
+
// never sent to the Hub.
|
|
12
|
+
import { readFileSync } from "node:fs";
|
|
13
|
+
import { join } from "node:path";
|
|
14
|
+
import { createInterface } from "node:readline/promises";
|
|
15
|
+
import { openBrowser } from "./browser-loopback.js";
|
|
16
|
+
import { OsAdapterError } from "./os-adapter.js";
|
|
17
|
+
import { startOsHandoff } from "./os-handoff.js";
|
|
18
|
+
import { connectStoredOs, hubFetcher } from "./os-machine.js";
|
|
19
|
+
import { askHubOwner, sameAccount } from "./os-owner.js";
|
|
20
|
+
import { machineOsSessionStore, osSessionExpiry, osSessionExpiryLine, OsSessionUnavailableError, } from "./os-session-store.js";
|
|
21
|
+
import { redactValues } from "./redaction.js";
|
|
22
|
+
import { CLI, envVar, OS } from "./identity.js";
|
|
23
|
+
import { acceptsEveryHubKind } from "./hub-kind.js";
|
|
24
|
+
const LOCAL_HOSTS = new Set(["localhost", "127.0.0.1", "[::1]"]);
|
|
25
|
+
/** The OS address as its origin. Only https, or this machine; nothing that could carry a secret. */
|
|
26
|
+
export function osOriginOf(address) {
|
|
27
|
+
let url;
|
|
28
|
+
try {
|
|
29
|
+
url = new URL(address.trim());
|
|
30
|
+
}
|
|
31
|
+
catch {
|
|
32
|
+
throw new Error(`The ${OS.noun} address must look like https://os.example. (The session is never given here: ${OS.the} sends it to this machine.)`);
|
|
33
|
+
}
|
|
34
|
+
if (url.username || url.password || url.search || url.hash || (url.pathname !== "/" && url.pathname !== "")) {
|
|
35
|
+
throw new Error(`Give only ${OS.the}'s address, such as https://os.example, with nothing after it.`);
|
|
36
|
+
}
|
|
37
|
+
if (url.protocol !== "https:" && !(url.protocol === "http:" && LOCAL_HOSTS.has(url.hostname))) {
|
|
38
|
+
throw new Error(`The ${OS.noun} address must be https.`);
|
|
39
|
+
}
|
|
40
|
+
return url.origin;
|
|
41
|
+
}
|
|
42
|
+
/**
|
|
43
|
+
* A line to show when the `tiller host` daemon that would use the session does not appear to run
|
|
44
|
+
* as this user from this config folder, or null when it does. It reads the daemon's own pid
|
|
45
|
+
* file in the folder and asks the system whether that process is there (signal 0, which sends
|
|
46
|
+
* nothing); the daemon itself is not touched.
|
|
47
|
+
*/
|
|
48
|
+
export function hostDaemonNote(configDir, probe = (pid) => { process.kill(pid, 0); }) {
|
|
49
|
+
let pid;
|
|
50
|
+
try {
|
|
51
|
+
pid = JSON.parse(readFileSync(join(configDir, "local", "host.pid.json"), "utf8"))?.pid;
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
pid = undefined;
|
|
55
|
+
}
|
|
56
|
+
if (typeof pid === "number" && Number.isInteger(pid) && pid > 0) {
|
|
57
|
+
try {
|
|
58
|
+
probe(pid);
|
|
59
|
+
return null;
|
|
60
|
+
}
|
|
61
|
+
catch (error) {
|
|
62
|
+
if (error.code === "EPERM") {
|
|
63
|
+
return `Note: the ${CLI.command} host daemon for ${configDir} runs as another user (pid ${pid}). It cannot read a session stored by you: run \`${CLI.command} os connect\` as that user.`;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return `Note: no ${CLI.command} host daemon is running from this config folder (${configDir}). The daemon is what uses the session. `
|
|
68
|
+
+ `If yours runs as another user or with another config folder (a system service, or ${envVar("CONFIG_DIR")}), run \`${CLI.command} os connect\` as that user with that folder; otherwise start \`${CLI.command} host\`.`;
|
|
69
|
+
}
|
|
70
|
+
async function askVisible(question) {
|
|
71
|
+
if (!process.stdin.isTTY)
|
|
72
|
+
throw new Error(`Give the ${OS.noun} address: ${CLI.command} os connect https://os.example`);
|
|
73
|
+
const rl = createInterface({ input: process.stdin, output: process.stderr });
|
|
74
|
+
try {
|
|
75
|
+
return await rl.question(question);
|
|
76
|
+
}
|
|
77
|
+
finally {
|
|
78
|
+
rl.close();
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
export function osCommandHelp() {
|
|
82
|
+
return [
|
|
83
|
+
`Usage: ${CLI.command} os [connect [https://<os address>] | status [--check] | forget]`,
|
|
84
|
+
"",
|
|
85
|
+
` os connect Connect this machine to Overvues: ${CLI.command} opens ${OS.the} in your browser, you confirm there,`,
|
|
86
|
+
` and ${OS.the} sends this machine a session that lasts 30 days. On a Mac it is kept in the`,
|
|
87
|
+
" keychain; on other machines, in a file only you can read.",
|
|
88
|
+
` os status Show whether this machine is connected to ${OS.the}, as whom, and until when`,
|
|
89
|
+
" (--check also asks the keychain for the session, which may ask you to unlock it)",
|
|
90
|
+
` os forget Forget the ${OS.noun} session kept on this machine`,
|
|
91
|
+
"",
|
|
92
|
+
`The session is used by the \`${CLI.command} host\` daemon running as the same user with the same config folder.`,
|
|
93
|
+
"`os status` and `os connect` say so when no such daemon is running.",
|
|
94
|
+
].join("\n");
|
|
95
|
+
}
|
|
96
|
+
const who = (account) => (account.name && account.name !== account.id ? `${account.name} (${account.id})` : account.id);
|
|
97
|
+
const kept = (store) => (store === "keychain" ? "in the Mac keychain" : "in a file only you can read");
|
|
98
|
+
/** The handoff: explains, opens the OS's confirm page, and waits for the OS to send the session. */
|
|
99
|
+
async function receiveByHandoff(osUrl, dependencies, write) {
|
|
100
|
+
const atTerminal = dependencies.atTerminal ?? (() => Boolean(process.stdin.isTTY && process.stderr.isTTY));
|
|
101
|
+
if (!atTerminal()) {
|
|
102
|
+
throw new Error(`\`${CLI.command} os connect\` is run by a person at a terminal on this machine: it opens a page in your browser for you to confirm. It was not started.`);
|
|
103
|
+
}
|
|
104
|
+
const attempt = await (dependencies.startHandoff ?? (() => startOsHandoff()))();
|
|
105
|
+
try {
|
|
106
|
+
if (!acceptsEveryHubKind()) {
|
|
107
|
+
// The address, where it cannot be missed: everything this machine ships goes there.
|
|
108
|
+
write("");
|
|
109
|
+
write(` ${OS.noun} address: ${osUrl}`);
|
|
110
|
+
write("");
|
|
111
|
+
write(` Check this is your ${OS.noun} before you go on. To use another, stop here (Ctrl-C) and run \`${CLI.command} os connect <address>\`.`);
|
|
112
|
+
}
|
|
113
|
+
write("");
|
|
114
|
+
write("What happens next:");
|
|
115
|
+
write(` 1. ${CLI.command} opens a page of ${osUrl} in your browser on this computer. Sign in there if it asks.`);
|
|
116
|
+
write(` 2. The page asks "Continue in Cloudflare OS?". It cannot say who is asking, so it does not mention your hub or ${CLI.command}.`);
|
|
117
|
+
write(` 3. When you press Continue, ${OS.the} makes a new session for your account and sends it to this ${CLI.command}, on this`);
|
|
118
|
+
write(` computer only. It lets ${CLI.command} deploy, pull and publish previews as you, for 30 days.`);
|
|
119
|
+
write("");
|
|
120
|
+
write("Confirm only the page that opens right after you press Enter here. If that page ever appears when you did not");
|
|
121
|
+
write(`just run \`${CLI.command} os connect\` yourself, in your own terminal, close it without pressing Continue: whoever`);
|
|
122
|
+
write("started it would get a session for your account.");
|
|
123
|
+
write("");
|
|
124
|
+
await (dependencies.ask ?? askVisible)("Press Enter to open the page (Ctrl-C to stop): ");
|
|
125
|
+
// Listening, and the two minutes running, before the page can answer.
|
|
126
|
+
const waiting = attempt.wait();
|
|
127
|
+
waiting.catch(() => { });
|
|
128
|
+
// The address holds the attempt's state, so it is opened and never shown.
|
|
129
|
+
const opened = await (dependencies.openBrowser ?? openBrowser)(attempt.confirmUrl(osUrl));
|
|
130
|
+
if (!opened) {
|
|
131
|
+
throw new Error(`${CLI.command} could not open a browser on this computer, so the machine was not connected. Nothing was stored. (A machine with no browser cannot be connected this way yet, and there is no link to copy.)`);
|
|
132
|
+
}
|
|
133
|
+
write("Waiting for you to confirm in the browser. This attempt ends in two minutes.");
|
|
134
|
+
const received = await waiting;
|
|
135
|
+
const ignored = Object.values(attempt.refused()).reduce((sum, count) => sum + (count ?? 0), 0);
|
|
136
|
+
if (ignored)
|
|
137
|
+
write(`(${ignored} request${ignored === 1 ? "" : "s"} to ${CLI.command}'s local port did not match this attempt and ${ignored === 1 ? "was" : "were"} ignored.)`);
|
|
138
|
+
return received;
|
|
139
|
+
}
|
|
140
|
+
finally {
|
|
141
|
+
attempt.cancel();
|
|
142
|
+
}
|
|
143
|
+
}
|
|
144
|
+
function statusLines(info, now) {
|
|
145
|
+
const expiry = osSessionExpiry(info.expiresAt, now);
|
|
146
|
+
const lines = [];
|
|
147
|
+
if (expiry.state === "expired") {
|
|
148
|
+
lines.push(`This machine was connected to ${info.osUrl} as ${who(info.account)}, and that session has run out.`);
|
|
149
|
+
}
|
|
150
|
+
else {
|
|
151
|
+
lines.push(`This machine is connected to ${info.osUrl} as ${who(info.account)} (since ${info.savedAt.slice(0, 10)}). The session is kept ${kept(info.store)}.`);
|
|
152
|
+
}
|
|
153
|
+
if (expiry.state === "ok")
|
|
154
|
+
lines.push(`It lasts until ${expiry.expiresAt.slice(0, 10)} (${expiry.daysLeft} days). Run \`${CLI.command} os connect\` again by then.`);
|
|
155
|
+
else if (expiry.state === "unknown")
|
|
156
|
+
lines.push(`${CLI.command} does not know when it ends. \`${CLI.command} os connect\` gets one that lasts 30 days.`);
|
|
157
|
+
else
|
|
158
|
+
lines.push(osSessionExpiryLine(expiry));
|
|
159
|
+
return lines;
|
|
160
|
+
}
|
|
161
|
+
export async function runOsCommand(args, dependencies) {
|
|
162
|
+
// A person is running this, so the keychain may ask them to unlock it.
|
|
163
|
+
const store = dependencies.store ?? machineOsSessionStore(dependencies.configDir, { interactive: true });
|
|
164
|
+
const write = dependencies.write ?? ((line) => { process.stderr.write(`${line}\n`); });
|
|
165
|
+
const now = () => dependencies.now?.() ?? new Date();
|
|
166
|
+
const [command, ...rest] = args;
|
|
167
|
+
const noteDaemon = () => {
|
|
168
|
+
const note = (dependencies.daemonNote ?? (() => hostDaemonNote(dependencies.configDir)))();
|
|
169
|
+
if (note)
|
|
170
|
+
write(note);
|
|
171
|
+
};
|
|
172
|
+
if (command === "status" && (rest.length === 0 || (rest.length === 1 && rest[0] === "--check"))) {
|
|
173
|
+
const info = store.describe();
|
|
174
|
+
if (!info) {
|
|
175
|
+
write(`This machine is not connected to ${OS.the}. Run \`${CLI.command} os connect\`.`);
|
|
176
|
+
}
|
|
177
|
+
else {
|
|
178
|
+
for (const line of statusLines(info, now().getTime()))
|
|
179
|
+
write(line);
|
|
180
|
+
if (rest[0] === "--check") {
|
|
181
|
+
try {
|
|
182
|
+
store.load();
|
|
183
|
+
write(`The session could be read ${info.store === "keychain" ? "from the Mac keychain" : "from its file"}.`);
|
|
184
|
+
}
|
|
185
|
+
catch (error) {
|
|
186
|
+
write(error instanceof OsSessionUnavailableError ? error.message : "The stored session could not be read.");
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
noteDaemon();
|
|
191
|
+
return;
|
|
192
|
+
}
|
|
193
|
+
if (command === "forget" && rest.length === 0) {
|
|
194
|
+
write(store.forget()
|
|
195
|
+
? `Forgot the ${OS.noun} session kept on this machine. ${OS.The} itself cannot take a session back: it stays valid there until it runs out, up to 30 days after it was made.`
|
|
196
|
+
: `This machine holds no ${OS.noun} session.`);
|
|
197
|
+
return;
|
|
198
|
+
}
|
|
199
|
+
if (command !== "connect" || rest.length > 1 || rest.some((argument) => argument.startsWith("--"))) {
|
|
200
|
+
throw new Error(`${command ? "Unknown os command" : `${CLI.command} os needs a command`}.\n${osCommandHelp()}`);
|
|
201
|
+
}
|
|
202
|
+
// The Hub is asked first: a hub with no link to Overvues refuses, and nothing is opened. Its
|
|
203
|
+
// answer is kept for the owner check below; the Hub is told nothing either way.
|
|
204
|
+
const { hub } = dependencies;
|
|
205
|
+
const askOwner = dependencies.hubOwner ?? (hub ? () => askHubOwner(hubFetcher(hub.url, hub.headers)) : null);
|
|
206
|
+
const owner = askOwner ? await askOwner() : { known: false, why: "this machine has no Hub yet" };
|
|
207
|
+
if ("kindRefused" in owner && owner.kindRefused) {
|
|
208
|
+
throw new Error(`Your Hub does not connect machines to Overvues: ${owner.why}\nNothing was opened or stored.`);
|
|
209
|
+
}
|
|
210
|
+
let before = null;
|
|
211
|
+
try {
|
|
212
|
+
before = store.describe();
|
|
213
|
+
}
|
|
214
|
+
catch {
|
|
215
|
+
before = null;
|
|
216
|
+
}
|
|
217
|
+
// Which Overvues: the address given here wins; then the one this machine is already connected
|
|
218
|
+
// to; the hub's report is used only when nothing is stored, and never overrides what is.
|
|
219
|
+
const address = rest[0] ?? await (async () => {
|
|
220
|
+
const reported = await dependencies.hubOsOrigin?.() ?? null;
|
|
221
|
+
const stored = before?.osUrl ?? null;
|
|
222
|
+
if (stored && reported) {
|
|
223
|
+
let reportedOrigin = null;
|
|
224
|
+
try {
|
|
225
|
+
reportedOrigin = osOriginOf(reported);
|
|
226
|
+
}
|
|
227
|
+
catch {
|
|
228
|
+
reportedOrigin = null;
|
|
229
|
+
}
|
|
230
|
+
if (reportedOrigin !== null && reportedOrigin !== osOriginOf(stored)) {
|
|
231
|
+
throw new Error(`This machine is connected to ${stored}, and your hub reports ${reportedOrigin}. ${CLI.command} does not choose between them. `
|
|
232
|
+
+ `Nothing was opened or stored. Run \`${CLI.command} os connect <address>\` with the address you mean.`);
|
|
233
|
+
}
|
|
234
|
+
}
|
|
235
|
+
return stored ?? reported ?? await (dependencies.ask ?? askVisible)(`${OS.noun} address (https://...): `);
|
|
236
|
+
})();
|
|
237
|
+
const osUrl = osOriginOf(address);
|
|
238
|
+
write(`Connecting this machine to ${osUrl}.`);
|
|
239
|
+
const { session, expiresAt, userId: namedUserId } = await receiveByHandoff(osUrl, dependencies, write);
|
|
240
|
+
const scrub = (text) => redactValues(text, [session, encodeURIComponent(session)], `[${OS.noun} session removed]`);
|
|
241
|
+
// Whose session it is comes from the OS, at the address this command was given, and from nothing else.
|
|
242
|
+
const savedAt = now().toISOString();
|
|
243
|
+
const candidate = { osUrl, session, account: { id: "", name: "" }, savedAt };
|
|
244
|
+
let account;
|
|
245
|
+
try {
|
|
246
|
+
const os = await (dependencies.connectOs ?? connectStoredOs)(candidate, () => { });
|
|
247
|
+
account = { id: os.account.id, name: os.account.name };
|
|
248
|
+
os.close();
|
|
249
|
+
}
|
|
250
|
+
catch (error) {
|
|
251
|
+
const reason = error instanceof OsAdapterError || error instanceof Error ? scrub(error.message) : `${OS.the} could not be reached`;
|
|
252
|
+
throw new Error(`${reason}\nNothing was stored.`);
|
|
253
|
+
}
|
|
254
|
+
if (!account.id)
|
|
255
|
+
throw new Error(`${OS.The} did not say whose session that is. Nothing was stored.`);
|
|
256
|
+
if (namedUserId !== account.id) {
|
|
257
|
+
throw new Error(`What arrived names one account and ${OS.the} says it belongs to another. Nothing was stored.`);
|
|
258
|
+
}
|
|
259
|
+
// The account from the first connection is kept: a session for someone else does not replace it silently.
|
|
260
|
+
if (before && before.osUrl === osUrl && before.account.id !== account.id) {
|
|
261
|
+
throw new Error(`That session belongs to ${scrub(who(account))}, and this machine is connected as ${who(before.account)}. `
|
|
262
|
+
+ `Nothing was stored. To change accounts, run \`${CLI.command} os forget\` first.`);
|
|
263
|
+
}
|
|
264
|
+
// The Hub can only refuse here. It never makes an account acceptable, and it is told nothing.
|
|
265
|
+
if (owner.known && !sameAccount(owner.email, account.id)) {
|
|
266
|
+
throw new Error(`That session belongs to ${scrub(who(account))}, and your Hub belongs to ${owner.email}. A machine deploys as its Hub's owner, so nothing was stored. `
|
|
267
|
+
+ `Sign in to ${OS.the} as the Hub's owner in your browser, then run \`${CLI.command} os connect\` again.`);
|
|
268
|
+
}
|
|
269
|
+
write(`${OS.The} says this session belongs to ${scrub(who(account))}.`);
|
|
270
|
+
if (owner.known) {
|
|
271
|
+
write("That is the owner of your Hub.");
|
|
272
|
+
}
|
|
273
|
+
else {
|
|
274
|
+
write(`${CLI.command} could not check that against your Hub (${owner.why}).`);
|
|
275
|
+
if (!(before && before.osUrl === osUrl)) {
|
|
276
|
+
const reply = (await (dependencies.ask ?? askVisible)("Is that your account? Type yes to keep the session on this machine: ")).trim().toLowerCase();
|
|
277
|
+
if (reply !== "yes" && reply !== "y")
|
|
278
|
+
throw new Error(`Not confirmed. Nothing was stored. The session ${OS.the} made is not kept anywhere and runs out by itself.`);
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
const kind = store.preferred;
|
|
282
|
+
try {
|
|
283
|
+
store.save({ osUrl, session, account, savedAt, expiresAt, connectedBy: "handoff" });
|
|
284
|
+
}
|
|
285
|
+
catch (error) {
|
|
286
|
+
const reason = error instanceof Error ? scrub(error.message) : "the session could not be saved";
|
|
287
|
+
throw new Error(`${reason}\nNothing was stored.`);
|
|
288
|
+
}
|
|
289
|
+
write(`Connected to ${osUrl} as ${scrub(who(account))}.`);
|
|
290
|
+
write(`The session is kept ${kept(kind)}. It lasts until ${expiresAt.slice(0, 10)}; run \`${CLI.command} os connect\` again by then, and \`${CLI.command} os forget\` to remove it.`);
|
|
291
|
+
noteDaemon();
|
|
292
|
+
}
|
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
// `tiller`'s side of the OS's device-session handoff: how an OS session reaches this machine.
|
|
2
|
+
//
|
|
3
|
+
// The OS's side, as built upstream (cloudflare-os `docs/oauth-signin.md`, "Desktop callback
|
|
4
|
+
// delivery"; `workshop-backend/src/auth/device-session-handoff.ts` and `-callback.ts`):
|
|
5
|
+
//
|
|
6
|
+
// 1. `tiller` makes a P-256 key pair and listens on a fresh port of 127.0.0.1.
|
|
7
|
+
// 2. It opens `<OS>/?cfos_native_state=<state>&cfos_native_key=<public key>` in the person's
|
|
8
|
+
// browser. The state is `desktop-v1.<port>.<43 characters>`.
|
|
9
|
+
// 3. The person confirms on the OS's page. The OS makes a new 30-day session, encrypts it to
|
|
10
|
+
// the public key with the state as authenticated data, and redirects the browser to
|
|
11
|
+
// `http://127.0.0.1:<port>/oauthredirect?cfos_callback=install-connected&state=…&publicKey=…
|
|
12
|
+
// &salt=…&iv=…&ciphertext=…`. The transfer is single-use and lasts two minutes.
|
|
13
|
+
// 4. The listener here checks that request and decrypts it.
|
|
14
|
+
//
|
|
15
|
+
// What the listener checks, each of which leaves the attempt open when it fails:
|
|
16
|
+
//
|
|
17
|
+
// - the request came from this computer, is a GET, and carries one Host header that is exactly
|
|
18
|
+
// `127.0.0.1:<its own port>`;
|
|
19
|
+
// - the path is exactly `/oauthredirect`, with each of the six parameters present once and no
|
|
20
|
+
// others;
|
|
21
|
+
// - the state is the full value issued here, compared in constant time;
|
|
22
|
+
// - it arrived within two minutes of the page being opened, and the transfer's own deadline
|
|
23
|
+
// has not passed and is no more than two minutes away;
|
|
24
|
+
// - the envelope decrypts with this attempt's key and state, and what is inside is an OS
|
|
25
|
+
// session (`kind: "workshop"`, `<user id>:<32-byte secret>`, with an end date) and nothing
|
|
26
|
+
// else. An Access credential is refused.
|
|
27
|
+
//
|
|
28
|
+
// The state, the private key and the session are never logged, printed or put in an error. A
|
|
29
|
+
// refused request is counted by its reason only. Decrypting proves nothing about who sent it:
|
|
30
|
+
// anyone holding the public key can encrypt. The caller asks the OS whose session it is.
|
|
31
|
+
import { createHash, randomBytes, timingSafeEqual, webcrypto } from "node:crypto";
|
|
32
|
+
import { createServer } from "node:http";
|
|
33
|
+
import { CLI, OS } from "./identity.js";
|
|
34
|
+
const { subtle } = webcrypto;
|
|
35
|
+
/** The transfer's lifetime at the OS, and how long the listener waits. */
|
|
36
|
+
export const HANDOFF_DEADLINE_MS = 2 * 60_000;
|
|
37
|
+
/** Room for this machine's clock and the OS's to differ when the transfer's deadline is read. */
|
|
38
|
+
const CLOCK_SLACK_MS = 60_000;
|
|
39
|
+
/** The OS ends a device session after 30 days; one that claims much longer is not what the OS makes. */
|
|
40
|
+
const MAX_SESSION_LIFETIME_MS = 32 * 24 * 60 * 60_000;
|
|
41
|
+
const CALLBACK_PATH = "/oauthredirect";
|
|
42
|
+
const CALLBACK_PARAMETERS = ["cfos_callback", "state", "publicKey", "salt", "iv", "ciphertext"];
|
|
43
|
+
const CALLBACK_KIND = "install-connected";
|
|
44
|
+
const ENVELOPE_CONTEXT = new TextEncoder().encode("cloudflare-os-device-session-v1");
|
|
45
|
+
const BASE64URL = /^[A-Za-z0-9_-]+$/;
|
|
46
|
+
/** `<user id>:<padded standard base64 of 32 bytes>`. */
|
|
47
|
+
const OS_SESSION_TOKEN = /^([^:\s]+):([A-Za-z0-9+/]{43}=)$/;
|
|
48
|
+
const MAX_URL_CHARS = 16 * 1024;
|
|
49
|
+
/** A request the listener refused. It carries the reason and never anything from the request. */
|
|
50
|
+
export class HandoffRefused extends Error {
|
|
51
|
+
reason;
|
|
52
|
+
constructor(reason) {
|
|
53
|
+
super(`handoff request refused: ${reason}`);
|
|
54
|
+
this.reason = reason;
|
|
55
|
+
this.name = "HandoffRefused";
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
const base64url = (bytes) => Buffer.from(bytes).toString("base64url");
|
|
59
|
+
function decodeBase64url(value, length) {
|
|
60
|
+
if (!BASE64URL.test(value))
|
|
61
|
+
throw new HandoffRefused("envelope");
|
|
62
|
+
const bytes = Buffer.from(value, "base64url");
|
|
63
|
+
if (base64url(bytes) !== value || (length !== undefined && bytes.length !== length))
|
|
64
|
+
throw new HandoffRefused("envelope");
|
|
65
|
+
const copy = new Uint8Array(new ArrayBuffer(bytes.length));
|
|
66
|
+
copy.set(bytes);
|
|
67
|
+
return copy;
|
|
68
|
+
}
|
|
69
|
+
/** Whether two values are the same, in time that does not depend on where they differ. */
|
|
70
|
+
function sameValue(left, right) {
|
|
71
|
+
const a = createHash("sha256").update(left).digest();
|
|
72
|
+
const b = createHash("sha256").update(right).digest();
|
|
73
|
+
return timingSafeEqual(a, b);
|
|
74
|
+
}
|
|
75
|
+
/** The query's parameters as sent: each name with every value it was given. */
|
|
76
|
+
function rawParameters(query) {
|
|
77
|
+
const found = new Map();
|
|
78
|
+
for (const part of query.split("&")) {
|
|
79
|
+
const at = part.indexOf("=");
|
|
80
|
+
if (at <= 0)
|
|
81
|
+
return null;
|
|
82
|
+
const name = part.slice(0, at);
|
|
83
|
+
const value = part.slice(at + 1);
|
|
84
|
+
// What the OS sends needs no escaping at all. Anything else is not the OS's redirect.
|
|
85
|
+
if (!/^[A-Za-z_]+$/.test(name) || !/^[A-Za-z0-9._~-]+$/.test(value))
|
|
86
|
+
return null;
|
|
87
|
+
found.set(name, [...(found.get(name) ?? []), value]);
|
|
88
|
+
}
|
|
89
|
+
return found;
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* Checks one request against the attempt and decrypts it. Throws `HandoffRefused` for anything
|
|
93
|
+
* that is not this attempt's redirect from the OS; the attempt is not affected.
|
|
94
|
+
*/
|
|
95
|
+
export async function checkHandoffRequest(request, context) {
|
|
96
|
+
if (request.remoteAddress !== "127.0.0.1")
|
|
97
|
+
throw new HandoffRefused("not-local");
|
|
98
|
+
if (request.method !== "GET")
|
|
99
|
+
throw new HandoffRefused("method");
|
|
100
|
+
// Addressed to exactly this listener: one Host header, and it is this address and port.
|
|
101
|
+
const hosts = [];
|
|
102
|
+
for (let index = 0; index + 1 < request.rawHeaders.length; index += 2) {
|
|
103
|
+
if (request.rawHeaders[index].toLowerCase() === "host")
|
|
104
|
+
hosts.push(request.rawHeaders[index + 1]);
|
|
105
|
+
}
|
|
106
|
+
if (hosts.length !== 1 || hosts[0] !== `127.0.0.1:${context.port}`)
|
|
107
|
+
throw new HandoffRefused("host");
|
|
108
|
+
const url = request.url ?? "";
|
|
109
|
+
if (url.length > MAX_URL_CHARS || !url.startsWith(`${CALLBACK_PATH}?`))
|
|
110
|
+
throw new HandoffRefused("path");
|
|
111
|
+
const parameters = rawParameters(url.slice(CALLBACK_PATH.length + 1));
|
|
112
|
+
if (!parameters || parameters.size !== CALLBACK_PARAMETERS.length)
|
|
113
|
+
throw new HandoffRefused("parameters");
|
|
114
|
+
const value = (name) => {
|
|
115
|
+
const values = parameters.get(name);
|
|
116
|
+
if (!values || values.length !== 1)
|
|
117
|
+
throw new HandoffRefused("parameters");
|
|
118
|
+
return values[0];
|
|
119
|
+
};
|
|
120
|
+
const sent = Object.fromEntries(CALLBACK_PARAMETERS.map((name) => [name, value(name)]));
|
|
121
|
+
if (sent.cfos_callback !== CALLBACK_KIND)
|
|
122
|
+
throw new HandoffRefused("callback-kind");
|
|
123
|
+
if (!sameValue(sent.state, context.state))
|
|
124
|
+
throw new HandoffRefused("state");
|
|
125
|
+
if (context.now > context.deadline)
|
|
126
|
+
throw new HandoffRefused("deadline");
|
|
127
|
+
const peer = decodeBase64url(sent.publicKey, 65);
|
|
128
|
+
if (peer[0] !== 4)
|
|
129
|
+
throw new HandoffRefused("envelope");
|
|
130
|
+
const salt = decodeBase64url(sent.salt, 32);
|
|
131
|
+
const iv = decodeBase64url(sent.iv, 12);
|
|
132
|
+
const ciphertext = decodeBase64url(sent.ciphertext);
|
|
133
|
+
let plaintext;
|
|
134
|
+
try {
|
|
135
|
+
const ephemeral = await subtle.importKey("raw", peer, { name: "ECDH", namedCurve: "P-256" }, false, []);
|
|
136
|
+
const shared = await subtle.deriveBits({ name: "ECDH", public: ephemeral }, context.privateKey, 256);
|
|
137
|
+
const material = await subtle.importKey("raw", shared, "HKDF", false, ["deriveKey"]);
|
|
138
|
+
const key = await subtle.deriveKey({ name: "HKDF", hash: "SHA-256", salt, info: ENVELOPE_CONTEXT }, material, { name: "AES-GCM", length: 256 }, false, ["decrypt"]);
|
|
139
|
+
plaintext = await subtle.decrypt({ name: "AES-GCM", iv, additionalData: new TextEncoder().encode(context.state) }, key, ciphertext);
|
|
140
|
+
}
|
|
141
|
+
catch {
|
|
142
|
+
throw new HandoffRefused("envelope");
|
|
143
|
+
}
|
|
144
|
+
let transfer;
|
|
145
|
+
try {
|
|
146
|
+
transfer = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(plaintext));
|
|
147
|
+
}
|
|
148
|
+
catch {
|
|
149
|
+
transfer = null;
|
|
150
|
+
}
|
|
151
|
+
if (!transfer || typeof transfer !== "object" || !transfer.credential || typeof transfer.credential !== "object")
|
|
152
|
+
throw new HandoffRefused("transfer");
|
|
153
|
+
// The OS's own two-minute deadline for this transfer.
|
|
154
|
+
if (typeof transfer.expiresAt !== "number" || !Number.isFinite(transfer.expiresAt) || transfer.expiresAt <= context.now
|
|
155
|
+
|| transfer.expiresAt > context.now + HANDOFF_DEADLINE_MS + CLOCK_SLACK_MS)
|
|
156
|
+
throw new HandoffRefused("transfer-deadline");
|
|
157
|
+
const credential = transfer.credential;
|
|
158
|
+
// An OS session and nothing else: not an Access credential, and not a kind added later.
|
|
159
|
+
if (credential.kind !== "workshop" || typeof credential.token !== "string")
|
|
160
|
+
throw new HandoffRefused("not-an-os-session");
|
|
161
|
+
const token = OS_SESSION_TOKEN.exec(credential.token);
|
|
162
|
+
if (!token || credential.token.length > 1024)
|
|
163
|
+
throw new HandoffRefused("not-an-os-session");
|
|
164
|
+
if (typeof credential.expiresAt !== "number" || !Number.isFinite(credential.expiresAt) || credential.expiresAt <= context.now
|
|
165
|
+
|| credential.expiresAt > context.now + MAX_SESSION_LIFETIME_MS)
|
|
166
|
+
throw new HandoffRefused("session-expired");
|
|
167
|
+
return { session: credential.token, userId: token[1], expiresAt: new Date(credential.expiresAt).toISOString() };
|
|
168
|
+
}
|
|
169
|
+
function answer(response, status, title, body) {
|
|
170
|
+
response.writeHead(status, {
|
|
171
|
+
"Content-Type": "text/html; charset=utf-8",
|
|
172
|
+
"Cache-Control": "no-store",
|
|
173
|
+
"Referrer-Policy": "no-referrer",
|
|
174
|
+
"Content-Security-Policy": "default-src 'none'; style-src 'unsafe-inline'",
|
|
175
|
+
"X-Content-Type-Options": "nosniff",
|
|
176
|
+
"Connection": "close",
|
|
177
|
+
});
|
|
178
|
+
response.end(`<!doctype html><meta charset="utf-8"><title>${title}</title>`
|
|
179
|
+
+ `<body style="font-family:system-ui;max-width:32rem;margin:4rem auto;padding:0 1rem"><h1>${title}</h1><p>${body}</p>`);
|
|
180
|
+
}
|
|
181
|
+
function closeServer(server) {
|
|
182
|
+
server.close();
|
|
183
|
+
server.closeAllConnections?.();
|
|
184
|
+
}
|
|
185
|
+
/**
|
|
186
|
+
* Makes the key pair and opens the listener. Nothing is sent anywhere yet: the caller explains
|
|
187
|
+
* what is about to happen, opens `confirmUrl` in the person's browser, and calls `wait`.
|
|
188
|
+
*/
|
|
189
|
+
export async function startOsHandoff(options = {}) {
|
|
190
|
+
const now = options.now ?? Date.now;
|
|
191
|
+
// The private key cannot be exported, and lives only as long as this attempt.
|
|
192
|
+
const keys = await subtle.generateKey({ name: "ECDH", namedCurve: "P-256" }, false, ["deriveBits"]);
|
|
193
|
+
const publicKey = base64url(new Uint8Array(await subtle.exportKey("raw", keys.publicKey)));
|
|
194
|
+
if (publicKey.length !== 87)
|
|
195
|
+
throw new Error("This machine could not make a key for the handoff.");
|
|
196
|
+
const server = createServer({ maxHeaderSize: 32 * 1024, requestTimeout: 10_000, headersTimeout: 10_000, keepAlive: false });
|
|
197
|
+
let port = 0;
|
|
198
|
+
// The OS delivers only to ports 1024 to 65535 written without a leading zero and with four or five digits.
|
|
199
|
+
for (let attempt = 0; attempt < 5 && port < 1024; attempt += 1) {
|
|
200
|
+
await new Promise((resolve, reject) => {
|
|
201
|
+
server.once("error", reject);
|
|
202
|
+
server.listen({ host: "127.0.0.1", port: 0, exclusive: true }, () => {
|
|
203
|
+
server.off("error", reject);
|
|
204
|
+
resolve();
|
|
205
|
+
});
|
|
206
|
+
});
|
|
207
|
+
port = server.address().port;
|
|
208
|
+
if (port < 1024) {
|
|
209
|
+
await new Promise((resolve) => server.close(() => resolve()));
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
if (port < 1024)
|
|
213
|
+
throw new Error("This machine could not open a local port for the handoff.");
|
|
214
|
+
const state = `desktop-v1.${port}.${base64url(randomBytes(32))}`;
|
|
215
|
+
const counts = {};
|
|
216
|
+
let finished = false;
|
|
217
|
+
let finish = null;
|
|
218
|
+
let waiting = null;
|
|
219
|
+
let deadline = 0;
|
|
220
|
+
let timer;
|
|
221
|
+
const end = (outcome) => {
|
|
222
|
+
if (finished)
|
|
223
|
+
return;
|
|
224
|
+
finished = true;
|
|
225
|
+
clearTimeout(timer);
|
|
226
|
+
closeServer(server);
|
|
227
|
+
finish?.(outcome);
|
|
228
|
+
};
|
|
229
|
+
server.on("request", (request, response) => {
|
|
230
|
+
request.resume();
|
|
231
|
+
if (finished || !waiting) {
|
|
232
|
+
answer(response, 410, "Nothing is waiting here", "This connection attempt is closed. Run the command again in your terminal.");
|
|
233
|
+
return;
|
|
234
|
+
}
|
|
235
|
+
checkHandoffRequest({ method: request.method, url: request.url, rawHeaders: request.rawHeaders, remoteAddress: request.socket.remoteAddress }, { port, state, privateKey: keys.privateKey, deadline, now: now() }).then((session) => {
|
|
236
|
+
if (finished) {
|
|
237
|
+
answer(response, 410, "Nothing is waiting here", "This connection attempt is closed. Run the command again in your terminal.");
|
|
238
|
+
return;
|
|
239
|
+
}
|
|
240
|
+
answer(response, 200, `Sent to ${CLI.command}`, `This machine received the sign-in. Close this tab and go back to your terminal: ${CLI.command} shows whose account it is there.`);
|
|
241
|
+
end({ session });
|
|
242
|
+
}, (error) => {
|
|
243
|
+
const reason = error instanceof HandoffRefused ? error.reason : "envelope";
|
|
244
|
+
counts[reason] = (counts[reason] ?? 0) + 1;
|
|
245
|
+
// The same words for every reason: the page tells a stranger nothing about what was wrong.
|
|
246
|
+
answer(response, 400, "Not accepted", `This request did not match the connection ${CLI.command} is waiting for. Nothing was changed.`);
|
|
247
|
+
});
|
|
248
|
+
});
|
|
249
|
+
return {
|
|
250
|
+
port,
|
|
251
|
+
confirmUrl(osUrl) {
|
|
252
|
+
const url = new URL("/", osUrl);
|
|
253
|
+
url.searchParams.set("cfos_native_state", state);
|
|
254
|
+
url.searchParams.set("cfos_native_key", publicKey);
|
|
255
|
+
return url.href;
|
|
256
|
+
},
|
|
257
|
+
wait() {
|
|
258
|
+
waiting ??= new Promise((resolve, reject) => {
|
|
259
|
+
finish = (outcome) => ("session" in outcome ? resolve(outcome.session) : reject(outcome.error));
|
|
260
|
+
if (finished) {
|
|
261
|
+
reject(new Error("The connection attempt was cancelled. Nothing was stored."));
|
|
262
|
+
return;
|
|
263
|
+
}
|
|
264
|
+
deadline = now() + HANDOFF_DEADLINE_MS;
|
|
265
|
+
timer = setTimeout(() => end({ error: new Error(`Two minutes passed and ${OS.the} sent nothing this machine could use. Nothing was stored. Run \`${CLI.command} os connect\` to try again.`) }), HANDOFF_DEADLINE_MS);
|
|
266
|
+
});
|
|
267
|
+
return waiting;
|
|
268
|
+
},
|
|
269
|
+
cancel() {
|
|
270
|
+
end({ error: new Error("The connection attempt was cancelled. Nothing was stored.") });
|
|
271
|
+
},
|
|
272
|
+
refused: () => ({ ...counts }),
|
|
273
|
+
};
|
|
274
|
+
}
|