@superintern/sites 0.0.0-stage → 0.2.0

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.
@@ -0,0 +1,104 @@
1
+ // Where each environment's services are, for the `sites` command.
2
+ //
3
+ // The command talks to two things and nothing else: the site API, and the git
4
+ // address.
5
+
6
+ /** @typedef {"test" | "prod"} EnvironmentName */
7
+
8
+ /**
9
+ * @typedef {object} CliEnvironment
10
+ * @property {EnvironmentName} name
11
+ * @property {string} api the site API, no trailing slash
12
+ * @property {string} git the git address, no trailing slash
13
+ * @property {string} sitesDomain where this environment's sites get their free address
14
+ * @property {boolean} overridden true when an address came from the environment, not from this file
15
+ */
16
+
17
+ const ENVIRONMENTS = {
18
+ test: {
19
+ api: "https://test-api.superintern.ai",
20
+ git: "https://git.testforstuff.com",
21
+ sitesDomain: "testforstuff.com",
22
+ },
23
+ prod: {
24
+ api: "https://api.superintern.ai",
25
+ git: "https://git.superintern.app",
26
+ sitesDomain: "superintern.app",
27
+ },
28
+ };
29
+
30
+ /** Test, until hosted sites are open to customers. */
31
+ export const DEFAULT_ENVIRONMENT = "test";
32
+
33
+ export const ENVIRONMENT_NAMES = /** @type {EnvironmentName[]} */ (Object.keys(ENVIRONMENTS));
34
+
35
+ /**
36
+ * The addresses for an environment.
37
+ *
38
+ * SUPERINTERN_SITES_API_BASE and SUPERINTERN_SITES_GIT_BASE replace them, for
39
+ * running against a stand-in on this machine. A key is only ever sent to the
40
+ * addresses returned here, so a replaced address is always said out loud by
41
+ * the caller (`overridden`).
42
+ *
43
+ * @param {string | undefined} name
44
+ * @param {NodeJS.ProcessEnv} [env]
45
+ * @returns {CliEnvironment}
46
+ */
47
+ export function resolveEnvironment(name, env = process.env) {
48
+ const chosen = name ?? DEFAULT_ENVIRONMENT;
49
+ if (!ENVIRONMENT_NAMES.includes(/** @type {EnvironmentName} */ (chosen))) {
50
+ throw new Error(`The environment must be one of ${ENVIRONMENT_NAMES.join(", ")}; got "${chosen}"`);
51
+ }
52
+ const base = ENVIRONMENTS[/** @type {EnvironmentName} */ (chosen)];
53
+ const api = trimSlash(env.SUPERINTERN_SITES_API_BASE || base.api);
54
+ const git = trimSlash(env.SUPERINTERN_SITES_GIT_BASE || base.git);
55
+ for (const address of [api, git]) {
56
+ const url = new URL(address);
57
+ const local = url.hostname === "127.0.0.1" || url.hostname === "localhost";
58
+ // A key must never travel in the clear, except to a stand-in on this machine.
59
+ if (url.protocol !== "https:" && !(url.protocol === "http:" && local)) {
60
+ throw new Error(`${address} is not an https address`);
61
+ }
62
+ }
63
+ return {
64
+ name: /** @type {EnvironmentName} */ (chosen),
65
+ api,
66
+ git,
67
+ sitesDomain: base.sitesDomain,
68
+ overridden: api !== base.api || git !== base.git,
69
+ };
70
+ }
71
+
72
+ /**
73
+ * A site's address at the git address.
74
+ * @param {CliEnvironment} environment @param {string} slug
75
+ */
76
+ export function gitUrl(environment, slug) {
77
+ return `${environment.git}/${slug}.git`;
78
+ }
79
+
80
+ /**
81
+ * The site a git address is for: the slug of `<git address>/<slug>.git`, or
82
+ * null when the address is not on this environment's git address.
83
+ * @param {CliEnvironment} environment @param {string} url
84
+ */
85
+ export function slugOfGitUrl(environment, url) {
86
+ const prefix = `${environment.git}/`;
87
+ if (!url.startsWith(prefix)) return null;
88
+ return /^([a-z0-9-]+)\.git$/.exec(url.slice(prefix.length))?.[1] ?? null;
89
+ }
90
+
91
+ /**
92
+ * Which environment's git address an address is on, by the addresses in this
93
+ * file. Used to say "this folder is a site on prod" to someone on test.
94
+ * @param {string} url
95
+ * @returns {EnvironmentName | null}
96
+ */
97
+ export function environmentOfGitUrl(url) {
98
+ return ENVIRONMENT_NAMES.find((name) => url.startsWith(`${ENVIRONMENTS[name].git}/`)) ?? null;
99
+ }
100
+
101
+ /** @param {string} value */
102
+ function trimSlash(value) {
103
+ return value.replace(/\/+$/, "");
104
+ }
@@ -0,0 +1,258 @@
1
+ // Everything the `sites` command does with git.
2
+ //
3
+ // A site is cloned from, and pushed to, our git address with the person's key
4
+ // as the password. Git gets the key from this command (a "credential helper")
5
+ // each time it needs it. The key is never written into the clone's
6
+ // .git/config, never put in an address, and never handed to git's own
7
+ // password stores.
8
+ //
9
+ // The clone also holds one line for the site's own build, `sites.datahelper`:
10
+ // the command that gives the build a short pass to read the business's public
11
+ // CRM tables. Like the credential helper, it names this command and holds no
12
+ // secret.
13
+
14
+ import { spawn } from "node:child_process";
15
+
16
+ /** Git needs a username; the git address ignores it. */
17
+ const USERNAME = "sites";
18
+
19
+ /** The remote a site keeps for reading the template it started from: read, never merged. */
20
+ export const STARTER_REMOTE = "starter";
21
+
22
+ /**
23
+ * The line git runs to ask for the key. It names this command and the
24
+ * environment, and holds no secret.
25
+ * @param {{ node: string, script: string, environment: string }} input
26
+ */
27
+ export function helperCommand({ node, script, environment }) {
28
+ return `!${shellQuote(node)} ${shellQuote(script)} git-credential --env ${environment}`;
29
+ }
30
+
31
+ /** The setting a site's build reads to find the command that gives it a pass to the CRM. */
32
+ export const DATA_HELPER_SETTING = "sites.datahelper";
33
+
34
+ /**
35
+ * The line a site's build runs to get that pass (`sites data-token`). The
36
+ * build runs it as a command line, so it is quoted as the credential helper is.
37
+ * @param {{ node: string, script: string, environment: string, slug: string }} input
38
+ */
39
+ export function dataHelperCommand({ node, script, environment, slug }) {
40
+ return `${shellQuote(node)} ${shellQuote(script)} data-token --env ${environment} --site ${shellQuote(slug)}`;
41
+ }
42
+
43
+ /**
44
+ * The git settings that make one address use our helper and nothing else.
45
+ * The first, empty value clears every helper set for the person's whole
46
+ * computer (the keychain helper, for one), so the key is not copied there
47
+ * after a successful push.
48
+ * @param {string} gitBase "https://git.testforstuff.com"
49
+ * @param {string} helper from helperCommand()
50
+ * @returns {Array<[string, string]>}
51
+ */
52
+ export function credentialSettings(gitBase, helper) {
53
+ const scope = `credential.${gitBase}`;
54
+ return [
55
+ [`${scope}.helper`, ""],
56
+ [`${scope}.helper`, helper],
57
+ [`${scope}.username`, USERNAME],
58
+ ];
59
+ }
60
+
61
+ /**
62
+ * Answer git's request for a credential (the helper protocol: `key=value`
63
+ * lines in, `key=value` lines out).
64
+ *
65
+ * Only a "get" for our own git address over https is answered. For any other
66
+ * address, and for git's "store" and "erase", nothing is said and nothing is
67
+ * kept.
68
+ *
69
+ * @param {{ action: string, input: string, gitBase: string, key: string | null }} request
70
+ * @returns {string} what to write to standard output
71
+ */
72
+ export function answerCredentialRequest({ action, input, gitBase, key }) {
73
+ if (action !== "get" || !key) return "";
74
+ /** @type {Record<string, string>} */
75
+ const asked = {};
76
+ for (const line of input.split("\n")) {
77
+ const at = line.indexOf("=");
78
+ if (at > 0) asked[line.slice(0, at)] = line.slice(at + 1);
79
+ }
80
+ const ours = new URL(gitBase);
81
+ if (`${asked.protocol}:` !== ours.protocol || asked.host !== ours.host) return "";
82
+ return `username=${USERNAME}\npassword=${key}\n`;
83
+ }
84
+
85
+ /**
86
+ * @typedef {(args: string[], options?: { cwd?: string, quiet?: boolean }) => Promise<{ code: number, stdout: string, stderr: string }>} GitRunner
87
+ */
88
+
89
+ /**
90
+ * Run git without a shell. It never asks for a password on the terminal: a
91
+ * key that does not work is an error to report, not a prompt.
92
+ *
93
+ * `safe.bareRepository=explicit`: a site's files come from a push, and a
94
+ * folder among them can be laid out like a bare repository, with settings of
95
+ * its own. Git must never take such a folder for the clone.
96
+ * @type {GitRunner}
97
+ */
98
+ export function runGit(args, options = {}) {
99
+ return new Promise((resolve, reject) => {
100
+ const child = spawn("git", ["-c", "safe.bareRepository=explicit", ...args], {
101
+ cwd: options.cwd,
102
+ env: { ...process.env, GIT_TERMINAL_PROMPT: "0" },
103
+ stdio: ["ignore", "pipe", "pipe"],
104
+ });
105
+ let stdout = "";
106
+ let stderr = "";
107
+ child.stdout.on("data", (chunk) => (stdout += chunk));
108
+ child.stderr.on("data", (chunk) => {
109
+ stderr += chunk;
110
+ if (!options.quiet) process.stderr.write(chunk);
111
+ });
112
+ child.on("error", (error) =>
113
+ reject(/** @type {NodeJS.ErrnoException} */ (error).code === "ENOENT" ? new Error("git is not installed on this computer") : error),
114
+ );
115
+ child.on("close", (code) => resolve({ code: code ?? 1, stdout, stderr }));
116
+ });
117
+ }
118
+
119
+ /**
120
+ * Clone a site and set the clone up so later pushes need no password.
121
+ *
122
+ * @param {object} input
123
+ * @param {GitRunner} input.git
124
+ * @param {string} input.url the site's address at the git address
125
+ * @param {string} input.gitBase the git address itself
126
+ * @param {string} input.dir where to put the clone
127
+ * @param {string} input.helper from helperCommand()
128
+ * @param {string} [input.dataHelper] from dataHelperCommand()
129
+ * @param {string} [input.starterUrl] where newer versions of the starter come from
130
+ */
131
+ export async function cloneSite({ git, url, gitBase, dir, helper, dataHelper, starterUrl }) {
132
+ const settings = credentialSettings(gitBase, helper);
133
+
134
+ // For the clone itself the settings ride on the command line, since there
135
+ // is no clone to hold them yet. They name the helper, not the key.
136
+ const flags = ["-c", "credential.helper=", ...settings.flatMap(([name, value]) => ["-c", `${name}=${value}`])];
137
+ const cloned = await git([...flags, "clone", "--origin", "origin", url, dir]);
138
+ if (cloned.code !== 0) throw new GitError("clone", cloned.stderr);
139
+
140
+ // Then they are written into this clone only, never the person's own settings.
141
+ for (const [name, value] of settings) {
142
+ const set = await git(["config", "--local", "--add", name, value], { cwd: dir, quiet: true });
143
+ if (set.code !== 0) throw new GitError("config", set.stderr);
144
+ }
145
+ if (dataHelper) {
146
+ const set = await git(["config", "--local", DATA_HELPER_SETTING, dataHelper], { cwd: dir, quiet: true });
147
+ if (set.code !== 0) throw new GitError("config", set.stderr);
148
+ }
149
+
150
+ if (starterUrl) {
151
+ await git(["remote", "add", STARTER_REMOTE, starterUrl], { cwd: dir, quiet: true });
152
+ // The starter is read from, never pushed to. A push by mistake stops here.
153
+ await git(["remote", "set-url", "--push", STARTER_REMOTE, "no-push://the-starter-is-read-only"], { cwd: dir, quiet: true });
154
+ }
155
+ }
156
+
157
+ /**
158
+ * Give the clone a name and an email for its commits when git has none.
159
+ *
160
+ * On a computer where nobody has told git who they are, git makes both up:
161
+ * on a Mac from the account's full name and the computer's network name (an
162
+ * address on the local network, often), and those go into every commit the
163
+ * site keeps. On Linux it refuses to commit at all. Either way the person's
164
+ * first `git commit` goes wrong, and nothing in a site's own guide would tell
165
+ * them why. So each one git has no setting for is set in this clone only:
166
+ * a non-empty setting the person made, anywhere, is never replaced.
167
+ *
168
+ * @param {object} input
169
+ * @param {GitRunner} input.git
170
+ * @param {string} input.dir
171
+ * @param {{ name: string, email: string }} input.identity
172
+ * @returns {Promise<string[]>} the settings it made: `user.name`, `user.email`
173
+ */
174
+ export async function ensureIdentity({ git, dir, identity }) {
175
+ const has = async (/** @type {string} */ setting) => {
176
+ const found = await git(["config", "--get", setting], { cwd: dir, quiet: true });
177
+ return found.code === 0 && found.stdout.trim() !== "";
178
+ };
179
+ /** @type {string[]} */
180
+ const made = [];
181
+ for (const [part, value] of /** @type {const} */ ([
182
+ ["name", identity.name],
183
+ ["email", identity.email],
184
+ ])) {
185
+ // What git reads at commit time, from the settings that last: user.<part>,
186
+ // or both author.<part> and committer.<part> (one alone leaves the other
187
+ // to be guessed). Environment variables are left out on purpose: they live
188
+ // in one shell, and the person's next commit may come from another.
189
+ if ((await has(`user.${part}`)) || ((await has(`author.${part}`)) && (await has(`committer.${part}`)))) continue;
190
+ const set = await git(["config", "--local", `user.${part}`, value], { cwd: dir, quiet: true });
191
+ if (set.code !== 0) throw new GitError("config", set.stderr);
192
+ made.push(`user.${part}`);
193
+ }
194
+ return made;
195
+ }
196
+
197
+ /**
198
+ * Set, or set again, both lines in a clone that already exists: the
199
+ * credential helper and the data helper. For a clone made before the data
200
+ * helper existed, or after this checkout or Node moved. Whatever the clone
201
+ * had for these settings is replaced; nothing else in it is touched, and
202
+ * nothing outside it.
203
+ *
204
+ * @param {object} input
205
+ * @param {GitRunner} input.git
206
+ * @param {string} input.dir a folder inside the clone
207
+ * @param {string} input.gitBase
208
+ * @param {string} input.helper from helperCommand()
209
+ * @param {string} input.dataHelper from dataHelperCommand()
210
+ */
211
+ export async function linkClone({ git, dir, gitBase, helper, dataHelper }) {
212
+ const settings = credentialSettings(gitBase, helper);
213
+ for (const name of new Set(settings.map(([name]) => name))) {
214
+ const cleared = await git(["config", "--local", "--unset-all", name], { cwd: dir });
215
+ // 5 is git's "there was nothing to remove".
216
+ if (cleared.code !== 0 && cleared.code !== 5) throw new GitError("config", cleared.stderr);
217
+ }
218
+ for (const [name, value] of settings) {
219
+ const set = await git(["config", "--local", "--add", name, value], { cwd: dir });
220
+ if (set.code !== 0) throw new GitError("config", set.stderr);
221
+ }
222
+ const set = await git(["config", "--local", "--replace-all", DATA_HELPER_SETTING, dataHelper], { cwd: dir });
223
+ if (set.code !== 0) throw new GitError("config", set.stderr);
224
+ }
225
+
226
+ export class GitError extends Error {
227
+ /** @param {string} step @param {string} stderr */
228
+ constructor(step, stderr) {
229
+ super(explain(stderr));
230
+ this.name = "GitError";
231
+ this.step = step;
232
+ }
233
+ }
234
+
235
+ /**
236
+ * What a git failure means for the person, from what git printed.
237
+ * @param {string} stderr
238
+ */
239
+ function explain(stderr) {
240
+ if (/Authentication failed|could not read (Username|Password)|terminal prompts disabled/i.test(stderr)) {
241
+ return "Your key was not accepted for this site. Run `sites login` to save a working key.";
242
+ }
243
+ if (/not found/i.test(stderr)) {
244
+ return "This site's files could not be found. Check the name, or that your key can use this site.";
245
+ }
246
+ if (/returned error: 50\d|Could not resolve host|Failed to connect/i.test(stderr)) {
247
+ return "The site's files could not be reached just now. Try again in a minute.";
248
+ }
249
+ if (/already exists and is not an empty directory/i.test(stderr)) {
250
+ return "That folder already exists and is not empty.";
251
+ }
252
+ return "git could not finish. What it said is above.";
253
+ }
254
+
255
+ /** @param {string} value */
256
+ function shellQuote(value) {
257
+ return `'${value.replaceAll("'", `'\\''`)}'`;
258
+ }
@@ -0,0 +1,137 @@
1
+ // Where the `sites` command keeps a person's key, one per environment.
2
+ //
3
+ // On macOS: the login keychain. Elsewhere, or when asked: a file only its
4
+ // owner can read. A key is never printed, never put on a command line, and
5
+ // never written into a repository.
6
+
7
+ import { spawn } from "node:child_process";
8
+ import { randomUUID } from "node:crypto";
9
+ import { chmod, mkdir, readFile, rename, rm, stat, writeFile } from "node:fs/promises";
10
+ import { homedir, platform } from "node:os";
11
+ import { join } from "node:path";
12
+
13
+ const SERVICE = "superintern-sites";
14
+
15
+ /**
16
+ * A key as a person would paste it: one run of printable characters.
17
+ * The limits match what the git address accepts as a password.
18
+ * @param {string} value
19
+ * @returns {string} the key, trimmed
20
+ */
21
+ export function checkedKey(value) {
22
+ const key = String(value ?? "").trim();
23
+ if (key === "") throw new Error("No key was given");
24
+ if (key.length < 8 || key.length > 1024 || !/^[\x21-\x7e]+$/.test(key) || /["'\\]/.test(key)) {
25
+ throw new Error("That does not look like a key: it should be one line of letters, digits and symbols, with no spaces or quotes");
26
+ }
27
+ return key;
28
+ }
29
+
30
+ /**
31
+ * @typedef {object} KeyStore
32
+ * @property {string} where said to the person: where the key is kept
33
+ * @property {(environment: string) => Promise<string | null>} get
34
+ * @property {(environment: string, key: string) => Promise<void>} set
35
+ * @property {(environment: string) => Promise<boolean>} remove true when there was a key to remove
36
+ */
37
+
38
+ /**
39
+ * A folder of files, one per environment, readable by their owner only.
40
+ * @param {string} [dir]
41
+ * @returns {KeyStore}
42
+ */
43
+ export function fileKeyStore(dir = join(homedir(), ".config", "superintern-sites")) {
44
+ const file = (/** @type {string} */ environment) => join(dir, `${environment}.key`);
45
+ return {
46
+ where: dir,
47
+ async get(environment) {
48
+ /** @type {import("node:fs").Stats} */
49
+ let info;
50
+ try {
51
+ info = await stat(file(environment));
52
+ } catch {
53
+ return null;
54
+ }
55
+ // Like ssh with a private key: a file others can read is not used.
56
+ if ((info.mode & 0o077) !== 0) {
57
+ throw new Error(`${file(environment)} can be read by other people on this computer. Run: chmod 600 "${file(environment)}"`);
58
+ }
59
+ const key = (await readFile(file(environment), "utf8")).trim();
60
+ return key === "" ? null : key;
61
+ },
62
+ async set(environment, key) {
63
+ await mkdir(dir, { recursive: true, mode: 0o700 });
64
+ await chmod(dir, 0o700);
65
+ // Written beside the file and moved into place, so nothing reading at
66
+ // the same moment (git asking for the key, say) sees half a file.
67
+ const fresh = `${file(environment)}.${randomUUID()}.tmp`;
68
+ await writeFile(fresh, `${checkedKey(key)}\n`, { mode: 0o600 });
69
+ await chmod(fresh, 0o600); // a leftover file would keep its old mode otherwise
70
+ await rename(fresh, file(environment));
71
+ },
72
+ async remove(environment) {
73
+ try {
74
+ await stat(file(environment));
75
+ } catch {
76
+ return false;
77
+ }
78
+ await rm(file(environment));
79
+ return true;
80
+ },
81
+ };
82
+ }
83
+
84
+ /**
85
+ * The macOS login keychain, through the `security` tool.
86
+ * @param {(args: string[], input?: string) => Promise<{ code: number, stdout: string }>} [run]
87
+ * @returns {KeyStore}
88
+ */
89
+ export function keychainKeyStore(run = runSecurity) {
90
+ return {
91
+ where: "your macOS keychain",
92
+ async get(environment) {
93
+ const { code, stdout } = await run(["find-generic-password", "-a", environment, "-s", SERVICE, "-w"]);
94
+ const key = stdout.trim();
95
+ return code === 0 && key !== "" ? key : null;
96
+ },
97
+ async set(environment, key) {
98
+ // `security -i` reads its command from standard input, so the key is
99
+ // never an argument of any process. checkedKey() has already refused
100
+ // quotes and backslashes, so it cannot break out of the quoted value.
101
+ const command = `add-generic-password -U -a "${environment}" -s "${SERVICE}" -w "${checkedKey(key)}"\n`;
102
+ const { code } = await run(["-i"], command);
103
+ if (code !== 0) throw new Error("The key could not be saved to the keychain");
104
+ },
105
+ async remove(environment) {
106
+ const { code } = await run(["delete-generic-password", "-a", environment, "-s", SERVICE]);
107
+ return code === 0;
108
+ },
109
+ };
110
+ }
111
+
112
+ /**
113
+ * The store to use: the keychain on a Mac, the file elsewhere.
114
+ * SUPERINTERN_SITES_KEY_STORE=file forces the file; SUPERINTERN_SITES_KEY_DIR moves it.
115
+ * @param {NodeJS.ProcessEnv} [env]
116
+ * @returns {KeyStore}
117
+ */
118
+ export function defaultKeyStore(env = process.env) {
119
+ const wantsFile = env.SUPERINTERN_SITES_KEY_STORE === "file" || Boolean(env.SUPERINTERN_SITES_KEY_DIR);
120
+ if (!wantsFile && platform() === "darwin") return keychainKeyStore();
121
+ return fileKeyStore(env.SUPERINTERN_SITES_KEY_DIR || undefined);
122
+ }
123
+
124
+ /**
125
+ * @param {string[]} args @param {string} [input]
126
+ * @returns {Promise<{ code: number, stdout: string }>}
127
+ */
128
+ function runSecurity(args, input) {
129
+ return new Promise((resolve, reject) => {
130
+ const child = spawn("/usr/bin/security", args, { stdio: ["pipe", "pipe", "ignore"] });
131
+ let stdout = "";
132
+ child.stdout.on("data", (chunk) => (stdout += chunk));
133
+ child.on("error", reject);
134
+ child.on("close", (code) => resolve({ code: code ?? 1, stdout }));
135
+ child.stdin.end(input ?? "");
136
+ });
137
+ }
@@ -0,0 +1,33 @@
1
+ // Names no site can have, so the command can say so before anything is sent.
2
+ // The service has the last word (it keeps back more names); this only catches
3
+ // what can never work.
4
+ //
5
+ // The same rule is applied where sites are served. A test
6
+ // (test/sites-package.test.ts) holds the two together: if a name is reserved
7
+ // there and not here, it fails.
8
+
9
+ /** Taken on both services. `site-starter` is the project every site starts from. */
10
+ export const RESERVED_NAMES = ["www", "sites", "app", "api", "admin", "git", "preview", "site-starter"];
11
+
12
+ /** Starts of names kept back on production, so nobody mistakes a live site for a trial one. */
13
+ export const RESERVED_STARTS_PROD = ["staging-", "test-"];
14
+
15
+ /** Names whose address is another service's (the git address), never a site's. */
16
+ const OTHER_SERVICES = ["git"];
17
+
18
+ /**
19
+ * Why a site on this service may not have this name, or null when it may.
20
+ * @param {string} slug one label: lowercase letters, digits, hyphens
21
+ * @param {"test" | "prod"} environment
22
+ * @param {string} sitesDomain where this service's sites get their address
23
+ * @returns {string | null}
24
+ */
25
+ export function nameProblem(slug, environment, sitesDomain) {
26
+ if (OTHER_SERVICES.includes(slug)) return `${slug}.${sitesDomain} is the address of another service`;
27
+ if (RESERVED_NAMES.includes(slug)) return `"${slug}" is a reserved name`;
28
+ if (environment === "prod") {
29
+ const start = RESERVED_STARTS_PROD.find((prefix) => slug.startsWith(prefix));
30
+ if (start) return `names starting "${start}" are reserved`;
31
+ }
32
+ return null;
33
+ }
@@ -0,0 +1,22 @@
1
+ // What the `sites` command is called when it is published, and its version.
2
+ //
3
+ // THE one place for both. `sites --version` prints the version from here,
4
+ // scripts/build-sites-package.mjs writes the published package.json from
5
+ // here, and the release workflow refuses a tag that does not match. To
6
+ // publish under another name, change PACKAGE_NAME and nothing else.
7
+
8
+ /** The npm package. `npm install -g <this>` puts `sites` on the PATH. */
9
+ export const PACKAGE_NAME = "@superintern/sites";
10
+
11
+ /** Raise it, add an entry to npm/CHANGELOG.md, then tag `sites-v<version>`. */
12
+ export const PACKAGE_VERSION = "0.2.0";
13
+
14
+ /**
15
+ * The licence the package is published under, as npm spells it (an SPDX
16
+ * identifier), with its text in npm/LICENSE. The owner chose MIT. `null`
17
+ * would mean "not chosen": the package cannot be built for publishing
18
+ * without a licence, nor while its text does not yet name who holds the
19
+ * copyright.
20
+ * @type {string | null}
21
+ */
22
+ export const PACKAGE_LICENSE = "MIT";
@@ -0,0 +1,88 @@
1
+ // Reading from the person: a key without showing it, and a typed answer.
2
+
3
+ /**
4
+ * The key, from standard input when it is piped (`pbpaste | sites login`),
5
+ * otherwise typed or pasted at a prompt that does not echo.
6
+ * @param {string} question
7
+ * @returns {Promise<string>}
8
+ */
9
+ export function readSecret(question) {
10
+ const input = process.stdin;
11
+ if (!input.isTTY) {
12
+ return new Promise((resolve, reject) => {
13
+ let text = "";
14
+ input.setEncoding("utf8");
15
+ input.on("data", (chunk) => (text += chunk));
16
+ input.on("end", () => resolve(text.split("\n")[0] ?? ""));
17
+ input.on("error", reject);
18
+ });
19
+ }
20
+
21
+ return new Promise((resolve, reject) => {
22
+ process.stderr.write(question);
23
+ input.setRawMode(true);
24
+ input.resume();
25
+ input.setEncoding("utf8");
26
+ let text = "";
27
+ const done = (/** @type {() => void} */ finish) => {
28
+ input.setRawMode(false);
29
+ input.pause();
30
+ input.off("data", onData);
31
+ process.stderr.write("\n");
32
+ finish();
33
+ };
34
+ const onData = (/** @type {string} */ chunk) => {
35
+ for (const char of chunk) {
36
+ if (char === "\r" || char === "\n") return done(() => resolve(text));
37
+ if (char === "\u0003") return done(() => reject(new Error("Cancelled")));
38
+ if (char === "\u007f" || char === "\b") text = text.slice(0, -1);
39
+ else if (char >= " ") text += char;
40
+ }
41
+ };
42
+ input.on("data", onData);
43
+ });
44
+ }
45
+
46
+ /** Asking a question where nobody can answer it (a script, a pipe). */
47
+ export class NotInteractive extends Error {
48
+ constructor() {
49
+ super("Nobody is there to answer");
50
+ this.name = "NotInteractive";
51
+ }
52
+ }
53
+
54
+ /**
55
+ * One line the person types, shown as they type it. Refuses at once when the
56
+ * input is not a terminal: an answer must never be read from a pipe or a
57
+ * script by mistake.
58
+ * @param {string} question
59
+ * @returns {Promise<string>}
60
+ */
61
+ export function readLine(question) {
62
+ const input = process.stdin;
63
+ if (!input.isTTY) return Promise.reject(new NotInteractive());
64
+ return new Promise((resolve, reject) => {
65
+ process.stderr.write(question);
66
+ input.resume();
67
+ input.setEncoding("utf8");
68
+ let text = "";
69
+ const done = (/** @type {() => void} */ finish) => {
70
+ input.pause();
71
+ input.off("data", onData);
72
+ input.off("end", onEnd);
73
+ finish();
74
+ };
75
+ const onData = (/** @type {string} */ chunk) => {
76
+ const end = chunk.search(/[\r\n]/);
77
+ if (end === -1) {
78
+ text += chunk;
79
+ return;
80
+ }
81
+ text += chunk.slice(0, end);
82
+ done(() => resolve(text));
83
+ };
84
+ const onEnd = () => done(() => reject(new Error("Cancelled")));
85
+ input.on("data", onData);
86
+ input.on("end", onEnd);
87
+ });
88
+ }