@flipstream/sdk 0.5.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +25 -0
- package/README.md +127 -33
- package/dist/index.d.ts +1 -0
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/node/fileLock.js +26 -7
- package/dist/node/fileLock.js.map +1 -1
- package/dist/node/fileStore.d.ts +19 -0
- package/dist/node/fileStore.js +135 -0
- package/dist/node/fileStore.js.map +1 -0
- package/dist/node/index.d.ts +4 -0
- package/dist/node/index.js +3 -1
- package/dist/node/index.js.map +1 -1
- package/dist/node/keychainChild.d.ts +1 -0
- package/dist/node/keychainChild.js +100 -0
- package/dist/node/keychainChild.js.map +1 -0
- package/dist/node/keychainStore.d.ts +30 -0
- package/dist/node/keychainStore.js +150 -0
- package/dist/node/keychainStore.js.map +1 -0
- package/dist/node/session.d.ts +44 -12
- package/dist/node/session.js +166 -24
- package/dist/node/session.js.map +1 -1
- package/dist/node/store.d.ts +44 -0
- package/dist/node/store.js +91 -0
- package/dist/node/store.js.map +1 -0
- package/dist/version.gen.d.ts +2 -0
- package/dist/version.gen.js +4 -0
- package/dist/version.gen.js.map +1 -0
- package/package.json +9 -3
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
/*
|
|
2
|
+
* One keychain step in a process of its own, which keychainStore spawns and kills at its deadline
|
|
3
|
+
* (D485, after the CLI's keychain-child.ts). A keychain call can park forever: on macOS, when the
|
|
4
|
+
* keychain wants a prompt that no screen can show, the call never returns (cli#119). Nothing inside
|
|
5
|
+
* the process can end it then, not an AbortSignal, a worker's terminate, or process.exit, which
|
|
6
|
+
* joins the stuck thread. A process can be killed.
|
|
7
|
+
*
|
|
8
|
+
* - **The request is one line on standard input:** the tokens never become an argument or a
|
|
9
|
+
* 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, and
|
|
11
|
+
* this process kills itself, rather than being left behind on a call that never returns.
|
|
12
|
+
* - **The answer is one line on file descriptor 3,** a pipe of its own, in one synchronous write:
|
|
13
|
+
* whatever else prints to standard output (a preload in NODE_OPTIONS, say) can't garble it.
|
|
14
|
+
*/
|
|
15
|
+
import { writeSync } from 'node:fs';
|
|
16
|
+
import { z } from 'zod';
|
|
17
|
+
/** The tokens to save are the `set` step's `secret`. */
|
|
18
|
+
const zRequest = z.discriminatedUnion('op', [
|
|
19
|
+
z.strictObject({ op: z.literal('get'), service: z.string(), account: z.string() }),
|
|
20
|
+
z.strictObject({ op: z.literal('delete'), service: z.string(), account: z.string() }),
|
|
21
|
+
z.strictObject({ op: z.literal('set'), service: z.string(), account: z.string(), secret: z.string() }),
|
|
22
|
+
]);
|
|
23
|
+
// SIGKILL, never process.exit: a call stuck in the kernel would hold up an exit too.
|
|
24
|
+
const dieWithParent = () => {
|
|
25
|
+
process.kill(process.pid, 'SIGKILL');
|
|
26
|
+
};
|
|
27
|
+
// Installed first, for the whole life of the process: a parent that dies right after writing the
|
|
28
|
+
// request must still take this process with it.
|
|
29
|
+
process.stdin.on('end', dieWithParent);
|
|
30
|
+
process.stdin.on('close', dieWithParent);
|
|
31
|
+
const ANSWER_FD = 3;
|
|
32
|
+
const emit = (answer) => {
|
|
33
|
+
writeSync(ANSWER_FD, `${JSON.stringify(answer)}\n`);
|
|
34
|
+
};
|
|
35
|
+
function firstLine() {
|
|
36
|
+
return new Promise((resolve, reject) => {
|
|
37
|
+
let buffered = '';
|
|
38
|
+
process.stdin.setEncoding('utf8');
|
|
39
|
+
process.stdin.on('data', (chunk) => {
|
|
40
|
+
buffered += chunk;
|
|
41
|
+
const end = buffered.indexOf('\n');
|
|
42
|
+
if (end !== -1)
|
|
43
|
+
resolve(buffered.slice(0, end));
|
|
44
|
+
});
|
|
45
|
+
process.stdin.on('error', reject);
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
function requestOf(line) {
|
|
49
|
+
let parsed;
|
|
50
|
+
try {
|
|
51
|
+
parsed = JSON.parse(line);
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
return undefined;
|
|
55
|
+
}
|
|
56
|
+
const request = zRequest.safeParse(parsed);
|
|
57
|
+
return request.success ? request.data : undefined;
|
|
58
|
+
}
|
|
59
|
+
async function step(request) {
|
|
60
|
+
let keyring;
|
|
61
|
+
try {
|
|
62
|
+
keyring = await import('@napi-rs/keyring');
|
|
63
|
+
}
|
|
64
|
+
catch (error) {
|
|
65
|
+
const missing = error instanceof Error && 'code' in error && error.code === 'ERR_MODULE_NOT_FOUND';
|
|
66
|
+
return missing ? { ok: false, error: 'not installed', missing: true } : { ok: false, error: `the keyring couldn't load: ${messageOf(error)}` };
|
|
67
|
+
}
|
|
68
|
+
// Linux: the Secret Service only. Without one, the library falls back to the kernel's keyring,
|
|
69
|
+
// which forgets everything at a reboot; a step that fails is better than a sign-in that vanishes.
|
|
70
|
+
try {
|
|
71
|
+
const entry = new keyring.AsyncEntry(request.service, request.account, { linux: { store: 'secret-service' } });
|
|
72
|
+
switch (request.op) {
|
|
73
|
+
case 'get': {
|
|
74
|
+
// No item is nothing stored. 2.1.0's typings say `undefined` for one, but it gives `null`
|
|
75
|
+
// (Michel's live check on #142, 17 Oct: a read after a clear failed on `Buffer.from(null)`).
|
|
76
|
+
// An empty secret is nothing stored too: no save writes one.
|
|
77
|
+
const secret = await entry.getSecret();
|
|
78
|
+
return { ok: true, value: secret === undefined || secret === null || secret.length === 0 ? null : Buffer.from(secret).toString('utf8') };
|
|
79
|
+
}
|
|
80
|
+
case 'set':
|
|
81
|
+
await entry.setSecret(Buffer.from(request.secret, 'utf8'));
|
|
82
|
+
return { ok: true, value: null };
|
|
83
|
+
// Deleted, or nothing there to delete: either way nothing is saved now.
|
|
84
|
+
case 'delete':
|
|
85
|
+
await entry.deletePassword();
|
|
86
|
+
return { ok: true, value: null };
|
|
87
|
+
}
|
|
88
|
+
}
|
|
89
|
+
catch (error) {
|
|
90
|
+
// The keyring's own words: they never hold the secret, which is the value it didn't give.
|
|
91
|
+
return { ok: false, error: messageOf(error) };
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
const messageOf = (error) => (error instanceof Error ? error.message : String(error));
|
|
95
|
+
const request = requestOf(await firstLine());
|
|
96
|
+
emit(request === undefined ? { ok: false, error: 'the keychain step got no readable request' } : await step(request));
|
|
97
|
+
// Standard input, still open as the heartbeat, would keep this process alive. The answer has left in
|
|
98
|
+
// a synchronous write, and the keychain call has returned, so no stuck thread holds up the exit.
|
|
99
|
+
process.exit(0);
|
|
100
|
+
//# sourceMappingURL=keychainChild.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"keychainChild.js","sourceRoot":"","sources":["../../src/node/keychainChild.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AACH,OAAO,EAAE,SAAS,EAAE,MAAM,SAAS,CAAA;AACnC,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,OAAO,CAAC,KAAK,CAAC,EAAE,OAAO,EAAE,CAAC,CAAC,MAAM,EAAE,EAAE,OAAO,EAAE,CAAC,CAAC,MAAM,EAAE,EAAE,CAAC;IAClF,CAAC,CAAC,YAAY,CAAC,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;IACrF,CAAC,CAAC,YAAY,CAAC,EAAE,EAAE,EAAE,CAAC,CAAC,OAAO,CAAC,KAAK,CAAC,EAAE,OAAO,EAAE,CAAC,CAAC,MAAM,EAAE,EAAE,OAAO,EAAE,CAAC,CAAC,MAAM,EAAE,EAA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;AACrH,qGAAqG;AACrG,iGAAiG;AACjG,OAAO,CAAC,IAAI,CAAC,CAAC,CAAC,CAAA"}
|
|
@@ -0,0 +1,30 @@
|
|
|
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
|
+
* - **Each step runs in a process of its own,** ended after `timeoutMs` (30 s). It is
|
|
26
|
+
* `process.execPath`, so it needs a Node that runs a script: not an Electron app (without
|
|
27
|
+
* `ELECTRON_RUN_AS_NODE`), a Node single-executable application, or a compiled Bun binary.
|
|
28
|
+
* - **Tokens over 2,560 bytes** fail the save, with nothing written.
|
|
29
|
+
*/
|
|
30
|
+
export declare function keychainStore(options: KeychainStoreOptions): TokenStore;
|
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { Readable } from 'node:stream';
|
|
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 a
|
|
8
|
+
* child process for each step that is killed at the step's deadline (D485): a keychain call that
|
|
9
|
+
* parks forever (cli#119) can't be ended in this process, not even by exiting it. The tokens go to
|
|
10
|
+
* the child on its standard input, never as an argument or in its environment.
|
|
11
|
+
*/
|
|
12
|
+
/**
|
|
13
|
+
* The child script beside this module, found when a step runs, never when the module loads: where
|
|
14
|
+
* import.meta.url is empty (an esbuild CommonJS bundle, say), only the keychain's steps fail, and
|
|
15
|
+
* the rest of this entry still loads.
|
|
16
|
+
*/
|
|
17
|
+
function childScript() {
|
|
18
|
+
try {
|
|
19
|
+
return fileURLToPath(new URL('./keychainChild.js', import.meta.url));
|
|
20
|
+
}
|
|
21
|
+
catch {
|
|
22
|
+
return undefined;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
const TIMEOUT_MS = 30_000;
|
|
26
|
+
// setTimeout's ceiling: a longer delay is cut to 1 ms, which would end every step at once.
|
|
27
|
+
const MAX_TIMEOUT_MS = 2_147_483_647;
|
|
28
|
+
/**
|
|
29
|
+
* The most a saved secret may hold, on every platform: Windows' Credential Manager keeps at most
|
|
30
|
+
* 2,560 bytes (CRED_MAX_CREDENTIAL_BLOB_SIZE). The macOS keychain and the Secret Service set no
|
|
31
|
+
* lower limit, and one limit everywhere means tokens that save on one platform save on all.
|
|
32
|
+
*/
|
|
33
|
+
const LIMIT_BYTES = 2_560;
|
|
34
|
+
/**
|
|
35
|
+
* The tokens in the system's own credential store, for a CLI or a tool on the person's own machine:
|
|
36
|
+
* the macOS keychain, Windows' Credential Manager, or the Secret Service on Linux (GNOME Keyring,
|
|
37
|
+
* KWallet). One item (`service`, `account`) holds them; a save is one write, seen whole once it has
|
|
38
|
+
* succeeded, or not at all.
|
|
39
|
+
*
|
|
40
|
+
* - **It needs `@napi-rs/keyring`** (`npm install @napi-rs/keyring`), which nothing else in the
|
|
41
|
+
* SDK uses. Without it, every step fails as `store_failed`, and says so.
|
|
42
|
+
* - **Linux without a Secret Service** (a server, a container) fails as `store_failed`: use
|
|
43
|
+
* `fileStore` there.
|
|
44
|
+
* - **Each step runs in a process of its own,** ended after `timeoutMs` (30 s). It is
|
|
45
|
+
* `process.execPath`, so it needs a Node that runs a script: not an Electron app (without
|
|
46
|
+
* `ELECTRON_RUN_AS_NODE`), a Node single-executable application, or a compiled Bun binary.
|
|
47
|
+
* - **Tokens over 2,560 bytes** fail the save, with nothing written.
|
|
48
|
+
*/
|
|
49
|
+
export function keychainStore(options) {
|
|
50
|
+
const { service, account, timeoutMs = TIMEOUT_MS } = options;
|
|
51
|
+
if (service === '' || account === '')
|
|
52
|
+
throw new TypeError('the keychain store needs a service and an account');
|
|
53
|
+
if (!Number.isInteger(timeoutMs) || timeoutMs <= 0 || timeoutMs > MAX_TIMEOUT_MS)
|
|
54
|
+
throw new TypeError(`timeoutMs must be a whole number of ms, from 1 to ${MAX_TIMEOUT_MS}`);
|
|
55
|
+
const item = { service, account };
|
|
56
|
+
return storeOf(`keychain:${JSON.stringify([service, account])}`, async () => {
|
|
57
|
+
const saved = await inChild({ op: 'get', ...item }, timeoutMs);
|
|
58
|
+
return saved === null ? null : parse(saved);
|
|
59
|
+
}, async (tokens) => {
|
|
60
|
+
if (tokens === null) {
|
|
61
|
+
await inChild({ op: 'delete', ...item }, timeoutMs);
|
|
62
|
+
return;
|
|
63
|
+
}
|
|
64
|
+
const secret = JSON.stringify(tokens);
|
|
65
|
+
if (Buffer.byteLength(secret, 'utf8') > LIMIT_BYTES)
|
|
66
|
+
throw new Error(`the tokens are too long for the keychain store (over ${LIMIT_BYTES} bytes): nothing was saved`);
|
|
67
|
+
await inChild({ op: 'set', ...item, secret }, timeoutMs);
|
|
68
|
+
});
|
|
69
|
+
}
|
|
70
|
+
const STEP = { get: 'read', set: 'save', delete: 'delete' };
|
|
71
|
+
const zAnswer = z.union([
|
|
72
|
+
z.strictObject({ ok: z.literal(true), value: z.string().nullable() }),
|
|
73
|
+
z.strictObject({ ok: z.literal(false), error: z.string(), missing: z.literal(true).exactOptional() }),
|
|
74
|
+
]);
|
|
75
|
+
/**
|
|
76
|
+
* One step in the child: the saved secret (`get`), or null, for none or for a step that saves
|
|
77
|
+
* nothing back. A child that can't start, dies, or answers anything else has said nothing about the
|
|
78
|
+
* keychain, so each of those throws: never null, which would read as nobody signed in.
|
|
79
|
+
*/
|
|
80
|
+
function inChild(request, timeoutMs) {
|
|
81
|
+
const script = childScript();
|
|
82
|
+
if (script === undefined)
|
|
83
|
+
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"));
|
|
84
|
+
return new Promise((resolve, reject) => {
|
|
85
|
+
let settled = false;
|
|
86
|
+
const settle = (finish) => {
|
|
87
|
+
if (settled)
|
|
88
|
+
return;
|
|
89
|
+
settled = true;
|
|
90
|
+
clearTimeout(timer);
|
|
91
|
+
finish();
|
|
92
|
+
};
|
|
93
|
+
// The answer comes on a pipe of its own (fd 3), apart from anything else printed to stdout.
|
|
94
|
+
const child = spawn(process.execPath, [script], { stdio: ['pipe', 'ignore', 'ignore', 'pipe'], windowsHide: true });
|
|
95
|
+
const [stdin, , , answers] = child.stdio;
|
|
96
|
+
// SIGKILL: a process stuck in the kernel runs no handler.
|
|
97
|
+
const timer = setTimeout(() => {
|
|
98
|
+
child.kill('SIGKILL');
|
|
99
|
+
settle(() => {
|
|
100
|
+
reject(new Error(`the keychain didn't answer within ${timeoutMs / 1000} s`));
|
|
101
|
+
});
|
|
102
|
+
}, timeoutMs);
|
|
103
|
+
child.on('error', (error) => {
|
|
104
|
+
settle(() => {
|
|
105
|
+
reject(new Error("the keychain step couldn't start", { cause: error }));
|
|
106
|
+
});
|
|
107
|
+
});
|
|
108
|
+
if (stdin === null || !(answers instanceof Readable)) {
|
|
109
|
+
child.kill('SIGKILL');
|
|
110
|
+
settle(() => {
|
|
111
|
+
reject(new Error("the keychain step's pipes didn't open"));
|
|
112
|
+
});
|
|
113
|
+
return;
|
|
114
|
+
}
|
|
115
|
+
// A child that died early closes the pipe under the write; the close below reports it.
|
|
116
|
+
stdin.on('error', () => undefined);
|
|
117
|
+
// One line, and the pipe then stays open as the child's heartbeat until it exits.
|
|
118
|
+
stdin.write(`${JSON.stringify(request)}\n`);
|
|
119
|
+
let out = '';
|
|
120
|
+
answers.setEncoding('utf8');
|
|
121
|
+
answers.on('data', (chunk) => {
|
|
122
|
+
out += chunk;
|
|
123
|
+
});
|
|
124
|
+
child.on('close', () => {
|
|
125
|
+
settle(() => {
|
|
126
|
+
const answer = answerOf(out);
|
|
127
|
+
if (answer === undefined)
|
|
128
|
+
reject(new Error('the keychain step gave no readable answer'));
|
|
129
|
+
else if (answer.ok)
|
|
130
|
+
resolve(answer.value);
|
|
131
|
+
else if (answer.missing === true)
|
|
132
|
+
reject(new Error('the keychain store needs the optional package @napi-rs/keyring, which is not installed: npm install @napi-rs/keyring'));
|
|
133
|
+
else
|
|
134
|
+
reject(new Error(`the keychain refused the ${STEP[request.op]}: ${answer.error}`));
|
|
135
|
+
});
|
|
136
|
+
});
|
|
137
|
+
});
|
|
138
|
+
}
|
|
139
|
+
function answerOf(out) {
|
|
140
|
+
let parsed;
|
|
141
|
+
try {
|
|
142
|
+
parsed = JSON.parse(out.trim());
|
|
143
|
+
}
|
|
144
|
+
catch {
|
|
145
|
+
return undefined;
|
|
146
|
+
}
|
|
147
|
+
const answer = zAnswer.safeParse(parsed);
|
|
148
|
+
return answer.success ? answer.data : undefined;
|
|
149
|
+
}
|
|
150
|
+
//# sourceMappingURL=keychainStore.js.map
|
|
@@ -0,0 +1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M,CAAC,EAAE;oBAAE,OAAO,CAAC,MAAM,CAAC,KAAK,CAAC,CAAA;qBACpC,IAAI,MAAM,CAAC,OAAO,KAAK,IAAI;oBAAE,MAAM,CAAC,IAAI,KAAK,CAAC,sHAAsH,CAAC,CAAC,CAAA;;oBACtK,MAAM,CAAC,IAAI,KAAK,CAAC,4BAA4B,IAAI,CAAC,OAAO,CAAC,EAAE,CAAC,KAAK,MAAM,CAAC,KAAK,EAAE,CAAC,CAAC,CAAA;YACzF,CAAC,CAAC,CAAA;QACJ,CAAC,CAAC,CAAA;IACJ,CAAC,CAAC,CAAA;AACJ,CAAC;AAED,SAAS,QAAQ,CAAC,GAAW;IAC3B,IAAI,MAAe,CAAA;IACnB,IAAI,CAAC;QACH,MAAM,GAAG,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,IAAI,EAAE,CAAC,CAAA;IACjC,CAAC;IAAC,MAAM,CAAC;QACP,OAAO,SAAS,CAAA;IAClB,CAAC;IACD,MAAM,MAAM,GAAG,OAAO,CAAC,SAAS,CAAC,MAAM,CAAC,CAAA;IACxC,OAAO,MAAM,CAAC,OAAO,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,CAAC,CAAC,SAAS,CAAA;AACjD,CAAC"}
|
package/dist/node/session.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { TokenAsk } from '../core/fetch.js';
|
|
2
2
|
import type { ApiError } from '../core/result.js';
|
|
3
|
-
import type
|
|
3
|
+
import { type AuthServer } from '../auth/discovery.js';
|
|
4
4
|
import type { Tokens } from '../auth/signIn.js';
|
|
5
5
|
import { type AuthCallOptions } from '../auth/transport.js';
|
|
6
6
|
/** What the app's store holds: `finishSignIn`'s tokens fit. */
|
|
@@ -33,21 +33,38 @@ export type TokenUpdate =
|
|
|
33
33
|
readonly replaces: string;
|
|
34
34
|
}
|
|
35
35
|
/**
|
|
36
|
-
* The server ended
|
|
37
|
-
* store's key is still `replaces`, so a
|
|
36
|
+
* The session is over: the server ended it (`invalid_grant`), or the app signed out
|
|
37
|
+
* (`revoke()`). Delete the stored tokens, only while the store's key is still `replaces`, so a
|
|
38
|
+
* newer sign-in is kept. For a store that holds only an access token, `replaces` is that token.
|
|
38
39
|
*/
|
|
39
40
|
| {
|
|
40
41
|
readonly kind: 'cleared';
|
|
41
42
|
readonly replaces: string;
|
|
42
43
|
};
|
|
43
|
-
|
|
44
|
-
|
|
44
|
+
/**
|
|
45
|
+
* Where the session refreshes and signs out comes from exactly one of `issuer` and `server`:
|
|
46
|
+
* neither or both doesn't compile. From JavaScript, neither, both, or an issuer that is no https
|
|
47
|
+
* URL is a TypeError at creation.
|
|
48
|
+
*/
|
|
49
|
+
export type SessionOptions = Pick<AuthCallOptions, 'fetch'> & ({
|
|
50
|
+
/**
|
|
51
|
+
* The session discovers the server itself (`discover`'s rules), at the first refresh or
|
|
52
|
+
* sign-out that needs it, and keeps it (#130). A token with time left is handed out with
|
|
53
|
+
* nothing sent to the auth host. Written exactly as the metadata names it: for pulse-auth,
|
|
54
|
+
* `https://auth.flipstream.io`, with no slash at the end.
|
|
55
|
+
*/
|
|
56
|
+
readonly issuer: string;
|
|
57
|
+
readonly server?: never;
|
|
58
|
+
} | {
|
|
59
|
+
/** The server, as `discover` gave it, for an app that has discovered already. */
|
|
45
60
|
readonly server: AuthServer;
|
|
61
|
+
readonly issuer?: never;
|
|
62
|
+
}) & {
|
|
46
63
|
/** The app's own OAuth client ID (D421). */
|
|
47
64
|
readonly clientId: string;
|
|
48
65
|
/**
|
|
49
66
|
* The app's client secret, as a confidential client (#123): sent only in the Authorization header
|
|
50
|
-
* of the refresh and the revocation, to
|
|
67
|
+
* of the refresh and the revocation, to the server's own endpoints, and their failures then keep
|
|
51
68
|
* no server text (`finishSignIn`'s rule). Left out, the session is a public client's. Never log it.
|
|
52
69
|
*/
|
|
53
70
|
readonly clientSecret?: string | undefined;
|
|
@@ -67,8 +84,8 @@ export interface SessionOptions extends Pick<AuthCallOptions, 'fetch'> {
|
|
|
67
84
|
*/
|
|
68
85
|
readonly tokens: () => SessionTokens | null | Promise<SessionTokens | null>;
|
|
69
86
|
/**
|
|
70
|
-
* Saves a refresh's tokens, or clears them once the
|
|
71
|
-
*
|
|
87
|
+
* Saves a refresh's tokens, or clears them once the session is over, only while the store's key
|
|
88
|
+
* (`refreshToken || accessToken`) is still `update.replaces`. The session reads the
|
|
72
89
|
* store again just before, and lets the answer go when the store has moved on (a newer sign-in,
|
|
73
90
|
* or a sign-out); comparing and setting on `replaces` closes the moment between that read and
|
|
74
91
|
* this write, and a store that refuses then throws. A refresh's answer is used only once this has
|
|
@@ -89,6 +106,8 @@ export interface SessionOptions extends Pick<AuthCallOptions, 'fetch'> {
|
|
|
89
106
|
* The lock's promise must settle only once `work` has settled, as Web Locks does with its
|
|
90
107
|
* signal: a lock that lets go while `work` still runs (a mutex with a timeout) lets another
|
|
91
108
|
* process in beside a pending save. The session itself waits for `work` before its next turn.
|
|
109
|
+
* A sign-out's turn passes a signal that fires 60 s after the turn reaches the lock (D487): it
|
|
110
|
+
* waits that long to clear the store, though it sends nothing after its own 10 s.
|
|
92
111
|
*
|
|
93
112
|
* Without one, there must be one session per store, shared by everything that uses it: two
|
|
94
113
|
* sessions on one store, in one process (a backend making one per request) or in two, refresh
|
|
@@ -97,7 +116,7 @@ export interface SessionOptions extends Pick<AuthCallOptions, 'fetch'> {
|
|
|
97
116
|
* ends.
|
|
98
117
|
*/
|
|
99
118
|
readonly lock?: <T>(work: () => Promise<T>, signal: AbortSignal) => Promise<T>;
|
|
100
|
-
}
|
|
119
|
+
};
|
|
101
120
|
/** Why a session has no token to give. */
|
|
102
121
|
export type SessionFailure =
|
|
103
122
|
/**
|
|
@@ -183,9 +202,22 @@ export interface Session {
|
|
|
183
202
|
* fails, the live refresh token goes (the store's, or a rotation's whose save failed, D456), and
|
|
184
203
|
* the result is `unconfirmed`.
|
|
185
204
|
*
|
|
186
|
-
*
|
|
187
|
-
*
|
|
188
|
-
*
|
|
205
|
+
* A sign-out ends the session the store holds when its turn comes (#134), a newer sign-in from
|
|
206
|
+
* another terminal included: signing out means this person is signed out on this machine (D484).
|
|
207
|
+
* Its turn is queued at the call, and in one hold of the app's lock it revokes that session, then
|
|
208
|
+
* clears it from the store through `onTokens` (`cleared`), once, however the revocation went: in
|
|
209
|
+
* time or too late to send anything, aborted by the caller (D478), failed, or with any result. A
|
|
210
|
+
* sign-in saved after the turn read the store is kept. The caller waits for the clear within its
|
|
211
|
+
* 10 s.
|
|
212
|
+
*
|
|
213
|
+
* Once the turn reaches the lock, it waits at most 60 s for it, and at most 60 s for each store
|
|
214
|
+
* call; then it gives up, touching nothing more, and later turns run (D487). So after `timeout`
|
|
215
|
+
* or `aborted` the clear may still be on its way: 60 s for the lock and for each of its three
|
|
216
|
+
* store calls, so up to about four minutes after the turn reaches the lock, plus any queue ahead
|
|
217
|
+
* of it. A lock held longer than its 60 s by another process, or a store call that doesn't answer
|
|
218
|
+
* within its 60 s, leaves the store as it was. A clear the
|
|
219
|
+
* store fails leaves the tokens too: until the next refresh meets `invalid_grant`, or, for a store
|
|
220
|
+
* holding only an access token, until that token expires.
|
|
189
221
|
*/
|
|
190
222
|
revoke(options?: Pick<AuthCallOptions, 'signal'>): Promise<RevokeResult>;
|
|
191
223
|
}
|