@flipstream/sdk 0.10.0 → 0.11.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 (45) hide show
  1. package/CHANGELOG.md +40 -0
  2. package/README.md +93 -515
  3. package/dist/api/account.d.ts +50 -0
  4. package/dist/api/account.js +102 -0
  5. package/dist/api/account.js.map +1 -0
  6. package/dist/api/backend.d.ts +8 -0
  7. package/dist/api/backend.js +11 -0
  8. package/dist/api/backend.js.map +1 -1
  9. package/dist/api/created.d.ts +1 -1
  10. package/dist/api/created.js +3 -2
  11. package/dist/api/created.js.map +1 -1
  12. package/dist/api/datasets.d.ts +12 -0
  13. package/dist/api/datasets.js +18 -3
  14. package/dist/api/datasets.js.map +1 -1
  15. package/dist/api/index.d.ts +3 -2
  16. package/dist/api/log.d.ts +21 -5
  17. package/dist/api/log.js +61 -3
  18. package/dist/api/log.js.map +1 -1
  19. package/dist/api/me.d.ts +2 -0
  20. package/dist/api/me.js +2 -1
  21. package/dist/api/me.js.map +1 -1
  22. package/dist/api/members.d.ts +36 -7
  23. package/dist/api/members.js +45 -7
  24. package/dist/api/members.js.map +1 -1
  25. package/dist/api/time.js +4 -3
  26. package/dist/api/time.js.map +1 -1
  27. package/dist/api/workspaces.d.ts +14 -0
  28. package/dist/api/workspaces.js +34 -4
  29. package/dist/api/workspaces.js.map +1 -1
  30. package/dist/core/names.d.ts +20 -3
  31. package/dist/core/names.js +17 -6
  32. package/dist/core/names.js.map +1 -1
  33. package/dist/flipstream.d.ts +18 -4
  34. package/dist/flipstream.js.map +1 -1
  35. package/dist/node/fileLock.d.ts +20 -2
  36. package/dist/node/fileLock.js +22 -13
  37. package/dist/node/fileLock.js.map +1 -1
  38. package/dist/node/keychainChild.js +14 -9
  39. package/dist/node/keychainChild.js.map +1 -1
  40. package/dist/node/keychainStore.d.ts +23 -12
  41. package/dist/node/keychainStore.js +49 -28
  42. package/dist/node/keychainStore.js.map +1 -1
  43. package/dist/version.gen.js +1 -1
  44. package/docs/node-sign-in.md +506 -0
  45. package/package.json +2 -1
package/README.md CHANGED
@@ -112,8 +112,9 @@ console.log(organization.name, user.email, user.role)
112
112
  otherwise: the SDK never reads the clock for it. A day that isn't a real `YYYY-MM-DD` is `null`.
113
113
  - Every role reads the same access, a viewer limited to some workspaces and Flipstream's own
114
114
  staff included.
115
- - **`user`** is `{ id, email, first_name, last_name, role, active, workspace_ids }`: a `Member`, as
116
- `flipstream.members` answers each person (see "Your organisation's members").
115
+ - **`user`** is
116
+ `{ id, email, first_name, last_name, role, active, workspace_ids, created_on, created_by_id }`: a
117
+ `Member`, as `flipstream.members` answers each person (see "Your organisation's members").
117
118
  - `me()` reads the token's own person and doesn't apply `members`' people-only rule. An API key's
118
119
  token isn't tested with it yet: service accounts come with pulse-admin#93.
119
120
  - `role` is the highest you hold: `'owner'`, `'admin'`, `'editor'` or `'viewer'`. It's `null`
@@ -153,10 +154,20 @@ const member = orThrow(await flipstream.members.get({ member_id: page.items[0]?.
153
154
  console.log(member.first_name, member.workspace_ids.length)
154
155
  ```
155
156
 
156
- - **A member** is `{ id, email, first_name, last_name, role, active, workspace_ids }`, and nothing
157
- else, with `role` and `workspace_ids` by `me()`'s rules (see "Who you are"): the highest role
158
- they hold, or `null` for none and for Flipstream's own staff. A role this version doesn't know
159
- counts as none of ours, and its name is never shown.
157
+ - **A member** is
158
+ `{ id, email, first_name, last_name, role, active, workspace_ids, created_on, created_by_id }`,
159
+ and nothing else, with `role` and `workspace_ids` by `me()`'s rules (see "Who you are"): the
160
+ highest role they hold, or `null` for none and for Flipstream's own staff. A role this version
161
+ doesn't know counts as none of ours, and its name is never shown.
162
+ - `created_on` is when their account was made, an ISO 8601 instant in UTC. For someone invited,
163
+ that's when they were invited if the invitation made it (an open invitation is in this list),
164
+ or when they accepted if accepting did. It's `null` when the service holds none, or one that
165
+ isn't a time: unlike a dataset's, it never fails the answer.
166
+ - `created_by_id` is the person who made their account, `null` when the service holds none.
167
+ - `flipstream.members.get({ member_id: created_by_id })` names the maker. When it doesn't answer
168
+ ok (see below), show the maker as unknown, for example for Flipstream's staff or an account
169
+ made by another organisation. The SDK doesn't guess which: a `not_found` may also be someone
170
+ your role can't read.
160
171
  - **An open invitation is in the list:** someone invited who hasn't joined yet has an empty
161
172
  `first_name`, as the console tells them apart.
162
173
  - **Keys are left out by the service itself,** so `total` counts people.
@@ -197,7 +208,17 @@ const workspace = orThrow(await flipstream.workspaces.get({ workspace_id: page.i
197
208
  console.log(workspace.slug)
198
209
  ```
199
210
 
200
- - **A workspace** is `{ id, name, slug }`. Nothing else the service sends is in it.
211
+ - **A workspace** is `{ id, name, slug, services }`. Nothing else the service sends is in it.
212
+ - **`services` says which services are on in it,** read from the workspace's `meta` field as the
213
+ console reads it (#291), so an app and the console agree. One exception: a `meta` that comes as
214
+ something other than text reads `unreadable` here, where the console can't read that workspace
215
+ at all.
216
+ - `{ status: 'known', on }`, with `on` the keys of the services that are on, as the backend
217
+ stores them, such as `['trackers']`, or `[]` when none is;
218
+ - `{ status: 'unreadable' }` when the workspace's `meta` can't be read. The services are then
219
+ neither on nor off: say they can't be read, not that they're off. The workspace still reads.
220
+
221
+ Turning a service on isn't in the SDK yet.
201
222
  - **A page** is `{ items, total, limit, offset }`. `total` counts every workspace, and `limit` and
202
223
  `offset` say what was read. `limit` is 100 when left out and at most 1,000, and a larger one is
203
224
  read as 1,000. A limit or offset that isn't a whole number in range rejects with a `TypeError`,
@@ -305,6 +326,28 @@ const entry = orThrow(await flipstream.log.get({ log_id: '<log entry id>' }))
305
326
  - **A missing entry:** `get` answers `not_found`. `get` reads your organisation beside the entry, and
306
327
  an answer that is another entry than the one asked for, or another organisation's, is `invalid`.
307
328
 
329
+ **One member's entries,** in every workspace of your organisation, for a person's page for example:
330
+ `list({ member_id })` instead of `{ workspace_id }`.
331
+
332
+ ```ts
333
+ import { createFlipstream, orThrow } from '@flipstream/sdk'
334
+
335
+ const flipstream = createFlipstream({ app: { name: 'my-app', version: '1.0.0' }, token: async () => '<your token>' })
336
+
337
+ const theirs = orThrow(await flipstream.log.list({ member_id: '<member id>', limit: 5 }))
338
+ for (const entry of theirs.items) console.log(entry.start_date, entry.workspace_id, entry.description)
339
+ ```
340
+
341
+ - **Exactly one of `workspace_id` and `member_id`:** both, or neither, rejects with a `TypeError`,
342
+ with nothing sent.
343
+ - **You and the member are read first,** with your organisation, under one deadline. A person who
344
+ isn't a member, or a key, is `not_found`, and another organisation's member `invalid`, and no
345
+ entries are asked for. Your organisation's failure, then yours, then the member's, is the answer.
346
+ - **Every entry must be the member's, your organisation's, and in a workspace you open.** If your
347
+ account names workspaces, you open only those, unless you're an owner, an admin or an editor;
348
+ otherwise you open every one. Any other entry makes the answer `invalid`; none is dropped.
349
+ - **The page and the order** are a workspace's: the backend's, newest written first.
350
+
308
351
  **Writing to it:** `add`, `update` and `remove`.
309
352
 
310
353
  ```ts
@@ -360,11 +403,12 @@ const types = orThrow(await flipstream.datasetTypes.list())
360
403
  console.log(dataset.name, types.length)
361
404
  ```
362
405
 
363
- - **A dataset** is `{ id, name, workspace_id, type, active, created_on, created_by_id, history }`,
364
- and nothing else: never a credential, a setting or its parameters. The service's answer embeds the dataset's
365
- sign-in, so a body that isn't the service's JSON is never kept either: a failure of the dataset's
366
- own read or write gives its kind and status, with no `text`. The reads of your organisation and
367
- the workspace beside it keep theirs.
406
+ - **A dataset** is
407
+ `{ id, name, workspace_id, type, active, created_on, created_by_id, history, account }`, and
408
+ nothing else: never a credential, a setting or its parameters, beyond its account's id. The
409
+ service's answer embeds the dataset's sign-in, so a body that isn't the service's JSON is never
410
+ kept either: a failure of the dataset's own read or write gives its kind and status, with no
411
+ `text`. The reads of your organisation and the workspace beside it keep theirs.
368
412
  - `type` is one of the types `datasetTypes.list()` gives, such as `'google_search_console'`, or
369
413
  a type this version doesn't know yet, kept as it came, so a new kind of dataset never makes the
370
414
  list unreadable. It's `null` when the service holds no type for it.
@@ -387,6 +431,24 @@ console.log(dataset.name, types.length)
387
431
  Merge them as your app needs: the console shows `'todo'` and `'started'` alike as "coming in".
388
432
  It's `null` when it's unknown, because the service holds none or a value this version doesn't
389
433
  know: show "Not available yet" then, never a value of your own.
434
+ - `account` says which account it reads, a `DatasetAccount`, as the console labels a dataset:
435
+ - `id` is the id as the service holds it: a string as stored, or a whole number from 1 to
436
+ 2^53 - 1 as its digits. Use it to find or send back the stored id;
437
+ - `shown` is the id as its source writes it, trimmed: a Google Ads id as `'412-883-1024'`, any
438
+ other as `id`, such as `'sc-domain:acme.nl'`. Compare two accounts of one `type` by `shown`,
439
+ as the console's connect dialog does within one source, so a Google Ads account stored as
440
+ `'4128831024'` and as `'412-883-1024'` is one account. Across types, two ids can be the same
441
+ digits for different accounts.
442
+
443
+ The SDK reads the key a type keeps its account under, and only its id: Search Console,
444
+ Analytics and Google Ads keep a property, Business Profile a location, Meta Ads and LinkedIn
445
+ Ads an account (an older LinkedIn Ads dataset a property), Facebook Pages a page. It's `null`
446
+ for any other type, or when the service holds no readable id: show the dataset's name then.
447
+ The console shows a label where the SDK says `null` only for an id the SDK refuses, because it
448
+ can't show it safely or exactly: one longer than 512 UTF-16 code units, one with a control or
449
+ format character or a line or paragraph separator in it (a terminal escape, say), or a finite
450
+ number that isn't a whole one from 1 to 2^53 - 1. A refused id ends the read: the SDK never
451
+ shows another key's account in its place, such as an older LinkedIn Ads dataset's property.
390
452
  - **A list is one page:** `{ items, total, limit, offset }`, where `total` counts every dataset.
391
453
  - The limit is 100 unless you set one, and at most 1,000.
392
454
  - A limit or offset that isn't a whole number in range rejects, with nothing sent.
@@ -521,8 +583,8 @@ console.log(ledger.items.length, 'rows')
521
583
  For an app that runs on the person's own machine, or in their terminal: a CLI, a script, a local
522
584
  tool. `@flipstream/sdk/node` signs them in through their browser, with OAuth 2.0's authorisation
523
585
  code and PKCE. Signing in stores nothing: the tokens are the app's to keep, and the SDK has stores
524
- ready for them (see "Keeping the person signed in"). A web app signs in on its server instead (see
525
- "In a browser").
586
+ ready for them (see "Keeping the person signed in" in [docs/node-sign-in.md](docs/node-sign-in.md)). A
587
+ web app signs in on its server instead (see "In a browser").
526
588
 
527
589
  In a TypeScript project, add `@types/node` (`npm install --save-dev @types/node`): this entry's
528
590
  types use Node's own.
@@ -562,510 +624,21 @@ const flipstream = createFlipstream({ app: { name: 'my-cli', version: '1.0.0' },
562
624
  - **The SDK opens nothing and writes nothing to the terminal.** `open` does that, once the port is
563
625
  open.
564
626
  - **The port listens on `127.0.0.1` only,** and is closed on every path: signed in, refused, timed
565
- out (after 5 minutes, or `timeoutMs`), aborted (`signal`), or `open` or `readPasted` failing.
627
+ out (after 5 minutes, or `timeoutMs`), aborted (`signal`), or `open` or `readPasted` failing
628
+ (`readPasted` reads a pasted address when the browser can't come back: see
629
+ [docs/node-sign-in.md](docs/node-sign-in.md)).
566
630
  - **The redirect is checked before its code is exchanged:** the sign-in's own state first, then the
567
631
  issuer.
568
632
  - **`page: { signedIn, failed }`** sets the HTML the browser shows afterwards.
569
633
  - **What comes back:** `accessToken`, `scope`, `expiresAt` (ms since the epoch) when the server
570
634
  says, and `refreshToken` when it issues one. Never log them.
571
635
 
572
- ### When the browser may not reach this machine
573
-
574
- **The way for a CLI, or any app that waits while the person signs in.** In a remote session
575
- nothing may say so (a tmux session started before the SSH login sets no `SSH_*` variable), and
576
- the person's browser, on their own device, then can't load the address it's sent back to. Give
577
- `signInWithLoopback` a `readPasted` as well: the person pastes that address back, and the same
578
- sign-in finishes. Where their browser can reach the port, it does, and the prompt stops.
579
-
580
- ```ts
581
- import { discover } from '@flipstream/sdk'
582
- import { signInWithLoopback } from '@flipstream/sdk/node'
583
- import { createInterface } from 'node:readline/promises'
584
-
585
- const server = await discover('https://auth.flipstream.io')
586
- if (!server.ok) throw new Error(`sign-in is unavailable: ${server.error.kind}`)
587
-
588
- const prompt = createInterface({ input: process.stdin, output: process.stdout })
589
- const signedIn = await signInWithLoopback({
590
- server: server.data,
591
- clientId: '<your client id>',
592
- scopes: ['<scope>'],
593
- open: (url) => {
594
- console.log(`Sign in at ${url}`)
595
- },
596
- // The signal fires once a paste can't be taken any more, and stops the prompt.
597
- readPasted: (signal) => prompt.question('If your browser fails to load the page after signing in, paste its address here: ', { signal }),
598
- })
599
- prompt.close()
600
- if (!signedIn.ok) throw new Error(`sign-in failed: ${signedIn.error.kind}`)
601
- ```
602
-
603
- - **Whichever comes first is taken,** the port's redirect or the paste, and only its code is
604
- exchanged. Once one is taken, the port answers anything else with the failure page, and a later
605
- paste is dropped.
606
- - **A paste is checked before anything is sent,** as `parsePastedRedirect` checks one: this
607
- sign-in's own address, then its state. A paste that fails ends the sign-in with its reason, such
608
- as `wrong_state`, and nothing is exchanged.
609
- - **A reader that rejects** ends the sign-in as `paste_failed`. `readPasted` is called once, just
610
- after `open`.
611
-
612
- ### Over SSH, in CI, or with no display
613
-
614
- When no browser can come back to this machine, the person opens the URL on another device. The
615
- redirect then fails to load, and they paste back the address it ended on. If one process waits for
616
- them, `readPasted` above does this. The two halves below are for when the app can't wait, or
617
- won't open a port: it keeps `pending` until the paste comes, for instance in a second command.
618
- `isHeadless` tells you when no browser can come back.
619
-
620
- ```ts
621
- import { discover, finishSignIn, startSignIn } from '@flipstream/sdk'
622
- import { isHeadless, parsePastedRedirect } from '@flipstream/sdk/node'
623
- import { createInterface } from 'node:readline/promises'
624
-
625
- const server = await discover('https://auth.flipstream.io')
626
- if (!server.ok) throw new Error(`sign-in is unavailable: ${server.error.kind}`)
627
-
628
- if (isHeadless(process.env)) {
629
- const { url, pending } = await startSignIn({
630
- server: server.data,
631
- clientId: '<your client id>',
632
- redirectUri: 'http://127.0.0.1:8976/callback',
633
- scopes: ['<scope>'],
634
- })
635
- console.log(`Open this on any device and sign in:\n${url}`)
636
-
637
- const prompt = createInterface({ input: process.stdin, output: process.stdout })
638
- const pasted = parsePastedRedirect(await prompt.question('Paste the address your browser ended on: '), pending)
639
- prompt.close()
640
- if (!pasted.ok) throw new Error(`that isn't this sign-in's redirect: ${pasted.error.kind}`)
641
-
642
- const signedIn = await finishSignIn(pasted.callbackUrl, pending)
643
- if (!signedIn.ok) throw new Error(`sign-in failed: ${signedIn.error.kind}`)
644
- }
645
- ```
646
-
647
- - **`isHeadless(env)`** is true in CI, in an SSH session, and on Linux without a display.
648
- - **`parsePastedRedirect`** checks the pasted address as the loopback checks a redirect, before
649
- anything is sent. Prompting for it is the app's.
650
- - **`pending` holds the PKCE verifier,** a secret. Keep it only until the sign-in finishes, and
651
- never log it.
652
-
653
- ### Keeping the person signed in
654
-
655
- `createSession` keeps an access token fresh from the tokens your store holds, and signs the person
656
- out. It holds a refresh token, so it belongs in a CLI or on a server, never in browser code. The
657
- SDK has two stores ready for it, which keep the store's rules for you.
658
-
659
- ```ts
660
- import { createFlipstream, discover } from '@flipstream/sdk'
661
- import { createSession, fileStore, KeychainError, keychainStore, signInWithLoopback } from '@flipstream/sdk/node'
662
- import { homedir } from 'node:os'
663
- import { join } from 'node:path'
664
-
665
- const issuer = 'https://auth.flipstream.io'
666
-
667
- // The system's keychain by default. A file that only this user can read when the person asks for
668
- // one, for a machine with no keychain (Linux without a Secret Service, as on most servers). A real
669
- // app remembers that choice, in its config say, so every run uses the same store.
670
- const inFile = process.argv.includes('--tokens-in-file')
671
- const tokensFile = join(homedir(), '.config', 'example-cli', 'tokens.json')
672
- const store = inFile ? fileStore(tokensFile) : keychainStore({ service: 'io.example.cli', account: issuer })
673
- if (inFile) console.error(`Your sign-in is kept in ${tokensFile}, which only your user can read.`)
674
-
675
- // A store that can't be read is the person's to fix: never a quiet switch from the keychain to a file.
676
- const saved = await store.tokens().catch((error: unknown) => {
677
- const why = error instanceof Error ? error.message : String(error)
678
- if (inFile) throw new Error(`${tokensFile} can't be read (${why})`)
679
- const kind = error instanceof KeychainError ? error.failure.kind : undefined
680
- if (kind === 'unavailable') throw new Error('this machine has no keychain: run with --tokens-in-file')
681
- if (kind === 'locked') throw new Error('the keychain is locked: unlock it, or log in at this machine once')
682
- throw new Error(`the keychain can't be read (${why})`)
683
- })
684
-
685
- // Sign in once, and save the tokens. Only signing in needs the server first.
686
- if (saved === null) {
687
- const server = await discover(issuer)
688
- if (!server.ok) throw new Error(`sign-in is unavailable: ${server.error.kind}`)
689
- const signedIn = await signInWithLoopback({
690
- server: server.data,
691
- clientId: '<your client id>',
692
- scopes: ['<scope>'],
693
- open: (url) => {
694
- console.log(`Sign in at ${url}`)
695
- },
696
- })
697
- if (!signedIn.ok) throw new Error(`sign-in failed: ${signedIn.error.kind}`)
698
- await store.save(signedIn.data)
699
- }
700
-
701
- // The session discovers the server itself, only when a refresh or a sign-out needs it.
702
- const session = createSession({ issuer, clientId: '<your client id>', ...store })
703
- const flipstream = createFlipstream({ app: { name: 'my-cli', version: '1.0.0' }, token: session.token })
704
-
705
- // Signing out ends the session at the server, then clears the store through onTokens, and says
706
- // how each went.
707
- const signedOut = await session.revoke()
708
- console.log(signedOut.kind)
709
- if (signedOut.cleared === 'failed') {
710
- // Where the store failed (read, lock or clear), and its own error: a KeychainError says why.
711
- const { step, cause } = signedOut.failure
712
- console.error(`the tokens may still be stored: the ${step} failed (${cause instanceof Error ? cause.message : String(cause)})`)
713
- } else if (signedOut.cleared !== 'cleared' && signedOut.cleared !== 'kept') {
714
- console.error(`the tokens may still be stored (${signedOut.cleared}): sign out again`)
715
- }
716
- ```
717
-
718
- - **`issuer`,** as above, discovers the server itself, only when a refresh or a sign-out needs it,
719
- and keeps it. A command holding a token with time left then sends nothing to the auth host, and
720
- an outage there doesn't stop it. Give exactly one of `issuer` and `server`, from your own
721
- `discover` (as in "Writing your own store" below).
722
- - **Write the issuer exactly as its metadata names it,** with no slash at the end for
723
- `https://auth.flipstream.io`. Any other spelling fails every discovery.
724
- - **A discovery that gets no answer** (offline, a 5xx, a timeout) is `unavailable` from
725
- `token()`. **One answered outside the contract** (a 404, metadata naming another issuer) is
726
- `refresh_failed`, with the error: waiting won't mend it. From `revoke()`, either is
727
- `unconfirmed`. A failed discovery is tried again at the next need.
728
- - **What it guarantees:** with a store that shows only what it has saved and compares and sets on
729
- `replaces`, and one lock shared by every process, the session never sends a refresh token another
730
- refresh is spending, never hands out a token that wasn't saved, never overwrites a newer sign-in,
731
- and says `revoked` only when the server took the access token just before and refuses it just
732
- after. A lost answer or a failed save can still leave a spent token stored, and a server fault
733
- between the two checks reads as `revoked`.
734
- - **The ready-made stores keep both rules:** each shows only what it has saved, and saves a
735
- refresh's tokens only while it still holds the ones they replace, so a newer sign-in is kept.
736
- `save` is for a sign-in's tokens, and `clear` for an app that signs out without a session:
737
- `session.revoke()` clears the store itself.
738
- - **`fileStore(path)`** is for a machine with no keychain, chosen by the app or the person, never
739
- switched to quietly when the keychain fails: tell them where the file is. **The risk:** anyone
740
- who can read their files, as them or as an administrator, can use the tokens in it.
741
- It writes the whole file under a temporary name in its folder, flushes it to disk, renames it
742
- over the old one and flushes the folder: a reader, or a power cut, sees the old
743
- tokens or the new ones, never half. The file's mode is 0600, and a folder it makes is 0700. It
744
- refuses a file that is a link, isn't this user's or is open to others, and it won't read or
745
- save in a folder others can write to. On Windows the folder isn't flushed, and nothing checks
746
- who owns what. With `{ lock: true }` it also brings a lock for several processes (see
747
- "Several processes on one store").
748
- - **`keychainStore({ service, account })`** keeps the tokens in one item of the system's
749
- credential store: the macOS keychain, Windows' Credential Manager, or the Secret Service on
750
- Linux (GNOME Keyring, KWallet). It needs the optional package `@napi-rs/keyring`
751
- (`npm install @napi-rs/keyring`).
752
- - **Every failure of the keychain or its helper is a `KeychainError`,** which is also the
753
- `cause` of a session's `store_failed`. Three failures are the store's own, not the
754
- keychain's: `save` rejects tokens with no access token as a `TypeError` before any step; an
755
- item holding something other than tokens fails its read with a plain `Error` that never
756
- quotes it; and an update for tokens the item no longer holds is refused with a
757
- `StoreMovedOnError`, which a sign-out reads as `kept` and a refresh reports as `store_failed`
758
- (`save`). A `KeychainError`'s `failure.kind` says why:
759
- - `unavailable`: there's no keychain on this machine, as on Linux with no Secret Service or no
760
- D-Bus session (most servers and containers). It's the only kind after which a file may
761
- stand in, if your app or the person chooses it;
762
- - `locked`: the keychain is locked and can't ask to be unlocked, as on a Mac over SSH after a
763
- reboot;
764
- - `refused`: any other refusal, in the keychain's own words;
765
- - `timeout`: the step took longer than its `timeoutMs`;
766
- - `helper`: the helper process couldn't start, or ended before it answered (`exit` says how);
767
- - `missing`: `@napi-rs/keyring` isn't installed, and the message names it;
768
- - `too-long`: the tokens are over 2,560 bytes, so nothing was saved.
769
-
770
- `unavailable` and `locked` are read from the keychain library's words, which carry no code.
771
- Only words known for them match, and anything else is `refused`. The words for a locked
772
- macOS keychain, and any on Windows, haven't been seen yet, so those failures may read as
773
- `refused` for now.
774
- - Its steps run in one helper process, one at a time. The first step starts it, and it stays
775
- warm while your app runs (about 57 MB), so a step after that takes a keychain call, not a
776
- process start. A step that takes longer than 30 s (`timeoutMs`) ends it, so a keychain prompt
777
- that nobody answers can't hold up your app, and the next step starts another. A Ctrl-C in
778
- the terminal reaches the helper too, and it ignores it, from before its own code loads. Not
779
- during Node's own start-up, though, or any preload in `NODE_OPTIONS`: a Ctrl-C then still
780
- ends a helper that is just starting. When your app ends, the helper ends
781
- too: at once if it's idle or reading, or once it has finished the save or delete it's on, so
782
- a refresh's save isn't lost to a Ctrl-C. It gives that step 1 s more at most, less than the
783
- soonest `fileLock` lets another process take the lock your app held: at the soonest about
784
- 2 s after your app ends, for an app whose heartbeat was running (3 s after its last touch),
785
- when the clock has stepped or your app's clock runs behind. So a late save can't land over
786
- that process's. For a helper's first step, that 1 s counts from the helper's own start, so a
787
- helper slow to start (on a loaded machine, say) can't stretch it. A first step still going
788
- when your app ends may therefore be cut sooner. A save waiting on a keychain prompt is ended
789
- then. On macOS, the keychain's
790
- own dialog stays open after a Ctrl-C until someone answers it, even once your app and its
791
- helper have ended. A step whose helper died
792
- before it answered runs once more on a fresh one, within the same 30 s. The helper never
793
- keeps your app running. It's `process.execPath`, so it needs a Node that runs a script: not an Electron
794
- app (without `ELECTRON_RUN_AS_NODE`), a Node single-executable application, or a compiled
795
- Bun binary. A bundle must keep
796
- `keychainChild.js` beside the module, with `zod` and `@napi-rs/keyring` resolvable from
797
- there, and `import.meta.url` set. Where it doesn't (an esbuild CommonJS bundle, say), only the
798
- keychain's steps fail, as `store_failed`.
799
- - Through `session.token()`, a keychain read that takes longer than the caller's wait, 15 s
800
- unless you pass `createSession({ waitMs })`, is `unavailable`. On macOS a read can wait on
801
- an access dialog, every time, for an item another program saved: give `waitMs` as long as
802
- the person may take. Each keychain step still ends at its own `timeoutMs`.
803
- - Tokens over 2,560 bytes, Windows' limit, kept on every platform, fail the save with nothing
804
- written. A Flipstream sign-in's tokens take about 1.6 KB.
805
- - On Linux without a Secret Service, as on most servers, every step is `unavailable`: use
806
- `fileStore`.
807
- - Over SSH on a Mac it works too, unless the keychain is locked, as after a reboot with nobody
808
- logged in at the screen. Then every step fails, as `locked` or at the latest after its 30 s,
809
- until the person logs in at the machine once, or runs `security unlock-keychain`.
810
- - On macOS, a script run by the same Node can read the item without a prompt, much as with a
811
- file only the person can read.
812
- - **After a Node upgrade, macOS may ask for the login password.** It knows a Node signed ad hoc,
813
- as Homebrew's Node and a Node built from source are, only by its code's hash, which every
814
- build changes. So after `brew upgrade node`, the item the old Node saved is, to macOS, another
815
- program's. Each of the new Node's keychain steps on it then shows a dialog: a read, a
816
- refresh's save, and a sign-out's clear.
817
- - "Allow" answers that one step, and the next step asks again;
818
- - "Always Allow" trusts that Node build with the item, until the next upgrade;
819
- - nothing is refused: a sign-out still clears the tokens, after its dialogs.
820
- - **Each dialog must be answered within the call's limits:** `session.token()`'s wait, 15 s
821
- unless you pass `waitMs` (see "Through `session.token()`" above; #233's first read took
822
- 18.6 s); each keychain step's `timeoutMs`, 30 s by default; and a sign-out's 10 s for its
823
- revocation, which its first read's dialog counts against. So after an upgrade, a sign-out
824
- whose first dialog is slow still clears the tokens, but ends `unconfirmed`, without
825
- revoking them at the server.
826
-
827
- nodejs.org's builds are signed with the Node.js Foundation's Developer ID, so they keep their
828
- identity across versions, and an upgrade shouldn't ask. Checked on macOS 26 with a copy of
829
- Homebrew's Node 26.12.1 re-signed ad hoc, standing in for an upgrade
830
- (`scripts/live/keychain-upgrade.mjs`, #233). Not run: a real upgrade of either kind, and
831
- "Always Allow".
832
- - It's tested on macOS. Windows and Linux aren't tested yet.
833
- - **One session per store,** shared by everything that uses it, or pass `lock`, a lock every
834
- process takes, which settles only once its work has settled. Two sessions on one store refresh as
835
- two processes would, and the server can end the session.
836
- - **In one process,** the ready-made stores take each save, update and clear of the same file or
837
- item in turn, so a sign-in saved while a refresh is saving is kept. A file counts as the same
838
- however its folder is spelt (through a link, or in another case on macOS), but not when its own
839
- name differs only in case.
840
- - **Across processes,** take the session's lock around `save` and `clear` too: a store's compare
841
- and its write are one step only among processes that take turns.
842
- - **`session.token()`** rejects with a `SessionError` when there's no token to give: `signed-out`,
843
- `unavailable`, `store_failed` or `refresh_failed`.
844
- - **`unavailable` comes at the caller's wait,** the store's read included: 15 s unless you pass
845
- `createSession({ waitMs })`. Give a store that can wait on a person, such as a keychain asking
846
- for access, as long as they may take: 120 s when interactive, say. Only this wait changes. A
847
- refresh still waits at most 60 s for its answer, and a sign-out sends nothing after its 10 s.
848
- - **Before your process exits, `await session.settled()`.** It resolves once the session has no
849
- refresh, save or sign-out in flight. `unavailable` comes while a refresh may still be saving the
850
- token it got, and an exit then loses it. It never rejects and starts nothing.
851
- - **It waits at most as long as the session's own limits.** A store that never answers a read or
852
- a save holds it, and so does a lock that ignores its signal. A sign-out's store call still
853
- running after 60 s isn't waited for.
854
- - **The SDK's own stores answer every call.** A `keychainStore` save or clear is two steps of up
855
- to its `timeoutMs` each, so keep `timeoutMs` at 30 s or under, or a sign-out's clear can be cut,
856
- which it reports as `cut`.
857
- - **Stop making calls before you await it:** calls that keep coming keep it waiting.
858
- - **`session.revoke()`** ends the session the store holds when its turn comes, then, whatever the
859
- server said, clears it through `onTokens` (`cleared`), once, in the same hold of the lock, so a
860
- refresh can't bring it back. A sign-in saved after that is kept. A refresh token the session holds
861
- only because saving it failed goes too, after the stored session, even once the store has moved
862
- on, and the session then lets it go.
863
- - **It answers once both are done:** `kind` is `revoked`, or `unconfirmed` with the reason, and
864
- `cleared` says what became of the store:
865
- - `cleared`: it was cleared;
866
- - `kept`: there was nothing to clear: nothing stored, or the store moved on meanwhile, to a
867
- newer sign-in, which is kept, or to another sign-out's clear;
868
- - `failed`: the store failed, and `failure` says where and how: its `step` is `read`, `lock`
869
- or `clear`, and its `cause` is what the store threw, unchanged, whether it's an `Error` or
870
- not: a `KeychainError`, for instance, whose `failure.kind` and message say why. A clear it
871
- refuses with anything but `StoreMovedOnError` counts as failed, at `clear`;
872
- - `cut`: the lock or a store call took longer than its 60 s;
873
- - `pending`: your `signal` answered first, and the clear goes on, unless the signal had already
874
- fired when you called, when nothing runs at all.
875
-
876
- After anything but `cleared` and `kept`, the tokens may still be stored: tell the person, so
877
- they can sign out again.
878
- - **It can take minutes on a stalled store, and longer behind one.** It sends nothing after its
879
- 10 s, but it waits for the clear. First it waits for any turn ahead of it, for as long as that
880
- takes: a refresh that is still saving, or a lock that ignores its signal. Then it waits at most
881
- 60 s for the lock and for each of its three store calls, so up to about four minutes. It used to
882
- answer within 10 s while the clear went on behind it. A lock held longer than its 60 s by
883
- another process, or a store call that doesn't answer within its 60 s, leaves the store as it
884
- was, unless that call finishes later on its own.
885
- - **Pass a `signal` to stop waiting:** it answers at once, with `cleared: 'pending'`, and the
886
- clear goes on. Await `session.settled()` before the process exits. A signal that has already
887
- fired when you call runs nothing at all, and answers `pending` too.
888
-
889
- **Writing your own store:** give `tokens` and `onTokens` instead, and keep the same two rules.
890
- `tokens()` returns only what `onTokens` has durably saved: write first, show second. `onTokens`
891
- writes only while the store's key is still `update.replaces`, and when it refuses, throws a
892
- `StoreMovedOnError`, as the ready-made stores do. A sign-out whose clear is refused that way says
893
- `kept`: the store holds a newer sign-in, or nothing. Any other throw is read as the store failing,
894
- and the sign-out says `failed`. The key is the stored refresh token, or the access token when it has
895
- none or an empty one (`refreshToken || accessToken`). Here in memory:
896
-
897
- ```ts
898
- import { discover } from '@flipstream/sdk'
899
- import { createSession, StoreMovedOnError, type SessionTokens, type TokenUpdate } from '@flipstream/sdk/node'
900
-
901
- const server = await discover('https://auth.flipstream.io')
902
- if (!server.ok) throw new Error(`sign-in is unavailable: ${server.error.kind}`)
903
-
904
- let stored: SessionTokens | null = null
905
-
906
- const session = createSession({
907
- server: server.data,
908
- clientId: '<your client id>',
909
- tokens: () => stored,
910
- onTokens: (update: TokenUpdate) => {
911
- // Compare and set: only while the store's key is still the one this update replaces.
912
- if (stored === null || (stored.refreshToken || stored.accessToken) !== update.replaces) throw new StoreMovedOnError()
913
- if (update.kind === 'cleared') {
914
- stored = null
915
- return
916
- }
917
- const { accessToken, expiresAt } = update
918
- const refreshToken = update.kind === 'rotated' ? update.refreshToken : stored.refreshToken
919
- stored = { accessToken, ...(refreshToken === undefined ? {} : { refreshToken }), ...(expiresAt === undefined ? {} : { expiresAt }) }
920
- },
921
- })
922
- ```
923
-
924
- ### Several processes on one store
925
-
926
- `fileLock(path)` is a ready-made `lock` for Node processes that share one store, such as a CLI
927
- run several times at once.
928
-
929
- ```ts
930
- import { homedir } from 'node:os'
931
- import { join } from 'node:path'
932
- import { discover } from '@flipstream/sdk'
933
- import { createSession, fileLock, signInWithLoopback, type TokenStore } from '@flipstream/sdk/node'
934
-
935
- const issuer = 'https://auth.flipstream.io'
936
-
937
- // The store, chosen as above: the keychain, or the file the person asked for.
938
- declare const store: TokenStore
939
-
940
- // One lock file for every process on this machine.
941
- const lock = fileLock(join(homedir(), '.config', 'example-cli', 'session.lock'))
942
- const session = createSession({ issuer, clientId: '<your client id>', ...store, lock })
943
-
944
- // A sign-in's save takes the same lock. Give it longer than the 10 s a lock file left by a crash
945
- // can take to go stale.
946
- if ((await store.tokens()) === null) {
947
- const server = await discover(issuer)
948
- if (!server.ok) throw new Error(`sign-in is unavailable: ${server.error.kind}`)
949
- const signedIn = await signInWithLoopback({
950
- server: server.data,
951
- clientId: '<your client id>',
952
- scopes: ['<scope>'],
953
- open: (url) => {
954
- console.log(`Sign in at ${url}`)
955
- },
956
- })
957
- if (!signedIn.ok) throw new Error(`sign-in failed: ${signedIn.error.kind}`)
958
- await lock(() => store.save(signedIn.data), AbortSignal.timeout(30_000))
959
- }
960
-
961
- // Signing out takes the lock itself, and clears the store inside it.
962
- await session.revoke()
963
- ```
964
-
965
- - **Give every process the same absolute path,** on a local disk, for processes on this machine's
966
- clock. A holder whose clock is 10 s or more behind, in a virtual machine sharing the folder say,
967
- loses the lock after 2 to 3 s without a touch. The file exists only while a process holds the
968
- lock. Its folder is made when it isn't there (on macOS and Linux, for this user only).
969
- - **One refresh at a time:** the next process waits for it, reads the store again, and uses the
970
- token it saved. A process still waiting at the refresh's 60 s deadline gives up, and sends
971
- nothing.
972
- - **A process that dies holding it** holds the others off for about 10 s: a holder touches the file
973
- every second, and a waiter takes a file over once nobody has touched it for 10 s and it has
974
- watched it for 3 s. A sign-out, which sends nothing after its 10 s, takes over a file left 10 s or
975
- more before within about 3 s.
976
- - **On Ctrl-C,** Node ends the process without letting a held lock go, and the next process waits
977
- up to 10 s for it. An app that wants it gone sooner can handle SIGINT itself, and exit only once
978
- every hold of its lock has settled, as below: a hold still waiting for the file gives up at once,
979
- and one running its work finishes it. Waiting for the session's calls isn't enough: `token()` can
980
- answer before its hold ends, and so can `revoke()` at its `signal`. Await `session.settled()`
981
- too, so the session's own work has finished before the exit. The keychain store's own helper
982
- ignores the Ctrl-C and finishes the step it's on, within that step's 30 s and at most 1 s after
983
- the app has gone; the lock file goes when that work settles, as long as the app waits for it, as
984
- below.
985
-
986
- ```ts
987
- import { homedir } from 'node:os'
988
- import { join } from 'node:path'
989
- import { fileLock, type Session } from '@flipstream/sdk/node'
990
-
991
- // The lock for the session and the app's own saves, with every hold kept until it settles. Once
992
- // the app is stopping, a hold still waiting for the file gives up, and a new one creates nothing
993
- // (fileLock with a signal that has fired), so the wait below is only for work already running.
994
- const file = fileLock(join(homedir(), '.config', 'example-cli', 'session.lock'))
995
- const holds = new Set<Promise<unknown>>()
996
- const stop = new AbortController()
997
- const lock: typeof file = (work, signal) => {
998
- const hold = file(work, AbortSignal.any([signal, stop.signal]))
999
- holds.add(hold)
1000
- const done = (): void => {
1001
- holds.delete(hold)
1002
- }
1003
- hold.then(done, done)
1004
- return hold
1005
- }
1006
-
1007
- declare const session: Session
1008
-
1009
- // On Ctrl-C, exit once every hold has let its lock file go and the session's own work is done; a
1010
- // second Ctrl-C exits at once.
1011
- process.on('SIGINT', () => {
1012
- if (stop.signal.aborted) process.exit(130)
1013
- stop.abort(new Error('stopping'))
1014
- void Promise.all([Promise.allSettled([...holds]), session.settled()]).then(() => process.exit(130))
1015
- })
1016
- ```
1017
-
1018
- - **A holder that can't touch its file for 10 s loses the lock,** and its work goes on beside the
1019
- next holder's: a thread blocked by a synchronous store waiting for a person, or a process stopped
1020
- by Ctrl-Z or a debugger. Keep your store asynchronous.
1021
- - **Take the same lock for the store's other writes,** a sign-in's `save`, or a `clear` without a
1022
- session, so they can't land between a refresh's compare and its set. `session.revoke()` takes it
1023
- for its own clear. Never take it inside `onTokens`, which runs inside it already: the lock isn't
1024
- reentrant.
1025
- - **On Windows, `fileLock` hasn't been tried yet.** What may differ there:
1026
- - the lock file and its folder take the folder's own permissions, so they aren't private to this
1027
- user;
1028
- - a lock file it isn't allowed to create, for the folder's permissions, reads as held by another
1029
- process: a refresh then waits out its 60 s and is `unavailable`, not `store_failed`. A file
1030
- antivirus still holds open reads as held only until it lets go;
1031
- - taking over a crashed holder's file fails while antivirus or the indexer has it open, as
1032
- `store_failed`;
1033
- - a path such as `\my-app\session.lock` counts as absolute but names a file on whichever drive
1034
- is current: give the drive as well (`C:\…`).
1035
-
1036
- **A file store can bring its own lock.** `fileStore(path, { lock: true })` also returns `lock`:
1037
- `fileLock` on the file's path with `.lock` added, beside it. Every process, and every version of
1038
- your app, that opens the same file then takes the same lock, with no path of its own to agree on.
1039
-
1040
- ```ts
1041
- import { homedir } from 'node:os'
1042
- import { join } from 'node:path'
1043
- import { createSession, fileStore, type SessionTokens } from '@flipstream/sdk/node'
1044
-
1045
- const store = fileStore(join(homedir(), '.config', 'example-cli', 'tokens.json'), { lock: true })
1046
-
1047
- // Spread in, so the session takes store.lock for its refreshes and sign-outs.
1048
- const session = createSession({ issuer: 'https://auth.flipstream.io', clientId: '<your client id>', ...store })
1049
-
1050
- // A sign-in's save takes it too, as does a clear of your own.
1051
- declare const signedIn: SessionTokens
1052
- await store.lock(() => store.save(signedIn), AbortSignal.timeout(30_000))
1053
-
1054
- // Signing out takes it itself.
1055
- await session.revoke()
1056
- ```
1057
-
1058
- - **The store's own steps never take it,** so a `save` or `clear` inside it doesn't wait for itself,
1059
- and a clear leaves the lock file alone. Without `{ lock: true }`, nothing changes.
1060
- - **Don't pass a `lock` of your own as well:** `{ ...store, lock }` leaves the session on yours and
1061
- your saves on `store.lock`, and `{ lock, ...store }` swaps yours out without a word. Either way a
1062
- sign-in can land between a refresh's compare and its write.
1063
- - **Never call the session inside `store.lock`:** the lock isn't reentrant, so the call waits for
1064
- the hold it's in, and fails at its own limit (`token()` at its `waitMs`, `revoke()` once its turn
1065
- gives up on the lock, 60 s on, with `cut`).
1066
- - **Nor from your own `tokens` or `onTokens`,** if you wrap the store's: they run inside the
1067
- session's own turn. A `revoke()` there waits for that turn for ever, answering only at its
1068
- `signal`, and a `token()` answers only at its `waitMs`.
636
+ **The rest is in [docs/node-sign-in.md](docs/node-sign-in.md),** which ships in the package, at
637
+ `node_modules/@flipstream/sdk/docs/node-sign-in.md`:
638
+ - when the browser may not reach this machine;
639
+ - over SSH, in CI, or with no display;
640
+ - keeping the person signed in: `createSession`, `keychainStore` and `fileStore`;
641
+ - several processes on one store: `fileLock`.
1069
642
 
1070
643
  ## In a browser
1071
644
 
@@ -1079,7 +652,8 @@ The main entry, `@flipstream/sdk`, runs in browsers with no Node polyfills. Only
1079
652
  - **A browser sends no identification yet.** `app`, `agent` and `conversationId` are still
1080
653
  required and checked, but none of "Which app sent a request"'s headers go from a page until the
1081
654
  hosts' CORS allows them (query-planner#48); a page can't set `User-Agent` anyway.
1082
- - **Signing in from a page** uses the same two halves as the paste-back above:
655
+ - **Signing in from a page** uses the same two halves as the paste-back ("Over SSH, in CI, or
656
+ with no display" in [docs/node-sign-in.md](docs/node-sign-in.md)):
1083
657
  - `startSignIn` gives the URL to send the person to, and a `pending` to keep, for instance in
1084
658
  `sessionStorage`;
1085
659
  - when they come back, `finishSignIn(location.href, pending)` checks the redirect and exchanges
@@ -1130,7 +704,8 @@ if (!signedIn.ok) throw new Error(`sign-in failed: ${signedIn.error.kind}`)
1130
704
  not the server's description or body (an empty `message` or `text`): a server or proxy that
1131
705
  echoes the request would put the credentials there.
1132
706
  - **Without `clientSecret`,** the sign-in is a public client's, with PKCE alone.
1133
- - **Keep the person signed in with `createSession`** (see "Keeping the person signed in"), passing
707
+ - **Keep the person signed in with `createSession`** (see "Keeping the person signed in" in
708
+ [docs/node-sign-in.md](docs/node-sign-in.md)), passing
1134
709
  the same `clientSecret`. Its refresh and its revocation then carry the header too, under the same
1135
710
  rules.
1136
711
  - **Browser code can't pass a secret:** the main entry's `startSignIn` and `finishSignIn` have no
@@ -1185,7 +760,10 @@ field or a value of the wrong type, is an `invalid` failure that names the field
1185
760
  back as data. Some of a dataset's fields are read more leniently, so one new or missing backend
1186
761
  value never makes a workspace's datasets unreadable: a `type` this version doesn't know is kept as
1187
762
  it came, `created_on` and `created_by_id` are `null` when missing, and `history` is `null` when
1188
- missing or when it holds a value this version doesn't know (see "A workspace's datasets"). A field the SDK doesn't know yet is kept, except in the answers of `me()`,
763
+ missing or when it holds a value this version doesn't know (see "A workspace's datasets"). A
764
+ member's `created_on` and `created_by_id` are `null` when missing too, and its `created_on` also
765
+ when it isn't a time, so one member's time never fails `me()` or a page of members (see "Your
766
+ organisation's members"). A field the SDK doesn't know yet is kept, except in the answers of `me()`,
1189
767
  `workspaces`, `log`, `datasets`, `wallet` and `members`, which hold only the fields their types name.
1190
768
 
1191
769
  ## Typed errors