@flipstream/sdk 0.0.0-stage → 0.5.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 (93) hide show
  1. package/CHANGELOG.md +102 -0
  2. package/LICENSE +202 -0
  3. package/README.md +491 -2
  4. package/dist/api/index.d.ts +1 -0
  5. package/dist/api/index.js +2 -0
  6. package/dist/api/index.js.map +1 -0
  7. package/dist/auth/discovery.d.ts +23 -0
  8. package/dist/auth/discovery.js +71 -0
  9. package/dist/auth/discovery.js.map +1 -0
  10. package/dist/auth/index.d.ts +5 -0
  11. package/dist/auth/index.js +5 -0
  12. package/dist/auth/index.js.map +1 -0
  13. package/dist/auth/pkce.d.ts +10 -0
  14. package/dist/auth/pkce.js +25 -0
  15. package/dist/auth/pkce.js.map +1 -0
  16. package/dist/auth/signIn.d.ts +106 -0
  17. package/dist/auth/signIn.js +125 -0
  18. package/dist/auth/signIn.js.map +1 -0
  19. package/dist/auth/tokenEndpoint.d.ts +18 -0
  20. package/dist/auth/tokenEndpoint.js +36 -0
  21. package/dist/auth/tokenEndpoint.js.map +1 -0
  22. package/dist/auth/transport.d.ts +18 -0
  23. package/dist/auth/transport.js +26 -0
  24. package/dist/auth/transport.js.map +1 -0
  25. package/dist/core/body.d.ts +14 -0
  26. package/dist/core/body.js +69 -0
  27. package/dist/core/body.js.map +1 -0
  28. package/dist/core/call.d.ts +17 -0
  29. package/dist/core/call.js +116 -0
  30. package/dist/core/call.js.map +1 -0
  31. package/dist/core/fetch.d.ts +43 -0
  32. package/dist/core/fetch.js +130 -0
  33. package/dist/core/fetch.js.map +1 -0
  34. package/dist/core/read.d.ts +17 -0
  35. package/dist/core/read.js +92 -0
  36. package/dist/core/read.js.map +1 -0
  37. package/dist/core/result.d.ts +96 -0
  38. package/dist/core/result.js +42 -0
  39. package/dist/core/result.js.map +1 -0
  40. package/dist/core/retry.d.ts +40 -0
  41. package/dist/core/retry.js +41 -0
  42. package/dist/core/retry.js.map +1 -0
  43. package/dist/core/transport.d.ts +62 -0
  44. package/dist/core/transport.js +9 -0
  45. package/dist/core/transport.js.map +1 -0
  46. package/dist/flipstream.d.ts +52 -0
  47. package/dist/flipstream.js +36 -0
  48. package/dist/flipstream.js.map +1 -0
  49. package/dist/index.d.ts +12 -0
  50. package/dist/index.js +8 -0
  51. package/dist/index.js.map +1 -0
  52. package/dist/node/clientSecret.d.ts +41 -0
  53. package/dist/node/clientSecret.js +124 -0
  54. package/dist/node/clientSecret.js.map +1 -0
  55. package/dist/node/fileLock.d.ts +27 -0
  56. package/dist/node/fileLock.js +248 -0
  57. package/dist/node/fileLock.js.map +1 -0
  58. package/dist/node/headless.d.ts +25 -0
  59. package/dist/node/headless.js +41 -0
  60. package/dist/node/headless.js.map +1 -0
  61. package/dist/node/index.d.ts +9 -0
  62. package/dist/node/index.js +11 -0
  63. package/dist/node/index.js.map +1 -0
  64. package/dist/node/loopback.d.ts +77 -0
  65. package/dist/node/loopback.js +183 -0
  66. package/dist/node/loopback.js.map +1 -0
  67. package/dist/node/session.d.ts +192 -0
  68. package/dist/node/session.js +480 -0
  69. package/dist/node/session.js.map +1 -0
  70. package/dist/query/catalog.d.ts +15 -0
  71. package/dist/query/catalog.js +41 -0
  72. package/dist/query/catalog.js.map +1 -0
  73. package/dist/query/errors.d.ts +8 -0
  74. package/dist/query/errors.js +16 -0
  75. package/dist/query/errors.js.map +1 -0
  76. package/dist/query/health.d.ts +16 -0
  77. package/dist/query/health.js +18 -0
  78. package/dist/query/health.js.map +1 -0
  79. package/dist/query/query.d.ts +35 -0
  80. package/dist/query/query.js +47 -0
  81. package/dist/query/query.js.map +1 -0
  82. package/dist/recorded/query-planner/catalog-google_search_console.json +140 -0
  83. package/dist/recorded/query-planner/catalog.json +1234 -0
  84. package/dist/spec/query-planner/index.d.ts +1 -0
  85. package/dist/spec/query-planner/index.js +3 -0
  86. package/dist/spec/query-planner/index.js.map +1 -0
  87. package/dist/spec/query-planner/types.gen.d.ts +300 -0
  88. package/dist/spec/query-planner/types.gen.js +3 -0
  89. package/dist/spec/query-planner/types.gen.js.map +1 -0
  90. package/dist/spec/query-planner/zod.gen.d.ts +325 -0
  91. package/dist/spec/query-planner/zod.gen.js +137 -0
  92. package/dist/spec/query-planner/zod.gen.js.map +1 -0
  93. package/package.json +99 -4
package/README.md CHANGED
@@ -1,3 +1,492 @@
1
- # Temporary Holding Version
1
+ # @flipstream/sdk
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The TypeScript SDK for Flipstream's APIs: sign in, read the catalogue and run queries, with typed
4
+ requests and checked answers, in Node and in browsers.
5
+
6
+ [![npm version](https://img.shields.io/npm/v/@flipstream/sdk)](https://www.npmjs.com/package/@flipstream/sdk)
7
+ [![licence](https://img.shields.io/npm/l/@flipstream/sdk)](https://www.apache.org/licenses/LICENSE-2.0)
8
+ [![types included](https://img.shields.io/npm/types/@flipstream/sdk)](https://www.npmjs.com/package/@flipstream/sdk)
9
+
10
+ > **Status: 0.x, and early.** Any 0.x release may change the API. It's built for Flipstream's own
11
+ > tools for now:
12
+ >
13
+ > - **"Sign in with Flipstream" isn't open to other apps yet.** Only Flipstream's own apps have an
14
+ > OAuth client ID.
15
+ > - **ID tokens aren't checked yet,** so don't use a sign-in to tell who a person is. A later
16
+ > release adds the checks.
17
+
18
+ ## Install
19
+
20
+ ```sh
21
+ npm install @flipstream/sdk
22
+ ```
23
+
24
+ ## Quick start
25
+
26
+ ```ts
27
+ import { createFlipstream, orThrow } from '@flipstream/sdk'
28
+
29
+ // Asked before every attempt: return the current access token.
30
+ const fs = createFlipstream({ token: async () => '<your token>' })
31
+
32
+ const catalog = await fs.catalog.list()
33
+ if (!catalog.ok) console.error(catalog.error.kind) // 'unauthorized', 'unavailable', …
34
+
35
+ const answer = orThrow(
36
+ await fs.query({
37
+ source: '<source>',
38
+ connection_id: '<connection id>',
39
+ dimensions: ['<dimension>'],
40
+ metrics: ['<metric>'],
41
+ }),
42
+ )
43
+ console.log(answer.rows, answer.lastRow)
44
+ ```
45
+
46
+ The catalogue names each source with its dimensions and metrics. `fs.catalog.get({ source })` gives
47
+ one source.
48
+
49
+ ## Signing in from Node and the CLI
50
+
51
+ For an app that runs on the person's own machine, or in their terminal: a CLI, a script, a local
52
+ tool. `@flipstream/sdk/node` signs them in through their browser, with OAuth 2.0's authorisation
53
+ code and PKCE. The SDK stores nothing: the tokens are the app's to keep. A web app signs in on its
54
+ server instead (see "In a browser").
55
+
56
+ In a TypeScript project, add `@types/node` (`npm install --save-dev @types/node`): this entry's
57
+ types use Node's own.
58
+
59
+ ### With a browser on the same machine
60
+
61
+ `signInWithLoopback` opens a one-time server on `127.0.0.1`, on a port the system chooses, and
62
+ waits for the browser to come back to it.
63
+
64
+ ```ts
65
+ import { createFlipstream, discover } from '@flipstream/sdk'
66
+ import { signInWithLoopback } from '@flipstream/sdk/node'
67
+
68
+ const server = await discover('https://auth.flipstream.io')
69
+ if (!server.ok) throw new Error(`sign-in is unavailable: ${server.error.kind}`)
70
+
71
+ const signedIn = await signInWithLoopback({
72
+ server: server.data,
73
+ clientId: '<your client id>',
74
+ scopes: ['<scope>'],
75
+ // Show the person where to sign in: open their browser, or print the URL.
76
+ open: (url) => {
77
+ console.log(`Sign in at ${url}`)
78
+ },
79
+ })
80
+ if (!signedIn.ok) throw new Error(`sign-in failed: ${signedIn.error.kind}`)
81
+
82
+ const fs = createFlipstream({ token: () => signedIn.data.accessToken })
83
+ ```
84
+
85
+ - **The SDK opens nothing and writes nothing to the terminal.** `open` does that, once the port is
86
+ open.
87
+ - **The port listens on `127.0.0.1` only,** and is closed on every path: signed in, refused, timed
88
+ out (after 5 minutes, or `timeoutMs`), aborted (`signal`), or `open` or `readPasted` failing.
89
+ - **The redirect is checked before its code is exchanged:** the sign-in's own state first, then the
90
+ issuer.
91
+ - **`page: { signedIn, failed }`** sets the HTML the browser shows afterwards.
92
+ - **What comes back:** `accessToken`, `scope`, `expiresAt` (ms since the epoch) when the server
93
+ says, and `refreshToken` when it issues one. Never log them.
94
+
95
+ ### When the browser may not reach this machine
96
+
97
+ **The way for a CLI, or any app that waits while the person signs in.** In a remote session
98
+ nothing may say so (a tmux session started before the SSH login sets no `SSH_*` variable), and
99
+ the person's browser, on their own device, then can't load the address it's sent back to. Give
100
+ `signInWithLoopback` a `readPasted` as well: the person pastes that address back, and the same
101
+ sign-in finishes. Where their browser can reach the port, it does, and the prompt stops.
102
+
103
+ ```ts
104
+ import { discover } from '@flipstream/sdk'
105
+ import { signInWithLoopback } from '@flipstream/sdk/node'
106
+ import { createInterface } from 'node:readline/promises'
107
+
108
+ const server = await discover('https://auth.flipstream.io')
109
+ if (!server.ok) throw new Error(`sign-in is unavailable: ${server.error.kind}`)
110
+
111
+ const prompt = createInterface({ input: process.stdin, output: process.stdout })
112
+ const signedIn = await signInWithLoopback({
113
+ server: server.data,
114
+ clientId: '<your client id>',
115
+ scopes: ['<scope>'],
116
+ open: (url) => {
117
+ console.log(`Sign in at ${url}`)
118
+ },
119
+ // The signal fires once a paste can't be taken any more, and stops the prompt.
120
+ readPasted: (signal) => prompt.question('If your browser fails to load the page after signing in, paste its address here: ', { signal }),
121
+ })
122
+ prompt.close()
123
+ if (!signedIn.ok) throw new Error(`sign-in failed: ${signedIn.error.kind}`)
124
+ ```
125
+
126
+ - **Whichever comes first is taken,** the port's redirect or the paste, and only its code is
127
+ exchanged. Once one is taken, the port answers anything else with the failure page, and a later
128
+ paste is dropped.
129
+ - **A paste is checked before anything is sent,** as `parsePastedRedirect` checks one: this
130
+ sign-in's own address, then its state. A paste that fails ends the sign-in with its reason, such
131
+ as `wrong_state`, and nothing is exchanged.
132
+ - **A reader that rejects** ends the sign-in as `paste_failed`. `readPasted` is called once, just
133
+ after `open`.
134
+
135
+ ### Over SSH, in CI, or with no display
136
+
137
+ When no browser can come back to this machine, the person opens the URL on another device. The
138
+ redirect then fails to load, and they paste back the address it ended on. If one process waits for
139
+ them, `readPasted` above does this. The two halves below are for when the app can't wait, or
140
+ won't open a port: it keeps `pending` until the paste comes, for instance in a second command.
141
+ `isHeadless` tells you when no browser can come back.
142
+
143
+ ```ts
144
+ import { discover, finishSignIn, startSignIn } from '@flipstream/sdk'
145
+ import { isHeadless, parsePastedRedirect } from '@flipstream/sdk/node'
146
+ import { createInterface } from 'node:readline/promises'
147
+
148
+ const server = await discover('https://auth.flipstream.io')
149
+ if (!server.ok) throw new Error(`sign-in is unavailable: ${server.error.kind}`)
150
+
151
+ if (isHeadless(process.env)) {
152
+ const { url, pending } = await startSignIn({
153
+ server: server.data,
154
+ clientId: '<your client id>',
155
+ redirectUri: 'http://127.0.0.1:8976/callback',
156
+ scopes: ['<scope>'],
157
+ })
158
+ console.log(`Open this on any device and sign in:\n${url}`)
159
+
160
+ const prompt = createInterface({ input: process.stdin, output: process.stdout })
161
+ const pasted = parsePastedRedirect(await prompt.question('Paste the address your browser ended on: '), pending)
162
+ prompt.close()
163
+ if (!pasted.ok) throw new Error(`that isn't this sign-in's redirect: ${pasted.error.kind}`)
164
+
165
+ const signedIn = await finishSignIn(pasted.callbackUrl, pending)
166
+ if (!signedIn.ok) throw new Error(`sign-in failed: ${signedIn.error.kind}`)
167
+ }
168
+ ```
169
+
170
+ - **`isHeadless(env)`** is true in CI, in an SSH session, and on Linux without a display.
171
+ - **`parsePastedRedirect`** checks the pasted address as the loopback checks a redirect, before
172
+ anything is sent. Prompting for it is the app's.
173
+ - **`pending` holds the PKCE verifier,** a secret. Keep it only until the sign-in finishes, and
174
+ never log it.
175
+
176
+ ### Keeping the person signed in
177
+
178
+ `createSession` keeps an access token fresh from the tokens your store holds, and signs the person
179
+ out. It holds a refresh token, so it belongs in a CLI or on a server, never in browser code.
180
+
181
+ ```ts
182
+ import { createFlipstream, discover } from '@flipstream/sdk'
183
+ import { createSession, type SessionTokens, type TokenUpdate } from '@flipstream/sdk/node'
184
+
185
+ const server = await discover('https://auth.flipstream.io')
186
+ if (!server.ok) throw new Error(`sign-in is unavailable: ${server.error.kind}`)
187
+
188
+ // Your store, here in memory. A real one saves first and shows second (see below).
189
+ let stored: SessionTokens | null = null
190
+
191
+ const session = createSession({
192
+ server: server.data,
193
+ clientId: '<your client id>',
194
+ tokens: () => stored,
195
+ onTokens: (update: TokenUpdate) => {
196
+ // Compare and set: only while the store's key is still the one this update replaces.
197
+ if (stored === null || (stored.refreshToken || stored.accessToken) !== update.replaces) throw new Error('the store moved on')
198
+ if (update.kind === 'cleared') {
199
+ stored = null
200
+ return
201
+ }
202
+ const { accessToken, expiresAt } = update
203
+ const refreshToken = update.kind === 'rotated' ? update.refreshToken : stored.refreshToken
204
+ stored = { accessToken, ...(refreshToken === undefined ? {} : { refreshToken }), ...(expiresAt === undefined ? {} : { expiresAt }) }
205
+ },
206
+ })
207
+
208
+ const fs = createFlipstream({ token: session.token })
209
+
210
+ // Signing out ends the session at the server. Then clear your own store, whatever the result.
211
+ const signedOut = await session.revoke()
212
+ stored = null
213
+ console.log(signedOut.kind)
214
+ ```
215
+
216
+ - **What it guarantees:** with a store that shows only what it has saved and compares and sets on
217
+ `replaces`, and one lock shared by every process, the session never sends a refresh token another
218
+ refresh is spending, never hands out a token that wasn't saved, never overwrites a newer sign-in,
219
+ and says `revoked` only when the server took the access token just before and refuses it just
220
+ after. A lost answer or a failed save can still leave a spent token stored, and a server fault
221
+ between the two checks reads as `revoked`.
222
+ - **Your store saves first and shows second.** `tokens()` returns only what `onTokens` has durably
223
+ saved: the system keychain, or a file written under a temporary name, flushed to disk (fsync),
224
+ renamed over the old one, and its folder flushed too. `onTokens` writes only while the store's key
225
+ is still `update.replaces`, and throws when it refuses. The key is the stored refresh token, or the
226
+ access token when it has none or an empty one (`refreshToken || accessToken`).
227
+ - **One session per store,** shared by everything that uses it, or pass `lock`, a lock every
228
+ process takes, which settles only once its work has settled. Two sessions on one store refresh as
229
+ two processes would, and the server can end the session.
230
+ - **`session.token()`** rejects with a `SessionError` when there's no token to give: `signed-out`,
231
+ `unavailable` (after 15 s at most), `store_failed` or `refresh_failed`.
232
+ - **`session.revoke()`** gives `revoked`, or `unconfirmed` with the reason. It doesn't touch your
233
+ store: clear it yourself afterwards, whatever the result.
234
+ - **A known risk:** on a store that doesn't compare and set, a refresh whose save is slow can
235
+ land after your clear and bring a live session back. A later release moves the clear into the
236
+ session, inside its queue.
237
+
238
+ ### Several processes on one store
239
+
240
+ `fileLock(path)` is a ready-made `lock` for Node processes that share one store, such as a CLI
241
+ run several times at once.
242
+
243
+ ```ts
244
+ import { homedir } from 'node:os'
245
+ import { join } from 'node:path'
246
+ import { discover } from '@flipstream/sdk'
247
+ import { createSession, fileLock, type SessionTokens, type TokenUpdate } from '@flipstream/sdk/node'
248
+
249
+ const server = await discover('https://auth.flipstream.io')
250
+ if (!server.ok) throw new Error(`sign-in is unavailable: ${server.error.kind}`)
251
+
252
+ // Your store, kept on disk, which every process reads and writes.
253
+ declare const store: {
254
+ tokens(): Promise<SessionTokens | null>
255
+ onTokens(update: TokenUpdate): Promise<void>
256
+ clear(): Promise<void>
257
+ }
258
+
259
+ // One lock file for every process on this machine.
260
+ const lock = fileLock(join(homedir(), '.config', 'my-app', 'session.lock'))
261
+ const session = createSession({ server: server.data, clientId: '<your client id>', tokens: store.tokens, onTokens: store.onTokens, lock })
262
+
263
+ // The store's other writes take the same lock: here, the clear after signing out. Give them
264
+ // longer than the 10 s a lock file left by a crash can take to go stale.
265
+ await session.revoke()
266
+ await lock(() => store.clear(), AbortSignal.timeout(30_000))
267
+ ```
268
+
269
+ - **Give every process the same absolute path,** on a local disk, for processes on this machine's
270
+ clock. A holder whose clock is 10 s or more behind, in a virtual machine sharing the folder say,
271
+ loses the lock after 2 to 3 s without a touch. The file exists only while a process holds the
272
+ lock. Its folder is made when it isn't there (on macOS and Linux, for this user only).
273
+ - **One refresh at a time:** the next process waits for it, reads the store again, and uses the
274
+ token it saved. A process still waiting at the refresh's 60 s deadline gives up, and sends
275
+ nothing.
276
+ - **A process that dies holding it** holds the others off for about 10 s: a holder touches the file
277
+ every second, and a waiter takes a file over once nobody has touched it for 10 s and it has
278
+ watched it for 3 s. A sign-out, which has 10 s in all, takes over a file left 10 s or more before
279
+ within about 3 s.
280
+ - **A holder that can't touch its file for 10 s loses the lock,** and its work goes on beside the
281
+ next holder's: a thread blocked by a synchronous store waiting for a person, or a process stopped
282
+ by Ctrl-Z or a debugger. Keep your store asynchronous.
283
+ - **Take the same lock for the store's other writes,** such as saving a sign-in's tokens, or
284
+ clearing the store after `revoke()`, so they can't land between a refresh's compare and its set.
285
+ Never inside `onTokens`, which runs inside it already: the lock isn't reentrant.
286
+
287
+ ## In a browser
288
+
289
+ The main entry, `@flipstream/sdk`, runs in browsers with no Node polyfills. Only
290
+ `@flipstream/sdk/node` needs Node.
291
+
292
+ - **Pass a token function** that returns the session's current access token. Never put an API key
293
+ in a browser.
294
+ - **The API must allow your page's origin (CORS).** The query API doesn't allow other origins yet,
295
+ so until it does, call it from a server.
296
+ - **Signing in from a page** uses the same two halves as the paste-back above:
297
+ - `startSignIn` gives the URL to send the person to, and a `pending` to keep, for instance in
298
+ `sessionStorage`;
299
+ - when they come back, `finishSignIn(location.href, pending)` checks the redirect and exchanges
300
+ its code.
301
+ - **Browser code shouldn't keep a refresh token.** We recommend signing in on your web app's
302
+ server instead (see "On your web app's server").
303
+
304
+ ## On your web app's server
305
+
306
+ Your server signs the person in, keeps the tokens, and proves who it is with your app's client
307
+ secret (a confidential client). `startSignIn` comes from the main entry, with your app's
308
+ registered https callback as the `redirectUri`; `finishSignIn` comes from `@flipstream/sdk/node`.
309
+
310
+ ```ts
311
+ import { discover, startSignIn } from '@flipstream/sdk'
312
+ import { finishSignIn } from '@flipstream/sdk/node'
313
+
314
+ const server = await discover('https://auth.flipstream.io')
315
+ if (!server.ok) throw new Error(`sign-in is unavailable: ${server.error.kind}`)
316
+ const clientSecret = process.env.FLIPSTREAM_CLIENT_SECRET
317
+ if (clientSecret === undefined) throw new Error('FLIPSTREAM_CLIENT_SECRET is not set')
318
+
319
+ // When the person signs in: send them to `url`, and keep `pending` in their session on the server.
320
+ const { url, pending } = await startSignIn({
321
+ server: server.data,
322
+ clientId: '<your client id>',
323
+ redirectUri: 'https://<your app>/callback',
324
+ scopes: ['<scope>'],
325
+ })
326
+
327
+ // When they come back to /callback: the full URL of that request, and the same `pending`.
328
+ const signedIn = await finishSignIn(new URL('https://<your app>/callback?code=…&state=…'), pending, {
329
+ server: server.data,
330
+ clientId: '<your client id>',
331
+ clientSecret,
332
+ })
333
+ if (!signedIn.ok) throw new Error(`sign-in failed: ${signedIn.error.kind}`)
334
+ ```
335
+
336
+ - **The secret goes only in the token request's `Authorization: Basic` header** (RFC 6749 §2.3.1),
337
+ and only to the token endpoint of the `server` you pass. A `pending` that names another server,
338
+ 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
339
+ the SDK logs nothing. A `fetch` you pass sees the request, header included: don't log it.
340
+ - **A failure keeps its kind, status and OAuth code** (`invalid_client`, `invalid_grant`, …), but
341
+ not the server's description or body (an empty `message` or `text`): a server or proxy that
342
+ echoes the request would put the credentials there.
343
+ - **Without `clientSecret`,** the sign-in is a public client's, with PKCE alone.
344
+ - **Keep the person signed in with `createSession`** (see "Keeping the person signed in"), passing
345
+ the same `clientSecret`. Its refresh and its revocation then carry the header too, under the same
346
+ rules.
347
+ - **Browser code can't pass a secret:** the main entry's `startSignIn` and `finishSignIn` have no
348
+ option for one. Never put the secret in code a browser loads.
349
+ - **`signInWithLoopback` isn't for this:** it waits on the server's own `127.0.0.1`, which the
350
+ person's browser can't reach. It's for apps on the person's own machine, which hold no secret.
351
+
352
+ ## Results, not exceptions
353
+
354
+ Every call settles into a result: `{ ok: true, data }` or `{ ok: false, error }`. A call rejects
355
+ only on a programming error. For instance, a request that can't be sent as JSON (a `BigInt`, a
356
+ cycle) rejects with the `TypeError`, and nothing is sent. `orThrow(result)` gives the data, or
357
+ throws the failure as an `ApiFailure` carrying its `error`, for callers who'd rather catch.
358
+
359
+ - **`fs.catalog.list()`** gives a `Catalog`.
360
+ - **`fs.catalog.get({ source })`** gives a `CatalogSource`: a source plus `catalogVersion`.
361
+ - **`fs.query(request)`** gives a `QueryResponse`, with `rows` and `lastRow`, and sometimes
362
+ `totals` and `timings`. Only the request's declared fields are sent: `source`, `connection_id`,
363
+ `dimensions`, `metrics`, `filters`, `sort`, `offset` and `rows`. A request with any other key,
364
+ `table` included, is `refused` with nothing sent, and `error.fields` names each one, so a
365
+ misspelt field never quietly changes the numbers.
366
+ - **`fs.health()`** gives the planner's answer to `GET /health`, an object of strings
367
+ (`{ status: 'ok' }` today). It works signed out: no token is asked for or sent, so it tells "the
368
+ service is down" from "the sign-in is wrong".
369
+
370
+ **Every answer is checked against the API's spec.** An answer that doesn't match, with a missing
371
+ field or a value of the wrong type, is an `invalid` failure that names the field. It never comes
372
+ back as data. A field the SDK doesn't know yet is kept.
373
+
374
+ ## Typed errors
375
+
376
+ `error.kind` says what happened, and each kind has one meaning:
377
+
378
+ | Kind | When |
379
+ |---|---|
380
+ | `unauthorized`, `forbidden`, `not_found`, `conflict`, `rejected` | The API refused: 401, 403, 404, 409 or 412, or any other 4xx |
381
+ | `unavailable` | A 429 or 5xx, or no answer at all (offline, or a connection that broke) |
382
+ | `invalid` | Outside the contract: an answer that isn't JSON or doesn't match its type, or a status no API sends |
383
+ | `timeout` | The call's own deadline passed |
384
+ | `aborted` | The caller's `signal` fired |
385
+ | `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` |
386
+ | `no_token` | The token function failed, or gave no token. `cause` is what it threw |
387
+ | `cancelled` | The app's own transport cancelled the call, because the session it was made for moved on |
388
+
389
+ **A failure the API answered keeps its `status`.**
390
+ - It keeps the API's `code` and `message` when the body is an error body, or its `text` when it
391
+ isn't (a proxy's `Bad gateway`).
392
+ - `isPlannerCode(error.code)` narrows the code to the ones the query API documents
393
+ (`PlannerErrorCode`), so a switch over them can be exhaustive. A code added since is kept as it
394
+ came.
395
+ - When the API asked the caller to wait, the failure keeps that as `retryAfterMs`.
396
+
397
+ ```ts
398
+ import { isPlannerCode, type ApiError } from '@flipstream/sdk'
399
+
400
+ function explain(error: ApiError): string {
401
+ switch (error.kind) {
402
+ case 'unauthorized':
403
+ return error.code === 'TOKEN_EXPIRED' ? 'Sign in again.' : 'Not signed in.'
404
+ case 'forbidden':
405
+ case 'not_found':
406
+ case 'conflict':
407
+ case 'rejected':
408
+ return isPlannerCode(error.code) ? `${error.code}: ${error.message ?? ''}` : `Refused: ${String(error.status)}`
409
+ case 'unavailable':
410
+ return error.status === undefined ? 'No answer: offline?' : `Busy: try again in ${String(error.retryAfterMs ?? 1000)} ms`
411
+ case 'invalid':
412
+ return `An answer outside the contract: ${error.issues}`
413
+ case 'timeout':
414
+ return 'Too slow.'
415
+ case 'aborted':
416
+ case 'cancelled':
417
+ return 'Stopped.'
418
+ case 'refused':
419
+ return error.fields === undefined ? 'Not sent.' : `Not sent: unknown field ${error.fields.join(', ')}`
420
+ case 'no_token':
421
+ return 'No token to send.'
422
+ default: {
423
+ const unhandled: never = error
424
+ return unhandled
425
+ }
426
+ }
427
+ }
428
+ ```
429
+
430
+ **Sign-in has a few kinds of its own,** beside the ones above:
431
+ - `wrong_state` and `wrong_issuer`: the redirect isn't this sign-in's;
432
+ - `provider_error`, with the server's `code`: the server ended the sign-in. It's `access_denied`
433
+ when the person declined;
434
+ - `no_code`: the redirect carried no code;
435
+ - `listen_failed`, `open_failed` and `paste_failed`: from `signInWithLoopback`;
436
+ - `not_a_url` and `wrong_redirect`: a pasted address that isn't a URL, or isn't this sign-in's
437
+ redirect (`parsePastedRedirect`, or `signInWithLoopback`'s `readPasted`).
438
+
439
+ There, `refused` also covers an issuer that isn't https, and a `pending` that isn't one (from
440
+ storage the app couldn't read back). Nothing is sent for either.
441
+
442
+ ## Options
443
+
444
+ ```ts
445
+ import { createFlipstream } from '@flipstream/sdk'
446
+
447
+ declare const session: { accessToken(rejected?: string): Promise<string> }
448
+
449
+ const fs = createFlipstream({
450
+ // Asked before every attempt; after a 401, asked once more with the token the API refused.
451
+ token: ({ rejected }) => session.accessToken(rejected),
452
+ fetch: globalThis.fetch, // optional: every request goes through it
453
+ hosts: { query: 'https://query.flipstream.io' }, // optional: the default
454
+ })
455
+
456
+ const controller = new AbortController()
457
+ await fs.catalog.list({ signal: controller.signal, deadlineMs: 10_000 })
458
+ ```
459
+
460
+ - **The token function** is asked before every attempt, so a renewed token is always the one sent.
461
+ After a 401 it's asked once more with `{ rejected }`, the token the API refused, and the call is
462
+ sent once more. A second 401 is the answer.
463
+ - **The token only goes to the configured hosts, over https.** No redirect is followed, and no
464
+ cookies are sent. Plain http to a loopback host needs `allowLocalhostHttp: true`, for development
465
+ only.
466
+ - **Retries:**
467
+ - A read (`catalog`, `health`) is tried again after a 408, 429, 502, 503 or 504, or a
468
+ connection that failed, at most twice. It waits as long as `Retry-After` asks, in seconds, or
469
+ 500 ms, then 1 s.
470
+ - `query` is never tried again: a timeout at the gateway may already have run on the warehouse.
471
+ - `no_token` and `refused` are never tried again.
472
+ - A wait that wouldn't end before the deadline isn't started.
473
+ - **Deadlines:** 60 s for `query`, 10 s for `health` and 30 s for the rest, every attempt and
474
+ wait included. `deadlineMs` sets one call's.
475
+ - **Abort:** `signal` ends a call at once, also while it waits for a token or to try again.
476
+ - **Your own transport:** an app that attaches the token itself passes `{ transport }` instead of
477
+ `token` and `fetch`. Retries and deadlines still apply, above it. `health` carries no token, so
478
+ it never goes through your transport: it goes to the query host, over https, with the global
479
+ `fetch`.
480
+
481
+ ## Requirements
482
+
483
+ - **Node 20.19+ or 22.12+,** or a current browser. Sign-in needs WebCrypto, so a page that signs
484
+ in must be served over https, or from localhost.
485
+ - **ESM.** The package is ES modules only. On these Node versions, `require()` loads it from
486
+ CommonJS too, both entries; Node 22.12 prints an experimental warning when it does.
487
+ - **The types ship in the package,** for both entries. The Node entry's types use Node's own,
488
+ from `@types/node`.
489
+
490
+ ## Licence
491
+
492
+ Apache-2.0.
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/api/index.ts"],"names":[],"mappings":""}
@@ -0,0 +1,23 @@
1
+ import type { ApiResult } from '../core/result.js';
2
+ import { type AuthCallOptions } from './transport.js';
3
+ /** What sign-in needs from an authorization server's metadata (RFC 8414), and nothing more. */
4
+ export interface AuthServer {
5
+ /** The issuer as its metadata names it: what a redirect's `iss` must equal (RFC 9207). */
6
+ readonly issuer: string;
7
+ /** Where the person is sent to sign in. */
8
+ readonly authorizationEndpoint: string;
9
+ /** Where the code is exchanged for tokens. */
10
+ readonly tokenEndpoint: string;
11
+ /** Where a session is ended (RFC 7009), when the server has one. */
12
+ readonly revocationEndpoint?: string;
13
+ /** The server puts `iss` on every redirect (RFC 9207), so a redirect without one is refused. */
14
+ readonly issuerOnRedirect: boolean;
15
+ }
16
+ /**
17
+ * The authorization server at `issuer`, from its RFC 8414 metadata. `refused`, with nothing sent,
18
+ * when `issuer` isn't an https URL. Refused as `invalid`: metadata that doesn't name `issuer`
19
+ * exactly (§3.3), an endpoint that is not an https URL, and a server that doesn't list PKCE's
20
+ * S256, since one that lists no methods supports no PKCE (§2), and a code it issues is bound to no
21
+ * verifier.
22
+ */
23
+ export declare function discover(issuer: string, options?: AuthCallOptions): Promise<ApiResult<AuthServer>>;
@@ -0,0 +1,71 @@
1
+ import { z } from 'zod';
2
+ import { call } from '../core/call.js';
3
+ import { authTransport, isHttpsUrl } from './transport.js';
4
+ // Unknown fields are kept and never read: `first_party_client_id` among them, which the SDK never
5
+ // uses in place of the app's own client ID (D421).
6
+ const zMetadata = z.looseObject({
7
+ issuer: z.string(),
8
+ authorization_endpoint: z.string(),
9
+ token_endpoint: z.string(),
10
+ revocation_endpoint: z.string().exactOptional(),
11
+ code_challenge_methods_supported: z.array(z.string()).exactOptional(),
12
+ authorization_response_iss_parameter_supported: z.boolean().exactOptional(),
13
+ });
14
+ /**
15
+ * The authorization server at `issuer`, from its RFC 8414 metadata. `refused`, with nothing sent,
16
+ * when `issuer` isn't an https URL. Refused as `invalid`: metadata that doesn't name `issuer`
17
+ * exactly (§3.3), an endpoint that is not an https URL, and a server that doesn't list PKCE's
18
+ * S256, since one that lists no methods supports no PKCE (§2), and a code it issues is bound to no
19
+ * verifier.
20
+ */
21
+ export async function discover(issuer, options = {}) {
22
+ if (typeof issuer !== 'string' || !isHttpsUrl(issuer))
23
+ return { ok: false, error: { kind: 'refused' } };
24
+ const read = await call(authTransport(options), {
25
+ effect: 'read',
26
+ service: 'auth',
27
+ endpoint: 'auth.discover',
28
+ makeRequest: () => new Request(metadataUrl(issuer), { headers: { accept: 'application/json' } }),
29
+ schema: zMetadata,
30
+ deadlineMs: 10_000,
31
+ retry: 'read',
32
+ }, options.signal);
33
+ if (!read.ok)
34
+ return read;
35
+ const doc = read.data;
36
+ const problem = problemWith(doc, issuer);
37
+ if (problem !== null)
38
+ return { ok: false, error: { kind: 'invalid', issues: problem, status: 200 } };
39
+ return {
40
+ ok: true,
41
+ data: {
42
+ issuer: doc.issuer,
43
+ authorizationEndpoint: doc.authorization_endpoint,
44
+ tokenEndpoint: doc.token_endpoint,
45
+ ...(doc.revocation_endpoint === undefined ? {} : { revocationEndpoint: doc.revocation_endpoint }),
46
+ issuerOnRedirect: doc.authorization_response_iss_parameter_supported === true,
47
+ },
48
+ };
49
+ }
50
+ /**
51
+ * RFC 8414 §3.1: the well-known path goes between the host and the issuer's own path, so
52
+ * `https://a.example/tenant` is read at `https://a.example/.well-known/oauth-authorization-server/tenant`.
53
+ */
54
+ function metadataUrl(issuer) {
55
+ const url = new URL(issuer);
56
+ const path = url.pathname === '/' ? '' : url.pathname.replace(/\/+$/, '');
57
+ url.pathname = `/.well-known/oauth-authorization-server${path}`;
58
+ return url.toString();
59
+ }
60
+ function problemWith(doc, issuer) {
61
+ // Identical, as §3.3 says: a redirect's `iss` is later held to this very string (RFC 9207).
62
+ if (doc.issuer !== issuer)
63
+ return 'the metadata names another issuer';
64
+ const endpoints = [doc.authorization_endpoint, doc.token_endpoint, ...(doc.revocation_endpoint === undefined ? [] : [doc.revocation_endpoint])];
65
+ if (!endpoints.every(isHttpsUrl))
66
+ return 'an endpoint is not an https URL';
67
+ if (doc.code_challenge_methods_supported?.includes('S256') !== true)
68
+ return 'the server does not list PKCE S256';
69
+ return null;
70
+ }
71
+ //# sourceMappingURL=discovery.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"discovery.js","sourceRoot":"","sources":["../../src/auth/discovery.ts"],"names":[],"mappings":"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"}
@@ -0,0 +1,5 @@
1
+ export { discover } from './discovery.js';
2
+ export type { AuthServer } from './discovery.js';
3
+ export { finishSignIn, startSignIn } from './signIn.js';
4
+ export type { CallbackError, PendingSignIn, SignInError, SignInRequest, SignInResult, Tokens } from './signIn.js';
5
+ export type { AuthCallOptions } from './transport.js';
@@ -0,0 +1,5 @@
1
+ // Sign-in (#63–#66) exports from here, so it never edits src/index.ts. For Flipstream's own apps
2
+ // for now (D424): each brings its own client ID and scopes (D421).
3
+ export { discover } from './discovery.js';
4
+ export { finishSignIn, startSignIn } from './signIn.js';
5
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/auth/index.ts"],"names":[],"mappings":"AAAA,iGAAiG;AACjG,mEAAmE;AACnE,OAAO,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAA;AAEzC,OAAO,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,aAAa,CAAA"}
@@ -0,0 +1,10 @@
1
+ /** base64url without padding (RFC 7636 §3, RFC 4648 §5). */
2
+ export declare function base64url(bytes: Uint8Array): string;
3
+ /**
4
+ * `byteLength` bytes from the platform's CSPRNG, base64url-encoded: the verifier (64 bytes, 86
5
+ * characters, inside RFC 7636's 43 to 128) and the state. Never a non-cryptographic generator:
6
+ * the verifier is a public client's whole defence against a stolen code.
7
+ */
8
+ export declare function randomValue(byteLength: number): string;
9
+ /** The S256 challenge: base64url(SHA-256(the verifier's ASCII bytes)). */
10
+ export declare function challengeOf(verifier: string): Promise<string>;
@@ -0,0 +1,25 @@
1
+ /*
2
+ * PKCE (RFC 7636) and the sign-in's random values, from Web Crypto alone, so the same code runs
3
+ * in browsers and in Node 20+, with no node:crypto in a bundle. Ported from the CLI's pkce.ts.
4
+ */
5
+ /** base64url without padding (RFC 7636 §3, RFC 4648 §5). */
6
+ export function base64url(bytes) {
7
+ let binary = '';
8
+ for (const byte of bytes)
9
+ binary += String.fromCharCode(byte);
10
+ return btoa(binary).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
11
+ }
12
+ /**
13
+ * `byteLength` bytes from the platform's CSPRNG, base64url-encoded: the verifier (64 bytes, 86
14
+ * characters, inside RFC 7636's 43 to 128) and the state. Never a non-cryptographic generator:
15
+ * the verifier is a public client's whole defence against a stolen code.
16
+ */
17
+ export function randomValue(byteLength) {
18
+ return base64url(crypto.getRandomValues(new Uint8Array(byteLength)));
19
+ }
20
+ /** The S256 challenge: base64url(SHA-256(the verifier's ASCII bytes)). */
21
+ export async function challengeOf(verifier) {
22
+ const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier));
23
+ return base64url(new Uint8Array(digest));
24
+ }
25
+ //# sourceMappingURL=pkce.js.map