@flipstream/sdk 0.6.0 → 0.8.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 +63 -0
  2. package/README.md +260 -43
  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 +2 -1
  18. package/dist/index.js +2 -0
  19. package/dist/index.js.map +1 -1
  20. package/dist/node/fileLock.d.ts +21 -0
  21. package/dist/node/fileLock.js +23 -54
  22. package/dist/node/fileLock.js.map +1 -1
  23. package/dist/node/fileStore.d.ts +23 -1
  24. package/dist/node/fileStore.js +20 -18
  25. package/dist/node/fileStore.js.map +1 -1
  26. package/dist/node/index.d.ts +2 -0
  27. package/dist/node/index.js +1 -0
  28. package/dist/node/index.js.map +1 -1
  29. package/dist/node/keychainChild.js +146 -54
  30. package/dist/node/keychainChild.js.map +1 -1
  31. package/dist/node/keychainError.d.ts +53 -0
  32. package/dist/node/keychainError.js +48 -0
  33. package/dist/node/keychainError.js.map +1 -0
  34. package/dist/node/keychainStore.d.ts +20 -9
  35. package/dist/node/keychainStore.js +207 -58
  36. package/dist/node/keychainStore.js.map +1 -1
  37. package/dist/node/loopback.js +1 -1
  38. package/dist/node/loopback.js.map +1 -1
  39. package/dist/node/session.d.ts +42 -3
  40. package/dist/node/session.js +95 -18
  41. package/dist/node/session.js.map +1 -1
  42. package/dist/node/store.d.ts +5 -1
  43. package/dist/node/store.js +12 -4
  44. package/dist/node/store.js.map +1 -1
  45. package/dist/query/catalog.d.ts +271 -2
  46. package/dist/query/catalog.js +93 -5
  47. package/dist/query/catalog.js.map +1 -1
  48. package/dist/query/query.d.ts +14 -5
  49. package/dist/query/query.js +21 -6
  50. package/dist/query/query.js.map +1 -1
  51. package/dist/spec/query-planner/index.d.ts +1 -1
  52. package/dist/spec/query-planner/types.gen.d.ts +35 -4
  53. package/dist/spec/query-planner/zod.gen.d.ts +257 -64
  54. package/dist/spec/query-planner/zod.gen.js +31 -5
  55. package/dist/spec/query-planner/zod.gen.js.map +1 -1
  56. package/dist/version.gen.js +1 -1
  57. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,68 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.8.0](https://github.com/flipstream-io/sdk/compare/typescript-v0.7.0...typescript-v0.8.0) (2026-10-23)
4
+
5
+
6
+ ### Features
7
+
8
+ * **typescript:** a KeychainError says why a keychain step failed ([#181](https://github.com/flipstream-io/sdk/issues/181)) ([4cafc6a](https://github.com/flipstream-io/sdk/commit/4cafc6ab8969214b80f0098ce36830f50147650e))
9
+ * **typescript:** createSession({ waitMs }) for stores that ask a person ([#188](https://github.com/flipstream-io/sdk/issues/188)) ([a45b790](https://github.com/flipstream-io/sdk/commit/a45b79034456dc284cddae746911c5c158bcbf4d))
10
+
11
+
12
+ ### Bug Fixes
13
+
14
+ * **typescript:** a keychain helper slow to start can't land a late save ([#191](https://github.com/flipstream-io/sdk/issues/191)) ([24a6cd0](https://github.com/flipstream-io/sdk/commit/24a6cd083258df09c72daf2a7b9b26d6e4657aca))
15
+ * **typescript:** the keychain helper finishes its step through a Ctrl-C ([#175](https://github.com/flipstream-io/sdk/issues/175)) ([7eced26](https://github.com/flipstream-io/sdk/commit/7eced261f5b143ad4820ba0715014e3b9467cb85))
16
+
17
+
18
+ ### Documentation
19
+
20
+ * **typescript:** on macOS, the keychain dialog stays open after Ctrl-C ([#189](https://github.com/flipstream-io/sdk/issues/189)) ([ef679bd](https://github.com/flipstream-io/sdk/commit/ef679bde3df414154e2c75340530120dbf85fd1c))
21
+
22
+ ## [0.7.0](https://github.com/flipstream-io/sdk/compare/typescript-v0.6.0...typescript-v0.7.0) (2026-10-18)
23
+
24
+
25
+ ### ⚠ BREAKING CHANGES
26
+
27
+ * **typescript:** Format is a union on type. Read decimals, format or thousandSeparator only after narrowing on type. An unknown type arrives as { type: 'unknown', declared }, and a known type with a part missing makes the answer invalid.
28
+
29
+ ### Features
30
+
31
+ * **typescript:** a field's format is a union on its type ([#156](https://github.com/flipstream-io/sdk/issues/156)) ([4427029](https://github.com/flipstream-io/sdk/commit/4427029741b88d54322596cad3458837b682eea9))
32
+ * **typescript:** an app can check a query's fields before it sends ([#184](https://github.com/flipstream-io/sdk/issues/184)) ([c708b78](https://github.com/flipstream-io/sdk/commit/c708b78cdced950d2dfb69dcf06a129a883899eb))
33
+ * **typescript:** fileStore(path, { lock: true }) also returns its lock ([#186](https://github.com/flipstream-io/sdk/issues/186)) ([f34b6f4](https://github.com/flipstream-io/sdk/commit/f34b6f4e7c431ad697dbdfc7d0f4b129f900e74b))
34
+ * **typescript:** onWarning decides where the SDK's warnings go ([#173](https://github.com/flipstream-io/sdk/issues/173)) ([11e1f58](https://github.com/flipstream-io/sdk/commit/11e1f589596af28cd129f88b236729acb440e000))
35
+ * **typescript:** session.settled() waits for the session before an exit ([#185](https://github.com/flipstream-io/sdk/issues/185)) ([9aa6dc5](https://github.com/flipstream-io/sdk/commit/9aa6dc51cde1ebecd51d2dcfb62c0cd0b4d75977))
36
+ * **typescript:** sign-in accepts a local http auth server, opt-in ([#172](https://github.com/flipstream-io/sdk/issues/172)) ([e626d08](https://github.com/flipstream-io/sdk/commit/e626d08651992144aba3464632272511cb39bea3))
37
+
38
+
39
+ ### Bug Fixes
40
+
41
+ * **typescript:** a sign-out also revokes a rotation held only in memory ([#167](https://github.com/flipstream-io/sdk/issues/167)) ([826f925](https://github.com/flipstream-io/sdk/commit/826f925b77289c40ff77137ad9ca19a47ee49d56))
42
+ * **typescript:** two spellings of one token file take one turn ([#174](https://github.com/flipstream-io/sdk/issues/174)) ([2c0d893](https://github.com/flipstream-io/sdk/commit/2c0d893cdff87b2b2839a32b10fb0806191774f6))
43
+
44
+
45
+ ### Performance Improvements
46
+
47
+ * **typescript:** keychainStore keeps one helper process warm ([#159](https://github.com/flipstream-io/sdk/issues/159)) ([f2823e6](https://github.com/flipstream-io/sdk/commit/f2823e6200152f12eb4f1eb436c76a46d1567a51))
48
+
49
+
50
+ ### Documentation
51
+
52
+ * **typescript:** fileLock on Ctrl-C, and the decisions behind its rules ([#166](https://github.com/flipstream-io/sdk/issues/166)) ([49d936d](https://github.com/flipstream-io/sdk/commit/49d936d0695f3f34d53c3ec56dfebb5258644b76))
53
+ * **typescript:** keychain by default, and fileLock's Windows limits ([#158](https://github.com/flipstream-io/sdk/issues/158)) ([d463a9c](https://github.com/flipstream-io/sdk/commit/d463a9cd0899751234551b0cb0f971b4a1312606))
54
+ * **typescript:** on Ctrl-C, a hold still waiting for the lock gives up ([#180](https://github.com/flipstream-io/sdk/issues/180)) ([cef2e80](https://github.com/flipstream-io/sdk/commit/cef2e805159dea0ebcd7604b8fb896b1e5f27e97))
55
+
56
+
57
+ ### Tests
58
+
59
+ * **typescript:** check:lock-live cleans up after a failed case ([#177](https://github.com/flipstream-io/sdk/issues/177)) ([648d36a](https://github.com/flipstream-io/sdk/commit/648d36a226e7f911037c18925822539cf32ad246))
60
+ * **typescript:** check:lock-live's third case, across two processes ([#179](https://github.com/flipstream-io/sdk/issues/179)) ([127444e](https://github.com/flipstream-io/sdk/commit/127444e8c54d8431ae696e7a1228a56743a68fcc))
61
+ * **typescript:** fileLock's slow cases run on a quarter of its timings ([#161](https://github.com/flipstream-io/sdk/issues/161)) ([e1126dd](https://github.com/flipstream-io/sdk/commit/e1126dd80b9e7ffd5c1a71e948fbe5e0be1fcb90))
62
+ * **typescript:** install:check holds the keyring to an optional peer ([#178](https://github.com/flipstream-io/sdk/issues/178)) ([ee2fce7](https://github.com/flipstream-io/sdk/commit/ee2fce7a21df523f7433a3d858fd258146652ed1))
63
+ * **typescript:** no lock turn outlives check:lock-live's clean-up ([#182](https://github.com/flipstream-io/sdk/issues/182)) ([bf603dc](https://github.com/flipstream-io/sdk/commit/bf603dcf24ddfaf2f3af0fce5895c3660c5f58d9))
64
+ * **typescript:** session.test.mjs ends in 5 s, not 60 s ([#162](https://github.com/flipstream-io/sdk/issues/162)) ([de96632](https://github.com/flipstream-io/sdk/commit/de96632c287b26ec6b4f58a373ab84640a95e208))
65
+
3
66
  ## [0.6.0](https://github.com/flipstream-io/sdk/compare/typescript-v0.5.0...typescript-v0.6.0) (2026-10-17)
4
67
 
5
68
 
package/README.md CHANGED
@@ -46,6 +46,39 @@ console.log(answer.rows, answer.lastRow)
46
46
  The catalogue names each source with its dimensions and metrics. `fs.catalog.get({ source })` gives
47
47
  one source.
48
48
 
49
+ Each dimension and metric has a `format`, a union on its `type`:
50
+ - `number`, `currency` and `percentage` carry `decimals`, and a `number` may carry
51
+ `thousandSeparator`;
52
+ - `date` carries its pattern, `YYYY-MM-DD`;
53
+ - `string` carries nothing more.
54
+
55
+ A type this version of the SDK doesn't know arrives as `{ type: 'unknown', declared }`, naming the
56
+ type it came as, and the rest of the catalogue reads as usual. The SDK then warns once per process
57
+ for each such type, on the console, or to your `onWarning` (see "Options"). The warning names the
58
+ type, the source and field it was first seen on, and how to update the SDK. A known type with a
59
+ part missing, such as a
60
+ `number` without `decimals`, makes the answer `invalid`, like any other answer that breaks the
61
+ contract.
62
+
63
+ ```ts
64
+ import type { Format } from '@flipstream/sdk'
65
+
66
+ function shownAs(format: Format): string {
67
+ switch (format.type) {
68
+ case 'number':
69
+ case 'currency':
70
+ case 'percentage':
71
+ return `${format.type}, ${format.decimals} decimals`
72
+ case 'date':
73
+ return `a date, ${format.format}`
74
+ case 'string':
75
+ return 'text'
76
+ case 'unknown':
77
+ return `as it comes (${format.declared})`
78
+ }
79
+ }
80
+ ```
81
+
49
82
  ## Signing in from Node and the CLI
50
83
 
51
84
  For an app that runs on the person's own machine, or in their terminal: a CLI, a script, a local
@@ -57,6 +90,12 @@ ready for them (see "Keeping the person signed in"). A web app signs in on its s
57
90
  In a TypeScript project, add `@types/node` (`npm install --save-dev @types/node`): this entry's
58
91
  types use Node's own.
59
92
 
93
+ **Against an auth server on your own machine,** while developing it, pass `allowLocalhostHttp: true`
94
+ to `discover`, `signInWithLoopback`, `finishSignIn` and `createSession`, as `createFlipstream` takes
95
+ it. Plain http is then accepted for `localhost`, `127.0.0.1` and `[::1]` only, and every endpoint
96
+ such a server names must be on its own origin. It's off unless your code sets it: the SDK never
97
+ reads it from the environment. Never set it in production.
98
+
60
99
  ### With a browser on the same machine
61
100
 
62
101
  `signInWithLoopback` opens a one-time server on `127.0.0.1`, on a port the system chooses, and
@@ -182,20 +221,32 @@ SDK has two stores ready for it, which keep the store's rules for you.
182
221
 
183
222
  ```ts
184
223
  import { createFlipstream, discover } from '@flipstream/sdk'
185
- import { createSession, fileStore, isHeadless, keychainStore, signInWithLoopback } from '@flipstream/sdk/node'
224
+ import { createSession, fileStore, KeychainError, keychainStore, signInWithLoopback } from '@flipstream/sdk/node'
186
225
  import { homedir } from 'node:os'
187
226
  import { join } from 'node:path'
188
227
 
189
228
  const issuer = 'https://auth.flipstream.io'
190
229
 
191
- // The system's keychain on the person's own machine; a file only this user can read on a server,
192
- // over SSH or in CI.
193
- const store = isHeadless(process.env)
194
- ? fileStore(join(homedir(), '.config', 'example-cli', 'tokens.json'))
195
- : keychainStore({ service: 'io.example.cli', account: issuer })
230
+ // The system's keychain by default. A file that only this user can read when the person asks for
231
+ // one, for a machine with no keychain (Linux without a Secret Service, as on most servers). A real
232
+ // app remembers that choice, in its config say, so every run uses the same store.
233
+ const inFile = process.argv.includes('--tokens-in-file')
234
+ const tokensFile = join(homedir(), '.config', 'example-cli', 'tokens.json')
235
+ const store = inFile ? fileStore(tokensFile) : keychainStore({ service: 'io.example.cli', account: issuer })
236
+ if (inFile) console.error(`Your sign-in is kept in ${tokensFile}, which only your user can read.`)
237
+
238
+ // A store that can't be read is the person's to fix: never a quiet switch from the keychain to a file.
239
+ const saved = await store.tokens().catch((error: unknown) => {
240
+ const why = error instanceof Error ? error.message : String(error)
241
+ if (inFile) throw new Error(`${tokensFile} can't be read (${why})`)
242
+ const kind = error instanceof KeychainError ? error.failure.kind : undefined
243
+ if (kind === 'unavailable') throw new Error('this machine has no keychain: run with --tokens-in-file')
244
+ if (kind === 'locked') throw new Error('the keychain is locked: unlock it, or log in at this machine once')
245
+ throw new Error(`the keychain can't be read (${why})`)
246
+ })
196
247
 
197
248
  // Sign in once, and save the tokens. Only signing in needs the server first.
198
- if ((await store.tokens()) === null) {
249
+ if (saved === null) {
199
250
  const server = await discover(issuer)
200
251
  if (!server.ok) throw new Error(`sign-in is unavailable: ${server.error.kind}`)
201
252
  const signedIn = await signInWithLoopback({
@@ -239,30 +290,74 @@ console.log(signedOut.kind)
239
290
  refresh's tokens only while it still holds the ones they replace, so a newer sign-in is kept.
240
291
  `save` is for a sign-in's tokens, and `clear` for an app that signs out without a session:
241
292
  `session.revoke()` clears the store itself.
242
- - **`fileStore(path)`** writes the whole file under a temporary name in its folder, flushes it to
243
- disk, renames it over the old one and flushes the folder: a reader, or a power cut, sees the old
293
+ - **`fileStore(path)`** is for a machine with no keychain, chosen by the app or the person, never
294
+ switched to quietly when the keychain fails: tell them where the file is. **The risk:** anyone
295
+ who can read their files, as them or as an administrator, can use the tokens in it.
296
+ It writes the whole file under a temporary name in its folder, flushes it to disk, renames it
297
+ over the old one and flushes the folder: a reader, or a power cut, sees the old
244
298
  tokens or the new ones, never half. The file's mode is 0600, and a folder it makes is 0700. It
245
299
  refuses a file that is a link, isn't this user's or is open to others, and it won't read or
246
300
  save in a folder others can write to. On Windows the folder isn't flushed, and nothing checks
247
- who owns what.
301
+ who owns what. With `{ lock: true }` it also brings a lock for several processes (see
302
+ "Several processes on one store").
248
303
  - **`keychainStore({ service, account })`** keeps the tokens in one item of the system's
249
304
  credential store: the macOS keychain, Windows' Credential Manager, or the Secret Service on
250
305
  Linux (GNOME Keyring, KWallet). It needs the optional package `@napi-rs/keyring`
251
- (`npm install @napi-rs/keyring`); without it, every step fails as `store_failed`, naming the
252
- package.
253
- - Each step runs in a process of its own, ended after 30 s (`timeoutMs`), so a keychain
254
- prompt that nobody answers can't hold up your app. That process is `process.execPath`, so
255
- it needs a Node that runs a script: not an Electron app (without `ELECTRON_RUN_AS_NODE`), a
256
- Node single-executable application, or a compiled Bun binary. A bundle must keep
306
+ (`npm install @napi-rs/keyring`).
307
+ - **Every failure of the keychain or its helper is a `KeychainError`,** which is also the
308
+ `cause` of a session's `store_failed`. Two failures are the store's own, not the keychain's:
309
+ `save` rejects tokens with no access token as a `TypeError` before any step, and an item
310
+ holding something other than tokens fails its read with a plain `Error` that never quotes
311
+ it. A `KeychainError`'s `failure.kind` says why:
312
+ - `unavailable`: there's no keychain on this machine, as on Linux with no Secret Service or no
313
+ D-Bus session (most servers and containers). It's the only kind after which a file may
314
+ stand in, if your app or the person chooses it;
315
+ - `locked`: the keychain is locked and can't ask to be unlocked, as on a Mac over SSH after a
316
+ reboot;
317
+ - `refused`: any other refusal, in the keychain's own words;
318
+ - `timeout`: the step took longer than its `timeoutMs`;
319
+ - `helper`: the helper process couldn't start, or ended before it answered (`exit` says how);
320
+ - `missing`: `@napi-rs/keyring` isn't installed, and the message names it;
321
+ - `too-long`: the tokens are over 2,560 bytes, so nothing was saved.
322
+
323
+ `unavailable` and `locked` are read from the keychain library's words, which carry no code.
324
+ Only words known for them match, and anything else is `refused`. The words for a locked
325
+ macOS keychain, and any on Windows, haven't been seen yet, so those failures may read as
326
+ `refused` for now.
327
+ - Its steps run in one helper process, one at a time. The first step starts it, and it stays
328
+ warm while your app runs (about 57 MB), so a step after that takes a keychain call, not a
329
+ process start. A step that takes longer than 30 s (`timeoutMs`) ends it, so a keychain prompt
330
+ that nobody answers can't hold up your app, and the next step starts another. A Ctrl-C in
331
+ the terminal reaches the helper too, and it ignores it. When your app ends, the helper ends
332
+ too: at once if it's idle or reading, or once it has finished the save or delete it's on, so
333
+ a refresh's save isn't lost to a Ctrl-C. It gives that step 1 s more at most, less than the
334
+ soonest `fileLock` lets another process take the lock your app held: at the soonest about
335
+ 2 s after your app ends, for an app whose heartbeat was running (3 s after its last touch),
336
+ when the clock has stepped or your app's clock runs behind. So a late save can't land over
337
+ that process's. For a helper's first step, that 1 s counts from the helper's own start, so a
338
+ helper slow to start (on a loaded machine, say) can't stretch it. A first step still going
339
+ when your app ends may therefore be cut sooner. A save waiting on a keychain prompt is ended
340
+ then. On macOS, the keychain's
341
+ own dialog stays open after a Ctrl-C until someone answers it, even once your app and its
342
+ helper have ended. A step whose helper died
343
+ before it answered runs once more on a fresh one, within the same 30 s. The helper never
344
+ keeps your app running. It's `process.execPath`, so it needs a Node that runs a script: not an Electron
345
+ app (without `ELECTRON_RUN_AS_NODE`), a Node single-executable application, or a compiled
346
+ Bun binary. A bundle must keep
257
347
  `keychainChild.js` beside the module, with `zod` and `@napi-rs/keyring` resolvable from
258
348
  there, and `import.meta.url` set. Where it doesn't (an esbuild CommonJS bundle, say), only the
259
349
  keychain's steps fail, as `store_failed`.
260
- - Through `session.token()`, a keychain read that takes longer than the caller's 15 s wait is
261
- `unavailable`. A longer `timeoutMs` helps your own `tokens`, `save` and `clear`, and a
262
- refresh, which goes on after the caller's wait.
350
+ - Through `session.token()`, a keychain read that takes longer than the caller's wait, 15 s
351
+ unless you pass `createSession({ waitMs })`, is `unavailable`. On macOS a read can wait on
352
+ an access dialog, every time, for an item another program saved: give `waitMs` as long as
353
+ the person may take. Each keychain step still ends at its own `timeoutMs`.
263
354
  - Tokens over 2,560 bytes, Windows' limit, kept on every platform, fail the save with nothing
264
355
  written. A Flipstream sign-in's tokens take about 1.6 KB.
265
- - On Linux without a Secret Service, as on most servers, use `fileStore`.
356
+ - On Linux without a Secret Service, as on most servers, every step is `unavailable`: use
357
+ `fileStore`.
358
+ - Over SSH on a Mac it works too, unless the keychain is locked, as after a reboot with nobody
359
+ logged in at the screen. Then every step fails, as `locked` or at the latest after its 30 s,
360
+ until the person logs in at the machine once, or runs `security unlock-keychain`.
266
361
  - On macOS, a script run by the same Node can read the item without a prompt, much as with a
267
362
  file only the person can read.
268
363
  - It's tested on macOS. Windows and Linux aren't tested yet.
@@ -270,15 +365,31 @@ console.log(signedOut.kind)
270
365
  process takes, which settles only once its work has settled. Two sessions on one store refresh as
271
366
  two processes would, and the server can end the session.
272
367
  - **In one process,** the ready-made stores take each save, update and clear of the same file or
273
- item in turn, so a sign-in saved while a refresh is saving is kept.
368
+ item in turn, so a sign-in saved while a refresh is saving is kept. A file counts as the same
369
+ however its folder is spelt (through a link, or in another case on macOS), but not when its own
370
+ name differs only in case.
274
371
  - **Across processes,** take the session's lock around `save` and `clear` too: a store's compare
275
372
  and its write are one step only among processes that take turns.
276
373
  - **`session.token()`** rejects with a `SessionError` when there's no token to give: `signed-out`,
277
- `unavailable` (after 15 s at most), `store_failed` or `refresh_failed`.
374
+ `unavailable`, `store_failed` or `refresh_failed`.
375
+ - **`unavailable` comes at the caller's wait,** the store's read included: 15 s unless you pass
376
+ `createSession({ waitMs })`. Give a store that can wait on a person, such as a keychain asking
377
+ for access, as long as they may take: 120 s when interactive, say. Only this wait changes. A
378
+ refresh still waits at most 60 s for its answer, and a sign-out answers at its 10 s.
379
+ - **Before your process exits, `await session.settled()`.** It resolves once the session has no
380
+ refresh, save or sign-out in flight. `unavailable` comes while a refresh may still be saving the
381
+ token it got, and an exit then loses it. It never rejects and starts nothing.
382
+ - **It waits at most as long as the session's own limits.** A store that never answers a read or
383
+ a save holds it, and so does a lock that ignores its signal. A sign-out's store call still
384
+ running after 60 s isn't waited for.
385
+ - **The SDK's own stores answer every call.** A `keychainStore` save or clear is two steps of up
386
+ to its `timeoutMs` each, so keep `timeoutMs` at 30 s or under, or a sign-out's clear can be cut.
387
+ - **Stop making calls before you await it:** calls that keep coming keep it waiting.
278
388
  - **`session.revoke()`** gives `revoked`, or `unconfirmed` with the reason. It ends the session the
279
389
  store holds when its turn comes, and, whatever the result, clears it through `onTokens`
280
390
  (`cleared`), once, in the same hold of the lock, so a refresh can't bring it back. A sign-in saved
281
- after that is kept. It waits for the clear at most 10 s. After `timeout` or `aborted`, the clear
391
+ after that is kept. A refresh token the session holds only because saving it failed goes too,
392
+ after the stored session, even once the store has moved on, and the session then lets it go. It waits for the clear at most 10 s. After `timeout` or `aborted`, the clear
282
393
  may still be on its way: once it reaches the lock, it waits at most 60 s for the lock and for each
283
394
  of its three store calls, so up to about four minutes. A lock held longer than its 60 s by another
284
395
  process, or a store call that doesn't answer within its 60 s, leaves the store as it was.
@@ -325,26 +436,36 @@ run several times at once.
325
436
  import { homedir } from 'node:os'
326
437
  import { join } from 'node:path'
327
438
  import { discover } from '@flipstream/sdk'
328
- import { createSession, fileLock, type SessionTokens, type TokenUpdate } from '@flipstream/sdk/node'
439
+ import { createSession, fileLock, signInWithLoopback, type TokenStore } from '@flipstream/sdk/node'
329
440
 
330
- const server = await discover('https://auth.flipstream.io')
331
- if (!server.ok) throw new Error(`sign-in is unavailable: ${server.error.kind}`)
441
+ const issuer = 'https://auth.flipstream.io'
332
442
 
333
- // Your store, kept on disk, which every process reads and writes.
334
- declare const store: {
335
- tokens(): Promise<SessionTokens | null>
336
- onTokens(update: TokenUpdate): Promise<void>
337
- clear(): Promise<void>
338
- }
443
+ // The store, chosen as above: the keychain, or the file the person asked for.
444
+ declare const store: TokenStore
339
445
 
340
446
  // One lock file for every process on this machine.
341
- const lock = fileLock(join(homedir(), '.config', 'my-app', 'session.lock'))
342
- const session = createSession({ server: server.data, clientId: '<your client id>', tokens: store.tokens, onTokens: store.onTokens, lock })
447
+ const lock = fileLock(join(homedir(), '.config', 'example-cli', 'session.lock'))
448
+ const session = createSession({ issuer, clientId: '<your client id>', ...store, lock })
343
449
 
344
- // The store's other writes take the same lock: here, the clear after signing out. Give them
345
- // longer than the 10 s a lock file left by a crash can take to go stale.
450
+ // A sign-in's save takes the same lock. Give it longer than the 10 s a lock file left by a crash
451
+ // can take to go stale.
452
+ if ((await store.tokens()) === null) {
453
+ const server = await discover(issuer)
454
+ if (!server.ok) throw new Error(`sign-in is unavailable: ${server.error.kind}`)
455
+ const signedIn = await signInWithLoopback({
456
+ server: server.data,
457
+ clientId: '<your client id>',
458
+ scopes: ['<scope>'],
459
+ open: (url) => {
460
+ console.log(`Sign in at ${url}`)
461
+ },
462
+ })
463
+ if (!signedIn.ok) throw new Error(`sign-in failed: ${signedIn.error.kind}`)
464
+ await lock(() => store.save(signedIn.data), AbortSignal.timeout(30_000))
465
+ }
466
+
467
+ // Signing out takes the lock itself, and clears the store inside it.
346
468
  await session.revoke()
347
- await lock(() => store.clear(), AbortSignal.timeout(30_000))
348
469
  ```
349
470
 
350
471
  - **Give every process the same absolute path,** on a local disk, for processes on this machine's
@@ -358,12 +479,94 @@ await lock(() => store.clear(), AbortSignal.timeout(30_000))
358
479
  every second, and a waiter takes a file over once nobody has touched it for 10 s and it has
359
480
  watched it for 3 s. A sign-out, which has 10 s in all, takes over a file left 10 s or more before
360
481
  within about 3 s.
482
+ - **On Ctrl-C,** Node ends the process without letting a held lock go, and the next process waits
483
+ up to 10 s for it. An app that wants it gone sooner can handle SIGINT itself, and exit only once
484
+ every hold of its lock has settled, as below: a hold still waiting for the file gives up at once,
485
+ and one running its work finishes it. Waiting for the session's calls isn't enough:
486
+ `token()` and `revoke()` can answer before their hold ends. Await `session.settled()` too, so the
487
+ session's own work has finished before the exit. The keychain store's own helper ignores the
488
+ Ctrl-C and finishes the step it's on, within that step's 30 s and at most 1 s after the app has
489
+ gone; the lock file goes when that work settles, as long as the app waits for it, as below.
490
+
491
+ ```ts
492
+ import { homedir } from 'node:os'
493
+ import { join } from 'node:path'
494
+ import { fileLock, type Session } from '@flipstream/sdk/node'
495
+
496
+ // The lock for the session and the app's own saves, with every hold kept until it settles. Once
497
+ // the app is stopping, a hold still waiting for the file gives up, and a new one creates nothing
498
+ // (fileLock with a signal that has fired), so the wait below is only for work already running.
499
+ const file = fileLock(join(homedir(), '.config', 'example-cli', 'session.lock'))
500
+ const holds = new Set<Promise<unknown>>()
501
+ const stop = new AbortController()
502
+ const lock: typeof file = (work, signal) => {
503
+ const hold = file(work, AbortSignal.any([signal, stop.signal]))
504
+ holds.add(hold)
505
+ const done = (): void => {
506
+ holds.delete(hold)
507
+ }
508
+ hold.then(done, done)
509
+ return hold
510
+ }
511
+
512
+ declare const session: Session
513
+
514
+ // On Ctrl-C, exit once every hold has let its lock file go and the session's own work is done; a
515
+ // second Ctrl-C exits at once.
516
+ process.on('SIGINT', () => {
517
+ if (stop.signal.aborted) process.exit(130)
518
+ stop.abort(new Error('stopping'))
519
+ void Promise.all([Promise.allSettled([...holds]), session.settled()]).then(() => process.exit(130))
520
+ })
521
+ ```
522
+
361
523
  - **A holder that can't touch its file for 10 s loses the lock,** and its work goes on beside the
362
524
  next holder's: a thread blocked by a synchronous store waiting for a person, or a process stopped
363
525
  by Ctrl-Z or a debugger. Keep your store asynchronous.
364
- - **Take the same lock for the store's other writes,** such as saving a sign-in's tokens, or
365
- clearing the store after `revoke()`, so they can't land between a refresh's compare and its set.
366
- Never inside `onTokens`, which runs inside it already: the lock isn't reentrant.
526
+ - **Take the same lock for the store's other writes,** a sign-in's `save`, or a `clear` without a
527
+ session, so they can't land between a refresh's compare and its set. `session.revoke()` takes it
528
+ for its own clear. Never take it inside `onTokens`, which runs inside it already: the lock isn't
529
+ reentrant.
530
+ - **On Windows, `fileLock` hasn't been tried yet.** What may differ there:
531
+ - the lock file and its folder take the folder's own permissions, so they aren't private to this
532
+ user;
533
+ - a lock file it isn't allowed to create, for the folder's permissions, reads as held by another
534
+ process: a refresh then waits out its 60 s and is `unavailable`, not `store_failed`. A file
535
+ antivirus still holds open reads as held only until it lets go;
536
+ - taking over a crashed holder's file fails while antivirus or the indexer has it open, as
537
+ `store_failed`;
538
+ - a path such as `\my-app\session.lock` counts as absolute but names a file on whichever drive
539
+ is current: give the drive as well (`C:\…`).
540
+
541
+ **A file store can bring its own lock.** `fileStore(path, { lock: true })` also returns `lock`:
542
+ `fileLock` on the file's path with `.lock` added, beside it. Every process, and every version of
543
+ your app, that opens the same file then takes the same lock, with no path of its own to agree on.
544
+
545
+ ```ts
546
+ import { homedir } from 'node:os'
547
+ import { join } from 'node:path'
548
+ import { createSession, fileStore, type SessionTokens } from '@flipstream/sdk/node'
549
+
550
+ const store = fileStore(join(homedir(), '.config', 'example-cli', 'tokens.json'), { lock: true })
551
+
552
+ // Spread in, so the session takes store.lock for its refreshes and sign-outs.
553
+ const session = createSession({ issuer: 'https://auth.flipstream.io', clientId: '<your client id>', ...store })
554
+
555
+ // A sign-in's save takes it too, as does a clear of your own.
556
+ declare const signedIn: SessionTokens
557
+ await store.lock(() => store.save(signedIn), AbortSignal.timeout(30_000))
558
+
559
+ // Signing out takes it itself.
560
+ await session.revoke()
561
+ ```
562
+
563
+ - **The store's own steps never take it,** so a `save` or `clear` inside it doesn't wait for itself,
564
+ and a clear leaves the lock file alone. Without `{ lock: true }`, nothing changes.
565
+ - **Don't pass a `lock` of your own as well:** `{ ...store, lock }` leaves the session on yours and
566
+ your saves on `store.lock`, and `{ lock, ...store }` swaps yours out without a word. Either way a
567
+ sign-in can land between a refresh's compare and its write.
568
+ - **Never call the session inside `store.lock`:** the lock isn't reentrant, so the call waits for
569
+ the hold it's in, and fails at its own limit (`token()` at its `waitMs`, `revoke()` at 10 s).
367
570
 
368
571
  ## In a browser
369
572
 
@@ -417,7 +620,10 @@ if (!signedIn.ok) throw new Error(`sign-in failed: ${signedIn.error.kind}`)
417
620
  - **The secret goes only in the token request's `Authorization: Basic` header** (RFC 6749 §2.3.1),
418
621
  and only to the token endpoint of the `server` you pass. A `pending` that names another server,
419
622
  or another client ID than `clientId`, is refused, with nothing sent. The secret is never in a body, a URL, a result or an error, and
420
- the SDK logs nothing. A `fetch` you pass sees the request, header included: don't log it.
623
+ never logged. The SDK logs nothing but one warning per catalogue format type it doesn't know,
624
+ which never holds a token, a secret or a field's value, and which `onWarning` routes or
625
+ silences. A `fetch` you pass sees the request,
626
+ header included: don't log it.
421
627
  - **A failure keeps its kind, status and OAuth code** (`invalid_client`, `invalid_grant`, …), but
422
628
  not the server's description or body (an empty `message` or `text`): a server or proxy that
423
629
  echoes the request would put the credentials there.
@@ -444,6 +650,11 @@ throws the failure as an `ApiFailure` carrying its `error`, for callers who'd ra
444
650
  `dimensions`, `metrics`, `filters`, `sort`, `offset` and `rows`. A request with any other key,
445
651
  `table` included, is `refused` with nothing sent, and `error.fields` names each one, so a
446
652
  misspelt field never quietly changes the numbers.
653
+ - **`refusedQueryFields(request)`** runs that check on its own, with no client and nothing
654
+ sent. It gives the same names, sorted, or `[]` for a request `fs.query` would send. So an
655
+ app can refuse a request before anything else it does: a CLI given a raw JSON body, for
656
+ instance, before its other calls. It reads only the keys; a missing `source` is still the
657
+ API's to refuse.
447
658
  - **`fs.health()`** gives the planner's answer to `GET /health`, an object of strings
448
659
  (`{ status: 'ok' }` today). It works signed out: no token is asked for or sent, so it tells "the
449
660
  service is down" from "the sign-in is wrong".
@@ -517,8 +728,9 @@ function explain(error: ApiError): string {
517
728
  - `not_a_url` and `wrong_redirect`: a pasted address that isn't a URL, or isn't this sign-in's
518
729
  redirect (`parsePastedRedirect`, or `signInWithLoopback`'s `readPasted`).
519
730
 
520
- There, `refused` also covers an issuer that isn't https, and a `pending` that isn't one (from
521
- storage the app couldn't read back). Nothing is sent for either.
731
+ There, `refused` also covers an issuer that isn't https (unless it's http on this machine, with
732
+ `allowLocalhostHttp`), and a `pending` that isn't one (from storage the app couldn't read back).
733
+ Nothing is sent for either.
522
734
 
523
735
  ## Options
524
736
 
@@ -532,6 +744,7 @@ const fs = createFlipstream({
532
744
  token: ({ rejected }) => session.accessToken(rejected),
533
745
  fetch: globalThis.fetch, // optional: every request goes through it
534
746
  hosts: { query: 'https://query.flipstream.io' }, // optional: the default
747
+ onWarning: (message) => process.stderr.write(`${message}\n`), // optional: console.warn by default
535
748
  })
536
749
 
537
750
  const controller = new AbortController()
@@ -554,6 +767,10 @@ await fs.catalog.list({ signal: controller.signal, deadlineMs: 10_000 })
554
767
  - **Deadlines:** 60 s for `query`, 10 s for `health` and 30 s for the rest, every attempt and
555
768
  wait included. `deadlineMs` sets one call's.
556
769
  - **Abort:** `signal` ends a call at once, also while it waits for a token or to try again.
770
+ - **Warnings:** the SDK's warnings go to `onWarning`, or to `console.warn` without it; `() => {}`
771
+ silences them. Today there is one kind: a catalogue format type this version doesn't know,
772
+ reported once per process to the client that read it first. A handler that throws is ignored,
773
+ and the read goes on.
557
774
  - **Your own transport:** an app that attaches the token itself passes `{ transport }` instead of
558
775
  `token` and `fetch`. Retries and deadlines still apply, above it. `health` carries no token, so
559
776
  it never goes through your transport: it goes to the query host, over https, with the global
@@ -15,9 +15,10 @@ export interface AuthServer {
15
15
  }
16
16
  /**
17
17
  * The authorization server at `issuer`, from its RFC 8414 metadata. `refused`, with nothing sent,
18
- * when `issuer` isn't an https URL. Refused as `invalid`: metadata that doesn't name `issuer`
19
- * exactly (§3.3), an endpoint that is not an https URL, and a server that doesn't list PKCE's
20
- * S256, since one that lists no methods supports no PKCE (§2), and a code it issues is bound to no
21
- * verifier.
18
+ * when `issuer` isn't an https URL, or with `allowLocalhostHttp`, an http one on this machine.
19
+ * Refused as `invalid`: metadata that doesn't name `issuer` exactly (§3.3), an endpoint that is
20
+ * not an https URL (for an http issuer on this machine, one not on its own origin), and a server
21
+ * that doesn't list PKCE's S256, since one that lists no methods supports no PKCE (§2), and a code
22
+ * it issues is bound to no verifier.
22
23
  */
23
24
  export declare function discover(issuer: string, options?: AuthCallOptions): Promise<ApiResult<AuthServer>>;
@@ -1,6 +1,6 @@
1
1
  import { z } from 'zod';
2
2
  import { call } from '../core/call.js';
3
- import { authTransport, isHttpsUrl } from './transport.js';
3
+ import { authTransport, endpointProblem, isSignInUrl } from './transport.js';
4
4
  // Unknown fields are kept and never read: `first_party_client_id` among them, which the SDK never
5
5
  // uses in place of the app's own client ID (D421).
6
6
  const zMetadata = z.looseObject({
@@ -13,13 +13,14 @@ const zMetadata = z.looseObject({
13
13
  });
14
14
  /**
15
15
  * The authorization server at `issuer`, from its RFC 8414 metadata. `refused`, with nothing sent,
16
- * when `issuer` isn't an https URL. Refused as `invalid`: metadata that doesn't name `issuer`
17
- * exactly (§3.3), an endpoint that is not an https URL, and a server that doesn't list PKCE's
18
- * S256, since one that lists no methods supports no PKCE (§2), and a code it issues is bound to no
19
- * verifier.
16
+ * when `issuer` isn't an https URL, or with `allowLocalhostHttp`, an http one on this machine.
17
+ * Refused as `invalid`: metadata that doesn't name `issuer` exactly (§3.3), an endpoint that is
18
+ * not an https URL (for an http issuer on this machine, one not on its own origin), and a server
19
+ * that doesn't list PKCE's S256, since one that lists no methods supports no PKCE (§2), and a code
20
+ * it issues is bound to no verifier.
20
21
  */
21
22
  export async function discover(issuer, options = {}) {
22
- if (typeof issuer !== 'string' || !isHttpsUrl(issuer))
23
+ if (typeof issuer !== 'string' || !isSignInUrl(issuer, options.allowLocalhostHttp))
23
24
  return { ok: false, error: { kind: 'refused' } };
24
25
  const read = await call(authTransport(options), {
25
26
  effect: 'read',
@@ -62,8 +63,9 @@ function problemWith(doc, issuer) {
62
63
  if (doc.issuer !== issuer)
63
64
  return 'the metadata names another issuer';
64
65
  const endpoints = [doc.authorization_endpoint, doc.token_endpoint, ...(doc.revocation_endpoint === undefined ? [] : [doc.revocation_endpoint])];
65
- if (!endpoints.every(isHttpsUrl))
66
- return 'an endpoint is not an https URL';
66
+ const problem = endpointProblem(issuer, endpoints);
67
+ if (problem !== null)
68
+ return problem;
67
69
  if (doc.code_challenge_methods_supported?.includes('S256') !== true)
68
70
  return 'the server does not list PKCE S256';
69
71
  return null;
@@ -1 +1 @@
1
- {"version":3,"file":"discov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'../core/call.js';
3
3
  import { challengeOf, randomValue } from './pkce.js';
4
4
  import { tokenCall } from './tokenEndpoint.js';
5
- import { authTransport, isHttpsUrl } from './transport.js';
5
+ import { authTransport, endpointProblem, isSignInUrl } from './transport.js';
6
6
  const nonEmpty = (value) => typeof value === 'string' && value !== '';
7
7
  /**
8
8
  * The URL to send the person to, and what finishing will need. Rejects with a TypeError, before
@@ -64,16 +64,21 @@ export function readCallback(callbackUrl, pending) {
64
64
  const code = params.get('code');
65
65
  return nonEmpty(code) ? { kind: 'code', code } : { kind: 'no_code' };
66
66
  }
67
- const zPending = z.object({
67
+ const zPending = z
68
+ .object({
68
69
  state: z.string().min(1),
69
70
  verifier: z.string().min(43).max(128),
70
71
  clientId: z.string().min(1),
71
72
  redirectUri: z.string().min(1),
72
73
  scope: z.string().min(1),
73
74
  issuer: z.string().min(1),
74
- tokenEndpoint: z.string().refine(isHttpsUrl),
75
+ tokenEndpoint: z.string(),
75
76
  issuerOnRedirect: z.boolean(),
76
- });
77
+ })
78
+ // A pending from storage may have been edited. Its token endpoint is held to the issuer's rule:
79
+ // https for an https issuer; for an http one on this machine, its own origin, which `finishSignIn`
80
+ // then sends to only with `allowLocalhostHttp` (#164).
81
+ .refine((pending) => endpointProblem(pending.issuer, [pending.tokenEndpoint]) === null);
77
82
  /** A pending sign-in as `startSignIn` makes one, checked: it comes back from the app's storage. */
78
83
  export const isPendingSignIn = (value) => zPending.safeParse(value).success;
79
84
  /**
@@ -91,7 +96,7 @@ export function finishSignIn(callbackUrl, pending, options = {}) {
91
96
  * entry never exports this, so browser code has no way to send client credentials.
92
97
  */
93
98
  export async function exchangeCode(callbackUrl, pending, options, authorization) {
94
- if (!isPendingSignIn(pending) || !URL.canParse(callbackUrl))
99
+ if (!isPendingSignIn(pending) || !isSignInUrl(pending.tokenEndpoint, options.allowLocalhostHttp) || !URL.canParse(callbackUrl))
95
100
  return { ok: false, error: { kind: 'refused' } };
96
101
  const callback = readCallback(callbackUrl, pending);
97
102
  if (callback.kind !== 'code')