@livespace/plugin-cli 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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Livespace S.A.
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/README.md CHANGED
@@ -1,3 +1,70 @@
1
- # Temporary Holding Version
1
+ # @livespace/plugin-cli
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Sets up a Livespace plugin's catalog manifest, `plugin-manifest.json`, its key pairs included.
4
+
5
+ ```sh
6
+ npx @livespace/plugin-cli manifest init
7
+ ```
8
+
9
+ In a terminal, it asks for each field. Fields with a fixed set of values are pickers, and defaults
10
+ come from the project's `package.json` when there is one. It checks the manifest the way the
11
+ catalog will before writing anything.
12
+
13
+ ## Commands
14
+
15
+ | Command | What it does |
16
+ |---|---|
17
+ | `manifest init` | Create `plugin-manifest.json`, and optionally the key pairs. Never overwrites a manifest: its `id` is the catalog key. |
18
+ | `manifest set <field> [value]` | Change one field: `version`, `origin`, `object-types`, `name-<lang>`, `description-<lang>`, `details-<lang>`, `categories`, `icon-url`, `illustration-url`, `accent-color`, `info-url`, `additional-images`, `secret-keys`. |
19
+ | `manifest check` | Check the manifest the way the catalog will. Exits 1 on a failure; warnings don't fail. |
20
+ | `keys init [--use sig\|enc\|both]` | Create the key pairs: a signing key, plus an encryption key when the manifest has `secretKeys`. |
21
+ | `keys rotate --use sig\|enc` | Add a key for a rotation. At most two of each; a new encryption key goes first, as the browser encrypts with the first. |
22
+ | `keys retire <kid>` | Remove a key from the manifest. The private half stays on disk until you destroy it. |
23
+ | `keys jwks [--out <path>]` | Write `.well-known/livespace/jwks.json` from the keys, for a plugin that's also installed by URL. |
24
+ | `client-id` | Print `plugin:<id>`, what your backend checks a plugin token's `aud` against. |
25
+
26
+ ## Keys
27
+
28
+ Your backend needs two RSA key pairs, and Livespace only ever holds their public halves:
29
+
30
+ - a **signing** key (RS256) proves requests come from your backend;
31
+ - an **encryption** key (RSA-OAEP-256) is what an admin's browser encrypts your plugin's secrets
32
+ with, so only your backend can read them.
33
+
34
+ The public halves go into the manifest's `publicKeys`. The private halves go to
35
+ `keys/<kid>.pem` (PKCS#8): the directory is mode `0700`, each file `0600`, and they're never
36
+ overwritten. `keys/` is added to `.gitignore`. Nothing is printed, and nothing goes over the
37
+ network. Move the private keys into your backend's secret storage, and back up the encryption key:
38
+ if it's lost, every customer has to re-enter their secrets.
39
+
40
+ Keys are generated with Web Crypto (`crypto.subtle`), built into Node, so there's no crypto
41
+ dependency.
42
+
43
+ ## Without a terminal
44
+
45
+ For scripts, CI and coding agents, every answer has a flag:
46
+
47
+ ```sh
48
+ npx @livespace/plugin-cli manifest init --yes --json \
49
+ --origin https://deal-scoring.example.com \
50
+ --object-types deal,company \
51
+ --name-en "Deal scoring" --name-pl "Scoring szans" \
52
+ --categories "Deal,Analytics and insights" \
53
+ --secrets --secret-keys apiToken \
54
+ --keys
55
+ ```
56
+
57
+ - `--yes` takes the defaults (`package.json`'s name and version among them).
58
+ - `--json` prints only a JSON result.
59
+ - `--object-types any` means no requirements: any type, the apps menu included.
60
+
61
+ Without a terminal, a missing answer is never waited for: the command exits 1 and lists every flag
62
+ it still needs. See `--help` for them all.
63
+
64
+ ## Requirements
65
+
66
+ Node 20.12 or later.
67
+
68
+ ## License
69
+
70
+ MIT © Livespace S.A.
package/dist/cli.js ADDED
@@ -0,0 +1,182 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * livespace-plugin: sets up a Livespace plugin's catalog manifest, its key pairs included.
4
+ *
5
+ * Interactive in a terminal. Without one (an agent, CI), every answer comes from a flag, and a
6
+ * missing one is an error that lists them all; it never waits on input. See `--help`.
7
+ */
8
+ import { readFileSync } from "node:fs";
9
+ import { resolve } from "node:path";
10
+ import { parseArgs } from "node:util";
11
+ import { clientId } from "./commands/client-id.js";
12
+ import { UsageError } from "./commands/context.js";
13
+ import { keysInit, keysJwks, keysRetire, keysRotate } from "./commands/keys.js";
14
+ import { manifestCheck, manifestInit, manifestSet, } from "./commands/manifest.js";
15
+ import { LOCALES } from "./manifest/schema.js";
16
+ import { Cancelled, clackBackend } from "./ui/clack.js";
17
+ import { clackOutput, jsonOutput, plainOutput } from "./ui/output.js";
18
+ import { MissingAnswers, createPrompter } from "./ui/prompter.js";
19
+ const { version: CLI_VERSION } = JSON.parse(readFileSync(new URL("../package.json", import.meta.url), "utf8"));
20
+ const TEXT_FLAGS = LOCALES.flatMap((lang) => ["name", "description", "details"].map((field) => `${field}-${lang}`));
21
+ const STRING_FLAGS = [
22
+ "dir",
23
+ "id",
24
+ "version",
25
+ "origin",
26
+ "object-types",
27
+ "languages",
28
+ "categories",
29
+ "other-categories",
30
+ "icon-url",
31
+ "illustration-url",
32
+ "accent-color",
33
+ "info-url",
34
+ "additional-images",
35
+ "secret-keys",
36
+ "use",
37
+ "bits",
38
+ "out",
39
+ ...TEXT_FLAGS,
40
+ ];
41
+ const BOOLEAN_FLAGS = [
42
+ "yes",
43
+ "json",
44
+ "help",
45
+ "secrets",
46
+ "no-secrets",
47
+ "keys",
48
+ "no-keys",
49
+ ];
50
+ const HELP = `livespace-plugin ${CLI_VERSION} — set up a Livespace plugin's catalog manifest
51
+
52
+ Usage: npx @livespace/plugin-cli <command> [flags]
53
+
54
+ Commands:
55
+ manifest init Create plugin-manifest.json, asking for each field.
56
+ Defaults come from package.json when there is one.
57
+ manifest set <field> [value]
58
+ Change one field (version, origin, object-types,
59
+ name-<lang>, description-<lang>, details-<lang>,
60
+ categories, icon-url, illustration-url, accent-color,
61
+ info-url, additional-images, secret-keys).
62
+ manifest check Check the manifest the way the catalog will. Exit 1 on
63
+ a failure.
64
+ keys init [--use sig|enc|both]
65
+ Create the key pairs: a signing key, and an encryption
66
+ key when there are secretKeys. Private halves go to
67
+ keys/<kid>.pem (0600, gitignored); never printed.
68
+ keys rotate --use sig|enc
69
+ Add a key for a rotation (at most two per use).
70
+ keys retire <kid> Remove a key from the manifest.
71
+ keys jwks [--out <path>] Write .well-known/livespace/jwks.json from the keys, for
72
+ a plugin that's also installed by URL.
73
+ client-id Print plugin:<id>, what the backend checks "aud" against.
74
+
75
+ Answers as flags (for scripts and agents; without a terminal, a missing one is an error):
76
+ --id, --version, --origin, --object-types deal,company|any, --languages en,pl,
77
+ --name-<lang>, --description-<lang>, --categories "Deal,Finance",
78
+ --icon-url, --illustration-url, --accent-color, --info-url,
79
+ --secrets | --no-secrets, --secret-keys apiToken,webhookSecret,
80
+ --keys | --no-keys, --bits 2048 (<lang>: ${LOCALES.join(", ")})
81
+
82
+ Other flags:
83
+ --dir <path> The plugin project (default: the current directory).
84
+ --yes, -y Take the defaults instead of asking.
85
+ --json Print only a JSON result.
86
+ --help, -h This text.
87
+ `;
88
+ async function run(argv) {
89
+ const { values, positionals } = parseArgs({
90
+ args: argv,
91
+ allowPositionals: true,
92
+ options: {
93
+ ...Object.fromEntries(STRING_FLAGS.map((name) => [name, { type: "string" }])),
94
+ ...Object.fromEntries(BOOLEAN_FLAGS.map((name) => [name, { type: "boolean" }])),
95
+ yes: { type: "boolean", short: "y" },
96
+ help: { type: "boolean", short: "h" },
97
+ },
98
+ });
99
+ const flags = values;
100
+ const [group, command, arg, value] = positionals;
101
+ if (flags.help || group === undefined || group === "help") {
102
+ console.log(HELP);
103
+ return 0;
104
+ }
105
+ // `manifest set <field> <value>` is the same as `manifest set <field> --<field> <value>`.
106
+ if (group === "manifest" &&
107
+ command === "set" &&
108
+ arg !== undefined &&
109
+ value !== undefined) {
110
+ flags[arg] = value;
111
+ }
112
+ const json = flags.json === true;
113
+ const yes = flags.yes === true;
114
+ const interactive = !yes &&
115
+ !json &&
116
+ process.stdin.isTTY === true &&
117
+ process.stdout.isTTY === true;
118
+ const ctx = {
119
+ dir: resolve(typeof flags.dir === "string" ? flags.dir : process.cwd()),
120
+ now: new Date(),
121
+ flags,
122
+ interactive,
123
+ out: json ? jsonOutput : interactive ? clackOutput : plainOutput,
124
+ prompter: createPrompter({
125
+ flags,
126
+ yes,
127
+ backend: interactive ? clackBackend : undefined,
128
+ }),
129
+ };
130
+ switch (`${group} ${command ?? ""}`.trim()) {
131
+ case "manifest init":
132
+ await manifestInit(ctx);
133
+ return 0;
134
+ case "manifest set":
135
+ await manifestSet(ctx, arg);
136
+ return 0;
137
+ case "manifest check":
138
+ return manifestCheck(ctx);
139
+ case "keys init":
140
+ await keysInit(ctx);
141
+ return 0;
142
+ case "keys rotate":
143
+ await keysRotate(ctx);
144
+ return 0;
145
+ case "keys retire":
146
+ await keysRetire(ctx, arg);
147
+ return 0;
148
+ case "keys jwks":
149
+ await keysJwks(ctx);
150
+ return 0;
151
+ case "client-id":
152
+ await clientId(ctx);
153
+ return 0;
154
+ default:
155
+ throw new UsageError(`unknown command "${positionals.join(" ")}" — see --help`);
156
+ }
157
+ }
158
+ const fail = (message) => {
159
+ if (process.argv.includes("--json")) {
160
+ console.log(JSON.stringify({ error: message }, null, 2));
161
+ }
162
+ else {
163
+ console.error(message);
164
+ }
165
+ };
166
+ run(process.argv.slice(2)).then((code) => {
167
+ process.exitCode = code;
168
+ }, (error) => {
169
+ if (error instanceof Cancelled) {
170
+ process.exitCode = 130;
171
+ return;
172
+ }
173
+ const known = error instanceof UsageError || error instanceof MissingAnswers;
174
+ const parse = error.code?.startsWith("ERR_PARSE_ARGS");
175
+ fail(known || parse
176
+ ? error.message
177
+ : `Unexpected error: ${error.stack ?? error}`);
178
+ if (parse) {
179
+ console.error("See --help.");
180
+ }
181
+ process.exitCode = 1;
182
+ });
@@ -0,0 +1,12 @@
1
+ import { ID_PATTERN, clientIdOf } from "../manifest/schema.js";
2
+ import { UsageError } from "./context.js";
3
+ import { loadManifest } from "./load.js";
4
+ /** Prints `plugin:<id>`: what a plugin token's `aud` carries, and what the backend checks. */
5
+ export async function clientId(ctx) {
6
+ const { id } = await loadManifest(ctx);
7
+ if (typeof id !== "string" || !ID_PATTERN.test(id)) {
8
+ throw new UsageError('the manifest has no valid "id" — `manifest check` says why');
9
+ }
10
+ ctx.out.info(clientIdOf(id));
11
+ ctx.out.result({ clientId: clientIdOf(id) });
12
+ }
@@ -0,0 +1,7 @@
1
+ /** A failure worth one plain message, no stack trace. */
2
+ export class UsageError extends Error {
3
+ constructor(message) {
4
+ super(message);
5
+ this.name = "UsageError";
6
+ }
7
+ }
@@ -0,0 +1,152 @@
1
+ /** `keys init`, `keys rotate`, `keys retire` and `keys jwks`. Never prints key material. */
2
+ import { mkdir, writeFile } from "node:fs/promises";
3
+ import { dirname, join, relative } from "node:path";
4
+ import { KEYS_DIR, ensureGitignored, writePrivateKey } from "../keys/files.js";
5
+ import { generateKeyPair } from "../keys/generate.js";
6
+ import { addKey, keysOfUse, nextKid, retireKey } from "../keys/keyset.js";
7
+ import { checkManifest } from "../manifest/check.js";
8
+ import { serializeManifest, writeManifest } from "../manifest/file.js";
9
+ import { KEY_USES, MANIFEST_FILE, MIN_RSA_BITS, } from "../manifest/schema.js";
10
+ import { UsageError } from "./context.js";
11
+ import { loadManifest } from "./load.js";
12
+ const JWKS_PATH = ".well-known/livespace/jwks.json";
13
+ const bitsOf = (ctx) => {
14
+ const raw = ctx.flags.bits;
15
+ if (raw === undefined) {
16
+ return MIN_RSA_BITS;
17
+ }
18
+ const bits = Number(raw);
19
+ if (!Number.isInteger(bits) || bits < MIN_RSA_BITS) {
20
+ throw new UsageError(`--bits must be ${MIN_RSA_BITS} or more`);
21
+ }
22
+ return bits;
23
+ };
24
+ /**
25
+ * New key pairs for `uses`, added to the manifest's `publicKeys` (in memory). Nothing is written:
26
+ * the caller saves the private halves with `saveKeys`, then the manifest.
27
+ */
28
+ export async function createKeys(ctx, manifest, uses) {
29
+ const bits = bitsOf(ctx);
30
+ const pairs = [];
31
+ for (const use of uses) {
32
+ const kids = (manifest.publicKeys?.keys ?? []).map((k) => k.kid);
33
+ const pair = await generateKeyPair(use, nextKid(use, ctx.now, kids), bits);
34
+ manifest.publicKeys = addKey(manifest.publicKeys, pair.publicJwk);
35
+ pairs.push(pair);
36
+ }
37
+ return pairs;
38
+ }
39
+ /** Writes each private half to keys/<kid>.pem (0600) and keeps keys/ out of git. */
40
+ export async function saveKeys(ctx, pairs) {
41
+ if (pairs.length === 0) {
42
+ return;
43
+ }
44
+ for (const { publicJwk, privatePem } of pairs) {
45
+ const path = await writePrivateKey(ctx.dir, publicJwk.kid, privatePem);
46
+ ctx.out.success(`${publicJwk.use === "sig" ? "Signing" : "Encryption"} key ${publicJwk.kid}: private half in ${relative(ctx.dir, path)}`);
47
+ }
48
+ if (await ensureGitignored(ctx.dir)) {
49
+ ctx.out.info(`Added ${KEYS_DIR}/ to .gitignore.`);
50
+ }
51
+ ctx.out.warn(`Move the private keys into your backend's secret storage, and back up the encryption key: if it's lost, every customer has to re-enter their secrets. Never commit ${KEYS_DIR}/.`);
52
+ }
53
+ /** After a key change: what still fails the checker is reported, but doesn't block the change. */
54
+ async function saveManifest(ctx, manifest) {
55
+ await writeManifest(ctx.dir, manifest, { create: false });
56
+ const { failures } = checkManifest(serializeManifest(manifest));
57
+ for (const failure of failures) {
58
+ ctx.out.warn(`${MANIFEST_FILE} still fails: ${failure}`);
59
+ }
60
+ }
61
+ /** `--use sig|enc|both`; by default a signing key, plus an encryption key if there are secrets. */
62
+ function usesFor(ctx, manifest) {
63
+ const requested = ctx.flags.use;
64
+ if (requested === undefined) {
65
+ return (manifest.secretKeys?.length ?? 0) > 0 ? ["sig", "enc"] : ["sig"];
66
+ }
67
+ if (requested === "both") {
68
+ return ["sig", "enc"];
69
+ }
70
+ if (KEY_USES.includes(requested)) {
71
+ return [requested];
72
+ }
73
+ throw new UsageError("--use is sig, enc or both");
74
+ }
75
+ export async function keysInit(ctx) {
76
+ const manifest = await loadManifest(ctx);
77
+ const uses = usesFor(ctx, manifest);
78
+ for (const use of uses) {
79
+ if (keysOfUse(manifest.publicKeys, use).length > 0) {
80
+ throw new UsageError(`the manifest already has a "${use}" key — add another with \`keys rotate --use ${use}\``);
81
+ }
82
+ }
83
+ const pairs = await createKeys(ctx, manifest, uses);
84
+ await saveKeys(ctx, pairs);
85
+ await saveManifest(ctx, manifest);
86
+ ctx.out.end(`Added ${pairs.map((p) => p.publicJwk.kid).join(" and ")} to ${MANIFEST_FILE}.`);
87
+ ctx.out.result({ added: pairs.map((p) => p.publicJwk.kid) });
88
+ }
89
+ export async function keysRotate(ctx) {
90
+ const manifest = await loadManifest(ctx);
91
+ const use = await ctx.prompter.select({
92
+ name: "use",
93
+ message: "Which key?",
94
+ options: [
95
+ {
96
+ value: "sig",
97
+ label: "Signing",
98
+ hint: "proves requests come from your backend",
99
+ },
100
+ {
101
+ value: "enc",
102
+ label: "Encryption",
103
+ hint: "what secrets are encrypted with",
104
+ },
105
+ ],
106
+ });
107
+ ctx.prompter.assertComplete();
108
+ // Fails here, before anything is written, if the use already holds two keys.
109
+ const pairs = await createKeys(ctx, manifest, [use]);
110
+ await saveKeys(ctx, pairs);
111
+ await saveManifest(ctx, manifest);
112
+ const kid = pairs[0]?.publicJwk.kid;
113
+ ctx.out.end(use === "enc"
114
+ ? `${kid} is now the first encryption key: secrets saved from the next release on use it. Keep both private keys, and pick by each secret's kid.`
115
+ : `${kid} is listed beside the current signing key. Switch your backend to sign with it, then \`keys retire\` the old one.`);
116
+ ctx.out.result({ added: kid });
117
+ }
118
+ export async function keysRetire(ctx, kid) {
119
+ if (kid === undefined) {
120
+ throw new UsageError('keys retire <kid> — the kids are in the manifest\'s "publicKeys"');
121
+ }
122
+ const manifest = await loadManifest(ctx);
123
+ const { set, retired } = (() => {
124
+ try {
125
+ return retireKey(manifest.publicKeys, kid);
126
+ }
127
+ catch (error) {
128
+ throw new UsageError(error.message);
129
+ }
130
+ })();
131
+ manifest.publicKeys = set.keys.length > 0 ? set : undefined;
132
+ await saveManifest(ctx, manifest);
133
+ ctx.out.warn(retired.use === "enc"
134
+ ? `Secrets stored under ${kid} will ask their admins to re-enter them. Destroy ${KEYS_DIR}/${kid}.pem only after that's done.`
135
+ : `Make sure your backend no longer signs with ${kid}. Then destroy ${KEYS_DIR}/${kid}.pem.`);
136
+ ctx.out.end(`Removed ${kid} from ${MANIFEST_FILE}.`);
137
+ ctx.out.result({ retired: kid });
138
+ }
139
+ export async function keysJwks(ctx) {
140
+ const manifest = await loadManifest(ctx);
141
+ const keys = manifest.publicKeys?.keys ?? [];
142
+ if (keys.length === 0) {
143
+ throw new UsageError("the manifest has no keys yet — `keys init` first");
144
+ }
145
+ const out = typeof ctx.flags.out === "string" ? ctx.flags.out : JWKS_PATH;
146
+ const path = join(ctx.dir, out);
147
+ await mkdir(dirname(path), { recursive: true });
148
+ await writeFile(path, `${JSON.stringify({ keys }, null, 2)}\n`);
149
+ ctx.out.success(`Wrote ${out}.`);
150
+ ctx.out.end('For a plugin also installed by URL: serve it at /.well-known/livespace/jwks.json on the plugin\'s origin, as application/json, no redirect, under 16 KiB, with Access-Control-Allow-Origin: * on any request header (browsers send priority and cache-control). On S3, that\'s a CORS rule with "AllowedHeaders": ["*"].');
151
+ ctx.out.result({ jwks: out, keys: keys.map((k) => k.kid) });
152
+ }
@@ -0,0 +1,25 @@
1
+ import { readManifestText } from "../manifest/file.js";
2
+ import { MANIFEST_FILE } from "../manifest/schema.js";
3
+ import { UsageError } from "./context.js";
4
+ /**
5
+ * The project's manifest, read as it is. Deliberately not refused when it fails the checker: a key
6
+ * command is often what fixes it (`secretKeys` with no encryption key yet, say). Commands check
7
+ * the result before writing.
8
+ */
9
+ export async function loadManifest(ctx) {
10
+ const text = await readManifestText(ctx.dir);
11
+ if (text === undefined) {
12
+ throw new UsageError(`no ${MANIFEST_FILE} here — create one with \`manifest init\``);
13
+ }
14
+ let value;
15
+ try {
16
+ value = JSON.parse(text);
17
+ }
18
+ catch (error) {
19
+ throw new UsageError(`${MANIFEST_FILE} is not valid JSON (${error.message})`);
20
+ }
21
+ if (typeof value !== "object" || value === null || Array.isArray(value)) {
22
+ throw new UsageError(`${MANIFEST_FILE} must be a JSON object`);
23
+ }
24
+ return value;
25
+ }