@livespace/plugin-cli 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +69 -2
- package/dist/cli.js +182 -0
- package/dist/commands/client-id.js +12 -0
- package/dist/commands/context.js +7 -0
- package/dist/commands/keys.js +152 -0
- package/dist/commands/load.js +25 -0
- package/dist/commands/manifest.js +378 -0
- package/dist/keys/files.js +48 -0
- package/dist/keys/generate.js +50 -0
- package/dist/keys/keyset.js +48 -0
- package/dist/manifest/check.js +258 -0
- package/dist/manifest/file.js +59 -0
- package/dist/manifest/package-json.js +49 -0
- package/dist/manifest/schema.js +77 -0
- package/dist/ui/clack.js +50 -0
- package/dist/ui/output.js +45 -0
- package/dist/ui/prompter.js +140 -0
- package/dist/ui/validators.js +45 -0
- package/package.json +39 -5
|
@@ -0,0 +1,378 @@
|
|
|
1
|
+
/** `manifest init`, `manifest set` and `manifest check`. */
|
|
2
|
+
import { checkManifest } from "../manifest/check.js";
|
|
3
|
+
import { readManifestText, readPackageJson, serializeManifest, writeManifest, } from "../manifest/file.js";
|
|
4
|
+
import { prefillFrom } from "../manifest/package-json.js";
|
|
5
|
+
import { CATEGORIES, EXPECTED_LOCALES, LOCALES, MANIFEST_FILE, OBJECT_TYPES, REQUIRED_LOCALE, clientIdOf, } from "../manifest/schema.js";
|
|
6
|
+
import { isHexColor, isHttpsOrigin, isHttpsUrl, isId, isKeyList, isSemver, isSvgUrl, splitList, } from "../ui/validators.js";
|
|
7
|
+
import { UsageError } from "./context.js";
|
|
8
|
+
import { createKeys, saveKeys } from "./keys.js";
|
|
9
|
+
import { loadManifest } from "./load.js";
|
|
10
|
+
const ANY = "any";
|
|
11
|
+
const OTHER = "__other";
|
|
12
|
+
const OBJECT_TYPE_LABELS = {
|
|
13
|
+
deal: "Deal",
|
|
14
|
+
company: "Company",
|
|
15
|
+
person: "Person",
|
|
16
|
+
space: "Space",
|
|
17
|
+
dashboard: "Dashboard (the start screen)",
|
|
18
|
+
};
|
|
19
|
+
const LOCALE_LABELS = {
|
|
20
|
+
en: "English",
|
|
21
|
+
pl: "Polish",
|
|
22
|
+
ro: "Romanian",
|
|
23
|
+
cs: "Czech",
|
|
24
|
+
es: "Spanish",
|
|
25
|
+
sk: "Slovak",
|
|
26
|
+
};
|
|
27
|
+
const objectTypeChoices = [
|
|
28
|
+
{
|
|
29
|
+
value: ANY,
|
|
30
|
+
label: "Any type",
|
|
31
|
+
hint: "no requirements, the apps menu included",
|
|
32
|
+
},
|
|
33
|
+
...OBJECT_TYPES.map((type) => ({
|
|
34
|
+
value: type,
|
|
35
|
+
label: OBJECT_TYPE_LABELS[type],
|
|
36
|
+
})),
|
|
37
|
+
];
|
|
38
|
+
/** `["any", …]` means no requirements: null in the manifest. */
|
|
39
|
+
const toObjectTypes = (answer) => answer.includes(ANY) ? null : answer;
|
|
40
|
+
const askObjectTypes = async (p, initial) => toObjectTypes(await p.multiselect({
|
|
41
|
+
name: "object-types",
|
|
42
|
+
message: "Where may it go? (one or more, or Any type)",
|
|
43
|
+
options: objectTypeChoices,
|
|
44
|
+
initial,
|
|
45
|
+
}));
|
|
46
|
+
/**
|
|
47
|
+
* Which languages to write texts in. Asked in a terminal; from flags, it's whatever languages the
|
|
48
|
+
* `--name-<lang>` and `--description-<lang>` flags name, English always included.
|
|
49
|
+
*/
|
|
50
|
+
async function askLanguages(ctx) {
|
|
51
|
+
const flagged = LOCALES.filter((lang) => ["name", "description"].some((field) => typeof ctx.flags[`${field}-${lang}`] === "string"));
|
|
52
|
+
const ensureEnglish = (langs) => [
|
|
53
|
+
REQUIRED_LOCALE,
|
|
54
|
+
...langs.filter((l) => l !== REQUIRED_LOCALE),
|
|
55
|
+
];
|
|
56
|
+
if (!ctx.interactive && typeof ctx.flags.languages !== "string") {
|
|
57
|
+
return ensureEnglish(flagged);
|
|
58
|
+
}
|
|
59
|
+
const chosen = await ctx.prompter.multiselect({
|
|
60
|
+
name: "languages",
|
|
61
|
+
message: "Which languages will you write its texts in? (English is required)",
|
|
62
|
+
options: LOCALES.map((lang) => ({
|
|
63
|
+
value: lang,
|
|
64
|
+
label: LOCALE_LABELS[lang],
|
|
65
|
+
})),
|
|
66
|
+
initial: [...new Set([...EXPECTED_LOCALES, ...flagged])],
|
|
67
|
+
});
|
|
68
|
+
return ensureEnglish(chosen);
|
|
69
|
+
}
|
|
70
|
+
const asText = (entries) => {
|
|
71
|
+
const text = Object.fromEntries(entries.filter((e) => e[1] !== undefined));
|
|
72
|
+
return Object.keys(text).length > 0 ? text : undefined;
|
|
73
|
+
};
|
|
74
|
+
async function askCategories(p, initial) {
|
|
75
|
+
const chosen = await p.multiselect({
|
|
76
|
+
name: "categories",
|
|
77
|
+
message: "Categories in the catalog (optional)",
|
|
78
|
+
options: [
|
|
79
|
+
...CATEGORIES.map((c) => ({ value: c, label: c })),
|
|
80
|
+
{ value: OTHER, label: "Other…", hint: "type your own" },
|
|
81
|
+
],
|
|
82
|
+
initial,
|
|
83
|
+
required: false,
|
|
84
|
+
allowOther: true,
|
|
85
|
+
});
|
|
86
|
+
const categories = chosen.filter((c) => c !== OTHER);
|
|
87
|
+
if (chosen.includes(OTHER)) {
|
|
88
|
+
const others = await p.text({
|
|
89
|
+
name: "other-categories",
|
|
90
|
+
message: "Other categories, comma-separated (English)",
|
|
91
|
+
});
|
|
92
|
+
categories.push(...splitList(others ?? ""));
|
|
93
|
+
}
|
|
94
|
+
return categories.length > 0 ? categories : undefined;
|
|
95
|
+
}
|
|
96
|
+
/** Refuses with every failure the checker found; otherwise reports its warnings. */
|
|
97
|
+
function requirePasses(ctx, manifest) {
|
|
98
|
+
const { failures, warnings } = checkManifest(serializeManifest(manifest));
|
|
99
|
+
if (failures.length > 0) {
|
|
100
|
+
throw new UsageError(`The manifest wouldn't pass, so nothing was written:\n${failures.map((f) => ` ✗ ${f}`).join("\n")}`);
|
|
101
|
+
}
|
|
102
|
+
for (const warning of warnings) {
|
|
103
|
+
ctx.out.warn(warning);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
export async function manifestInit(ctx) {
|
|
107
|
+
const p = ctx.prompter;
|
|
108
|
+
if ((await readManifestText(ctx.dir)) !== undefined) {
|
|
109
|
+
throw new UsageError(`${MANIFEST_FILE} already exists — its "id" is the catalog key, so it isn't rewritten. Change a field with \`manifest set\`, or check it with \`manifest check\`.`);
|
|
110
|
+
}
|
|
111
|
+
const pkg = await readPackageJson(ctx.dir);
|
|
112
|
+
const prefill = pkg ? prefillFrom(pkg) : {};
|
|
113
|
+
ctx.out.start("Livespace plugin manifest");
|
|
114
|
+
if (pkg) {
|
|
115
|
+
ctx.out.info("Defaults come from package.json; change any of them.");
|
|
116
|
+
}
|
|
117
|
+
const id = await p.text({
|
|
118
|
+
name: "id",
|
|
119
|
+
message: "Catalog key (the plugin's id)?",
|
|
120
|
+
initial: prefill.id,
|
|
121
|
+
placeholder: "deal-scoring",
|
|
122
|
+
validate: isId,
|
|
123
|
+
});
|
|
124
|
+
const version = await p.text({
|
|
125
|
+
name: "version",
|
|
126
|
+
message: "Version?",
|
|
127
|
+
initial: prefill.version ?? "0.1.0",
|
|
128
|
+
validate: isSemver,
|
|
129
|
+
});
|
|
130
|
+
const iframeOrigin = await p.text({
|
|
131
|
+
name: "origin",
|
|
132
|
+
message: "Origin it's served from?",
|
|
133
|
+
placeholder: "https://deal-scoring.example.com",
|
|
134
|
+
validate: isHttpsOrigin,
|
|
135
|
+
});
|
|
136
|
+
const allowedObjectTypes = await askObjectTypes(p);
|
|
137
|
+
const languages = await askLanguages(ctx);
|
|
138
|
+
const names = [];
|
|
139
|
+
const descriptions = [];
|
|
140
|
+
for (const lang of languages) {
|
|
141
|
+
const english = lang === REQUIRED_LOCALE;
|
|
142
|
+
names.push([
|
|
143
|
+
lang,
|
|
144
|
+
await p.text({
|
|
145
|
+
name: `name-${lang}`,
|
|
146
|
+
message: `Name, in ${LOCALE_LABELS[lang]}?`,
|
|
147
|
+
initial: english ? prefill.name : undefined,
|
|
148
|
+
optional: !english,
|
|
149
|
+
}),
|
|
150
|
+
]);
|
|
151
|
+
descriptions.push([
|
|
152
|
+
lang,
|
|
153
|
+
await p.text({
|
|
154
|
+
name: `description-${lang}`,
|
|
155
|
+
message: `Catalog card text, in ${LOCALE_LABELS[lang]}? (Markdown, no links)`,
|
|
156
|
+
initial: english ? prefill.description : undefined,
|
|
157
|
+
optional: true,
|
|
158
|
+
}),
|
|
159
|
+
]);
|
|
160
|
+
}
|
|
161
|
+
const categories = await askCategories(p);
|
|
162
|
+
const iconUrl = await p.text({
|
|
163
|
+
name: "icon-url",
|
|
164
|
+
message: "Icon URL (.svg, optional)?",
|
|
165
|
+
optional: true,
|
|
166
|
+
validate: isSvgUrl,
|
|
167
|
+
});
|
|
168
|
+
const illustrationUrl = await p.text({
|
|
169
|
+
name: "illustration-url",
|
|
170
|
+
message: "Illustration URL (.svg, optional)?",
|
|
171
|
+
optional: true,
|
|
172
|
+
validate: isSvgUrl,
|
|
173
|
+
});
|
|
174
|
+
const accentColor = await p.text({
|
|
175
|
+
name: "accent-color",
|
|
176
|
+
message: "Accent colour (optional)?",
|
|
177
|
+
optional: true,
|
|
178
|
+
validate: isHexColor,
|
|
179
|
+
});
|
|
180
|
+
const infoUrl = await p.text({
|
|
181
|
+
name: "info-url",
|
|
182
|
+
message: "Info page URL (optional)?",
|
|
183
|
+
initial: prefill.infoUrl,
|
|
184
|
+
optional: true,
|
|
185
|
+
validate: isHttpsUrl,
|
|
186
|
+
});
|
|
187
|
+
const hasSecrets = await p.confirm({
|
|
188
|
+
name: "secrets",
|
|
189
|
+
message: "Does its config form have Secret Fields (API tokens and the like)?",
|
|
190
|
+
initial: typeof ctx.flags["secret-keys"] === "string",
|
|
191
|
+
});
|
|
192
|
+
const secretKeys = hasSecrets
|
|
193
|
+
? splitList((await p.text({
|
|
194
|
+
name: "secret-keys",
|
|
195
|
+
message: "The Secret Fields' keys, comma-separated?",
|
|
196
|
+
placeholder: "apiToken",
|
|
197
|
+
validate: isKeyList,
|
|
198
|
+
})) ?? "")
|
|
199
|
+
: undefined;
|
|
200
|
+
const wantsKeys = await p.confirm({
|
|
201
|
+
name: "keys",
|
|
202
|
+
message: hasSecrets
|
|
203
|
+
? "Create its key pairs now (signing + encryption)?"
|
|
204
|
+
: "Create a signing key for its backend now?",
|
|
205
|
+
initial: hasSecrets,
|
|
206
|
+
});
|
|
207
|
+
p.assertComplete();
|
|
208
|
+
const manifest = {
|
|
209
|
+
id: id ?? "",
|
|
210
|
+
version: version ?? "",
|
|
211
|
+
type: "iframe",
|
|
212
|
+
iframeOrigin: iframeOrigin ?? "",
|
|
213
|
+
allowedObjectTypes,
|
|
214
|
+
name: asText(names) ?? {},
|
|
215
|
+
description: asText(descriptions),
|
|
216
|
+
categories,
|
|
217
|
+
iconUrl,
|
|
218
|
+
illustrationUrl,
|
|
219
|
+
accentColor,
|
|
220
|
+
infoUrl,
|
|
221
|
+
secretKeys,
|
|
222
|
+
};
|
|
223
|
+
const keys = wantsKeys
|
|
224
|
+
? await createKeys(ctx, manifest, hasSecrets ? ["sig", "enc"] : ["sig"])
|
|
225
|
+
: [];
|
|
226
|
+
requirePasses(ctx, manifest);
|
|
227
|
+
// Private keys first: if one can't be written, no manifest names a key that isn't on disk.
|
|
228
|
+
await saveKeys(ctx, keys);
|
|
229
|
+
await writeManifest(ctx.dir, manifest, { create: true });
|
|
230
|
+
ctx.out.success(`Wrote ${MANIFEST_FILE}.`);
|
|
231
|
+
ctx.out.info(`Its client id is ${clientIdOf(manifest.id)}: what your backend checks a plugin token's "aud" against.`);
|
|
232
|
+
ctx.out.end('Next: write its "details" (the details view, Markdown) in the file, and run `manifest check` before each release.');
|
|
233
|
+
ctx.out.result({
|
|
234
|
+
manifest: MANIFEST_FILE,
|
|
235
|
+
clientId: clientIdOf(manifest.id),
|
|
236
|
+
keys: keys.map((k) => k.publicJwk.kid),
|
|
237
|
+
});
|
|
238
|
+
}
|
|
239
|
+
/** What `manifest set <field>` can change, and how. */
|
|
240
|
+
const SETTERS = {
|
|
241
|
+
version: async (p, m) => {
|
|
242
|
+
m.version =
|
|
243
|
+
(await p.text({
|
|
244
|
+
name: "version",
|
|
245
|
+
message: "Version?",
|
|
246
|
+
initial: m.version,
|
|
247
|
+
validate: isSemver,
|
|
248
|
+
})) ?? m.version;
|
|
249
|
+
},
|
|
250
|
+
origin: async (p, m) => {
|
|
251
|
+
m.iframeOrigin =
|
|
252
|
+
(await p.text({
|
|
253
|
+
name: "origin",
|
|
254
|
+
message: "Origin?",
|
|
255
|
+
initial: m.iframeOrigin,
|
|
256
|
+
validate: isHttpsOrigin,
|
|
257
|
+
})) ?? m.iframeOrigin;
|
|
258
|
+
},
|
|
259
|
+
"object-types": async (p, m) => {
|
|
260
|
+
m.allowedObjectTypes = await askObjectTypes(p, m.allowedObjectTypes ?? [ANY]);
|
|
261
|
+
},
|
|
262
|
+
categories: async (p, m) => {
|
|
263
|
+
m.categories = await askCategories(p, m.categories);
|
|
264
|
+
},
|
|
265
|
+
"icon-url": async (p, m) => {
|
|
266
|
+
m.iconUrl = await p.text({
|
|
267
|
+
name: "icon-url",
|
|
268
|
+
message: "Icon URL?",
|
|
269
|
+
initial: m.iconUrl,
|
|
270
|
+
optional: true,
|
|
271
|
+
validate: isSvgUrl,
|
|
272
|
+
});
|
|
273
|
+
},
|
|
274
|
+
"illustration-url": async (p, m) => {
|
|
275
|
+
m.illustrationUrl = await p.text({
|
|
276
|
+
name: "illustration-url",
|
|
277
|
+
message: "Illustration URL?",
|
|
278
|
+
initial: m.illustrationUrl,
|
|
279
|
+
optional: true,
|
|
280
|
+
validate: isSvgUrl,
|
|
281
|
+
});
|
|
282
|
+
},
|
|
283
|
+
"accent-color": async (p, m) => {
|
|
284
|
+
m.accentColor = await p.text({
|
|
285
|
+
name: "accent-color",
|
|
286
|
+
message: "Accent colour?",
|
|
287
|
+
initial: m.accentColor,
|
|
288
|
+
optional: true,
|
|
289
|
+
validate: isHexColor,
|
|
290
|
+
});
|
|
291
|
+
},
|
|
292
|
+
"info-url": async (p, m) => {
|
|
293
|
+
m.infoUrl = await p.text({
|
|
294
|
+
name: "info-url",
|
|
295
|
+
message: "Info page URL?",
|
|
296
|
+
initial: m.infoUrl,
|
|
297
|
+
optional: true,
|
|
298
|
+
validate: isHttpsUrl,
|
|
299
|
+
});
|
|
300
|
+
},
|
|
301
|
+
"additional-images": async (p, m) => {
|
|
302
|
+
const images = await p.text({
|
|
303
|
+
name: "additional-images",
|
|
304
|
+
message: "Screenshot URLs, comma-separated?",
|
|
305
|
+
initial: m.additionalImages?.join(", "),
|
|
306
|
+
optional: true,
|
|
307
|
+
});
|
|
308
|
+
m.additionalImages = images === undefined ? undefined : splitList(images);
|
|
309
|
+
},
|
|
310
|
+
"secret-keys": async (p, m) => {
|
|
311
|
+
const keys = await p.text({
|
|
312
|
+
name: "secret-keys",
|
|
313
|
+
message: "Secret Fields' keys, comma-separated?",
|
|
314
|
+
initial: m.secretKeys?.join(", "),
|
|
315
|
+
optional: true,
|
|
316
|
+
validate: isKeyList,
|
|
317
|
+
});
|
|
318
|
+
m.secretKeys = keys === undefined ? undefined : splitList(keys);
|
|
319
|
+
},
|
|
320
|
+
...Object.fromEntries(LOCALES.flatMap((lang) => ["name", "description", "details"].map((field) => [
|
|
321
|
+
`${field}-${lang}`,
|
|
322
|
+
async (p, m) => {
|
|
323
|
+
const current = m[field]?.[lang];
|
|
324
|
+
const value = await p.text({
|
|
325
|
+
name: `${field}-${lang}`,
|
|
326
|
+
message: `${field}, in ${LOCALE_LABELS[lang]}?`,
|
|
327
|
+
initial: current,
|
|
328
|
+
optional: true,
|
|
329
|
+
});
|
|
330
|
+
const text = { ...(m[field] ?? {}) };
|
|
331
|
+
if (value === undefined) {
|
|
332
|
+
delete text[lang];
|
|
333
|
+
}
|
|
334
|
+
else {
|
|
335
|
+
text[lang] = value;
|
|
336
|
+
}
|
|
337
|
+
m[field] = (Object.keys(text).length > 0 ? text : undefined);
|
|
338
|
+
},
|
|
339
|
+
]))),
|
|
340
|
+
};
|
|
341
|
+
export async function manifestSet(ctx, field) {
|
|
342
|
+
if (field === "id") {
|
|
343
|
+
throw new UsageError('"id" is the catalog key: a new id is a new plugin. Start a new manifest for it instead.');
|
|
344
|
+
}
|
|
345
|
+
const setter = field === undefined ? undefined : SETTERS[field];
|
|
346
|
+
if (setter === undefined) {
|
|
347
|
+
throw new UsageError(`manifest set <field> [value] — <field> is one of: ${Object.keys(SETTERS).join(", ")}`);
|
|
348
|
+
}
|
|
349
|
+
const manifest = await loadManifest(ctx);
|
|
350
|
+
await setter(ctx.prompter, manifest);
|
|
351
|
+
ctx.prompter.assertComplete();
|
|
352
|
+
requirePasses(ctx, manifest);
|
|
353
|
+
await writeManifest(ctx.dir, manifest, { create: false });
|
|
354
|
+
ctx.out.success(`Updated ${field} in ${MANIFEST_FILE}.`);
|
|
355
|
+
ctx.out.result({ manifest: MANIFEST_FILE, field });
|
|
356
|
+
}
|
|
357
|
+
/** 0 when the manifest passes, 1 when it fails or is missing. */
|
|
358
|
+
export async function manifestCheck(ctx) {
|
|
359
|
+
const text = await readManifestText(ctx.dir);
|
|
360
|
+
if (text === undefined) {
|
|
361
|
+
const failure = `no ${MANIFEST_FILE} here — create one with \`manifest init\``;
|
|
362
|
+
ctx.out.warn(failure);
|
|
363
|
+
ctx.out.result({ ok: false, failures: [failure], warnings: [] });
|
|
364
|
+
return 1;
|
|
365
|
+
}
|
|
366
|
+
const { failures, warnings } = checkManifest(text);
|
|
367
|
+
for (const failure of failures) {
|
|
368
|
+
ctx.out.warn(`✗ ${failure}`);
|
|
369
|
+
}
|
|
370
|
+
for (const warning of warnings) {
|
|
371
|
+
ctx.out.warn(warning);
|
|
372
|
+
}
|
|
373
|
+
if (failures.length === 0) {
|
|
374
|
+
ctx.out.success(`${MANIFEST_FILE} passes${warnings.length > 0 ? ", with warnings" : ""}.`);
|
|
375
|
+
}
|
|
376
|
+
ctx.out.result({ ok: failures.length === 0, failures, warnings });
|
|
377
|
+
return failures.length === 0 ? 0 : 1;
|
|
378
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Where private keys go: `keys/<kid>.pem` in the project, the directory 0700, each file 0600,
|
|
3
|
+
* never overwritten, and `keys/` in `.gitignore`. Nothing here prints a key.
|
|
4
|
+
*/
|
|
5
|
+
import { mkdir, readFile, writeFile } from "node:fs/promises";
|
|
6
|
+
import { join } from "node:path";
|
|
7
|
+
export const KEYS_DIR = "keys";
|
|
8
|
+
const SAFE_KID = /^[A-Za-z0-9][A-Za-z0-9._-]*$/;
|
|
9
|
+
export async function writePrivateKey(dir, kid, pem) {
|
|
10
|
+
if (!SAFE_KID.test(kid)) {
|
|
11
|
+
throw new Error(`the kid "${kid}" can't be a file name`);
|
|
12
|
+
}
|
|
13
|
+
await mkdir(join(dir, KEYS_DIR), { recursive: true, mode: 0o700 });
|
|
14
|
+
const path = join(dir, KEYS_DIR, `${kid}.pem`);
|
|
15
|
+
try {
|
|
16
|
+
await writeFile(path, pem, { flag: "wx", mode: 0o600 });
|
|
17
|
+
}
|
|
18
|
+
catch (error) {
|
|
19
|
+
if (error.code === "EEXIST") {
|
|
20
|
+
throw new Error(`${path} already exists — a private key is never overwritten`);
|
|
21
|
+
}
|
|
22
|
+
throw error;
|
|
23
|
+
}
|
|
24
|
+
return path;
|
|
25
|
+
}
|
|
26
|
+
/** Adds `keys/` to the project's `.gitignore`. True if it had to. */
|
|
27
|
+
export async function ensureGitignored(dir) {
|
|
28
|
+
const path = join(dir, ".gitignore");
|
|
29
|
+
let text = "";
|
|
30
|
+
try {
|
|
31
|
+
text = await readFile(path, "utf8");
|
|
32
|
+
}
|
|
33
|
+
catch (error) {
|
|
34
|
+
if (error.code !== "ENOENT") {
|
|
35
|
+
throw error;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
const covered = text
|
|
39
|
+
.split(/\r?\n/)
|
|
40
|
+
.map((line) => line.trim().replace(/^\//, "").replace(/\/$/, ""))
|
|
41
|
+
.includes(KEYS_DIR);
|
|
42
|
+
if (covered) {
|
|
43
|
+
return false;
|
|
44
|
+
}
|
|
45
|
+
const separator = text === "" || text.endsWith("\n") ? "" : "\n";
|
|
46
|
+
await writeFile(path, `${text}${separator}${KEYS_DIR}/\n`);
|
|
47
|
+
return true;
|
|
48
|
+
}
|
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* RSA key pairs from Web Crypto: Node's `crypto.subtle`, the same API a browser has, so no crypto
|
|
3
|
+
* dependency. The public half comes back as the JWK the manifest lists; the private half as a
|
|
4
|
+
* PKCS#8 PEM, the format the SDK's backend.md has authors keep (`openssl genpkey` makes the same).
|
|
5
|
+
*/
|
|
6
|
+
import { KEY_ALG, MIN_RSA_BITS, } from "../manifest/schema.js";
|
|
7
|
+
const ALGORITHMS = {
|
|
8
|
+
sig: {
|
|
9
|
+
name: "RSASSA-PKCS1-v1_5",
|
|
10
|
+
hash: "SHA-256",
|
|
11
|
+
usages: ["sign", "verify"],
|
|
12
|
+
},
|
|
13
|
+
enc: { name: "RSA-OAEP", hash: "SHA-256", usages: ["encrypt", "decrypt"] },
|
|
14
|
+
};
|
|
15
|
+
const toPem = (der) => {
|
|
16
|
+
const lines = Buffer.from(der)
|
|
17
|
+
.toString("base64")
|
|
18
|
+
.match(/.{1,64}/g) ?? [];
|
|
19
|
+
return `-----BEGIN PRIVATE KEY-----\n${lines.join("\n")}\n-----END PRIVATE KEY-----\n`;
|
|
20
|
+
};
|
|
21
|
+
export async function generateKeyPair(use, kid, bits = MIN_RSA_BITS) {
|
|
22
|
+
if (bits < MIN_RSA_BITS) {
|
|
23
|
+
throw new Error(`RSA keys need ${MIN_RSA_BITS} bits or more, not ${bits}`);
|
|
24
|
+
}
|
|
25
|
+
const { name, hash, usages } = ALGORITHMS[use];
|
|
26
|
+
const pair = await crypto.subtle.generateKey({
|
|
27
|
+
name,
|
|
28
|
+
hash,
|
|
29
|
+
modulusLength: bits,
|
|
30
|
+
publicExponent: new Uint8Array([1, 0, 1]),
|
|
31
|
+
}, true, [...usages]);
|
|
32
|
+
const jwk = await crypto.subtle.exportKey("jwk", pair.publicKey);
|
|
33
|
+
if (jwk.n === undefined || jwk.e === undefined) {
|
|
34
|
+
throw new Error("Web Crypto returned an RSA key without n or e");
|
|
35
|
+
}
|
|
36
|
+
const privatePem = toPem(await crypto.subtle.exportKey("pkcs8", pair.privateKey));
|
|
37
|
+
// Built field by field, never spread from the export: nothing but these can reach the manifest.
|
|
38
|
+
return {
|
|
39
|
+
publicJwk: { kty: "RSA", kid, use, alg: KEY_ALG[use], n: jwk.n, e: jwk.e },
|
|
40
|
+
privatePem,
|
|
41
|
+
};
|
|
42
|
+
}
|
|
43
|
+
/** The private key back from its PEM, for the one use it was made for. */
|
|
44
|
+
export async function importPrivatePem(pem, use) {
|
|
45
|
+
const der = Buffer.from(pem.replace(/-----(BEGIN|END) PRIVATE KEY-----|\s/g, ""), "base64");
|
|
46
|
+
const { name, hash } = ALGORITHMS[use];
|
|
47
|
+
return crypto.subtle.importKey("pkcs8", der, { name, hash }, false, [
|
|
48
|
+
use === "sig" ? "sign" : "decrypt",
|
|
49
|
+
]);
|
|
50
|
+
}
|
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The manifest's `publicKeys`, kept to the rotation rules (ls-fe plugin-authorization.md §3–§4, and
|
|
3
|
+
* the SDK's backend.md → "Rotating a key"): at most two keys per use, so either can be rotated
|
|
4
|
+
* across two releases, and encryption keys newest first, because the browser encrypts with the
|
|
5
|
+
* first one. Pure: these functions return new sets and never touch the one they're given.
|
|
6
|
+
*/
|
|
7
|
+
import { MAX_KEYS_PER_USE, } from "../manifest/schema.js";
|
|
8
|
+
/** `sig-2026-10`, or `sig-2026-10-2` and on when that one is taken. */
|
|
9
|
+
export function nextKid(use, now, existing) {
|
|
10
|
+
const month = `${now.getUTCFullYear()}-${String(now.getUTCMonth() + 1).padStart(2, "0")}`;
|
|
11
|
+
const base = `${use}-${month}`;
|
|
12
|
+
if (!existing.includes(base)) {
|
|
13
|
+
return base;
|
|
14
|
+
}
|
|
15
|
+
let n = 2;
|
|
16
|
+
while (existing.includes(`${base}-${n}`)) {
|
|
17
|
+
n++;
|
|
18
|
+
}
|
|
19
|
+
return `${base}-${n}`;
|
|
20
|
+
}
|
|
21
|
+
export const keysOfUse = (set, use) => (set?.keys ?? []).filter((key) => key.use === use);
|
|
22
|
+
/**
|
|
23
|
+
* The key a rotation would replace: the last encryption key (they're listed newest first), or the
|
|
24
|
+
* first signing key (new ones are added after it).
|
|
25
|
+
*/
|
|
26
|
+
export const oldestOfUse = (set, use) => {
|
|
27
|
+
const keys = keysOfUse(set, use);
|
|
28
|
+
return use === "enc" ? keys.at(-1) : keys[0];
|
|
29
|
+
};
|
|
30
|
+
export function addKey(set, key) {
|
|
31
|
+
const keys = [...(set?.keys ?? [])];
|
|
32
|
+
if (keys.some((k) => k.kid === key.kid)) {
|
|
33
|
+
throw new Error(`the kid "${key.kid}" is already in "publicKeys" — every key needs its own`);
|
|
34
|
+
}
|
|
35
|
+
if (keysOfUse(set, key.use).length >= MAX_KEYS_PER_USE) {
|
|
36
|
+
const oldest = oldestOfUse(set, key.use);
|
|
37
|
+
throw new Error(`"publicKeys" holds at most ${MAX_KEYS_PER_USE} "${key.use}" keys — retire the oldest first: keys retire ${oldest?.kid}`);
|
|
38
|
+
}
|
|
39
|
+
return { keys: key.use === "enc" ? [key, ...keys] : [...keys, key] };
|
|
40
|
+
}
|
|
41
|
+
export function retireKey(set, kid) {
|
|
42
|
+
const keys = set?.keys ?? [];
|
|
43
|
+
const retired = keys.find((key) => key.kid === kid);
|
|
44
|
+
if (retired === undefined) {
|
|
45
|
+
throw new Error(`no key "${kid}" in "publicKeys" (it has ${keys.map((k) => k.kid).join(", ") || "none"})`);
|
|
46
|
+
}
|
|
47
|
+
return { set: { keys: keys.filter((key) => key !== retired) }, retired };
|
|
48
|
+
}
|