@unson/brainbase-mcp 0.50.23 → 0.50.25
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/contracts/brainbase-public-contract.v1.json +4 -0
- package/dist/brainbase-login.d.ts +238 -0
- package/dist/brainbase-login.js +1345 -0
- package/dist/claude-code-judgment-hook.d.ts +173 -0
- package/dist/claude-code-judgment-hook.js +1003 -0
- package/dist/cli.d.ts +1 -0
- package/dist/cli.js +714 -9
- package/dist/judgment-project-binding.d.ts +26 -0
- package/dist/judgment-project-binding.js +30 -0
- package/package.json +14 -2
|
@@ -0,0 +1,1345 @@
|
|
|
1
|
+
// `brainbase login`: a person signs in from the terminal with the Device Code
|
|
2
|
+
// Flow of their Brainbase API, and the CLI keeps the resulting person token on
|
|
3
|
+
// this machine. Hooks and commands then ask `getAccessToken` for a token
|
|
4
|
+
// instead of reading one from an environment variable; an expired token is
|
|
5
|
+
// renewed with the stored refresh token.
|
|
6
|
+
//
|
|
7
|
+
// The token is the same person JWT the Web login issues, so a hosted MCP that
|
|
8
|
+
// verifies it through the API treats it as that person. Nothing here carries a
|
|
9
|
+
// default server: the person names their own server once at login.
|
|
10
|
+
import { createHash, randomBytes, randomUUID } from 'node:crypto';
|
|
11
|
+
import { execFile } from 'node:child_process';
|
|
12
|
+
import { constants as fsConstants } from 'node:fs';
|
|
13
|
+
import { link, lstat, mkdir, open, readFile, realpath, rename, rm, stat, writeFile } from 'node:fs/promises';
|
|
14
|
+
import { homedir, hostname } from 'node:os';
|
|
15
|
+
import { basename, dirname, join, sep } from 'node:path';
|
|
16
|
+
import { promisify } from 'node:util';
|
|
17
|
+
export const CREDENTIALS_SCHEMA_VERSION = 'brainbase-credentials-v1';
|
|
18
|
+
export class BrainbaseLoginError extends Error {
|
|
19
|
+
code;
|
|
20
|
+
constructor(code, message) {
|
|
21
|
+
super(message ?? code);
|
|
22
|
+
this.code = code;
|
|
23
|
+
this.name = 'BrainbaseLoginError';
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
const REQUEST_TIMEOUT_MS = 15_000;
|
|
27
|
+
const DEFAULT_REFRESH_SKEW_MS = 60_000;
|
|
28
|
+
// A renewal holds the lock across its requests, so a waiter waits longer than
|
|
29
|
+
// they can take: a CSRF token and the refresh, asked once more when another
|
|
30
|
+
// API instance refuses the CSRF token, so up to four requests.
|
|
31
|
+
const RENEWAL_MAX_REQUESTS = 4;
|
|
32
|
+
const LOCK_WAIT_MS = RENEWAL_MAX_REQUESTS * REQUEST_TIMEOUT_MS + 5_000;
|
|
33
|
+
export function defaultCredentialsPath(env = process.env) {
|
|
34
|
+
const configured = env.BRAINBASE_CREDENTIALS_FILE?.trim();
|
|
35
|
+
if (configured)
|
|
36
|
+
return configured;
|
|
37
|
+
return join(env.HOME || homedir(), '.brainbase', 'credentials.json');
|
|
38
|
+
}
|
|
39
|
+
/**
|
|
40
|
+
* The server URL a person typed, reduced to its origin. A bearer token is only
|
|
41
|
+
* ever sent over HTTPS, or over HTTP to this machine's loopback address.
|
|
42
|
+
*/
|
|
43
|
+
export function normalizeServerUrl(value) {
|
|
44
|
+
let url;
|
|
45
|
+
try {
|
|
46
|
+
url = new URL(value.trim());
|
|
47
|
+
}
|
|
48
|
+
catch {
|
|
49
|
+
throw new BrainbaseLoginError('login_server_invalid', `Not a URL: ${value}`);
|
|
50
|
+
}
|
|
51
|
+
const loopback = ['127.0.0.1', 'localhost', '[::1]'].includes(url.hostname);
|
|
52
|
+
if (!(url.protocol === 'https:' || (url.protocol === 'http:' && loopback))) {
|
|
53
|
+
throw new BrainbaseLoginError('login_server_transport_unsafe', 'The server must use https (http is allowed only for localhost).');
|
|
54
|
+
}
|
|
55
|
+
if (url.username || url.password) {
|
|
56
|
+
throw new BrainbaseLoginError('login_server_invalid', 'The server URL must not contain a user name or password.');
|
|
57
|
+
}
|
|
58
|
+
return url.origin;
|
|
59
|
+
}
|
|
60
|
+
function defaultSleep(ms) {
|
|
61
|
+
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
62
|
+
}
|
|
63
|
+
async function readJson(response) {
|
|
64
|
+
let text;
|
|
65
|
+
try {
|
|
66
|
+
text = await response.text();
|
|
67
|
+
}
|
|
68
|
+
catch {
|
|
69
|
+
return { status: response.status, ok: response.ok, json: null, bodyLost: true };
|
|
70
|
+
}
|
|
71
|
+
let json = null;
|
|
72
|
+
try {
|
|
73
|
+
const parsed = JSON.parse(text);
|
|
74
|
+
json = parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null;
|
|
75
|
+
}
|
|
76
|
+
catch {
|
|
77
|
+
json = null;
|
|
78
|
+
}
|
|
79
|
+
return { status: response.status, ok: response.ok, json };
|
|
80
|
+
}
|
|
81
|
+
async function postJson(fetchImpl, url, body, headers = {}) {
|
|
82
|
+
const response = await fetchImpl(url, {
|
|
83
|
+
method: 'POST',
|
|
84
|
+
headers: { 'content-type': 'application/json', ...headers },
|
|
85
|
+
body: JSON.stringify(body),
|
|
86
|
+
redirect: 'error',
|
|
87
|
+
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
|
88
|
+
});
|
|
89
|
+
return readJson(response);
|
|
90
|
+
}
|
|
91
|
+
/**
|
|
92
|
+
* The Brainbase API checks a CSRF token on every POST outside the device-flow
|
|
93
|
+
* paths, `/api/auth/refresh` included. It hands one out at
|
|
94
|
+
* `GET /api/csrf-token` for the `x-session-id` sent with it, and expects both
|
|
95
|
+
* back as `x-session-id` and `x-csrf-token` (the same steps as the
|
|
96
|
+
* organization client). A server without that endpoint (404) gets no headers.
|
|
97
|
+
*/
|
|
98
|
+
async function csrfHeaders(fetchImpl, serverUrl) {
|
|
99
|
+
const sessionId = `brainbase-login-${randomUUID()}`;
|
|
100
|
+
let result;
|
|
101
|
+
try {
|
|
102
|
+
result = await readJson(await fetchImpl(`${serverUrl}/api/csrf-token`, {
|
|
103
|
+
method: 'GET',
|
|
104
|
+
headers: { 'x-session-id': sessionId },
|
|
105
|
+
redirect: 'error',
|
|
106
|
+
signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
|
|
107
|
+
}));
|
|
108
|
+
}
|
|
109
|
+
catch {
|
|
110
|
+
throw new BrainbaseLoginError('login_refresh_unreachable', `Cannot reach ${serverUrl} to renew the login.`);
|
|
111
|
+
}
|
|
112
|
+
if (result.status === 404)
|
|
113
|
+
return {};
|
|
114
|
+
const token = result.json?.token;
|
|
115
|
+
if (!result.ok || typeof token !== 'string' || !token) {
|
|
116
|
+
throw new BrainbaseLoginError('login_refresh_unavailable', 'The server could not renew the login right now. Try again.');
|
|
117
|
+
}
|
|
118
|
+
return { 'x-session-id': sessionId, 'x-csrf-token': token };
|
|
119
|
+
}
|
|
120
|
+
function isCsrfRefusal(result) {
|
|
121
|
+
const message = result.json?.message;
|
|
122
|
+
return result.status === 403 && typeof message === 'string' && /csrf/iu.test(message);
|
|
123
|
+
}
|
|
124
|
+
/** The `exp` claim of a JWT, read without verifying it (the server verifies). */
|
|
125
|
+
export function jwtExpiryMs(token) {
|
|
126
|
+
const payload = token.split('.')[1];
|
|
127
|
+
if (!payload)
|
|
128
|
+
return undefined;
|
|
129
|
+
try {
|
|
130
|
+
const claims = JSON.parse(Buffer.from(payload, 'base64url').toString('utf8'));
|
|
131
|
+
const exp = claims?.exp;
|
|
132
|
+
return typeof exp === 'number' && Number.isFinite(exp) ? exp * 1000 : undefined;
|
|
133
|
+
}
|
|
134
|
+
catch {
|
|
135
|
+
return undefined;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
function expiryIso(token, expiresInSeconds, now) {
|
|
139
|
+
const fromToken = jwtExpiryMs(token);
|
|
140
|
+
if (fromToken !== undefined)
|
|
141
|
+
return new Date(fromToken).toISOString();
|
|
142
|
+
if (typeof expiresInSeconds === 'number' && expiresInSeconds > 0) {
|
|
143
|
+
return new Date(now + expiresInSeconds * 1000).toISOString();
|
|
144
|
+
}
|
|
145
|
+
throw new BrainbaseLoginError('login_token_expiry_missing', 'The server did not say when the token expires. Nothing was saved.');
|
|
146
|
+
}
|
|
147
|
+
export async function readCredentials(path = defaultCredentialsPath()) {
|
|
148
|
+
const text = await readCredentialsText(path) ?? await readAfterSave(path) ?? await readAfterInterrupted(path);
|
|
149
|
+
return text === null ? null : parseCredentials(text, path);
|
|
150
|
+
}
|
|
151
|
+
/**
|
|
152
|
+
* A save that stopped after moving the saved login aside leaves no file at
|
|
153
|
+
* the path. Nothing would ever put it back if reads only looked at the path,
|
|
154
|
+
* so when such a file is there, the lock is taken (which rolls the save back,
|
|
155
|
+
* see finishInterrupted) and the path is read again under it.
|
|
156
|
+
*/
|
|
157
|
+
async function readAfterInterrupted(path) {
|
|
158
|
+
let target;
|
|
159
|
+
try {
|
|
160
|
+
target = await physicalPath(path);
|
|
161
|
+
}
|
|
162
|
+
catch {
|
|
163
|
+
return null;
|
|
164
|
+
}
|
|
165
|
+
if (await isFree(replacingPath(target)))
|
|
166
|
+
return null;
|
|
167
|
+
return withCredentialsLock(path, (lock) => readCredentialsText(path, lock.target));
|
|
168
|
+
}
|
|
169
|
+
/** How long a read without the lock waits for a save in progress to put its file in place. */
|
|
170
|
+
const READ_DURING_SAVE_WAIT_MS = 1000;
|
|
171
|
+
/**
|
|
172
|
+
* A save that replaces a saved login moves it aside before the new file is
|
|
173
|
+
* linked into place (see placeCredentials), so a read without the lock may
|
|
174
|
+
* find no file for a moment. When the lock is held meanwhile, this waits for
|
|
175
|
+
* it to be released and reads again; when no save holds it, nothing is there.
|
|
176
|
+
*/
|
|
177
|
+
async function readAfterSave(path) {
|
|
178
|
+
let target;
|
|
179
|
+
try {
|
|
180
|
+
target = await physicalPath(path);
|
|
181
|
+
}
|
|
182
|
+
catch {
|
|
183
|
+
return null;
|
|
184
|
+
}
|
|
185
|
+
const started = Date.now();
|
|
186
|
+
let waited = false;
|
|
187
|
+
while (await readRaw(`${target}.lock`).catch(() => null) !== null) {
|
|
188
|
+
if (Date.now() - started > READ_DURING_SAVE_WAIT_MS)
|
|
189
|
+
break;
|
|
190
|
+
waited = true;
|
|
191
|
+
await defaultSleep(10);
|
|
192
|
+
}
|
|
193
|
+
return waited ? readCredentialsText(path) : null;
|
|
194
|
+
}
|
|
195
|
+
/**
|
|
196
|
+
* The saved login's text, read from the same file that saves, locks and
|
|
197
|
+
* logout act on (see physicalPath); null when there is none. A saved login
|
|
198
|
+
* that is a symbolic link is refused, also when it is swapped in between.
|
|
199
|
+
*/
|
|
200
|
+
async function readCredentialsText(path, resolved) {
|
|
201
|
+
let target;
|
|
202
|
+
try {
|
|
203
|
+
target = resolved ?? await physicalPath(path);
|
|
204
|
+
}
|
|
205
|
+
catch (error) {
|
|
206
|
+
if (error?.code === 'ENOENT')
|
|
207
|
+
return null; // Its folder is not there.
|
|
208
|
+
throw error;
|
|
209
|
+
}
|
|
210
|
+
const read = await readRegularFile(target);
|
|
211
|
+
if (read.kind === 'missing')
|
|
212
|
+
return null;
|
|
213
|
+
if (read.kind === 'symlink')
|
|
214
|
+
throw symbolicLinkRefused(path);
|
|
215
|
+
if (read.kind === 'other')
|
|
216
|
+
throw notAFile(path);
|
|
217
|
+
return read.text;
|
|
218
|
+
}
|
|
219
|
+
/** Opening without O_NONBLOCK would wait forever on a FIFO with no writer. */
|
|
220
|
+
const READ_FLAGS = fsConstants.O_RDONLY | (fsConstants.O_NOFOLLOW ?? 0) | (fsConstants.O_NONBLOCK ?? 0);
|
|
221
|
+
/**
|
|
222
|
+
* Reads `target` only when it is a regular file. It is opened without
|
|
223
|
+
* following a symbolic link and without blocking, and its type is checked on
|
|
224
|
+
* the open handle before anything is read, so a FIFO, a device or a socket at
|
|
225
|
+
* the path never makes the command wait, and nothing swapped in between the
|
|
226
|
+
* check and the read is read instead.
|
|
227
|
+
*/
|
|
228
|
+
async function readRegularFile(target) {
|
|
229
|
+
let handle;
|
|
230
|
+
try {
|
|
231
|
+
handle = await open(target, READ_FLAGS);
|
|
232
|
+
}
|
|
233
|
+
catch (error) {
|
|
234
|
+
const code = error?.code;
|
|
235
|
+
if (code === 'ENOENT')
|
|
236
|
+
return { kind: 'missing' };
|
|
237
|
+
if (code === 'ELOOP')
|
|
238
|
+
return { kind: 'symlink' };
|
|
239
|
+
// ENXIO: a FIFO opened for writing only; other kinds are opened and refused below.
|
|
240
|
+
if (code === 'ENXIO')
|
|
241
|
+
return { kind: 'other' };
|
|
242
|
+
throw error;
|
|
243
|
+
}
|
|
244
|
+
try {
|
|
245
|
+
if (!(await handle.stat()).isFile())
|
|
246
|
+
return { kind: 'other' };
|
|
247
|
+
return { kind: 'file', text: await handle.readFile('utf8') };
|
|
248
|
+
}
|
|
249
|
+
finally {
|
|
250
|
+
await handle.close();
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
function parseCredentials(text, path) {
|
|
254
|
+
let parsed;
|
|
255
|
+
try {
|
|
256
|
+
parsed = JSON.parse(text);
|
|
257
|
+
}
|
|
258
|
+
catch {
|
|
259
|
+
throw new BrainbaseLoginError('login_credentials_invalid', `Saved login is not valid JSON: ${path}. Run brainbase login again.`);
|
|
260
|
+
}
|
|
261
|
+
const value = parsed;
|
|
262
|
+
const unusable = () => new BrainbaseLoginError('login_credentials_invalid', `Saved login is not usable: ${path}. Run brainbase login again.`);
|
|
263
|
+
if (!value || value.schema_version !== CREDENTIALS_SCHEMA_VERSION
|
|
264
|
+
|| typeof value.login_id !== 'string' || !value.login_id
|
|
265
|
+
|| typeof value.server_url !== 'string' || typeof value.access_token !== 'string' || !value.access_token
|
|
266
|
+
|| typeof value.expires_at !== 'string' || Number.isNaN(Date.parse(value.expires_at))) {
|
|
267
|
+
throw unusable();
|
|
268
|
+
}
|
|
269
|
+
// The saved server receives the refresh token, so it must pass the same
|
|
270
|
+
// transport check as the server typed at login.
|
|
271
|
+
let normalized;
|
|
272
|
+
try {
|
|
273
|
+
normalized = normalizeServerUrl(value.server_url);
|
|
274
|
+
}
|
|
275
|
+
catch {
|
|
276
|
+
throw unusable();
|
|
277
|
+
}
|
|
278
|
+
if (normalized !== value.server_url)
|
|
279
|
+
throw unusable();
|
|
280
|
+
return value;
|
|
281
|
+
}
|
|
282
|
+
export function newLoginId() {
|
|
283
|
+
return randomBytes(16).toString('hex');
|
|
284
|
+
}
|
|
285
|
+
/**
|
|
286
|
+
* Fsync on a directory: true once it is flushed, false on a platform or file
|
|
287
|
+
* system that cannot flush directories. Any other failure is an I/O error and
|
|
288
|
+
* is thrown.
|
|
289
|
+
*/
|
|
290
|
+
async function syncDirectory(directory) {
|
|
291
|
+
if (process.platform === 'win32')
|
|
292
|
+
return false; // Directories cannot be opened for fsync there.
|
|
293
|
+
const handle = await open(directory, 'r');
|
|
294
|
+
try {
|
|
295
|
+
await handle.sync();
|
|
296
|
+
return true;
|
|
297
|
+
}
|
|
298
|
+
catch (error) {
|
|
299
|
+
if (DIRECTORY_SYNC_UNSUPPORTED.has(String(error?.code)))
|
|
300
|
+
return false;
|
|
301
|
+
throw error;
|
|
302
|
+
}
|
|
303
|
+
finally {
|
|
304
|
+
await handle.close();
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
const DIRECTORY_SYNC_UNSUPPORTED = new Set(['EINVAL', 'ENOTSUP', 'EOPNOTSUPP']);
|
|
308
|
+
const DIRECTORY_OPEN_REFUSED = new Set(['EACCES', 'EPERM']);
|
|
309
|
+
/**
|
|
310
|
+
* Flushes `directory` and the directories above it that hold an entry of this
|
|
311
|
+
* user's: walking up, it flushes each directory, and stops after the first one
|
|
312
|
+
* that this user does not own (that one holds the entry of the topmost
|
|
313
|
+
* directory the user may have created). It does not matter who created a
|
|
314
|
+
* directory or when: one made by another process a moment ago, or left by a
|
|
315
|
+
* save whose flush failed, is flushed again. Returns false when some
|
|
316
|
+
* directory could not be flushed.
|
|
317
|
+
*/
|
|
318
|
+
async function syncDirectoryChain(directory) {
|
|
319
|
+
if (process.platform === 'win32')
|
|
320
|
+
return false; // Directories cannot be opened for fsync there.
|
|
321
|
+
const uid = process.getuid?.();
|
|
322
|
+
let durable = true;
|
|
323
|
+
// Callers pass the physical directory (see physicalPath), so each dirname()
|
|
324
|
+
// is the real parent: no '.', no '..', no symbolic link left to resolve.
|
|
325
|
+
for (let current = directory;; current = dirname(current)) {
|
|
326
|
+
try {
|
|
327
|
+
durable = (await syncDirectory(current)) && durable;
|
|
328
|
+
}
|
|
329
|
+
catch (error) {
|
|
330
|
+
if (!DIRECTORY_OPEN_REFUSED.has(String(error?.code)))
|
|
331
|
+
throw error;
|
|
332
|
+
durable = false;
|
|
333
|
+
}
|
|
334
|
+
if (dirname(current) === current || uid === undefined)
|
|
335
|
+
break;
|
|
336
|
+
if ((await stat(current)).uid !== uid)
|
|
337
|
+
break;
|
|
338
|
+
}
|
|
339
|
+
return durable;
|
|
340
|
+
}
|
|
341
|
+
/**
|
|
342
|
+
* The path the OS actually uses for `path`, with its directory resolved to
|
|
343
|
+
* the real one: symbolic links followed and '.' and '..' applied the way the
|
|
344
|
+
* OS applies them (a string resolve() would drop `link/..` instead). Changes
|
|
345
|
+
* and flushes then go to the same directory. The directory must exist.
|
|
346
|
+
*/
|
|
347
|
+
async function physicalPath(path) {
|
|
348
|
+
assertCredentialsFilePath(path);
|
|
349
|
+
const target = join(await realpath(dirname(path)), basename(path));
|
|
350
|
+
await assertNotSymbolicLink(target, path);
|
|
351
|
+
return target;
|
|
352
|
+
}
|
|
353
|
+
/**
|
|
354
|
+
* The saved login itself must not be a symbolic link. Reading follows a link
|
|
355
|
+
* while rename() and rm() replace or remove the link itself, so a save would
|
|
356
|
+
* split the login into two files and a logout would leave the linked file
|
|
357
|
+
* behind with its tokens. Refused before anything is read, saved or removed.
|
|
358
|
+
*/
|
|
359
|
+
async function assertNotSymbolicLink(target, path) {
|
|
360
|
+
try {
|
|
361
|
+
if ((await lstat(target)).isSymbolicLink())
|
|
362
|
+
throw symbolicLinkRefused(path);
|
|
363
|
+
}
|
|
364
|
+
catch (error) {
|
|
365
|
+
if (error?.code === 'ENOENT')
|
|
366
|
+
return;
|
|
367
|
+
throw error;
|
|
368
|
+
}
|
|
369
|
+
}
|
|
370
|
+
function symbolicLinkRefused(path) {
|
|
371
|
+
return new BrainbaseLoginError('login_credentials_path_symlink', `The saved-login path is a symbolic link: ${JSON.stringify(path)}. Give the real file with --credentials. Nothing was changed.`);
|
|
372
|
+
}
|
|
373
|
+
function notAFile(path) {
|
|
374
|
+
return new BrainbaseLoginError('login_credentials_path_invalid', `The saved-login path is not a file: ${JSON.stringify(path)}. Nothing was changed.`);
|
|
375
|
+
}
|
|
376
|
+
/**
|
|
377
|
+
* The saved login is a file, so its path must name one. `dir/` or `dir/.`
|
|
378
|
+
* would otherwise lose its last part in dirname()/basename() and point at a
|
|
379
|
+
* different file (logout would delete `dir`'s neighbour). Refused before any
|
|
380
|
+
* lock or file is touched.
|
|
381
|
+
*/
|
|
382
|
+
export function assertCredentialsFilePath(path) {
|
|
383
|
+
const name = basename(path);
|
|
384
|
+
if (!path || path.endsWith('/') || path.endsWith(sep) || name === '' || name === '.' || name === '..') {
|
|
385
|
+
throw new BrainbaseLoginError('login_credentials_path_invalid', `The saved-login path must name a file, not a folder: ${JSON.stringify(path)}. Nothing was changed.`);
|
|
386
|
+
}
|
|
387
|
+
if (RESERVED_SUFFIX.test(name)) {
|
|
388
|
+
throw new BrainbaseLoginError('login_credentials_path_invalid', `The saved-login path ends in a name brainbase keeps for the lock and for a login moved aside while saving or logging out: ${JSON.stringify(path)}. Give another file name with --credentials. Nothing was changed.`);
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
/**
|
|
392
|
+
* Names brainbase derives from another saved login's path: its lock, the
|
|
393
|
+
* login moved aside while saving or logging out, and the probe of the file
|
|
394
|
+
* system. A saved login may not be at one of these, so recovering a stopped
|
|
395
|
+
* save or logout (see finishInterrupted) never takes another saved login for
|
|
396
|
+
* the one it moved aside. Case is ignored, as on macOS and Windows file systems.
|
|
397
|
+
*/
|
|
398
|
+
const RESERVED_SUFFIX = /\.(?:lock|replacing|removing|probe-[0-9a-f]+)$/iu;
|
|
399
|
+
function sameFile(a, b) {
|
|
400
|
+
return a.dev === b.dev && a.ino === b.ino && a.size === b.size && a.mtimeNs === b.mtimeNs && a.ctimeNs === b.ctimeNs;
|
|
401
|
+
}
|
|
402
|
+
/**
|
|
403
|
+
* Fails with `login_credentials_unrecognized` (or `_unreadable`, `_path_symlink`,
|
|
404
|
+
* `_path_invalid`) unless `target` is free or holds a saved brainbase login,
|
|
405
|
+
* so a save never replaces any other file. Returns null when nothing is
|
|
406
|
+
* there, else which file was checked, so the save can make sure it replaces
|
|
407
|
+
* that same file and nothing put there after the check.
|
|
408
|
+
*/
|
|
409
|
+
async function assertReplaceable(target, path, expected) {
|
|
410
|
+
const checked = await checkedSavedLogin(target, path);
|
|
411
|
+
// Another login (or no login, or a login where there was none) was saved
|
|
412
|
+
// since the caller looked: it stays, and this save is refused.
|
|
413
|
+
if (expected !== undefined && checked.key !== expected)
|
|
414
|
+
throw changedDuringSave(path);
|
|
415
|
+
return checked.identity;
|
|
416
|
+
}
|
|
417
|
+
/**
|
|
418
|
+
* Which saved login is at `target` and which file holds it. The file is
|
|
419
|
+
* identified before and after its content is read: when both agree, the
|
|
420
|
+
* content read is that file's, not one swapped in between. Throws like
|
|
421
|
+
* savedLoginKey for a file that is no saved login.
|
|
422
|
+
*/
|
|
423
|
+
async function checkedSavedLogin(target, path) {
|
|
424
|
+
const first = await identityOf(target, path);
|
|
425
|
+
const key = await savedLoginKey(path, target);
|
|
426
|
+
if (key === null) {
|
|
427
|
+
// Nothing there: a file created later is caught by the exclusive link.
|
|
428
|
+
if (first !== null)
|
|
429
|
+
throw changedDuringSave(path);
|
|
430
|
+
return { key, identity: null };
|
|
431
|
+
}
|
|
432
|
+
const second = await identityOf(target, path);
|
|
433
|
+
if (first === null || second === null || !sameFile(first, second))
|
|
434
|
+
throw changedDuringSave(path);
|
|
435
|
+
return { key, identity: second };
|
|
436
|
+
}
|
|
437
|
+
async function identityOf(target, path) {
|
|
438
|
+
try {
|
|
439
|
+
const info = await lstat(target, { bigint: true });
|
|
440
|
+
if (info.isSymbolicLink())
|
|
441
|
+
throw symbolicLinkRefused(path);
|
|
442
|
+
if (!info.isFile())
|
|
443
|
+
throw notAFile(path);
|
|
444
|
+
return { dev: info.dev, ino: info.ino, size: info.size, mtimeNs: info.mtimeNs, ctimeNs: info.ctimeNs };
|
|
445
|
+
}
|
|
446
|
+
catch (error) {
|
|
447
|
+
if (error?.code === 'ENOENT')
|
|
448
|
+
return null;
|
|
449
|
+
throw error;
|
|
450
|
+
}
|
|
451
|
+
}
|
|
452
|
+
function changedDuringSave(path) {
|
|
453
|
+
return new BrainbaseLoginError('login_changed', `Another program created or changed ${JSON.stringify(path)} while the login was being saved. That file was left as it is and the login was not saved. Check --credentials and run the command again.`);
|
|
454
|
+
}
|
|
455
|
+
/**
|
|
456
|
+
* Puts the written `temporary` file at `target` without ever replacing a file
|
|
457
|
+
* that was not checked. When nothing was at `target` at the check (`before`
|
|
458
|
+
* is null), the file is linked into place, which fails instead of replacing a
|
|
459
|
+
* file another program created meanwhile. When a saved login was there, it is
|
|
460
|
+
* first moved aside in one step, so what is compared with `before` is exactly
|
|
461
|
+
* the file taken away; only then is the new file linked into the now empty
|
|
462
|
+
* path, again without replacing anything. A file another program put there
|
|
463
|
+
* after the check is put back where it was and `login_changed` is thrown.
|
|
464
|
+
* (rename() changes a file's ctime, so the moved file is compared by device,
|
|
465
|
+
* inode, size and mtime.) A read without the lock that finds no file in
|
|
466
|
+
* between waits for the lock (see readAfterSave).
|
|
467
|
+
*/
|
|
468
|
+
async function placeCredentials(temporary, target, path, before) {
|
|
469
|
+
if (before === null) {
|
|
470
|
+
await linkNew(temporary, target, path);
|
|
471
|
+
await rm(temporary, { force: true });
|
|
472
|
+
return;
|
|
473
|
+
}
|
|
474
|
+
const aside = replacingPath(target);
|
|
475
|
+
// A file left there would be replaced by the move below: finishInterrupted
|
|
476
|
+
// runs whenever the lock is taken, so only a file it had to keep is there.
|
|
477
|
+
await assertAsideFree(aside, path);
|
|
478
|
+
try {
|
|
479
|
+
await rename(target, aside);
|
|
480
|
+
}
|
|
481
|
+
catch (error) {
|
|
482
|
+
// Gone since the check: removed by someone else, nothing is put there.
|
|
483
|
+
if (error?.code === 'ENOENT')
|
|
484
|
+
throw changedDuringSave(path);
|
|
485
|
+
throw error;
|
|
486
|
+
}
|
|
487
|
+
const moved = await identityOf(aside, path).catch(() => null);
|
|
488
|
+
if (moved === null || moved.dev !== before.dev || moved.ino !== before.ino
|
|
489
|
+
|| moved.size !== before.size || moved.mtimeNs !== before.mtimeNs) {
|
|
490
|
+
await putBack(aside, target, path);
|
|
491
|
+
throw changedDuringSave(path);
|
|
492
|
+
}
|
|
493
|
+
try {
|
|
494
|
+
await linkNew(temporary, target, path);
|
|
495
|
+
}
|
|
496
|
+
catch (error) {
|
|
497
|
+
// A file created at the path meanwhile stays; else the checked login
|
|
498
|
+
// goes back, so a failed save leaves the old login where it was.
|
|
499
|
+
if (!(error instanceof BrainbaseLoginError && error.code === 'login_changed')) {
|
|
500
|
+
await putBack(aside, target, path);
|
|
501
|
+
}
|
|
502
|
+
else {
|
|
503
|
+
await rm(aside, { force: true });
|
|
504
|
+
}
|
|
505
|
+
throw error;
|
|
506
|
+
}
|
|
507
|
+
await rm(aside, { force: true });
|
|
508
|
+
await rm(temporary, { force: true });
|
|
509
|
+
}
|
|
510
|
+
/** Links `source` to `target`, failing with `login_changed` instead of replacing a file there. */
|
|
511
|
+
async function linkNew(source, target, path) {
|
|
512
|
+
try {
|
|
513
|
+
await link(source, target);
|
|
514
|
+
}
|
|
515
|
+
catch (error) {
|
|
516
|
+
const code = error?.code;
|
|
517
|
+
if (code === 'EEXIST')
|
|
518
|
+
throw changedDuringSave(path);
|
|
519
|
+
if (code && NO_HARD_LINK_CODES.has(code))
|
|
520
|
+
throw storageUnsupported(dirname(target), code);
|
|
521
|
+
throw error;
|
|
522
|
+
}
|
|
523
|
+
}
|
|
524
|
+
/** Puts a file moved `aside` back at `target` without replacing anything created there meanwhile. */
|
|
525
|
+
async function putBack(aside, target, path) {
|
|
526
|
+
try {
|
|
527
|
+
await link(aside, target);
|
|
528
|
+
await rm(aside, { force: true });
|
|
529
|
+
}
|
|
530
|
+
catch {
|
|
531
|
+
throw new BrainbaseLoginError('login_changed', `Another program changed ${JSON.stringify(path)} while the login was being saved, and its file could not be put back. It was kept as ${JSON.stringify(aside)}. The login was not saved.`);
|
|
532
|
+
}
|
|
533
|
+
}
|
|
534
|
+
/**
|
|
535
|
+
* Where a save puts the checked login while it links the new one in, and
|
|
536
|
+
* where a logout puts it before deleting it. The names are fixed, not random,
|
|
537
|
+
* so a save or logout that stopped half way (the process was killed, the
|
|
538
|
+
* machine lost power) leaves its file where the next holder of the lock looks
|
|
539
|
+
* (see finishInterrupted). Only the holder of the lock uses them.
|
|
540
|
+
*/
|
|
541
|
+
function replacingPath(target) {
|
|
542
|
+
return `${target}.replacing`;
|
|
543
|
+
}
|
|
544
|
+
function removingPath(target) {
|
|
545
|
+
return `${target}.removing`;
|
|
546
|
+
}
|
|
547
|
+
/** Fails with `login_changed` when a file is at `aside`, so moving a login there never replaces it. */
|
|
548
|
+
async function assertAsideFree(aside, path) {
|
|
549
|
+
try {
|
|
550
|
+
await lstat(aside);
|
|
551
|
+
}
|
|
552
|
+
catch (error) {
|
|
553
|
+
if (error?.code === 'ENOENT')
|
|
554
|
+
return;
|
|
555
|
+
throw error;
|
|
556
|
+
}
|
|
557
|
+
throw new BrainbaseLoginError('login_changed', `A file that is no saved brainbase login is at ${JSON.stringify(aside)}, where brainbase keeps a login while saving or logging out. It was left as it is and nothing was changed for ${JSON.stringify(path)}. Check that file, move it away, and run the command again.`);
|
|
558
|
+
}
|
|
559
|
+
/**
|
|
560
|
+
* What is at `aside`: a regular file holding a saved brainbase login, another
|
|
561
|
+
* regular file, something that is no regular file (a link, a folder), or
|
|
562
|
+
* nothing. It is read without following a link (see readRegularFile).
|
|
563
|
+
*/
|
|
564
|
+
async function asideKind(aside) {
|
|
565
|
+
let info;
|
|
566
|
+
try {
|
|
567
|
+
info = await lstat(aside);
|
|
568
|
+
}
|
|
569
|
+
catch (error) {
|
|
570
|
+
if (error?.code === 'ENOENT')
|
|
571
|
+
return 'missing';
|
|
572
|
+
throw error;
|
|
573
|
+
}
|
|
574
|
+
if (!info.isFile())
|
|
575
|
+
return 'other';
|
|
576
|
+
try {
|
|
577
|
+
return (await savedLoginKey(aside, aside)) === null ? 'missing' : 'login';
|
|
578
|
+
}
|
|
579
|
+
catch {
|
|
580
|
+
return 'other-file';
|
|
581
|
+
}
|
|
582
|
+
}
|
|
583
|
+
/** True when nothing is at `target`; a link or any other entry there counts as something. */
|
|
584
|
+
async function isFree(target) {
|
|
585
|
+
try {
|
|
586
|
+
await lstat(target);
|
|
587
|
+
return false;
|
|
588
|
+
}
|
|
589
|
+
catch (error) {
|
|
590
|
+
if (error?.code === 'ENOENT')
|
|
591
|
+
return true;
|
|
592
|
+
throw error;
|
|
593
|
+
}
|
|
594
|
+
}
|
|
595
|
+
/**
|
|
596
|
+
* Brings back a consistent state after a save or logout that stopped half way.
|
|
597
|
+
* Runs under the lock, right after it is taken, so it is never in the way of a
|
|
598
|
+
* save or logout that is still running.
|
|
599
|
+
*
|
|
600
|
+
* - A logout's login left at `.removing`: the logout is finished by deleting
|
|
601
|
+
* it, so a retried logout leaves no token on the machine.
|
|
602
|
+
* - A save's login left at `.replacing` with nothing at the path: the save
|
|
603
|
+
* stopped before its new file was linked in, so the old login is linked back
|
|
604
|
+
* and keeps working. With a file at the path, the save had placed its new
|
|
605
|
+
* file: the old login is deleted.
|
|
606
|
+
* - A file there that is no saved brainbase login, or no regular file, was not
|
|
607
|
+
* put there by brainbase: no saved login may be at such a name (see
|
|
608
|
+
* assertCredentialsFilePath). It is left where it is, neither moved nor
|
|
609
|
+
* deleted, and the next save or logout fails while it is there (see
|
|
610
|
+
* assertAsideFree) instead of replacing it.
|
|
611
|
+
*/
|
|
612
|
+
async function finishInterrupted(target) {
|
|
613
|
+
const done = { logoutFinished: false, saveRolledBack: false };
|
|
614
|
+
let changed = false;
|
|
615
|
+
for (const [aside, kind] of [[removingPath(target), 'logout'], [replacingPath(target), 'save']]) {
|
|
616
|
+
if (await asideKind(aside) !== 'login')
|
|
617
|
+
continue;
|
|
618
|
+
if (kind === 'save' && await isFree(target)) {
|
|
619
|
+
try {
|
|
620
|
+
await link(aside, target);
|
|
621
|
+
done.saveRolledBack = true;
|
|
622
|
+
}
|
|
623
|
+
catch (error) {
|
|
624
|
+
// Created meanwhile by another program: that file stays.
|
|
625
|
+
if (error?.code !== 'EEXIST')
|
|
626
|
+
throw error;
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
await rm(aside, { force: true });
|
|
630
|
+
if (kind === 'logout')
|
|
631
|
+
done.logoutFinished = true;
|
|
632
|
+
changed = true;
|
|
633
|
+
}
|
|
634
|
+
if (changed)
|
|
635
|
+
await syncDirectory(dirname(target));
|
|
636
|
+
return done;
|
|
637
|
+
}
|
|
638
|
+
async function folderIdentity(directory) {
|
|
639
|
+
const info = await stat(directory, { bigint: true });
|
|
640
|
+
return { dev: info.dev, ino: info.ino };
|
|
641
|
+
}
|
|
642
|
+
function sameFolder(a, b) {
|
|
643
|
+
return a.dev === b.dev && a.ino === b.ino;
|
|
644
|
+
}
|
|
645
|
+
function destinationChanged() {
|
|
646
|
+
return new BrainbaseLoginError('login_changed', 'The folder of the saved login changed while it was locked or while the login waited. Nothing was changed. Run the command again.');
|
|
647
|
+
}
|
|
648
|
+
/**
|
|
649
|
+
* Fails before anything is asked of the server or of the person when a login
|
|
650
|
+
* could not be saved to `path`: the file there is not a saved login, or the
|
|
651
|
+
* lock cannot be taken because something that is no brainbase lock is in its
|
|
652
|
+
* way. Returns where the save goes and which login is there, so the save
|
|
653
|
+
* after the approval goes to the same file and replaces the same login.
|
|
654
|
+
*/
|
|
655
|
+
export async function checkCredentialsTarget(path) {
|
|
656
|
+
return withCredentialsLock(path, async (lock) => ({
|
|
657
|
+
destination: lock.destination,
|
|
658
|
+
saved: await savedLoginKey(path, lock.target),
|
|
659
|
+
}));
|
|
660
|
+
}
|
|
661
|
+
/**
|
|
662
|
+
* Writes the file atomically: data and rename are flushed to disk, and so are
|
|
663
|
+
* the directories above it that hold this user's entries, before this
|
|
664
|
+
* returns. A new file is 0600, a new directory 0700. `durable` is false when
|
|
665
|
+
* the platform could not flush a directory, so the file may not survive a
|
|
666
|
+
* crash; a real I/O error is thrown instead.
|
|
667
|
+
*/
|
|
668
|
+
export async function writeCredentials(path, credentials, options = {}) {
|
|
669
|
+
assertCredentialsFilePath(path);
|
|
670
|
+
const { lock } = options;
|
|
671
|
+
// A save without the lock could land between another process's check and
|
|
672
|
+
// its write (a renewal's read and write-back), so it takes the lock itself.
|
|
673
|
+
if (!lock)
|
|
674
|
+
return withCredentialsLock(path, (taken) => writeCredentials(path, credentials, { ...options, lock: taken }));
|
|
675
|
+
const target = lock.target;
|
|
676
|
+
// The lock must be the one for this file: a lock taken for another path
|
|
677
|
+
// would make the write land in a file `path` does not name.
|
|
678
|
+
await lock.assertHeld();
|
|
679
|
+
if (await physicalPath(path) !== target)
|
|
680
|
+
throw destinationChanged();
|
|
681
|
+
// Only a saved login is ever replaced: a --credentials naming some other
|
|
682
|
+
// file (a config, another tool's data, a lock) is left as it is.
|
|
683
|
+
const before = await assertReplaceable(target, path, options.expected);
|
|
684
|
+
await lock.assertHeld();
|
|
685
|
+
const directory = dirname(target);
|
|
686
|
+
const temporary = `${target}.${process.pid}.${randomBytes(4).toString('hex')}.tmp`;
|
|
687
|
+
const handle = await open(temporary, 'wx', 0o600);
|
|
688
|
+
try {
|
|
689
|
+
try {
|
|
690
|
+
await handle.writeFile(`${JSON.stringify(credentials, null, 2)}\n`, 'utf8');
|
|
691
|
+
await handle.chmod(0o600);
|
|
692
|
+
await handle.sync();
|
|
693
|
+
}
|
|
694
|
+
finally {
|
|
695
|
+
await handle.close();
|
|
696
|
+
}
|
|
697
|
+
await lock.assertHeld();
|
|
698
|
+
await placeCredentials(temporary, target, path, before);
|
|
699
|
+
}
|
|
700
|
+
catch (error) {
|
|
701
|
+
// No copy of the login is left behind when the save fails.
|
|
702
|
+
await rm(temporary, { force: true });
|
|
703
|
+
throw error;
|
|
704
|
+
}
|
|
705
|
+
return { durable: await syncDirectoryChain(directory) };
|
|
706
|
+
}
|
|
707
|
+
const DEFAULT_LOCK_TIMING = { waitMs: LOCK_WAIT_MS };
|
|
708
|
+
const execFileAsync = promisify(execFile);
|
|
709
|
+
/**
|
|
710
|
+
* An identity of the start of process `pid`, so that a process id the system
|
|
711
|
+
* has handed to another process since is told apart from the holder. On Linux
|
|
712
|
+
* it is the boot id and the start time in clock ticks from /proc; elsewhere the
|
|
713
|
+
* start time `ps` reports. Null when it cannot be read, and always on Windows:
|
|
714
|
+
* a lock there is only taken over when its process id runs no process.
|
|
715
|
+
*/
|
|
716
|
+
async function processStart(pid) {
|
|
717
|
+
if (process.platform === 'linux') {
|
|
718
|
+
try {
|
|
719
|
+
const stat = await readFile(`/proc/${pid}/stat`, 'utf8');
|
|
720
|
+
// Field 22 (starttime); the fields after the ')' that closes comm start at field 3.
|
|
721
|
+
const ticks = stat.slice(stat.lastIndexOf(')') + 2).split(' ')[19];
|
|
722
|
+
const boot = (await readFile('/proc/sys/kernel/random/boot_id', 'utf8')).trim();
|
|
723
|
+
return ticks ? `linux:${boot}:${ticks}` : null;
|
|
724
|
+
}
|
|
725
|
+
catch {
|
|
726
|
+
return null;
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
if (process.platform === 'win32')
|
|
730
|
+
return null;
|
|
731
|
+
try {
|
|
732
|
+
const { stdout } = await execFileAsync('ps', ['-o', 'lstart=', '-p', String(pid)], {
|
|
733
|
+
timeout: 5000,
|
|
734
|
+
// Fixed locale and zone, so every process prints the same start the same way.
|
|
735
|
+
env: { ...process.env, LC_ALL: 'C', TZ: 'UTC' },
|
|
736
|
+
});
|
|
737
|
+
const value = stdout.trim();
|
|
738
|
+
return value ? `ps:${value}` : null;
|
|
739
|
+
}
|
|
740
|
+
catch {
|
|
741
|
+
return null;
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
let ownStart;
|
|
745
|
+
/**
|
|
746
|
+
* A lock file's content, or null when there is none. Something at the path
|
|
747
|
+
* that is not a regular file (a FIFO, a link, a folder) is not read: it gives
|
|
748
|
+
* NOT_A_LOCK, which is no lock record, so it is never removed and only makes
|
|
749
|
+
* the caller wait and report `login_busy`.
|
|
750
|
+
*/
|
|
751
|
+
async function readRaw(path) {
|
|
752
|
+
const read = await readRegularFile(path).catch((error) => {
|
|
753
|
+
if (error?.code === 'EISDIR')
|
|
754
|
+
return { kind: 'other' };
|
|
755
|
+
throw error;
|
|
756
|
+
});
|
|
757
|
+
if (read.kind === 'missing')
|
|
758
|
+
return null;
|
|
759
|
+
return read.kind === 'file' ? read.text : NOT_A_LOCK;
|
|
760
|
+
}
|
|
761
|
+
/** What readRaw gives for a path that holds no regular file; no lock record ever equals it. */
|
|
762
|
+
const NOT_A_LOCK = '\u0000not-a-regular-file';
|
|
763
|
+
/**
|
|
764
|
+
* What every lock file this code writes starts with. A file at a lock path is
|
|
765
|
+
* only taken for a lock (and ever removed as an abandoned one) when it carries
|
|
766
|
+
* exactly this format and exactly the fields lockRecord() writes, so another
|
|
767
|
+
* tool's process record or any other JSON at that path is left as it is.
|
|
768
|
+
*/
|
|
769
|
+
const LOCK_FORMAT = 'brainbase-login-lock/v1';
|
|
770
|
+
const LOCK_KEYS = new Set(['format', 'owner', 'pid', 'host', 'start']);
|
|
771
|
+
const LOCK_OWNER_PATTERN = /^[0-9a-f]{32}$/;
|
|
772
|
+
function parseLockRecord(raw) {
|
|
773
|
+
let value;
|
|
774
|
+
try {
|
|
775
|
+
value = JSON.parse(raw);
|
|
776
|
+
}
|
|
777
|
+
catch {
|
|
778
|
+
return null; // not a lock record
|
|
779
|
+
}
|
|
780
|
+
if (!value || typeof value !== 'object' || Array.isArray(value))
|
|
781
|
+
return null;
|
|
782
|
+
const record = value;
|
|
783
|
+
if (Object.keys(record).some((key) => !LOCK_KEYS.has(key)))
|
|
784
|
+
return null;
|
|
785
|
+
if (record.format !== LOCK_FORMAT)
|
|
786
|
+
return null;
|
|
787
|
+
if (typeof record.owner !== 'string' || !LOCK_OWNER_PATTERN.test(record.owner))
|
|
788
|
+
return null;
|
|
789
|
+
if (typeof record.pid !== 'number' || !Number.isSafeInteger(record.pid) || record.pid <= 0)
|
|
790
|
+
return null;
|
|
791
|
+
if (typeof record.host !== 'string' || !record.host)
|
|
792
|
+
return null;
|
|
793
|
+
if (record.start !== undefined && (typeof record.start !== 'string' || !record.start))
|
|
794
|
+
return null;
|
|
795
|
+
// Byte for byte what lockRecord() writes, so a hand-edited or look-alike file is no lock.
|
|
796
|
+
if (raw !== serializeLockRecord(record))
|
|
797
|
+
return null;
|
|
798
|
+
return record;
|
|
799
|
+
}
|
|
800
|
+
function serializeLockRecord(record) {
|
|
801
|
+
const { owner, pid, host, start } = record;
|
|
802
|
+
return JSON.stringify({ format: LOCK_FORMAT, owner, pid, host, ...(start !== undefined ? { start } : {}) });
|
|
803
|
+
}
|
|
804
|
+
function processAlive(pid) {
|
|
805
|
+
try {
|
|
806
|
+
process.kill(pid, 0);
|
|
807
|
+
return true;
|
|
808
|
+
}
|
|
809
|
+
catch (error) {
|
|
810
|
+
return error?.code === 'EPERM';
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
/**
|
|
814
|
+
* True only when the holder is known to be gone: on this machine, its process
|
|
815
|
+
* id runs no process, or runs one that started at another time than the one
|
|
816
|
+
* recorded (the id was reused, for instance after a crash and a reboot). A
|
|
817
|
+
* live holder never loses its lock, however long it works, so nothing has to
|
|
818
|
+
* be re-checked between a check and a write. A lock held from another machine
|
|
819
|
+
* is never taken over, nor one whose start cannot be read and compared.
|
|
820
|
+
*
|
|
821
|
+
* A file that is not a lock record is never taken over, however old: the
|
|
822
|
+
* saved-login path is chosen freely, so the derived lock path can name a file
|
|
823
|
+
* that is no lock at all (a config, another login's saved file). This code
|
|
824
|
+
* links a lock file into place only once its content is written, so a lock
|
|
825
|
+
* it made is always a record.
|
|
826
|
+
*/
|
|
827
|
+
async function isAbandoned(raw) {
|
|
828
|
+
const record = parseLockRecord(raw);
|
|
829
|
+
if (!record)
|
|
830
|
+
return false;
|
|
831
|
+
if (record.host !== hostname())
|
|
832
|
+
return false;
|
|
833
|
+
if (!processAlive(record.pid))
|
|
834
|
+
return true;
|
|
835
|
+
if (record.start === undefined)
|
|
836
|
+
return false;
|
|
837
|
+
const current = await processStart(record.pid);
|
|
838
|
+
return current !== null && current !== record.start;
|
|
839
|
+
}
|
|
840
|
+
/**
|
|
841
|
+
* Creates `path` holding `content`, only when it does not exist yet. The
|
|
842
|
+
* content is written first and linked into place, so the file is never seen
|
|
843
|
+
* empty. Returns false when the file already exists.
|
|
844
|
+
*/
|
|
845
|
+
async function createExclusive(path, content) {
|
|
846
|
+
const temporary = `${path}.${randomBytes(6).toString('hex')}.new`;
|
|
847
|
+
await writeFile(temporary, content, { encoding: 'utf8', mode: 0o600, flag: 'wx' });
|
|
848
|
+
try {
|
|
849
|
+
await link(temporary, path);
|
|
850
|
+
return true;
|
|
851
|
+
}
|
|
852
|
+
catch (error) {
|
|
853
|
+
const code = error?.code;
|
|
854
|
+
if (code === 'EEXIST')
|
|
855
|
+
return false;
|
|
856
|
+
if (code && NO_HARD_LINK_CODES.has(code))
|
|
857
|
+
throw storageUnsupported(dirname(path), code);
|
|
858
|
+
throw error;
|
|
859
|
+
}
|
|
860
|
+
finally {
|
|
861
|
+
await rm(temporary, { force: true });
|
|
862
|
+
}
|
|
863
|
+
}
|
|
864
|
+
/** What link() answers on a file system without hard links (exFAT, FAT32, some network shares). */
|
|
865
|
+
const NO_HARD_LINK_CODES = new Set(['EPERM', 'ENOTSUP', 'EOPNOTSUPP', 'ENOSYS', 'EXDEV']);
|
|
866
|
+
function storageUnsupported(directory, code) {
|
|
867
|
+
return new BrainbaseLoginError('login_storage_unsupported', `The saved login needs a folder on a file system with hard links (such as APFS, ext4 or NTFS); ${directory} does not offer them (${code}). `
|
|
868
|
+
+ 'Pass --credentials with a path on such a file system, or leave it out to use the default under your home folder. Nothing was changed.');
|
|
869
|
+
}
|
|
870
|
+
/**
|
|
871
|
+
* Fails with `login_storage_unsupported` when the folder of `path` cannot hold
|
|
872
|
+
* the lock, before anything is asked of the server or of the person.
|
|
873
|
+
*/
|
|
874
|
+
export async function checkCredentialsStorage(path) {
|
|
875
|
+
assertCredentialsFilePath(path);
|
|
876
|
+
await mkdir(dirname(path), { recursive: true, mode: 0o700 });
|
|
877
|
+
const probe = `${await physicalPath(path)}.probe-${randomBytes(6).toString('hex')}`;
|
|
878
|
+
if (await createExclusive(probe, ''))
|
|
879
|
+
await rm(probe, { force: true });
|
|
880
|
+
}
|
|
881
|
+
async function lockRecord(owner) {
|
|
882
|
+
ownStart ??= processStart(process.pid);
|
|
883
|
+
const start = await ownStart;
|
|
884
|
+
return serializeLockRecord({ format: LOCK_FORMAT, owner, pid: process.pid, host: hostname(), ...(start ? { start } : {}) });
|
|
885
|
+
}
|
|
886
|
+
/**
|
|
887
|
+
* Removes the lock at `path`, which was seen holding `observed` from a holder
|
|
888
|
+
* that is gone. Every process that wants to remove that same lock first takes
|
|
889
|
+
* a takeover lock named after what it saw; only the one holding it reads the
|
|
890
|
+
* file again and removes it, and only when it still holds `observed`. Nobody
|
|
891
|
+
* else changes the file meanwhile: its holder is gone, a new lock cannot be
|
|
892
|
+
* created while it exists, and the other takers wait for the takeover lock.
|
|
893
|
+
* A takeover lock left by a taker that died is removed the same way.
|
|
894
|
+
*/
|
|
895
|
+
async function removeAbandoned(path, observed) {
|
|
896
|
+
const guard = `${path}.takeover-${createHash('sha256').update(observed).digest('hex').slice(0, 16)}`;
|
|
897
|
+
const owner = randomBytes(16).toString('hex');
|
|
898
|
+
if (!(await createExclusive(guard, await lockRecord(owner)))) {
|
|
899
|
+
const guardRaw = await readRaw(guard);
|
|
900
|
+
if (guardRaw !== null && await isAbandoned(guardRaw)) {
|
|
901
|
+
await removeAbandoned(guard, guardRaw);
|
|
902
|
+
}
|
|
903
|
+
return false; // Another process is taking it over; the caller looks again.
|
|
904
|
+
}
|
|
905
|
+
try {
|
|
906
|
+
const current = await readRaw(path);
|
|
907
|
+
if (current === observed && await isAbandoned(current)) {
|
|
908
|
+
await rm(path, { force: true });
|
|
909
|
+
}
|
|
910
|
+
return true;
|
|
911
|
+
}
|
|
912
|
+
finally {
|
|
913
|
+
if (parseLockRecord((await readRaw(guard)) ?? '')?.owner === owner)
|
|
914
|
+
await rm(guard, { force: true });
|
|
915
|
+
}
|
|
916
|
+
}
|
|
917
|
+
function busy(lockPath, holder) {
|
|
918
|
+
const record = parseLockRecord(holder);
|
|
919
|
+
if (!record) {
|
|
920
|
+
return new BrainbaseLoginError('login_busy', `${lockPath} is in the way of the saved login's lock and is not a brainbase lock, so it was left as it is. `
|
|
921
|
+
+ 'If it is not needed, move it away; otherwise pass another path with --credentials.');
|
|
922
|
+
}
|
|
923
|
+
if (record && record.host !== hostname()) {
|
|
924
|
+
return new BrainbaseLoginError('login_busy', `The saved login is locked from another machine (${record.host}). If nothing runs there, remove ${lockPath}.`);
|
|
925
|
+
}
|
|
926
|
+
if (record && record.start === undefined && process.platform === 'win32') {
|
|
927
|
+
// Windows does not let this tell a crashed holder whose process id was
|
|
928
|
+
// given to another program from a holder that still runs, so it waits.
|
|
929
|
+
return new BrainbaseLoginError('login_busy', `Another brainbase process may be changing the saved login. On Windows, a lock left by a brainbase process that stopped cannot be told apart from a running one. If no brainbase command is running, remove ${lockPath} and try again.`);
|
|
930
|
+
}
|
|
931
|
+
return new BrainbaseLoginError('login_busy', 'Another brainbase process is changing the saved login. Try again.');
|
|
932
|
+
}
|
|
933
|
+
/**
|
|
934
|
+
* Serialises changes to the credentials file between processes on this
|
|
935
|
+
* machine: login, logout, and a renewal from its request to its write-back.
|
|
936
|
+
* The lock file holds the holder's random id, process id and host name. It is
|
|
937
|
+
* held until the holder removes it: another process only removes it when the
|
|
938
|
+
* holder's process no longer runs, so the lock covers every read, write and
|
|
939
|
+
* removal of the credentials file done under it.
|
|
940
|
+
*/
|
|
941
|
+
export async function withCredentialsLock(path, task, timing = {}) {
|
|
942
|
+
assertCredentialsFilePath(path);
|
|
943
|
+
const { waitMs, destination: pinned, suffix = '.lock', recover = true } = { ...DEFAULT_LOCK_TIMING, ...timing };
|
|
944
|
+
// A pinned destination is a folder that was there: it is not made again.
|
|
945
|
+
if (!pinned)
|
|
946
|
+
await mkdir(dirname(path), { recursive: true, mode: 0o700 });
|
|
947
|
+
// Every spelling of the same file takes the same lock, and the work under
|
|
948
|
+
// the lock acts on this one resolution (lock.target).
|
|
949
|
+
const target = await physicalPath(path).catch((error) => {
|
|
950
|
+
if (pinned && error?.code === 'ENOENT')
|
|
951
|
+
throw destinationChanged();
|
|
952
|
+
throw error;
|
|
953
|
+
});
|
|
954
|
+
const folder = await folderIdentity(dirname(target));
|
|
955
|
+
if (pinned && (pinned.target !== target || !sameFolder(pinned.folder, folder)))
|
|
956
|
+
throw destinationChanged();
|
|
957
|
+
const destination = { target, folder };
|
|
958
|
+
const lockPath = `${target}${suffix}`;
|
|
959
|
+
const owner = randomBytes(16).toString('hex');
|
|
960
|
+
const record = await lockRecord(owner);
|
|
961
|
+
const started = Date.now();
|
|
962
|
+
while (!(await createExclusive(lockPath, record))) {
|
|
963
|
+
const holder = await readRaw(lockPath);
|
|
964
|
+
if (holder === null)
|
|
965
|
+
continue; // Released meanwhile.
|
|
966
|
+
// This code links a lock into place only once it is written, so a file
|
|
967
|
+
// that is no lock record is no lock of a holder that is about to finish:
|
|
968
|
+
// waiting would not free it.
|
|
969
|
+
if (!parseLockRecord(holder))
|
|
970
|
+
throw busy(lockPath, holder);
|
|
971
|
+
if (await isAbandoned(holder) && await removeAbandoned(lockPath, holder))
|
|
972
|
+
continue;
|
|
973
|
+
if (Date.now() - started > waitMs)
|
|
974
|
+
throw busy(lockPath, holder);
|
|
975
|
+
await defaultSleep(25);
|
|
976
|
+
}
|
|
977
|
+
const release = async () => {
|
|
978
|
+
// Nobody else removes a lock whose holder runs, so this is still ours
|
|
979
|
+
// unless something outside brainbase replaced it.
|
|
980
|
+
if ((await readRaw(lockPath).catch(() => null)) === record)
|
|
981
|
+
await rm(lockPath, { force: true });
|
|
982
|
+
};
|
|
983
|
+
let interrupted;
|
|
984
|
+
try {
|
|
985
|
+
// Whoever takes the lock next finishes (or rolls back) a save or logout
|
|
986
|
+
// that stopped half way, before anything else reads or writes the login.
|
|
987
|
+
interrupted = recover
|
|
988
|
+
? await finishInterrupted(target)
|
|
989
|
+
: { logoutFinished: false, saveRolledBack: false };
|
|
990
|
+
}
|
|
991
|
+
catch (error) {
|
|
992
|
+
await release();
|
|
993
|
+
throw error;
|
|
994
|
+
}
|
|
995
|
+
const lock = {
|
|
996
|
+
target,
|
|
997
|
+
destination,
|
|
998
|
+
interrupted,
|
|
999
|
+
async assertHeld() {
|
|
1000
|
+
if ((await readRaw(lockPath)) !== record) {
|
|
1001
|
+
throw new BrainbaseLoginError('login_lock_lost', 'Another brainbase process took over the saved login. Run the command again.');
|
|
1002
|
+
}
|
|
1003
|
+
// A folder on the way may have been swapped for a link since the lock
|
|
1004
|
+
// was taken: then the path no longer leads to the locked file, nor does
|
|
1005
|
+
// the locked path itself lead to the same folder.
|
|
1006
|
+
const directory = dirname(target);
|
|
1007
|
+
const now = await Promise.all([realpath(directory), realpath(dirname(path)), folderIdentity(directory)]).catch(() => null);
|
|
1008
|
+
// The same real path can also name a new folder (the old one moved away
|
|
1009
|
+
// and another made in its place), so the folder itself is compared too.
|
|
1010
|
+
if (!now || now[0] !== directory || now[1] !== directory || !sameFolder(now[2], folder))
|
|
1011
|
+
throw destinationChanged();
|
|
1012
|
+
},
|
|
1013
|
+
};
|
|
1014
|
+
try {
|
|
1015
|
+
return await task(lock);
|
|
1016
|
+
}
|
|
1017
|
+
finally {
|
|
1018
|
+
await release();
|
|
1019
|
+
}
|
|
1020
|
+
}
|
|
1021
|
+
/**
|
|
1022
|
+
* The SavedLoginKey of the file at `path` (read at `target`): null when no
|
|
1023
|
+
* file is there. A file that brainbase did not write (a mistyped
|
|
1024
|
+
* --credentials naming some other file) or that cannot be read is refused,
|
|
1025
|
+
* so no save replaces it and logout never deletes it. A saved login that has
|
|
1026
|
+
* become unusable still counts while it carries brainbase's schema_version,
|
|
1027
|
+
* so the person can log out of a broken one.
|
|
1028
|
+
*/
|
|
1029
|
+
async function savedLoginKey(path, target) {
|
|
1030
|
+
let text;
|
|
1031
|
+
try {
|
|
1032
|
+
text = await readCredentialsText(path, target);
|
|
1033
|
+
}
|
|
1034
|
+
catch (error) {
|
|
1035
|
+
if (error instanceof BrainbaseLoginError)
|
|
1036
|
+
throw error;
|
|
1037
|
+
const code = error?.code ?? 'error';
|
|
1038
|
+
throw new BrainbaseLoginError('login_credentials_unreadable', `The saved login could not be read (${code}): ${path}. Nothing was removed.`);
|
|
1039
|
+
}
|
|
1040
|
+
if (text === null)
|
|
1041
|
+
return null;
|
|
1042
|
+
try {
|
|
1043
|
+
return loginKeyOf(parseCredentials(text, path));
|
|
1044
|
+
}
|
|
1045
|
+
catch {
|
|
1046
|
+
// Unusable: still ours if brainbase wrote it.
|
|
1047
|
+
}
|
|
1048
|
+
let parsed;
|
|
1049
|
+
try {
|
|
1050
|
+
parsed = JSON.parse(text);
|
|
1051
|
+
}
|
|
1052
|
+
catch {
|
|
1053
|
+
parsed = null;
|
|
1054
|
+
}
|
|
1055
|
+
if (parsed?.schema_version === CREDENTIALS_SCHEMA_VERSION) {
|
|
1056
|
+
return `file:${createHash('sha256').update(text).digest('hex')}`;
|
|
1057
|
+
}
|
|
1058
|
+
throw new BrainbaseLoginError('login_credentials_unrecognized', `This file is not a saved brainbase login: ${path}. It was left as it is. Check --credentials.`);
|
|
1059
|
+
}
|
|
1060
|
+
/** The SavedLoginKey of a login: equal for the login and its renewals. */
|
|
1061
|
+
export function loginKeyOf(credentials) {
|
|
1062
|
+
return `login:${credentials.login_id}`;
|
|
1063
|
+
}
|
|
1064
|
+
/**
|
|
1065
|
+
* Removes the file at `target` only when it is the file that was checked
|
|
1066
|
+
* (`checked`). It is first moved aside in one step, so what is compared is
|
|
1067
|
+
* exactly the file taken away: when another program replaced the saved login
|
|
1068
|
+
* after the check, its file is put back where it was and `login_changed` is
|
|
1069
|
+
* thrown. (rename() changes a file's ctime, so the moved file is compared by
|
|
1070
|
+
* device, inode, size and mtime.)
|
|
1071
|
+
*/
|
|
1072
|
+
async function removeCheckedFile(target, path, checked) {
|
|
1073
|
+
const aside = removingPath(target);
|
|
1074
|
+
await assertAsideFree(aside, path);
|
|
1075
|
+
try {
|
|
1076
|
+
await rename(target, aside);
|
|
1077
|
+
}
|
|
1078
|
+
catch (error) {
|
|
1079
|
+
// Gone since the check: removed by someone else, nothing of ours is left.
|
|
1080
|
+
if (error?.code === 'ENOENT')
|
|
1081
|
+
throw changedDuringRemove(path);
|
|
1082
|
+
throw error;
|
|
1083
|
+
}
|
|
1084
|
+
const moved = await identityOf(aside, path).catch(() => null);
|
|
1085
|
+
if (moved === null || moved.dev !== checked.dev || moved.ino !== checked.ino
|
|
1086
|
+
|| moved.size !== checked.size || moved.mtimeNs !== checked.mtimeNs) {
|
|
1087
|
+
// Put it back without replacing anything created at the path meanwhile.
|
|
1088
|
+
try {
|
|
1089
|
+
await link(aside, target);
|
|
1090
|
+
await rm(aside, { force: true });
|
|
1091
|
+
}
|
|
1092
|
+
catch {
|
|
1093
|
+
throw new BrainbaseLoginError('login_changed', `Another program changed ${JSON.stringify(path)} while logging out, and its file could not be put back. It was kept as ${JSON.stringify(aside)}. Nothing was removed.`);
|
|
1094
|
+
}
|
|
1095
|
+
throw changedDuringRemove(path);
|
|
1096
|
+
}
|
|
1097
|
+
await rm(aside, { force: true });
|
|
1098
|
+
}
|
|
1099
|
+
function changedDuringRemove(path) {
|
|
1100
|
+
return new BrainbaseLoginError('login_changed', `Another program created or changed ${JSON.stringify(path)} while logging out. That file was left as it is. Check --credentials and run the command again.`);
|
|
1101
|
+
}
|
|
1102
|
+
/**
|
|
1103
|
+
* Removes the saved login and flushes the directory that held it, under the
|
|
1104
|
+
* lock, before this returns. Without the flush, a power loss right after a
|
|
1105
|
+
* logout could bring the old login back. The directory is flushed even when
|
|
1106
|
+
* no file was there, since an earlier logout may have stopped before its flush.
|
|
1107
|
+
* Only a file that is a saved login is removed (see savedLoginKey); any other
|
|
1108
|
+
* file is left as it is and `login_credentials_unrecognized` is thrown.
|
|
1109
|
+
*/
|
|
1110
|
+
export async function removeCredentials(path = defaultCredentialsPath()) {
|
|
1111
|
+
assertCredentialsFilePath(path);
|
|
1112
|
+
return withCredentialsLock(path, async (lock) => {
|
|
1113
|
+
// Check, remove and flush the file the lock covers, in its real directory.
|
|
1114
|
+
const { target } = lock;
|
|
1115
|
+
const { identity } = await checkedSavedLogin(target, path);
|
|
1116
|
+
await lock.assertHeld();
|
|
1117
|
+
// No file at the check: nothing is removed, so a file another program
|
|
1118
|
+
// creates meanwhile stays. The folder is still flushed (see above).
|
|
1119
|
+
if (identity !== null)
|
|
1120
|
+
await removeCheckedFile(target, path, identity);
|
|
1121
|
+
const durable = await syncDirectory(dirname(target));
|
|
1122
|
+
// A logout that stopped half way was finished when the lock was taken:
|
|
1123
|
+
// its login was there and is gone now.
|
|
1124
|
+
return { existed: identity !== null || lock.interrupted.logoutFinished, durable };
|
|
1125
|
+
});
|
|
1126
|
+
}
|
|
1127
|
+
/**
|
|
1128
|
+
* Runs the Device Code Flow against `serverUrl` and saves the person token.
|
|
1129
|
+
* Asks for a receipt so the server issues the token once and forgets it only
|
|
1130
|
+
* after this machine has stored it.
|
|
1131
|
+
*/
|
|
1132
|
+
export async function loginWithDeviceCode(options) {
|
|
1133
|
+
const fetchImpl = options.fetch ?? fetch;
|
|
1134
|
+
const now = options.now ?? Date.now;
|
|
1135
|
+
const sleep = options.sleep ?? defaultSleep;
|
|
1136
|
+
const serverUrl = normalizeServerUrl(options.serverUrl);
|
|
1137
|
+
const credentialsPath = options.credentialsPath ?? defaultCredentialsPath();
|
|
1138
|
+
const codeVerifier = randomBytes(32).toString('base64url');
|
|
1139
|
+
// A folder that cannot hold the lock would only fail after the approval.
|
|
1140
|
+
await checkCredentialsStorage(credentialsPath);
|
|
1141
|
+
// A path that names some other file would only be refused after the approval.
|
|
1142
|
+
// Where the save goes and which login is there are fixed here: the save
|
|
1143
|
+
// after the approval goes to this same file and replaces only this login.
|
|
1144
|
+
const check = await checkCredentialsTarget(credentialsPath);
|
|
1145
|
+
let start;
|
|
1146
|
+
try {
|
|
1147
|
+
start = await postJson(fetchImpl, `${serverUrl}/api/auth/device/code`, {
|
|
1148
|
+
code_verifier: codeVerifier,
|
|
1149
|
+
receipt_required: true,
|
|
1150
|
+
});
|
|
1151
|
+
}
|
|
1152
|
+
catch {
|
|
1153
|
+
throw new BrainbaseLoginError('login_server_unreachable', `Cannot reach ${serverUrl}. Nothing was saved.`);
|
|
1154
|
+
}
|
|
1155
|
+
if (start.status === 404) {
|
|
1156
|
+
throw new BrainbaseLoginError('login_device_flow_unavailable', `${serverUrl} does not offer terminal login (HTTP 404). Nothing was saved.`);
|
|
1157
|
+
}
|
|
1158
|
+
const deviceCode = start.json?.device_code;
|
|
1159
|
+
const verificationUri = start.json?.verification_uri;
|
|
1160
|
+
if (!start.ok || typeof deviceCode !== 'string' || !deviceCode || typeof verificationUri !== 'string') {
|
|
1161
|
+
throw new BrainbaseLoginError('login_device_code_failed', `The server refused to start a login (HTTP ${start.status}). Nothing was saved.`);
|
|
1162
|
+
}
|
|
1163
|
+
const expiresInSeconds = typeof start.json?.expires_in === 'number' ? start.json.expires_in : 300;
|
|
1164
|
+
let intervalMs = (typeof start.json?.interval === 'number' && start.json.interval > 0 ? start.json.interval : 5) * 1000;
|
|
1165
|
+
options.onPrompt({
|
|
1166
|
+
verificationUri,
|
|
1167
|
+
...(typeof start.json?.verification_uri_complete === 'string'
|
|
1168
|
+
? { verificationUriComplete: start.json.verification_uri_complete } : {}),
|
|
1169
|
+
...(typeof start.json?.user_code === 'string' ? { userCode: start.json.user_code } : {}),
|
|
1170
|
+
expiresInSeconds,
|
|
1171
|
+
});
|
|
1172
|
+
const deadline = now() + expiresInSeconds * 1000;
|
|
1173
|
+
while (now() < deadline) {
|
|
1174
|
+
await sleep(intervalMs);
|
|
1175
|
+
if (now() >= deadline)
|
|
1176
|
+
break; // A longer wait (slow_down) may have run past the code's expiry.
|
|
1177
|
+
let poll;
|
|
1178
|
+
try {
|
|
1179
|
+
poll = await postJson(fetchImpl, `${serverUrl}/api/auth/device/token`, {
|
|
1180
|
+
device_code: deviceCode,
|
|
1181
|
+
code_verifier: codeVerifier,
|
|
1182
|
+
});
|
|
1183
|
+
}
|
|
1184
|
+
catch {
|
|
1185
|
+
continue; // A dropped poll is retried until the code expires.
|
|
1186
|
+
}
|
|
1187
|
+
const error = poll.json?.error;
|
|
1188
|
+
if (!poll.ok) {
|
|
1189
|
+
if (error === 'authorization_pending') {
|
|
1190
|
+
options.onWaiting?.();
|
|
1191
|
+
continue;
|
|
1192
|
+
}
|
|
1193
|
+
if (error === 'slow_down') {
|
|
1194
|
+
intervalMs += 5000;
|
|
1195
|
+
continue;
|
|
1196
|
+
}
|
|
1197
|
+
if (error === 'access_denied') {
|
|
1198
|
+
throw new BrainbaseLoginError('login_denied', 'The login was denied in the browser. Nothing was saved.');
|
|
1199
|
+
}
|
|
1200
|
+
if (error === 'expired_token') {
|
|
1201
|
+
throw new BrainbaseLoginError('login_expired', 'The login code expired or was already used. Run brainbase login again.');
|
|
1202
|
+
}
|
|
1203
|
+
if (poll.status >= 500) {
|
|
1204
|
+
continue; // A passing server error is retried until the code expires.
|
|
1205
|
+
}
|
|
1206
|
+
if (typeof error === 'string' && /^[a-z_]{1,40}$/u.test(error)) {
|
|
1207
|
+
throw new BrainbaseLoginError(`login_${error}`, `The server refused the login (${error}). Nothing was saved.`);
|
|
1208
|
+
}
|
|
1209
|
+
continue;
|
|
1210
|
+
}
|
|
1211
|
+
const accessToken = poll.json?.access_token;
|
|
1212
|
+
if (typeof accessToken !== 'string' || !accessToken) {
|
|
1213
|
+
throw new BrainbaseLoginError('login_token_response_invalid', 'The server answered without a token. Nothing was saved.');
|
|
1214
|
+
}
|
|
1215
|
+
const refreshToken = poll.json?.refresh_token;
|
|
1216
|
+
const credentials = {
|
|
1217
|
+
schema_version: CREDENTIALS_SCHEMA_VERSION,
|
|
1218
|
+
login_id: newLoginId(),
|
|
1219
|
+
server_url: serverUrl,
|
|
1220
|
+
access_token: accessToken,
|
|
1221
|
+
...(typeof refreshToken === 'string' && refreshToken ? { refresh_token: refreshToken } : {}),
|
|
1222
|
+
expires_at: expiryIso(accessToken, poll.json?.expires_in, now()),
|
|
1223
|
+
};
|
|
1224
|
+
// The receipt lets the server forget the token, so it goes out only once
|
|
1225
|
+
// the file is known to be on disk. Where a directory cannot be flushed,
|
|
1226
|
+
// no receipt is sent and the code expires on its own.
|
|
1227
|
+
let saved;
|
|
1228
|
+
try {
|
|
1229
|
+
saved = await withCredentialsLock(credentialsPath, (lock) => writeCredentials(credentialsPath, credentials, { lock, expected: check.saved }), { destination: check.destination });
|
|
1230
|
+
}
|
|
1231
|
+
catch (error) {
|
|
1232
|
+
if (error instanceof BrainbaseLoginError)
|
|
1233
|
+
throw error;
|
|
1234
|
+
throw new BrainbaseLoginError('login_save_failed', `Could not save the login to ${credentialsPath} (${error?.code ?? 'error'}). Run brainbase login again.`);
|
|
1235
|
+
}
|
|
1236
|
+
const receiptToken = poll.json?.receipt_token;
|
|
1237
|
+
if (saved.durable && typeof receiptToken === 'string' && receiptToken) {
|
|
1238
|
+
// Tells the server the token is stored, so it stops handing it out.
|
|
1239
|
+
// A lost receipt only leaves the code to expire on its own.
|
|
1240
|
+
await postJson(fetchImpl, `${serverUrl}/api/auth/device/received`, {
|
|
1241
|
+
device_code: deviceCode,
|
|
1242
|
+
receipt_token: receiptToken,
|
|
1243
|
+
}).catch(() => undefined);
|
|
1244
|
+
}
|
|
1245
|
+
return credentials;
|
|
1246
|
+
}
|
|
1247
|
+
throw new BrainbaseLoginError('login_timeout', 'The login was not approved in time. Run brainbase login again.');
|
|
1248
|
+
}
|
|
1249
|
+
async function requestRenewal(credentials, fetchImpl, now) {
|
|
1250
|
+
const refresh = async () => {
|
|
1251
|
+
const headers = await csrfHeaders(fetchImpl, credentials.server_url);
|
|
1252
|
+
try {
|
|
1253
|
+
return await postJson(fetchImpl, `${credentials.server_url}/api/auth/refresh`, {
|
|
1254
|
+
refresh_token: credentials.refresh_token,
|
|
1255
|
+
}, headers);
|
|
1256
|
+
}
|
|
1257
|
+
catch {
|
|
1258
|
+
throw new BrainbaseLoginError('login_refresh_unreachable', `Cannot reach ${credentials.server_url} to renew the login.`);
|
|
1259
|
+
}
|
|
1260
|
+
};
|
|
1261
|
+
let result = await refresh();
|
|
1262
|
+
// The API keeps CSRF tokens in each server process, so a token handed out
|
|
1263
|
+
// by one instance can be refused by another. That says nothing about the
|
|
1264
|
+
// refresh token: ask once more, and otherwise report a retryable failure.
|
|
1265
|
+
if (isCsrfRefusal(result))
|
|
1266
|
+
result = await refresh();
|
|
1267
|
+
const token = result.json?.token ?? result.json?.access_token;
|
|
1268
|
+
if (!result.ok || typeof token !== 'string' || !token) {
|
|
1269
|
+
// Overload and server errors say nothing about the refresh token: the saved
|
|
1270
|
+
// login stays and a later try may succeed.
|
|
1271
|
+
// An answer cut off in transit is no refusal either.
|
|
1272
|
+
if (result.status === 429 || result.status >= 500 || isCsrfRefusal(result) || result.bodyLost) {
|
|
1273
|
+
throw new BrainbaseLoginError('login_refresh_unavailable', 'The server could not renew the login right now. Try again.');
|
|
1274
|
+
}
|
|
1275
|
+
throw new BrainbaseLoginError('login_expired', 'The saved login can no longer be renewed. Run brainbase login again.');
|
|
1276
|
+
}
|
|
1277
|
+
const nextRefresh = result.json?.refresh_token;
|
|
1278
|
+
return {
|
|
1279
|
+
...credentials,
|
|
1280
|
+
access_token: token,
|
|
1281
|
+
...(typeof nextRefresh === 'string' && nextRefresh ? { refresh_token: nextRefresh } : {}),
|
|
1282
|
+
expires_at: expiryIso(token, result.json?.expires_in, now()),
|
|
1283
|
+
};
|
|
1284
|
+
}
|
|
1285
|
+
function sameLogin(a, b) {
|
|
1286
|
+
return a.login_id === b.login_id && a.server_url === b.server_url;
|
|
1287
|
+
}
|
|
1288
|
+
function isFresh(credentials, now, skew) {
|
|
1289
|
+
return Date.parse(credentials.expires_at) - skew > now;
|
|
1290
|
+
}
|
|
1291
|
+
function usableWithoutRenewal(credentials, now) {
|
|
1292
|
+
// Nothing can renew it, so it is used until it actually expires.
|
|
1293
|
+
if (Date.parse(credentials.expires_at) > now) {
|
|
1294
|
+
return { token: credentials.access_token, serverUrl: credentials.server_url, loginId: credentials.login_id };
|
|
1295
|
+
}
|
|
1296
|
+
throw new BrainbaseLoginError('login_expired', 'The saved login has expired. Run brainbase login again.');
|
|
1297
|
+
}
|
|
1298
|
+
/**
|
|
1299
|
+
* The person token for this machine, renewed first when it is about to expire.
|
|
1300
|
+
* Fails with a `login_*` code when there is no usable login.
|
|
1301
|
+
*
|
|
1302
|
+
* A renewal holds the credentials lock from its request to its write-back, so
|
|
1303
|
+
* two renewals never race on a rotating refresh token, and a logout or another
|
|
1304
|
+
* login waits for it and then wins.
|
|
1305
|
+
*/
|
|
1306
|
+
export async function getAccessToken(options = {}) {
|
|
1307
|
+
const { token, serverUrl } = await getAccessTokenOfLogin(options);
|
|
1308
|
+
return { token, serverUrl };
|
|
1309
|
+
}
|
|
1310
|
+
/**
|
|
1311
|
+
* getAccessToken, with the saved login's login_id. A renewal keeps the
|
|
1312
|
+
* login_id; another `brainbase login` (as anyone) gets a new one.
|
|
1313
|
+
*/
|
|
1314
|
+
export async function getAccessTokenOfLogin(options = {}) {
|
|
1315
|
+
const credentialsPath = options.credentialsPath ?? defaultCredentialsPath();
|
|
1316
|
+
const fetchImpl = options.fetch ?? fetch;
|
|
1317
|
+
const now = options.now ?? Date.now;
|
|
1318
|
+
const skew = options.refreshSkewMs ?? DEFAULT_REFRESH_SKEW_MS;
|
|
1319
|
+
const credentials = await readCredentials(credentialsPath);
|
|
1320
|
+
if (!credentials) {
|
|
1321
|
+
throw new BrainbaseLoginError('login_missing', 'Not logged in. Run brainbase login --server <url>.');
|
|
1322
|
+
}
|
|
1323
|
+
if (isFresh(credentials, now(), skew)) {
|
|
1324
|
+
return { token: credentials.access_token, serverUrl: credentials.server_url, loginId: credentials.login_id };
|
|
1325
|
+
}
|
|
1326
|
+
if (!credentials.refresh_token)
|
|
1327
|
+
return usableWithoutRenewal(credentials, now());
|
|
1328
|
+
return withCredentialsLock(credentialsPath, async (lock) => {
|
|
1329
|
+
// Read again under the lock: another process may have renewed, logged out
|
|
1330
|
+
// or logged in as someone else while this one waited.
|
|
1331
|
+
const latest = await readCredentialsText(credentialsPath, lock.target)
|
|
1332
|
+
.then((text) => (text === null ? null : parseCredentials(text, credentialsPath)), () => null);
|
|
1333
|
+
if (!latest || !sameLogin(latest, credentials)) {
|
|
1334
|
+
throw new BrainbaseLoginError('login_changed', 'The saved login changed while it was being renewed. Run the command again.');
|
|
1335
|
+
}
|
|
1336
|
+
if (isFresh(latest, now(), skew))
|
|
1337
|
+
return { token: latest.access_token, serverUrl: latest.server_url, loginId: latest.login_id };
|
|
1338
|
+
if (!latest.refresh_token)
|
|
1339
|
+
return usableWithoutRenewal(latest, now());
|
|
1340
|
+
const next = await requestRenewal(latest, fetchImpl, now);
|
|
1341
|
+
// The login checked before the request must still be the one replaced.
|
|
1342
|
+
await writeCredentials(credentialsPath, next, { lock, expected: loginKeyOf(latest) });
|
|
1343
|
+
return { token: next.access_token, serverUrl: next.server_url, loginId: next.login_id };
|
|
1344
|
+
});
|
|
1345
|
+
}
|