@flipstream/sdk 0.5.0 → 0.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/CHANGELOG.md +69 -0
  2. package/README.md +325 -53
  3. package/dist/auth/discovery.d.ts +5 -4
  4. package/dist/auth/discovery.js +10 -8
  5. package/dist/auth/discovery.js.map +1 -1
  6. package/dist/auth/signIn.js +10 -5
  7. package/dist/auth/signIn.js.map +1 -1
  8. package/dist/auth/transport.d.ts +20 -2
  9. package/dist/auth/transport.js +25 -5
  10. package/dist/auth/transport.js.map +1 -1
  11. package/dist/core/fetch.d.ts +5 -0
  12. package/dist/core/fetch.js +8 -1
  13. package/dist/core/fetch.js.map +1 -1
  14. package/dist/flipstream.d.ts +8 -0
  15. package/dist/flipstream.js +4 -3
  16. package/dist/flipstream.js.map +1 -1
  17. package/dist/index.d.ts +3 -1
  18. package/dist/index.js +4 -0
  19. package/dist/index.js.map +1 -1
  20. package/dist/node/fileLock.d.ts +21 -0
  21. package/dist/node/fileLock.js +36 -48
  22. package/dist/node/fileLock.js.map +1 -1
  23. package/dist/node/fileStore.d.ts +41 -0
  24. package/dist/node/fileStore.js +137 -0
  25. package/dist/node/fileStore.js.map +1 -0
  26. package/dist/node/index.d.ts +4 -0
  27. package/dist/node/index.js +3 -1
  28. package/dist/node/index.js.map +1 -1
  29. package/dist/node/keychainChild.d.ts +1 -0
  30. package/dist/node/keychainChild.js +136 -0
  31. package/dist/node/keychainChild.js.map +1 -0
  32. package/dist/node/keychainStore.d.ts +34 -0
  33. package/dist/node/keychainStore.js +268 -0
  34. package/dist/node/keychainStore.js.map +1 -0
  35. package/dist/node/loopback.js +1 -1
  36. package/dist/node/loopback.js.map +1 -1
  37. package/dist/node/session.d.ts +73 -12
  38. package/dist/node/session.js +248 -35
  39. package/dist/node/session.js.map +1 -1
  40. package/dist/node/store.d.ts +48 -0
  41. package/dist/node/store.js +99 -0
  42. package/dist/node/store.js.map +1 -0
  43. package/dist/query/catalog.d.ts +271 -2
  44. package/dist/query/catalog.js +93 -5
  45. package/dist/query/catalog.js.map +1 -1
  46. package/dist/query/query.d.ts +14 -5
  47. package/dist/query/query.js +21 -6
  48. package/dist/query/query.js.map +1 -1
  49. package/dist/spec/query-planner/index.d.ts +1 -1
  50. package/dist/spec/query-planner/types.gen.d.ts +35 -4
  51. package/dist/spec/query-planner/zod.gen.d.ts +257 -64
  52. package/dist/spec/query-planner/zod.gen.js +31 -5
  53. package/dist/spec/query-planner/zod.gen.js.map +1 -1
  54. package/dist/version.gen.d.ts +2 -0
  55. package/dist/version.gen.js +4 -0
  56. package/dist/version.gen.js.map +1 -0
  57. package/package.json +9 -3
@@ -0,0 +1,137 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import { constants } from 'node:fs';
3
+ import { mkdir, open, readdir, rename, stat, unlink } from 'node:fs/promises';
4
+ import { basename, dirname, join, resolve } from 'node:path';
5
+ import { fileLock } from './fileLock.js';
6
+ import { parse, storeOf } from './store.js';
7
+ export function fileStore(path, options = {}) {
8
+ const file = resolve(path);
9
+ const store = storeOf(`file:${file}`, () => read(file), (tokens) => (tokens === null ? remove(file) : replace(file, tokens)), () => folderPlace(file));
10
+ return options.lock === true ? { ...store, lock: fileLock(`${file}.lock`) } : store;
11
+ }
12
+ /**
13
+ * The file as its folder's device and inode with its name, which two spellings of it share: a path
14
+ * through a linked folder, or a folder spelt in another case on macOS (D504). A name that differs
15
+ * only in case still takes its own turn. Before the folder exists there is nothing to share: the
16
+ * first save makes it.
17
+ */
18
+ async function folderPlace(file) {
19
+ try {
20
+ const { dev, ino } = await stat(dirname(file), { bigint: true });
21
+ return `file-in:${String(dev)}:${String(ino)}:${basename(file)}`;
22
+ }
23
+ catch (error) {
24
+ if (codeOf(error) === 'ENOENT')
25
+ return undefined;
26
+ throw error;
27
+ }
28
+ }
29
+ const POSIX = process.platform !== 'win32';
30
+ // Not through a link, and not waiting on a pipe that nobody writes to (O_NONBLOCK): what is opened
31
+ // is checked before a byte is read.
32
+ const READ = constants.O_RDONLY | (POSIX ? constants.O_NOFOLLOW | constants.O_NONBLOCK : 0);
33
+ async function read(file) {
34
+ try {
35
+ await mustBeMine(dirname(file));
36
+ }
37
+ catch (error) {
38
+ if (codeOf(error) === 'ENOENT')
39
+ return null;
40
+ throw error;
41
+ }
42
+ let handle;
43
+ try {
44
+ handle = await open(file, READ);
45
+ }
46
+ catch (error) {
47
+ if (codeOf(error) === 'ENOENT')
48
+ return null;
49
+ if (codeOf(error) === 'ELOOP')
50
+ throw new Error(`the token file is a symbolic link, which the store doesn't follow: ${file}`, { cause: error });
51
+ throw error;
52
+ }
53
+ try {
54
+ const found = await handle.stat();
55
+ if (!found.isFile())
56
+ throw new Error(`the token file isn't a regular file: ${file}`);
57
+ if (POSIX && (!ownedByMe(found) || (found.mode & 0o077) !== 0))
58
+ throw new Error(`the token file must be this user's, readable by them only (mode 0600): ${file}`);
59
+ return parse(await handle.readFile('utf8'));
60
+ }
61
+ finally {
62
+ await handle.close();
63
+ }
64
+ }
65
+ async function replace(file, tokens) {
66
+ const folder = dirname(file);
67
+ await mkdir(folder, { recursive: true, mode: 0o700 });
68
+ await mustBeMine(folder);
69
+ // Created, never opened over an existing file ('wx'), so a name planted beforehand fails the save.
70
+ const temporary = join(folder, `.${basename(file)}.${randomUUID()}.tmp`);
71
+ const handle = await open(temporary, 'wx', 0o600);
72
+ try {
73
+ try {
74
+ await handle.writeFile(JSON.stringify(tokens), 'utf8');
75
+ await handle.sync();
76
+ }
77
+ finally {
78
+ await handle.close();
79
+ }
80
+ await rename(temporary, file);
81
+ }
82
+ catch (error) {
83
+ // What this save created goes with it; a rename that failed left the old file as it was.
84
+ await unlink(temporary).catch(() => undefined);
85
+ throw error;
86
+ }
87
+ await flush(folder);
88
+ }
89
+ /** The file, and any temporary file a save left behind when its process died: it may hold a live refresh token. */
90
+ async function remove(file) {
91
+ const folder = dirname(file);
92
+ let entries;
93
+ try {
94
+ entries = await readdir(folder);
95
+ }
96
+ catch (error) {
97
+ if (codeOf(error) === 'ENOENT')
98
+ return;
99
+ throw error;
100
+ }
101
+ const prefix = `.${basename(file)}.`;
102
+ const left = (entry) => entry.startsWith(prefix) && entry.endsWith('.tmp') && UUID.test(entry.slice(prefix.length, -'.tmp'.length));
103
+ for (const name of [basename(file), ...entries.filter(left)]) {
104
+ try {
105
+ await unlink(join(folder, name));
106
+ }
107
+ catch (error) {
108
+ if (codeOf(error) !== 'ENOENT')
109
+ throw error;
110
+ }
111
+ }
112
+ await flush(folder);
113
+ }
114
+ /** The folder's entries to disk: without this, a power cut can undo a rename or a delete that had already shown. */
115
+ async function flush(folder) {
116
+ if (!POSIX)
117
+ return;
118
+ const handle = await open(folder, 'r');
119
+ try {
120
+ await handle.sync();
121
+ }
122
+ finally {
123
+ await handle.close();
124
+ }
125
+ }
126
+ /** A folder this user owns, which others can't write to: no one else can swap, plant or delete the file in it. */
127
+ async function mustBeMine(folder) {
128
+ if (!POSIX)
129
+ return;
130
+ const found = await stat(folder);
131
+ if (!ownedByMe(found) || (found.mode & 0o022) !== 0)
132
+ throw new Error(`the token file's folder must be this user's, and writable by them only: ${folder}`);
133
+ }
134
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/;
135
+ const ownedByMe = (found) => found.uid === process.getuid?.();
136
+ const codeOf = (error) => (error instanceof Error && 'code' in error ? error.code : undefined);
137
+ //# sourceMappingURL=fileStore.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"fileStore.js","sourceRoot":"","sources":["../../src/node/fileStore.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAE,MAAM,aAAa,CAAA;AACxC,OAAO,EAAE,SAAS,EAAc,MAAM,SAAS,CAAA;AAC/C,OAAO,EAAE,KAAK,EAAE,IAAI,EAAE,OAAO,EAAE,MAAM,EAAE,IAAI,EAAE,MAAM,EAAmB,MAAM,kBAAkB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AM,MAAM,GAAG,MAAM,IAAI,CAAC,MAAM,EAAE,GAAG,CAAC,CAAA;IACtC,IAAI,CAAC;QACH,MAAM,MAAM,CAAC,IAAI,EAAE,CAAA;IACrB,CAAC;YAAS,CAAC;QACT,MAAM,MAAM,CAAC,KAAK,EAAE,CAAA;IACtB,CAAC;AACH,CAAC;AAED,kHAAkH;AAClH,KAAK,UAAU,UAAU,CAAC,MAAc;IACtC,IAAI,CAAC,KAAK;QAAE,OAAM;IAClB,MAAM,KAAK,GAAG,MAAM,IAAI,CAAC,MAAM,CAAC,CAAA;IAChC,IAAI,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,CAAC,KAAK,CAAC,IAAI,GAAG,KAAK,CAAC,KAAK,CAAC;QAAE,MAAM,IAAI,KAAK,CAAC,2EAA2E,MAAM,EAAE,CAAC,CAAA;AAC3J,CAAC;AAED,MAAM,IAAI,GAAG,gEAAgE,CAAA;AAE7E,MAAM,SAAS,GAAG,CAAC,KAAY,EAAW,EAAE,CAAC,KAAK,CAAC,GAAG,KAAK,OAAO,CAAC,MAAM,EAAE,EAAE,CAAA;AAE7E,MAAM,MAAM,GAAG,CAAC,KAAc,EAAW,EAAE,CAAC,CAAC,KAAK,YAAY,KAAK,IAAI,MAAM,IAAI,KAAK,CAAC,CAAC,CAAC,KAAK,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAC,CAAA"}
@@ -7,3 +7,7 @@ export { fileLock } from './fileLock.js';
7
7
  export type { RevokeResult, Session, SessionFailure, SessionOptions, SessionTokens, TokenUpdate } from './session.js';
8
8
  export { finishSignIn } from './clientSecret.js';
9
9
  export type { ServerSignInOptions } from './clientSecret.js';
10
+ export { fileStore } from './fileStore.js';
11
+ export { keychainStore } from './keychainStore.js';
12
+ export type { KeychainStoreOptions } from './keychainStore.js';
13
+ export type { TokenStore } from './store.js';
@@ -1,11 +1,13 @@
1
1
  // The `@flipstream/sdk/node` entry: sign-in for Node apps, which the main entry never pulls in,
2
2
  // so a browser bundle has no node:http (#65), and the session, which holds a refresh token and so
3
3
  // belongs on a backend or in a CLI, never in browser code (D452), with a lock for a store several
4
- // processes share (#114).
4
+ // processes share (#114), and ready-made stores for it (#137).
5
5
  export { signInWithLoopback } from './loopback.js';
6
6
  export { isHeadless, parsePastedRedirect } from './headless.js';
7
7
  export { createSession, SessionError } from './session.js';
8
8
  export { fileLock } from './fileLock.js';
9
9
  // An app with a server signs in as a confidential client, with its client secret (#123).
10
10
  export { finishSignIn } from './clientSecret.js';
11
+ export { fileStore } from './fileStore.js';
12
+ export { keychainStore } from './keychainStore.js';
11
13
  //# sourceMappingURL=index.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/node/index.ts"],"names":[],"mappings":"AAAA,gGAAgG;AAChG,kGAAkG;AAClG,kGAAkG;AAClG,0BAA0B;AAC1B,OAAO,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAA;AAElD,OAAO,EAAE,UAAU,EAAE,mBAAmB,EAAE,MAAM,eAAe,CAAA;AAE/D,OAAO,EAAE,aAAa,EAAE,YAAY,EAAE,MAAM,cAAc,CAAA;AAC1D,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAA;AAExC,yFAAyF;AACzF,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAA"}
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/node/index.ts"],"names":[],"mappings":"AAAA,gGAAgG;AAChG,kGAAkG;AAClG,kGAAkG;AAClG,+DAA+D;AAC/D,OAAO,EAAE,kBAAkB,EAAE,MAAM,eAAe,CAAA;AAElD,OAAO,EAAE,UAAU,EAAE,mBAAmB,EAAE,MAAM,eAAe,CAAA;AAE/D,OAAO,EAAE,aAAa,EAAE,YAAY,EAAE,MAAM,cAAc,CAAA;AAC1D,OAAO,EAAE,QAAQ,EAAE,MAAM,eAAe,CAAA;AAExC,yFAAyF;AACzF,OAAO,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAA;AAEhD,OAAO,EAAE,SAAS,EAAE,MAAM,gBAAgB,CAAA;AAC1C,OAAO,EAAE,aAAa,EAAE,MAAM,oBAAoB,CAAA"}
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,136 @@
1
+ /*
2
+ * The keychain helper: one process that keychainStore keeps warm, sends its steps to one at a time,
3
+ * and kills at a step's deadline (D485, D495, after the CLI's keychain-child.ts). A keychain call can
4
+ * park forever: on macOS, when the keychain wants a prompt that no screen can show, the call never
5
+ * returns (cli#119). Nothing inside the process can end it then, not an AbortSignal, a worker's
6
+ * terminate, or process.exit, which joins the stuck thread. A process can be killed.
7
+ *
8
+ * - **Each request is one line on standard input,** with its id: the tokens never become an
9
+ * argument or a variable of this process, which other users can read.
10
+ * - **Standard input stays open as the parent's heartbeat.** When it closes, the parent is gone (it
11
+ * exited, threw, or was killed), and this process kills itself, rather than being left behind,
12
+ * warm or on a call that never returns.
13
+ * - **Each answer is one line on file descriptor 3,** a pipe of its own, with the request's id, in
14
+ * one synchronous write: whatever else prints to standard output (a preload in NODE_OPTIONS, say)
15
+ * can't garble it.
16
+ * - **One request at a time,** in the order they came.
17
+ * - **After an answer, nothing here refers to a token:** not the request line, the parsed request,
18
+ * the secret's bytes or the answer. The bytes this process holds, the ones it saves and the ones
19
+ * a read returns, are zeroed once the keychain call is done. Strings can't be: the request line,
20
+ * the tokens' JSON and the answer stay in this process's heap until the garbage collector reclaims
21
+ * them, as the same tokens do in the app itself.
22
+ */
23
+ import { writeSync } from 'node:fs';
24
+ import { createInterface } from 'node:readline';
25
+ import { z } from 'zod';
26
+ /** The tokens to save are the `set` step's `secret`. */
27
+ const zRequest = z.discriminatedUnion('op', [
28
+ z.strictObject({ id: z.number().int(), op: z.literal('get'), service: z.string(), account: z.string() }),
29
+ z.strictObject({ id: z.number().int(), op: z.literal('delete'), service: z.string(), account: z.string() }),
30
+ z.strictObject({ id: z.number().int(), op: z.literal('set'), service: z.string(), account: z.string(), secret: z.string() }),
31
+ ]);
32
+ // SIGKILL, never process.exit: a call stuck in the kernel would hold up an exit too.
33
+ const dieWithParent = () => {
34
+ process.kill(process.pid, 'SIGKILL');
35
+ };
36
+ // Installed first, for the whole life of the process: a parent that dies right after writing the
37
+ // request must still take this process with it.
38
+ process.stdin.on('end', dieWithParent);
39
+ process.stdin.on('close', dieWithParent);
40
+ const ANSWER_FD = 3;
41
+ const emit = (answer) => {
42
+ writeSync(ANSWER_FD, `${JSON.stringify(answer)}\n`);
43
+ };
44
+ /** The request in one line, or the id of a line that is no request (null when it has none). */
45
+ function requestOf(line) {
46
+ let parsed;
47
+ try {
48
+ parsed = JSON.parse(line);
49
+ }
50
+ catch {
51
+ return { id: null };
52
+ }
53
+ const request = zRequest.safeParse(parsed);
54
+ if (request.success)
55
+ return { request: request.data };
56
+ const id = z.object({ id: z.number().int() }).safeParse(parsed);
57
+ return { id: id.success ? id.data.id : null };
58
+ }
59
+ let keyring;
60
+ const loadKeyring = () => (keyring ??= import('@napi-rs/keyring').then((module) => ({ ok: true, module }), (error) => {
61
+ const missing = error instanceof Error && 'code' in error && error.code === 'ERR_MODULE_NOT_FOUND';
62
+ const outcome = missing ? { ok: false, error: 'not installed', missing: true } : { ok: false, error: `the keyring couldn't load: ${messageOf(error)}` };
63
+ return { ok: false, outcome };
64
+ }));
65
+ async function step(request) {
66
+ const loaded = await loadKeyring();
67
+ if (!loaded.ok)
68
+ return loaded.outcome;
69
+ const keyring = loaded.module;
70
+ // Linux: the Secret Service only. Without one, the library falls back to the kernel's keyring,
71
+ // which forgets everything at a reboot; a step that fails is better than a sign-in that vanishes.
72
+ try {
73
+ const entry = new keyring.AsyncEntry(request.service, request.account, { linux: { store: 'secret-service' } });
74
+ switch (request.op) {
75
+ case 'get': {
76
+ // 2.1.0's typings say `Uint8Array | undefined`, but its Rust returns `Option<Vec<u8>>`, which
77
+ // napi gives as a plain Array of numbers, or null for no item (Michel's live checks: on #142,
78
+ // 17 Oct, a read after a clear failed on null; on #159, 18 Oct, a read of a saved item failed
79
+ // on the Array's missing `.buffer`). A Uint8Array or a Buffer, as another version may give,
80
+ // reads the same. Anything else is no answer about the keychain, never nobody signed in.
81
+ const secret = await entry.getSecret();
82
+ if (secret === undefined || secret === null)
83
+ return { ok: true, value: null };
84
+ const isBytes = secret instanceof Uint8Array || (Array.isArray(secret) && secret.every((byte) => Number.isInteger(byte) && byte >= 0 && byte <= 255));
85
+ if (!isBytes)
86
+ return { ok: false, error: `the keyring gave the secret as ${Array.isArray(secret) ? 'an array of non-bytes' : typeof secret}, not bytes` };
87
+ // Bytes of their own, never Buffer's shared pool, so they can be zeroed once decoded.
88
+ const bytes = Uint8Array.from(secret);
89
+ try {
90
+ // An empty secret is nothing stored too: no save writes one.
91
+ if (bytes.length === 0)
92
+ return { ok: true, value: null };
93
+ return { ok: true, value: Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).toString('utf8') };
94
+ }
95
+ finally {
96
+ bytes.fill(0);
97
+ secret.fill(0);
98
+ }
99
+ }
100
+ case 'set': {
101
+ // Bytes of their own, never Buffer's shared pool, so they can be zeroed once saved.
102
+ const bytes = new Uint8Array(Buffer.byteLength(request.secret, 'utf8'));
103
+ Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength).write(request.secret, 'utf8');
104
+ try {
105
+ await entry.setSecret(bytes);
106
+ }
107
+ finally {
108
+ bytes.fill(0);
109
+ }
110
+ return { ok: true, value: null };
111
+ }
112
+ // Deleted, or nothing there to delete: either way nothing is saved now.
113
+ case 'delete':
114
+ await entry.deletePassword();
115
+ return { ok: true, value: null };
116
+ }
117
+ }
118
+ catch (error) {
119
+ // The keyring's own words: they never hold the secret, which is the value it didn't give.
120
+ return { ok: false, error: messageOf(error) };
121
+ }
122
+ }
123
+ const messageOf = (error) => (error instanceof Error ? error.message : String(error));
124
+ // One request at a time, in order: each waits for the one before it to be answered.
125
+ let tail = Promise.resolve();
126
+ createInterface({ input: process.stdin, crlfDelay: Infinity }).on('line', (line) => {
127
+ tail = tail.then(async () => {
128
+ const read = requestOf(line);
129
+ if (!('request' in read)) {
130
+ emit({ id: read.id, ok: false, error: 'the keychain step got no readable request' });
131
+ return;
132
+ }
133
+ emit({ id: read.request.id, ...(await step(read.request)) });
134
+ });
135
+ });
136
+ //# sourceMappingURL=keychainChild.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"keychainChild.js","sourceRoot":"","sources":["../../src/node/keychainChild.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,OAAO,EAAE,SAAS,EAAE,MAAM,SAAS,CAAA;AACnC,OAAO,EAAE,eAAe,EAAE,MAAM,eAAe,CAAA;AAC/C,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAA;AAEvB,wDAAwD;AACxD,MAAM,QAAQ,GAAG,CAAC,CAAC,kBAAkB,CAAC,IAAI,EAAE;IAC1C,CAAC,CAAC,YAAY,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,OAAO,EAAE,CAAC,CAAC,MAAM,EAAE,EAAE,OAAO,EAAE,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC;IACxG,CAAC,CAAC,YAAY,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,QAAQ,CAAC,EAAE,OAAO,EAAE,CAAC,CAAC,MAAM,EAAE,EAAE,OAAO,EAAE,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC;IAC3G,CAAC,CAAC,YAAY,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC,MAAM,EAAE,CAAC,GAAG,EAAE,EAAE,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,OAAO,EAAE,CAAC,CAAC,MAAM,EAAE,EAAE,OAAO,EAAE,CAA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,EAAE,CAAA;AAC3C,eAAe,CAAC,EAAE,KAAK,EAAE,OAAO,CAAC,KAAK,EAAE,SAAS,EAAE,QAAQ,EAAE,CAAC,CAAC,EAAE,CAAC,MAAM,EAAE,CAAC,IAAI,EAAE,EAAE;IACjF,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC,KAAK,IAAI,EAAE;QAC1B,MAAM,IAAI,GAAG,SAAS,CAAC,IAAI,CAAC,CAAA;QAC5B,IAAI,CAAC,CAAC,SAAS,IAAI,IAAI,CAAC,EAAE,CAAC;YACzB,IAAI,CAAC,EAAE,EAAE,EAAE,IAAI,CAAC,EAAE,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,2CAA2C,EAAE,CAAC,CAAA;YACpF,OAAM;QACR,CAAC;QACD,IAAI,CAAC,EAAE,EAAE,EAAE,IAAI,CAAC,OAAO,CAAC,EAAE,EAAE,GAAG,CAAC,MAAM,IAAI,CAAC,IAAI,CAAC,OAAO,CAAC,CAAC,EAAE,CAAC,CAAA;IAC9D,CAAC,CAAC,CAAA;AACJ,CAAC,CAAC,CAAA"}
@@ -0,0 +1,34 @@
1
+ import { type TokenStore } from './store.js';
2
+ export interface KeychainStoreOptions {
3
+ /** The item's service: your app's own name, such as `io.example.cli`. */
4
+ readonly service: string;
5
+ /** The item's account, such as the issuer the tokens are for. */
6
+ readonly account: string;
7
+ /**
8
+ * How long one step may take before it is ended, as `store_failed`: 30 s unless you say. A
9
+ * keychain prompt that a person must answer may need longer. Through `session.token()`, a read
10
+ * longer than the caller's 15 s wait is `unavailable`: a longer limit helps the app's own
11
+ * `tokens`, `save` and `clear`, and a refresh, which goes on after the caller's wait.
12
+ */
13
+ readonly timeoutMs?: number;
14
+ }
15
+ /**
16
+ * The tokens in the system's own credential store, for a CLI or a tool on the person's own machine:
17
+ * the macOS keychain, Windows' Credential Manager, or the Secret Service on Linux (GNOME Keyring,
18
+ * KWallet). One item (`service`, `account`) holds them; a save is one write, seen whole once it has
19
+ * succeeded, or not at all.
20
+ *
21
+ * - **It needs `@napi-rs/keyring`** (`npm install @napi-rs/keyring`), which nothing else in the
22
+ * SDK uses. Without it, every step fails as `store_failed`, and says so.
23
+ * - **Linux without a Secret Service** (a server, a container) fails as `store_failed`: use
24
+ * `fileStore` there.
25
+ * - **Its steps run in one helper process,** one at a time: started by the first step and kept
26
+ * warm while the app runs, for every keychain store of the process. A step past its `timeoutMs`
27
+ * (30 s) kills it, and the next step starts another. A step whose helper died before it answered
28
+ * (a terminal Ctrl-C reaches the helper too) runs once more on a fresh one, within its `timeoutMs`.
29
+ * It never keeps the app running, and it ends with the app. It is `process.execPath`, so it needs a Node that runs a script: not an Electron
30
+ * app (without `ELECTRON_RUN_AS_NODE`), a Node single-executable application, or a compiled Bun
31
+ * binary.
32
+ * - **Tokens over 2,560 bytes** fail the save, with nothing written.
33
+ */
34
+ export declare function keychainStore(options: KeychainStoreOptions): TokenStore;
@@ -0,0 +1,268 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { Socket } from 'node:net';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { z } from 'zod';
5
+ import { parse, storeOf } from './store.js';
6
+ /*
7
+ * Through `@napi-rs/keyring` (D481), an optional peer dependency that only this store needs, in one
8
+ * helper process that this process keeps warm for every keychain step (D495), killed at a step's
9
+ * deadline and started again for the next (D485): a keychain call that parks forever (cli#119)
10
+ * can't be ended in this process, not even by exiting it. The tokens go to the helper on its
11
+ * standard input, never as an argument or in its environment.
12
+ */
13
+ /**
14
+ * The child script beside this module, found when a step runs, never when the module loads: where
15
+ * import.meta.url is empty (an esbuild CommonJS bundle, say), only the keychain's steps fail, and
16
+ * the rest of this entry still loads.
17
+ */
18
+ function childScript() {
19
+ try {
20
+ return fileURLToPath(new URL('./keychainChild.js', import.meta.url));
21
+ }
22
+ catch {
23
+ return undefined;
24
+ }
25
+ }
26
+ const TIMEOUT_MS = 30_000;
27
+ // setTimeout's ceiling: a longer delay is cut to 1 ms, which would end every step at once.
28
+ const MAX_TIMEOUT_MS = 2_147_483_647;
29
+ /**
30
+ * The most a saved secret may hold, on every platform: Windows' Credential Manager keeps at most
31
+ * 2,560 bytes (CRED_MAX_CREDENTIAL_BLOB_SIZE). The macOS keychain and the Secret Service set no
32
+ * lower limit, and one limit everywhere means tokens that save on one platform save on all.
33
+ */
34
+ const LIMIT_BYTES = 2_560;
35
+ /**
36
+ * The tokens in the system's own credential store, for a CLI or a tool on the person's own machine:
37
+ * the macOS keychain, Windows' Credential Manager, or the Secret Service on Linux (GNOME Keyring,
38
+ * KWallet). One item (`service`, `account`) holds them; a save is one write, seen whole once it has
39
+ * succeeded, or not at all.
40
+ *
41
+ * - **It needs `@napi-rs/keyring`** (`npm install @napi-rs/keyring`), which nothing else in the
42
+ * SDK uses. Without it, every step fails as `store_failed`, and says so.
43
+ * - **Linux without a Secret Service** (a server, a container) fails as `store_failed`: use
44
+ * `fileStore` there.
45
+ * - **Its steps run in one helper process,** one at a time: started by the first step and kept
46
+ * warm while the app runs, for every keychain store of the process. A step past its `timeoutMs`
47
+ * (30 s) kills it, and the next step starts another. A step whose helper died before it answered
48
+ * (a terminal Ctrl-C reaches the helper too) runs once more on a fresh one, within its `timeoutMs`.
49
+ * It never keeps the app running, and it ends with the app. It is `process.execPath`, so it needs a Node that runs a script: not an Electron
50
+ * app (without `ELECTRON_RUN_AS_NODE`), a Node single-executable application, or a compiled Bun
51
+ * binary.
52
+ * - **Tokens over 2,560 bytes** fail the save, with nothing written.
53
+ */
54
+ export function keychainStore(options) {
55
+ const { service, account, timeoutMs = TIMEOUT_MS } = options;
56
+ if (service === '' || account === '')
57
+ throw new TypeError('the keychain store needs a service and an account');
58
+ if (!Number.isInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > MAX_TIMEOUT_MS)
59
+ throw new TypeError(`timeoutMs must be a whole number of ms, from 1 to ${MAX_TIMEOUT_MS}`);
60
+ const item = { service, account };
61
+ return storeOf(`keychain:${JSON.stringify([service, account])}`, async () => {
62
+ const saved = await inChild({ op: 'get', ...item }, timeoutMs);
63
+ return saved === null ? null : parse(saved);
64
+ }, async (tokens) => {
65
+ if (tokens === null) {
66
+ await inChild({ op: 'delete', ...item }, timeoutMs);
67
+ return;
68
+ }
69
+ const secret = JSON.stringify(tokens);
70
+ if (Buffer.byteLength(secret, 'utf8') > LIMIT_BYTES)
71
+ throw new Error(`the tokens are too long for the keychain store (over ${LIMIT_BYTES} bytes): nothing was saved`);
72
+ await inChild({ op: 'set', ...item, secret }, timeoutMs);
73
+ });
74
+ }
75
+ const STEP = { get: 'read', set: 'save', delete: 'delete' };
76
+ // `id` is the request's, or null for a request too broken to have one.
77
+ const zAnswer = z.union([
78
+ z.strictObject({ id: z.number().nullable(), ok: z.literal(true), value: z.string().nullable() }),
79
+ z.strictObject({ id: z.number().nullable(), ok: z.literal(false), error: z.string(), missing: z.literal(true).exactOptional() }),
80
+ ]);
81
+ /** This process's one helper: null until a step needs it, and again once it has died or been killed. */
82
+ let helper = null;
83
+ /** Steps go to the helper one at a time, in the order they were asked for. */
84
+ let queue = Promise.resolve();
85
+ let lastId = 0;
86
+ /**
87
+ * One step in the helper: the saved secret (`get`), or null, for none or for a step that saves
88
+ * nothing back. A helper that can't start, dies, or answers anything else has said nothing about the
89
+ * keychain, so each of those throws: never null, which would read as nobody signed in. The step's
90
+ * `timeoutMs` counts from the call, so a step behind a stuck one fails on time too, and is then
91
+ * never sent.
92
+ */
93
+ function inChild(request, timeoutMs) {
94
+ const script = childScript();
95
+ if (script === undefined)
96
+ return Promise.reject(new Error("the keychain store can't find its child script, keychainChild.js: this module's import.meta.url is empty, as a CommonJS bundle may leave it"));
97
+ return new Promise((resolve, reject) => {
98
+ const deadline = Date.now() + timeoutMs;
99
+ let settled = false;
100
+ // The helper this step was sent to, once it was: stuck on it if the deadline passes.
101
+ let sentTo = null;
102
+ const settle = (finish) => {
103
+ if (settled)
104
+ return;
105
+ settled = true;
106
+ clearTimeout(timer);
107
+ finish();
108
+ };
109
+ const late = () => {
110
+ settle(() => {
111
+ reject(new Error(`the keychain didn't answer within ${timeoutMs / 1000} s`));
112
+ });
113
+ };
114
+ const timer = setTimeout(() => {
115
+ if (sentTo !== null)
116
+ stop(sentTo);
117
+ late();
118
+ }, timeoutMs);
119
+ // Exactly once more, on a fresh helper and within the same deadline, when the first helper
120
+ // closed before it answered: one killed with the app's process group (a terminal Ctrl-C, which
121
+ // an app may handle and go on), or one that died while idle. Every step is safe to repeat: a
122
+ // read or a delete changes nothing twice, and a save writes the same tokens again.
123
+ const turn = async () => {
124
+ for (let attempt = 1; attempt <= 2; attempt++) {
125
+ if (settled)
126
+ return;
127
+ // By the clock as well as the timer: a thread blocked past the deadline gives this turn
128
+ // first, before the overdue timer has run, and a step that late is never sent.
129
+ if (Date.now() >= deadline) {
130
+ late();
131
+ return;
132
+ }
133
+ const current = helper ?? startHelper(script);
134
+ if (current instanceof Error) {
135
+ settle(() => {
136
+ reject(current);
137
+ });
138
+ return;
139
+ }
140
+ helper = current;
141
+ sentTo = current;
142
+ const answer = await ask(current, { id: ++lastId, ...request });
143
+ sentTo = null;
144
+ if (answer instanceof HelperClosed && attempt === 1)
145
+ continue;
146
+ settle(() => {
147
+ if (answer instanceof Error)
148
+ reject(answer);
149
+ else if (answer.ok)
150
+ resolve(answer.value);
151
+ else if (answer.missing === true)
152
+ reject(new Error('the keychain store needs the optional package @napi-rs/keyring, which is not installed: npm install @napi-rs/keyring'));
153
+ else
154
+ reject(new Error(`the keychain refused the ${STEP[request.op]}: ${answer.error}`));
155
+ });
156
+ return;
157
+ }
158
+ };
159
+ queue = queue.then(turn).catch((error) => {
160
+ settle(() => {
161
+ reject(error instanceof Error ? error : new Error(String(error)));
162
+ });
163
+ });
164
+ });
165
+ }
166
+ /** Sends one request, and waits for its answer, or for the helper to be gone. */
167
+ function ask(to, request) {
168
+ return new Promise((resolve) => {
169
+ to.waiting = {
170
+ id: request.id,
171
+ settle: (answer) => {
172
+ idle(to);
173
+ resolve(answer);
174
+ },
175
+ };
176
+ busy(to);
177
+ to.stdin.write(`${JSON.stringify(request)}\n`);
178
+ });
179
+ }
180
+ function startHelper(script) {
181
+ // The answers come on a pipe of their own (fd 3), apart from anything else printed to stdout.
182
+ const child = spawn(process.execPath, [script], { stdio: ['pipe', 'ignore', 'ignore', 'pipe'], windowsHide: true });
183
+ // Listened for before anything else: a spawn that fails (EMFILE, ENFILE) leaves no pipes, and
184
+ // emits 'error' on the next tick, which with no listener would end the app.
185
+ let started = null;
186
+ child.on('error', (error) => {
187
+ if (started !== null)
188
+ gone(started, new Error("the keychain helper couldn't start", { cause: error }));
189
+ });
190
+ const [stdin, , , answers] = child.stdio;
191
+ if (!(stdin instanceof Socket) || !(answers instanceof Socket)) {
192
+ child.kill('SIGKILL');
193
+ return new Error("the keychain helper's pipes didn't open");
194
+ }
195
+ const ready = { child, stdin, answers, waiting: null };
196
+ started = ready;
197
+ child.on('close', () => {
198
+ gone(ready, new HelperClosed());
199
+ });
200
+ // A helper that died closes the pipe under a write; its close reports it.
201
+ stdin.on('error', () => undefined);
202
+ let buffered = '';
203
+ answers.setEncoding('utf8');
204
+ answers.on('data', (chunk) => {
205
+ buffered += chunk;
206
+ for (let end = buffered.indexOf('\n'); end !== -1; end = buffered.indexOf('\n')) {
207
+ const answer = answerOf(buffered.slice(0, end));
208
+ buffered = buffered.slice(end + 1);
209
+ const waiting = ready.waiting;
210
+ // Anything but the awaited step's answer: the helper can't be trusted with the next step.
211
+ // Its close then settles the step that waits.
212
+ if (answer === undefined || waiting === null || answer.id !== waiting.id) {
213
+ stop(ready);
214
+ return;
215
+ }
216
+ ready.waiting = null;
217
+ waiting.settle(answer);
218
+ }
219
+ });
220
+ idle(ready);
221
+ return ready;
222
+ }
223
+ /** A helper that closed before it answered: the step it was answering may run once more (`inChild`). */
224
+ class HelperClosed extends Error {
225
+ constructor() {
226
+ super('the keychain step gave no readable answer');
227
+ this.name = 'HelperClosed';
228
+ }
229
+ }
230
+ /** A helper that died or couldn't start: the next step starts another, and the step it was answering fails with `reason`. */
231
+ function gone(of, reason) {
232
+ if (helper === of)
233
+ helper = null;
234
+ const waiting = of.waiting;
235
+ of.waiting = null;
236
+ waiting?.settle(reason);
237
+ }
238
+ /** Kills a helper, perhaps stuck in the kernel on a step past its deadline: SIGKILL, which needs no handler. The next step starts another. */
239
+ function stop(stopping) {
240
+ if (helper === stopping)
241
+ helper = null;
242
+ stopping.child.kill('SIGKILL');
243
+ }
244
+ // While a step waits, the helper and its pipes keep this process alive; between steps they don't,
245
+ // so a warm helper never holds up the app's exit. When this process ends, however it ends, the
246
+ // helper's standard input closes, and the helper kills itself.
247
+ function busy(of) {
248
+ of.child.ref();
249
+ of.stdin.ref();
250
+ of.answers.ref();
251
+ }
252
+ function idle(of) {
253
+ of.child.unref();
254
+ of.stdin.unref();
255
+ of.answers.unref();
256
+ }
257
+ function answerOf(line) {
258
+ let parsed;
259
+ try {
260
+ parsed = JSON.parse(line);
261
+ }
262
+ catch {
263
+ return undefined;
264
+ }
265
+ const answer = zAnswer.safeParse(parsed);
266
+ return answer.success ? answer.data : undefined;
267
+ }
268
+ //# sourceMappingURL=keychainStore.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"keychainStore.js","sourceRoot":"","sources":["../../src/node/keychainStore.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,KAAK,EAAqB,MAAM,oBAAoB,CAAA;AAC7D,OAAO,EAAE,MAAM,EAAE,MAAM,UAAU,CAAA;AACjC,OAAO,EAAE,aAAa,EAAE,MAAM,UAAU,CAAA;AACxC,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAA;AACvB,OAAO,EAAE,KAAK,EAAE,OAAO,EAAmB,MAAM,YAAY,CAAA;AAgB5D;;;;;;GAMG;AACH;;;;GAIG;AACH,SAAS,WAAW;IAClB,IAAI,CAAC;QACH,OAAO,aAAa,CAAC,IAAI,GAAG,CAAC,oBAAoB,EAAE,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,CAAC,CAAA;IACtE,CAA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