@flipstream/sdk 0.10.0 → 0.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,18 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.10.1](https://github.com/flipstream-io/sdk/compare/typescript-v0.10.0...typescript-v0.10.1) (2026-11-03)
4
+
5
+
6
+ ### Code Refactoring
7
+
8
+ * **typescript:** fileLock's lookout reads its clocks through createFileLock, so its clock tests own them ([#318](https://github.com/flipstream-io/sdk/issues/318)) ([30f42f0](https://github.com/flipstream-io/sdk/commit/30f42f056c2f9eb253f0aded2ca72663de9d5c97))
9
+ * **typescript:** four keychain and loopback tests wait for events, not wall-clock margins, with an unexported seam for the helper's budget ([#309](https://github.com/flipstream-io/sdk/issues/309)) ([e0cdf66](https://github.com/flipstream-io/sdk/commit/e0cdf666899e3111fde94a48bf3fd542256c8e88))
10
+
11
+
12
+ ### Documentation
13
+
14
+ * **typescript:** the README fits npmjs.com's 64 KiB, with the Node sign-in reference moved to docs/node-sign-in.md, shipped in the package, and a 61,440-byte budget in readme:check ([#317](https://github.com/flipstream-io/sdk/issues/317)) ([feab932](https://github.com/flipstream-io/sdk/commit/feab932a9e1cfc6991915621046eb764b07aecae))
15
+
3
16
  ## [0.10.0](https://github.com/flipstream-io/sdk/compare/typescript-v0.9.0...typescript-v0.10.0) (2026-11-02)
4
17
 
5
18
 
package/README.md CHANGED
@@ -521,8 +521,8 @@ console.log(ledger.items.length, 'rows')
521
521
  For an app that runs on the person's own machine, or in their terminal: a CLI, a script, a local
522
522
  tool. `@flipstream/sdk/node` signs them in through their browser, with OAuth 2.0's authorisation
523
523
  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").
524
+ ready for them (see "Keeping the person signed in" in [docs/node-sign-in.md](docs/node-sign-in.md)). A
525
+ web app signs in on its server instead (see "In a browser").
526
526
 
527
527
  In a TypeScript project, add `@types/node` (`npm install --save-dev @types/node`): this entry's
528
528
  types use Node's own.
@@ -562,510 +562,21 @@ const flipstream = createFlipstream({ app: { name: 'my-cli', version: '1.0.0' },
562
562
  - **The SDK opens nothing and writes nothing to the terminal.** `open` does that, once the port is
563
563
  open.
564
564
  - **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.
565
+ out (after 5 minutes, or `timeoutMs`), aborted (`signal`), or `open` or `readPasted` failing
566
+ (`readPasted` reads a pasted address when the browser can't come back: see
567
+ [docs/node-sign-in.md](docs/node-sign-in.md)).
566
568
  - **The redirect is checked before its code is exchanged:** the sign-in's own state first, then the
567
569
  issuer.
568
570
  - **`page: { signedIn, failed }`** sets the HTML the browser shows afterwards.
569
571
  - **What comes back:** `accessToken`, `scope`, `expiresAt` (ms since the epoch) when the server
570
572
  says, and `refreshToken` when it issues one. Never log them.
571
573
 
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`.
574
+ **The rest is in [docs/node-sign-in.md](docs/node-sign-in.md),** which ships in the package, at
575
+ `node_modules/@flipstream/sdk/docs/node-sign-in.md`:
576
+ - when the browser may not reach this machine;
577
+ - over SSH, in CI, or with no display;
578
+ - keeping the person signed in: `createSession`, `keychainStore` and `fileStore`;
579
+ - several processes on one store: `fileLock`.
1069
580
 
1070
581
  ## In a browser
1071
582
 
@@ -1079,7 +590,8 @@ The main entry, `@flipstream/sdk`, runs in browsers with no Node polyfills. Only
1079
590
  - **A browser sends no identification yet.** `app`, `agent` and `conversationId` are still
1080
591
  required and checked, but none of "Which app sent a request"'s headers go from a page until the
1081
592
  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:
593
+ - **Signing in from a page** uses the same two halves as the paste-back ("Over SSH, in CI, or
594
+ with no display" in [docs/node-sign-in.md](docs/node-sign-in.md)):
1083
595
  - `startSignIn` gives the URL to send the person to, and a `pending` to keep, for instance in
1084
596
  `sessionStorage`;
1085
597
  - when they come back, `finishSignIn(location.href, pending)` checks the redirect and exchanges
@@ -1130,7 +642,8 @@ if (!signedIn.ok) throw new Error(`sign-in failed: ${signedIn.error.kind}`)
1130
642
  not the server's description or body (an empty `message` or `text`): a server or proxy that
1131
643
  echoes the request would put the credentials there.
1132
644
  - **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
645
+ - **Keep the person signed in with `createSession`** (see "Keeping the person signed in" in
646
+ [docs/node-sign-in.md](docs/node-sign-in.md)), passing
1134
647
  the same `clientSecret`. Its refresh and its revocation then carry the header too, under the same
1135
648
  rules.
1136
649
  - **Browser code can't pass a secret:** the main entry's `startSignIn` and `finishSignIn` have no
@@ -18,6 +18,21 @@ export interface Timings {
18
18
  readonly wakeMs: number;
19
19
  }
20
20
  export declare const TIMINGS: Timings;
21
+ /**
22
+ * The two clocks a waiter reads (#298): `date()`, the wall clock, which a step or a sleep moves,
23
+ * and `time()`, the monotonic one. `fileLock` always reads `CLOCKS`; `createFileLock`, which the
24
+ * package doesn't export, takes others, so the tests own both and count tries by `time()`.
25
+ */
26
+ export interface Clocks {
27
+ readonly date: () => number;
28
+ readonly time: () => number;
29
+ }
30
+ /**
31
+ * The real clocks, frozen, and the only place fileLock reads `Date.now()` and `performance.now()`.
32
+ * eslint.config.js refuses the other ways to a clock that someone might reach for by accident, as
33
+ * test/lint/fileLock-clocks.test.mjs lists them; a deliberate way round it is out of its scope.
34
+ */
35
+ export declare const CLOCKS: Clocks;
21
36
  /**
22
37
  * A lock across processes, for `createSession`'s `lock` option: for a token store that several
23
38
  * Node processes share, such as a CLI run several times at once. Give every process the same
@@ -44,5 +59,8 @@ export declare const TIMINGS: Timings;
44
59
  * only, as the file is).
45
60
  */
46
61
  export declare function fileLock(path: string): NonNullable<SessionOptions['lock']>;
47
- /** `fileLock` on other timings. The package doesn't export it: the tests use it, to run faster. */
48
- export declare function createFileLock(path: string, timings: Timings): NonNullable<SessionOptions['lock']>;
62
+ /**
63
+ * `fileLock` on other timings, and other clocks. The package doesn't export it: the tests use it,
64
+ * to run faster, and to own the clocks.
65
+ */
66
+ export declare function createFileLock(path: string, timings: Timings, clocks?: Clocks): NonNullable<SessionOptions['lock']>;