@flipstream/sdk 0.9.0 → 0.10.1

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 (87) hide show
  1. package/CHANGELOG.md +73 -0
  2. package/README.md +534 -487
  3. package/dist/api/backend.d.ts +182 -0
  4. package/dist/api/backend.js +314 -0
  5. package/dist/api/backend.js.map +1 -0
  6. package/dist/api/created.d.ts +5 -0
  7. package/dist/api/created.js +15 -0
  8. package/dist/api/created.js.map +1 -0
  9. package/dist/api/credentials.d.ts +36 -0
  10. package/dist/api/credentials.js +94 -0
  11. package/dist/api/credentials.js.map +1 -0
  12. package/dist/api/datasets.d.ts +94 -0
  13. package/dist/api/datasets.js +212 -0
  14. package/dist/api/datasets.js.map +1 -0
  15. package/dist/api/handoff.d.ts +34 -0
  16. package/dist/api/handoff.js +52 -0
  17. package/dist/api/handoff.js.map +1 -0
  18. package/dist/api/ids.d.ts +7 -0
  19. package/dist/api/ids.js +27 -0
  20. package/dist/api/ids.js.map +1 -0
  21. package/dist/api/index.d.ts +9 -1
  22. package/dist/api/log.d.ts +95 -0
  23. package/dist/api/log.js +213 -0
  24. package/dist/api/log.js.map +1 -0
  25. package/dist/api/me.d.ts +58 -0
  26. package/dist/api/me.js +64 -0
  27. package/dist/api/me.js.map +1 -0
  28. package/dist/api/members.d.ts +48 -0
  29. package/dist/api/members.js +102 -0
  30. package/dist/api/members.js.map +1 -0
  31. package/dist/api/organization.d.ts +11 -0
  32. package/dist/api/organization.js +15 -0
  33. package/dist/api/organization.js.map +1 -0
  34. package/dist/api/page.d.ts +33 -0
  35. package/dist/api/page.js +38 -0
  36. package/dist/api/page.js.map +1 -0
  37. package/dist/api/time.d.ts +3 -0
  38. package/dist/api/time.js +49 -0
  39. package/dist/api/time.js.map +1 -0
  40. package/dist/api/unsent.d.ts +6 -0
  41. package/dist/api/unsent.js +9 -0
  42. package/dist/api/unsent.js.map +1 -0
  43. package/dist/api/wallet.d.ts +45 -0
  44. package/dist/api/wallet.js +102 -0
  45. package/dist/api/wallet.js.map +1 -0
  46. package/dist/api/workspaces.d.ts +70 -0
  47. package/dist/api/workspaces.js +108 -0
  48. package/dist/api/workspaces.js.map +1 -0
  49. package/dist/core/body.js +23 -5
  50. package/dist/core/body.js.map +1 -1
  51. package/dist/core/call.d.ts +6 -0
  52. package/dist/core/call.js +1 -1
  53. package/dist/core/call.js.map +1 -1
  54. package/dist/core/fetch.js +4 -1
  55. package/dist/core/fetch.js.map +1 -1
  56. package/dist/core/names.d.ts +39 -0
  57. package/dist/core/names.js +41 -0
  58. package/dist/core/names.js.map +1 -1
  59. package/dist/core/read.d.ts +1 -1
  60. package/dist/core/read.js +7 -4
  61. package/dist/core/read.js.map +1 -1
  62. package/dist/core/result.d.ts +41 -3
  63. package/dist/core/result.js +18 -4
  64. package/dist/core/result.js.map +1 -1
  65. package/dist/core/secrets.d.ts +2 -0
  66. package/dist/core/secrets.js +33 -0
  67. package/dist/core/secrets.js.map +1 -0
  68. package/dist/core/transport.d.ts +6 -2
  69. package/dist/flipstream.d.ts +296 -4
  70. package/dist/flipstream.js +172 -23
  71. package/dist/flipstream.js.map +1 -1
  72. package/dist/index.d.ts +1 -1
  73. package/dist/node/clientSecret.js +1 -0
  74. package/dist/node/clientSecret.js.map +1 -1
  75. package/dist/node/fileLock.d.ts +20 -2
  76. package/dist/node/fileLock.js +22 -13
  77. package/dist/node/fileLock.js.map +1 -1
  78. package/dist/node/keychainStore.d.ts +10 -0
  79. package/dist/node/keychainStore.js +33 -13
  80. package/dist/node/keychainStore.js.map +1 -1
  81. package/dist/node/session.d.ts +1 -2
  82. package/dist/node/session.js +22 -14
  83. package/dist/node/session.js.map +1 -1
  84. package/dist/version.gen.js +1 -1
  85. package/dist/version.gen.js.map +1 -1
  86. package/docs/node-sign-in.md +503 -0
  87. package/package.json +3 -2
@@ -0,0 +1,503 @@
1
+ # Signing in from Node and the CLI: the reference
2
+
3
+ Part of `@flipstream/sdk`'s documentation, shipped in the package as `docs/node-sign-in.md`. The
4
+ basics, and signing in with a browser on the same machine, are in the package's README, under
5
+ "Signing in from Node and the CLI" ([README.md](../README.md)).
6
+
7
+ ## When the browser may not reach this machine
8
+
9
+ **The way for a CLI, or any app that waits while the person signs in.** In a remote session
10
+ nothing may say so (a tmux session started before the SSH login sets no `SSH_*` variable), and
11
+ the person's browser, on their own device, then can't load the address it's sent back to. Give
12
+ `signInWithLoopback` a `readPasted` as well: the person pastes that address back, and the same
13
+ sign-in finishes. Where their browser can reach the port, it does, and the prompt stops.
14
+
15
+ ```ts
16
+ import { discover } from '@flipstream/sdk'
17
+ import { signInWithLoopback } from '@flipstream/sdk/node'
18
+ import { createInterface } from 'node:readline/promises'
19
+
20
+ const server = await discover('https://auth.flipstream.io')
21
+ if (!server.ok) throw new Error(`sign-in is unavailable: ${server.error.kind}`)
22
+
23
+ const prompt = createInterface({ input: process.stdin, output: process.stdout })
24
+ const signedIn = await signInWithLoopback({
25
+ server: server.data,
26
+ clientId: '<your client id>',
27
+ scopes: ['<scope>'],
28
+ open: (url) => {
29
+ console.log(`Sign in at ${url}`)
30
+ },
31
+ // The signal fires once a paste can't be taken any more, and stops the prompt.
32
+ readPasted: (signal) => prompt.question('If your browser fails to load the page after signing in, paste its address here: ', { signal }),
33
+ })
34
+ prompt.close()
35
+ if (!signedIn.ok) throw new Error(`sign-in failed: ${signedIn.error.kind}`)
36
+ ```
37
+
38
+ - **Whichever comes first is taken,** the port's redirect or the paste, and only its code is
39
+ exchanged. Once one is taken, the port answers anything else with the failure page, and a later
40
+ paste is dropped.
41
+ - **A paste is checked before anything is sent,** as `parsePastedRedirect` checks one: this
42
+ sign-in's own address, then its state. A paste that fails ends the sign-in with its reason, such
43
+ as `wrong_state`, and nothing is exchanged.
44
+ - **A reader that rejects** ends the sign-in as `paste_failed`. `readPasted` is called once, just
45
+ after `open`.
46
+
47
+ ## Over SSH, in CI, or with no display
48
+
49
+ When no browser can come back to this machine, the person opens the URL on another device. The
50
+ redirect then fails to load, and they paste back the address it ended on. If one process waits for
51
+ them, `readPasted` above does this. The two halves below are for when the app can't wait, or
52
+ won't open a port: it keeps `pending` until the paste comes, for instance in a second command.
53
+ `isHeadless` tells you when no browser can come back.
54
+
55
+ ```ts
56
+ import { discover, finishSignIn, startSignIn } from '@flipstream/sdk'
57
+ import { isHeadless, parsePastedRedirect } from '@flipstream/sdk/node'
58
+ import { createInterface } from 'node:readline/promises'
59
+
60
+ const server = await discover('https://auth.flipstream.io')
61
+ if (!server.ok) throw new Error(`sign-in is unavailable: ${server.error.kind}`)
62
+
63
+ if (isHeadless(process.env)) {
64
+ const { url, pending } = await startSignIn({
65
+ server: server.data,
66
+ clientId: '<your client id>',
67
+ redirectUri: 'http://127.0.0.1:8976/callback',
68
+ scopes: ['<scope>'],
69
+ })
70
+ console.log(`Open this on any device and sign in:\n${url}`)
71
+
72
+ const prompt = createInterface({ input: process.stdin, output: process.stdout })
73
+ const pasted = parsePastedRedirect(await prompt.question('Paste the address your browser ended on: '), pending)
74
+ prompt.close()
75
+ if (!pasted.ok) throw new Error(`that isn't this sign-in's redirect: ${pasted.error.kind}`)
76
+
77
+ const signedIn = await finishSignIn(pasted.callbackUrl, pending)
78
+ if (!signedIn.ok) throw new Error(`sign-in failed: ${signedIn.error.kind}`)
79
+ }
80
+ ```
81
+
82
+ - **`isHeadless(env)`** is true in CI, in an SSH session, and on Linux without a display.
83
+ - **`parsePastedRedirect`** checks the pasted address as the loopback checks a redirect, before
84
+ anything is sent. Prompting for it is the app's.
85
+ - **`pending` holds the PKCE verifier,** a secret. Keep it only until the sign-in finishes, and
86
+ never log it.
87
+
88
+ ## Keeping the person signed in
89
+
90
+ `createSession` keeps an access token fresh from the tokens your store holds, and signs the person
91
+ out. It holds a refresh token, so it belongs in a CLI or on a server, never in browser code. The
92
+ SDK has two stores ready for it, which keep the store's rules for you.
93
+
94
+ ```ts
95
+ import { createFlipstream, discover } from '@flipstream/sdk'
96
+ import { createSession, fileStore, KeychainError, keychainStore, signInWithLoopback } from '@flipstream/sdk/node'
97
+ import { homedir } from 'node:os'
98
+ import { join } from 'node:path'
99
+
100
+ const issuer = 'https://auth.flipstream.io'
101
+
102
+ // The system's keychain by default. A file that only this user can read when the person asks for
103
+ // one, for a machine with no keychain (Linux without a Secret Service, as on most servers). A real
104
+ // app remembers that choice, in its config say, so every run uses the same store.
105
+ const inFile = process.argv.includes('--tokens-in-file')
106
+ const tokensFile = join(homedir(), '.config', 'example-cli', 'tokens.json')
107
+ const store = inFile ? fileStore(tokensFile) : keychainStore({ service: 'io.example.cli', account: issuer })
108
+ if (inFile) console.error(`Your sign-in is kept in ${tokensFile}, which only your user can read.`)
109
+
110
+ // A store that can't be read is the person's to fix: never a quiet switch from the keychain to a file.
111
+ const saved = await store.tokens().catch((error: unknown) => {
112
+ const why = error instanceof Error ? error.message : String(error)
113
+ if (inFile) throw new Error(`${tokensFile} can't be read (${why})`)
114
+ const kind = error instanceof KeychainError ? error.failure.kind : undefined
115
+ if (kind === 'unavailable') throw new Error('this machine has no keychain: run with --tokens-in-file')
116
+ if (kind === 'locked') throw new Error('the keychain is locked: unlock it, or log in at this machine once')
117
+ throw new Error(`the keychain can't be read (${why})`)
118
+ })
119
+
120
+ // Sign in once, and save the tokens. Only signing in needs the server first.
121
+ if (saved === null) {
122
+ const server = await discover(issuer)
123
+ if (!server.ok) throw new Error(`sign-in is unavailable: ${server.error.kind}`)
124
+ const signedIn = await signInWithLoopback({
125
+ server: server.data,
126
+ clientId: '<your client id>',
127
+ scopes: ['<scope>'],
128
+ open: (url) => {
129
+ console.log(`Sign in at ${url}`)
130
+ },
131
+ })
132
+ if (!signedIn.ok) throw new Error(`sign-in failed: ${signedIn.error.kind}`)
133
+ await store.save(signedIn.data)
134
+ }
135
+
136
+ // The session discovers the server itself, only when a refresh or a sign-out needs it.
137
+ const session = createSession({ issuer, clientId: '<your client id>', ...store })
138
+ const flipstream = createFlipstream({ app: { name: 'my-cli', version: '1.0.0' }, token: session.token })
139
+
140
+ // Signing out ends the session at the server, then clears the store through onTokens, and says
141
+ // how each went.
142
+ const signedOut = await session.revoke()
143
+ console.log(signedOut.kind)
144
+ if (signedOut.cleared === 'failed') {
145
+ // Where the store failed (read, lock or clear), and its own error: a KeychainError says why.
146
+ const { step, cause } = signedOut.failure
147
+ console.error(`the tokens may still be stored: the ${step} failed (${cause instanceof Error ? cause.message : String(cause)})`)
148
+ } else if (signedOut.cleared !== 'cleared' && signedOut.cleared !== 'kept') {
149
+ console.error(`the tokens may still be stored (${signedOut.cleared}): sign out again`)
150
+ }
151
+ ```
152
+
153
+ - **`issuer`,** as above, discovers the server itself, only when a refresh or a sign-out needs it,
154
+ and keeps it. A command holding a token with time left then sends nothing to the auth host, and
155
+ an outage there doesn't stop it. Give exactly one of `issuer` and `server`, from your own
156
+ `discover` (as in "Writing your own store" below).
157
+ - **Write the issuer exactly as its metadata names it,** with no slash at the end for
158
+ `https://auth.flipstream.io`. Any other spelling fails every discovery.
159
+ - **A discovery that gets no answer** (offline, a 5xx, a timeout) is `unavailable` from
160
+ `token()`. **One answered outside the contract** (a 404, metadata naming another issuer) is
161
+ `refresh_failed`, with the error: waiting won't mend it. From `revoke()`, either is
162
+ `unconfirmed`. A failed discovery is tried again at the next need.
163
+ - **What it guarantees:** with a store that shows only what it has saved and compares and sets on
164
+ `replaces`, and one lock shared by every process, the session never sends a refresh token another
165
+ refresh is spending, never hands out a token that wasn't saved, never overwrites a newer sign-in,
166
+ and says `revoked` only when the server took the access token just before and refuses it just
167
+ after. A lost answer or a failed save can still leave a spent token stored, and a server fault
168
+ between the two checks reads as `revoked`.
169
+ - **The ready-made stores keep both rules:** each shows only what it has saved, and saves a
170
+ refresh's tokens only while it still holds the ones they replace, so a newer sign-in is kept.
171
+ `save` is for a sign-in's tokens, and `clear` for an app that signs out without a session:
172
+ `session.revoke()` clears the store itself.
173
+ - **`fileStore(path)`** is for a machine with no keychain, chosen by the app or the person, never
174
+ switched to quietly when the keychain fails: tell them where the file is. **The risk:** anyone
175
+ who can read their files, as them or as an administrator, can use the tokens in it.
176
+ It writes the whole file under a temporary name in its folder, flushes it to disk, renames it
177
+ over the old one and flushes the folder: a reader, or a power cut, sees the old
178
+ tokens or the new ones, never half. The file's mode is 0600, and a folder it makes is 0700. It
179
+ refuses a file that is a link, isn't this user's or is open to others, and it won't read or
180
+ save in a folder others can write to. On Windows the folder isn't flushed, and nothing checks
181
+ who owns what. With `{ lock: true }` it also brings a lock for several processes (see
182
+ "Several processes on one store").
183
+ - **`keychainStore({ service, account })`** keeps the tokens in one item of the system's
184
+ credential store: the macOS keychain, Windows' Credential Manager, or the Secret Service on
185
+ Linux (GNOME Keyring, KWallet). It needs the optional package `@napi-rs/keyring`
186
+ (`npm install @napi-rs/keyring`).
187
+ - **Every failure of the keychain or its helper is a `KeychainError`,** which is also the
188
+ `cause` of a session's `store_failed`. Three failures are the store's own, not the
189
+ keychain's: `save` rejects tokens with no access token as a `TypeError` before any step; an
190
+ item holding something other than tokens fails its read with a plain `Error` that never
191
+ quotes it; and an update for tokens the item no longer holds is refused with a
192
+ `StoreMovedOnError`, which a sign-out reads as `kept` and a refresh reports as `store_failed`
193
+ (`save`). A `KeychainError`'s `failure.kind` says why:
194
+ - `unavailable`: there's no keychain on this machine, as on Linux with no Secret Service or no
195
+ D-Bus session (most servers and containers). It's the only kind after which a file may
196
+ stand in, if your app or the person chooses it;
197
+ - `locked`: the keychain is locked and can't ask to be unlocked, as on a Mac over SSH after a
198
+ reboot;
199
+ - `refused`: any other refusal, in the keychain's own words;
200
+ - `timeout`: the step took longer than its `timeoutMs`;
201
+ - `helper`: the helper process couldn't start, or ended before it answered (`exit` says how);
202
+ - `missing`: `@napi-rs/keyring` isn't installed, and the message names it;
203
+ - `too-long`: the tokens are over 2,560 bytes, so nothing was saved.
204
+
205
+ `unavailable` and `locked` are read from the keychain library's words, which carry no code.
206
+ Only words known for them match, and anything else is `refused`. The words for a locked
207
+ macOS keychain, and any on Windows, haven't been seen yet, so those failures may read as
208
+ `refused` for now.
209
+ - Its steps run in one helper process, one at a time. The first step starts it, and it stays
210
+ warm while your app runs (about 57 MB), so a step after that takes a keychain call, not a
211
+ process start. A step that takes longer than 30 s (`timeoutMs`) ends it, so a keychain prompt
212
+ that nobody answers can't hold up your app, and the next step starts another. A Ctrl-C in
213
+ the terminal reaches the helper too, and it ignores it, from before its own code loads. Not
214
+ during Node's own start-up, though, or any preload in `NODE_OPTIONS`: a Ctrl-C then still
215
+ ends a helper that is just starting. When your app ends, the helper ends
216
+ too: at once if it's idle or reading, or once it has finished the save or delete it's on, so
217
+ a refresh's save isn't lost to a Ctrl-C. It gives that step 1 s more at most, less than the
218
+ soonest `fileLock` lets another process take the lock your app held: at the soonest about
219
+ 2 s after your app ends, for an app whose heartbeat was running (3 s after its last touch),
220
+ when the clock has stepped or your app's clock runs behind. So a late save can't land over
221
+ that process's. For a helper's first step, that 1 s counts from the helper's own start, so a
222
+ helper slow to start (on a loaded machine, say) can't stretch it. A first step still going
223
+ when your app ends may therefore be cut sooner. A save waiting on a keychain prompt is ended
224
+ then. On macOS, the keychain's
225
+ own dialog stays open after a Ctrl-C until someone answers it, even once your app and its
226
+ helper have ended. A step whose helper died
227
+ before it answered runs once more on a fresh one, within the same 30 s. The helper never
228
+ keeps your app running. It's `process.execPath`, so it needs a Node that runs a script: not an Electron
229
+ app (without `ELECTRON_RUN_AS_NODE`), a Node single-executable application, or a compiled
230
+ Bun binary. A bundle must keep
231
+ `keychainChild.js` beside the module, with `zod` and `@napi-rs/keyring` resolvable from
232
+ there, and `import.meta.url` set. Where it doesn't (an esbuild CommonJS bundle, say), only the
233
+ keychain's steps fail, as `store_failed`.
234
+ - Through `session.token()`, a keychain read that takes longer than the caller's wait, 15 s
235
+ unless you pass `createSession({ waitMs })`, is `unavailable`. On macOS a read can wait on
236
+ an access dialog, every time, for an item another program saved: give `waitMs` as long as
237
+ the person may take. Each keychain step still ends at its own `timeoutMs`.
238
+ - Tokens over 2,560 bytes, Windows' limit, kept on every platform, fail the save with nothing
239
+ written. A Flipstream sign-in's tokens take about 1.6 KB.
240
+ - On Linux without a Secret Service, as on most servers, every step is `unavailable`: use
241
+ `fileStore`.
242
+ - Over SSH on a Mac it works too, unless the keychain is locked, as after a reboot with nobody
243
+ logged in at the screen. Then every step fails, as `locked` or at the latest after its 30 s,
244
+ until the person logs in at the machine once, or runs `security unlock-keychain`.
245
+ - On macOS, a script run by the same Node can read the item without a prompt, much as with a
246
+ file only the person can read.
247
+ - **After a Node upgrade, macOS may ask for the login password.** It knows a Node signed ad hoc,
248
+ as Homebrew's Node and a Node built from source are, only by its code's hash, which every
249
+ build changes. So after `brew upgrade node`, the item the old Node saved is, to macOS, another
250
+ program's. Each of the new Node's keychain steps on it then shows a dialog: a read, a
251
+ refresh's save, and a sign-out's clear.
252
+ - "Allow" answers that one step, and the next step asks again;
253
+ - "Always Allow" trusts that Node build with the item, until the next upgrade;
254
+ - nothing is refused: a sign-out still clears the tokens, after its dialogs.
255
+ - **Each dialog must be answered within the call's limits:** `session.token()`'s wait, 15 s
256
+ unless you pass `waitMs` (see "Through `session.token()`" above; #233's first read took
257
+ 18.6 s); each keychain step's `timeoutMs`, 30 s by default; and a sign-out's 10 s for its
258
+ revocation, which its first read's dialog counts against. So after an upgrade, a sign-out
259
+ whose first dialog is slow still clears the tokens, but ends `unconfirmed`, without
260
+ revoking them at the server.
261
+
262
+ nodejs.org's builds are signed with the Node.js Foundation's Developer ID, so they keep their
263
+ identity across versions, and an upgrade shouldn't ask. Checked on macOS 26 with a copy of
264
+ Homebrew's Node 26.12.1 re-signed ad hoc, standing in for an upgrade
265
+ (`scripts/live/keychain-upgrade.mjs`, #233). Not run: a real upgrade of either kind, and
266
+ "Always Allow".
267
+ - It's tested on macOS. Windows and Linux aren't tested yet.
268
+ - **One session per store,** shared by everything that uses it, or pass `lock`, a lock every
269
+ process takes, which settles only once its work has settled. Two sessions on one store refresh as
270
+ two processes would, and the server can end the session.
271
+ - **In one process,** the ready-made stores take each save, update and clear of the same file or
272
+ item in turn, so a sign-in saved while a refresh is saving is kept. A file counts as the same
273
+ however its folder is spelt (through a link, or in another case on macOS), but not when its own
274
+ name differs only in case.
275
+ - **Across processes,** take the session's lock around `save` and `clear` too: a store's compare
276
+ and its write are one step only among processes that take turns.
277
+ - **`session.token()`** rejects with a `SessionError` when there's no token to give: `signed-out`,
278
+ `unavailable`, `store_failed` or `refresh_failed`.
279
+ - **`unavailable` comes at the caller's wait,** the store's read included: 15 s unless you pass
280
+ `createSession({ waitMs })`. Give a store that can wait on a person, such as a keychain asking
281
+ for access, as long as they may take: 120 s when interactive, say. Only this wait changes. A
282
+ refresh still waits at most 60 s for its answer, and a sign-out sends nothing after its 10 s.
283
+ - **Before your process exits, `await session.settled()`.** It resolves once the session has no
284
+ refresh, save or sign-out in flight. `unavailable` comes while a refresh may still be saving the
285
+ token it got, and an exit then loses it. It never rejects and starts nothing.
286
+ - **It waits at most as long as the session's own limits.** A store that never answers a read or
287
+ a save holds it, and so does a lock that ignores its signal. A sign-out's store call still
288
+ running after 60 s isn't waited for.
289
+ - **The SDK's own stores answer every call.** A `keychainStore` save or clear is two steps of up
290
+ to its `timeoutMs` each, so keep `timeoutMs` at 30 s or under, or a sign-out's clear can be cut,
291
+ which it reports as `cut`.
292
+ - **Stop making calls before you await it:** calls that keep coming keep it waiting.
293
+ - **`session.revoke()`** ends the session the store holds when its turn comes, then, whatever the
294
+ server said, clears it through `onTokens` (`cleared`), once, in the same hold of the lock, so a
295
+ refresh can't bring it back. A sign-in saved after that is kept. A refresh token the session holds
296
+ only because saving it failed goes too, after the stored session, even once the store has moved
297
+ on, and the session then lets it go.
298
+ - **It answers once both are done:** `kind` is `revoked`, or `unconfirmed` with the reason, and
299
+ `cleared` says what became of the store:
300
+ - `cleared`: it was cleared;
301
+ - `kept`: there was nothing to clear: nothing stored, or the store moved on meanwhile, to a
302
+ newer sign-in, which is kept, or to another sign-out's clear;
303
+ - `failed`: the store failed, and `failure` says where and how: its `step` is `read`, `lock`
304
+ or `clear`, and its `cause` is what the store threw, unchanged, whether it's an `Error` or
305
+ not: a `KeychainError`, for instance, whose `failure.kind` and message say why. A clear it
306
+ refuses with anything but `StoreMovedOnError` counts as failed, at `clear`;
307
+ - `cut`: the lock or a store call took longer than its 60 s;
308
+ - `pending`: your `signal` answered first, and the clear goes on, unless the signal had already
309
+ fired when you called, when nothing runs at all.
310
+
311
+ After anything but `cleared` and `kept`, the tokens may still be stored: tell the person, so
312
+ they can sign out again.
313
+ - **It can take minutes on a stalled store, and longer behind one.** It sends nothing after its
314
+ 10 s, but it waits for the clear. First it waits for any turn ahead of it, for as long as that
315
+ takes: a refresh that is still saving, or a lock that ignores its signal. Then it waits at most
316
+ 60 s for the lock and for each of its three store calls, so up to about four minutes. It used to
317
+ answer within 10 s while the clear went on behind it. A lock held longer than its 60 s by
318
+ another process, or a store call that doesn't answer within its 60 s, leaves the store as it
319
+ was, unless that call finishes later on its own.
320
+ - **Pass a `signal` to stop waiting:** it answers at once, with `cleared: 'pending'`, and the
321
+ clear goes on. Await `session.settled()` before the process exits. A signal that has already
322
+ fired when you call runs nothing at all, and answers `pending` too.
323
+
324
+ **Writing your own store:** give `tokens` and `onTokens` instead, and keep the same two rules.
325
+ `tokens()` returns only what `onTokens` has durably saved: write first, show second. `onTokens`
326
+ writes only while the store's key is still `update.replaces`, and when it refuses, throws a
327
+ `StoreMovedOnError`, as the ready-made stores do. A sign-out whose clear is refused that way says
328
+ `kept`: the store holds a newer sign-in, or nothing. Any other throw is read as the store failing,
329
+ and the sign-out says `failed`. The key is the stored refresh token, or the access token when it has
330
+ none or an empty one (`refreshToken || accessToken`). Here in memory:
331
+
332
+ ```ts
333
+ import { discover } from '@flipstream/sdk'
334
+ import { createSession, StoreMovedOnError, type SessionTokens, type TokenUpdate } from '@flipstream/sdk/node'
335
+
336
+ const server = await discover('https://auth.flipstream.io')
337
+ if (!server.ok) throw new Error(`sign-in is unavailable: ${server.error.kind}`)
338
+
339
+ let stored: SessionTokens | null = null
340
+
341
+ const session = createSession({
342
+ server: server.data,
343
+ clientId: '<your client id>',
344
+ tokens: () => stored,
345
+ onTokens: (update: TokenUpdate) => {
346
+ // Compare and set: only while the store's key is still the one this update replaces.
347
+ if (stored === null || (stored.refreshToken || stored.accessToken) !== update.replaces) throw new StoreMovedOnError()
348
+ if (update.kind === 'cleared') {
349
+ stored = null
350
+ return
351
+ }
352
+ const { accessToken, expiresAt } = update
353
+ const refreshToken = update.kind === 'rotated' ? update.refreshToken : stored.refreshToken
354
+ stored = { accessToken, ...(refreshToken === undefined ? {} : { refreshToken }), ...(expiresAt === undefined ? {} : { expiresAt }) }
355
+ },
356
+ })
357
+ ```
358
+
359
+ ## Several processes on one store
360
+
361
+ `fileLock(path)` is a ready-made `lock` for Node processes that share one store, such as a CLI
362
+ run several times at once.
363
+
364
+ ```ts
365
+ import { homedir } from 'node:os'
366
+ import { join } from 'node:path'
367
+ import { discover } from '@flipstream/sdk'
368
+ import { createSession, fileLock, signInWithLoopback, type TokenStore } from '@flipstream/sdk/node'
369
+
370
+ const issuer = 'https://auth.flipstream.io'
371
+
372
+ // The store, chosen as above: the keychain, or the file the person asked for.
373
+ declare const store: TokenStore
374
+
375
+ // One lock file for every process on this machine.
376
+ const lock = fileLock(join(homedir(), '.config', 'example-cli', 'session.lock'))
377
+ const session = createSession({ issuer, clientId: '<your client id>', ...store, lock })
378
+
379
+ // A sign-in's save takes the same lock. Give it longer than the 10 s a lock file left by a crash
380
+ // can take to go stale.
381
+ if ((await store.tokens()) === null) {
382
+ const server = await discover(issuer)
383
+ if (!server.ok) throw new Error(`sign-in is unavailable: ${server.error.kind}`)
384
+ const signedIn = await signInWithLoopback({
385
+ server: server.data,
386
+ clientId: '<your client id>',
387
+ scopes: ['<scope>'],
388
+ open: (url) => {
389
+ console.log(`Sign in at ${url}`)
390
+ },
391
+ })
392
+ if (!signedIn.ok) throw new Error(`sign-in failed: ${signedIn.error.kind}`)
393
+ await lock(() => store.save(signedIn.data), AbortSignal.timeout(30_000))
394
+ }
395
+
396
+ // Signing out takes the lock itself, and clears the store inside it.
397
+ await session.revoke()
398
+ ```
399
+
400
+ - **Give every process the same absolute path,** on a local disk, for processes on this machine's
401
+ clock. A holder whose clock is 10 s or more behind, in a virtual machine sharing the folder say,
402
+ loses the lock after 2 to 3 s without a touch. The file exists only while a process holds the
403
+ lock. Its folder is made when it isn't there (on macOS and Linux, for this user only).
404
+ - **One refresh at a time:** the next process waits for it, reads the store again, and uses the
405
+ token it saved. A process still waiting at the refresh's 60 s deadline gives up, and sends
406
+ nothing.
407
+ - **A process that dies holding it** holds the others off for about 10 s: a holder touches the file
408
+ every second, and a waiter takes a file over once nobody has touched it for 10 s and it has
409
+ watched it for 3 s. A sign-out, which sends nothing after its 10 s, takes over a file left 10 s or
410
+ more before within about 3 s.
411
+ - **On Ctrl-C,** Node ends the process without letting a held lock go, and the next process waits
412
+ up to 10 s for it. An app that wants it gone sooner can handle SIGINT itself, and exit only once
413
+ every hold of its lock has settled, as below: a hold still waiting for the file gives up at once,
414
+ and one running its work finishes it. Waiting for the session's calls isn't enough: `token()` can
415
+ answer before its hold ends, and so can `revoke()` at its `signal`. Await `session.settled()`
416
+ too, so the session's own work has finished before the exit. The keychain store's own helper
417
+ ignores the Ctrl-C and finishes the step it's on, within that step's 30 s and at most 1 s after
418
+ the app has gone; the lock file goes when that work settles, as long as the app waits for it, as
419
+ below.
420
+
421
+ ```ts
422
+ import { homedir } from 'node:os'
423
+ import { join } from 'node:path'
424
+ import { fileLock, type Session } from '@flipstream/sdk/node'
425
+
426
+ // The lock for the session and the app's own saves, with every hold kept until it settles. Once
427
+ // the app is stopping, a hold still waiting for the file gives up, and a new one creates nothing
428
+ // (fileLock with a signal that has fired), so the wait below is only for work already running.
429
+ const file = fileLock(join(homedir(), '.config', 'example-cli', 'session.lock'))
430
+ const holds = new Set<Promise<unknown>>()
431
+ const stop = new AbortController()
432
+ const lock: typeof file = (work, signal) => {
433
+ const hold = file(work, AbortSignal.any([signal, stop.signal]))
434
+ holds.add(hold)
435
+ const done = (): void => {
436
+ holds.delete(hold)
437
+ }
438
+ hold.then(done, done)
439
+ return hold
440
+ }
441
+
442
+ declare const session: Session
443
+
444
+ // On Ctrl-C, exit once every hold has let its lock file go and the session's own work is done; a
445
+ // second Ctrl-C exits at once.
446
+ process.on('SIGINT', () => {
447
+ if (stop.signal.aborted) process.exit(130)
448
+ stop.abort(new Error('stopping'))
449
+ void Promise.all([Promise.allSettled([...holds]), session.settled()]).then(() => process.exit(130))
450
+ })
451
+ ```
452
+
453
+ - **A holder that can't touch its file for 10 s loses the lock,** and its work goes on beside the
454
+ next holder's: a thread blocked by a synchronous store waiting for a person, or a process stopped
455
+ by Ctrl-Z or a debugger. Keep your store asynchronous.
456
+ - **Take the same lock for the store's other writes,** a sign-in's `save`, or a `clear` without a
457
+ session, so they can't land between a refresh's compare and its set. `session.revoke()` takes it
458
+ for its own clear. Never take it inside `onTokens`, which runs inside it already: the lock isn't
459
+ reentrant.
460
+ - **On Windows, `fileLock` hasn't been tried yet.** What may differ there:
461
+ - the lock file and its folder take the folder's own permissions, so they aren't private to this
462
+ user;
463
+ - a lock file it isn't allowed to create, for the folder's permissions, reads as held by another
464
+ process: a refresh then waits out its 60 s and is `unavailable`, not `store_failed`. A file
465
+ antivirus still holds open reads as held only until it lets go;
466
+ - taking over a crashed holder's file fails while antivirus or the indexer has it open, as
467
+ `store_failed`;
468
+ - a path such as `\my-app\session.lock` counts as absolute but names a file on whichever drive
469
+ is current: give the drive as well (`C:\…`).
470
+
471
+ **A file store can bring its own lock.** `fileStore(path, { lock: true })` also returns `lock`:
472
+ `fileLock` on the file's path with `.lock` added, beside it. Every process, and every version of
473
+ your app, that opens the same file then takes the same lock, with no path of its own to agree on.
474
+
475
+ ```ts
476
+ import { homedir } from 'node:os'
477
+ import { join } from 'node:path'
478
+ import { createSession, fileStore, type SessionTokens } from '@flipstream/sdk/node'
479
+
480
+ const store = fileStore(join(homedir(), '.config', 'example-cli', 'tokens.json'), { lock: true })
481
+
482
+ // Spread in, so the session takes store.lock for its refreshes and sign-outs.
483
+ const session = createSession({ issuer: 'https://auth.flipstream.io', clientId: '<your client id>', ...store })
484
+
485
+ // A sign-in's save takes it too, as does a clear of your own.
486
+ declare const signedIn: SessionTokens
487
+ await store.lock(() => store.save(signedIn), AbortSignal.timeout(30_000))
488
+
489
+ // Signing out takes it itself.
490
+ await session.revoke()
491
+ ```
492
+
493
+ - **The store's own steps never take it,** so a `save` or `clear` inside it doesn't wait for itself,
494
+ and a clear leaves the lock file alone. Without `{ lock: true }`, nothing changes.
495
+ - **Don't pass a `lock` of your own as well:** `{ ...store, lock }` leaves the session on yours and
496
+ your saves on `store.lock`, and `{ lock, ...store }` swaps yours out without a word. Either way a
497
+ sign-in can land between a refresh's compare and its write.
498
+ - **Never call the session inside `store.lock`:** the lock isn't reentrant, so the call waits for
499
+ the hold it's in, and fails at its own limit (`token()` at its `waitMs`, `revoke()` once its turn
500
+ gives up on the lock, 60 s on, with `cut`).
501
+ - **Nor from your own `tokens` or `onTokens`,** if you wrap the store's: they run inside the
502
+ session's own turn. A `revoke()` there waits for that turn for ever, answering only at its
503
+ `signal`, and a `token()` answers only at its `waitMs`.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@flipstream/sdk",
3
- "version": "0.9.0",
3
+ "version": "0.10.1",
4
4
  "description": "TypeScript SDK for the Flipstream APIs: typed requests and checked answers, in Node and in browsers.",
5
5
  "keywords": [
6
6
  "flipstream",
@@ -40,6 +40,7 @@
40
40
  },
41
41
  "files": [
42
42
  "dist",
43
+ "docs",
43
44
  "README.md",
44
45
  "CHANGELOG.md",
45
46
  "LICENSE"
@@ -99,7 +100,7 @@
99
100
  "vite": "8.3.0"
100
101
  },
101
102
  "dependencies": {
102
- "zod": "4.6.2"
103
+ "zod": "4.6.6"
103
104
  },
104
105
  "overrides": {
105
106
  "js-yaml": "4.3.2"