@composable-os/client 0.1.0-beta.14 → 0.1.0-beta.16

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/dist/binding.js CHANGED
@@ -23,10 +23,12 @@ function isCustomerCookie(pair) {
23
23
  }
24
24
  /** The customer cookies in a `Cookie` header, as one header value ("" when there are none). */
25
25
  export function customerCookies(cookieHeader) {
26
- return (cookieHeader ?? "")
27
- .split(/;\s*/)
28
- .filter((pair) => pair && isCustomerCookie(pair))
29
- .join("; ");
26
+ const pairs = (cookieHeader ?? "").split(/;\s*/).filter((pair) => pair && isCustomerCookie(pair));
27
+ // A host of many clients sets only `__Host-` names, which a sibling hostname cannot plant: when
28
+ // the browser holds one, only those go on, never an unprefixed one planted on the parent domain
29
+ // (stage 66, ADR 0616; the host reads only `__Host-` names there anyway).
30
+ const hostOnly = pairs.filter((pair) => pair.startsWith(`__Host-${CUSTOMER_COOKIE_PREFIX}.`));
31
+ return (hostOnly.length ? hostOnly : pairs).join("; ");
30
32
  }
31
33
  /** Headers for a call made for the browser's customer: their session cookie, if any. */
32
34
  export function customerSession(cookieHeader) {
@@ -85,15 +87,26 @@ function cookiePairs(header) {
85
87
  */
86
88
  export async function keepCustomerSignedIn(options) {
87
89
  const pairs = cookiePairs(options.cookieHeader);
88
- const session = pairs.find(([name]) => unprefixed(name) === `${CUSTOMER_COOKIE_PREFIX}.session_token`);
90
+ const sessionName = `${CUSTOMER_COOKIE_PREFIX}.session_token`;
91
+ // A host of many clients sets only `__Host-` names (stage 66, ADR 0616): when the browser holds
92
+ // one, it is the session, and an unprefixed one (which a sibling could plant on a parent
93
+ // domain) is never read or set back (stage 66 step 8, ADR 0619).
94
+ const session = pairs.find(([name]) => name === `__Host-${sessionName}`) ??
95
+ pairs.find(([name]) => unprefixed(name) === sessionName);
89
96
  if (!session)
90
97
  return [];
98
+ const [name, value] = session;
99
+ const hostOnly = name.startsWith("__Host-");
100
+ // The web app's own marker follows the session's rules: `__Host-` beside a `__Host-` session.
101
+ const marker = hostOnly ? `__Host-${SESSION_CHECKED_COOKIE}` : SESSION_CHECKED_COOKIE;
91
102
  const now = (options.now ?? new Date()).getTime();
92
- const checked = Number(pairs.find(([name]) => name === SESSION_CHECKED_COOKIE)?.[1]);
103
+ const checked = Number(pairs.find(([n]) => n === marker)?.[1]);
93
104
  if (checked > 0 && now - checked >= 0 && now - checked < SESSION_CHECK_INTERVAL_MS)
94
105
  return [];
95
- const [name, value] = session;
96
- const attributes = `; Path=/; HttpOnly; SameSite=Lax${name.startsWith("__Secure-") ? "; Secure" : ""}`;
106
+ // A `__Host-` cookie is refused by the browser unless it is Secure with `Path=/` and no Domain;
107
+ // a `__Secure-` one unless it is Secure. Neither ever names a Domain here.
108
+ const secure = hostOnly || name.startsWith("__Secure-");
109
+ const attributes = `; Path=/; HttpOnly; SameSite=Lax${secure ? "; Secure" : ""}`;
97
110
  let response;
98
111
  try {
99
112
  response = await options.fetch(`${options.baseUrl.replace(/\/+$/, "")}${CUSTOMER_AUTH_PATH}/get-session`, { method: "GET", headers: { cookie: customerCookies(options.cookieHeader) } });
@@ -114,14 +127,11 @@ export async function keepCustomerSignedIn(options) {
114
127
  catch { }
115
128
  }
116
129
  if (!(expiresAt > now)) {
117
- return [
118
- `${name}=${attributes}; Max-Age=0`,
119
- `${SESSION_CHECKED_COOKIE}=${attributes}; Max-Age=0`,
120
- ];
130
+ return [`${name}=${attributes}; Max-Age=0`, `${marker}=${attributes}; Max-Age=0`];
121
131
  }
122
132
  const maxAge = Math.floor((expiresAt - now) / 1000);
123
133
  return [
124
134
  `${name}=${value}${attributes}; Max-Age=${maxAge}`,
125
- `${SESSION_CHECKED_COOKIE}=${now}${attributes}; Max-Age=${maxAge}`,
135
+ `${marker}=${now}${attributes}; Max-Age=${maxAge}`,
126
136
  ];
127
137
  }
package/dist/session.d.ts CHANGED
@@ -23,6 +23,12 @@ export interface TokenSessionOptions {
23
23
  fetch?: FetchLike;
24
24
  /** Refresh this long before the access token runs out. Default 30 seconds. */
25
25
  refreshEarlyMs?: number;
26
+ /**
27
+ * Give up on a refresh that has not answered after this long, so a request left hanging (an
28
+ * app backgrounded mid-refresh, a network that changed) never holds up every call. Not a
29
+ * refusal: the session is kept and the next call tries again. Default 15 seconds.
30
+ */
31
+ refreshTimeoutMs?: number;
26
32
  now?: () => number;
27
33
  }
28
34
  /** Which part of a sign-in by code failed: asking for the code, or signing in with it. */
@@ -66,8 +72,21 @@ export declare function tokenSession(options: TokenSessionOptions): {
66
72
  redirectUri: string;
67
73
  deviceName: string;
68
74
  }): Promise<Tokens>;
69
- /** The headers for a call: a current access token, refreshed first when it is about to end. */
75
+ /**
76
+ * The headers for a call: a current access token, refreshed first when it is about to end by
77
+ * this device's clock. Prefer `fetch`, which also refreshes when the host says it has ended.
78
+ */
70
79
  headers(): Promise<Record<string, string>>;
80
+ /**
81
+ * A fetch that carries the session (pass it as the typed client's `fetch`): each call with a
82
+ * current access token, sent at most twice:
83
+ * - refused (401) with a token the session has since replaced (a refresh landed while the
84
+ * call was on its way: the host then says `token_invalid`), sent again with the new one;
85
+ * - refused as expired (`token_expired`: this device's clock behind the host's), one refresh,
86
+ * shared by every call refused at once, and sent again.
87
+ * Any other answer is passed back as it came, a 401 it has read as a `Response` again.
88
+ */
89
+ fetch: FetchLike;
71
90
  /**
72
91
  * Ends this device's session on the host (ADR 0455) with its refresh token, which any account
73
92
  * may do whatever it may call, then forgets the tokens, even when the host could not be
package/dist/session.js CHANGED
@@ -7,11 +7,49 @@
7
7
  // const session = tokenSession({ baseUrl, store: secureStore });
8
8
  // await session.requestCode(email);
9
9
  // await session.signInWithCode(email, code, "Ada's phone");
10
- // const api = createCustomerClient({ baseUrl, headers: session.headers });
10
+ // const api = createCustomerClient({ baseUrl, fetch: session.fetch });
11
+ //
12
+ // `session.fetch` adds the access token to each call and, when the host says it has expired
13
+ // (this device's clock behind the host's), refreshes once and sends the call again. A refresh
14
+ // the host refuses forgets the session; one that fails for any other reason keeps it.
11
15
  //
12
16
  // Staff whose sign-in is browser-based (Google, Cloudflare Access) use `startBrowserSignIn` and
13
17
  // `finishBrowserSignIn` instead: the system browser signs them in, never a web view.
14
18
  import { ApiError, NetworkError } from "./errors.js";
19
+ /**
20
+ * A fetch that gives up after `ms`: the request is aborted where the platform can (an
21
+ * `AbortController`, which browsers, Workers, Node and React Native have), and the wait ends
22
+ * either way, whether or not the platform honours the signal.
23
+ */
24
+ function withTimeout(fetcher, ms) {
25
+ return (url, init) => {
26
+ const Controller = globalThis.AbortController;
27
+ const controller = Controller ? new Controller() : null;
28
+ let timer;
29
+ const timedOut = new Promise((_, reject) => {
30
+ timer = globalThis.setTimeout(() => {
31
+ controller?.abort();
32
+ reject(new Error(`No answer from the host within ${ms} ms`));
33
+ }, ms);
34
+ });
35
+ // Read by the caller or not, a timeout is never an unhandled rejection.
36
+ timedOut.catch(() => { });
37
+ const stop = () => globalThis.clearTimeout(timer);
38
+ const sent = fetcher(url, {
39
+ ...init,
40
+ ...(controller ? { signal: controller.signal } : {}),
41
+ });
42
+ // The same limit covers the answer's body, read after its headers (review of #554, F1).
43
+ return Promise.race([sent, timedOut]).then((response) => ({
44
+ status: response.status,
45
+ headers: response.headers,
46
+ text: () => Promise.race([response.text(), timedOut]).finally(stop),
47
+ }), (error) => {
48
+ stop();
49
+ throw error;
50
+ });
51
+ };
52
+ }
15
53
  async function post(fetcher, url, body, headers = {}) {
16
54
  let response;
17
55
  try {
@@ -26,9 +64,17 @@ async function post(fetcher, url, body, headers = {}) {
26
64
  }
27
65
  // Something in front of the host (a proxy, a gateway) can answer with a page, not JSON: the
28
66
  // status still says what happened.
67
+ let text;
68
+ try {
69
+ text = await response.text();
70
+ }
71
+ catch (error) {
72
+ // The answer started and never finished (or took too long): no answer, not a refusal.
73
+ throw new NetworkError("The host's answer did not arrive", error);
74
+ }
29
75
  let parsed = {};
30
76
  try {
31
- parsed = JSON.parse(await response.text());
77
+ parsed = JSON.parse(text);
32
78
  }
33
79
  catch { }
34
80
  if (response.status === 200 && parsed.data)
@@ -68,28 +114,133 @@ export function signInErrorWords(error, step = "code") {
68
114
  ? "We could not send a code just now. Try again in a moment."
69
115
  : "We could not sign you in just now. Try again in a moment.";
70
116
  }
117
+ /**
118
+ * Whether a refresh's failure means the session is over: the host refused the token (401, 403, or
119
+ * 400 for one that is not a token). A 5xx, a 429 or no answer at all does not.
120
+ */
121
+ function sessionRefused(error) {
122
+ return error instanceof ApiError && [400, 401, 403].includes(error.status);
123
+ }
124
+ /**
125
+ * An answer whose body has been read, to pass on: a `Response` again where the platform has one
126
+ * (a page's code may read `.ok` or `.json()`), else the little the client reads.
127
+ */
128
+ function replayed(answer, text) {
129
+ const platform = globalThis;
130
+ if (platform.Response) {
131
+ // The platform's own headers as they came; else the one a reader of the body needs.
132
+ const headers = platform.Headers && answer.headers instanceof platform.Headers
133
+ ? answer.headers
134
+ : { "content-type": answer.headers.get("content-type") ?? "application/json" };
135
+ return new platform.Response(text, { status: answer.status, headers });
136
+ }
137
+ return { status: answer.status, headers: answer.headers, text: async () => text };
138
+ }
139
+ /** The `details.reason` of a refusal's envelope, or null. */
140
+ function refusalReason(text) {
141
+ try {
142
+ const reason = JSON.parse(text).error
143
+ ?.details?.reason;
144
+ return typeof reason === "string" ? reason : null;
145
+ }
146
+ catch {
147
+ return null;
148
+ }
149
+ }
150
+ /**
151
+ * What every session over one store shares (review of #548, F-c): the refresh in flight, so two
152
+ * sessions over one store never present one refresh token twice (which ends the session), and
153
+ * which session the store holds, so a sign-out through one is one for a refresh another began.
154
+ * Keyed by the store object a device app holds; the host never makes one.
155
+ */
156
+ const byStore = new WeakMap();
157
+ function sharedOf(store) {
158
+ let shared = byStore.get(store);
159
+ if (!shared) {
160
+ shared = { refreshing: null, generation: 0 };
161
+ byStore.set(store, shared);
162
+ }
163
+ return shared;
164
+ }
71
165
  export function tokenSession(options) {
72
166
  const base = options.baseUrl.replace(/\/+$/, "");
73
167
  const fetcher = options.fetch ?? globalThis.fetch?.bind(globalThis);
74
168
  const early = options.refreshEarlyMs ?? 30_000;
75
169
  const now = options.now ?? (() => Date.now());
170
+ const refresher = withTimeout(fetcher, options.refreshTimeoutMs ?? 15_000);
76
171
  // One refresh at a time: two at once would present one refresh token twice and end the session.
77
- let refreshing = null;
172
+ // And which session the store holds: a sign-out or a sign-in moves it on, and a refresh begun
173
+ // before that keeps nothing it brings back (review of #542, F1). Both are the store's.
174
+ const shared = sharedOf(options.store);
175
+ /** Saves `tokens` as a new session (a sign-in) or none (a sign-out): any refresh is stale. */
176
+ async function replace(tokens) {
177
+ shared.generation += 1;
178
+ await options.store.save(tokens);
179
+ }
78
180
  async function refresh(tokens) {
181
+ const began = shared.generation;
79
182
  try {
80
- const next = await post(fetcher, `${base}/api/v1/auth/refresh`, {
183
+ const next = await post(refresher, `${base}/api/v1/auth/refresh`, {
81
184
  refreshToken: tokens.refreshToken,
82
185
  });
186
+ // Signed out, or signed in afresh, meanwhile: that is the session now, not this one.
187
+ if (shared.generation !== began)
188
+ return options.store.load();
83
189
  await options.store.save(next);
84
190
  return next;
85
191
  }
86
192
  catch (error) {
87
- // The session ended (signed out, unused too long, a reused token): forget it.
88
- if (error instanceof ApiError)
193
+ // The host refused the token (signed out, unused too long, reused, not a token): the session
194
+ // is over, so forget it. A 5xx, a 429, a proxy's page, no answer or none in time says
195
+ // nothing about the session: the tokens are kept for the next try.
196
+ if (sessionRefused(error) && shared.generation === began)
89
197
  await options.store.save(null);
90
198
  throw error;
91
199
  }
92
200
  }
201
+ /** One refresh at a time, shared by every call waiting on it. */
202
+ function refreshOnce(tokens) {
203
+ const running = shared.refreshing ??
204
+ refresh(tokens).finally(() => {
205
+ if (shared.refreshing === running)
206
+ shared.refreshing = null;
207
+ });
208
+ shared.refreshing = running;
209
+ return running;
210
+ }
211
+ /**
212
+ * The tokens to use after `used` was refused as expired (a clock behind the host's): those a
213
+ * refresh already in flight, or just finished, gives; else one refresh, shared.
214
+ */
215
+ async function renewedAfter(used) {
216
+ if (shared.refreshing)
217
+ return shared.refreshing;
218
+ const now = await options.store.load();
219
+ if (!now)
220
+ return null;
221
+ if (now.accessToken !== used.accessToken)
222
+ return now;
223
+ return refreshOnce(now);
224
+ }
225
+ /**
226
+ * The tokens for a call: a refresh in flight first (whatever this device's clock says: with a
227
+ * clock behind the host's, the old access token stops working the moment the refresh lands, and
228
+ * a call sent with it then is refused), else the stored ones, refreshed first when the access
229
+ * token is about to end.
230
+ */
231
+ async function current() {
232
+ // A refresh the host refused has forgotten the session (none); one that failed otherwise has
233
+ // kept it, and a call with it is refused as expired and tries again.
234
+ if (shared.refreshing)
235
+ return shared.refreshing.catch(() => options.store.load());
236
+ const tokens = await options.store.load();
237
+ if (!tokens)
238
+ return null;
239
+ if (Date.parse(tokens.accessExpiresAt) - early <= now())
240
+ return refreshOnce(tokens);
241
+ return tokens;
242
+ }
243
+ const bearer = (tokens) => tokens ? { authorization: `Bearer ${tokens.accessToken}` } : {};
93
244
  return {
94
245
  /**
95
246
  * Exchanges a sign-in for tokens. `credentials` are the headers that carry it, such as the
@@ -97,7 +248,7 @@ export function tokenSession(options) {
97
248
  */
98
249
  async exchange(deviceName, credentials) {
99
250
  const tokens = await post(fetcher, `${base}/api/v1/auth/token`, { deviceName }, credentials);
100
- await options.store.save(tokens);
251
+ await replace(tokens);
101
252
  return tokens;
102
253
  },
103
254
  /**
@@ -125,7 +276,7 @@ export function tokenSession(options) {
125
276
  ...(previous?.refreshToken ? { replaces: previous.refreshToken } : {}),
126
277
  });
127
278
  const { account: _account, ...tokens } = signedIn;
128
- await options.store.save(tokens);
279
+ await replace(tokens);
129
280
  return signedIn;
130
281
  },
131
282
  /**
@@ -153,24 +304,59 @@ export function tokenSession(options) {
153
304
  redirectUri: input.redirectUri,
154
305
  deviceName: input.deviceName,
155
306
  });
156
- await options.store.save(tokens);
307
+ await replace(tokens);
157
308
  return tokens;
158
309
  },
159
- /** The headers for a call: a current access token, refreshed first when it is about to end. */
310
+ /**
311
+ * The headers for a call: a current access token, refreshed first when it is about to end by
312
+ * this device's clock. Prefer `fetch`, which also refreshes when the host says it has ended.
313
+ */
160
314
  async headers() {
161
- let tokens = await options.store.load();
162
- if (!tokens)
163
- return {};
164
- if (Date.parse(tokens.accessExpiresAt) - early <= now()) {
165
- refreshing ??= refresh(tokens).finally(() => {
166
- refreshing = null;
167
- });
168
- tokens = await refreshing;
169
- if (!tokens)
170
- return {};
171
- }
172
- return { authorization: `Bearer ${tokens.accessToken}` };
315
+ return bearer(await current());
173
316
  },
317
+ /**
318
+ * A fetch that carries the session (pass it as the typed client's `fetch`): each call with a
319
+ * current access token, sent at most twice:
320
+ * - refused (401) with a token the session has since replaced (a refresh landed while the
321
+ * call was on its way: the host then says `token_invalid`), sent again with the new one;
322
+ * - refused as expired (`token_expired`: this device's clock behind the host's), one refresh,
323
+ * shared by every call refused at once, and sent again.
324
+ * Any other answer is passed back as it came, a 401 it has read as a `Response` again.
325
+ */
326
+ fetch: (async (url, init) => {
327
+ const used = await current();
328
+ const send = (tokens) => fetcher(url, { ...init, headers: { ...init.headers, ...bearer(tokens) } });
329
+ const first = await send(used);
330
+ if (!used || first.status !== 401)
331
+ return first;
332
+ const text = await first.text();
333
+ const again = replayed(first, text);
334
+ // A refresh in flight, or one that landed while this call was out: the session's token now.
335
+ if (shared.refreshing)
336
+ await shared.refreshing.catch(() => null);
337
+ const stored = await options.store.load();
338
+ // The same session with a new token (a refresh keeps the session's id): sent again. Never
339
+ // another session's (a sign-out and a new sign-in meanwhile): the call is not theirs.
340
+ if (stored &&
341
+ stored.sessionId === used.sessionId &&
342
+ stored.accessToken !== used.accessToken) {
343
+ return send(stored);
344
+ }
345
+ if (refusalReason(text) !== "token_expired")
346
+ return again;
347
+ let next;
348
+ try {
349
+ next = await renewedAfter(used);
350
+ }
351
+ catch (error) {
352
+ // Refused: the session is over and forgotten; the call's own refusal says so.
353
+ if (!(await options.store.load()))
354
+ return again;
355
+ throw error;
356
+ }
357
+ // Only ever as the session the call was made in.
358
+ return next && next.sessionId === used.sessionId ? send(next) : again;
359
+ }),
174
360
  /**
175
361
  * Ends this device's session on the host (ADR 0455) with its refresh token, which any account
176
362
  * may do whatever it may call, then forgets the tokens, even when the host could not be
@@ -189,7 +375,7 @@ export function tokenSession(options) {
189
375
  // Forgotten here either way; the host ends an unused session after the idle setting.
190
376
  }
191
377
  finally {
192
- await options.store.save(null);
378
+ await replace(null);
193
379
  }
194
380
  },
195
381
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@composable-os/client",
3
- "version": "0.1.0-beta.14",
3
+ "version": "0.1.0-beta.16",
4
4
  "license": "FSL-1.1-ALv2",
5
5
  "type": "module",
6
6
  "repository": {