@sandboxsonny/ace-kit 0.2.0 → 0.3.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.
- package/CHANGELOG.md +10 -0
- package/README.md +1 -0
- package/dist/cli.js +583 -23
- package/docs/command-line.md +51 -0
- package/docs/getting-started.md +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,15 @@
|
|
|
1
1
|
# @sandboxsonny/ace-kit
|
|
2
2
|
|
|
3
|
+
## 0.3.0
|
|
4
|
+
|
|
5
|
+
### Minor Changes
|
|
6
|
+
|
|
7
|
+
- a9d7700: `ace-kit login`, `ace-kit logout` and `ace-kit whoami`: sign in to CMS Ace from the command line.
|
|
8
|
+
|
|
9
|
+
`ace-kit login` uses the OAuth device flow: the terminal shows a short code and opens the admin app, where you type the code and approve it. No password goes into the terminal. The login is kept in the macOS Keychain, or in a file only you can read on other systems, and is what the dev-server sync for sections will use. It can do much less than a browser login and ends after 30 days unused. Needs a CMS Ace API with command-line sign-in (its migration 00020). Set `ACE_TOKEN` to use a token instead (for a build server).
|
|
10
|
+
|
|
11
|
+
`ace-kit generate` is unchanged.
|
|
12
|
+
|
|
3
13
|
## 0.2.0
|
|
4
14
|
|
|
5
15
|
### Minor Changes
|
package/README.md
CHANGED
|
@@ -51,6 +51,7 @@ const about = await getEntry("pages", "about");
|
|
|
51
51
|
| [React](docs/react.md) | Components for any React framework |
|
|
52
52
|
| [Live preview](docs/live-preview.md) | What a site must do for the editor's preview |
|
|
53
53
|
| [Typed content](docs/typed-content.md) | `ace-kit generate` |
|
|
54
|
+
| [The command line](docs/command-line.md) | `ace-kit login`, `logout`, `whoami` |
|
|
54
55
|
| [Rich text](docs/rich-text.md) | The document format and how it is drawn |
|
|
55
56
|
| [API reference](docs/api-reference.md) | Every export |
|
|
56
57
|
| [Releasing](docs/releasing.md) | Versions, the changelog and publishing |
|
package/dist/cli.js
CHANGED
|
@@ -1,8 +1,233 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
|
|
3
|
-
// src/
|
|
4
|
-
import {
|
|
5
|
-
import {
|
|
3
|
+
// src/cli/environment.ts
|
|
4
|
+
import { spawn } from "child_process";
|
|
5
|
+
import { hostname } from "os";
|
|
6
|
+
|
|
7
|
+
// src/auth/file-store.ts
|
|
8
|
+
import { mkdir, readFile, rename, writeFile } from "fs/promises";
|
|
9
|
+
import { homedir } from "os";
|
|
10
|
+
import { dirname, join } from "path";
|
|
11
|
+
|
|
12
|
+
// src/auth/login-store.ts
|
|
13
|
+
function normaliseApiUrl(address) {
|
|
14
|
+
let parsed;
|
|
15
|
+
try {
|
|
16
|
+
parsed = new URL(address.trim());
|
|
17
|
+
} catch {
|
|
18
|
+
throw new Error(`"${address}" is not a web address. Write the API address like http://localhost:8080.`);
|
|
19
|
+
}
|
|
20
|
+
if (parsed.protocol !== "http:" && parsed.protocol !== "https:") {
|
|
21
|
+
throw new Error(`The API address must start with http:// or https:// (it was "${address}").`);
|
|
22
|
+
}
|
|
23
|
+
if (parsed.username || parsed.password) {
|
|
24
|
+
throw new Error("The API address must not contain a username or password.");
|
|
25
|
+
}
|
|
26
|
+
return `${parsed.origin}${parsed.pathname.replace(/\/+$/, "")}`;
|
|
27
|
+
}
|
|
28
|
+
function hasExpired(login, now) {
|
|
29
|
+
const endsAt = Date.parse(login.expiresAt);
|
|
30
|
+
return Number.isNaN(endsAt) || endsAt <= now;
|
|
31
|
+
}
|
|
32
|
+
function parseStoredLogin(value) {
|
|
33
|
+
if (typeof value !== "object" || value === null) return null;
|
|
34
|
+
const { token, expiresAt, email } = value;
|
|
35
|
+
if (typeof token !== "string" || token === "" || typeof expiresAt !== "string" || typeof email !== "string")
|
|
36
|
+
return null;
|
|
37
|
+
return { token, expiresAt, email };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// src/auth/file-store.ts
|
|
41
|
+
function defaultLoginFile(variables, platform) {
|
|
42
|
+
if (platform === "win32" && variables.APPDATA) return join(variables.APPDATA, "ace-kit", "credentials.json");
|
|
43
|
+
const configFolder = variables.XDG_CONFIG_HOME || join(homedir(), ".config");
|
|
44
|
+
return join(configFolder, "ace-kit", "credentials.json");
|
|
45
|
+
}
|
|
46
|
+
function createFileStore(path) {
|
|
47
|
+
async function readAll() {
|
|
48
|
+
let text;
|
|
49
|
+
try {
|
|
50
|
+
text = await readFile(path, "utf8");
|
|
51
|
+
} catch {
|
|
52
|
+
return {};
|
|
53
|
+
}
|
|
54
|
+
let parsed;
|
|
55
|
+
try {
|
|
56
|
+
parsed = JSON.parse(text);
|
|
57
|
+
} catch {
|
|
58
|
+
return {};
|
|
59
|
+
}
|
|
60
|
+
const found = {};
|
|
61
|
+
if (typeof parsed === "object" && parsed !== null) {
|
|
62
|
+
for (const [address, value] of Object.entries(parsed)) {
|
|
63
|
+
const login = parseStoredLogin(value);
|
|
64
|
+
if (login) found[address] = login;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
return found;
|
|
68
|
+
}
|
|
69
|
+
async function writeAll(logins) {
|
|
70
|
+
await mkdir(dirname(path), { recursive: true, mode: 448 });
|
|
71
|
+
const temporary = `${path}.${process.pid}.tmp`;
|
|
72
|
+
await writeFile(temporary, `${JSON.stringify(logins, null, 2)}
|
|
73
|
+
`, { mode: 384 });
|
|
74
|
+
await rename(temporary, path);
|
|
75
|
+
}
|
|
76
|
+
return {
|
|
77
|
+
description: path,
|
|
78
|
+
async read(apiUrl) {
|
|
79
|
+
return (await readAll())[normaliseApiUrl(apiUrl)] ?? null;
|
|
80
|
+
},
|
|
81
|
+
async write(apiUrl, login) {
|
|
82
|
+
const logins = await readAll();
|
|
83
|
+
logins[normaliseApiUrl(apiUrl)] = login;
|
|
84
|
+
await writeAll(logins);
|
|
85
|
+
},
|
|
86
|
+
async remove(apiUrl) {
|
|
87
|
+
const logins = await readAll();
|
|
88
|
+
delete logins[normaliseApiUrl(apiUrl)];
|
|
89
|
+
await writeAll(logins);
|
|
90
|
+
}
|
|
91
|
+
};
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
// src/auth/keychain-store.ts
|
|
95
|
+
var keychainService = "ace-kit";
|
|
96
|
+
function createKeychainStore(run) {
|
|
97
|
+
async function read(apiUrl) {
|
|
98
|
+
const found = await run("security", [
|
|
99
|
+
"find-generic-password",
|
|
100
|
+
"-s",
|
|
101
|
+
keychainService,
|
|
102
|
+
"-a",
|
|
103
|
+
normaliseApiUrl(apiUrl),
|
|
104
|
+
"-w"
|
|
105
|
+
]);
|
|
106
|
+
if (found.exitCode !== 0) return null;
|
|
107
|
+
try {
|
|
108
|
+
return parseStoredLogin(JSON.parse(Buffer.from(found.stdout.trim(), "base64").toString("utf8")));
|
|
109
|
+
} catch {
|
|
110
|
+
return null;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
return {
|
|
114
|
+
description: "the macOS Keychain",
|
|
115
|
+
read,
|
|
116
|
+
async write(apiUrl, login) {
|
|
117
|
+
const account = normaliseApiUrl(apiUrl);
|
|
118
|
+
if (/["\\\s]/.test(account)) throw new Error("That API address can't be kept in the Keychain.");
|
|
119
|
+
const secret = Buffer.from(JSON.stringify(login), "utf8").toString("base64");
|
|
120
|
+
await run(
|
|
121
|
+
"security",
|
|
122
|
+
["-i"],
|
|
123
|
+
`add-generic-password -s "${keychainService}" -a "${account}" -l "Ace Kit login" -w "${secret}" -U
|
|
124
|
+
`
|
|
125
|
+
);
|
|
126
|
+
const kept = await read(apiUrl);
|
|
127
|
+
if (kept?.token !== login.token) throw new Error("The login could not be saved in the macOS Keychain.");
|
|
128
|
+
},
|
|
129
|
+
async remove(apiUrl) {
|
|
130
|
+
await run("security", ["delete-generic-password", "-s", keychainService, "-a", normaliseApiUrl(apiUrl)]);
|
|
131
|
+
}
|
|
132
|
+
};
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// src/auth/choose-store.ts
|
|
136
|
+
async function chooseLoginStore(options) {
|
|
137
|
+
const file = createFileStore(defaultLoginFile(options.variables, options.platform));
|
|
138
|
+
if (options.platform !== "darwin" || options.variables.ACE_KIT_CREDENTIALS === "file") return file;
|
|
139
|
+
try {
|
|
140
|
+
await options.run("security", ["help"]);
|
|
141
|
+
return createKeychainStore(options.run);
|
|
142
|
+
} catch {
|
|
143
|
+
return file;
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
// src/auth/last-api-url.ts
|
|
148
|
+
import { mkdir as mkdir2, readFile as readFile2, rename as rename2, writeFile as writeFile2 } from "fs/promises";
|
|
149
|
+
import { dirname as dirname2, join as join2 } from "path";
|
|
150
|
+
function defaultLastApiUrlFile(variables, platform) {
|
|
151
|
+
return join2(dirname2(defaultLoginFile(variables, platform)), "last-api-url");
|
|
152
|
+
}
|
|
153
|
+
function createLastApiUrl(path) {
|
|
154
|
+
return {
|
|
155
|
+
async read() {
|
|
156
|
+
try {
|
|
157
|
+
return normaliseApiUrl((await readFile2(path, "utf8")).trim());
|
|
158
|
+
} catch {
|
|
159
|
+
return null;
|
|
160
|
+
}
|
|
161
|
+
},
|
|
162
|
+
async write(apiUrl) {
|
|
163
|
+
await mkdir2(dirname2(path), { recursive: true, mode: 448 });
|
|
164
|
+
const temporary = `${path}.${process.pid}.tmp`;
|
|
165
|
+
await writeFile2(temporary, `${normaliseApiUrl(apiUrl)}
|
|
166
|
+
`, { mode: 384 });
|
|
167
|
+
await rename2(temporary, path);
|
|
168
|
+
}
|
|
169
|
+
};
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
// src/cli/version.ts
|
|
173
|
+
var aceKitVersion = true ? "0.3.0" : "development";
|
|
174
|
+
|
|
175
|
+
// src/cli/environment.ts
|
|
176
|
+
var runCommand = (command, commandArguments, input) => new Promise((resolve2, reject) => {
|
|
177
|
+
const child = spawn(command, commandArguments, { stdio: ["pipe", "pipe", "ignore"] });
|
|
178
|
+
let stdout = "";
|
|
179
|
+
child.stdout.on("data", (chunk) => {
|
|
180
|
+
stdout += chunk.toString("utf8");
|
|
181
|
+
});
|
|
182
|
+
child.on("error", reject);
|
|
183
|
+
child.on("close", (exitCode) => resolve2({ exitCode: exitCode ?? 1, stdout }));
|
|
184
|
+
child.stdin.on("error", () => {
|
|
185
|
+
});
|
|
186
|
+
child.stdin.end(input ?? "");
|
|
187
|
+
});
|
|
188
|
+
function browserCommand(platform, address) {
|
|
189
|
+
if (platform === "darwin") return { command: "open", commandArguments: [address] };
|
|
190
|
+
if (platform === "win32") return { command: "rundll32", commandArguments: ["url.dll,FileProtocolHandler", address] };
|
|
191
|
+
return { command: "xdg-open", commandArguments: [address] };
|
|
192
|
+
}
|
|
193
|
+
async function openBrowser(platform, address) {
|
|
194
|
+
const { command, commandArguments } = browserCommand(platform, address);
|
|
195
|
+
await new Promise((resolve2) => {
|
|
196
|
+
const child = spawn(command, commandArguments, { stdio: "ignore", detached: true });
|
|
197
|
+
child.on("error", () => resolve2());
|
|
198
|
+
child.on("spawn", () => {
|
|
199
|
+
child.unref();
|
|
200
|
+
resolve2();
|
|
201
|
+
});
|
|
202
|
+
});
|
|
203
|
+
}
|
|
204
|
+
async function createRealEnvironment() {
|
|
205
|
+
try {
|
|
206
|
+
process.loadEnvFile(".env");
|
|
207
|
+
} catch {
|
|
208
|
+
}
|
|
209
|
+
const variables = { ...process.env };
|
|
210
|
+
const platform = process.platform;
|
|
211
|
+
return {
|
|
212
|
+
variables,
|
|
213
|
+
platform,
|
|
214
|
+
hostname: hostname(),
|
|
215
|
+
version: aceKitVersion,
|
|
216
|
+
out: (text) => process.stdout.write(`${text}
|
|
217
|
+
`),
|
|
218
|
+
error: (text) => console.error(text),
|
|
219
|
+
fetchImplementation: (input, init) => fetch(input, init),
|
|
220
|
+
sleep: (milliseconds) => new Promise((resolve2) => setTimeout(resolve2, milliseconds)),
|
|
221
|
+
now: Date.now,
|
|
222
|
+
openBrowser: (address) => openBrowser(platform, address),
|
|
223
|
+
store: await chooseLoginStore({ platform, variables, run: runCommand }),
|
|
224
|
+
lastApiUrl: createLastApiUrl(defaultLastApiUrlFile(variables, platform))
|
|
225
|
+
};
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
// src/cli/generate-command.ts
|
|
229
|
+
import { mkdir as mkdir3, writeFile as writeFile3 } from "fs/promises";
|
|
230
|
+
import { dirname as dirname3, resolve } from "path";
|
|
6
231
|
import { parseArgs } from "util";
|
|
7
232
|
|
|
8
233
|
// src/client/errors.ts
|
|
@@ -160,8 +385,8 @@ export {};
|
|
|
160
385
|
// src/helpers/package-name.ts
|
|
161
386
|
var packageName = "@sandboxsonny/ace-kit";
|
|
162
387
|
|
|
163
|
-
// src/generate
|
|
164
|
-
var
|
|
388
|
+
// src/cli/generate-command.ts
|
|
389
|
+
var generateUsage = `ace-kit generate: write TypeScript types for your CMS Ace content types.
|
|
165
390
|
|
|
166
391
|
Usage:
|
|
167
392
|
ace-kit generate [--api-url <address>] [--domain <domain>] [--out <file>]
|
|
@@ -172,13 +397,10 @@ Options:
|
|
|
172
397
|
--out Where to write the types (default: src/ace-kit.generated.d.ts).
|
|
173
398
|
--help Show this message.
|
|
174
399
|
`;
|
|
175
|
-
async function
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
}
|
|
180
|
-
const { positionals, values } = parseArgs({
|
|
181
|
-
allowPositionals: true,
|
|
400
|
+
async function generateCommand(commandArguments, environment) {
|
|
401
|
+
const { values } = parseArgs({
|
|
402
|
+
// eslint-disable-next-line id-denylist -- "args" is the name node's parseArgs gives this option.
|
|
403
|
+
args: commandArguments,
|
|
182
404
|
options: {
|
|
183
405
|
"api-url": { type: "string" },
|
|
184
406
|
domain: { type: "string" },
|
|
@@ -186,27 +408,365 @@ async function main() {
|
|
|
186
408
|
help: { type: "boolean" }
|
|
187
409
|
}
|
|
188
410
|
});
|
|
189
|
-
if (values.help
|
|
190
|
-
|
|
191
|
-
return
|
|
411
|
+
if (values.help) {
|
|
412
|
+
environment.out(generateUsage);
|
|
413
|
+
return 0;
|
|
192
414
|
}
|
|
193
|
-
const apiUrl = values["api-url"] ??
|
|
194
|
-
const siteDomain = values.domain ??
|
|
415
|
+
const apiUrl = values["api-url"] ?? environment.variables.ACE_API_URL;
|
|
416
|
+
const siteDomain = values.domain ?? environment.variables.ACE_SITE_DOMAIN;
|
|
195
417
|
if (!apiUrl || !siteDomain) {
|
|
196
|
-
|
|
418
|
+
environment.error(
|
|
197
419
|
"Give the API address and the site's domain: --api-url and --domain, or ACE_API_URL and ACE_SITE_DOMAIN."
|
|
198
420
|
);
|
|
199
421
|
return 1;
|
|
200
422
|
}
|
|
201
|
-
const client = createAceClient({
|
|
423
|
+
const client = createAceClient({
|
|
424
|
+
apiUrl,
|
|
425
|
+
siteDomain,
|
|
426
|
+
cacheSeconds: 0,
|
|
427
|
+
fetchImplementation: environment.fetchImplementation
|
|
428
|
+
});
|
|
202
429
|
const contentTypes = await client.getContentTypes();
|
|
203
430
|
const file = resolve(values.out ?? "src/ace-kit.generated.d.ts");
|
|
204
|
-
await
|
|
205
|
-
await
|
|
206
|
-
|
|
431
|
+
await mkdir3(dirname3(file), { recursive: true });
|
|
432
|
+
await writeFile3(file, generateTypes(contentTypes, packageName, siteDomain));
|
|
433
|
+
environment.out(
|
|
434
|
+
`Wrote types for ${contentTypes.length} content type${contentTypes.length === 1 ? "" : "s"} to ${file}.`
|
|
435
|
+
);
|
|
436
|
+
return 0;
|
|
437
|
+
}
|
|
438
|
+
|
|
439
|
+
// src/cli/login-commands.ts
|
|
440
|
+
import { parseArgs as parseArgs2 } from "util";
|
|
441
|
+
|
|
442
|
+
// src/auth/device-login.ts
|
|
443
|
+
var DeviceLoginError = class extends Error {
|
|
444
|
+
reason;
|
|
445
|
+
constructor(reason, message) {
|
|
446
|
+
super(message);
|
|
447
|
+
this.name = "DeviceLoginError";
|
|
448
|
+
this.reason = reason;
|
|
449
|
+
}
|
|
450
|
+
};
|
|
451
|
+
var requestTimeoutMilliseconds2 = 15e3;
|
|
452
|
+
var maximumFailures = 5;
|
|
453
|
+
async function post(dependencies, apiUrl, path, body) {
|
|
454
|
+
return dependencies.fetchImplementation(`${apiUrl}${path}`, {
|
|
455
|
+
method: "POST",
|
|
456
|
+
headers: { Accept: "application/json", "Content-Type": "application/json" },
|
|
457
|
+
body: JSON.stringify(body),
|
|
458
|
+
signal: AbortSignal.timeout(requestTimeoutMilliseconds2)
|
|
459
|
+
});
|
|
460
|
+
}
|
|
461
|
+
async function readMessage(response) {
|
|
462
|
+
try {
|
|
463
|
+
const body = await response.json();
|
|
464
|
+
if (typeof body.error === "string") return body.error;
|
|
465
|
+
} catch {
|
|
466
|
+
}
|
|
467
|
+
return `The CMS answered with an error (${response.status}).`;
|
|
468
|
+
}
|
|
469
|
+
async function startDeviceLogin(dependencies) {
|
|
470
|
+
let response;
|
|
471
|
+
try {
|
|
472
|
+
response = await post(dependencies, dependencies.apiUrl, "/auth/device", { client_name: dependencies.clientName });
|
|
473
|
+
} catch {
|
|
474
|
+
throw new DeviceLoginError("unavailable", `Could not reach the CMS at ${dependencies.apiUrl}.`);
|
|
475
|
+
}
|
|
476
|
+
if (response.status === 503) throw new DeviceLoginError("unsupported", await readMessage(response));
|
|
477
|
+
if (response.status === 429)
|
|
478
|
+
throw new DeviceLoginError("unavailable", "Too many attempts. Wait a minute and try again.");
|
|
479
|
+
if (response.status === 404) {
|
|
480
|
+
throw new DeviceLoginError(
|
|
481
|
+
"unsupported",
|
|
482
|
+
`${dependencies.apiUrl} does not offer command-line sign-in. Is it a CMS Ace API, and is it up to date?`
|
|
483
|
+
);
|
|
484
|
+
}
|
|
485
|
+
if (!response.ok) throw new DeviceLoginError("unavailable", await readMessage(response));
|
|
486
|
+
const body = await response.json().catch(() => null);
|
|
487
|
+
const { device_code, user_code, verification_uri, expires_in, interval } = body ?? {};
|
|
488
|
+
if (typeof device_code !== "string" || typeof user_code !== "string" || typeof verification_uri !== "string" || typeof expires_in !== "number" || typeof interval !== "number") {
|
|
489
|
+
throw new DeviceLoginError(
|
|
490
|
+
"unavailable",
|
|
491
|
+
"The CMS sent a reply this version of ace-kit can't read. Update ace-kit."
|
|
492
|
+
);
|
|
493
|
+
}
|
|
494
|
+
return {
|
|
495
|
+
deviceCode: device_code,
|
|
496
|
+
userCode: user_code,
|
|
497
|
+
verificationUri: verification_uri,
|
|
498
|
+
expiresInSeconds: expires_in,
|
|
499
|
+
intervalSeconds: Math.max(1, interval)
|
|
500
|
+
};
|
|
501
|
+
}
|
|
502
|
+
async function waitForApproval(dependencies) {
|
|
503
|
+
const { apiUrl, request, sleep, now } = dependencies;
|
|
504
|
+
const deadline = now() + request.expiresInSeconds * 1e3;
|
|
505
|
+
let intervalSeconds = request.intervalSeconds;
|
|
506
|
+
let failures = 0;
|
|
507
|
+
for (; ; ) {
|
|
508
|
+
await sleep(intervalSeconds * 1e3);
|
|
509
|
+
if (now() > deadline)
|
|
510
|
+
throw new DeviceLoginError("expired", "The code ran out before it was approved. Run ace-kit login again.");
|
|
511
|
+
let response;
|
|
512
|
+
try {
|
|
513
|
+
response = await post(dependencies, apiUrl, "/auth/device/token", { device_code: request.deviceCode });
|
|
514
|
+
} catch {
|
|
515
|
+
failures += 1;
|
|
516
|
+
if (failures >= maximumFailures)
|
|
517
|
+
throw new DeviceLoginError("unavailable", `Lost contact with the CMS at ${apiUrl}.`);
|
|
518
|
+
continue;
|
|
519
|
+
}
|
|
520
|
+
if (response.status === 404) {
|
|
521
|
+
throw new DeviceLoginError("expired", "The CMS no longer knows this login. Run ace-kit login again.");
|
|
522
|
+
}
|
|
523
|
+
if (response.status === 429) {
|
|
524
|
+
intervalSeconds += 5;
|
|
525
|
+
continue;
|
|
526
|
+
}
|
|
527
|
+
if (!response.ok) {
|
|
528
|
+
failures += 1;
|
|
529
|
+
if (failures >= maximumFailures) throw new DeviceLoginError("unavailable", await readMessage(response));
|
|
530
|
+
continue;
|
|
531
|
+
}
|
|
532
|
+
failures = 0;
|
|
533
|
+
const body = await response.json().catch(() => null);
|
|
534
|
+
switch (body?.status) {
|
|
535
|
+
case "pending":
|
|
536
|
+
continue;
|
|
537
|
+
case "slow_down":
|
|
538
|
+
intervalSeconds += 5;
|
|
539
|
+
continue;
|
|
540
|
+
case "denied":
|
|
541
|
+
throw new DeviceLoginError("denied", "The login was turned down in the admin app.");
|
|
542
|
+
case "expired":
|
|
543
|
+
throw new DeviceLoginError("expired", "The code ran out before it was approved. Run ace-kit login again.");
|
|
544
|
+
case "approved": {
|
|
545
|
+
const user = body.user;
|
|
546
|
+
if (typeof body.token !== "string" || typeof body.expires_at !== "string" || typeof user?.email !== "string") {
|
|
547
|
+
throw new DeviceLoginError("unavailable", "The CMS approved the login but sent a reply that can't be read.");
|
|
548
|
+
}
|
|
549
|
+
return { token: body.token, expiresAt: body.expires_at, email: user.email };
|
|
550
|
+
}
|
|
551
|
+
default:
|
|
552
|
+
throw new DeviceLoginError(
|
|
553
|
+
"unavailable",
|
|
554
|
+
"The CMS sent a reply this version of ace-kit can't read. Update ace-kit."
|
|
555
|
+
);
|
|
556
|
+
}
|
|
557
|
+
}
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
// src/auth/resolve-login.ts
|
|
561
|
+
async function resolveLogin(options) {
|
|
562
|
+
const fromEnvironment = options.variables.ACE_TOKEN?.trim();
|
|
563
|
+
if (fromEnvironment) return { token: fromEnvironment, source: "the ACE_TOKEN setting" };
|
|
564
|
+
const stored = await options.store.read(options.apiUrl);
|
|
565
|
+
if (!stored || hasExpired(stored, options.now())) return null;
|
|
566
|
+
return { token: stored.token, email: stored.email, source: options.store.description };
|
|
567
|
+
}
|
|
568
|
+
|
|
569
|
+
// src/cli/login-commands.ts
|
|
570
|
+
var loginUsage = `ace-kit login: sign in to CMS Ace from the command line.
|
|
571
|
+
|
|
572
|
+
Usage:
|
|
573
|
+
ace-kit login [--api-url <address>] Sign in. Opens the admin app, where you type the code shown here.
|
|
574
|
+
ace-kit logout [--api-url <address>] Sign out, and forget the login kept on this machine.
|
|
575
|
+
ace-kit whoami [--api-url <address>] Say who you are signed in as.
|
|
576
|
+
|
|
577
|
+
Options:
|
|
578
|
+
--api-url Where the CMS Ace API lives (or set ACE_API_URL, in the environment or a .env file).
|
|
579
|
+
--help Show this message.
|
|
580
|
+
|
|
581
|
+
The login is kept in the macOS Keychain, or in a file only you can read on other systems. On a build server,
|
|
582
|
+
where nobody can approve a login in a browser, set ACE_TOKEN instead.
|
|
583
|
+
`;
|
|
584
|
+
var requestTimeoutMilliseconds3 = 15e3;
|
|
585
|
+
async function readApiUrl(commandArguments, environment) {
|
|
586
|
+
const { values } = parseArgs2({
|
|
587
|
+
// eslint-disable-next-line id-denylist -- "args" is the name node's parseArgs gives this option.
|
|
588
|
+
args: commandArguments,
|
|
589
|
+
options: { "api-url": { type: "string" }, help: { type: "boolean" } }
|
|
590
|
+
});
|
|
591
|
+
if (values.help) return { help: true };
|
|
592
|
+
const address = values["api-url"] ?? environment.variables.ACE_API_URL ?? await environment.lastApiUrl.read();
|
|
593
|
+
if (!address) {
|
|
594
|
+
environment.error(
|
|
595
|
+
"Give the API address: --api-url, or ACE_API_URL in the environment or a .env file. (Once you have signed in, that address is remembered.)"
|
|
596
|
+
);
|
|
597
|
+
return null;
|
|
598
|
+
}
|
|
599
|
+
try {
|
|
600
|
+
return { apiUrl: normaliseApiUrl(address) };
|
|
601
|
+
} catch (error) {
|
|
602
|
+
environment.error(error instanceof Error ? error.message : String(error));
|
|
603
|
+
return null;
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
function webAddress(address) {
|
|
607
|
+
try {
|
|
608
|
+
const parsed = new URL(address);
|
|
609
|
+
return parsed.protocol === "http:" || parsed.protocol === "https:" ? parsed.href : null;
|
|
610
|
+
} catch {
|
|
611
|
+
return null;
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
var isLocal = (apiUrl) => ["localhost", "127.0.0.1", "[::1]"].includes(new URL(apiUrl).hostname);
|
|
615
|
+
async function loginCommand(commandArguments, environment) {
|
|
616
|
+
const read = await readApiUrl(commandArguments, environment);
|
|
617
|
+
if (!read) return 1;
|
|
618
|
+
if ("help" in read) {
|
|
619
|
+
environment.out(loginUsage);
|
|
620
|
+
return 0;
|
|
621
|
+
}
|
|
622
|
+
const { apiUrl } = read;
|
|
623
|
+
if (apiUrl.startsWith("http://") && !isLocal(apiUrl)) {
|
|
624
|
+
environment.error(
|
|
625
|
+
`Warning: ${apiUrl} is not encrypted (http://), so the login could be read on the way. Use https:// if you can.`
|
|
626
|
+
);
|
|
627
|
+
}
|
|
628
|
+
try {
|
|
629
|
+
const request = await startDeviceLogin({
|
|
630
|
+
fetchImplementation: environment.fetchImplementation,
|
|
631
|
+
apiUrl,
|
|
632
|
+
clientName: `ace-kit ${environment.version} on ${environment.hostname}`
|
|
633
|
+
});
|
|
634
|
+
const page = webAddress(request.verificationUri);
|
|
635
|
+
if (!page)
|
|
636
|
+
throw new DeviceLoginError(
|
|
637
|
+
"unsupported",
|
|
638
|
+
"The CMS sent an approval address that isn't a web address, so it was not opened."
|
|
639
|
+
);
|
|
640
|
+
environment.out(`Signing in to ${apiUrl}
|
|
641
|
+
`);
|
|
642
|
+
environment.out(` 1. Go to ${page}`);
|
|
643
|
+
environment.out(` 2. Type ${request.userCode}
|
|
644
|
+
`);
|
|
645
|
+
environment.out("Check the code on that page matches. Waiting for you to approve it (Ctrl-C to cancel)...");
|
|
646
|
+
await environment.openBrowser(page).catch(() => void 0);
|
|
647
|
+
const login = await waitForApproval({
|
|
648
|
+
fetchImplementation: environment.fetchImplementation,
|
|
649
|
+
apiUrl,
|
|
650
|
+
request,
|
|
651
|
+
sleep: environment.sleep,
|
|
652
|
+
now: environment.now
|
|
653
|
+
});
|
|
654
|
+
await environment.store.write(apiUrl, login);
|
|
655
|
+
await environment.lastApiUrl.write(apiUrl).catch(() => void 0);
|
|
656
|
+
environment.out(`
|
|
657
|
+
Signed in as ${login.email}. The login is kept in ${environment.store.description}.`);
|
|
658
|
+
return 0;
|
|
659
|
+
} catch (error) {
|
|
660
|
+
environment.error(`
|
|
661
|
+
${error instanceof Error ? error.message : String(error)}`);
|
|
662
|
+
return 1;
|
|
663
|
+
}
|
|
664
|
+
}
|
|
665
|
+
async function logoutCommand(commandArguments, environment) {
|
|
666
|
+
const read = await readApiUrl(commandArguments, environment);
|
|
667
|
+
if (!read) return 1;
|
|
668
|
+
if ("help" in read) {
|
|
669
|
+
environment.out(loginUsage);
|
|
670
|
+
return 0;
|
|
671
|
+
}
|
|
672
|
+
const { apiUrl } = read;
|
|
673
|
+
const stored = await environment.store.read(apiUrl);
|
|
674
|
+
if (!stored) {
|
|
675
|
+
environment.out(`Not signed in to ${apiUrl}.`);
|
|
676
|
+
return 0;
|
|
677
|
+
}
|
|
678
|
+
const ended = await environment.fetchImplementation(`${apiUrl}/auth/logout`, {
|
|
679
|
+
method: "POST",
|
|
680
|
+
headers: { Authorization: `Bearer ${stored.token}` },
|
|
681
|
+
signal: AbortSignal.timeout(requestTimeoutMilliseconds3)
|
|
682
|
+
}).then(
|
|
683
|
+
(response) => response.ok || response.status === 401,
|
|
684
|
+
() => false
|
|
685
|
+
);
|
|
686
|
+
await environment.store.remove(apiUrl);
|
|
687
|
+
environment.out(
|
|
688
|
+
ended ? `Signed out of ${apiUrl}.` : `Forgot the login for ${apiUrl} on this machine, but could not reach the CMS to end it there. It ends by itself after 30 days unused; a super admin can also end it from the Sessions screen.`
|
|
689
|
+
);
|
|
207
690
|
return 0;
|
|
208
691
|
}
|
|
209
|
-
|
|
692
|
+
async function whoamiCommand(commandArguments, environment) {
|
|
693
|
+
const read = await readApiUrl(commandArguments, environment);
|
|
694
|
+
if (!read) return 1;
|
|
695
|
+
if ("help" in read) {
|
|
696
|
+
environment.out(loginUsage);
|
|
697
|
+
return 0;
|
|
698
|
+
}
|
|
699
|
+
const { apiUrl } = read;
|
|
700
|
+
const login = await resolveLogin({
|
|
701
|
+
apiUrl,
|
|
702
|
+
variables: environment.variables,
|
|
703
|
+
store: environment.store,
|
|
704
|
+
now: environment.now
|
|
705
|
+
});
|
|
706
|
+
if (!login) {
|
|
707
|
+
environment.out(`Not signed in to ${apiUrl}. Run: ace-kit login`);
|
|
708
|
+
return 1;
|
|
709
|
+
}
|
|
710
|
+
try {
|
|
711
|
+
const response = await environment.fetchImplementation(`${apiUrl}/auth/me`, {
|
|
712
|
+
headers: { Accept: "application/json", Authorization: `Bearer ${login.token}` },
|
|
713
|
+
signal: AbortSignal.timeout(requestTimeoutMilliseconds3)
|
|
714
|
+
});
|
|
715
|
+
if (response.status === 401) {
|
|
716
|
+
environment.out(`The login from ${login.source} has ended. Run: ace-kit login`);
|
|
717
|
+
return 1;
|
|
718
|
+
}
|
|
719
|
+
if (!response.ok) {
|
|
720
|
+
environment.error(`The CMS answered with an error (${response.status}).`);
|
|
721
|
+
return 1;
|
|
722
|
+
}
|
|
723
|
+
const me = await response.json();
|
|
724
|
+
environment.out(`Signed in to ${apiUrl} as ${String(me.email)}, using the login in ${login.source}.`);
|
|
725
|
+
return 0;
|
|
726
|
+
} catch {
|
|
727
|
+
environment.error(`Could not reach the CMS at ${apiUrl}.`);
|
|
728
|
+
return 1;
|
|
729
|
+
}
|
|
730
|
+
}
|
|
731
|
+
|
|
732
|
+
// src/cli/main.ts
|
|
733
|
+
var usage = `ace-kit: tools for sites built on CMS Ace.
|
|
734
|
+
|
|
735
|
+
Commands:
|
|
736
|
+
ace-kit generate Write TypeScript types for your content types.
|
|
737
|
+
ace-kit login Sign in from the command line (opens the admin app).
|
|
738
|
+
ace-kit logout Sign out.
|
|
739
|
+
ace-kit whoami Say who you are signed in as.
|
|
740
|
+
|
|
741
|
+
Run a command with --help for more.
|
|
742
|
+
`;
|
|
743
|
+
async function runCli(commandArguments, environment) {
|
|
744
|
+
const [command, ...rest] = commandArguments;
|
|
745
|
+
switch (command) {
|
|
746
|
+
case "generate":
|
|
747
|
+
return generateCommand(rest, environment);
|
|
748
|
+
case "login":
|
|
749
|
+
return loginCommand(rest, environment);
|
|
750
|
+
case "logout":
|
|
751
|
+
return logoutCommand(rest, environment);
|
|
752
|
+
case "whoami":
|
|
753
|
+
return whoamiCommand(rest, environment);
|
|
754
|
+
case "--help":
|
|
755
|
+
case "-h":
|
|
756
|
+
case "help":
|
|
757
|
+
case void 0:
|
|
758
|
+
environment.out(usage);
|
|
759
|
+
return command === void 0 ? 1 : 0;
|
|
760
|
+
default:
|
|
761
|
+
environment.error(`Unknown command "${command}".
|
|
762
|
+
|
|
763
|
+
${usage}`);
|
|
764
|
+
return 1;
|
|
765
|
+
}
|
|
766
|
+
}
|
|
767
|
+
|
|
768
|
+
// src/cli/bin.ts
|
|
769
|
+
createRealEnvironment().then((environment) => runCli(process.argv.slice(2), environment)).then(
|
|
210
770
|
(code) => process.exit(code),
|
|
211
771
|
(error) => {
|
|
212
772
|
console.error(error instanceof Error ? error.message : error);
|
|
@@ -0,0 +1,51 @@
|
|
|
1
|
+
# The command line
|
|
2
|
+
|
|
3
|
+
`ace-kit` is also a command. It signs you in to CMS Ace from your terminal, and writes types for your content.
|
|
4
|
+
|
|
5
|
+
```sh
|
|
6
|
+
npx ace-kit login # sign in
|
|
7
|
+
npx ace-kit whoami # who am I signed in as?
|
|
8
|
+
npx ace-kit logout # sign out
|
|
9
|
+
npx ace-kit generate # write TypeScript types (see Typed content)
|
|
10
|
+
```
|
|
11
|
+
|
|
12
|
+
Every command takes `--api-url`, or reads `ACE_API_URL` from the environment or a `.env` file in the folder you run it in. Failing both, it uses the address you last signed in to (kept in a small file beside your logins), so after `ace-kit login --api-url …` you can simply run `ace-kit whoami` from anywhere.
|
|
13
|
+
|
|
14
|
+
## Signing in
|
|
15
|
+
|
|
16
|
+
```sh
|
|
17
|
+
npx ace-kit login --api-url http://localhost:8080
|
|
18
|
+
```
|
|
19
|
+
|
|
20
|
+
```
|
|
21
|
+
Signing in to http://localhost:8080
|
|
22
|
+
|
|
23
|
+
1. Go to http://localhost:5173/device
|
|
24
|
+
2. Type BCDF-GHJK
|
|
25
|
+
|
|
26
|
+
Check the code on that page matches. Waiting for you to approve it (Ctrl-C to cancel)...
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
Your browser opens the CMS admin app's approval page. **Type the code from your terminal** into it (it is deliberately not in the link), check that the tool and the address it shows are yours, and choose **Approve**. The terminal then says who you are signed in as. This is the OAuth device flow, the same shape as `gh auth login`: no password is ever typed into the terminal, and nothing secret is written in a file inside your project.
|
|
30
|
+
|
|
31
|
+
Only approve a login you started just now, from your own terminal. If the code on the page doesn't match the one in your terminal, or you didn't ask for a login, choose **Turn it down**.
|
|
32
|
+
|
|
33
|
+
## Where the login is kept
|
|
34
|
+
|
|
35
|
+
- **On a Mac:** the macOS Keychain, as an item named `ace-kit` whose account is the API address. You can see it in Keychain Access. Ace Kit uses the `security` program that comes with macOS, so nothing native is installed, and the login is handed to it on standard input, never as an argument other users of the machine could read.
|
|
36
|
+
- **Anywhere else:** a file only you can read, `~/.config/ace-kit/credentials.json` (mode `0600`, in a folder of mode `0700`; `%APPDATA%\ace-kit` on Windows). Set `XDG_CONFIG_HOME` to move it.
|
|
37
|
+
- Set `ACE_KIT_CREDENTIALS=file` to use the file even on a Mac.
|
|
38
|
+
|
|
39
|
+
One login is kept per API address, so you can be signed in to a local CMS and a hosted one at once.
|
|
40
|
+
|
|
41
|
+
## What a command-line login can do
|
|
42
|
+
|
|
43
|
+
Much less than you can in the browser. It can see which sites you can reach, read their content types, and read and sync their section types (the last only on a site where you are an owner, or a super admin). It cannot manage members, passwords or other logins, read or change entries and images, or approve another command-line login. It lasts 90 days at most and ends after 30 days unused. A super admin sees it on the Sessions screen, named after your machine, and can end it from there.
|
|
44
|
+
|
|
45
|
+
## Build servers
|
|
46
|
+
|
|
47
|
+
A build server has nobody to approve a login in a browser. Set `ACE_TOKEN` to a token instead and Ace Kit uses it in place of a stored login. (Tokens for this are not made yet; for now sign in on the machine that needs it.)
|
|
48
|
+
|
|
49
|
+
## Signing out
|
|
50
|
+
|
|
51
|
+
`npx ace-kit logout` ends the login at the CMS and forgets it on this machine. If the CMS can't be reached it still forgets it here, and says so.
|
package/docs/getting-started.md
CHANGED
|
@@ -22,7 +22,7 @@ npm install @sandboxsonny/ace-kit
|
|
|
22
22
|
| `@sandboxsonny/ace-kit/react-router` | React Router 7, browser-safe: `AceRichText` (router links), `AceImage`, `AceNotice`, `createMeta`, `useAceMenu`, `useAcePreview` |
|
|
23
23
|
| `@sandboxsonny/ace-kit/react-router/server` | React Router 7, server only: `createPageLoader`, `createRootLoader`, `handleRequest` (the server entry), `getEntry`, `getEntries`, `getMenuLinks`, `getAceClient` |
|
|
24
24
|
| `@sandboxsonny/ace-kit/vite` | A Vite plugin: reads `ACE_` settings from `.env` in development and keeps one copy of React |
|
|
25
|
-
| `ace-kit` (command) | `ace-kit generate
|
|
25
|
+
| `ace-kit` (command) | `ace-kit generate` (TypeScript types for your content), `login`, `logout`, `whoami` (see [the command line](./command-line.md)) |
|
|
26
26
|
|
|
27
27
|
## The client
|
|
28
28
|
|
package/package.json
CHANGED