@superintelligentfamily/key-install 0.0.0-stage → 0.1.1
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/LICENSE +21 -0
- package/package.json +29 -3
- package/src/cli.mjs +63 -0
- package/src/install.mjs +341 -0
- package/src/loopback.mjs +72 -0
- package/src/run.mjs +38 -0
- package/src/site.mjs +150 -0
- package/README.md +0 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Seth Shoultes
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/package.json
CHANGED
|
@@ -1,6 +1,32 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@superintelligentfamily/key-install",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"description": "
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"license": "MIT",
|
|
5
|
+
"description": "Adds Sign in with Key to a site: one command, a preview before each change, the secret key stored without being shown.",
|
|
6
|
+
"homepage": "https://superintelligentkey.com",
|
|
7
|
+
"repository": {
|
|
8
|
+
"type": "git",
|
|
9
|
+
"url": "git+https://github.com/sethshoultes/doorman.git",
|
|
10
|
+
"directory": "packages/install"
|
|
11
|
+
},
|
|
12
|
+
"type": "module",
|
|
13
|
+
"engines": {
|
|
14
|
+
"node": ">=22.13"
|
|
15
|
+
},
|
|
16
|
+
"bin": {
|
|
17
|
+
"key-install": "./src/cli.mjs"
|
|
18
|
+
},
|
|
19
|
+
"files": [
|
|
20
|
+
"src",
|
|
21
|
+
"LICENSE"
|
|
22
|
+
],
|
|
23
|
+
"publishConfig": {
|
|
24
|
+
"access": "public"
|
|
25
|
+
},
|
|
26
|
+
"scripts": {
|
|
27
|
+
"typecheck": "tsc --noEmit -p .",
|
|
28
|
+
"lint": "eslint .",
|
|
29
|
+
"test": "vitest run",
|
|
30
|
+
"check": "pnpm run typecheck && pnpm run lint && pnpm run test"
|
|
31
|
+
}
|
|
6
32
|
}
|
package/src/cli.mjs
ADDED
|
@@ -0,0 +1,63 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// key-install: run from a site's folder (npx @superintelligentfamily/key-install). See install.mjs for what it does.
|
|
3
|
+
import { realpathSync } from "node:fs";
|
|
4
|
+
import { createInterface } from "node:readline/promises";
|
|
5
|
+
import { pathToFileURL } from "node:url";
|
|
6
|
+
import { install, PORTS, Stop } from "./install.mjs";
|
|
7
|
+
import { loopback } from "./loopback.mjs";
|
|
8
|
+
import { runChild } from "./run.mjs";
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* The CLI, as a function of its terminal: resolves the exit code. Any stop (and an unexpected error) is 1, so
|
|
12
|
+
* `npx @superintelligentfamily/key-install && npm run deploy` never deploys a site that was not set up (maint-review on #156).
|
|
13
|
+
* @param {{ stdin: NodeJS.ReadStream, stdout: NodeJS.WriteStream }} io
|
|
14
|
+
* @param {Partial<import("./install.mjs").Deps>} [over] the installer's dependencies, as a test sets them
|
|
15
|
+
* @returns {Promise<number>}
|
|
16
|
+
*/
|
|
17
|
+
export async function main(io, over = {}) {
|
|
18
|
+
const log = (/** @type {string} */ line) => { io.stdout.write(`${line}\n`); };
|
|
19
|
+
if (!io.stdin.isTTY) {
|
|
20
|
+
log("STOPPED: the installer asks you questions; run it in a terminal. Nothing was made.");
|
|
21
|
+
return 1;
|
|
22
|
+
}
|
|
23
|
+
const rl = createInterface({ input: io.stdin, output: io.stdout });
|
|
24
|
+
try {
|
|
25
|
+
await install({
|
|
26
|
+
cwd: process.cwd(),
|
|
27
|
+
env: process.env,
|
|
28
|
+
platform: process.platform,
|
|
29
|
+
run: runChild,
|
|
30
|
+
fetch: (url, init) => fetch(url, init),
|
|
31
|
+
log,
|
|
32
|
+
ask: (q) => rl.question(q),
|
|
33
|
+
// y/n with a timer: no answer in time resolves null, and the installer asks (and Key previews) again.
|
|
34
|
+
confirm: async (q, ms) => {
|
|
35
|
+
const ac = new AbortController();
|
|
36
|
+
const timer = setTimeout(() => ac.abort(), ms);
|
|
37
|
+
try {
|
|
38
|
+
return /^y(es)?$/i.test((await rl.question(`${q} [y/n, ${Math.round(ms / 1000)}s] `, { signal: ac.signal })).trim());
|
|
39
|
+
} catch (e) {
|
|
40
|
+
if (/** @type {Error} */ (e).name !== "AbortError") throw e;
|
|
41
|
+
io.stdout.write("\n");
|
|
42
|
+
return null;
|
|
43
|
+
} finally {
|
|
44
|
+
clearTimeout(timer);
|
|
45
|
+
}
|
|
46
|
+
},
|
|
47
|
+
authorize: (href, state) => loopback(href, state, PORTS, log, undefined, "close what uses them, then run again"),
|
|
48
|
+
...over,
|
|
49
|
+
});
|
|
50
|
+
return 0;
|
|
51
|
+
} catch (e) {
|
|
52
|
+
log(`STOPPED: ${/** @type {Error} */ (e).message}`);
|
|
53
|
+
if (!(e instanceof Stop)) log("(an unexpected error; nothing after it was done)");
|
|
54
|
+
return 1;
|
|
55
|
+
} finally {
|
|
56
|
+
rl.close();
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
// Run as the command (npx links bin/key-install to this file), not when a test imports it.
|
|
61
|
+
if (process.argv[1] && import.meta.url === pathToFileURL(realpathSync(process.argv[1])).href) {
|
|
62
|
+
process.exitCode = await main({ stdin: process.stdin, stdout: process.stdout });
|
|
63
|
+
}
|
package/src/install.mjs
ADDED
|
@@ -0,0 +1,341 @@
|
|
|
1
|
+
// The Key installer (doorman#152 item 4, the plan in its comment 6995031943): one command that adds "Sign in with Key" to a
|
|
2
|
+
// site. It signs the person in with loopback PKCE, shows Key's preview before each write and asks y/n, and puts the app's
|
|
3
|
+
// secret key straight into the host's secret store on stdin. The secret is never printed, logged, put on argv or written to a
|
|
4
|
+
// file. The only thing it writes on this computer is the site's own config: the app id, so a re-run finds the app.
|
|
5
|
+
import { createHash, randomBytes } from "node:crypto";
|
|
6
|
+
import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
7
|
+
import { dirname, join } from "node:path";
|
|
8
|
+
import { BOX } from "./loopback.mjs";
|
|
9
|
+
import { detect, FUNCTION, functionSource, MANUAL_STEPS, PLUGINS, plugins, Stop, tomlAppId, tomlSessions, withTomlAppId, withTomlSessions, workerSnippet } from "./site.mjs";
|
|
10
|
+
|
|
11
|
+
export const AUTH = "https://auth.superintelligentkey.com";
|
|
12
|
+
export const API = "https://api.superintelligentkey.com/v1";
|
|
13
|
+
/** The installer's own client metadata document (Fable's fix 3), served by key-site. */
|
|
14
|
+
export const CLIENT = "https://superintelligentkey.com/.well-known/key-installer.json";
|
|
15
|
+
/** The loopback ports its client document lists, tried in order (Fable's fix 2: Key matches redirect_uris exactly). */
|
|
16
|
+
export const PORTS = [53682, 53683, 53684];
|
|
17
|
+
export const SCOPES = ["apps:write", "keys:write", "account:read"];
|
|
18
|
+
/** The same pin as scripts/key-app-setup.mjs. */
|
|
19
|
+
export const WRANGLER = "wrangler@4.156.0";
|
|
20
|
+
/** The sign-in handler a Pages or Worker site imports (the lead on #156: published under the installer's npm org). */
|
|
21
|
+
export const HANDLER = "@superintelligentfamily/key-handler";
|
|
22
|
+
/** False until HANDLER is on npm (Seth's org and token): until then only a site-kit site is installed, and a Pages or
|
|
23
|
+
* Worker site stops before anything is asked or made, never halfway (the lead on #156). The release PR flips it. */
|
|
24
|
+
export const HANDLER_PUBLISHED = false;
|
|
25
|
+
/** workers/api's CONFIRM_TTL (seconds): a confirm token lives this long. Each y/n on a write closes a minute before it. */
|
|
26
|
+
export const CONFIRM_TTL = 600;
|
|
27
|
+
/** @superintelligentfamily/key-handler's D1_SCHEMA (a test holds them equal). The installer runs with no dependencies, so it keeps a copy. */
|
|
28
|
+
export const D1_SCHEMA = `CREATE TABLE IF NOT EXISTS doorman_sessions (
|
|
29
|
+
id_hash TEXT PRIMARY KEY,
|
|
30
|
+
user_id TEXT NOT NULL,
|
|
31
|
+
refresh_hash TEXT NOT NULL,
|
|
32
|
+
refresh_enc TEXT NOT NULL,
|
|
33
|
+
access_enc TEXT NOT NULL,
|
|
34
|
+
access_exp INTEGER NOT NULL,
|
|
35
|
+
exp INTEGER NOT NULL,
|
|
36
|
+
lease_until INTEGER NOT NULL DEFAULT 0
|
|
37
|
+
)`;
|
|
38
|
+
const CHILD_ENV = ["PATH", "HOME", "USER", "LOGNAME", "TMPDIR", "LANG", "SHELL", "XDG_CONFIG_HOME", "CLOUDFLARE_API_TOKEN", "CLOUDFLARE_ACCOUNT_ID"];
|
|
39
|
+
// Windows: npx.cmd runs under cmd.exe, which needs these; wrangler keeps its sign-in under APPDATA and USERPROFILE.
|
|
40
|
+
const WINDOWS_ENV = ["APPDATA", "USERPROFILE", "LOCALAPPDATA", "SystemRoot", "ComSpec", "PATHEXT", "TEMP", "TMP"];
|
|
41
|
+
const PROJECT = /^[a-z0-9][a-z0-9-]{0,57}$/;
|
|
42
|
+
const DB_NAME = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
|
|
43
|
+
|
|
44
|
+
/**
|
|
45
|
+
* @typedef {{
|
|
46
|
+
* cwd: string,
|
|
47
|
+
* env: Record<string, string | undefined>,
|
|
48
|
+
* platform: string,
|
|
49
|
+
* run: (cmd: string, args: string[], opts: { input?: string, env: Record<string, string>, mask?: string }) => Promise<string>,
|
|
50
|
+
* fetch: (url: string, init: RequestInit) => Promise<Response>,
|
|
51
|
+
* log: (line: string) => void,
|
|
52
|
+
* ask: (question: string) => Promise<string>,
|
|
53
|
+
* confirm: (question: string, ms: number) => Promise<boolean | null>,
|
|
54
|
+
* authorize: (href: (port: number) => string, state: string) => Promise<string>,
|
|
55
|
+
* handlerPublished?: boolean | undefined,
|
|
56
|
+
* }} Deps
|
|
57
|
+
*/
|
|
58
|
+
|
|
59
|
+
const b64url = (/** @type {Buffer} */ b) => b.toString("base64url");
|
|
60
|
+
|
|
61
|
+
/** The person's https origin, e.g. https://example.com: asked, never guessed. */
|
|
62
|
+
export function originOf(/** @type {string} */ answer) {
|
|
63
|
+
const s = answer.trim().replace(/\/+$/, "");
|
|
64
|
+
let u;
|
|
65
|
+
try { u = new URL(s); } catch { return null; }
|
|
66
|
+
return u.protocol === "https:" && u.origin === s ? s : null;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** @param {Deps} deps */
|
|
70
|
+
export async function install(deps) {
|
|
71
|
+
const { cwd, log } = deps;
|
|
72
|
+
const site = detect(cwd);
|
|
73
|
+
if (site.kind === "manual") {
|
|
74
|
+
for (const line of MANUAL_STEPS) log(line);
|
|
75
|
+
return { kind: site.kind, appId: null };
|
|
76
|
+
}
|
|
77
|
+
if ((site.kind === "pages" || site.kind === "worker") && !(deps.handlerPublished ?? HANDLER_PUBLISHED)) {
|
|
78
|
+
// A stop, not a return, so the command exits 1 (maint-review on #156): "install && deploy" must not deploy.
|
|
79
|
+
throw new Stop(`this ${site.kind === "pages" ? "static Cloudflare Pages site" : "Cloudflare Worker"} needs ${HANDLER} (not published yet), `
|
|
80
|
+
+ "so nothing was asked for and nothing was made. Until it ships, set the site up on Key's dashboard "
|
|
81
|
+
+ "(https://dash.superintelligentkey.com), or use a site-kit site, which the installer supports now.");
|
|
82
|
+
}
|
|
83
|
+
log("Key installer: adds \"Sign in with Key\" to this site.");
|
|
84
|
+
log("It signs you in to Key in your browser and asks for three permissions: apps:write, keys:write and account:read.");
|
|
85
|
+
log(`On the consent page, "${BOX["keys:write"]}" (keys:write) starts unticked: tick it. A second run within 30 days skips that page.`);
|
|
86
|
+
log("Before each change Key makes you see what it will do, and answer y or n. The secret key is never shown: it goes");
|
|
87
|
+
log("straight into Cloudflare. Nothing is saved on this computer except this site's own config (the app's id).");
|
|
88
|
+
|
|
89
|
+
/** A y/n for a change on this computer or in Cloudflare: no answer in time asks again. A no stops the run. */
|
|
90
|
+
const yes = async (/** @type {string} */ q) => {
|
|
91
|
+
for (;;) {
|
|
92
|
+
const a = await deps.confirm(q, (CONFIRM_TTL - 60) * 1000);
|
|
93
|
+
if (a === true) return;
|
|
94
|
+
if (a === false) throw new Stop("you said no. Nothing more was changed; what was done stays, and a re-run picks up from here");
|
|
95
|
+
log("no answer in time; asking again");
|
|
96
|
+
}
|
|
97
|
+
};
|
|
98
|
+
|
|
99
|
+
// What the site already records, and what the person tells us. Nothing is guessed.
|
|
100
|
+
const where = site.kind === "sitekit" ? "members.app in .sitekit/plugins.json" : "KEY_APP_ID in wrangler.toml";
|
|
101
|
+
const members = site.kind === "sitekit" ? (plugins(cwd).members ?? {}) : null;
|
|
102
|
+
const recorded = members ? (typeof members.app === "string" ? members.app : null) : tomlAppId(site.toml ?? "");
|
|
103
|
+
log(recorded ? `This site records the Key app ${recorded} (${where}): a re-run changes only what's missing.` : `This site has no Key app yet (${where}).`);
|
|
104
|
+
const project = site.project ?? (await deps.ask("Your Cloudflare Pages project's name: ")).trim();
|
|
105
|
+
if (!PROJECT.test(project)) throw new Stop(`"${project}" is not a Cloudflare project name (a-z, 0-9 and -). Nothing was made`);
|
|
106
|
+
const origin = originOf(await deps.ask("Your site's address, as people type it (e.g. https://example.com): "));
|
|
107
|
+
if (!origin) throw new Stop("that is not an https address with no path, like https://example.com. Nothing was made");
|
|
108
|
+
if (members?.origin && members.origin !== origin) await yes(`.sitekit/plugins.json has members.origin ${members.origin}. Change it to ${origin}?`);
|
|
109
|
+
const rules = members ? (members.rules || (await deps.ask("Which pages are for members? A members rule, e.g. /members/ (or /dues/ plans:officers): ")).trim()) : null;
|
|
110
|
+
if (members && !rules) throw new Stop("the members plugin needs a rule. Nothing was made");
|
|
111
|
+
const name = recorded ? null : (await deps.ask("The name people see on Key's sign-in page: ")).trim();
|
|
112
|
+
if (name !== null && !name) throw new Stop("the app needs a name. Nothing was made");
|
|
113
|
+
const secretVar = typeof members?.secret_var === "string" ? members.secret_var : "DOORMAN_SECRET";
|
|
114
|
+
if (!/^[A-Z][A-Z0-9_]{0,63}$/.test(secretVar)) throw new Stop(`members.secret_var "${secretVar}" is not a secret name (A-Z, 0-9 and _). Nothing was made`);
|
|
115
|
+
const pages = site.kind !== "worker";
|
|
116
|
+
const store = pages ? `the Pages project ${project}` : `the Worker ${project}`;
|
|
117
|
+
|
|
118
|
+
// Fable's fix 5: prove the store before anything is minted. wrangler is found, and signed in to the account shown.
|
|
119
|
+
const childEnv = Object.fromEntries([...CHILD_ENV, ...(deps.platform === "win32" ? WINDOWS_ENV : [])]
|
|
120
|
+
.filter((k) => deps.env[k] !== undefined).map((k) => [k, /** @type {string} */ (deps.env[k])]));
|
|
121
|
+
const npx = deps.platform === "win32" ? "npx.cmd" : "npx";
|
|
122
|
+
const wr = (/** @type {string[]} */ args, /** @type {{ input?: string, mask?: string }} */ o = {}) =>
|
|
123
|
+
deps.run(npx, ["--yes", WRANGLER, ...args], { ...o, env: childEnv });
|
|
124
|
+
const whoami = await wr(["whoami", "--json"]).catch((e) => {
|
|
125
|
+
throw new Stop(`wrangler is not signed in to Cloudflare (run: npx ${WRANGLER} login). Nothing was made. ${e.message}`);
|
|
126
|
+
});
|
|
127
|
+
const account = accountOf(whoami);
|
|
128
|
+
await wr(pages ? ["pages", "deployment", "list", "--project-name", project] : ["deployments", "list", "--name", project]).catch((e) => {
|
|
129
|
+
throw new Stop(`Cloudflare did not find ${store} for ${account}. Nothing was made. ${e.message}`);
|
|
130
|
+
});
|
|
131
|
+
const listed = await wr(pages ? ["pages", "secret", "list", "--project-name", project] : ["secret", "list", "--name", project]);
|
|
132
|
+
const has = (/** @type {string} */ n) => new RegExp(`(^|[^A-Za-z0-9_])${n}([^A-Za-z0-9_]|$)`).test(listed);
|
|
133
|
+
const wanted = site.kind === "sitekit" ? [secretVar] : [secretVar, "SEAL_KEY"];
|
|
134
|
+
log(`Cloudflare: ${account}, ${store}. Secrets already there: ${wanted.filter(has).join(", ") || "none"}.`);
|
|
135
|
+
|
|
136
|
+
// Sign in: loopback PKCE on the first free port; only the access token is used, the refresh token is never kept.
|
|
137
|
+
const verifier = b64url(randomBytes(32)), state = b64url(randomBytes(16));
|
|
138
|
+
let redirect = "";
|
|
139
|
+
const code = await deps.authorize((port) => {
|
|
140
|
+
redirect = `http://127.0.0.1:${port}/callback`;
|
|
141
|
+
const url = new URL(`${AUTH}/authorize`);
|
|
142
|
+
for (const [k, v] of Object.entries({ client_id: CLIENT, redirect_uri: redirect, response_type: "code", code_challenge_method: "S256",
|
|
143
|
+
code_challenge: b64url(createHash("sha256").update(verifier).digest()), state, scope: SCOPES.join(" "), resource: API })) url.searchParams.set(k, v);
|
|
144
|
+
return url.href;
|
|
145
|
+
}, state);
|
|
146
|
+
if (!code) throw new Stop("the sign-in came back with no code. Nothing was made");
|
|
147
|
+
const tokenRes = await deps.fetch(`${AUTH}/token`, { method: "POST", headers: { "content-type": "application/x-www-form-urlencoded" },
|
|
148
|
+
body: new URLSearchParams({ grant_type: "authorization_code", code, redirect_uri: redirect, client_id: CLIENT, code_verifier: verifier, resource: API }) });
|
|
149
|
+
/** @type {{ access_token?: unknown, scope?: unknown, error?: unknown }} */
|
|
150
|
+
const tok = /** @type {any} */ (await tokenRes.json().catch(() => ({})));
|
|
151
|
+
if (!tokenRes.ok || typeof tok.access_token !== "string") throw new Stop(`Key's sign-in failed: ${tok.error ?? tokenRes.status}. Nothing was made`);
|
|
152
|
+
const access = tok.access_token;
|
|
153
|
+
const granted = String(tok.scope ?? "").split(" ");
|
|
154
|
+
const missing = SCOPES.filter((s) => !granted.includes(s));
|
|
155
|
+
if (missing.length) {
|
|
156
|
+
throw new Stop(`not granted: ${missing.join(", ")} (tick ${missing.map((s) => `"${BOX[/** @type {keyof typeof BOX} */ (s)]}"`).join(" and ")} on the consent page, and run again). Nothing was made`);
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
const call = (/** @type {string} */ path, method = "GET", /** @type {unknown} */ body = undefined, /** @type {Record<string, string>} */ extra = {}) =>
|
|
160
|
+
deps.fetch(`${API}${path}`, { method, headers: { "content-type": "application/json", authorization: `Bearer ${access}`, ...extra },
|
|
161
|
+
...(body === undefined ? {} : { body: JSON.stringify(body) }) });
|
|
162
|
+
/** Key's JSON answer (any: each caller checks the fields it reads), or a Stop on a refusal. @returns {Promise<any>} */
|
|
163
|
+
const answer = async (/** @type {Response} */ r, /** @type {string} */ what) => {
|
|
164
|
+
/** @type {any} */
|
|
165
|
+
const out = await r.json().catch(() => ({}));
|
|
166
|
+
if (!r.ok) throw new Stop(`${what}: Key answered ${r.status} ${out.error ?? ""} ${out.error_description ?? out.message ?? ""}`.trimEnd());
|
|
167
|
+
return out;
|
|
168
|
+
};
|
|
169
|
+
const get = async (/** @type {string} */ path) => answer(await call(path), `GET ${path}`);
|
|
170
|
+
/**
|
|
171
|
+
* One write through Key's preview-then-confirm step (Fable's fix 9): the preview is shown, and the y/n closes a minute
|
|
172
|
+
* before the confirm token does. No answer in time previews again, so a stale token is never sent. `auto` sends the
|
|
173
|
+
* confirm without asking: only the revoke of a key that was never stored.
|
|
174
|
+
*/
|
|
175
|
+
/** @returns {Promise<any>} */
|
|
176
|
+
const write = async (/** @type {string} */ path, /** @type {unknown} */ body, method = "POST", auto = false) => {
|
|
177
|
+
const idem = method === "DELETE" ? { "idempotency-key": b64url(randomBytes(16)) } : {};
|
|
178
|
+
for (;;) {
|
|
179
|
+
const r = await call(path, method, body, idem);
|
|
180
|
+
if (r.status !== 202) return answer(r, `${method} ${path}`);
|
|
181
|
+
/** @type {{ preview?: { method?: string, path?: string, arguments?: unknown, current?: unknown }, confirm_token?: string, expires_in?: number }} */
|
|
182
|
+
const p = /** @type {any} */ (await r.json().catch(() => ({})));
|
|
183
|
+
log(`Key will: ${p.preview?.method ?? method} ${p.preview?.path ?? path} ${JSON.stringify(p.preview?.arguments ?? {})}`);
|
|
184
|
+
if (p.preview?.current != null) log(` now: ${JSON.stringify(p.preview.current)}`);
|
|
185
|
+
const ttl = Math.min(p.expires_in ?? CONFIRM_TTL, CONFIRM_TTL);
|
|
186
|
+
const ok = auto || (await deps.confirm("Do it?", Math.max(10, ttl - 60) * 1000));
|
|
187
|
+
if (ok === null) { log("no answer in time; Key previews it again"); continue; }
|
|
188
|
+
if (!ok) throw new Stop("you said no. Nothing more was changed; what was done stays, and a re-run picks up from here");
|
|
189
|
+
return answer(await call(path, method, body, { ...idem, "confirm-token": String(p.confirm_token) }), `${method} ${path}`);
|
|
190
|
+
}
|
|
191
|
+
};
|
|
192
|
+
|
|
193
|
+
// The app: the recorded one, found through account:read, or a new one recorded in the site straight away.
|
|
194
|
+
let appId = recorded, created = false;
|
|
195
|
+
if (appId) {
|
|
196
|
+
const r = await call(`/apps/${encodeURIComponent(appId)}`);
|
|
197
|
+
if (r.status === 404) throw new Stop(`this site records ${appId}, but it is not on the Key account you signed in with. Sign in with that account, or remove it from ${where}. Nothing was made`);
|
|
198
|
+
await answer(r, `GET /apps/${appId}`);
|
|
199
|
+
log(`app: ${appId} (found)`);
|
|
200
|
+
} else {
|
|
201
|
+
const app = await write("/apps", { name, kind: "server" });
|
|
202
|
+
if (typeof app.id !== "string" || !app.id.startsWith("app_")) throw new Stop("Key made no app id; look in Key's dashboard before running again");
|
|
203
|
+
appId = app.id;
|
|
204
|
+
created = true;
|
|
205
|
+
log(`app: ${appId} (made)`);
|
|
206
|
+
}
|
|
207
|
+
const id = /** @type {string} */ (appId);
|
|
208
|
+
record(cwd, site.kind, members && { ...members, origin, app: id, rules }, id, log);
|
|
209
|
+
|
|
210
|
+
const have = /** @type {{ uri: string, kind: string }[]} */ ((await get(`/apps/${id}/redirect_uris`)).redirect_uris ?? []);
|
|
211
|
+
for (const [kind, uri] of [["callback", `${origin}/_doorman/callback`], ["post_logout", `${origin}/`]]) {
|
|
212
|
+
if (have.some((h) => h.kind === kind && h.uri === uri)) { log(`${kind} ${uri}: already there`); continue; }
|
|
213
|
+
await write(`/apps/${id}/redirect_uris`, { uri, kind });
|
|
214
|
+
log(`${kind} ${uri}: added`);
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
// The secret key: made only when the store lacks it (or the person says to replace it), then piped on stdin.
|
|
218
|
+
const live = /** @type {{ kind: string, revoked_at: unknown }[]} */ ((await get(`/apps/${id}/keys`)).keys ?? []).filter((k) => k.kind === "sk" && k.revoked_at === null);
|
|
219
|
+
let keyId = null;
|
|
220
|
+
if (has(secretVar) && live.length && !created) log(`${secretVar}: already on ${store}; no new key`);
|
|
221
|
+
else {
|
|
222
|
+
await yes(has(secretVar)
|
|
223
|
+
? `${secretVar} is already on ${store}, but ${created ? "this app is new" : `${id} has no live secret key`}. Replace it with a new key for ${id}?`
|
|
224
|
+
: `Make a secret key for ${id} and put it on ${store} as ${secretVar} (Cloudflare: ${account})?`);
|
|
225
|
+
const key = await write(`/apps/${id}/keys`, { kind: "sk" });
|
|
226
|
+
keyId = typeof key.key?.id === "string" ? key.key.id : null;
|
|
227
|
+
if (typeof key.secret !== "string" || !key.secret || !keyId) throw new Stop(`Key's answer held no secret key; look in Key's dashboard for ${id} and revoke any key there you did not store`);
|
|
228
|
+
try {
|
|
229
|
+
await wr(pages ? ["pages", "secret", "put", secretVar, "--project-name", project] : ["secret", "put", secretVar, "--name", project],
|
|
230
|
+
{ input: `${key.secret}\n`, mask: key.secret });
|
|
231
|
+
} catch (e) {
|
|
232
|
+
log(`${secretVar}: Cloudflare did not take it (${/** @type {Error} */ (e).message}). Revoking ${keyId} now, so no key is left unstored`);
|
|
233
|
+
// Fable on #156: the revoke itself can fail (a token that ran out during the questions); never leave that unsaid.
|
|
234
|
+
try {
|
|
235
|
+
await write(`/apps/${id}/keys/${keyId}`, undefined, "DELETE", true);
|
|
236
|
+
} catch (r) {
|
|
237
|
+
throw new Stop(`the revoke failed (${/** @type {Error} */ (r).message}): ${keyId} is live and stored nowhere; `
|
|
238
|
+
+ "revoke it at https://dash.superintelligentkey.com, then fix what Cloudflare said and run again");
|
|
239
|
+
}
|
|
240
|
+
throw new Stop(`${keyId} was revoked, and nothing holds it. Fix what Cloudflare said, then run again`);
|
|
241
|
+
}
|
|
242
|
+
log(`${secretVar}: put on ${store} (key ${keyId})`);
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
if (site.kind !== "sitekit") {
|
|
246
|
+
// SEAL_KEY: 32 random bytes made here, piped the same way. Never replaced: that would end every session.
|
|
247
|
+
if (has("SEAL_KEY")) log(`SEAL_KEY: already on ${store}`);
|
|
248
|
+
else {
|
|
249
|
+
await yes(`Make a SEAL_KEY (32 random bytes, made on this computer) and put it on ${store}?`);
|
|
250
|
+
const seal = b64url(randomBytes(32));
|
|
251
|
+
await wr(pages ? ["pages", "secret", "put", "SEAL_KEY", "--project-name", project] : ["secret", "put", "SEAL_KEY", "--name", project],
|
|
252
|
+
{ input: `${seal}\n`, mask: seal });
|
|
253
|
+
log(`SEAL_KEY: put on ${store}`);
|
|
254
|
+
}
|
|
255
|
+
await sessions(cwd, project, wr, yes, log);
|
|
256
|
+
if (site.kind === "pages") await writeFunction(cwd, origin, log, yes);
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
if (site.kind === "worker") {
|
|
260
|
+
log(`Add this to your Worker (npm install ${HANDLER}), then deploy it with wrangler deploy:`);
|
|
261
|
+
log(workerSnippet(origin));
|
|
262
|
+
} else {
|
|
263
|
+
log(`Done. ${store} has its secrets, but a Pages secret reaches only the next deployment: deploy the site now, then`);
|
|
264
|
+
log(`open ${origin}/_doorman/sign-in to check the sign-in.`);
|
|
265
|
+
if (site.kind === "pages") log(`${FUNCTION} imports ${HANDLER}: add it to the site's package.json before deploying.`);
|
|
266
|
+
else log("site-kit's members plugin serves /_doorman/*: build the site with --functions, then deploy it.");
|
|
267
|
+
}
|
|
268
|
+
return { kind: site.kind, appId: id, keyId };
|
|
269
|
+
}
|
|
270
|
+
|
|
271
|
+
/** The account wrangler is signed in to, from whoami --json, for the preview. */
|
|
272
|
+
function accountOf(/** @type {string} */ out) {
|
|
273
|
+
try {
|
|
274
|
+
const w = JSON.parse(out);
|
|
275
|
+
const names = (Array.isArray(w.accounts) ? w.accounts : []).map((/** @type {{ name?: string }} */ a) => a.name).filter(Boolean);
|
|
276
|
+
return [w.email, names.length ? `account ${names.join(", ")}` : null].filter(Boolean).join(", ") || "signed in";
|
|
277
|
+
} catch {
|
|
278
|
+
return "signed in";
|
|
279
|
+
}
|
|
280
|
+
}
|
|
281
|
+
|
|
282
|
+
/** The app id, and on a site-kit site the members settings, recorded in the site: only what is missing is added. */
|
|
283
|
+
function record(/** @type {string} */ cwd, /** @type {string} */ kind, /** @type {Record<string, unknown> | null} */ members, /** @type {string} */ id, /** @type {(l: string) => void} */ log) {
|
|
284
|
+
if (kind === "sitekit") {
|
|
285
|
+
const all = plugins(cwd);
|
|
286
|
+
if (JSON.stringify(all.members) === JSON.stringify(members)) return;
|
|
287
|
+
writeFileSync(join(cwd, PLUGINS), `${JSON.stringify({ ...all, members }, null, 2)}\n`);
|
|
288
|
+
log(`${PLUGINS}: members settings written (app ${id})`);
|
|
289
|
+
return;
|
|
290
|
+
}
|
|
291
|
+
const file = join(cwd, "wrangler.toml"), text = readFileSync(file, "utf8");
|
|
292
|
+
if (tomlAppId(text) === id) return;
|
|
293
|
+
writeFileSync(file, withTomlAppId(text, id));
|
|
294
|
+
log(`wrangler.toml: [vars] KEY_APP_ID = "${id}" added`);
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
/** The SESSIONS D1: found or made, bound in wrangler.toml, with the sessions table applied. Each change is asked first. */
|
|
298
|
+
async function sessions(
|
|
299
|
+
/** @type {string} */ cwd, /** @type {string} */ project,
|
|
300
|
+
/** @type {(args: string[]) => Promise<string>} */ wr, /** @type {(q: string) => Promise<void>} */ yes, /** @type {(l: string) => void} */ log,
|
|
301
|
+
) {
|
|
302
|
+
const file = join(cwd, "wrangler.toml");
|
|
303
|
+
let name = tomlSessions(readFileSync(file, "utf8"));
|
|
304
|
+
if (name) log(`D1 ${name}: bound as SESSIONS in wrangler.toml`);
|
|
305
|
+
else {
|
|
306
|
+
name = `${project}-sessions`;
|
|
307
|
+
const find = async () => /** @type {{ name: string, uuid: string }[]} */ (JSON.parse(await wr(["d1", "list", "--json"]))).find((d) => d.name === name);
|
|
308
|
+
let db = await find();
|
|
309
|
+
if (!db) {
|
|
310
|
+
await yes(`Make the D1 database ${name} for the sign-in sessions?`);
|
|
311
|
+
await wr(["d1", "create", name]);
|
|
312
|
+
db = await find();
|
|
313
|
+
if (!db) throw new Stop(`wrangler made ${name}, but d1 list does not show it; run again`);
|
|
314
|
+
log(`D1 ${name}: made`);
|
|
315
|
+
}
|
|
316
|
+
writeFileSync(file, withTomlSessions(readFileSync(file, "utf8"), name, db.uuid));
|
|
317
|
+
log(`wrangler.toml: SESSIONS binding to ${name} added`);
|
|
318
|
+
}
|
|
319
|
+
if (!DB_NAME.test(name)) throw new Stop(`wrangler.toml's SESSIONS database_name "${name}" is not a D1 name the installer can pass on`);
|
|
320
|
+
const tables = await wr(["d1", "execute", name, "--remote", "--json", "--command", "SELECT name FROM sqlite_master WHERE type='table' AND name='doorman_sessions'"]);
|
|
321
|
+
let there = false;
|
|
322
|
+
try { there = JSON.parse(tables).some((/** @type {{ results?: unknown[] }} */ r) => (r.results ?? []).length > 0); } catch { there = false; }
|
|
323
|
+
if (there) { log(`D1 ${name}: the sessions table is there`); return; }
|
|
324
|
+
await yes(`Add the sessions table (doorman_sessions) to the D1 database ${name}?`);
|
|
325
|
+
await wr(["d1", "execute", name, "--remote", "--command", D1_SCHEMA.replace(/\s+/g, " ")]);
|
|
326
|
+
log(`D1 ${name}: the sessions table added`);
|
|
327
|
+
}
|
|
328
|
+
|
|
329
|
+
/** functions/_doorman/[[path]].js: written when missing; a different file there is replaced only on a yes. */
|
|
330
|
+
async function writeFunction(/** @type {string} */ cwd, /** @type {string} */ origin, /** @type {(l: string) => void} */ log, /** @type {(q: string) => Promise<void>} */ yes) {
|
|
331
|
+
const file = join(cwd, FUNCTION), src = functionSource(origin);
|
|
332
|
+
if (existsSync(file)) {
|
|
333
|
+
if (readFileSync(file, "utf8") === src) { log(`${FUNCTION}: already there`); return; }
|
|
334
|
+
await yes(`${FUNCTION} is there, and differs from the installer's. Replace it?`);
|
|
335
|
+
}
|
|
336
|
+
mkdirSync(dirname(file), { recursive: true });
|
|
337
|
+
writeFileSync(file, src);
|
|
338
|
+
log(`${FUNCTION}: written`);
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
export { Stop };
|
package/src/loopback.mjs
ADDED
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
// The loopback sign-in both Key installers share (RFC 8252 §7.3): the CLI here and scripts/key-app-setup.mjs import it, so
|
|
2
|
+
// it is one source (doorman#152 item 4, Fable's fix 1).
|
|
3
|
+
import { createHash, timingSafeEqual } from "node:crypto";
|
|
4
|
+
import { createServer } from "node:http";
|
|
5
|
+
|
|
6
|
+
/** The callback's state against ours, in constant time (maint-review on #156): equal-length digests, never a short-circuit. */
|
|
7
|
+
const sameState = (/** @type {string | null} */ got, /** @type {string} */ want) =>
|
|
8
|
+
got !== null && timingSafeEqual(createHash("sha256").update(got).digest(), createHash("sha256").update(want).digest());
|
|
9
|
+
|
|
10
|
+
/** Each scope as Key's consent page words its box (workers/auth/src/lib/grants.ts), so a refusal names the box to tick. */
|
|
11
|
+
export const BOX = {
|
|
12
|
+
"apps:write": "Create and change your sites, their return addresses, plans and rules",
|
|
13
|
+
"keys:write": "Create and revoke your sites' keys",
|
|
14
|
+
"account:read": "See your account and its sites",
|
|
15
|
+
"members:write": "Add members by email, change a member's plan, suspend or delete members",
|
|
16
|
+
};
|
|
17
|
+
/** The boxes Key's consent page leaves unticked (workers/auth/src/lib/grants.ts OFF_BY_DEFAULT): a run asking for one says so. */
|
|
18
|
+
export const OFF_BY_DEFAULT = ["keys:write", "members:write"];
|
|
19
|
+
export const SIGN_IN_DEADLINE_MS = 10 * 60_000;
|
|
20
|
+
|
|
21
|
+
/**
|
|
22
|
+
* Listens on the first free port of `ports` (a number, or a list tried in order: a port in use moves on to the next), then
|
|
23
|
+
* waits on 127.0.0.1 for this sign-in's callback. Any other request gets a 400 and the wait goes on, until the deadline.
|
|
24
|
+
* `href` is the sign-in link, or a function of the port that makes it (the redirect_uri names the port). Resolves the code.
|
|
25
|
+
* `busy` ends the message when every port is in use.
|
|
26
|
+
* @param {string | ((port: number) => string)} href
|
|
27
|
+
* @param {string} state
|
|
28
|
+
* @param {number | number[]} ports
|
|
29
|
+
* @param {(line: string) => void} log
|
|
30
|
+
* @param {number} [deadlineMs]
|
|
31
|
+
* @param {string} [busy]
|
|
32
|
+
* @returns {Promise<string>}
|
|
33
|
+
*/
|
|
34
|
+
export function loopback(href, state, ports, log, deadlineMs = SIGN_IN_DEADLINE_MS, busy = "free one and run again") {
|
|
35
|
+
const list = Array.isArray(ports) ? ports : [ports];
|
|
36
|
+
return new Promise((resolve, reject) => {
|
|
37
|
+
/** @type {ReturnType<typeof setTimeout> | undefined} */
|
|
38
|
+
let timer;
|
|
39
|
+
const listenOn = (/** @type {number} */ i) => {
|
|
40
|
+
const port = /** @type {number} */ (list[i]);
|
|
41
|
+
const server = createServer((req, res) => {
|
|
42
|
+
const q = new URL(req.url ?? "/", `http://127.0.0.1:${port}`);
|
|
43
|
+
// Key's redirect is a browser GET; anything else, another path or another state is not this sign-in.
|
|
44
|
+
if (req.method !== "GET" || q.pathname !== "/callback" || !sameState(q.searchParams.get("state"), state)) {
|
|
45
|
+
res.writeHead(400, { "content-type": "text/plain" }).end("Not this sign-in.\n");
|
|
46
|
+
return;
|
|
47
|
+
}
|
|
48
|
+
res.writeHead(200, { "content-type": "text/plain" }).end("Signed in. You can close this tab.\n");
|
|
49
|
+
done();
|
|
50
|
+
if (q.searchParams.get("error")) reject(new Error(`authorize answered ${q.searchParams.get("error")}; nothing was created`));
|
|
51
|
+
else resolve(q.searchParams.get("code") ?? "");
|
|
52
|
+
});
|
|
53
|
+
const done = () => { clearTimeout(timer); server.close(); };
|
|
54
|
+
server.on("error", (/** @type {NodeJS.ErrnoException} */ e) => {
|
|
55
|
+
if (e.code === "EADDRINUSE" && i + 1 < list.length) { listenOn(i + 1); return; }
|
|
56
|
+
clearTimeout(timer);
|
|
57
|
+
const where = list.length > 1 ? `any of 127.0.0.1:${list.join(", ")} (all in use)` : `127.0.0.1:${port} (${e.code ?? e.message})`;
|
|
58
|
+
reject(new Error(`the sign-in listener could not start on ${where}; ${busy}`));
|
|
59
|
+
});
|
|
60
|
+
server.listen(port, "127.0.0.1", () => {
|
|
61
|
+
timer = setTimeout(() => { done(); reject(new Error(`no sign-in within ${deadlineMs / 60_000} minutes; nothing was created`)); }, deadlineMs);
|
|
62
|
+
// The link as it is, with plain & between its parameters: paste it whole into the browser's address bar.
|
|
63
|
+
// Key leaves the keys and members boxes unticked; a run that asks for either says to tick it.
|
|
64
|
+
const link = typeof href === "function" ? href(port) : href;
|
|
65
|
+
const asked = new URL(link).searchParams.get("scope")?.split(" ") ?? [];
|
|
66
|
+
const tick = OFF_BY_DEFAULT.filter((s) => asked.includes(s)).map((s) => `"${BOX[/** @type {keyof typeof BOX} */ (s)]}"`).join(" and ");
|
|
67
|
+
log(`OPEN (leave every box ticked${tick ? `, and tick ${tick}` : ""}): ${link}`);
|
|
68
|
+
});
|
|
69
|
+
};
|
|
70
|
+
listenOn(0);
|
|
71
|
+
});
|
|
72
|
+
}
|
package/src/run.mjs
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
// Runs a child (wrangler, through npx) with `input` on stdin and only `env`. Resolves its stdout; a failure rejects with its
|
|
2
|
+
// stderr, with any secret masked out of both. A secret only ever travels on stdin, never on argv.
|
|
3
|
+
import { spawn } from "node:child_process";
|
|
4
|
+
|
|
5
|
+
const CHILD_TIMEOUT_MS = 180_000;
|
|
6
|
+
|
|
7
|
+
/** cmd.exe's quoting for one argument (npx.cmd needs a shell on Windows). The installer's args hold no quote or %. */
|
|
8
|
+
function winArg(/** @type {string} */ a) {
|
|
9
|
+
if (/["%\r\n]/.test(a)) throw new Error(`an argument the installer would pass to cmd.exe holds a quote, % or line break: ${a.slice(0, 40)}`);
|
|
10
|
+
return /[\s&|<>^()]/.test(a) ? `"${a}"` : a;
|
|
11
|
+
}
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* @param {string} cmd
|
|
15
|
+
* @param {string[]} args
|
|
16
|
+
* @param {{ input?: string, env: Record<string, string>, mask?: string, timeoutMs?: number, platform?: string }} o
|
|
17
|
+
* @returns {Promise<string>}
|
|
18
|
+
*/
|
|
19
|
+
export function runChild(cmd, args, { input = "", env, mask = "", timeoutMs = CHILD_TIMEOUT_MS, platform = process.platform }) {
|
|
20
|
+
const hide = (/** @type {string} */ s) => (mask ? s.replaceAll(mask, "<secret>") : s);
|
|
21
|
+
return new Promise((ok, no) => {
|
|
22
|
+
const win = platform === "win32";
|
|
23
|
+
const p = win ? spawn(cmd, args.map(winArg), { stdio: ["pipe", "pipe", "pipe"], env, shell: true })
|
|
24
|
+
: spawn(cmd, args, { stdio: ["pipe", "pipe", "pipe"], env });
|
|
25
|
+
let out = "", err = "";
|
|
26
|
+
const timer = setTimeout(() => { p.kill("SIGKILL"); no(new Error(`${cmd} gave no answer in ${timeoutMs / 1000}s`)); }, timeoutMs);
|
|
27
|
+
p.stdout.on("data", (d) => { out += d; });
|
|
28
|
+
p.stderr.on("data", (d) => { err += d; });
|
|
29
|
+
p.on("error", (e) => { clearTimeout(timer); no(e); });
|
|
30
|
+
p.on("close", (code) => {
|
|
31
|
+
clearTimeout(timer);
|
|
32
|
+
if (code === 0) ok(hide(out));
|
|
33
|
+
else no(new Error(`${args[2] ?? cmd} ${args[3] ?? ""} exited ${code}: ${hide(err || out).trim().slice(0, 300)}`));
|
|
34
|
+
});
|
|
35
|
+
p.stdin.on("error", () => {});
|
|
36
|
+
p.stdin.end(input);
|
|
37
|
+
});
|
|
38
|
+
}
|
package/src/site.mjs
ADDED
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
// What kind of site the installer runs in, and the few edits it makes to that site's own config (doorman#152 item 4).
|
|
2
|
+
// wrangler.toml is edited as text: lines are added, and one line is replaced only after the person says yes.
|
|
3
|
+
import { existsSync, readFileSync, statSync } from "node:fs";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
|
|
6
|
+
/** @typedef {"sitekit" | "pages" | "worker" | "manual"} Kind */
|
|
7
|
+
/** @typedef {{ kind: Kind, toml: string | null, project: string | null }} Site */
|
|
8
|
+
|
|
9
|
+
const TOML = "wrangler.toml";
|
|
10
|
+
export const PLUGINS = join(".sitekit", "plugins.json");
|
|
11
|
+
export const FUNCTION = join("functions", "_doorman", "[[path]].js");
|
|
12
|
+
|
|
13
|
+
const read = (/** @type {string} */ file) => (existsSync(file) ? readFileSync(file, "utf8") : null);
|
|
14
|
+
|
|
15
|
+
/** A top-level `key = "value"` of a TOML text (before its first table), or null. */
|
|
16
|
+
export function topLevel(/** @type {string} */ text, /** @type {string} */ key) {
|
|
17
|
+
for (const line of text.split("\n")) {
|
|
18
|
+
if (/^\s*\[/.test(line)) break;
|
|
19
|
+
const m = line.match(new RegExp(`^\\s*${key}\\s*=\\s*"([^"]*)"`));
|
|
20
|
+
if (m) return m[1] ?? null;
|
|
21
|
+
}
|
|
22
|
+
return null;
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* A site-kit site (`.sitekit/`), a static Pages site (wrangler.toml with pages_build_output_dir), a Worker (wrangler.toml
|
|
27
|
+
* with main), or anything else, which gets manual steps.
|
|
28
|
+
* @param {string} cwd
|
|
29
|
+
* @returns {Site}
|
|
30
|
+
*/
|
|
31
|
+
export function detect(cwd) {
|
|
32
|
+
const toml = read(join(cwd, TOML));
|
|
33
|
+
const project = toml === null ? null : topLevel(toml, "name");
|
|
34
|
+
const dir = join(cwd, ".sitekit");
|
|
35
|
+
if (existsSync(dir) && statSync(dir).isDirectory()) return { kind: "sitekit", toml, project };
|
|
36
|
+
if (toml !== null && topLevel(toml, "pages_build_output_dir") !== null) return { kind: "pages", toml, project };
|
|
37
|
+
if (toml !== null && topLevel(toml, "main") !== null) return { kind: "worker", toml, project };
|
|
38
|
+
return { kind: "manual", toml, project };
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/** The steps for a site the installer can't set up itself. */
|
|
42
|
+
export const MANUAL_STEPS = [
|
|
43
|
+
"This folder is not a site the installer knows: no .sitekit/ folder, and no wrangler.toml with pages_build_output_dir or main.",
|
|
44
|
+
"Nothing was made. To add Key by hand:",
|
|
45
|
+
" 1. Make a server app at https://dash.superintelligentkey.com, with the return address https://<your site>/_doorman/callback",
|
|
46
|
+
" and the sign-out address https://<your site>/.",
|
|
47
|
+
" 2. Make its secret key there, and put it straight into your host's secret store as DOORMAN_SECRET.",
|
|
48
|
+
" 3. Mount @superintelligentfamily/key-handler at /_doorman in your server, with a SEAL_KEY of 32 random bytes and a sessions table (D1_SCHEMA).",
|
|
49
|
+
"Or run this installer again from the folder that holds your site's wrangler.toml.",
|
|
50
|
+
];
|
|
51
|
+
|
|
52
|
+
/** [vars] KEY_APP_ID from wrangler.toml, or null. */
|
|
53
|
+
/** A stop the installer explains: the message is the whole story, and nothing more is made after it. */
|
|
54
|
+
export class Stop extends Error {}
|
|
55
|
+
|
|
56
|
+
export function tomlAppId(/** @type {string} */ text) {
|
|
57
|
+
let inVars = false;
|
|
58
|
+
for (const line of text.split("\n")) {
|
|
59
|
+
if (/^\s*\[/.test(line)) { inVars = /^\s*\[vars\]\s*$/.test(line); continue; }
|
|
60
|
+
if (!inVars || !/^\s*KEY_APP_ID\s*=/.test(line)) continue;
|
|
61
|
+
// A basic ("…") or literal ('…') TOML string; any other KEY_APP_ID line is never guessed at (Fable on #156): it stops.
|
|
62
|
+
const m = line.match(/^\s*KEY_APP_ID\s*=\s*(?:"([^"\\]*)"|'([^']*)')\s*(?:#.*)?$/);
|
|
63
|
+
if (!m) throw new Stop(`wrangler.toml has a KEY_APP_ID line the installer can't read (${line.trim()}); write it as KEY_APP_ID = "app_…" and run again`);
|
|
64
|
+
return m[1] ?? m[2] ?? null;
|
|
65
|
+
}
|
|
66
|
+
return null;
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** The text with [vars] KEY_APP_ID = "<id>": added to [vars], or [vars] added at the end. Replaces a different id. */
|
|
70
|
+
export function withTomlAppId(/** @type {string} */ text, /** @type {string} */ id) {
|
|
71
|
+
const lines = text.split("\n");
|
|
72
|
+
const line = `KEY_APP_ID = "${id}"`;
|
|
73
|
+
let inVars = false, header = -1;
|
|
74
|
+
for (let i = 0; i < lines.length; i++) {
|
|
75
|
+
const l = /** @type {string} */ (lines[i]);
|
|
76
|
+
if (/^\s*\[/.test(l)) { inVars = /^\s*\[vars\]\s*$/.test(l); if (inVars) header = i; continue; }
|
|
77
|
+
if (inVars && /^\s*KEY_APP_ID\s*=/.test(l)) { lines[i] = line; return lines.join("\n"); }
|
|
78
|
+
}
|
|
79
|
+
if (header >= 0) { lines.splice(header + 1, 0, line); return lines.join("\n"); }
|
|
80
|
+
return `${text.replace(/\n*$/, "\n")}\n[vars]\n${line}\n`;
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
/** The SESSIONS D1 binding's database_name in wrangler.toml, or null. */
|
|
84
|
+
export function tomlSessions(/** @type {string} */ text) {
|
|
85
|
+
for (const block of text.split(/^\s*\[\[d1_databases\]\]\s*$/m).slice(1)) {
|
|
86
|
+
const body = block.split(/^\s*\[/m)[0] ?? "";
|
|
87
|
+
if (/^\s*binding\s*=\s*"SESSIONS"/m.test(body)) return body.match(/^\s*database_name\s*=\s*"([^"]*)"/m)?.[1] ?? null;
|
|
88
|
+
}
|
|
89
|
+
return null;
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/** The text with a SESSIONS D1 binding added at the end. */
|
|
93
|
+
export function withTomlSessions(/** @type {string} */ text, /** @type {string} */ name, /** @type {string} */ id) {
|
|
94
|
+
return `${text.replace(/\n*$/, "\n")}\n[[d1_databases]]\nbinding = "SESSIONS"\ndatabase_name = "${name}"\ndatabase_id = "${id}"\n`;
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** .sitekit/plugins.json as an object ({} when there is none). */
|
|
98
|
+
export function plugins(/** @type {string} */ cwd) {
|
|
99
|
+
const text = read(join(cwd, PLUGINS));
|
|
100
|
+
if (text === null) return {};
|
|
101
|
+
const out = JSON.parse(text);
|
|
102
|
+
if (!out || typeof out !== "object" || Array.isArray(out)) throw new Error(`${PLUGINS} is not a JSON object; fix it, then run again. Nothing was made`);
|
|
103
|
+
return out;
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
/**
|
|
107
|
+
* The Pages Function that serves /_doorman/* through @superintelligentfamily/key-handler. The app id comes from wrangler.toml's [vars]
|
|
108
|
+
* KEY_APP_ID, the secrets from the Pages project, the sessions from the SESSIONS binding.
|
|
109
|
+
* @param {string} origin
|
|
110
|
+
*/
|
|
111
|
+
export function functionSource(origin) {
|
|
112
|
+
return `// Key sign-in for this site, written by @superintelligentfamily/key-install (doorman#152): GET /_doorman/sign-in and
|
|
113
|
+
// /_doorman/callback, POST /_doorman/token and /_doorman/signout. KEY_APP_ID is in wrangler.toml's [vars]; DOORMAN_SECRET
|
|
114
|
+
// and SEAL_KEY are the Pages project's secrets; SESSIONS is its D1 binding.
|
|
115
|
+
import { createHandler, d1Store } from "@superintelligentfamily/key-handler";
|
|
116
|
+
|
|
117
|
+
let handler;
|
|
118
|
+
export function onRequest({ request, env }) {
|
|
119
|
+
handler ??= createHandler({
|
|
120
|
+
issuer: "https://auth.superintelligentkey.com",
|
|
121
|
+
clientId: env.KEY_APP_ID,
|
|
122
|
+
clientSecret: env.DOORMAN_SECRET,
|
|
123
|
+
origin: ${JSON.stringify(origin)},
|
|
124
|
+
mount: "/_doorman",
|
|
125
|
+
store: d1Store(env.SESSIONS),
|
|
126
|
+
sealKey: env.SEAL_KEY,
|
|
127
|
+
markers: { api: "https://api.superintelligentkey.com", secretKey: env.DOORMAN_SECRET },
|
|
128
|
+
});
|
|
129
|
+
return handler(request);
|
|
130
|
+
}
|
|
131
|
+
`;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
/** What a Worker adds to its fetch handler, printed for the person to paste. */
|
|
135
|
+
export function workerSnippet(/** @type {string} */ origin) {
|
|
136
|
+
return `import { createHandler, d1Store } from "@superintelligentfamily/key-handler";
|
|
137
|
+
|
|
138
|
+
let doorman;
|
|
139
|
+
export default {
|
|
140
|
+
async fetch(request, env) {
|
|
141
|
+
doorman ??= createHandler({
|
|
142
|
+
issuer: "https://auth.superintelligentkey.com", clientId: env.KEY_APP_ID, clientSecret: env.DOORMAN_SECRET,
|
|
143
|
+
origin: ${JSON.stringify(origin)}, mount: "/_doorman", store: d1Store(env.SESSIONS), sealKey: env.SEAL_KEY,
|
|
144
|
+
markers: { api: "https://api.superintelligentkey.com", secretKey: env.DOORMAN_SECRET },
|
|
145
|
+
});
|
|
146
|
+
if (new URL(request.url).pathname.startsWith("/_doorman/")) return doorman(request);
|
|
147
|
+
// ... the Worker's own routes
|
|
148
|
+
},
|
|
149
|
+
};`;
|
|
150
|
+
}
|
package/README.md
DELETED