@politelabs/cabin-cli 0.5.0 → 0.6.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/README.md CHANGED
@@ -10,15 +10,15 @@ Node 22.12 or newer. Nothing else is installed with it.
10
10
 
11
11
  ## Signing in
12
12
 
13
- A token is made on the site, under Site settings › API tokens: a *management* token, which acts as you. A self-hosted install can make one with `php artisan cabin:tokens:make`.
14
-
15
13
  ```
16
14
  cabin login
17
15
  ```
18
16
 
19
- That signs in to https://app.cabincms.com. For a self-hosted install, set `CABIN_HOST=https://cabin.example.com`. Inside a theme's folder, the host in `cabin.json` is used.
17
+ That opens your browser on Cabin, where you approve Cabin CLI. One sign-in reaches every site you're on, and each theme's folder says which site it's for, so you can work on several sites from one machine. It signs in to https://app.cabincms.com; for a self-hosted install, set `CABIN_HOST=https://cabin.example.com`, and sign in to each install you use. Inside a theme's folder, the host in `cabin.json` is used.
18
+
19
+ The sign-in is kept in `~/.config/cabin/credentials.json`, never in the theme's folder, and is refreshed as you use it. It ends after 30 days unused, or when you disconnect Cabin CLI under Security settings. `cabin whoami` says who you are and lists your sites; `cabin logout` signs out.
20
20
 
21
- The token is kept in `~/.config/cabin/credentials.json`, by host and site, never in the theme's folder.
21
+ On a machine with no browser, such as a server or CI, use a *management* token instead, made on the site under Site settings › API tokens (or with `php artisan cabin:tokens:make` on a self-hosted install): `cabin login --token cabin_…`, or `CABIN_TOKEN` in the environment. A token reaches its one site.
22
22
 
23
23
  ## A theme
24
24
 
@@ -31,13 +31,13 @@ cabin theme push --note "Tighter header" # saves a version
31
31
  cabin theme publish # draws the site with it
32
32
  ```
33
33
 
34
- `cabin theme init` asks which of the sites you're signed in to the theme is for, and what to call it; the folder is named after the theme unless you give one. `--site` and `--name` skip the questions. It makes the theme on the site and writes `cabin.json` (the host, the site's handle and the theme's key), which is committed; `.cabin/` holds what the CLI remembers and isn't.
34
+ `cabin theme init` asks which of your sites the theme is for (the ones where you may change themes, as an Owner or Admin), and what to call it; the folder is named after the theme unless you give one. `--site` and `--name` skip the questions. It makes the theme on the site and writes `cabin.json` (the host, the site's handle and the theme's key), which is committed; `.cabin/` holds what the CLI remembers and isn't.
35
35
 
36
36
  A theme is `theme.json`, `theme.css`, templates under `templates/`, patterns under `patterns/`, and its own scripts and drawings (`.js`, `.svg`) under `assets/`: a template prints one's address with `{{ asset('assets/nav.js') }}`, `theme.css` names one by its path (`url(assets/wave.svg)`), and a script at `assets/blocks/<block key>.js` is loaded only on the pages that block is on. A theme's pictures (`.png`, `.jpg`, `.webp`, `.gif`, `.avif` under `assets/`, 2 MB each at most) are synced too: `push` and `dev` send only the ones the site doesn't hold yet, `pull` fetches only the ones the folder lacks, and `{{ asset('assets/hero.png') }}` or `url(assets/hero.png)` in `theme.css` reaches one. With Tailwind, `src/theme.css` is the source and `theme.css` is built from it by the `dev` and `build` scripts in the folder's `package.json`. A new theme's Tailwind classes carry the prefix `tw:` (`tw:flex`, `tw:md:grid`), because Tailwind scans the templates for class names and a class of your own called `container` or `hidden` would otherwise silently take Tailwind's rules; a theme made with an earlier CLI has no prefix, and gets one by adding `prefix(tw)` to both `@import` lines in `src/theme.css` and to its Tailwind classes. `cabin theme dev` runs `dev` beside the watcher, and `push` runs `build` first; a `push` made while `dev` is running is remembered by both. A folder with no scripts is synced as it is.
37
37
 
38
38
  | Command | What it does |
39
39
  | --- | --- |
40
- | `cabin login [--token]` | Keep a token for a host and site. The host defaults to https://app.cabincms.com. `logout` forgets it; `whoami` says who it is. |
40
+ | `cabin login [--token]` | Sign in through the browser, which reaches every site you're on, or keep a management token for one site. The host defaults to https://app.cabincms.com. `whoami` says who you are and lists your sites; `logout` signs out (`--site` forgets one site's token). |
41
41
  | `cabin theme init [dir] [--from blank\|birch] [--site] [--name] [--key] [--no-tailwind]` | Make a theme on a site and write it into a folder. Asks for the site and name when they aren't given. |
42
42
  | `cabin theme list` | The site's themes, with a star on the one the site is drawn with. |
43
43
  | `cabin theme pull [--theme key] [--version id] [--all]` | Take the current (or a named) version's files. `theme.css` is skipped when `src/theme.css` exists, unless `--all`. |
@@ -2,7 +2,8 @@ import { join } from 'node:path';
2
2
  import { readText, writeText } from '../io/fs.js';
3
3
  import { ApiClient } from '../lib/api.js';
4
4
  import { CONFIG_FILE, DEFAULT_HOST, normalizeHost, parseConfig, parseState, STATE_FILE, serializeState, } from '../lib/config.js';
5
- import { credentialsDir, parseCredentials, pick } from '../lib/credentials.js';
5
+ import { credentialsDir, keepSignIn, parseCredentials, pick, serializeCredentials, signInFor, } from '../lib/credentials.js';
6
+ import { isDue, OauthRefused, refreshTokens } from '../lib/oauth.js';
6
7
  export class Refused extends Error {
7
8
  }
8
9
  /** Read `cabin.json` from the working directory, or refuse. */
@@ -15,29 +16,97 @@ export async function project(io) {
15
16
  if ('error' in config) {
16
17
  throw new Refused(config.error);
17
18
  }
18
- const token = await tokenFor(io, config.host, config.site);
19
+ const auth = await authFor(io, config.host, config.site);
19
20
  const state = parseState(await readText(join(io.cwd, STATE_FILE)));
20
21
  return {
21
22
  config,
22
23
  state,
23
- api: new ApiClient(config.host, token, io.fetch),
24
+ api: new ApiClient(config.host, auth, io.fetch),
24
25
  root: io.cwd,
25
26
  saveState: (next) => writeText(join(io.cwd, STATE_FILE), serializeState(next)),
26
27
  updateState: async (change) => writeText(join(io.cwd, STATE_FILE), serializeState(change(parseState(await readText(join(io.cwd, STATE_FILE)))))),
27
28
  };
28
29
  }
29
- /** The token kept for a host and site, or refuse with what to do. */
30
- export async function tokenFor(io, host, site) {
30
+ /** Where the credentials file is. */
31
+ export function credentialsFile(io) {
32
+ return join(credentialsDir(io.env, io.home), 'credentials.json');
33
+ }
34
+ export async function readCredentials(io) {
35
+ return parseCredentials(await readText(credentialsFile(io)));
36
+ }
37
+ /**
38
+ * Change the credentials file, starting from what it holds now, since
39
+ * another `cabin` may have written it meanwhile. It is only ever readable
40
+ * by its owner.
41
+ */
42
+ export async function updateCredentials(io, change) {
43
+ await writeText(credentialsFile(io), serializeCredentials(change(await readCredentials(io))), 0o600);
44
+ }
45
+ /**
46
+ * How to call a host for one of its sites: `CABIN_TOKEN`, else the person
47
+ * signed in through the browser on the host (refreshed when it is due),
48
+ * else a token kept for that site; or refuse with what to do.
49
+ */
50
+ export async function authFor(io, host, site) {
31
51
  const envToken = io.env.CABIN_TOKEN;
32
52
  if (envToken) {
33
- return envToken;
53
+ return { token: envToken };
54
+ }
55
+ const credentials = await readCredentials(io);
56
+ const signedIn = signInFor(credentials, host);
57
+ if (signedIn !== null) {
58
+ return signedInAuth(io, host, signedIn, site);
34
59
  }
35
- const credentials = parseCredentials(await readText(join(credentialsDir(io.env, io.home), 'credentials.json')));
36
60
  const kept = pick(credentials, host, site);
37
61
  if (kept === null) {
38
- throw new Refused(`No token is kept for ${site} on ${host}. Run cabin login${host === DEFAULT_HOST ? '' : ` with CABIN_HOST=${host}`}.`);
62
+ throw new Refused(`You aren't signed in to ${host}. Run cabin login${host === DEFAULT_HOST ? '' : ` with CABIN_HOST=${host}`}.`);
63
+ }
64
+ return { token: kept.token };
65
+ }
66
+ /**
67
+ * Call a host as the person signed in there: for one site, named by
68
+ * `Cabin-Site`, or, with none, to ask about their sites.
69
+ */
70
+ export async function signedInAuth(io, host, signedIn, site) {
71
+ let held = isDue(signedIn.expiresAt, io.now())
72
+ ? await refreshSignIn(io, host, signedIn)
73
+ : signedIn;
74
+ return {
75
+ token: held.accessToken,
76
+ ...(site === undefined ? {} : { site }),
77
+ refresh: async () => {
78
+ held = await refreshSignIn(io, host, held);
79
+ return held.accessToken;
80
+ },
81
+ };
82
+ }
83
+ /**
84
+ * Trade a sign-in's refresh token for new tokens, and keep them. Cabin ends
85
+ * a refresh token once it is used, so when two `cabin`s refresh at once
86
+ * (`theme dev` and `theme push`), the one that loses finds the other's new
87
+ * tokens in the file and uses those.
88
+ */
89
+ async function refreshSignIn(io, host, held) {
90
+ try {
91
+ const tokens = await refreshTokens(host, io.fetch, held.refreshToken, io.now());
92
+ const fresh = {
93
+ ...held,
94
+ ...tokens,
95
+ savedAt: new Date(io.now()).toISOString(),
96
+ };
97
+ await updateCredentials(io, (current) => keepSignIn(current, host, fresh));
98
+ return fresh;
99
+ }
100
+ catch (error) {
101
+ if (!(error instanceof OauthRefused)) {
102
+ throw error;
103
+ }
104
+ const now = signInFor(await readCredentials(io), host);
105
+ if (now !== null && now.refreshToken !== held.refreshToken) {
106
+ return now;
107
+ }
108
+ throw new Refused(`Your sign-in to ${host} has ended. Run cabin login${host === DEFAULT_HOST ? '' : ` with CABIN_HOST=${host}`}.`);
39
109
  }
40
- return kept.token;
41
110
  }
42
111
  /** The host named by CABIN_HOST, if any. */
43
112
  export function hostFrom(io) {
@@ -1,24 +1,93 @@
1
+ import { randomBytes } from 'node:crypto';
1
2
  import { join } from 'node:path';
2
- import { readText, writeText } from '../io/fs.js';
3
+ import { readText } from '../io/fs.js';
3
4
  import { ApiClient, ApiFailed } from '../lib/api.js';
4
5
  import { flag } from '../lib/args.js';
5
6
  import { CONFIG_FILE, DEFAULT_HOST, parseConfig } from '../lib/config.js';
6
- import { credentialsDir, drop, looksLikeToken, parseCredentials, put, serializeCredentials, } from '../lib/credentials.js';
7
- import { hostFrom, Refused, tokenFor } from './context.js';
8
- /** The host to sign in to: the flag or CABIN_HOST, then cabin.json, then Cabin's own. */
9
- async function loginHost(io) {
10
- const fromProject = parseConfig((await readText(join(io.cwd, CONFIG_FILE))) ?? '');
11
- return (hostFrom(io) ??
12
- ('error' in fromProject ? null : fromProject.host) ??
13
- DEFAULT_HOST);
7
+ import { drop, forgetSignIn, keepSignIn, looksLikeToken, pick, put, signInFor, } from '../lib/credentials.js';
8
+ import { APPROVE_WITHIN_MS, authorizeUrl, base64url, callbackPage, exchangeCode, pkce, readCallback, takesBrowserSignIn, } from '../lib/oauth.js';
9
+ import { authFor, hostFrom, Refused, readCredentials, signedInAuth, updateCredentials, } from './context.js';
10
+ /** The folder's `cabin.json`, when there is a good one. */
11
+ async function folderConfig(io) {
12
+ const json = await readText(join(io.cwd, CONFIG_FILE));
13
+ const config = json === null ? null : parseConfig(json);
14
+ return config === null || 'error' in config ? null : config;
14
15
  }
15
- /** Keep a token for a host and the site it names. */
16
+ /** The host to work with: CABIN_HOST, then cabin.json, then Cabin's own. */
17
+ async function hostFor(io) {
18
+ return hostFrom(io) ?? (await folderConfig(io))?.host ?? DEFAULT_HOST;
19
+ }
20
+ /**
21
+ * Sign in to a host: through the browser, which reaches every site the
22
+ * person is on there, or with a management token given by `--token` or
23
+ * `CABIN_TOKEN`, which reaches one. A Cabin that doesn't take signing in
24
+ * through the browser yet is asked for a token instead.
25
+ */
16
26
  export async function login(parsed, io) {
17
- const host = await loginHost(io);
18
- let token = flag(parsed, 'token') ?? io.env.CABIN_TOKEN ?? '';
19
- if (token === '') {
20
- token = (await io.prompt('Paste a management token from Site settings › API tokens: ', true)).trim();
27
+ const host = await hostFor(io);
28
+ const given = flag(parsed, 'token') ?? io.env.CABIN_TOKEN ?? '';
29
+ if (given !== '') {
30
+ return keepToken(io, host, given);
31
+ }
32
+ if (!(await takesBrowserSignIn(host, io.fetch))) {
33
+ io.err(`${host} doesn't take signing in through the browser yet, so it needs a token.`);
34
+ return keepToken(io, host, (await io.prompt('Paste a management token from Site settings › API tokens: ', true)).trim());
35
+ }
36
+ return signInThroughBrowser(io, host);
37
+ }
38
+ /**
39
+ * Send the person to Cabin to approve the CLI, and wait at a loopback
40
+ * address for the browser to come back with a code to trade for tokens.
41
+ */
42
+ async function signInThroughBrowser(io, host) {
43
+ const state = base64url(randomBytes(16));
44
+ const { verifier, challenge } = pkce(randomBytes(32));
45
+ const loopback = await io.listen((url) => callbackPage(readCallback(url, state)));
46
+ const deadline = new AbortController();
47
+ try {
48
+ const url = authorizeUrl(host, {
49
+ redirectUri: loopback.url,
50
+ state,
51
+ challenge,
52
+ });
53
+ io.out(`Opening ${new URL(host).host} in your browser to sign in…`);
54
+ io.out(`If it didn't open, go to: ${url}`);
55
+ await io.open(url);
56
+ const came = await Promise.race([
57
+ loopback.next,
58
+ io.stopped.then(() => 'stopped'),
59
+ io
60
+ .sleep(APPROVE_WITHIN_MS, deadline.signal)
61
+ .then(() => 'late'),
62
+ ]);
63
+ if (came === 'stopped') {
64
+ throw new Refused('Stopped before signing in.');
65
+ }
66
+ if (came === 'late') {
67
+ throw new Refused('Nobody approved the sign-in in the browser. Run cabin login again, or use cabin login --token on a machine with no browser.');
68
+ }
69
+ const read = readCallback(came, state);
70
+ if ('refused' in read) {
71
+ throw new Refused(read.refused);
72
+ }
73
+ const tokens = await exchangeCode(host, io.fetch, { code: read.code, verifier, redirectUri: loopback.url }, io.now());
74
+ const answer = await new ApiClient(host, tokens.accessToken, io.fetch).sites();
75
+ await updateCredentials(io, (current) => keepSignIn(current, host, {
76
+ ...tokens,
77
+ user: answer.person,
78
+ savedAt: new Date(io.now()).toISOString(),
79
+ }));
80
+ io.out(`Signed in to ${host} as ${answer.person.name}.`);
81
+ printSites(io, answer, null);
82
+ return 0;
21
83
  }
84
+ finally {
85
+ deadline.abort();
86
+ await loopback.close();
87
+ }
88
+ }
89
+ /** Keep a management token for the site it names. */
90
+ async function keepToken(io, host, token) {
22
91
  if (!looksLikeToken(token)) {
23
92
  throw new Refused("That doesn't look like one of Cabin's tokens: they start with cabin_ and are 46 characters long.");
24
93
  }
@@ -35,40 +104,76 @@ export async function login(parsed, io) {
35
104
  if (info.kind !== 'management') {
36
105
  io.err(`This is a ${info.kind} token. The theme commands need a management token, which acts as you.`);
37
106
  }
38
- const file = join(credentialsDir(io.env, io.home), 'credentials.json');
39
- const all = put(parseCredentials(await readText(file)), host, info.site.handle, {
107
+ await updateCredentials(io, (current) => put(current, host, info.site.handle, {
40
108
  token,
41
109
  name: info.user?.name ?? info.name,
42
110
  savedAt: new Date(io.now()).toISOString(),
43
- });
44
- await writeText(file, serializeCredentials(all), 0o600);
111
+ }));
45
112
  io.out(`Signed in to ${info.site.name} (${info.site.handle}) on ${host}${info.user ? ` as ${info.user.name}` : ''}.`);
46
113
  return 0;
47
114
  }
48
- /** Forget a token. */
115
+ /** List a person's sites, marking the folder's and those whose themes they can't change. */
116
+ function printSites(io, answer, folderSite) {
117
+ if (answer.sites.length === 0) {
118
+ io.out("You aren't on any site there yet.");
119
+ return;
120
+ }
121
+ io.out('Your sites:');
122
+ for (const site of answer.sites) {
123
+ const notes = [
124
+ ...(site.handle === folderSite ? ['this folder'] : []),
125
+ ...(site.canEditThemes ? [] : ["you can't change its themes"]),
126
+ ];
127
+ io.out(` ${site.name} (${site.handle})${notes.length > 0 ? `, ${notes.join(', ')}` : ''}`);
128
+ }
129
+ }
130
+ /**
131
+ * Forget a sign-in: with `--site`, the token kept for that site; else the
132
+ * person signed in through the browser on the host, or, failing that, the
133
+ * token kept for the folder's site.
134
+ */
49
135
  export async function logout(parsed, io) {
50
- const fromProject = parseConfig((await readText(join(io.cwd, CONFIG_FILE))) ?? '');
51
- const host = hostFrom(io) ?? ('error' in fromProject ? null : fromProject.host);
52
- const site = flag(parsed, 'site') ??
53
- ('error' in fromProject ? null : fromProject.site);
54
- if (host === null || site === null) {
55
- throw new Refused("Say which to forget: cabin logout --site handle, or run it inside a theme's folder.");
136
+ const folder = await folderConfig(io);
137
+ const host = hostFrom(io) ?? folder?.host ?? DEFAULT_HOST;
138
+ const site = flag(parsed, 'site');
139
+ const credentials = await readCredentials(io);
140
+ if (site === null && signInFor(credentials, host) !== null) {
141
+ await updateCredentials(io, (current) => forgetSignIn(current, host));
142
+ io.out(`Signed out of ${host}.`);
143
+ io.out('Cabin CLI stays among your connected agents on Security settings until you disconnect it there.');
144
+ return 0;
145
+ }
146
+ const handle = site ?? folder?.site ?? null;
147
+ if (handle === null || pick(credentials, host, handle) === null) {
148
+ throw new Refused(handle === null
149
+ ? `You aren't signed in to ${host}.`
150
+ : `No token is kept for ${handle} on ${host}.`);
56
151
  }
57
- const file = join(credentialsDir(io.env, io.home), 'credentials.json');
58
- await writeText(file, serializeCredentials(drop(parseCredentials(await readText(file)), host, site)), 0o600);
59
- io.out(`Forgot the token for ${site} on ${host}.`);
152
+ await updateCredentials(io, (current) => drop(current, host, handle));
153
+ io.out(`Forgot the token for ${handle} on ${host}.`);
60
154
  return 0;
61
155
  }
62
- /** Say who the kept token is. */
156
+ /**
157
+ * Say who is signed in: the person and their sites, for a sign-in through
158
+ * the browser; the token for a site, otherwise.
159
+ */
63
160
  export async function whoami(parsed, io) {
64
- const fromProject = parseConfig((await readText(join(io.cwd, CONFIG_FILE))) ?? '');
65
- const host = hostFrom(io) ?? ('error' in fromProject ? null : fromProject.host);
66
- const site = flag(parsed, 'site') ??
67
- ('error' in fromProject ? null : fromProject.site);
68
- if (host === null || site === null) {
69
- throw new Refused("Say which: cabin whoami --site handle, or run it inside a theme's folder.");
161
+ const folder = await folderConfig(io);
162
+ const host = hostFrom(io) ?? folder?.host ?? DEFAULT_HOST;
163
+ const signedIn = io.env.CABIN_TOKEN
164
+ ? null
165
+ : signInFor(await readCredentials(io), host);
166
+ if (signedIn !== null) {
167
+ const answer = await new ApiClient(host, await signedInAuth(io, host, signedIn), io.fetch).sites();
168
+ io.out(`${answer.person.name} <${answer.person.email}> on ${host}, signed in through the browser`);
169
+ printSites(io, answer, folder?.site ?? null);
170
+ return 0;
171
+ }
172
+ const site = flag(parsed, 'site') ?? folder?.site ?? null;
173
+ if (site === null) {
174
+ throw new Refused(`You aren't signed in to ${host}. Run cabin login, or say which site's token: cabin whoami --site handle.`);
70
175
  }
71
- const info = await new ApiClient(host, await tokenFor(io, host, site), io.fetch).token_();
176
+ const info = await new ApiClient(host, await authFor(io, host, site), io.fetch).token_();
72
177
  io.out(`${info.site.name} (${info.site.handle}) on ${host}${info.site.url ? `, at ${info.site.url}` : ''}`);
73
178
  io.out(info.user
74
179
  ? `${info.user.name} <${info.user.email}>, through the ${info.kind} token "${info.name}"`
@@ -5,7 +5,7 @@ import { paint, syncedLine, wantsColor } from '../../lib/output.js';
5
5
  import { problemLines } from '../../lib/problems.js';
6
6
  import { binariesFor, blobKey, heldBlobs, isSkipped, isSynced, toThemePath, } from '../../lib/theme-files.js';
7
7
  import { backoff, Debounce } from '../../lib/watch.js';
8
- import { project } from '../context.js';
8
+ import { project, Refused } from '../context.js';
9
9
  import { filesIn, picturesIn, scriptIn } from './sync.js';
10
10
  /**
11
11
  * Keep a draft of the folder on the site as it changes: the theme's `dev`
@@ -61,8 +61,13 @@ export async function dev(parsed, io) {
61
61
  if (error instanceof ApiFailed &&
62
62
  (error.status === 401 || error.status === 403)) {
63
63
  io.err(error.status === 401
64
- ? 'The token was refused. Run cabin login.'
65
- : `This token can't manage themes on ${config.site}.`);
64
+ ? `${config.host} refused your sign-in. Run cabin login.`
65
+ : `You can't change the themes of ${config.site}.`);
66
+ stopped = true;
67
+ return false;
68
+ }
69
+ if (error instanceof Refused) {
70
+ io.err(error.message);
66
71
  stopped = true;
67
72
  return false;
68
73
  }
@@ -1,13 +1,13 @@
1
1
  import { join, resolve } from 'node:path';
2
- import { exists, readText, writeText } from '../../io/fs.js';
2
+ import { exists, writeText } from '../../io/fs.js';
3
3
  import { ApiClient, ApiFailed } from '../../lib/api.js';
4
4
  import { flag, has } from '../../lib/args.js';
5
5
  import { parseChoice } from '../../lib/choose.js';
6
6
  import { CONFIG_FILE, DEFAULT_HOST, serializeState } from '../../lib/config.js';
7
- import { credentialsDir, parseCredentials, sitesOn, } from '../../lib/credentials.js';
7
+ import { signInFor, sitesOn } from '../../lib/credentials.js';
8
8
  import { problemLines } from '../../lib/problems.js';
9
9
  import { scaffold } from '../../lib/scaffold.js';
10
- import { hostFrom, Refused, tokenFor } from '../context.js';
10
+ import { authFor, hostFrom, Refused, readCredentials, signedInAuth, } from '../context.js';
11
11
  /** A key from a name: lowercase letters, digits and hyphens, starting with a letter. */
12
12
  export function keyFrom(name) {
13
13
  const key = name
@@ -20,35 +20,20 @@ export function keyFrom(name) {
20
20
  }
21
21
  /**
22
22
  * The site to make the theme on: the flag or CABIN_SITE, else one of the
23
- * sites a token is kept for on the host, asked for when there are several.
24
- * The API names a token's site but lists no others, so the list is the
25
- * kept tokens, each asked for its site's name.
23
+ * person's sites, asked for when there are several. Signed in through the
24
+ * browser, they are every site the person is on where they may change its
25
+ * themes; otherwise, the sites a token is kept for, each asked its name.
26
26
  */
27
27
  async function chooseSite(parsed, io, host) {
28
28
  const given = flag(parsed, 'site') ?? io.env.CABIN_SITE ?? null;
29
29
  if (given !== null) {
30
30
  return given;
31
31
  }
32
- const credentials = parseCredentials(await readText(join(credentialsDir(io.env, io.home), 'credentials.json')));
33
- const handles = sitesOn(credentials, host);
34
- if (handles.length === 0) {
35
- throw new Refused(`You aren't signed in to a site on ${host}. Run cabin login first.`);
36
- }
37
- const found = await Promise.all(handles.map(async (handle) => {
38
- const token = credentials.hosts[host]?.[handle]?.token ?? '';
39
- try {
40
- const info = await new ApiClient(host, token, io.fetch).token_();
41
- return { handle, name: info.site.name };
42
- }
43
- catch (error) {
44
- if (error instanceof ApiFailed && error.status === 401) {
45
- io.err(`The token for ${handle} isn't accepted any more. Run cabin login to replace it.`);
46
- return null;
47
- }
48
- throw error;
49
- }
50
- }));
51
- const sites = found.filter((site) => site !== null);
32
+ const credentials = await readCredentials(io);
33
+ const signedIn = io.env.CABIN_TOKEN ? null : signInFor(credentials, host);
34
+ const sites = signedIn === null
35
+ ? await keptSites(io, host, credentials)
36
+ : await signedInSites(io, host, signedIn);
52
37
  const [only] = sites;
53
38
  if (only === undefined) {
54
39
  throw new Refused(`No kept token is accepted by ${host}.`);
@@ -68,6 +53,43 @@ async function chooseSite(parsed, io, host) {
68
53
  }
69
54
  return chosen.handle;
70
55
  }
56
+ /** The sites the person signed in through the browser may make a theme on. */
57
+ async function signedInSites(io, host, signedIn) {
58
+ const { sites } = await new ApiClient(host, await signedInAuth(io, host, signedIn), io.fetch).sites();
59
+ const open = sites.filter((site) => site.canEditThemes);
60
+ if (sites.length === 0) {
61
+ throw new Refused(`You aren't on any site at ${host} yet.`);
62
+ }
63
+ if (open.length === 0) {
64
+ throw new Refused(`You can't change the themes of any of your sites at ${host}: that takes an Owner or Admin.`);
65
+ }
66
+ return open;
67
+ }
68
+ /**
69
+ * The sites a token is kept for on the host. The API names a token's site
70
+ * but lists no others, so each token is asked for its site's name.
71
+ */
72
+ async function keptSites(io, host, credentials) {
73
+ const handles = sitesOn(credentials, host);
74
+ if (handles.length === 0) {
75
+ throw new Refused(`You aren't signed in to a site on ${host}. Run cabin login first.`);
76
+ }
77
+ const found = await Promise.all(handles.map(async (handle) => {
78
+ const token = credentials.hosts[host]?.[handle]?.token ?? '';
79
+ try {
80
+ const info = await new ApiClient(host, token, io.fetch).token_();
81
+ return { handle, name: info.site.name };
82
+ }
83
+ catch (error) {
84
+ if (error instanceof ApiFailed && error.status === 401) {
85
+ io.err(`The token for ${handle} isn't accepted any more. Run cabin login to replace it.`);
86
+ return null;
87
+ }
88
+ throw error;
89
+ }
90
+ }));
91
+ return found.filter((site) => site !== null);
92
+ }
71
93
  /** The theme's name: the flag, else asked for, offering the folder's name. */
72
94
  async function chooseName(parsed, io, dir) {
73
95
  const given = flag(parsed, 'name');
@@ -91,7 +113,7 @@ export async function init(parsed, io) {
91
113
  }
92
114
  const host = hostFrom(io) ?? DEFAULT_HOST;
93
115
  const site = await chooseSite(parsed, io, host);
94
- const api = new ApiClient(host, await tokenFor(io, host, site), io.fetch);
116
+ const api = new ApiClient(host, await authFor(io, host, site), io.fetch);
95
117
  const name = await chooseName(parsed, io, given);
96
118
  const key = flag(parsed, 'key') ?? keyFrom(name);
97
119
  const dir = given ?? key;
package/dist/index.js CHANGED
@@ -15,7 +15,7 @@ import { push } from './commands/theme/push.js';
15
15
  import { ApiFailed } from './lib/api.js';
16
16
  import { has, parse, USAGE } from './lib/args.js';
17
17
  import { problemLines } from './lib/problems.js';
18
- const VERSION = '0.5.0';
18
+ const VERSION = '0.6.0';
19
19
  const COMMANDS = {
20
20
  login,
21
21
  logout,
@@ -0,0 +1,43 @@
1
+ import { createServer } from 'node:http';
2
+ /**
3
+ * Listen on 127.0.0.1, on a port the system picks, for the browser to come
4
+ * back from signing in. The first visit to `/callback` is answered with the
5
+ * page `answer` makes, and settles `next`; anything else is a 404.
6
+ */
7
+ export function loopback(answer) {
8
+ let arrived = () => { };
9
+ const next = new Promise((resolve) => {
10
+ arrived = resolve;
11
+ });
12
+ let done = false;
13
+ const server = createServer((request, response) => {
14
+ const url = new URL(request.url ?? '/', 'http://127.0.0.1');
15
+ if (url.pathname !== '/callback' || done) {
16
+ response.writeHead(404, { 'Content-Type': 'text/plain' });
17
+ response.end('Not found');
18
+ return;
19
+ }
20
+ done = true;
21
+ response.writeHead(200, {
22
+ 'Content-Type': 'text/html; charset=utf-8',
23
+ 'Cache-Control': 'no-store',
24
+ Connection: 'close',
25
+ });
26
+ response.end(answer(url));
27
+ arrived(url);
28
+ });
29
+ return new Promise((resolve, reject) => {
30
+ server.once('error', reject);
31
+ server.listen(0, '127.0.0.1', () => {
32
+ const { port } = server.address();
33
+ resolve({
34
+ url: `http://127.0.0.1:${port}/callback`,
35
+ next,
36
+ close: () => new Promise((closed) => {
37
+ server.close(() => closed());
38
+ server.closeAllConnections();
39
+ }),
40
+ });
41
+ });
42
+ });
43
+ }
package/dist/io/world.js CHANGED
@@ -1,6 +1,7 @@
1
1
  import { spawn as nodeSpawn } from 'node:child_process';
2
2
  import { homedir } from 'node:os';
3
3
  import { createInterface } from 'node:readline/promises';
4
+ import { loopback } from './loopback.js';
4
5
  /** The real world, for `cabin` run from a terminal. */
5
6
  export function world() {
6
7
  let stop = () => { };
@@ -55,7 +56,14 @@ export function world() {
55
56
  detached: true,
56
57
  }).unref();
57
58
  },
58
- sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
59
+ listen: loopback,
60
+ sleep: (ms, signal) => new Promise((resolve) => {
61
+ const timer = setTimeout(resolve, ms);
62
+ signal?.addEventListener('abort', () => {
63
+ clearTimeout(timer);
64
+ resolve();
65
+ }, { once: true });
66
+ }),
59
67
  now: () => Date.now(),
60
68
  stopped,
61
69
  };
package/dist/lib/api.js CHANGED
@@ -34,16 +34,19 @@ export function failureOf(status, body) {
34
34
  */
35
35
  export class ApiClient {
36
36
  host;
37
- token;
38
37
  fetchFn;
39
- constructor(host, token, fetchFn) {
38
+ auth;
39
+ constructor(host, auth, fetchFn) {
40
40
  this.host = host;
41
- this.token = token;
42
41
  this.fetchFn = fetchFn;
42
+ this.auth = typeof auth === 'string' ? { token: auth } : { ...auth };
43
43
  }
44
44
  token_() {
45
45
  return this.call('GET', '/v1/token');
46
46
  }
47
+ sites() {
48
+ return this.call('GET', '/v1/sites');
49
+ }
47
50
  themes() {
48
51
  return this.call('GET', '/v1/themes');
49
52
  }
@@ -91,26 +94,20 @@ export class ApiClient {
91
94
  });
92
95
  return this.call('GET', `/v1/themes/${key}/context?${query.toString()}`);
93
96
  }
97
+ /**
98
+ * Send a request and read its `data`. A token that is refused (401) is
99
+ * swapped for a fresh one once, when there is a way to get one: a sign-in
100
+ * outlives its day-long token, and `theme dev` runs for longer than that.
101
+ */
94
102
  async call(method, path, body) {
95
- let response;
96
- try {
97
- const init = {
98
- method,
99
- headers: {
100
- Authorization: `Bearer ${this.token}`,
101
- Accept: 'application/json',
102
- ...(body === undefined
103
- ? {}
104
- : { 'Content-Type': 'application/json' }),
105
- },
106
- };
107
- if (body !== undefined) {
108
- init.body = JSON.stringify(body);
103
+ let response = await this.send(method, path, body);
104
+ if (response.status === 401 && this.auth.refresh !== undefined) {
105
+ const fresh = await this.auth.refresh();
106
+ if (fresh !== null) {
107
+ this.auth.token = fresh;
108
+ await response.body?.cancel();
109
+ response = await this.send(method, path, body);
109
110
  }
110
- response = await this.fetchFn(`${this.host}${path}`, init);
111
- }
112
- catch {
113
- throw failureOf(0, null);
114
111
  }
115
112
  const text = await response.text();
116
113
  let parsed = null;
@@ -125,4 +122,30 @@ export class ApiClient {
125
122
  }
126
123
  return parsed.data;
127
124
  }
125
+ async send(method, path, body) {
126
+ const init = {
127
+ method,
128
+ headers: {
129
+ Authorization: `Bearer ${this.auth.token}`,
130
+ Accept: 'application/json',
131
+ ...(this.auth.site === undefined
132
+ ? {}
133
+ : { [SITE_HEADER]: this.auth.site }),
134
+ ...(body === undefined
135
+ ? {}
136
+ : { 'Content-Type': 'application/json' }),
137
+ },
138
+ };
139
+ if (body !== undefined) {
140
+ init.body = JSON.stringify(body);
141
+ }
142
+ try {
143
+ return await this.fetchFn(`${this.host}${path}`, init);
144
+ }
145
+ catch {
146
+ throw failureOf(0, null);
147
+ }
148
+ }
128
149
  }
150
+ /** The header a request names its site with, for a person signed in through the browser. */
151
+ export const SITE_HEADER = 'Cabin-Site';
package/dist/lib/args.js CHANGED
@@ -76,7 +76,7 @@ export const USAGE = `cabin — develop a Cabin site theme locally
76
76
  cabin theme publish
77
77
  cabin theme open [--site]
78
78
 
79
- Signs in to https://app.cabincms.com.
80
- Set CABIN_HOST to use another install.
79
+ Signs in to https://app.cabincms.com through the browser.
80
+ Set CABIN_HOST to use another install, or --token where there is no browser.
81
81
 
82
82
  Exit codes: 0 done, 1 refused or problems found, 2 usage.`;
@@ -9,8 +9,9 @@ export function credentialsDir(env, home) {
9
9
  return `${home}/.config/cabin`;
10
10
  }
11
11
  export function parseCredentials(json) {
12
+ const none = { hosts: {}, signIns: {} };
12
13
  if (json === null) {
13
- return { hosts: {} };
14
+ return none;
14
15
  }
15
16
  try {
16
17
  const parsed = JSON.parse(json);
@@ -18,12 +19,22 @@ export function parseCredentials(json) {
18
19
  hosts: typeof parsed.hosts === 'object' && parsed.hosts !== null
19
20
  ? parsed.hosts
20
21
  : {},
22
+ signIns: readSignIns(parsed.signIns),
21
23
  };
22
24
  }
23
25
  catch {
24
- return { hosts: {} };
26
+ return none;
25
27
  }
26
28
  }
29
+ /** The sign-ins a file holds, leaving out any that can't be used. */
30
+ function readSignIns(given) {
31
+ if (typeof given !== 'object' || given === null) {
32
+ return {};
33
+ }
34
+ return Object.fromEntries(Object.entries(given).filter(([, signIn]) => typeof signIn?.accessToken === 'string' &&
35
+ typeof signIn.refreshToken === 'string' &&
36
+ typeof signIn.expiresAt === 'string'));
37
+ }
27
38
  export function serializeCredentials(credentials) {
28
39
  return `${JSON.stringify(credentials, null, 4)}\n`;
29
40
  }
@@ -32,6 +43,7 @@ export function pick(credentials, host, site) {
32
43
  }
33
44
  export function put(credentials, host, site, credential) {
34
45
  return {
46
+ ...credentials,
35
47
  hosts: {
36
48
  ...credentials.hosts,
37
49
  [host]: { ...(credentials.hosts[host] ?? {}), [site]: credential },
@@ -48,7 +60,22 @@ export function drop(credentials, host, site) {
48
60
  else {
49
61
  hosts[host] = forHost;
50
62
  }
51
- return { hosts };
63
+ return { ...credentials, hosts };
64
+ }
65
+ /** Who is signed in through the browser on a host, if anyone. */
66
+ export function signInFor(credentials, host) {
67
+ return credentials.signIns[host] ?? null;
68
+ }
69
+ export function keepSignIn(credentials, host, signIn) {
70
+ return {
71
+ ...credentials,
72
+ signIns: { ...credentials.signIns, [host]: signIn },
73
+ };
74
+ }
75
+ export function forgetSignIn(credentials, host) {
76
+ const signIns = { ...credentials.signIns };
77
+ delete signIns[host];
78
+ return { ...credentials, signIns };
52
79
  }
53
80
  /** Whether a string looks like one of Cabin's tokens. */
54
81
  export function looksLikeToken(token) {
@@ -0,0 +1,180 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { failureOf } from './api.js';
3
+ /**
4
+ * Signing in through the browser: OAuth 2.1 with Cabin's own client, the
5
+ * authorization code with PKCE, sent back to a loopback address the CLI
6
+ * listens on. The token is the person, on every site they are on, so each
7
+ * request names its site with `Cabin-Site`.
8
+ */
9
+ /** Cabin CLI, the client every Cabin makes for this tool. */
10
+ export const CLI_CLIENT = 'b9a719b1-9b60-49a0-bd1b-fa4938f836a8';
11
+ /** What the CLI asks to do: work on the person's sites' themes. */
12
+ export const SCOPE = 'themes';
13
+ /** How long to wait for the person to approve in the browser. */
14
+ export const APPROVE_WITHIN_MS = 5 * 60_000;
15
+ /** A sign-in is refreshed when it has less than this left. */
16
+ const REFRESH_MARGIN_MS = 60_000;
17
+ /** The token endpoint refused, in OAuth's own shape (`invalid_grant`…). */
18
+ export class OauthRefused extends Error {
19
+ status;
20
+ code;
21
+ constructor(status, code, message) {
22
+ super(message);
23
+ this.status = status;
24
+ this.code = code;
25
+ }
26
+ }
27
+ export function base64url(bytes) {
28
+ return Buffer.from(bytes).toString('base64url');
29
+ }
30
+ /** A PKCE verifier from random bytes, and its S256 challenge. */
31
+ export function pkce(random) {
32
+ const verifier = base64url(random);
33
+ return {
34
+ verifier,
35
+ challenge: createHash('sha256').update(verifier).digest('base64url'),
36
+ };
37
+ }
38
+ /** Where to send the person to approve the CLI. */
39
+ export function authorizeUrl(host, given) {
40
+ const query = new URLSearchParams({
41
+ client_id: CLI_CLIENT,
42
+ redirect_uri: given.redirectUri,
43
+ response_type: 'code',
44
+ scope: SCOPE,
45
+ state: given.state,
46
+ code_challenge: given.challenge,
47
+ code_challenge_method: 'S256',
48
+ });
49
+ return `${host}/oauth/authorize?${query.toString()}`;
50
+ }
51
+ /**
52
+ * What the browser came back with: a code, or why there is none. A state
53
+ * that isn't the one sent is another sign-in's, and is refused.
54
+ */
55
+ export function readCallback(url, state) {
56
+ if (url.searchParams.get('state') !== state) {
57
+ return {
58
+ refused: 'The browser came back from another sign-in. Run cabin login again.',
59
+ };
60
+ }
61
+ const error = url.searchParams.get('error');
62
+ if (error === 'access_denied') {
63
+ return { refused: 'You cancelled signing in.' };
64
+ }
65
+ if (error !== null) {
66
+ return {
67
+ refused: `Cabin refused to sign you in: ${url.searchParams.get('error_description') ?? error}`,
68
+ };
69
+ }
70
+ const code = url.searchParams.get('code');
71
+ return code === null || code === ''
72
+ ? {
73
+ refused: 'The browser came back without a code. Run cabin login again.',
74
+ }
75
+ : { code };
76
+ }
77
+ /** The page the browser is shown when it comes back to the CLI: what the CLI made of it. */
78
+ export function callbackPage(read) {
79
+ const words = 'code' in read
80
+ ? 'Signed in to Cabin. You can close this tab and go back to the terminal.'
81
+ : `${read.refused} You can close this tab.`;
82
+ return `<!doctype html><html lang="en"><meta charset="utf-8"><title>Cabin CLI</title><body style="font:16px/1.5 system-ui,sans-serif;margin:4rem auto;max-width:32rem;padding:0 1rem"><p>${escapeHtml(words)}</p></body></html>`;
83
+ }
84
+ /** Text made safe to put in a page: a refusal can carry words from the address. */
85
+ function escapeHtml(text) {
86
+ return text.replace(/[&<>"']/g, (character) => ({
87
+ '&': '&amp;',
88
+ '<': '&lt;',
89
+ '>': '&gt;',
90
+ '"': '&quot;',
91
+ "'": '&#39;',
92
+ })[character] ?? character);
93
+ }
94
+ /** Read the token endpoint's answer, or null when it isn't one. */
95
+ export function tokensFrom(answer, now) {
96
+ const given = answer;
97
+ if (typeof given?.access_token !== 'string' ||
98
+ typeof given.refresh_token !== 'string' ||
99
+ typeof given.expires_in !== 'number') {
100
+ return null;
101
+ }
102
+ return {
103
+ accessToken: given.access_token,
104
+ refreshToken: given.refresh_token,
105
+ expiresAt: new Date(now + given.expires_in * 1000).toISOString(),
106
+ };
107
+ }
108
+ /** Whether a sign-in's access token has run out, or nearly. */
109
+ export function isDue(expiresAt, now) {
110
+ const at = Date.parse(expiresAt);
111
+ return Number.isNaN(at) || at - now < REFRESH_MARGIN_MS;
112
+ }
113
+ /** Trade the code the browser came back with for tokens. */
114
+ export function exchangeCode(host, fetchFn, given, now) {
115
+ return tokenRequest(host, fetchFn, {
116
+ grant_type: 'authorization_code',
117
+ client_id: CLI_CLIENT,
118
+ code: given.code,
119
+ redirect_uri: given.redirectUri,
120
+ code_verifier: given.verifier,
121
+ }, now);
122
+ }
123
+ /** Trade a refresh token for new tokens. Cabin ends the old one. */
124
+ export function refreshTokens(host, fetchFn, refreshToken, now) {
125
+ return tokenRequest(host, fetchFn, {
126
+ grant_type: 'refresh_token',
127
+ client_id: CLI_CLIENT,
128
+ refresh_token: refreshToken,
129
+ scope: SCOPE,
130
+ }, now);
131
+ }
132
+ /**
133
+ * Whether a host takes signing in through the browser: an older Cabin has
134
+ * no `/v1/sites`, and answers 404 where a newer one asks for a token.
135
+ */
136
+ export async function takesBrowserSignIn(host, fetchFn) {
137
+ let response;
138
+ try {
139
+ response = await fetchFn(`${host}/v1/sites`, {
140
+ headers: { Accept: 'application/json' },
141
+ });
142
+ }
143
+ catch {
144
+ throw failureOf(0, null);
145
+ }
146
+ await response.body?.cancel();
147
+ return response.status !== 404;
148
+ }
149
+ async function tokenRequest(host, fetchFn, form, now) {
150
+ let response;
151
+ try {
152
+ response = await fetchFn(`${host}/oauth/token`, {
153
+ method: 'POST',
154
+ headers: {
155
+ Accept: 'application/json',
156
+ 'Content-Type': 'application/x-www-form-urlencoded',
157
+ },
158
+ body: new URLSearchParams(form).toString(),
159
+ });
160
+ }
161
+ catch {
162
+ throw failureOf(0, null);
163
+ }
164
+ let answer = null;
165
+ try {
166
+ answer = await response.json();
167
+ }
168
+ catch {
169
+ answer = null;
170
+ }
171
+ const tokens = response.ok ? tokensFrom(answer, now) : null;
172
+ if (tokens === null) {
173
+ const given = answer;
174
+ const code = typeof given?.error === 'string' ? given.error : 'http_error';
175
+ throw new OauthRefused(response.status, code, typeof given?.error_description === 'string'
176
+ ? given.error_description
177
+ : `The server answered ${response.status}.`);
178
+ }
179
+ return tokens;
180
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@politelabs/cabin-cli",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "description": "Develop a Cabin site theme locally: init, dev, push, pull, check, publish.",
5
5
  "license": "MIT",
6
6
  "repository": {