@flipstream/sdk 0.4.0 → 0.6.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +42 -0
- package/README.md +325 -20
- package/dist/auth/discovery.d.ts +2 -0
- package/dist/auth/discovery.js +4 -1
- package/dist/auth/discovery.js.map +1 -1
- package/dist/auth/signIn.d.ts +11 -2
- package/dist/auth/signIn.js +19 -27
- package/dist/auth/signIn.js.map +1 -1
- package/dist/auth/tokenEndpoint.d.ts +18 -0
- package/dist/auth/tokenEndpoint.js +36 -0
- package/dist/auth/tokenEndpoint.js.map +1 -0
- package/dist/core/fetch.d.ts +8 -0
- package/dist/core/fetch.js +36 -11
- package/dist/core/fetch.js.map +1 -1
- package/dist/core/result.d.ts +4 -2
- package/dist/core/result.js +3 -1
- package/dist/core/result.js.map +1 -1
- package/dist/flipstream.d.ts +7 -0
- package/dist/flipstream.js +14 -4
- package/dist/flipstream.js.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/node/clientSecret.d.ts +41 -0
- package/dist/node/clientSecret.js +124 -0
- package/dist/node/clientSecret.js.map +1 -0
- package/dist/node/fileLock.d.ts +27 -0
- package/dist/node/fileLock.js +267 -0
- package/dist/node/fileLock.js.map +1 -0
- package/dist/node/fileStore.d.ts +19 -0
- package/dist/node/fileStore.js +135 -0
- package/dist/node/fileStore.js.map +1 -0
- package/dist/node/headless.d.ts +7 -2
- package/dist/node/headless.js +15 -2
- package/dist/node/headless.js.map +1 -1
- package/dist/node/index.d.ts +9 -0
- package/dist/node/index.js +9 -1
- package/dist/node/index.js.map +1 -1
- package/dist/node/keychainChild.d.ts +1 -0
- package/dist/node/keychainChild.js +100 -0
- package/dist/node/keychainChild.js.map +1 -0
- package/dist/node/keychainStore.d.ts +30 -0
- package/dist/node/keychainStore.js +150 -0
- package/dist/node/keychainStore.js.map +1 -0
- package/dist/node/loopback.d.ts +24 -5
- package/dist/node/loopback.js +80 -23
- package/dist/node/loopback.js.map +1 -1
- package/dist/node/session.d.ts +224 -0
- package/dist/node/session.js +622 -0
- package/dist/node/session.js.map +1 -0
- package/dist/node/store.d.ts +44 -0
- package/dist/node/store.js +91 -0
- package/dist/node/store.js.map +1 -0
- package/dist/query/health.d.ts +16 -0
- package/dist/query/health.js +18 -0
- package/dist/query/health.js.map +1 -0
- package/dist/query/query.d.ts +8 -0
- package/dist/query/query.js +12 -0
- package/dist/query/query.js.map +1 -1
- package/dist/version.gen.d.ts +2 -0
- package/dist/version.gen.js +4 -0
- package/dist/version.gen.js.map +1 -0
- package/package.json +18 -3
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,47 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [0.6.0](https://github.com/flipstream-io/sdk/compare/typescript-v0.5.0...typescript-v0.6.0) (2026-10-17)
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
### Features
|
|
7
|
+
|
|
8
|
+
* **typescript:** a sign-out clears the store, once, however it ends ([#140](https://github.com/flipstream-io/sdk/issues/140)) ([e594331](https://github.com/flipstream-io/sdk/commit/e594331fc796bebdc125cc58b6ed9eaedb2d9549))
|
|
9
|
+
* **typescript:** createSession({ issuer }) discovers on first need ([#152](https://github.com/flipstream-io/sdk/issues/152)) ([3120bf7](https://github.com/flipstream-io/sdk/commit/3120bf7bc20f8651b85fd91a7806710e4d132850))
|
|
10
|
+
* **typescript:** keychain and file token stores in /node ([#142](https://github.com/flipstream-io/sdk/issues/142)) ([bc81870](https://github.com/flipstream-io/sdk/commit/bc8187045dcf05a30952fba1971ba52eb6db86cf))
|
|
11
|
+
* **typescript:** version, the SDK's own version, readable at run time ([#148](https://github.com/flipstream-io/sdk/issues/148)) ([ac287e0](https://github.com/flipstream-io/sdk/commit/ac287e06d790971fee316335e73e1401790054bb))
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
### Bug Fixes
|
|
15
|
+
|
|
16
|
+
* **typescript:** fileLock restarts its watch after a clock jump ([#145](https://github.com/flipstream-io/sdk/issues/145)) ([4990d88](https://github.com/flipstream-io/sdk/commit/4990d886c81e7faa43473c6d0f90176307ecda0a))
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
### Tests
|
|
20
|
+
|
|
21
|
+
* **typescript:** an opt-in check of a sign-out behind a real fileLock ([#155](https://github.com/flipstream-io/sdk/issues/155)) ([5a1956c](https://github.com/flipstream-io/sdk/commit/5a1956cd0af293d656b60c81025076193ba547da))
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
### CI
|
|
25
|
+
|
|
26
|
+
* close three blind spots in the root check scripts ([#150](https://github.com/flipstream-io/sdk/issues/150)) ([00e6d41](https://github.com/flipstream-io/sdk/commit/00e6d415da1dfcd6aa1dc434547a3661d0a89ec4))
|
|
27
|
+
|
|
28
|
+
## [0.5.0](https://github.com/flipstream-io/sdk/compare/typescript-v0.4.0...typescript-v0.5.0) (2026-10-17)
|
|
29
|
+
|
|
30
|
+
|
|
31
|
+
### Features
|
|
32
|
+
|
|
33
|
+
* **typescript:** a sign-in session with one shared refresh and revocation ([#105](https://github.com/flipstream-io/sdk/issues/105)) ([3f89388](https://github.com/flipstream-io/sdk/commit/3f893880ae006827d341d8b68b02899fee9e71da))
|
|
34
|
+
* **typescript:** fileLock, a lock across processes for one token store ([#143](https://github.com/flipstream-io/sdk/issues/143)) ([8c528cd](https://github.com/flipstream-io/sdk/commit/8c528cdc90a766a1e601dec451233e8f6c59b0d0)), closes [#114](https://github.com/flipstream-io/sdk/issues/114)
|
|
35
|
+
* **typescript:** finish a loopback sign-in from a pasted redirect ([#125](https://github.com/flipstream-io/sdk/issues/125)) ([e90b4dc](https://github.com/flipstream-io/sdk/commit/e90b4dc2cdbb7cf27af18130c977a158a26b7c6d)), closes [#112](https://github.com/flipstream-io/sdk/issues/112)
|
|
36
|
+
* **typescript:** fs.health() asks the planner if it is up, signed out ([#124](https://github.com/flipstream-io/sdk/issues/124)) ([c446f0b](https://github.com/flipstream-io/sdk/commit/c446f0bb86b6afa676e9a124052f62779715d081)), closes [#111](https://github.com/flipstream-io/sdk/issues/111)
|
|
37
|
+
* **typescript:** sign in from a server with the app's client secret ([#127](https://github.com/flipstream-io/sdk/issues/127)) ([6ef56aa](https://github.com/flipstream-io/sdk/commit/6ef56aa962a0d1884abb49578a231e5596af62c4))
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
### Bug Fixes
|
|
41
|
+
|
|
42
|
+
* **typescript:** declare @types/node as an optional peer ([#136](https://github.com/flipstream-io/sdk/issues/136)) ([8716cbe](https://github.com/flipstream-io/sdk/commit/8716cbeb07deaae43d9d1af61407cad65aed4ad7)), closes [#135](https://github.com/flipstream-io/sdk/issues/135)
|
|
43
|
+
* **typescript:** fs.query refuses a field it doesn't send, instead of dropping it ([#121](https://github.com/flipstream-io/sdk/issues/121)) ([d4d6593](https://github.com/flipstream-io/sdk/commit/d4d65930658c2d964c73c91fa5a17d63e78f15bb)), closes [#113](https://github.com/flipstream-io/sdk/issues/113)
|
|
44
|
+
|
|
3
45
|
## [0.4.0](https://github.com/flipstream-io/sdk/compare/typescript-v0.3.0...typescript-v0.4.0) (2026-10-17)
|
|
4
46
|
|
|
5
47
|
|
package/README.md
CHANGED
|
@@ -50,8 +50,12 @@ one source.
|
|
|
50
50
|
|
|
51
51
|
For an app that runs on the person's own machine, or in their terminal: a CLI, a script, a local
|
|
52
52
|
tool. `@flipstream/sdk/node` signs them in through their browser, with OAuth 2.0's authorisation
|
|
53
|
-
code and PKCE.
|
|
54
|
-
|
|
53
|
+
code and PKCE. Signing in stores nothing: the tokens are the app's to keep, and the SDK has stores
|
|
54
|
+
ready for them (see "Keeping the person signed in"). A web app signs in on its server instead (see
|
|
55
|
+
"In a browser").
|
|
56
|
+
|
|
57
|
+
In a TypeScript project, add `@types/node` (`npm install --save-dev @types/node`): this entry's
|
|
58
|
+
types use Node's own.
|
|
55
59
|
|
|
56
60
|
### With a browser on the same machine
|
|
57
61
|
|
|
@@ -82,18 +86,60 @@ const fs = createFlipstream({ token: () => signedIn.data.accessToken })
|
|
|
82
86
|
- **The SDK opens nothing and writes nothing to the terminal.** `open` does that, once the port is
|
|
83
87
|
open.
|
|
84
88
|
- **The port listens on `127.0.0.1` only,** and is closed on every path: signed in, refused, timed
|
|
85
|
-
out (after 5 minutes, or `timeoutMs`), aborted (`signal`), or `open` failing.
|
|
89
|
+
out (after 5 minutes, or `timeoutMs`), aborted (`signal`), or `open` or `readPasted` failing.
|
|
86
90
|
- **The redirect is checked before its code is exchanged:** the sign-in's own state first, then the
|
|
87
91
|
issuer.
|
|
88
92
|
- **`page: { signedIn, failed }`** sets the HTML the browser shows afterwards.
|
|
89
93
|
- **What comes back:** `accessToken`, `scope`, `expiresAt` (ms since the epoch) when the server
|
|
90
94
|
says, and `refreshToken` when it issues one. Never log them.
|
|
91
95
|
|
|
96
|
+
### When the browser may not reach this machine
|
|
97
|
+
|
|
98
|
+
**The way for a CLI, or any app that waits while the person signs in.** In a remote session
|
|
99
|
+
nothing may say so (a tmux session started before the SSH login sets no `SSH_*` variable), and
|
|
100
|
+
the person's browser, on their own device, then can't load the address it's sent back to. Give
|
|
101
|
+
`signInWithLoopback` a `readPasted` as well: the person pastes that address back, and the same
|
|
102
|
+
sign-in finishes. Where their browser can reach the port, it does, and the prompt stops.
|
|
103
|
+
|
|
104
|
+
```ts
|
|
105
|
+
import { discover } from '@flipstream/sdk'
|
|
106
|
+
import { signInWithLoopback } from '@flipstream/sdk/node'
|
|
107
|
+
import { createInterface } from 'node:readline/promises'
|
|
108
|
+
|
|
109
|
+
const server = await discover('https://auth.flipstream.io')
|
|
110
|
+
if (!server.ok) throw new Error(`sign-in is unavailable: ${server.error.kind}`)
|
|
111
|
+
|
|
112
|
+
const prompt = createInterface({ input: process.stdin, output: process.stdout })
|
|
113
|
+
const signedIn = await signInWithLoopback({
|
|
114
|
+
server: server.data,
|
|
115
|
+
clientId: '<your client id>',
|
|
116
|
+
scopes: ['<scope>'],
|
|
117
|
+
open: (url) => {
|
|
118
|
+
console.log(`Sign in at ${url}`)
|
|
119
|
+
},
|
|
120
|
+
// The signal fires once a paste can't be taken any more, and stops the prompt.
|
|
121
|
+
readPasted: (signal) => prompt.question('If your browser fails to load the page after signing in, paste its address here: ', { signal }),
|
|
122
|
+
})
|
|
123
|
+
prompt.close()
|
|
124
|
+
if (!signedIn.ok) throw new Error(`sign-in failed: ${signedIn.error.kind}`)
|
|
125
|
+
```
|
|
126
|
+
|
|
127
|
+
- **Whichever comes first is taken,** the port's redirect or the paste, and only its code is
|
|
128
|
+
exchanged. Once one is taken, the port answers anything else with the failure page, and a later
|
|
129
|
+
paste is dropped.
|
|
130
|
+
- **A paste is checked before anything is sent,** as `parsePastedRedirect` checks one: this
|
|
131
|
+
sign-in's own address, then its state. A paste that fails ends the sign-in with its reason, such
|
|
132
|
+
as `wrong_state`, and nothing is exchanged.
|
|
133
|
+
- **A reader that rejects** ends the sign-in as `paste_failed`. `readPasted` is called once, just
|
|
134
|
+
after `open`.
|
|
135
|
+
|
|
92
136
|
### Over SSH, in CI, or with no display
|
|
93
137
|
|
|
94
138
|
When no browser can come back to this machine, the person opens the URL on another device. The
|
|
95
|
-
redirect then fails to load, and they paste back the address it ended on.
|
|
96
|
-
when
|
|
139
|
+
redirect then fails to load, and they paste back the address it ended on. If one process waits for
|
|
140
|
+
them, `readPasted` above does this. The two halves below are for when the app can't wait, or
|
|
141
|
+
won't open a port: it keeps `pending` until the paste comes, for instance in a second command.
|
|
142
|
+
`isHeadless` tells you when no browser can come back.
|
|
97
143
|
|
|
98
144
|
```ts
|
|
99
145
|
import { discover, finishSignIn, startSignIn } from '@flipstream/sdk'
|
|
@@ -128,6 +174,197 @@ if (isHeadless(process.env)) {
|
|
|
128
174
|
- **`pending` holds the PKCE verifier,** a secret. Keep it only until the sign-in finishes, and
|
|
129
175
|
never log it.
|
|
130
176
|
|
|
177
|
+
### Keeping the person signed in
|
|
178
|
+
|
|
179
|
+
`createSession` keeps an access token fresh from the tokens your store holds, and signs the person
|
|
180
|
+
out. It holds a refresh token, so it belongs in a CLI or on a server, never in browser code. The
|
|
181
|
+
SDK has two stores ready for it, which keep the store's rules for you.
|
|
182
|
+
|
|
183
|
+
```ts
|
|
184
|
+
import { createFlipstream, discover } from '@flipstream/sdk'
|
|
185
|
+
import { createSession, fileStore, isHeadless, keychainStore, signInWithLoopback } from '@flipstream/sdk/node'
|
|
186
|
+
import { homedir } from 'node:os'
|
|
187
|
+
import { join } from 'node:path'
|
|
188
|
+
|
|
189
|
+
const issuer = 'https://auth.flipstream.io'
|
|
190
|
+
|
|
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 })
|
|
196
|
+
|
|
197
|
+
// Sign in once, and save the tokens. Only signing in needs the server first.
|
|
198
|
+
if ((await store.tokens()) === null) {
|
|
199
|
+
const server = await discover(issuer)
|
|
200
|
+
if (!server.ok) throw new Error(`sign-in is unavailable: ${server.error.kind}`)
|
|
201
|
+
const signedIn = await signInWithLoopback({
|
|
202
|
+
server: server.data,
|
|
203
|
+
clientId: '<your client id>',
|
|
204
|
+
scopes: ['<scope>'],
|
|
205
|
+
open: (url) => {
|
|
206
|
+
console.log(`Sign in at ${url}`)
|
|
207
|
+
},
|
|
208
|
+
})
|
|
209
|
+
if (!signedIn.ok) throw new Error(`sign-in failed: ${signedIn.error.kind}`)
|
|
210
|
+
await store.save(signedIn.data)
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
// The session discovers the server itself, only when a refresh or a sign-out needs it.
|
|
214
|
+
const session = createSession({ issuer, clientId: '<your client id>', ...store })
|
|
215
|
+
const fs = createFlipstream({ token: session.token })
|
|
216
|
+
|
|
217
|
+
// Signing out ends the session at the server, and clears the store through onTokens.
|
|
218
|
+
const signedOut = await session.revoke()
|
|
219
|
+
console.log(signedOut.kind)
|
|
220
|
+
```
|
|
221
|
+
|
|
222
|
+
- **`issuer`,** as above, discovers the server itself, only when a refresh or a sign-out needs it,
|
|
223
|
+
and keeps it. A command holding a token with time left then sends nothing to the auth host, and
|
|
224
|
+
an outage there doesn't stop it. Give exactly one of `issuer` and `server`, from your own
|
|
225
|
+
`discover` (as in "Writing your own store" below).
|
|
226
|
+
- **Write the issuer exactly as its metadata names it,** with no slash at the end for
|
|
227
|
+
`https://auth.flipstream.io`. Any other spelling fails every discovery.
|
|
228
|
+
- **A discovery that gets no answer** (offline, a 5xx, a timeout) is `unavailable` from
|
|
229
|
+
`token()`. **One answered outside the contract** (a 404, metadata naming another issuer) is
|
|
230
|
+
`refresh_failed`, with the error: waiting won't mend it. From `revoke()`, either is
|
|
231
|
+
`unconfirmed`. A failed discovery is tried again at the next need.
|
|
232
|
+
- **What it guarantees:** with a store that shows only what it has saved and compares and sets on
|
|
233
|
+
`replaces`, and one lock shared by every process, the session never sends a refresh token another
|
|
234
|
+
refresh is spending, never hands out a token that wasn't saved, never overwrites a newer sign-in,
|
|
235
|
+
and says `revoked` only when the server took the access token just before and refuses it just
|
|
236
|
+
after. A lost answer or a failed save can still leave a spent token stored, and a server fault
|
|
237
|
+
between the two checks reads as `revoked`.
|
|
238
|
+
- **The ready-made stores keep both rules:** each shows only what it has saved, and saves a
|
|
239
|
+
refresh's tokens only while it still holds the ones they replace, so a newer sign-in is kept.
|
|
240
|
+
`save` is for a sign-in's tokens, and `clear` for an app that signs out without a session:
|
|
241
|
+
`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
|
|
244
|
+
tokens or the new ones, never half. The file's mode is 0600, and a folder it makes is 0700. It
|
|
245
|
+
refuses a file that is a link, isn't this user's or is open to others, and it won't read or
|
|
246
|
+
save in a folder others can write to. On Windows the folder isn't flushed, and nothing checks
|
|
247
|
+
who owns what.
|
|
248
|
+
- **`keychainStore({ service, account })`** keeps the tokens in one item of the system's
|
|
249
|
+
credential store: the macOS keychain, Windows' Credential Manager, or the Secret Service on
|
|
250
|
+
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
|
|
257
|
+
`keychainChild.js` beside the module, with `zod` and `@napi-rs/keyring` resolvable from
|
|
258
|
+
there, and `import.meta.url` set. Where it doesn't (an esbuild CommonJS bundle, say), only the
|
|
259
|
+
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.
|
|
263
|
+
- Tokens over 2,560 bytes, Windows' limit, kept on every platform, fail the save with nothing
|
|
264
|
+
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`.
|
|
266
|
+
- On macOS, a script run by the same Node can read the item without a prompt, much as with a
|
|
267
|
+
file only the person can read.
|
|
268
|
+
- It's tested on macOS. Windows and Linux aren't tested yet.
|
|
269
|
+
- **One session per store,** shared by everything that uses it, or pass `lock`, a lock every
|
|
270
|
+
process takes, which settles only once its work has settled. Two sessions on one store refresh as
|
|
271
|
+
two processes would, and the server can end the session.
|
|
272
|
+
- **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.
|
|
274
|
+
- **Across processes,** take the session's lock around `save` and `clear` too: a store's compare
|
|
275
|
+
and its write are one step only among processes that take turns.
|
|
276
|
+
- **`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`.
|
|
278
|
+
- **`session.revoke()`** gives `revoked`, or `unconfirmed` with the reason. It ends the session the
|
|
279
|
+
store holds when its turn comes, and, whatever the result, clears it through `onTokens`
|
|
280
|
+
(`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
|
|
282
|
+
may still be on its way: once it reaches the lock, it waits at most 60 s for the lock and for each
|
|
283
|
+
of its three store calls, so up to about four minutes. A lock held longer than its 60 s by another
|
|
284
|
+
process, or a store call that doesn't answer within its 60 s, leaves the store as it was.
|
|
285
|
+
|
|
286
|
+
**Writing your own store:** give `tokens` and `onTokens` instead, and keep the same two rules.
|
|
287
|
+
`tokens()` returns only what `onTokens` has durably saved: write first, show second. `onTokens`
|
|
288
|
+
writes only while the store's key is still `update.replaces`, and throws when it refuses. The key is
|
|
289
|
+
the stored refresh token, or the access token when it has none or an empty one
|
|
290
|
+
(`refreshToken || accessToken`). Here in memory:
|
|
291
|
+
|
|
292
|
+
```ts
|
|
293
|
+
import { discover } from '@flipstream/sdk'
|
|
294
|
+
import { createSession, type SessionTokens, type TokenUpdate } from '@flipstream/sdk/node'
|
|
295
|
+
|
|
296
|
+
const server = await discover('https://auth.flipstream.io')
|
|
297
|
+
if (!server.ok) throw new Error(`sign-in is unavailable: ${server.error.kind}`)
|
|
298
|
+
|
|
299
|
+
let stored: SessionTokens | null = null
|
|
300
|
+
|
|
301
|
+
const session = createSession({
|
|
302
|
+
server: server.data,
|
|
303
|
+
clientId: '<your client id>',
|
|
304
|
+
tokens: () => stored,
|
|
305
|
+
onTokens: (update: TokenUpdate) => {
|
|
306
|
+
// Compare and set: only while the store's key is still the one this update replaces.
|
|
307
|
+
if (stored === null || (stored.refreshToken || stored.accessToken) !== update.replaces) throw new Error('the store moved on')
|
|
308
|
+
if (update.kind === 'cleared') {
|
|
309
|
+
stored = null
|
|
310
|
+
return
|
|
311
|
+
}
|
|
312
|
+
const { accessToken, expiresAt } = update
|
|
313
|
+
const refreshToken = update.kind === 'rotated' ? update.refreshToken : stored.refreshToken
|
|
314
|
+
stored = { accessToken, ...(refreshToken === undefined ? {} : { refreshToken }), ...(expiresAt === undefined ? {} : { expiresAt }) }
|
|
315
|
+
},
|
|
316
|
+
})
|
|
317
|
+
```
|
|
318
|
+
|
|
319
|
+
### Several processes on one store
|
|
320
|
+
|
|
321
|
+
`fileLock(path)` is a ready-made `lock` for Node processes that share one store, such as a CLI
|
|
322
|
+
run several times at once.
|
|
323
|
+
|
|
324
|
+
```ts
|
|
325
|
+
import { homedir } from 'node:os'
|
|
326
|
+
import { join } from 'node:path'
|
|
327
|
+
import { discover } from '@flipstream/sdk'
|
|
328
|
+
import { createSession, fileLock, type SessionTokens, type TokenUpdate } from '@flipstream/sdk/node'
|
|
329
|
+
|
|
330
|
+
const server = await discover('https://auth.flipstream.io')
|
|
331
|
+
if (!server.ok) throw new Error(`sign-in is unavailable: ${server.error.kind}`)
|
|
332
|
+
|
|
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
|
+
}
|
|
339
|
+
|
|
340
|
+
// 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 })
|
|
343
|
+
|
|
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.
|
|
346
|
+
await session.revoke()
|
|
347
|
+
await lock(() => store.clear(), AbortSignal.timeout(30_000))
|
|
348
|
+
```
|
|
349
|
+
|
|
350
|
+
- **Give every process the same absolute path,** on a local disk, for processes on this machine's
|
|
351
|
+
clock. A holder whose clock is 10 s or more behind, in a virtual machine sharing the folder say,
|
|
352
|
+
loses the lock after 2 to 3 s without a touch. The file exists only while a process holds the
|
|
353
|
+
lock. Its folder is made when it isn't there (on macOS and Linux, for this user only).
|
|
354
|
+
- **One refresh at a time:** the next process waits for it, reads the store again, and uses the
|
|
355
|
+
token it saved. A process still waiting at the refresh's 60 s deadline gives up, and sends
|
|
356
|
+
nothing.
|
|
357
|
+
- **A process that dies holding it** holds the others off for about 10 s: a holder touches the file
|
|
358
|
+
every second, and a waiter takes a file over once nobody has touched it for 10 s and it has
|
|
359
|
+
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
|
+
within about 3 s.
|
|
361
|
+
- **A holder that can't touch its file for 10 s loses the lock,** and its work goes on beside the
|
|
362
|
+
next holder's: a thread blocked by a synchronous store waiting for a person, or a process stopped
|
|
363
|
+
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.
|
|
367
|
+
|
|
131
368
|
## In a browser
|
|
132
369
|
|
|
133
370
|
The main entry, `@flipstream/sdk`, runs in browsers with no Node polyfills. Only
|
|
@@ -143,10 +380,55 @@ The main entry, `@flipstream/sdk`, runs in browsers with no Node polyfills. Only
|
|
|
143
380
|
- when they come back, `finishSignIn(location.href, pending)` checks the redirect and exchanges
|
|
144
381
|
its code.
|
|
145
382
|
- **Browser code shouldn't keep a refresh token.** We recommend signing in on your web app's
|
|
146
|
-
server instead
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
383
|
+
server instead (see "On your web app's server").
|
|
384
|
+
|
|
385
|
+
## On your web app's server
|
|
386
|
+
|
|
387
|
+
Your server signs the person in, keeps the tokens, and proves who it is with your app's client
|
|
388
|
+
secret (a confidential client). `startSignIn` comes from the main entry, with your app's
|
|
389
|
+
registered https callback as the `redirectUri`; `finishSignIn` comes from `@flipstream/sdk/node`.
|
|
390
|
+
|
|
391
|
+
```ts
|
|
392
|
+
import { discover, startSignIn } from '@flipstream/sdk'
|
|
393
|
+
import { finishSignIn } from '@flipstream/sdk/node'
|
|
394
|
+
|
|
395
|
+
const server = await discover('https://auth.flipstream.io')
|
|
396
|
+
if (!server.ok) throw new Error(`sign-in is unavailable: ${server.error.kind}`)
|
|
397
|
+
const clientSecret = process.env.FLIPSTREAM_CLIENT_SECRET
|
|
398
|
+
if (clientSecret === undefined) throw new Error('FLIPSTREAM_CLIENT_SECRET is not set')
|
|
399
|
+
|
|
400
|
+
// When the person signs in: send them to `url`, and keep `pending` in their session on the server.
|
|
401
|
+
const { url, pending } = await startSignIn({
|
|
402
|
+
server: server.data,
|
|
403
|
+
clientId: '<your client id>',
|
|
404
|
+
redirectUri: 'https://<your app>/callback',
|
|
405
|
+
scopes: ['<scope>'],
|
|
406
|
+
})
|
|
407
|
+
|
|
408
|
+
// When they come back to /callback: the full URL of that request, and the same `pending`.
|
|
409
|
+
const signedIn = await finishSignIn(new URL('https://<your app>/callback?code=…&state=…'), pending, {
|
|
410
|
+
server: server.data,
|
|
411
|
+
clientId: '<your client id>',
|
|
412
|
+
clientSecret,
|
|
413
|
+
})
|
|
414
|
+
if (!signedIn.ok) throw new Error(`sign-in failed: ${signedIn.error.kind}`)
|
|
415
|
+
```
|
|
416
|
+
|
|
417
|
+
- **The secret goes only in the token request's `Authorization: Basic` header** (RFC 6749 §2.3.1),
|
|
418
|
+
and only to the token endpoint of the `server` you pass. A `pending` that names another server,
|
|
419
|
+
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.
|
|
421
|
+
- **A failure keeps its kind, status and OAuth code** (`invalid_client`, `invalid_grant`, …), but
|
|
422
|
+
not the server's description or body (an empty `message` or `text`): a server or proxy that
|
|
423
|
+
echoes the request would put the credentials there.
|
|
424
|
+
- **Without `clientSecret`,** the sign-in is a public client's, with PKCE alone.
|
|
425
|
+
- **Keep the person signed in with `createSession`** (see "Keeping the person signed in"), passing
|
|
426
|
+
the same `clientSecret`. Its refresh and its revocation then carry the header too, under the same
|
|
427
|
+
rules.
|
|
428
|
+
- **Browser code can't pass a secret:** the main entry's `startSignIn` and `finishSignIn` have no
|
|
429
|
+
option for one. Never put the secret in code a browser loads.
|
|
430
|
+
- **`signInWithLoopback` isn't for this:** it waits on the server's own `127.0.0.1`, which the
|
|
431
|
+
person's browser can't reach. It's for apps on the person's own machine, which hold no secret.
|
|
150
432
|
|
|
151
433
|
## Results, not exceptions
|
|
152
434
|
|
|
@@ -159,7 +441,12 @@ throws the failure as an `ApiFailure` carrying its `error`, for callers who'd ra
|
|
|
159
441
|
- **`fs.catalog.get({ source })`** gives a `CatalogSource`: a source plus `catalogVersion`.
|
|
160
442
|
- **`fs.query(request)`** gives a `QueryResponse`, with `rows` and `lastRow`, and sometimes
|
|
161
443
|
`totals` and `timings`. Only the request's declared fields are sent: `source`, `connection_id`,
|
|
162
|
-
`dimensions`, `metrics`, `filters`, `sort`, `offset` and `rows`.
|
|
444
|
+
`dimensions`, `metrics`, `filters`, `sort`, `offset` and `rows`. A request with any other key,
|
|
445
|
+
`table` included, is `refused` with nothing sent, and `error.fields` names each one, so a
|
|
446
|
+
misspelt field never quietly changes the numbers.
|
|
447
|
+
- **`fs.health()`** gives the planner's answer to `GET /health`, an object of strings
|
|
448
|
+
(`{ status: 'ok' }` today). It works signed out: no token is asked for or sent, so it tells "the
|
|
449
|
+
service is down" from "the sign-in is wrong".
|
|
163
450
|
|
|
164
451
|
**Every answer is checked against the API's spec.** An answer that doesn't match, with a missing
|
|
165
452
|
field or a value of the wrong type, is an `invalid` failure that names the field. It never comes
|
|
@@ -176,7 +463,7 @@ back as data. A field the SDK doesn't know yet is kept.
|
|
|
176
463
|
| `invalid` | Outside the contract: an answer that isn't JSON or doesn't match its type, or a status no API sends |
|
|
177
464
|
| `timeout` | The call's own deadline passed |
|
|
178
465
|
| `aborted` | The caller's `signal` fired |
|
|
179
|
-
| `refused` | Nothing was sent, by rule: a destination that isn't one of the configured hosts over https,
|
|
466
|
+
| `refused` | Nothing was sent, by rule: a destination that isn't one of the configured hosts over https, a `source` of `''`, `.` or `..`, or a query with keys it doesn't send, named in `fields` |
|
|
180
467
|
| `no_token` | The token function failed, or gave no token. `cause` is what it threw |
|
|
181
468
|
| `cancelled` | The app's own transport cancelled the call, because the session it was made for moved on |
|
|
182
469
|
|
|
@@ -210,7 +497,7 @@ function explain(error: ApiError): string {
|
|
|
210
497
|
case 'cancelled':
|
|
211
498
|
return 'Stopped.'
|
|
212
499
|
case 'refused':
|
|
213
|
-
return 'Not sent.'
|
|
500
|
+
return error.fields === undefined ? 'Not sent.' : `Not sent: unknown field ${error.fields.join(', ')}`
|
|
214
501
|
case 'no_token':
|
|
215
502
|
return 'No token to send.'
|
|
216
503
|
default: {
|
|
@@ -226,8 +513,9 @@ function explain(error: ApiError): string {
|
|
|
226
513
|
- `provider_error`, with the server's `code`: the server ended the sign-in. It's `access_denied`
|
|
227
514
|
when the person declined;
|
|
228
515
|
- `no_code`: the redirect carried no code;
|
|
229
|
-
- `listen_failed` and `
|
|
230
|
-
- `not_a_url`:
|
|
516
|
+
- `listen_failed`, `open_failed` and `paste_failed`: from `signInWithLoopback`;
|
|
517
|
+
- `not_a_url` and `wrong_redirect`: a pasted address that isn't a URL, or isn't this sign-in's
|
|
518
|
+
redirect (`parsePastedRedirect`, or `signInWithLoopback`'s `readPasted`).
|
|
231
519
|
|
|
232
520
|
There, `refused` also covers an issuer that isn't https, and a `pending` that isn't one (from
|
|
233
521
|
storage the app couldn't read back). Nothing is sent for either.
|
|
@@ -257,16 +545,30 @@ await fs.catalog.list({ signal: controller.signal, deadlineMs: 10_000 })
|
|
|
257
545
|
cookies are sent. Plain http to a loopback host needs `allowLocalhostHttp: true`, for development
|
|
258
546
|
only.
|
|
259
547
|
- **Retries:**
|
|
260
|
-
- A read (`catalog`) is tried again after a 408, 429, 502, 503 or 504, or a
|
|
261
|
-
failed, at most twice. It waits as long as `Retry-After` asks, in seconds, or
|
|
548
|
+
- A read (`catalog`, `health`) is tried again after a 408, 429, 502, 503 or 504, or a
|
|
549
|
+
connection that failed, at most twice. It waits as long as `Retry-After` asks, in seconds, or
|
|
550
|
+
500 ms, then 1 s.
|
|
262
551
|
- `query` is never tried again: a timeout at the gateway may already have run on the warehouse.
|
|
263
552
|
- `no_token` and `refused` are never tried again.
|
|
264
553
|
- A wait that wouldn't end before the deadline isn't started.
|
|
265
|
-
- **Deadlines:** 60 s for `query` and 30 s for the rest, every attempt and
|
|
266
|
-
`deadlineMs` sets one call's.
|
|
554
|
+
- **Deadlines:** 60 s for `query`, 10 s for `health` and 30 s for the rest, every attempt and
|
|
555
|
+
wait included. `deadlineMs` sets one call's.
|
|
267
556
|
- **Abort:** `signal` ends a call at once, also while it waits for a token or to try again.
|
|
268
557
|
- **Your own transport:** an app that attaches the token itself passes `{ transport }` instead of
|
|
269
|
-
`token` and `fetch`. Retries and deadlines still apply, above it.
|
|
558
|
+
`token` and `fetch`. Retries and deadlines still apply, above it. `health` carries no token, so
|
|
559
|
+
it never goes through your transport: it goes to the query host, over https, with the global
|
|
560
|
+
`fetch`.
|
|
561
|
+
|
|
562
|
+
## Which version is running
|
|
563
|
+
|
|
564
|
+
```ts
|
|
565
|
+
import { version } from '@flipstream/sdk'
|
|
566
|
+
|
|
567
|
+
console.log(`@flipstream/sdk ${version}`) // "@flipstream/sdk 0.5.0", say
|
|
568
|
+
```
|
|
569
|
+
|
|
570
|
+
`version` is the installed package's own, from its `package.json`. It's a string in the code, so it
|
|
571
|
+
reads the same in Node and in a browser bundle, with no file to load.
|
|
270
572
|
|
|
271
573
|
## Requirements
|
|
272
574
|
|
|
@@ -274,7 +576,10 @@ await fs.catalog.list({ signal: controller.signal, deadlineMs: 10_000 })
|
|
|
274
576
|
in must be served over https, or from localhost.
|
|
275
577
|
- **ESM.** The package is ES modules only. On these Node versions, `require()` loads it from
|
|
276
578
|
CommonJS too, both entries; Node 22.12 prints an experimental warning when it does.
|
|
277
|
-
- **The types ship in the package,** for both entries.
|
|
579
|
+
- **The types ship in the package,** for both entries. The Node entry's types use Node's own,
|
|
580
|
+
from `@types/node`.
|
|
581
|
+
- **`keychainStore` needs `@napi-rs/keyring` 2.1 or later,** an optional peer dependency. Nothing
|
|
582
|
+
else needs it, and npm doesn't install it for you.
|
|
278
583
|
|
|
279
584
|
## Licence
|
|
280
585
|
|
package/dist/auth/discovery.d.ts
CHANGED
|
@@ -8,6 +8,8 @@ export interface AuthServer {
|
|
|
8
8
|
readonly authorizationEndpoint: string;
|
|
9
9
|
/** Where the code is exchanged for tokens. */
|
|
10
10
|
readonly tokenEndpoint: string;
|
|
11
|
+
/** Where a session is ended (RFC 7009), when the server has one. */
|
|
12
|
+
readonly revocationEndpoint?: string;
|
|
11
13
|
/** The server puts `iss` on every redirect (RFC 9207), so a redirect without one is refused. */
|
|
12
14
|
readonly issuerOnRedirect: boolean;
|
|
13
15
|
}
|
package/dist/auth/discovery.js
CHANGED
|
@@ -7,6 +7,7 @@ const zMetadata = z.looseObject({
|
|
|
7
7
|
issuer: z.string(),
|
|
8
8
|
authorization_endpoint: z.string(),
|
|
9
9
|
token_endpoint: z.string(),
|
|
10
|
+
revocation_endpoint: z.string().exactOptional(),
|
|
10
11
|
code_challenge_methods_supported: z.array(z.string()).exactOptional(),
|
|
11
12
|
authorization_response_iss_parameter_supported: z.boolean().exactOptional(),
|
|
12
13
|
});
|
|
@@ -41,6 +42,7 @@ export async function discover(issuer, options = {}) {
|
|
|
41
42
|
issuer: doc.issuer,
|
|
42
43
|
authorizationEndpoint: doc.authorization_endpoint,
|
|
43
44
|
tokenEndpoint: doc.token_endpoint,
|
|
45
|
+
...(doc.revocation_endpoint === undefined ? {} : { revocationEndpoint: doc.revocation_endpoint }),
|
|
44
46
|
issuerOnRedirect: doc.authorization_response_iss_parameter_supported === true,
|
|
45
47
|
},
|
|
46
48
|
};
|
|
@@ -59,7 +61,8 @@ function problemWith(doc, issuer) {
|
|
|
59
61
|
// Identical, as §3.3 says: a redirect's `iss` is later held to this very string (RFC 9207).
|
|
60
62
|
if (doc.issuer !== issuer)
|
|
61
63
|
return 'the metadata names another issuer';
|
|
62
|
-
|
|
64
|
+
const endpoints = [doc.authorization_endpoint, doc.token_endpoint, ...(doc.revocation_endpoint === undefined ? [] : [doc.revocation_endpoint])];
|
|
65
|
+
if (!endpoints.every(isHttpsUrl))
|
|
63
66
|
return 'an endpoint is not an https URL';
|
|
64
67
|
if (doc.code_challenge_methods_supported?.includes('S256') !== true)
|
|
65
68
|
return 'the server does not list PKCE S256';
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"discovery.js","sourceRoot":"","sources":["../../src/auth/discovery.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,CAAC,EAAE,MAAM,KAAK,CAAA;AACvB,OAAO,EAAE,IAAI,EAAE,MAAM,iBAAiB,CAAA;AAEtC,OAAO,EAAE,aAAa,EAAE,UAAU,EAAwB,MAAM,gBAAgB,CAAA;
|
|
1
|
+
{"version":3,"file":"discovery.js","sourceRoot":"","sources":["../../src/auth/discovery.ts"],"names":[],"mappings":"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"}
|
package/dist/auth/signIn.d.ts
CHANGED
|
@@ -89,9 +89,18 @@ export declare function readCallback(callbackUrl: string | URL, pending: Pending
|
|
|
89
89
|
readonly kind: 'code';
|
|
90
90
|
readonly code: string;
|
|
91
91
|
} | CallbackError;
|
|
92
|
+
/** A pending sign-in as `startSignIn` makes one, checked: it comes back from the app's storage. */
|
|
93
|
+
export declare const isPendingSignIn: (value: unknown) => value is PendingSignIn;
|
|
92
94
|
/**
|
|
93
95
|
* Finishes a sign-in: the redirect is read (`readCallback`), and only then is its code exchanged
|
|
94
|
-
* for tokens, once
|
|
95
|
-
* storage the app couldn't read back) is `refused`, with nothing sent.
|
|
96
|
+
* for tokens, once (`tokenCall`). A `pending` that isn't one (from
|
|
97
|
+
* storage the app couldn't read back) is `refused`, with nothing sent. A public client's: an app
|
|
98
|
+
* with a server signs in as a confidential client with `@flipstream/sdk/node`'s `finishSignIn`.
|
|
96
99
|
*/
|
|
97
100
|
export declare function finishSignIn(callbackUrl: string | URL, pending: PendingSignIn, options?: AuthCallOptions): Promise<SignInResult>;
|
|
101
|
+
/**
|
|
102
|
+
* `finishSignIn`'s work, with `authorization` as the token request's Authorization header when
|
|
103
|
+
* the app authenticates as a confidential client (only `@flipstream/sdk/node` makes one). The main
|
|
104
|
+
* entry never exports this, so browser code has no way to send client credentials.
|
|
105
|
+
*/
|
|
106
|
+
export declare function exchangeCode(callbackUrl: string | URL, pending: PendingSignIn, options: AuthCallOptions, authorization?: string): Promise<SignInResult>;
|
package/dist/auth/signIn.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { z } from 'zod';
|
|
2
2
|
import { call } from '../core/call.js';
|
|
3
3
|
import { challengeOf, randomValue } from './pkce.js';
|
|
4
|
+
import { tokenCall } from './tokenEndpoint.js';
|
|
4
5
|
import { authTransport, isHttpsUrl } from './transport.js';
|
|
5
6
|
const nonEmpty = (value) => typeof value === 'string' && value !== '';
|
|
6
7
|
/**
|
|
@@ -73,47 +74,38 @@ const zPending = z.object({
|
|
|
73
74
|
tokenEndpoint: z.string().refine(isHttpsUrl),
|
|
74
75
|
issuerOnRedirect: z.boolean(),
|
|
75
76
|
});
|
|
76
|
-
|
|
77
|
-
const
|
|
78
|
-
access_token: z.string().min(1),
|
|
79
|
-
token_type: z.string().refine((type) => type.toLowerCase() === 'bearer', 'the token type is not bearer'),
|
|
80
|
-
expires_in: z.int().nonnegative().exactOptional(),
|
|
81
|
-
refresh_token: z.string().exactOptional(),
|
|
82
|
-
scope: z.string().exactOptional(),
|
|
83
|
-
});
|
|
77
|
+
/** A pending sign-in as `startSignIn` makes one, checked: it comes back from the app's storage. */
|
|
78
|
+
export const isPendingSignIn = (value) => zPending.safeParse(value).success;
|
|
84
79
|
/**
|
|
85
80
|
* Finishes a sign-in: the redirect is read (`readCallback`), and only then is its code exchanged
|
|
86
|
-
* for tokens, once
|
|
87
|
-
* storage the app couldn't read back) is `refused`, with nothing sent.
|
|
81
|
+
* for tokens, once (`tokenCall`). A `pending` that isn't one (from
|
|
82
|
+
* storage the app couldn't read back) is `refused`, with nothing sent. A public client's: an app
|
|
83
|
+
* with a server signs in as a confidential client with `@flipstream/sdk/node`'s `finishSignIn`.
|
|
88
84
|
*/
|
|
89
|
-
export
|
|
90
|
-
|
|
85
|
+
export function finishSignIn(callbackUrl, pending, options = {}) {
|
|
86
|
+
return exchangeCode(callbackUrl, pending, options);
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* `finishSignIn`'s work, with `authorization` as the token request's Authorization header when
|
|
90
|
+
* the app authenticates as a confidential client (only `@flipstream/sdk/node` makes one). The main
|
|
91
|
+
* entry never exports this, so browser code has no way to send client credentials.
|
|
92
|
+
*/
|
|
93
|
+
export async function exchangeCode(callbackUrl, pending, options, authorization) {
|
|
94
|
+
if (!isPendingSignIn(pending) || !URL.canParse(callbackUrl))
|
|
91
95
|
return { ok: false, error: { kind: 'refused' } };
|
|
92
96
|
const callback = readCallback(callbackUrl, pending);
|
|
93
97
|
if (callback.kind !== 'code')
|
|
94
98
|
return { ok: false, error: callback };
|
|
95
|
-
const form =
|
|
99
|
+
const form = {
|
|
96
100
|
grant_type: 'authorization_code',
|
|
97
101
|
code: callback.code,
|
|
98
102
|
redirect_uri: pending.redirectUri,
|
|
99
103
|
client_id: pending.clientId,
|
|
100
104
|
code_verifier: pending.verifier,
|
|
101
|
-
}
|
|
105
|
+
};
|
|
102
106
|
// Before the request, so the expiry is never later than the server's own.
|
|
103
107
|
const sentAt = Date.now();
|
|
104
|
-
const answer = await call(authTransport(options),
|
|
105
|
-
effect: 'write',
|
|
106
|
-
service: 'auth',
|
|
107
|
-
endpoint: 'auth.token',
|
|
108
|
-
makeRequest: () => new Request(pending.tokenEndpoint, {
|
|
109
|
-
method: 'POST',
|
|
110
|
-
headers: { accept: 'application/json', 'content-type': 'application/x-www-form-urlencoded' },
|
|
111
|
-
body: form.toString(),
|
|
112
|
-
}),
|
|
113
|
-
schema: zTokenAnswer,
|
|
114
|
-
deadlineMs: 30_000,
|
|
115
|
-
retry: 'never',
|
|
116
|
-
}, options.signal);
|
|
108
|
+
const answer = await call(authTransport(options), tokenCall('auth.token', pending.tokenEndpoint, form, 30_000, authorization), options.signal);
|
|
117
109
|
if (!answer.ok)
|
|
118
110
|
return answer;
|
|
119
111
|
const { access_token, expires_in, refresh_token, scope } = answer.data;
|