loaner-sdk 0.3.0 → 0.5.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,175 @@
1
+ import { CliError, EXIT } from './mcp.js';
2
+ /** Flags every command takes, with whether they take a value (the kit's `CLI_GLOBAL_FLAGS`; a kit test keeps them equal). */
3
+ export const GLOBAL_FLAGS = {
4
+ json: { value: false, about: 'Print the JSON answer; `--json id,name` keeps those fields' },
5
+ yes: { value: false, about: 'Confirm a destructive command without asking' },
6
+ 'dry-run': { value: false, about: 'Print the call it would make, and stop' },
7
+ input: { value: true, about: 'Read the arguments as a JSON object: `-` for stdin, or a file' },
8
+ timeout: { value: true, about: 'Seconds to wait; passed to the tool when it takes a timeout' },
9
+ profile: { value: true, about: 'The signed-in deployment to use' },
10
+ help: { value: false, about: 'Show the arguments and examples' },
11
+ };
12
+ /** What a resource's command takes besides its template variables (the kit's `CLI_RESOURCE_FLAGS`). */
13
+ export const RESOURCE_FLAGS = {
14
+ out: { value: true, about: 'Write the file part here' },
15
+ };
16
+ const FIELDS = /^[A-Za-z_$][\w$.-]*(,[A-Za-z_$][\w$.-]*)*$/;
17
+ /** Global flags written before the command (`--profile work mail list`) set apart, so the command's words come first. */
18
+ export const splitLeadingFlags = (argv) => {
19
+ const leading = [];
20
+ let index = 0;
21
+ for (; index < argv.length; index++) {
22
+ const token = argv[index];
23
+ const name = token.replace(/^--?/, '').split('=')[0];
24
+ if (!token.startsWith('-') || !(GLOBAL_FLAGS[name] || token === '-h' || token === '-y'))
25
+ break;
26
+ leading.push(token);
27
+ if (GLOBAL_FLAGS[name]?.value && !token.includes('='))
28
+ leading.push(argv[++index] ?? '');
29
+ }
30
+ return { leading, words: argv.slice(index) };
31
+ };
32
+ const usage = (message) => new CliError(message, EXIT.usage);
33
+ const coerce = (flag, raw, label) => {
34
+ if (flag.type === 'object')
35
+ throw usage(`${label} is an object: give it inside the JSON of \`--input -\``);
36
+ if (flag.type === 'boolean') {
37
+ if (/^(true|yes|1)$/i.test(raw))
38
+ return true;
39
+ if (/^(false|no|0)$/i.test(raw))
40
+ return false;
41
+ throw usage(`${label} is true or false, not "${raw}"`);
42
+ }
43
+ if (flag.type === 'number' || flag.type === 'integer') {
44
+ const value = Number(raw);
45
+ if (raw.trim() === '' || Number.isNaN(value) || (flag.type === 'integer' && !Number.isInteger(value)))
46
+ throw usage(`${label} is ${flag.type === 'integer' ? 'a whole number' : 'a number'}, not "${raw}"`);
47
+ return value;
48
+ }
49
+ if (flag.enum && !flag.enum.includes(raw))
50
+ throw usage(`${label} is one of ${flag.enum.join(', ')}, not "${raw}"`);
51
+ return raw;
52
+ };
53
+ /** A command's arguments and the global flags, from the words after the command. */
54
+ export const parseArguments = (command, tokens) => {
55
+ const byName = new Map();
56
+ for (const flag of command.flags) {
57
+ byName.set(flag.name, flag);
58
+ byName.set(flag.key, flag);
59
+ }
60
+ const globals = { yes: false, dryRun: false, help: false };
61
+ const values = {};
62
+ const bare = [];
63
+ const set = (flag, value) => {
64
+ values[flag.key] = flag.multiple ? [...(values[flag.key] ?? []), value] : value;
65
+ };
66
+ for (let index = 0; index < tokens.length; index++) {
67
+ const token = tokens[index];
68
+ if (token === '--') {
69
+ bare.push(...tokens.slice(index + 1));
70
+ break;
71
+ }
72
+ if (token === '-h') {
73
+ globals.help = true;
74
+ continue;
75
+ }
76
+ if (token === '-y') {
77
+ globals.yes = true;
78
+ continue;
79
+ }
80
+ if (!token.startsWith('--') || token === '-') {
81
+ bare.push(token);
82
+ continue;
83
+ }
84
+ const [name = '', inline] = token.slice(2).split(/=(.*)/s);
85
+ const next = () => {
86
+ if (inline !== undefined)
87
+ return inline;
88
+ const value = tokens[index + 1];
89
+ if (value === undefined)
90
+ throw usage(`--${name} needs a value`);
91
+ index++;
92
+ return value;
93
+ };
94
+ const flag = byName.get(name);
95
+ if (flag) {
96
+ if (flag.type === 'boolean' && inline === undefined)
97
+ set(flag, true);
98
+ else
99
+ set(flag, coerce(flag, next(), `--${flag.name}`));
100
+ if (name === 'timeout')
101
+ globals.timeout = Number(values[flag.key]);
102
+ continue;
103
+ }
104
+ const negated = name.startsWith('no-') ? byName.get(name.slice(3)) : undefined;
105
+ if (negated?.type === 'boolean' && !negated.multiple) {
106
+ set(negated, false);
107
+ continue;
108
+ }
109
+ // A list flag negated sends an empty list (`--no-allow-from` → `[]`)
110
+ if (negated?.multiple) {
111
+ values[negated.key] = [];
112
+ continue;
113
+ }
114
+ switch (name) {
115
+ case 'json': {
116
+ const following = tokens[index + 1];
117
+ const needsBare = bare.length < command.positional.length;
118
+ if (inline !== undefined)
119
+ globals.json = inline ? inline.split(',') : true;
120
+ else if (following && FIELDS.test(following) && !needsBare) {
121
+ globals.json = following.split(',');
122
+ index++;
123
+ }
124
+ else
125
+ globals.json = true;
126
+ continue;
127
+ }
128
+ case 'yes':
129
+ globals.yes = true;
130
+ continue;
131
+ case 'dry-run':
132
+ globals.dryRun = true;
133
+ continue;
134
+ case 'help':
135
+ globals.help = true;
136
+ continue;
137
+ case 'input':
138
+ globals.input = next();
139
+ continue;
140
+ case 'profile':
141
+ globals.profile = next();
142
+ continue;
143
+ case 'timeout': {
144
+ const seconds = Number(next());
145
+ if (!(seconds > 0))
146
+ throw usage('--timeout is a number of seconds');
147
+ globals.timeout = seconds;
148
+ continue;
149
+ }
150
+ }
151
+ const known = command.flags.map((one) => `--${one.name}`).join(', ');
152
+ throw usage(`unknown flag --${name} for "${command.name}"${known ? `; it takes ${known}` : '; it takes no flags'}`);
153
+ }
154
+ if (bare.length > command.positional.length)
155
+ throw usage(`"${command.name}" takes ${command.positional.length ? command.positional.map((name) => `<${name}>`).join(' ') : 'no bare arguments'}, and got ${bare.map((word) => `"${word}"`).join(' ')}`);
156
+ bare.forEach((word, index) => {
157
+ const key = command.positional[index];
158
+ const flag = byName.get(key) ?? { name: key, key, type: 'string', description: '', required: true, multiple: false };
159
+ if (values[key] !== undefined)
160
+ throw usage(`<${key}> was given twice: bare and as --${flag.name}`);
161
+ set(flag, coerce(flag, word, `<${key}>`));
162
+ });
163
+ return { values, globals };
164
+ };
165
+ /** The arguments `--input` gave under the flags, then a usage error naming the first required one still missing. */
166
+ export const completeArguments = (command, values, input = {}) => {
167
+ const merged = { ...input, ...values };
168
+ for (const flag of command.flags) {
169
+ if (!flag.required || merged[flag.key] !== undefined)
170
+ continue;
171
+ const named = command.positional.includes(flag.key) ? `<${flag.key}>` : `--${flag.name}`;
172
+ throw usage(`"${command.name}" needs ${named}${flag.description ? `: ${flag.description}` : ''}`);
173
+ }
174
+ return merged;
175
+ };
@@ -0,0 +1,243 @@
1
+ /**
2
+ * Sign-in: profiles per deployment in the user's config folder (file mode 0600), the browser on this computer
3
+ * (authorization code with PKCE and a loopback redirect, RFC 8252) or the device code flow (RFC 8628) against the
4
+ * kit's OAuth server, and tokens that refresh themselves. `<PREFIX>_URL`, `<PREFIX>_API_KEY` and
5
+ * `<PREFIX>_PROFILE` override the file, for CI and agents without a browser.
6
+ */
7
+ import { spawn } from 'node:child_process';
8
+ import { createHash, randomBytes } from 'node:crypto';
9
+ import { chmodSync, existsSync, mkdirSync, openSync, closeSync, readFileSync, rmSync, statSync, writeFileSync } from 'node:fs';
10
+ import { createServer } from 'node:http';
11
+ import { hostname, homedir } from 'node:os';
12
+ import { join } from 'node:path';
13
+ import { CliError, EXIT } from './mcp.js';
14
+ /** Where the app keeps its profiles: `$XDG_CONFIG_HOME/<app>`, `%APPDATA%\<app>` on Windows, else `~/.config/<app>`. */
15
+ export const configDirOf = (app, env, platform = process.platform) => env.XDG_CONFIG_HOME ? join(env.XDG_CONFIG_HOME, app) : platform === 'win32' && env.APPDATA ? join(env.APPDATA, app) : join(homedir(), '.config', app);
16
+ /** A profile's default name: the deployment's host. */
17
+ export const profileNameOf = (url) => new URL(url).host;
18
+ export const profileStore = (dir) => {
19
+ const file = join(dir, 'profiles.json');
20
+ const lock = join(dir, 'profiles.lock');
21
+ const read = () => {
22
+ try {
23
+ return JSON.parse(readFileSync(file, 'utf8'));
24
+ }
25
+ catch {
26
+ return { profiles: {} };
27
+ }
28
+ };
29
+ const write = (profiles) => {
30
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
31
+ writeFileSync(file, `${JSON.stringify(profiles, null, 2)}\n`, { mode: 0o600 });
32
+ // The mode only applies when the file is made; keep it 0600 when it already was there
33
+ chmodSync(file, 0o600);
34
+ };
35
+ /** Runs `work` holding the lock, so two processes never send the same refresh token (that revokes the sign-in). */
36
+ const locked = async (work, sleep) => {
37
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
38
+ for (let tries = 0;; tries++) {
39
+ try {
40
+ closeSync(openSync(lock, 'wx'));
41
+ break;
42
+ }
43
+ catch {
44
+ // A lock older than half a minute was left by a process that died
45
+ if (existsSync(lock) && Date.now() - statSync(lock).mtimeMs > 30_000)
46
+ rmSync(lock, { force: true });
47
+ else if (tries > 100)
48
+ throw new CliError(`Another process holds ${lock}; delete it if none is running`, EXIT.signIn);
49
+ else
50
+ await sleep(100);
51
+ }
52
+ }
53
+ try {
54
+ return await work();
55
+ }
56
+ finally {
57
+ rmSync(lock, { force: true });
58
+ }
59
+ };
60
+ return { file, read, write, locked };
61
+ };
62
+ const DEVICE_GRANT = 'urn:ietf:params:oauth:grant-type:device_code';
63
+ const form = (fields) => ({ method: 'POST', headers: { 'content-type': 'application/x-www-form-urlencoded', accept: 'application/json' }, body: new URLSearchParams(fields).toString() });
64
+ /** What to run to sign in to `url` again, as a command: `postbox auth login https://mail.example.com`. */
65
+ const loginAgain = (app, url) => `run \`${app} auth login ${url}\` again`;
66
+ export const metadataOf = async (url, send, app) => {
67
+ const response = await send(`${url}/.well-known/oauth-authorization-server`, { headers: { accept: 'application/json' } }).catch(() => null);
68
+ if (!response?.ok)
69
+ throw new CliError(`${url} offers no OAuth sign-in (no /.well-known/oauth-authorization-server): sign in with a key instead, \`${app} auth login ${url} --with-token\` with the key on stdin`, EXIT.signIn);
70
+ return (await response.json());
71
+ };
72
+ const withTokens = (profile, tokens, now) => ({ ...profile, accessToken: tokens.access_token, refreshToken: tokens.refresh_token ?? profile.refreshToken, expiresAt: now + (tokens.expires_in ?? 3600) * 1000 });
73
+ /**
74
+ * The device code flow: registers this CLI as a public client, asks for a code, shows it on stderr, and polls until
75
+ * the owner approves it (or says no, or the code expires).
76
+ */
77
+ export const deviceLogin = async ({ url, app, send, tell, sleep, signal, now }) => {
78
+ const metadata = await metadataOf(url, send, app);
79
+ if (!metadata.device_authorization_endpoint || !metadata.registration_endpoint)
80
+ throw new CliError(`${url} has no device sign-in: sign in with a key instead (\`${app} auth login ${url} --with-token\`)`, EXIT.signIn);
81
+ const registered = await send(metadata.registration_endpoint, { method: 'POST', headers: { 'content-type': 'application/json', accept: 'application/json' }, body: JSON.stringify({ client_name: `${app} CLI on ${hostname()}`, grant_types: [DEVICE_GRANT, 'refresh_token'] }) });
82
+ if (!registered.ok)
83
+ throw new CliError(`Could not register this CLI at ${url} (${registered.status})`, EXIT.signIn);
84
+ const { client_id: clientId } = (await registered.json());
85
+ const started = await send(metadata.device_authorization_endpoint, form({ client_id: clientId, scope: 'read write' }));
86
+ if (!started.ok)
87
+ throw new CliError(`Could not start the sign-in at ${url} (${started.status})`, EXIT.signIn);
88
+ const device = (await started.json());
89
+ const code = device.user_code.length === 8 ? `${device.user_code.slice(0, 4)}-${device.user_code.slice(4)}` : device.user_code;
90
+ tell(`Open ${device.verification_uri_complete ?? device.verification_uri} and check that it shows ${code}, or type the code at ${device.verification_uri}.`);
91
+ let interval = (device.interval ?? 5) * 1000;
92
+ const until = now() + device.expires_in * 1000;
93
+ while (now() < until) {
94
+ await sleep(interval);
95
+ if (signal.aborted)
96
+ throw signal.reason instanceof CliError ? signal.reason : new CliError('Stopped.', EXIT.interrupted);
97
+ const polled = await send(metadata.token_endpoint, form({ grant_type: DEVICE_GRANT, device_code: device.device_code, client_id: clientId }));
98
+ const body = (await polled.json().catch(() => ({})));
99
+ if (polled.ok)
100
+ return withTokens({ url, clientId }, body, now());
101
+ if (body.error === 'authorization_pending')
102
+ continue;
103
+ if (body.error === 'slow_down') {
104
+ interval = (body.interval ?? interval / 1000 + 5) * 1000;
105
+ continue;
106
+ }
107
+ // The server's own words name its endpoints, for raw OAuth clients; a person here needs the command instead
108
+ if (body.error === 'access_denied')
109
+ throw new CliError('The owner said no.', EXIT.signIn);
110
+ if (body.error === 'expired_token')
111
+ throw new CliError(`The code expired before it was approved: ${loginAgain(app, url)}.`, EXIT.signIn);
112
+ if (body.error === 'invalid_grant')
113
+ throw new CliError(`The server no longer knows this code: ${loginAgain(app, url)}.`, EXIT.signIn);
114
+ throw new CliError(`Sign-in failed (${body.error ?? polled.status}): ${loginAgain(app, url)}.`, EXIT.signIn);
115
+ }
116
+ throw new CliError(`The code expired before it was approved: ${loginAgain(app, url)}.`, EXIT.signIn);
117
+ };
118
+ /**
119
+ * How this computer opens a page in its browser, or null when it can't: over SSH, or on Linux without a display.
120
+ * The address goes as one argument, never through a shell.
121
+ *
122
+ * @example
123
+ * const open = browserOpener(process.env)
124
+ * if (open) await open('https://api.example.com/oauth/authorize?…') // true once the browser was started
125
+ */
126
+ export const browserOpener = (env, platform = process.platform) => {
127
+ if (env.SSH_CONNECTION || env.SSH_TTY)
128
+ return null;
129
+ const command = platform === 'darwin' ? ['open'] : platform === 'win32' ? ['rundll32', 'url.dll,FileProtocolHandler'] : env.DISPLAY || env.WAYLAND_DISPLAY ? ['xdg-open'] : null;
130
+ if (!command)
131
+ return null;
132
+ return (url) => new Promise((done) => {
133
+ const child = spawn(command[0], [...command.slice(1), url], { stdio: 'ignore', detached: true });
134
+ child.once('error', () => done(false));
135
+ child.once('spawn', () => (child.unref(), done(true)));
136
+ });
137
+ };
138
+ const base64url = (bytes) => bytes.toString('base64url');
139
+ const page = (title, text) => `<!doctype html><meta charset="utf-8"><title>${title}</title><body style="font:16px system-ui;margin:4rem auto;max-width:32rem"><h1 style="font-size:1.4rem">${title}</h1><p>${text}</p>`;
140
+ /** Waits for the browser to come back to the loopback redirect with this sign-in's `state`; answers its code. */
141
+ const callbackOf = (server, state, signal) => new Promise((resolve, reject) => {
142
+ const stop = () => reject(signal.reason instanceof CliError ? signal.reason : new CliError('Stopped.', EXIT.interrupted));
143
+ if (signal.aborted)
144
+ return stop();
145
+ signal.addEventListener('abort', stop, { once: true });
146
+ server.on('request', (request, response) => {
147
+ const back = new URL(request.url ?? '/', 'http://127.0.0.1');
148
+ if (back.pathname !== '/callback')
149
+ return void response.writeHead(404).end();
150
+ // Another page's request, not this sign-in's answer: refused, and the sign-in goes on waiting
151
+ if (back.searchParams.get('state') !== state)
152
+ return void response.writeHead(400, { 'content-type': 'text/html; charset=utf-8' }).end(page('Not this sign-in', 'This answer is for another sign-in. Go back to the terminal.'));
153
+ const code = back.searchParams.get('code');
154
+ const done = code ? page('Signed in', 'You can close this tab and go back to the terminal.') : page('Not signed in', 'The sign-in was refused. Go back to the terminal.');
155
+ response.writeHead(code ? 200 : 403, { 'content-type': 'text/html; charset=utf-8', connection: 'close' }).end(done);
156
+ signal.removeEventListener('abort', stop);
157
+ if (code)
158
+ resolve(code);
159
+ else
160
+ reject(new CliError(back.searchParams.get('error') === 'access_denied' ? 'The owner said no.' : `Sign-in failed (${back.searchParams.get('error') ?? 'no code'}).`, EXIT.signIn));
161
+ });
162
+ });
163
+ /**
164
+ * Sign-in in the browser on this computer: registers this CLI as a public client with a loopback redirect on a free
165
+ * port, opens the server's consent page (PKCE, S256), and exchanges the code the page sends back. Answers null when
166
+ * the server has no such sign-in, so the caller can use the device flow instead. The address is printed too, for when
167
+ * no browser opens.
168
+ */
169
+ export const browserLogin = async ({ url, app, send, tell, signal, now, open }) => {
170
+ const metadata = await metadataOf(url, send, app);
171
+ if (!metadata.authorization_endpoint || !metadata.registration_endpoint)
172
+ return null;
173
+ const server = createServer();
174
+ await new Promise((listening, failed) => (server.once('error', failed), server.listen(0, '127.0.0.1', listening)));
175
+ // Ten minutes, as a device code lasts
176
+ const limit = AbortSignal.any([signal, AbortSignal.timeout(600_000)]);
177
+ try {
178
+ const redirectUri = `http://127.0.0.1:${server.address().port}/callback`;
179
+ const registered = await send(metadata.registration_endpoint, { method: 'POST', headers: { 'content-type': 'application/json', accept: 'application/json' }, body: JSON.stringify({ client_name: `${app} CLI on ${hostname()}`, redirect_uris: [redirectUri], grant_types: ['authorization_code', 'refresh_token'], token_endpoint_auth_method: 'none' }) });
180
+ if (!registered.ok)
181
+ return null;
182
+ const { client_id: clientId } = (await registered.json());
183
+ const verifier = base64url(randomBytes(32));
184
+ const state = base64url(randomBytes(16));
185
+ const authorize = new URL(metadata.authorization_endpoint);
186
+ for (const [key, value] of Object.entries({ response_type: 'code', client_id: clientId, redirect_uri: redirectUri, code_challenge: base64url(createHash('sha256').update(verifier).digest()), code_challenge_method: 'S256', state, scope: 'read write' }))
187
+ authorize.searchParams.set(key, value);
188
+ const code = callbackOf(server, state, limit);
189
+ // Handled where it is awaited, after the browser was opened; the browser may answer first
190
+ code.catch(() => undefined);
191
+ tell(`Opening ${authorize} in your browser. If none opens, open that address on this computer.`);
192
+ if (!(await open(authorize.toString())))
193
+ tell(`No browser opened: open the address above, or stop and run \`${app} auth login ${url} --device\` to approve a code from any device.`);
194
+ const given = await code.catch((error) => {
195
+ if (error instanceof CliError && error.exitCode === EXIT.interrupted && limit.aborted && !signal.aborted)
196
+ throw new CliError(`The browser never came back in ten minutes: ${loginAgain(app, url)}.`, EXIT.signIn);
197
+ throw error;
198
+ });
199
+ const exchanged = await send(metadata.token_endpoint, form({ grant_type: 'authorization_code', code: given, redirect_uri: redirectUri, client_id: clientId, code_verifier: verifier }));
200
+ const body = (await exchanged.json().catch(() => ({})));
201
+ if (!exchanged.ok)
202
+ throw new CliError(`Sign-in failed (${body.error ?? exchanged.status}): ${loginAgain(app, url)}.`, EXIT.signIn);
203
+ return withTokens({ url, clientId }, body, now());
204
+ }
205
+ finally {
206
+ server.closeAllConnections();
207
+ server.close();
208
+ }
209
+ };
210
+ /**
211
+ * A new access token from the profile's refresh token, under the lock. A token another process refreshed meanwhile is
212
+ * taken as it is; `stale` is the token a server just refused, renewed even before it expires.
213
+ */
214
+ export const refreshProfile = async ({ app, store, name, send, sleep, now, stale }) => store.locked(async () => {
215
+ const profiles = store.read();
216
+ const profile = profiles.profiles[name];
217
+ if (!profile?.refreshToken || !profile.clientId)
218
+ throw new CliError(`The sign-in for ${name} can't be renewed: ${loginAgain(app, profile?.url ?? '<url>')}`, EXIT.signIn);
219
+ const refused = stale !== undefined && profile.accessToken === stale;
220
+ if (!refused && profile.accessToken && profile.expiresAt && profile.expiresAt - 60_000 > now())
221
+ return profile;
222
+ const metadata = await metadataOf(profile.url, send, app);
223
+ const response = await send(metadata.token_endpoint, form({ grant_type: 'refresh_token', refresh_token: profile.refreshToken, client_id: profile.clientId }));
224
+ const body = (await response.json().catch(() => ({})));
225
+ if (!response.ok)
226
+ throw new CliError(`The sign-in for ${name} has ended (${body.error ?? response.status}): ${loginAgain(app, profile.url)}`, EXIT.signIn);
227
+ const renewed = withTokens(profile, body, now());
228
+ store.write({ ...profiles, profiles: { ...profiles.profiles, [name]: renewed } });
229
+ return renewed;
230
+ }, sleep);
231
+ /** Revokes a profile's refresh token, as far as the server lets it; signing out never fails on it. */
232
+ export const revokeProfile = async (profile, send, app) => {
233
+ if (!profile.refreshToken)
234
+ return;
235
+ try {
236
+ const metadata = await metadataOf(profile.url, send, app);
237
+ if (metadata.revocation_endpoint)
238
+ await send(metadata.revocation_endpoint, form({ token: profile.refreshToken, ...(profile.clientId ? { client_id: profile.clientId } : {}) }));
239
+ }
240
+ catch {
241
+ // Offline or gone: the local sign-out still happens
242
+ }
243
+ };