@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.
@@ -0,0 +1,311 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.nextSteps = exports.introduction = exports.signedInWords = exports.heldElsewhereLogout = exports.unattendedWords = exports.dayWords = exports.idleWords = exports.countryName = exports.heldTo = exports.activation = exports.cancelSetup = exports.redeem = exports.WRONG_CODE = exports.profileInUse = exports.holdsSignIn = exports.checkedSetupCode = exports.notUnattendedHost = exports.unattendedHost = exports.CHECK_CODE = exports.CODE_ON_COMMAND_LINE = exports.LOOKS_LIKE_SETUP_CODE = exports.SETUP_CODE = void 0;
4
+ const os_1 = require("os");
5
+ const errors_1 = require("./errors");
6
+ const http_1 = require("./http");
7
+ const secrets_1 = require("./secrets");
8
+ // `blocklive login --unattended` (docs/developer-api/cli-unattended-sign-ins.md):
9
+ // a sign-in that keeps working without you, for an AI agent or a script on
10
+ // this computer. The person makes a one-time setup code on the Developer
11
+ // page; the CLI reads it from standard input only, sends it to Blocklive
12
+ // itself (never anywhere else: until it is activated, the code is as good as
13
+ // the sign-in), keeps the token pair it gets as every sign-in is kept,
14
+ // prints the check code Blocklive answers with, and waits until the person
15
+ // types that check code on the page and presses Activate. Nothing works
16
+ // before that. A check code ties the setup on the page to this computer:
17
+ // someone else who redeemed the setup code first can't show it here.
18
+ /** A setup code, as the Developer page shows it once. */
19
+ exports.SETUP_CODE = /^bl_cls_(live|test)_[0-9a-f]{64}$/;
20
+ /** Anything on a command line that looks like one: refused, saying why. */
21
+ exports.LOOKS_LIKE_SETUP_CODE = /bl_cls_/i;
22
+ // Said when one was on the command line: it is in the shell's history now,
23
+ // so the setup it belongs to is cancelled and a new code made. (Piping it in
24
+ // from a command typed with the code would put it there too.)
25
+ exports.CODE_ON_COMMAND_LINE = 'Never put a setup code on the command line: this one is now in your shell history, where other programs on this computer can see it. Press Cancel for that setup on the Developer page and make a new setup code, then run `blocklive login --unattended` and paste it when asked.';
26
+ /** The check code Blocklive answers a setup code with, to type on the page. */
27
+ exports.CHECK_CODE = /^[BCDFGHJKLMNPQRSTVWXZ]{4}-[BCDFGHJKLMNPQRSTVWXZ]{4}$/;
28
+ const LOOPBACK = ['localhost', '127.0.0.1', '[::1]'];
29
+ /**
30
+ * Which setup code an address may be sent: a live one only to exactly
31
+ * https://blocklive.io, a test one (a development server's) only to this
32
+ * computer (localhost, 127.0.0.1 or [::1], http or https, any port). No
33
+ * other address takes one, whatever option, variable or profile names it.
34
+ */
35
+ function unattendedHost(url) {
36
+ const { protocol, hostname: host, origin } = new URL(url);
37
+ if (LOOPBACK.includes(host) &&
38
+ (protocol === 'http:' || protocol === 'https:'))
39
+ return 'test';
40
+ return origin === 'https://blocklive.io' ? 'live' : undefined;
41
+ }
42
+ exports.unattendedHost = unattendedHost;
43
+ const ONLY_BLOCKLIVE = 'An unattended sign-in is set up only with Blocklive itself: a live setup code is sent only to https://blocklive.io, a test one only to a development server on this computer (localhost, 127.0.0.1 or [::1]). Until it is activated, its setup code is as good as the sign-in, so it is never sent anywhere else.';
44
+ /** Why an address can't take an unattended sign-in, naming where it came from. */
45
+ function notUnattendedHost(url, from) {
46
+ const why = ONLY_BLOCKLIVE;
47
+ const host = new URL(url).host;
48
+ if (from === 'environment')
49
+ return (0, errors_1.usage)(`BLOCKLIVE_API_URL is set to ${host}. ${why} Unset BLOCKLIVE_API_URL to use blocklive.io.`);
50
+ if (from === 'profile')
51
+ return (0, errors_1.usage)(`This profile is signed in to ${host}. ${why} Use --api https://blocklive.io, or another --profile.`);
52
+ return (0, errors_1.usage)(`Not ${host}. ${why}`);
53
+ }
54
+ exports.notUnattendedHost = notUnattendedHost;
55
+ const client = () => ({
56
+ version: http_1.VERSION,
57
+ os: (0, os_1.platform)(),
58
+ hostname: (0, os_1.hostname)().slice(0, 64),
59
+ });
60
+ /**
61
+ * The setup code as read, or a usage error that never repeats it. A live
62
+ * code goes only to https://blocklive.io, a test one only to this computer:
63
+ * the other way round it is refused here, and nothing is sent.
64
+ */
65
+ function checkedSetupCode(read, url) {
66
+ const code = (read ?? '').trim();
67
+ if (!code)
68
+ throw (0, errors_1.usage)('No setup code was given. Paste it when asked, or pipe it in: the Developer page shows it once.');
69
+ const kind = exports.SETUP_CODE.exec(code)?.[1];
70
+ if (!kind)
71
+ throw (0, errors_1.usage)("That isn't a setup code: one starts with bl_cls_ and has 64 letters and digits after that. Copy it again from the Developer page.");
72
+ if (kind !== unattendedHost(url)) {
73
+ const host = new URL(url).host;
74
+ throw (0, errors_1.usage)(kind === 'live'
75
+ ? `That is a setup code from blocklive.io: it is sent only to https://blocklive.io, never to ${host}, so nothing was sent. Run it again with https://blocklive.io (no --api or BLOCKLIVE_API_URL).`
76
+ : `That is a test setup code, from a development server: it is sent only to a server on this computer, never to ${host}, so nothing was sent. Make the code on blocklive.io, or use --api with the development server's address.`);
77
+ }
78
+ return code;
79
+ }
80
+ exports.checkedSetupCode = checkedSetupCode;
81
+ /** A profile that holds a sign-in still live, or one waiting for Activate
82
+ * within its time (a minute's grace for the clocks). */
83
+ function holdsSignIn(saved, now = Date.now()) {
84
+ if (saved?.session)
85
+ return true;
86
+ const until = Date.parse(saved?.activating?.until ?? '');
87
+ return !!saved?.activating && !(until + 60000 < now);
88
+ }
89
+ exports.holdsSignIn = holdsSignIn;
90
+ /** Why login --unattended won't set one up over the profile's sign-in. */
91
+ function profileInUse(profile, saved) {
92
+ const logout = `\`blocklive logout${profile === 'default' ? '' : ` --profile ${profile}`}\``;
93
+ return saved.session
94
+ ? `This profile (${profile}) is signed in already, so no setup code was asked for. Set up the unattended sign-in on another --profile, or run ${logout} first.`
95
+ : `This profile (${profile}) has an unattended sign-in waiting to be activated, so no setup code was asked for. Press Activate on the Developer page, run ${logout} to cancel it, or use another --profile.`;
96
+ }
97
+ exports.profileInUse = profileInUse;
98
+ /** What the CLI says to a setup code that is wrong, used or expired: if a
99
+ * computer waits on the page, someone else redeemed it. */
100
+ exports.WRONG_CODE = 'That setup code is wrong, was already used or has expired. If the Developer page shows a computer waiting to be activated, it is not this one: press Cancel there and make a new setup code.';
101
+ /** The pair for the setup code: it works once the person activates it. */
102
+ async function redeem(api, code, now = Date.now) {
103
+ let answer;
104
+ try {
105
+ answer = await api.post('/login/unattended', {
106
+ setup_code: code,
107
+ client: client(),
108
+ });
109
+ }
110
+ catch (error) {
111
+ // The CLI's own words, whatever came with it.
112
+ if (error instanceof errors_1.CliError && error.code === 'wrong_code')
113
+ throw new errors_1.CliError(exports.WRONG_CODE, errors_1.EXIT.refused, 'wrong_code', error.requestId);
114
+ throw error;
115
+ }
116
+ const tokens = (0, secrets_1.splitTokens)(`${answer.access_token}:${answer.refresh_token}`);
117
+ const seconds = Number(answer.activate_within);
118
+ if (answer.status !== 'waiting_for_activation' ||
119
+ !tokens ||
120
+ !Number.isFinite(seconds) ||
121
+ seconds < 0 ||
122
+ typeof answer.check_code !== 'string' ||
123
+ !exports.CHECK_CODE.test(answer.check_code))
124
+ throw new errors_1.CliError('Blocklive sent an unexpected answer, so nothing was kept here. If the Developer page shows a computer waiting to be activated, press Cancel there and make a new setup code.');
125
+ return {
126
+ tokens,
127
+ until: new Date(now() + Math.min(seconds, 900) * 1000).toISOString(),
128
+ check: answer.check_code,
129
+ };
130
+ }
131
+ exports.redeem = redeem;
132
+ /**
133
+ * `blocklive logout` before Activate: cancels the setup on Blocklive with
134
+ * the pair's access token, so it can't be activated any more. 'cancelled'
135
+ * (or already); 'gone' when Blocklive doesn't know the pair (it expired);
136
+ * 'activated' when the person activated it meanwhile: then it is signed out
137
+ * as any other. A dropped connection is tried twice more; without an
138
+ * answer, or refused, it is kept as it was and the command says so.
139
+ */
140
+ async function cancelSetup(api, { wait, site, until }) {
141
+ for (let attempt = 1;; attempt += 1) {
142
+ try {
143
+ const answer = await api.post('/login/unattended/cancel', {});
144
+ if (answer.status === 'cancelled' || answer.status === 'activated')
145
+ return answer.status;
146
+ throw new errors_1.CliError('Blocklive sent an unexpected answer, so the unattended sign-in set up here is kept. Run `blocklive logout` again, or press Cancel on the Developer page.');
147
+ }
148
+ catch (error) {
149
+ if ((0, errors_1.endedOnBlocklive)(error))
150
+ return 'gone';
151
+ const code = error instanceof errors_1.CliError ? error.code : undefined;
152
+ const lost = code === 'unreachable' || code === 'unavailable';
153
+ if (lost && code === 'unreachable' && attempt < 3) {
154
+ await wait(2000);
155
+ continue;
156
+ }
157
+ if (lost)
158
+ throw new errors_1.CliError(`${code === 'unreachable'
159
+ ? "Couldn't reach Blocklive to cancel the unattended sign-in set up here"
160
+ : "Blocklive couldn't cancel the unattended sign-in set up here just now"}, so it is kept: it could still be activated. Run \`blocklive logout\` again ${code === 'unreachable'
161
+ ? 'when you’re online'
162
+ : 'in a minute'}, or press Cancel on the Developer page at ${site}. If nobody activates it, it expires by itself${clock(until, ' at')}.`, errors_1.EXIT.error, code);
163
+ throw error;
164
+ }
165
+ }
166
+ }
167
+ exports.cancelSetup = cancelSetup;
168
+ // " at 10:42" (this computer's time), or nothing for a time that isn't one.
169
+ function clock(value, before) {
170
+ const date = new Date(value);
171
+ return Number.isNaN(date.getTime())
172
+ ? ''
173
+ : `${before} ${date.toLocaleTimeString('en-GB', {
174
+ hour: '2-digit',
175
+ minute: '2-digit',
176
+ })}`;
177
+ }
178
+ /**
179
+ * Asks Blocklive, with the pair's access token, whether the person activated
180
+ * it: every 5 seconds (longer when told to slow down) until it is active,
181
+ * cancelled or expired, or `once` for a single look ('pending' then).
182
+ * While waiting, lost connections and Blocklive's own failures are not
183
+ * answers; a single look that gets none says so.
184
+ */
185
+ async function activation(api, { until, wait, once = false, now = Date.now, }) {
186
+ // Waited time, not the clock alone: a server that never answers can't
187
+ // keep it looking for ever.
188
+ const left = new Date(until).getTime() + 15000 - now();
189
+ const budget = Math.min(Number.isFinite(left) ? left : 600000, 960000);
190
+ let interval = 5;
191
+ let waited = 0;
192
+ for (;;) {
193
+ try {
194
+ const answer = await api.post('/login/unattended/wait', {});
195
+ if (answer.status === 'active')
196
+ return 'active';
197
+ throw new errors_1.CliError('Blocklive sent an unexpected answer. Try again.');
198
+ }
199
+ catch (error) {
200
+ const code = error instanceof errors_1.CliError ? error.code : undefined;
201
+ if (code === 'access_denied')
202
+ throw new errors_1.CliError('The unattended sign-in was cancelled on the page, so nothing was turned on.', errors_1.EXIT.refused, code);
203
+ if (code === 'expired_token' || code === 'not_signed_in')
204
+ throw new errors_1.CliError("The unattended sign-in wasn't activated in time, so it expired. Make a new setup code on the Developer page.", errors_1.EXIT.refused, 'expired_token');
205
+ if (code === 'slow_down')
206
+ interval += 5;
207
+ else if (code !== 'authorization_pending' &&
208
+ (once || (code !== 'unreachable' && code !== 'unavailable')))
209
+ // One look that got no answer says so, rather than "not yet".
210
+ throw error;
211
+ }
212
+ if (once)
213
+ return 'pending';
214
+ if (waited >= budget)
215
+ break;
216
+ await wait(interval * 1000);
217
+ waited += interval * 1000;
218
+ }
219
+ throw new errors_1.CliError("The unattended sign-in wasn't activated in time, so it expired. Make a new setup code on the Developer page.", errors_1.EXIT.refused, 'expired_token');
220
+ }
221
+ exports.activation = activation;
222
+ /** "this network (94.200.12.0/24)" or "this country (United Arab Emirates)". */
223
+ function heldTo(session) {
224
+ if (session.pin === 'country')
225
+ return session.pinned
226
+ ? `this country (${countryName(session.pinned)})`
227
+ : 'the country it was set up in';
228
+ return session.pinned
229
+ ? `this network (${session.pinned})`
230
+ : 'the network it was set up on';
231
+ }
232
+ exports.heldTo = heldTo;
233
+ function countryName(code) {
234
+ try {
235
+ return (new Intl.DisplayNames(['en'], { type: 'region' }).of(code) ?? code);
236
+ }
237
+ catch {
238
+ return code;
239
+ }
240
+ }
241
+ exports.countryName = countryName;
242
+ /** "7 days", "1 day", "12 hours": how long it may sit unused. */
243
+ function idleWords(minutes) {
244
+ const value = minutes ?? 10080;
245
+ if (value >= 1440) {
246
+ const days = Math.round(value / 1440);
247
+ return days === 1 ? '1 day' : `${days} days`;
248
+ }
249
+ const hours = Math.max(1, Math.round(value / 60));
250
+ return hours === 1 ? '1 hour' : `${hours} hours`;
251
+ }
252
+ exports.idleWords = idleWords;
253
+ /** "19 Nov 2026" (UTC), the day it ends. */
254
+ function dayWords(value) {
255
+ const date = value ? new Date(value) : undefined;
256
+ return date && !Number.isNaN(date.getTime())
257
+ ? date.toLocaleDateString('en-GB', {
258
+ day: 'numeric',
259
+ month: 'short',
260
+ year: 'numeric',
261
+ timeZone: 'UTC',
262
+ })
263
+ : 'when it runs out';
264
+ }
265
+ exports.dayWords = dayWords;
266
+ /** whoami's lines for an unattended sign-in: where it works from, how long
267
+ * it may sit unused, and whether it may read guests' and buyers' details. */
268
+ function unattendedWords(me) {
269
+ const lines = [
270
+ `Unattended: works only from ${heldTo(me)}; stops after ${idleWords(me.idleLimitMinutes)} unused`,
271
+ ];
272
+ if (typeof me.personal === 'boolean')
273
+ lines.push(me.personal
274
+ ? 'Guests’ and buyers’ details: readable'
275
+ : 'Guests’ and buyers’ details: not readable (make one that may on the Developer page)');
276
+ return lines;
277
+ }
278
+ exports.unattendedWords = unattendedWords;
279
+ /** What `logout` says when the sign-in is held to another network: it is
280
+ * still live, and is ended from there or on the page. */
281
+ function heldElsewhereLogout(session, site) {
282
+ return `This unattended sign-in works only from ${heldTo(session)}, so it can’t be ended from here: it is still active. Run \`blocklive logout\` from there, or end it on ${site} → Developer → CLI sign-ins.`;
283
+ }
284
+ exports.heldElsewhereLogout = heldElsewhereLogout;
285
+ /** What `login --unattended` says once it is active. */
286
+ function signedInWords(session, where, site) {
287
+ return `Signed in, unattended, as ${session.person ?? 'you'} ${where}. It works only from ${heldTo(session)}, ends ${dayWords(session.endsAt)}, and stops after ${idleWords(session.idleLimitMinutes)} unused. End it with \`blocklive logout\` or on ${site}.`;
288
+ }
289
+ exports.signedInWords = signedInWords;
290
+ /** The two lines before the code is asked for. */
291
+ function introduction(style, site) {
292
+ return style.block([
293
+ style.bold('Set up an unattended sign-in'),
294
+ '',
295
+ 'It keeps working without you, for an AI agent or a script on this computer.',
296
+ `Make its setup code on ${site}: Developer → CLI sign-ins → Add unattended sign-in.`,
297
+ ]);
298
+ }
299
+ exports.introduction = introduction;
300
+ /** What to do on the page, once the code was taken: the check code to type
301
+ * there, which only this terminal shows. */
302
+ function nextSteps(style, site, until, check) {
303
+ return style.block([
304
+ 'Setup code taken. Nothing works until you activate it.',
305
+ `Go back to the page on ${site}: it shows this computer (${client().hostname || 'unnamed'}) and where Blocklive saw it from.`,
306
+ `Type this code on the Developer page, not here: ${style.code(check)}`,
307
+ `Check it is this computer, then press Activate${clock(until, ' before')}.`,
308
+ style.dim('Never type a code someone sent you.'),
309
+ ]);
310
+ }
311
+ exports.nextSteps = nextSteps;
package/package.json CHANGED
@@ -1,6 +1,31 @@
1
1
  {
2
- "name": "@blocklive/cli",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
2
+ "name": "@blocklive/cli",
3
+ "version": "0.7.0",
4
+ "description": "Blocklive from the command line: read your events and make safe changes.",
5
+ "license": "UNLICENSED",
6
+ "homepage": "https://blocklive.io/docs/developers/cli",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://github.com/blocklive/platform.git",
10
+ "directory": "packages/cli"
11
+ },
12
+ "bugs": {
13
+ "url": "https://blocklive.io/support"
14
+ },
15
+ "publishConfig": {
16
+ "access": "public"
17
+ },
18
+ "bin": {
19
+ "blocklive": "dist/main.js"
20
+ },
21
+ "files": [
22
+ "dist"
23
+ ],
24
+ "engines": {
25
+ "node": ">=20"
26
+ },
27
+ "scripts": {
28
+ "build": "tsc -p tsconfig.json && chmod +x dist/main.js",
29
+ "typecheck": "tsc -p tsconfig.json --noEmit"
30
+ }
31
+ }