@zerosumstudio/conduit 0.0.0-stage → 1.0.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.
@@ -0,0 +1,27 @@
1
+ import { t as Client } from "./core-DXSbz15-.js";
2
+ import { i as ConduitPromise, u as MethodOptions } from "./types-B9nuOKel.js";
3
+ interface UploadProgressEvent {
4
+ readonly loaded: number;
5
+ /** `undefined` when the server did not report a length, so a percentage cannot be shown. */
6
+ readonly total: number | undefined;
7
+ readonly percent: number | undefined;
8
+ }
9
+ export interface UploadProgressOptions extends MethodOptions {
10
+ /** Fires as the body is sent, which `fetch` has no way to report. */
11
+ onProgress: (event: UploadProgressEvent) => void;
12
+ }
13
+ /**
14
+ * Posts a `FormData` or `Blob` with upload progress. It goes through
15
+ * `XMLHttpRequest`, since `fetch` has no event for it, but still runs through
16
+ * the client's middleware: session, retry, the queue and the origin check apply.
17
+ *
18
+ * `XMLHttpRequest` cannot refuse a redirect, so a request that carries a custom
19
+ * credential header fails with `INVALID_ARGUMENT` unless it sets
20
+ * `redirect: 'follow'`. Credentials in `Authorization` and cookies are fine.
21
+ *
22
+ * ```ts
23
+ * await uploadWithProgress(api, '/files', form, { onProgress: e => setPercent(e.percent) })
24
+ * ```
25
+ */
26
+ export declare function uploadWithProgress<T = unknown>(client: Client, path: string, body: FormData | Blob, options: UploadProgressOptions): ConduitPromise<T>;
27
+ export type { UploadProgressEvent };
package/dist/upload.js ADDED
@@ -0,0 +1,94 @@
1
+ // src/http/xhr.ts
2
+ function toProgressEvent(loaded, total, lengthComputable) {
3
+ return {
4
+ loaded,
5
+ total: lengthComputable ? total : void 0,
6
+ percent: lengthComputable && total > 0 ? Math.round(loaded / total * 100) : void 0
7
+ };
8
+ }
9
+ /** Statuses a `Response` refuses to be built with a body for. */
10
+ const NULL_BODY_STATUSES = /* @__PURE__ */ new Set([
11
+ 101,
12
+ 204,
13
+ 205,
14
+ 304
15
+ ]);
16
+ function parseRawHeaders(raw) {
17
+ const headers = new Headers();
18
+ for (const line of raw.trim().split(/\r?\n/)) {
19
+ if (line === "") continue;
20
+ const split = line.indexOf(":");
21
+ if (split === -1) continue;
22
+ headers.append(line.slice(0, split).trim(), line.slice(split + 1).trim());
23
+ }
24
+ return headers;
25
+ }
26
+ /** A `fetch` that reports upload progress, which `fetch` itself has no way to do. */
27
+ function createXhrFetch(onProgress) {
28
+ return (input, init) => new Promise((resolve, reject) => {
29
+ const signal = init.signal;
30
+ if (signal?.aborted === true) {
31
+ reject(new DOMException("The operation was aborted.", "AbortError"));
32
+ return;
33
+ }
34
+ const xhr = new XMLHttpRequest();
35
+ xhr.open(init.method ?? "GET", input, true);
36
+ xhr.responseType = "blob";
37
+ if (init.credentials === "include") xhr.withCredentials = true;
38
+ if (init.headers !== void 0) new Headers(init.headers).forEach((value, name) => {
39
+ xhr.setRequestHeader(name, value);
40
+ });
41
+ xhr.upload.addEventListener("progress", (event) => {
42
+ onProgress(toProgressEvent(event.loaded, event.total, event.lengthComputable));
43
+ });
44
+ xhr.addEventListener("load", () => {
45
+ try {
46
+ resolve(new Response(NULL_BODY_STATUSES.has(xhr.status) ? null : xhr.response, {
47
+ status: xhr.status,
48
+ statusText: xhr.statusText,
49
+ headers: parseRawHeaders(xhr.getAllResponseHeaders())
50
+ }));
51
+ } catch (cause) {
52
+ reject(cause instanceof Error ? cause : /* @__PURE__ */ new TypeError("Failed to read the response"));
53
+ }
54
+ });
55
+ xhr.addEventListener("error", () => {
56
+ reject(/* @__PURE__ */ new TypeError("Failed to fetch"));
57
+ });
58
+ xhr.addEventListener("timeout", () => {
59
+ reject(new DOMException("The upload timed out.", "TimeoutError"));
60
+ });
61
+ xhr.addEventListener("abort", () => {
62
+ reject(new DOMException("The operation was aborted.", "AbortError"));
63
+ });
64
+ if (signal !== void 0 && signal !== null) signal.addEventListener("abort", () => xhr.abort(), { once: true });
65
+ xhr.send(init.body);
66
+ });
67
+ }
68
+
69
+ // src/upload.ts
70
+ /**
71
+ * Posts a `FormData` or `Blob` with upload progress. It goes through
72
+ * `XMLHttpRequest`, since `fetch` has no event for it, but still runs through
73
+ * the client's middleware: session, retry, the queue and the origin check apply.
74
+ *
75
+ * `XMLHttpRequest` cannot refuse a redirect, so a request that carries a custom
76
+ * credential header fails with `INVALID_ARGUMENT` unless it sets
77
+ * `redirect: 'follow'`. Credentials in `Authorization` and cookies are fine.
78
+ *
79
+ * ```ts
80
+ * await uploadWithProgress(api, '/files', form, { onProgress: e => setPercent(e.percent) })
81
+ * ```
82
+ */
83
+ function uploadWithProgress(client, path, body, options) {
84
+ const { onProgress, meta, ...rest } = options;
85
+ return client.upload(path, body, {
86
+ ...rest,
87
+ meta: {
88
+ ...meta,
89
+ fetch: createXhrFetch(onProgress)
90
+ }
91
+ });
92
+ }
93
+
94
+ export { uploadWithProgress };
@@ -0,0 +1,423 @@
1
+ # Migrating from `@bkincz/conduit` 2.0 to `@zerosumstudio/conduit` 1.0
2
+
3
+ 1.0 is the first release under `@zerosumstudio`. It is ESM-only on Node 26, renames and splits the error codes, stops caching a tagged `POST` on its own, removes the sticky session terminal state, makes redirects and origins stricter, and renames many options and methods. There is no compatibility layer, so every change below is yours to make. Most are mechanical.
4
+
5
+ This guide covers `@bkincz/conduit` 2.0.0. Older versions need the 2.0 changes first.
6
+
7
+ ## Checklist
8
+
9
+ Work through these in order, then run the type checker and your tests.
10
+
11
+ 1. Install `@zerosumstudio/conduit`, remove `@bkincz/conduit`, and change every import and any `declare module '@bkincz/conduit'`. Use Node 26 or newer.
12
+ 2. Replace error code checks: `'HTTP_ERROR'` is `'HTTP_STATUS'`, `'PARSE'` is `'PARSE_FAILED'`, `'SCHEMA'` is `'VALIDATION_FAILED'`, and `'CONFIG'` is split. See [error codes](#error-codes).
13
+ 3. Add `identify` to every session adapter, including a cookie adapter. See [session](#session).
14
+ 4. Rename plugin options: `cache({ ttl, staleWhileRevalidate })` is `{ ttlMs, staleMs }`, `retry` delays take `Ms`, `session({ eager, refreshLeeway })` is `{ autoLoad, refreshLeewayMs }`, and `meta.timeout` is `meta.timeoutMs`. See [plugins](#plugins).
15
+ 5. Rename client methods and state reads: `keyFor` is `getKey`, `cacheSize` is `getCacheSize`, and every store's `get()` is `getState()`, `api.session.get()` included. See [client](#client).
16
+ 6. Add `cacheable: true` to every endpoint or request that reads through a `POST`. Tags no longer switch caching on. See [caching](#caching).
17
+ 7. Rename `sharedClient` options: `{ contract, version }` is `{ apiVersion, clientVersion }`, and `contract()` is `apiVersion()`. See [shared client](#shared-client).
18
+ 8. Update `redact` and `DEFAULT_REDACTED_HEADERS`. See [redaction](#redaction).
19
+ 9. If a custom `fetch` or a test matches the request url, match on the pathname, since the url is always absolute. See [origins](#origins-and-urls).
20
+ 10. Move `clearSharedClients` to `@zerosumstudio/conduit/testing`, and move `onProgress` uploads to `@zerosumstudio/conduit/upload`.
21
+ 11. Check [behaviour changes](#behaviour-changes) against what your app relies on, especially hooks that used to abort and scopes that were killed by a sign-out.
22
+
23
+ ## Package and runtime
24
+
25
+ | 2.0 | 1.0 |
26
+ | ---------------------------------------------- | ------------------------------------------------------------------------------------------------------ |
27
+ | `@bkincz/conduit` | `@zerosumstudio/conduit`. `@bkincz/conduit` stays on npm at 2.0.0 |
28
+ | ESM and CommonJS | ESM only. `require()` of the package works on Node 26 |
29
+ | Node 22.12 or newer | Node 26 or newer (`engines.node` is `>=26`) |
30
+ | Entries `.`, `/react`, `/devtools`, `/testing` | Those, plus `/upload` |
31
+ | Internals exported from the main entry | 21 value exports. Internals such as `compose`, `createRequest`, `createStore` and `deriveKey` are gone |
32
+ | `Client` a class | `Client` a type. Create one with `createClient` |
33
+
34
+ Jest setups that transform to CommonJS need `transformIgnorePatterns` to let the package through.
35
+
36
+ The shared client registry is separate from 2.0's. A page that loads both runs two clients, each with its own cache and session, so move every bundle on a page together.
37
+
38
+ ## Error codes
39
+
40
+ Codes lose the `_ERROR` suffix and each has one meaning. `ERROR_CODES` is gone, so use the `ConduitErrorCode` type. Errors are not subclassed, so check `error.code`.
41
+
42
+ ```ts
43
+ // before
44
+ if (error.code !== 'HTTP_ERROR') return null
45
+ ```
46
+
47
+ ```ts
48
+ // after
49
+ import type { ConduitError } from '@zerosumstudio/conduit'
50
+
51
+ const isStatusFailure = (error: ConduitError) => error.code === 'HTTP_STATUS'
52
+ ```
53
+
54
+ | 2.0 | 1.0 |
55
+ | ------------------------------------------------------------- | ----------------------------------------------------- |
56
+ | `HTTP_ERROR` | `HTTP_STATUS` |
57
+ | `PARSE` | `PARSE_FAILED` |
58
+ | `SCHEMA` | `VALIDATION_FAILED` |
59
+ | `CONFIG` for misuse, bad params, a body on `GET` | `INVALID_ARGUMENT`. A `GET` with a body was `NETWORK` |
60
+ | `CONFIG` for a rejected origin | `ORIGIN_REJECTED` |
61
+ | `CONFIG` for a destroyed client | `DESTROYED` |
62
+ | `CONFIG` for a duplicate plugin | `DUPLICATE_PLUGIN` |
63
+ | `CONFIG` for an extension name clash | `EXTENSION_COLLISION` |
64
+ | (none) | `REDIRECT_BLOCKED`, see [redirects](#redirects) |
65
+ | `NETWORK`, `TIMEOUT`, `ABORTED`, `UNAUTHENTICATED`, `UNKNOWN` | Same |
66
+
67
+ A cancelled request keeps `ABORTED`. `ConduitError.retryAfter` is `retryAfterMs`, and `requestId` is new. `toConduitError(value, code?, message?)` can recode an error and keeps the original as `cause`.
68
+
69
+ Use `isConduitError(value)` for the check, as before. It holds across bundles that carry their own copy of conduit, where `instanceof` doesn't.
70
+
71
+ ## Client
72
+
73
+ | 2.0 | 1.0 |
74
+ | ---------------------------------------------------------------- | ------------------------------------------------------------------------------------------------- |
75
+ | `api.keyFor(path, options)` | `api.getKey(path, options)` |
76
+ | `api.cacheSize()` | `api.getCacheSize()` |
77
+ | `api.inFlight()` | `api.getInFlightCount()` |
78
+ | `api.queueDepth(lane?)`, `api.activeRequests()` | `api.getQueueDepth(lane?)`, `api.getActiveCount()` |
79
+ | `api.observedKeys()` | `api.getObservedCount()` |
80
+ | `store.get()` on `observe(key)`, `api.session`, `devtools.store` | `store.getState()` |
81
+ | `api.events` with `emit` and `clear` | `api.events` with `on`, `onAny` and `active`. Plugins keep the full bus on `PluginContext.events` |
82
+ | `ClientContext`, `EmptyExtension` | `PluginContext`, `NoExtension` |
83
+ | Devtools `stop()` | `detach()` |
84
+
85
+ ```ts
86
+ // before
87
+ const state = api.session.get()
88
+ api.invalidate(api.keyFor('/users/:id', { params: { id } }))
89
+ ```
90
+
91
+ ```ts
92
+ // after
93
+ const state = api.session.getState()
94
+ api.invalidate(api.getKey('/users/:id', { params: { id: 7 } }))
95
+ ```
96
+
97
+ `subscribe(listener)` on every store doesn't call the listener on subscribe, as before. In Svelte, wrap the store: `readable(store.getState(), set => store.subscribe(set))`. 2.0's README said Svelte reads it as is, and it didn't.
98
+
99
+ ### Path params are typed
100
+
101
+ When the path is a literal, `params` is required and checked. A call that omitted `params`, or passed the wrong name, no longer compiles. Give the result type with `get<User>(path)` and `params` stays loose, and unchecked until run time.
102
+
103
+ ```ts
104
+ // after
105
+ api.get('/users/:id', { params: { id: 7 } })
106
+ api.get('/users/:id', { params: { userId: 7 } }) // compile error: no such param
107
+ ```
108
+
109
+ `defineEndpoint` without type arguments reads `Vars` from the path, so `defineEndpoint({ method: 'GET', path: '/users/:id' })` asks for `{ id }`. Give both type arguments to keep the old shape.
110
+
111
+ ### Uploads
112
+
113
+ `api.upload(path, body, options)` no longer takes `onProgress`. Progress uploads moved to their own entry, which takes the `XMLHttpRequest` path out of the core bundle.
114
+
115
+ ```ts
116
+ // before
117
+ await api.upload('/avatars', file, { onProgress: event => setProgress(event.percent) })
118
+ ```
119
+
120
+ ```ts
121
+ // after
122
+ import { uploadWithProgress } from '@zerosumstudio/conduit/upload'
123
+
124
+ await uploadWithProgress(api, '/avatars', file, {
125
+ onProgress: event => setProgress(event.percent ?? 0),
126
+ })
127
+ ```
128
+
129
+ `percent` and `total` are `undefined` when the server reports no length. A progress upload with a custom credential header rejects with `INVALID_ARGUMENT` unless `redirect: 'follow'` is set, and `credentials: 'omit'` is rejected too. See [redirects](#redirects).
130
+
131
+ ## Plugins
132
+
133
+ | 2.0 | 1.0 |
134
+ | ------------------------------------------------------------------------- | --------------------------------------------------------------------------------- |
135
+ | `cache({ ttl })` | `cache({ ttlMs })` |
136
+ | `cache({ staleWhileRevalidate: true })` | `cache({ staleMs: Infinity })`. A number of ms is `staleMs` too |
137
+ | `cache({ shouldCache })`, `dedupe({ shouldDedupe })` | Gone. Use `cacheable` on the request or endpoint, or the `bypass` meta |
138
+ | `dedupe(config)`, `defaults({ dedupe })` | `dedupe()` takes no options and `defaults()` has no `dedupe` key |
139
+ | `retry({ baseDelay, maxDelay })` | `retry({ baseDelayMs, maxDelayMs })`, plus `maxRetryAfterMs` (30 s) |
140
+ | `RetryInfo.delay`, event `delay` and `reason` | `delayMs` and `code` (a `ConduitErrorCode`) |
141
+ | `ConduitError.retryAfter` | `retryAfterMs` |
142
+ | `meta: { timeout: 60_000 }` | `meta: { timeoutMs: 60_000 }` |
143
+ | `CACHE_META`, `DEDUPE_META`, `QUEUE_META`, `SESSION_META`, `TIMEOUT_META` | Gone. Write the key: `meta: { cache: 'bypass' }`. Keys are typed on `ConduitMeta` |
144
+ | `contract({ expected })` | `apiVersion({ expected })` |
145
+ | Event `contract:mismatch` | `api-version:mismatch` |
146
+
147
+ ```ts
148
+ // before
149
+ cache: { ttl: 30_000, staleWhileRevalidate: true }
150
+ ```
151
+
152
+ ```ts
153
+ // after
154
+ const api = defaults(createClient({ baseUrl: '/api' }), {
155
+ cache: { ttlMs: 30_000, staleMs: Infinity },
156
+ })
157
+ ```
158
+
159
+ Event fields changed with the names: `duration` is `durationMs`, `cache:stale`'s `revalidating` is `isRevalidating`, and `session:change`'s `terminal` is `isLost`. Devtools state follows: `duration` is `durationMs` and `sessionTerminal` is `isSessionLost`.
160
+
161
+ `retry` now also refuses to replay a `POST` or `PATCH` unless it is `cacheable`, and gives up on a `Retry-After` longer than `maxRetryAfterMs` instead of waiting for it.
162
+
163
+ ## Caching
164
+
165
+ In 2.0 a request with `tags` was cached whatever its method. Two tagged `POST`s or `DELETE`s with the same body became one request at the server, so a tag meant for invalidation silently stopped writes from happening. In 1.0 `tags` are labels for `invalidateTag` and nothing else, and `cacheable` switches caching and request sharing on. It defaults to `true` for `GET` and `HEAD`.
166
+
167
+ ```ts
168
+ // before
169
+ export const listSubmissions = defineEndpoint<ListVars, ListResponse>({
170
+ method: 'POST',
171
+ path: '/marked-assessments/list-submissions',
172
+ body: vars => vars,
173
+ tags: vars => ['submissions', `submissions:${vars.assessmentId}`],
174
+ })
175
+ ```
176
+
177
+ ```ts
178
+ // after
179
+ export const listSubmissions = defineEndpoint<{ assessmentId: string }, User[]>({
180
+ method: 'POST',
181
+ path: '/marked-assessments/list-submissions',
182
+ body: vars => vars,
183
+ cacheable: true, // this POST only reads
184
+ tags: vars => ['submissions', `submissions:${vars.assessmentId}`],
185
+ })
186
+ ```
187
+
188
+ Without `cacheable: true` an endpoint like this stops caching and stops sharing flights, and `useRequest` warns in development. A cacheable `POST` with a `FormData` or `Blob` body never shares an entry. `retry` treats a `cacheable` request as safe to replay.
189
+
190
+ `isStale` on a hook is now true only when the data was served stale while a refresh runs. It used to be true on any cache hit. Read `updatedAt` for when the data arrived.
191
+
192
+ ## Session
193
+
194
+ The state is a union on `status`, with no sticky terminal state.
195
+
196
+ | 2.0 | 1.0 |
197
+ | ----------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------- |
198
+ | `identify` optional | Required. `session()` throws `INVALID_ARGUMENT` without it |
199
+ | `authorize(request, session \| null)` | `authorize(request, session)`, called only when signed in. Drop the null check |
200
+ | `session({ eager, refreshLeeway })` | `session({ autoLoad, refreshLeewayMs })` |
201
+ | `api.session.get()` | `api.session.getState()` |
202
+ | After a failed renewal every in-scope request rejected `UNAUTHENTICATED` until `reload()` | The session is `anonymous` with `error.code === 'UNAUTHENTICATED'`, and later requests go out without credentials |
203
+ | Any 401 on an in-scope request ended the session | Only a 401 on a request that carried credentials, after one renewal, does |
204
+ | `reload()` joined a read in flight | It starts a new read, and the latest wins |
205
+ | `load()` returned early after a terminal state | It returns a known session without a request, and otherwise joins the read in flight |
206
+ | A lost session aborted every scope for good | It cancels only the session's own credentialed requests. Scopes stay usable |
207
+
208
+ ```ts
209
+ // before
210
+ export const nextAuthSession: SessionAdapter<MmwSession> = {
211
+ load: async ctx => {
212
+ const response = await ctx.request<NextAuthSessionResponse>('/auth/session')
213
+
214
+ if (!response.user) return null
215
+
216
+ return { user: response.user, expires: response.expires ?? '' }
217
+ },
218
+ expiresAt: session => Date.parse(session.expires),
219
+ }
220
+ ```
221
+
222
+ ```ts
223
+ // after
224
+ import type { SessionAdapter } from '@zerosumstudio/conduit'
225
+
226
+ interface AppSession {
227
+ user: { id: string }
228
+ expires: string
229
+ }
230
+
231
+ interface SessionResponse {
232
+ user?: { id: string }
233
+ expires?: string
234
+ }
235
+
236
+ export const nextAuthSession: SessionAdapter<AppSession> = {
237
+ load: async ctx => {
238
+ const response = await ctx.request<SessionResponse>('/auth/session')
239
+
240
+ if (!response.user) return null
241
+
242
+ return { user: response.user, expires: response.expires ?? '' }
243
+ },
244
+ identify: session => session.user.id,
245
+ expiresAt: session => Date.parse(session.expires),
246
+ }
247
+ ```
248
+
249
+ A cookie adapter has no `authorize`, so it doesn't wait for its first read. Call `api.session.load()` at boot, or pass `autoLoad: true`, before a 401 can mean a lost session. Call `reload()` after signing in. A sign-in or refresh call that must skip `authorize` and 401 handling takes `meta: { session: 'bypass' }`. A failed first read is `UNKNOWN` with the original as `cause`.
250
+
251
+ `session({ channel })` is new and optional. It makes other tabs re-read when this one signs out or changes user.
252
+
253
+ ## Origins and urls
254
+
255
+ | 2.0 | 1.0 |
256
+ | --------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------------------------- |
257
+ | A string guard compared origins | Every url resolves with `new URL` and is compared as an origin. What is sent is the checked href |
258
+ | `//host/path` rejected with `CONFIG` | A path under `baseUrl`, so it can't reach another host. Only an absolute url can name another origin, and it must be in `origins` |
259
+ | `/\host`, `data:` and similar spellings could go out | `ORIGIN_REJECTED` |
260
+ | A relative path could climb out of `baseUrl`'s path | It has to stay inside the prefix, or it is `ORIGIN_REJECTED`. A `.` or `..` param is `INVALID_ARGUMENT` |
261
+ | A path that reads as a scheme (`users:list`) | `ORIGIN_REJECTED` with a hint. Write `/users:list` |
262
+ | `origins` compared as strings | Bare origins, normalised at install. A path, query or non-http scheme is `INVALID_ARGUMENT` |
263
+ | A relative `baseUrl` with no page passed through | `INVALID_ARGUMENT`. Pass an absolute `baseUrl` on a server or in a node test environment |
264
+ | `request.url`, `MockCall.url` and a custom `fetch`'s input as written | Always the absolute href |
265
+
266
+ A custom `fetch`, a dev mock or a test double that matched on the written path needs the pathname:
267
+
268
+ ```ts
269
+ // before
270
+ const isSession = (input: string) => input.startsWith('/api/auth/session')
271
+ ```
272
+
273
+ ```ts
274
+ // after
275
+ const isSession = (input: string) => new URL(input).pathname.startsWith('/api/auth/session')
276
+ ```
277
+
278
+ A check that used `input.includes('/api/auth/')` keeps working. The mock server matches on the pathname for you.
279
+
280
+ ## Redirects
281
+
282
+ Node and every browser strip `Authorization` and `cookie` when a redirect crosses origins, and send any other header on. In 2.0 a same-origin download endpoint that answered 302 to a CDN, or an open redirect, therefore received an `x-api-key` or a CSRF token. In 1.0 a request carrying such a credential is sent with `redirect: 'manual'`, and a redirect answer rejects with `REDIRECT_BLOCKED`.
283
+
284
+ A credential here is a header in `DEFAULT_REDACT.headers`, one in `redact.headers`, or one the session's `authorize` sets. Plain Bearer and cookie setups don't match and keep following redirects. A static header outside the list, such as an `x-mmw-client` marker, isn't a credential.
285
+
286
+ ```ts
287
+ // after
288
+ api.get('/download', { headers: { 'x-api-key': key }, redirect: 'follow' })
289
+ ```
290
+
291
+ An explicit `redirect` on the request or the client always wins. The rule covers same-origin redirects too, so a custom credential on an endpoint that really redirects needs `redirect: 'follow'`. With an explicit `redirect: 'manual'`, a 3xx is an `HTTP_STATUS`.
292
+
293
+ ## Redaction
294
+
295
+ `redact` is an object with a list for headers and one for query parameters.
296
+
297
+ ```ts
298
+ // before
299
+ createClient({ redact: ['authorization', 'x-tenant'] })
300
+ ```
301
+
302
+ ```ts
303
+ // after
304
+ import { DEFAULT_REDACT, createClient } from '@zerosumstudio/conduit'
305
+
306
+ createClient({
307
+ redact: { headers: [...DEFAULT_REDACT.headers, 'x-tenant'], query: [...DEFAULT_REDACT.query] },
308
+ })
309
+ ```
310
+
311
+ - `DEFAULT_REDACTED_HEADERS` is `DEFAULT_REDACT.headers`, and the defaults are wider: `x-api-key`, `x-auth-token`, `x-csrf-token`, `x-xsrf-token`, `x-session-token`, `x-access-token` and `x-amz-security-token` join the three from 2.0.
312
+ - Secret query values are hidden too, in error urls, keys and events, from `DEFAULT_REDACT.query`.
313
+ - `redact.headers` still replaces the defaults for display only. The redirect and upload guards always use the defaults plus `redact.headers` plus what `authorize` sets.
314
+ - `redactRequest` is no longer exported.
315
+
316
+ ## Shared client
317
+
318
+ ```ts
319
+ // before
320
+ sharedClient('mmw.api', factory, { contract: 'v2', version: 2 })
321
+ ```
322
+
323
+ ```ts
324
+ // after
325
+ import { sharedClient } from '@zerosumstudio/conduit'
326
+
327
+ export const shared = sharedClient('mmw.api', () => createClient({ baseUrl: '/api' }), {
328
+ apiVersion: 'v2',
329
+ clientVersion: 2,
330
+ })
331
+ ```
332
+
333
+ The options type is `SharedClientConfig`, and the `apiVersion` plugin replaces `contract()`. The mismatch kinds are `'conduit-version'`, `'api-version'` and `'client-version'`. `clearSharedClients` moved to the testing entry:
334
+
335
+ ```ts
336
+ // after
337
+ import { clearSharedClients } from '@zerosumstudio/conduit/testing'
338
+
339
+ afterEach(() => {
340
+ clearSharedClients()
341
+ })
342
+ ```
343
+
344
+ ## React
345
+
346
+ | 2.0 | 1.0 |
347
+ | --------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------- |
348
+ | `useRequest` aborted the previous request on a key change and unmount | It never aborts. A superseded request finishes and fills the cache. Cancel with a `signal` or a scope |
349
+ | `refetchOnFocus` fired on `focus` and `visibilitychange` | `visibilitychange` only, through one shared listener, and it honours a fresh cache entry |
350
+ | `useMutation().mutate` resolved `T \| undefined`, `error: unknown` | It resolves a `SafeResult<T>`, `error` is `ConduitError \| undefined`, and `status` is new |
351
+ | `useRequest` result | Adds `updatedAt` |
352
+ | `useSession` without the plugin | Throws `INVALID_ARGUMENT` |
353
+
354
+ ```ts
355
+ // before
356
+ const result = await mutate({ name })
357
+
358
+ if (result === undefined) return showError()
359
+ ```
360
+
361
+ ```tsx
362
+ // after
363
+ function NewUser() {
364
+ const { mutate } = useMutation((variables: { name: string }) =>
365
+ api.post<User>('/users', variables),
366
+ )
367
+
368
+ async function handleSubmit(name: string) {
369
+ const { data, error } = await mutate({ name })
370
+
371
+ if (error !== null) return reportToTelemetry(error.message)
372
+
373
+ navigate(`/users/${data.id}`)
374
+ }
375
+
376
+ return <Form onSubmit={handleSubmit} busy={false} error={undefined} />
377
+ }
378
+ ```
379
+
380
+ A mutation that succeeds with no body resolves `{ data, error: null }`, which 2.0's `undefined` couldn't tell apart from a failure.
381
+
382
+ ## Testing
383
+
384
+ `createMockServer` matches what a real `fetch` does:
385
+
386
+ | 2.0 | 1.0 |
387
+ | -------------------------------------------- | ------------------------------------------------------------------------------------------------- |
388
+ | A string responder was JSON | A string is text. Anything else that isn't a body type is JSON |
389
+ | The first matching route won | The last one registered wins, and a route used up by `times` falls through |
390
+ | A responder that threw was a `NETWORK` error | It answers 500 with `{ message }`. Return an `Error` for a network failure |
391
+ | The request's signal was ignored | It is honoured, and `MockRequest.signal` is new |
392
+ | Routes matched the written path | They match the pathname of the absolute url, and `MockRequest` has an absolute `url` and a `path` |
393
+ | `clearSharedClients` from the root | From `@zerosumstudio/conduit/testing` |
394
+
395
+ Test environments that run on happy-dom or jsdom have a page, so a relative `baseUrl` keeps working. A node environment needs an absolute `baseUrl`.
396
+
397
+ ## Behaviour changes
398
+
399
+ - A sign-out, or a lost session, no longer kills every scope. `scope.abort()` cancels what is in flight and the scope stays usable. Use `scope.dispose()` to end one. `api.abortAll()` keeps scopes usable too.
400
+ - A change of user and `session.clear()` cancel the session's in-flight credentialed requests with `ABORTED`.
401
+ - A 401 on an anonymous session, such as a failed sign-in, is an ordinary `HTTP_STATUS`.
402
+ - Messages, errors and events carry the url with secret query values hidden, and devtools strip the query entirely.
403
+ - The shared registry key is `Symbol.for('conduit.sharedClients.1')`.
404
+ - Logs use the `[conduit]` prefix, and every background failure goes through `config.logger`: a throwing listener, a failed background refresh, a failed renewal and a background session read.
405
+ - Sizes: core 6.81 KB and the full entry 12.62 KB brotli, from 6.0 and 11.7 KB. `/upload` is 651 B.
406
+
407
+ ## Types
408
+
409
+ | 2.0 | 1.0 |
410
+ | ---------------------------------------------------------------- | ------------------------------------------------------------------- |
411
+ | `ClientContext` | `PluginContext`, with `notifyCacheChange` and `onCacheChange` |
412
+ | `EmptyExtension` | `NoExtension` |
413
+ | `SharedClientOptions` | `SharedClientConfig` |
414
+ | `ContractMismatch`, `ContractConfig`, `ContractMismatchEvent` | `ApiVersionMismatch`, `ApiVersionConfig`, `ApiVersionMismatchEvent` |
415
+ | `DefaultStack` | `DefaultClient` |
416
+ | `ConduitErrorCode` from `ERROR_CODES` | A union type |
417
+ | Event and devtools fields `duration`, `terminal`, `revalidating` | `durationMs`, `isLost`, `isRevalidating` |
418
+
419
+ ## Plugin authors
420
+
421
+ - A plugin gets a `PluginContext`: `config`, `events` (the full bus), `request`, `dispatch`, `isApiOrigin`, `resetIdentity`, `onResetIdentity`, `notifyCacheChange` and `onCacheChange`. `abortAll` is no longer on it.
422
+ - `ConduitRequest.cacheable` is resolved once. Check it instead of method and tags.
423
+ - Report a failure nobody awaits through `ctx.config.logger`.
@@ -0,0 +1,69 @@
1
+ # Threat model
2
+
3
+ What conduit protects, what it deliberately leaves to the app, and what that asks of you. The decisions behind it are in [docs/adr](./adr).
4
+
5
+ ## The setting
6
+
7
+ One client is shared by every bundle on a page. Bundles are built and deployed separately, and they reach the client through a registry on `globalThis`, not through a framework provider. The session plugin holds whatever credential your adapter gives it and attaches it to requests.
8
+
9
+ That shape has one consequence worth stating first: **every bundle on the page is trusted with the whole client.** A bundle that runs script in the page can issue authenticated requests, read every response, clear the session, or replace the shared client. conduit doesn't try to stop that, because nothing in a browser can. The boundary is the integrity of the bundles you load: immutable remote urls, a content security policy that names the origins you deploy to, and a build pipeline you control. A federation tool such as [spool](https://github.com/zerosumstudio/spool) owns that side.
10
+
11
+ ## Assets
12
+
13
+ | Asset | Where it lives |
14
+ | ------------------------------------ | -------------------------------------------------------------------------------------------- |
15
+ | Credentials | The adapter's session (a token), the browser's cookies, and static `headers` on the client |
16
+ | User data | Response bodies held in the cache, in observed stores, in flight, and in `ConduitError.body` |
17
+ | Secrets in query strings | Request urls, and so history, referrers and server logs |
18
+ | The identity of the signed-in user | `session` state, and the cache and stores keyed under it |
19
+ | Which origin a credential is sent to | The origin policy and the redirect rule |
20
+
21
+ conduit writes nothing to storage. It holds the cache, the session and the registry in memory.
22
+
23
+ ## Trust boundaries
24
+
25
+ - **Remotes on one page.** They share one origin's trust and one client. Treat a remote as able to do whatever the host can through the client. `scope()` is a cancellation boundary, not a permission boundary.
26
+ - **The shared client.** Its registry key is `Symbol.for('conduit.sharedClients.1')`, one per major version, so a 1.0 bundle never receives a client built by another major. A remote can listen to `client.events` and nothing else on the bus: it can't clear listeners or publish events.
27
+ - **A hostile bundle.** One that runs in the page is out of scope, see above. A hostile response, url or markup is in scope: a server-supplied link, a `<base>` tag, a redirect, or a path param built from user input must not move a credential to another origin.
28
+ - **The API and everything it links to.** Origins other than the API's are reachable only when listed in `origins`.
29
+
30
+ ## What conduit enforces
31
+
32
+ - **Credentials stay on listed origins.** Every url resolves with `new URL` and is compared as an origin. Anything outside `baseUrl`'s origin and `origins` rejects with `ORIGIN_REJECTED` before a plugin runs. Only `http:` and `https:` are sent, and a url with credentials in it is refused. The transport checks again and sends the href it checked, so a middleware that rewrites `url` can't leave the list. Relative paths are joined under `baseUrl` and must stay inside its path prefix, so `//host` is a path and `..` climbs nowhere. Path params are URL-encoded, and `.` and `..` are refused.
33
+ - **The session's credentials go to the API origin only.** `authorize` runs for the API origin and for `session({ origins })`, and for nothing else.
34
+ - **A credential isn't carried through a redirect.** A request holding a credential the platform doesn't strip itself (any `DEFAULT_REDACT.headers` entry other than `authorization`, `cookie` and `proxy-authorization`, anything in `redact.headers`, and every header `authorize` sets) is sent with `redirect: 'manual'`, and a redirect answer rejects with `REDIRECT_BLOCKED`. The guard list can't be narrowed through `redact`. A progress upload can't be blocked, so it fails closed with `INVALID_ARGUMENT` unless `redirect: 'follow'` is set.
35
+ - **Credentials and secrets stay out of the client's own surfaces.** `.response()`, every event and devtools read credential headers as `[redacted]`, including a header an adapter sets in place after the event was built. Secret query values read `[redacted]` in error urls, keys and events. `body` and `headers` on a `ConduitError` are non-enumerable and omitted from `toJSON()`, and messages carry the url without its query.
36
+ - **One user's data isn't served to the next.** When `identify` returns a different id, or the session is lost or cleared, the cache, dedupe flights and observed stores reset. The session's in-flight credentialed requests are cancelled, observed state drops writes from reads that began before the reset, and a request that gets its 401 while the user changes is rejected and never replayed under the next user's credentials. Cache keys include the headers `vary` selects, so callers with different headers don't share an entry.
37
+ - **A lost session fails toward anonymous.** After a failed renewal, the session is `anonymous` with `UNAUTHENTICATED`, in-flight credentialed requests are cancelled, cached data is dropped and `onUnauthenticated` fires once. Requests then go out without credentials. There is no refresh storm, because renewal is single-flight, and a 401 on a request that carried no credential doesn't end anything.
38
+ - **Only reads are shared.** Cache and dedupe serve `cacheable` requests, `GET` and `HEAD` by default. `tags` never switch caching on, so a tagged write can't be collapsed into one request. Responses with `cache-control: no-store` or `no-cache` aren't stored. Shared bodies are deeply frozen.
39
+ - **A cross-tab message can't change identity.** The `session({ channel })` message carries no session or user, and only `{ type: 'session:change' }` is acted on. A forged one causes a read from the server.
40
+ - **Misuse fails loudly.** A relative `baseUrl` with no page, a malformed `origins` entry, a missing `identify` and a body on `GET` all throw `INVALID_ARGUMENT`.
41
+
42
+ ## What conduit leaves to the app
43
+
44
+ - **A compromised bundle on the page.** Control the remotes you load: immutable urls, a CSP naming your deploy origins, and `base-uri`.
45
+ - **A `<base href>` on another origin.** With a relative `baseUrl` the API origin comes from the page's base url, so injected markup that sets `<base href>` moves the API origin and the credentials with it. Plain `fetch` resolves the same way. Set `base-uri 'self'` or `'none'` in the CSP.
46
+ - **Static `headers` on listed origins.** They go on every request, including to third-party origins in `origins`. Only `authorize` is scoped to the API origin. Keep a static credential out of `headers` unless every listed origin may see it.
47
+ - **Credentials outside the guard list.** A static header with a name that isn't in `DEFAULT_REDACT.headers` follows a redirect and shows in events. Add its name to `redact.headers`.
48
+ - **Where the credential lives.** A token in memory or an `HttpOnly` cookie is the adapter's and the backend's business. conduit never writes either to storage.
49
+ - **Secrets in query strings.** They travel in the url, into history, referrers and server logs. conduit hides them in its own messages and events, not in the request, and `response.raw.url` is the platform's real url. Put secrets in headers.
50
+ - **What responses contain.** Response bodies are cached, shared between callers and visible to every bundle on the page, and `ConduitError.body` holds the server's error body. Don't log either wholesale.
51
+ - **Server-side isolation.** The registry is process-global and so is a module-level client. On a server, one client per process means one cache and one session across requests. Build a client per request there, with an absolute `baseUrl`.
52
+ - **A page that mixes majors.** A 2.0 bundle and a 1.0 bundle run two clients, each with its own cache and session.
53
+ - **Reachability of the API.** Authorisation is the server's job. A hidden button or a client check isn't access control.
54
+
55
+ ## Defaults that matter
56
+
57
+ | Default | Why |
58
+ | ----------------------------------- | ---------------------------------------------------------------------------- |
59
+ | Other origins rejected | The list is short and explicit, or empty |
60
+ | `vary: '*'` | Every header counts toward identity, so no accidental sharing |
61
+ | `credentials` follows `fetch` | Cross-site cookies need an explicit opt in |
62
+ | Display redaction on | Nobody outside the plugin chain needs the credential |
63
+ | Custom credentials block redirects | The platform strips only `authorization`, `cookie` and `proxy-authorization` |
64
+ | Devtools handle exposed in dev only | A console handle to the client is a development convenience |
65
+ | `retry` replays idempotent requests | Replaying a `POST` that writes can double the write |
66
+
67
+ ## Reporting
68
+
69
+ A security issue in conduit itself: open a private advisory on the GitHub repository rather than a public issue.