@blocklive/cli 0.0.0-stage → 0.7.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 ADDED
@@ -0,0 +1,3 @@
1
+ Copyright Blocklive.
2
+
3
+ Anyone can install and use it, but there's no licence to copy it.
package/README.md CHANGED
@@ -1,3 +1,203 @@
1
- # Temporary Holding Version
1
+ # Blocklive CLI (`packages/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
+ `blocklive`: reads and safe writes for producers, from the terminal. What it
4
+ does: [docs/public/developers/cli/](../../docs/public/developers/cli/). How
5
+ it's built and what it may do: [docs/developer-api/cli-writes-plan.md](../../docs/developer-api/cli-writes-plan.md).
6
+
7
+ ## Install
8
+
9
+ From npm, with Node 20 or later:
10
+
11
+ ```sh
12
+ npm install --global @blocklive/cli # puts `blocklive` on the PATH
13
+ blocklive --version
14
+ blocklive login
15
+ ```
16
+
17
+ It has no dependencies of its own. To update: run the install again. To
18
+ remove it: `npm uninstall --global @blocklive/cli`.
19
+
20
+ Anyone can install and use it, but there's no licence to copy it.
21
+
22
+ ## Development: install from this repository
23
+
24
+ To run the CLI as it is on a checkout of `main` (Node 20 or later):
25
+
26
+ ```sh
27
+ yarn install --frozen-lockfile # TypeScript, to build it
28
+ yarn --cwd packages/cli build # tsc into packages/cli/dist
29
+ npm install --global ./packages/cli # puts `blocklive` on the PATH
30
+ blocklive --version
31
+ ```
32
+
33
+ To update: pull `main`, build and install again.
34
+
35
+ Upgrading from 0.4.0 or earlier: `blocklive logout` (or `blocklive login`)
36
+ ends a sign-in made by CLI 0.4.0 or earlier on blocklive.io for you. For any
37
+ other server, end it under **CLI sign-ins** on that server's Developer page.
38
+ Since 0.4.1 the CLI keeps separate credentials for each configuration
39
+ directory, API origin and profile.
40
+
41
+ Against a local server: `blocklive login --api http://localhost:3000`.
42
+
43
+ ### What changed in 0.7.0
44
+
45
+ - **Prices:** `blocklive tickets add <event> --title <title> --price <amount>`
46
+ and `tickets edit <event> <ticket> --price <amount>` set a ticket type's
47
+ price in the event's currency, in its draft. It goes live with Publish.
48
+ - **Removing ticket types:** `blocklive tickets remove <event> <ticket>`
49
+ removes a ticket type in its draft. It's refused once any are sold or
50
+ reserved, and it goes live with Publish.
51
+ - **Images:** `blocklive events edit <event> --cover <file>` and
52
+ `tickets edit <event> <ticket> --art <file>` set the event's cover and a
53
+ ticket type's art in the draft. PNG, JPEG or WebP; at most 4 MB, 200 to
54
+ 8,000 px a side, 40 megapixels in all; refused if it carries metadata
55
+ such as location.
56
+ - **Places:** `blocklive places search <text>` finds up to five places on
57
+ Google Maps, and `events edit <event> --place <place ID>` sets one in the
58
+ draft. Each person has 20 lookups a day.
59
+ - **Payout account:** `blocklive payment-account choices <event>` lists the
60
+ accounts an unpublished event could take, and
61
+ `payment-account choose <event> --to <team|id>` asks for one. Nothing
62
+ changes until you confirm it on blocklive.io with a new code from your
63
+ authenticator; the CLI never takes a code. Never with an unattended
64
+ sign-in. Choosing a payout account from the CLI isn't open for every
65
+ team yet: until it is for yours, the ask answers "Choosing a payment
66
+ account from the CLI isn't open for this team yet."
67
+ - **The draft:** `blocklive event draft <event>` shows the cover, the place
68
+ with its map link, and each ticket type with its price and art, beside
69
+ what is live. `event publish <event> --dry-run` lists the same as what
70
+ goes live.
71
+ - **After publishing:** `event publish` prints the event's public page,
72
+ the one guests see (`publicUrl` in `--json`), and where to manage it.
73
+ The public page can take a few minutes to show what was published.
74
+ `event show` says whether an event is published, shows a place as its
75
+ name and address, and links the public page once it is live.
76
+ - **An older Blocklive:** a command the Blocklive you are signed in to
77
+ doesn't have yet says so ("This command isn't on this Blocklive yet",
78
+ code `command_unavailable`, exit code 1) instead of "not found".
79
+
80
+ ### What changed in 0.5.0
81
+
82
+ - `blocklive event publish <event>` publishes the event (it, its tickets
83
+ and its prices go live for everyone) when the sign-in was approved with
84
+ **Publish** switched on; it is off unless you switch it on when you run
85
+ `blocklive login`. It shows what goes live and asks first (`--yes` to
86
+ skip, `--dry-run` for the plan only). Unattended sign-ins never publish,
87
+ and an event published from its organiser's own wallet is published on
88
+ blocklive.io.
89
+ - Without **Publish**, `event publish` now exits 3 (refused) with the link
90
+ to publish on blocklive.io. Before 0.5.0 it only printed that link and
91
+ exited 0.
92
+ - A publish still going after 3 minutes, or with `--no-wait`, exits 7 with
93
+ the command that finishes it (`--finish <publish>`).
94
+
95
+ For an AI agent or a script on a computer you control:
96
+ `blocklive login --unattended`, a sign-in that keeps working without you,
97
+ made and activated on blocklive.io
98
+ ([unattended sign-ins](../../docs/public/developers/cli/sign-in.md#unattended-sign-ins)).
99
+
100
+ ## How it's put together
101
+
102
+ - `src/catalog.ts` lists every command: its usage, kind (`session`, `read`,
103
+ `change`, `ask`), arguments, options and who may use it. The `commands`
104
+ command prints it, `cli.ts` resolves commands from it and refuses any
105
+ option a command doesn't take (exit 2), and the tests check that every
106
+ command in it runs, has a line in the help and survives a hostile
107
+ server.
108
+ - `src/safe.ts`: names, titles and reasons come from other people. Answers
109
+ are cleaned of control and invisible characters as they arrive
110
+ (`http.ts`), and everything printed goes through one guard in `cli.ts`
111
+ that lets through only the CLI's own colour codes; `--json` output is
112
+ escaped instead, so it stays the same JSON.
113
+ - `src/reads/requests.ts`: the commands that only ask, confirmed on
114
+ blocklive.io: the link, waiting for the answer, `--no-wait` and
115
+ `request show`.
116
+ - `src/change.ts`: what every change does alike (`tickets add|edit`,
117
+ `events create|edit`). It is tried on Blocklive first (a dry run, every
118
+ check, nothing written), the plan read as sent and cleaned to be shown,
119
+ then asked (or `--yes`), and sent once with an idempotency key
120
+ (`src/idempotency.ts`: a UUID a run, or `--idempotency-key`). An answer
121
+ lost (none, a 5xx, one that can't be read: `NoAnswer` in `http.ts`) is
122
+ sent again twice with the same key, then the error carries the key. With
123
+ `--idempotency-key` a refused dry run, or one that would change nothing,
124
+ doesn't stop it from reaching Blocklive's answer for that key.
125
+ - `src/http.ts` waits out only a 429 with `Retry-After` (the per-minute
126
+ limit); a budget (an hour's changes, a day's events) is said at once,
127
+ exit 5.
128
+ - `src/reads/tickets.ts`: `tickets list|add|edit|remove`, ticket types as
129
+ drafts. `--price` sets a paid price in the draft, in the event's currency;
130
+ it goes live with `event publish`. The database computes the chain units
131
+ (20261202140000). An unattended sign-in sets no price. `tickets remove`
132
+ marks a ticket type removed in the draft, with its codes and gates; it is
133
+ refused once any are sold or on an open order, and for package and
134
+ free-ticket types (20261202150000). Never from an unattended sign-in.
135
+ - `src/image-file.ts`: `events edit --cover <file>` and `tickets edit
136
+ --art <file>`. The file is read through one handle (at most 4 MB, and
137
+ one of PNG, JPEG or WebP by its first bytes) and sent as it is, as the
138
+ request's body, to `/api/cli/v1/images/…` (`upload` in `http.ts`): once
139
+ as a dry run for the plan, then with the change's key, through
140
+ `src/change.ts` like every change. Blocklive checks the whole file
141
+ (still images only, no metadata, 200 to 8,000 pixels a side), stores it
142
+ and puts it in the draft (20261202160000). Each goes on its own, and
143
+ never from an unattended sign-in: the catalog marks the two options
144
+ `attendedOnly`.
145
+ - `src/reads/places.ts`: `places search <text>`, up to five places on
146
+ Google Maps with their place IDs (a POST, so the text is never in an
147
+ address). `events edit --place <place ID>` (`src/reads/events.ts`) sends
148
+ that ID and nothing else, through `src/change.ts` like every change:
149
+ Blocklive asks Google for the place and builds what it stores
150
+ (20261202170000). Each lookup is counted, 20 a person a day. Neither
151
+ from an unattended sign-in: the catalog marks the command and the
152
+ option `attendedOnly`.
153
+ - `src/reads/payment-account.ts`: besides `show` and `switch`,
154
+ `payment-account choices <event>` (the accounts an unpublished event
155
+ could take, by row ID, masked) and `payment-account choose <event> --to
156
+ <team|id>`, which only asks: it posts `{ to }`, prints the link to
157
+ `/cli/confirm` and waits like every ask (`src/reads/requests.ts`). The
158
+ account changes only when the same person confirms there with a new
159
+ two-step code; the CLI takes no code (20261212110000). Neither from an
160
+ unattended sign-in.
161
+ - `src/reads/events.ts`: `events create|edit` and `event draft|publish`. A
162
+ new event is unpublished, and an edit changes the event's draft, the same
163
+ way (`src/change.ts`). `event publish` publishes it, only with a sign-in
164
+ the person approved with **Publish** switched on (never an unattended
165
+ one): it shows what goes live (a dry run), takes a yes at its prompt or
166
+ `--yes`, starts it, waits for it to go through (every 2 seconds, up to 3
167
+ minutes) and finishes it; `--finish <publish>` finishes one later, safe
168
+ to run twice. An event published from the organiser's own wallet is
169
+ published on blocklive.io. `--description-file` reads one UTF-8
170
+ text file through one handle, and nothing it names; an empty one is
171
+ refused. Times are shown with their offset, from Blocklive's `starts`
172
+ and `ends`; a description is its first 300 characters unless
173
+ `event draft --full`.
174
+ - `src/unattended.ts` and `src/stdin.ts`: `login --unattended`. The setup
175
+ code is read from standard input only (hidden at a terminal, else the
176
+ first line piped in), refused anywhere on the command line, and sent
177
+ only to Blocklive itself: a live code to exactly `https://blocklive.io`,
178
+ a test one to a server on this computer. Blocklive answers with a check
179
+ code the person enters on the page; `logout` before Activate cancels the
180
+ setup. `src/lock.ts` keeps two commands from renewing a sign-in at once,
181
+ and the `--insecure-storage` file's changes in turn (`src/secrets.ts`).
182
+ - Modules only some commands need (login, the browser's local server, the
183
+ keychain tools, the lock, each command's file) are loaded when they run,
184
+ so `--version`, `help` and `commands` start in about 6 ms more than Node
185
+ itself.
186
+
187
+ For scripts and agents: `--json`, `--no-wait`, `--dry-run`,
188
+ `--idempotency-key`, `blocklive commands --json` (each exit code with its
189
+ error codes, which commands are confirmed on blocklive.io), `BLOCKLIVE_PROFILE`
190
+ and `BLOCKLIVE_NO_BROWSER`, in
191
+ [docs/public/developers/cli/scripts.md](../../docs/public/developers/cli/scripts.md#agents-and-scripts).
192
+
193
+ ## Tests
194
+
195
+ ```sh
196
+ npx jest packages/cli packages/services/server/cli
197
+ yarn --cwd packages/cli typecheck
198
+ ```
199
+
200
+ The database side of each command has a kit under `tests/cli-*`
201
+ (`python3 tests/cli-<name>/run.py`, a throwaway PostgreSQL 15). The tests
202
+ also check that `docs/public/developers/cli/scripts.md` lists every
203
+ command's JSON and the catalog's error and exit codes.
@@ -0,0 +1,194 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.onEnter = exports.openInBrowser = exports.listenForCallback = exports.CALLBACK_PATH = void 0;
4
+ const child_process_1 = require("child_process");
5
+ const crypto_1 = require("crypto");
6
+ const http_1 = require("http");
7
+ const readline_1 = require("readline");
8
+ // A browser login's three local pieces (login.ts): opening /cli in this
9
+ // computer's browser, the person's Enter key that does it, and a server on
10
+ // 127.0.0.1 that hears the one answer the approval sends back. The answer
11
+ // carries a one-time grant; it is taken only with this login's state, and
12
+ // only on 127.0.0.1 under its own port (a page elsewhere that points a
13
+ // browser here doesn't match), then the server stops. Signed in, it sends
14
+ // the tab on to the success page on the Blocklive the CLI uses (0.3.3), with
15
+ // nothing in that address but its path; anything else gets a page from here.
16
+ exports.CALLBACK_PATH = '/blocklive-cli/callback';
17
+ function same(given, expected) {
18
+ const a = Buffer.from(given);
19
+ const b = Buffer.from(expected);
20
+ return a.length === b.length && (0, crypto_1.timingSafeEqual)(a, b);
21
+ }
22
+ function listenForCallback(state) {
23
+ let answered;
24
+ let settle = () => undefined;
25
+ const answer = new Promise((resolve) => {
26
+ settle = resolve;
27
+ });
28
+ const server = (0, http_1.createServer)((req, res) => {
29
+ const url = new URL(req.url ?? '/', 'http://127.0.0.1');
30
+ const port = server.address().port;
31
+ if (req.method !== 'GET' ||
32
+ url.pathname !== exports.CALLBACK_PATH ||
33
+ req.headers.host !== `127.0.0.1:${port}`)
34
+ return send(res, 404, 'unknown');
35
+ if (answered)
36
+ return send(res, 409, 'done');
37
+ const grant = url.searchParams.get('code') ?? '';
38
+ const refused = url.searchParams.get('error') === 'access_denied';
39
+ if (!same(url.searchParams.get('state') ?? '', state) ||
40
+ (!/^[0-9a-f]{64}$/.test(grant) && !refused))
41
+ return send(res, 400, 'unknown');
42
+ // Held until the CLI has its tokens, so the tab says what happened.
43
+ answered = res;
44
+ settle(refused ? { refused: true } : { grant });
45
+ });
46
+ const stop = () => {
47
+ server.close();
48
+ server.closeAllConnections();
49
+ };
50
+ return new Promise((resolve, reject) => {
51
+ server.once('error', reject);
52
+ server.listen(0, '127.0.0.1', () => {
53
+ resolve({
54
+ port: server.address().port,
55
+ wait: (timeoutMs) => Promise.race([
56
+ answer,
57
+ new Promise((done) => setTimeout(() => done(undefined), timeoutMs).unref()),
58
+ ]),
59
+ finish: (outcome, signedIn) => {
60
+ const to = outcome === 'signed_in' && successPage(signedIn);
61
+ if (!answered || answered.headersSent)
62
+ stop();
63
+ else if (to)
64
+ redirect(answered, to, stop);
65
+ else
66
+ send(answered, 200, outcome, stop);
67
+ },
68
+ });
69
+ });
70
+ });
71
+ }
72
+ exports.listenForCallback = listenForCallback;
73
+ // Only the success page itself: http(s), its path, nothing else in it.
74
+ function successPage(address) {
75
+ try {
76
+ const url = new URL(address ?? '');
77
+ return (url.protocol === 'https:' || url.protocol === 'http:') &&
78
+ url.pathname === '/cli/signed-in' &&
79
+ !url.search &&
80
+ !url.hash &&
81
+ !url.username &&
82
+ !url.password
83
+ ? url.href
84
+ : undefined;
85
+ }
86
+ catch {
87
+ return undefined;
88
+ }
89
+ }
90
+ // The tab came here with the grant and state in its address: it leaves with
91
+ // no Referer, so they go nowhere else.
92
+ function redirect(res, to, then) {
93
+ res.writeHead(302, {
94
+ Location: to,
95
+ 'Cache-Control': 'no-store',
96
+ 'Referrer-Policy': 'no-referrer',
97
+ 'Content-Type': 'text/plain; charset=utf-8',
98
+ 'X-Content-Type-Options': 'nosniff',
99
+ Connection: 'close',
100
+ });
101
+ res.end('Signed in. Going back to Blocklive.', then);
102
+ }
103
+ const PAGES = {
104
+ signed_in: [
105
+ 'Signed in',
106
+ 'The Blocklive CLI is signed in. You can close this tab and go back to your terminal.',
107
+ ],
108
+ refused: [
109
+ 'Sign-in refused',
110
+ 'Nothing was signed in. You can close this tab and go back to your terminal.',
111
+ ],
112
+ failed: [
113
+ 'Something went wrong',
114
+ 'The CLI couldn’t finish signing in. Your terminal says why; run blocklive login again.',
115
+ ],
116
+ unknown: [
117
+ 'Not this sign-in',
118
+ 'This isn’t the sign-in this computer’s Blocklive CLI is waiting for.',
119
+ ],
120
+ done: ['Already answered', 'This sign-in was already answered.'],
121
+ };
122
+ function send(res, status, page, then) {
123
+ const [title, text] = PAGES[page];
124
+ const ok = page === 'signed_in';
125
+ res.writeHead(status, {
126
+ 'Content-Type': 'text/html; charset=utf-8',
127
+ 'Cache-Control': 'no-store',
128
+ 'Content-Security-Policy': "default-src 'none'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'; frame-ancestors 'none'",
129
+ 'Referrer-Policy': 'no-referrer',
130
+ 'X-Content-Type-Options': 'nosniff',
131
+ Connection: 'close',
132
+ });
133
+ res.end(`<!doctype html><html lang="en"><head><meta charset="utf-8">` +
134
+ `<meta name="viewport" content="width=device-width,initial-scale=1">` +
135
+ `<title>Blocklive CLI · ${title}</title><style>${PAGE_CSS}</style></head>` +
136
+ `<body><main${ok ? ' class="ok"' : ''}><small>Blocklive CLI</small>` +
137
+ `<span class="mark" aria-hidden="true">${ok ? CHECK : CROSS}</span>` +
138
+ `<h1>${title}</h1><p>${text}</p></main></body></html>`, then);
139
+ }
140
+ // blocklive.io's own look (the admin's dark ground, white ink, lime for
141
+ // done), with nothing loaded from anywhere: the CSP allows inline style only.
142
+ const PAGE_CSS = '*{box-sizing:border-box}' +
143
+ 'body{margin:0;min-height:100vh;display:grid;place-items:center;padding:24px;color:#fff;' +
144
+ 'background:radial-gradient(1000px 560px at 85% -12%,rgba(135,79,251,.16),transparent 62%),#15161a;' +
145
+ 'font:500 16px/1.5 -apple-system,BlinkMacSystemFont,"Helvetica Neue",Helvetica,Arial,sans-serif;-webkit-font-smoothing:antialiased}' +
146
+ 'main{width:100%;max-width:440px;display:grid;justify-items:center;gap:14px;text-align:center;padding:40px 32px 32px;' +
147
+ 'border-radius:28px;background:#202126;border:1px solid rgba(255,255,255,.07);box-shadow:0 30px 80px rgba(0,0,0,.3)}' +
148
+ 'small{color:#ab82ff;font-size:13px;font-weight:700;letter-spacing:.08em;text-transform:uppercase}' +
149
+ '.mark{display:grid;place-items:center;width:76px;height:76px;border-radius:50%;background:rgba(255,255,255,.07);color:rgba(255,255,255,.76)}' +
150
+ '.ok .mark{background:rgba(160,236,0,.12);color:#a0ec00}' +
151
+ 'h1{margin:0;font-size:28px;line-height:1.15;font-weight:800;letter-spacing:-.02em}' +
152
+ 'p{margin:0;color:rgba(255,255,255,.76);max-width:360px}';
153
+ const icon = (path) => `<svg width="36" height="36" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round" stroke-linejoin="round">${path}</svg>`;
154
+ const CHECK = icon('<path d="M5 12.5l4.5 4.5L19 7.5"/>');
155
+ const CROSS = icon('<path d="M7 7l10 10M17 7L7 17"/>');
156
+ // The system's own opener, by its full path where it has one.
157
+ function openInBrowser(url, platform = process.platform) {
158
+ const [command, args] = platform === 'darwin'
159
+ ? ['/usr/bin/open', [url]]
160
+ : platform === 'win32'
161
+ ? [
162
+ `${process.env.SystemRoot ?? 'C:\\Windows'}\\System32\\rundll32.exe`,
163
+ ['url.dll,FileProtocolHandler', url],
164
+ ]
165
+ : ['xdg-open', [url]];
166
+ try {
167
+ const child = (0, child_process_1.spawn)(command, args, { stdio: 'ignore', detached: true });
168
+ child.on('error', () => undefined);
169
+ child.unref();
170
+ return true;
171
+ }
172
+ catch {
173
+ return false;
174
+ }
175
+ }
176
+ exports.openInBrowser = openInBrowser;
177
+ function onEnter(input) {
178
+ if (!input.isTTY)
179
+ return undefined;
180
+ const lines = (0, readline_1.createInterface)({ input, terminal: false });
181
+ let heard = () => undefined;
182
+ const pressed = new Promise((resolve) => lines.on('line', (text) => {
183
+ resolve();
184
+ heard(text);
185
+ }));
186
+ return {
187
+ pressed,
188
+ typed: (listener) => {
189
+ heard = listener;
190
+ },
191
+ stop: () => lines.close(),
192
+ };
193
+ }
194
+ exports.onEnter = onEnter;