@composable-os/client 0.1.0-beta.10 → 0.1.0-beta.13

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,518 @@
1
+ // Agreements for a client app (stage 44 step 5): the headless entry the agreement blocks share,
2
+ // web and native. Functions and hooks over the typed client, no markup and no platform API: the
3
+ // web blocks draw with React DOM and pointer events, the native ones with React Native and its
4
+ // touch responder, and both use what is here.
5
+ //
6
+ // It holds no rules. What is due, for whom, who may agree, whether a purchase or a booking may go
7
+ // ahead and whether a signature or an answer is acceptable are the host's (ADR 0401, ADR 0644): a
8
+ // block asks (`me.agreements.due`, or the refusal a buying or booking call answers with) and shows
9
+ // the answer. The checks here (a box ticked, a name typed, every question answered, enough ink)
10
+ // only say what is missing before a call the host checks again in full.
11
+ //
12
+ // What a person types, draws and answers is personal data, and health answers are health
13
+ // information: nothing here logs, stores or sends them anywhere but the one call that agrees.
14
+ // They live in a block's memory until that call, and the block forgets them after it.
15
+ import { packHooks } from "./hooks.js";
16
+ export const MINOR_PAYER_WORDS = "A parent or guardian needs to buy this for you.";
17
+ const CHANGED_WORDS = "What must be agreed to changed just now. Please read it again.";
18
+ function record(value) {
19
+ return value !== null && typeof value === "object" ? value : null;
20
+ }
21
+ /** The host's details of an error: its own, or a pack tool's that carries the host's inside. */
22
+ function hostDetails(error) {
23
+ const details = record(record(error)?.details);
24
+ if (!details)
25
+ return null;
26
+ if (typeof details.rule === "string")
27
+ return details;
28
+ // A pack tool's refusal (`extension_error`) carries the host's code and details inside.
29
+ const inner = record(details.details);
30
+ return inner && typeof inner.rule === "string" ? inner : null;
31
+ }
32
+ function refusedDocuments(value) {
33
+ if (!Array.isArray(value))
34
+ return [];
35
+ return value.flatMap((item) => {
36
+ const d = record(item);
37
+ if (!d || typeof d.documentId !== "string" || typeof d.versionId !== "string")
38
+ return [];
39
+ return [
40
+ {
41
+ documentId: d.documentId,
42
+ title: typeof d.title === "string" ? d.title : "",
43
+ versionId: d.versionId,
44
+ personId: typeof d.personId === "string" ? d.personId : null,
45
+ },
46
+ ];
47
+ });
48
+ }
49
+ /**
50
+ * Reads an error from a call that buys, subscribes or books (order.start, subscription.start, a
51
+ * pack's buy or book tool): the host's agreements refusal, or null when it is not one.
52
+ */
53
+ export function agreementRefusal(error) {
54
+ const details = hostDetails(error);
55
+ if (!details)
56
+ return null;
57
+ if (details.rule === "agreements_changed")
58
+ return { kind: "changed", message: CHANGED_WORDS };
59
+ if (details.rule === "agreement_not_asked" || details.rule === "agreement_version_replaced") {
60
+ return { kind: "read_again", message: CHANGED_WORDS };
61
+ }
62
+ if (details.rule !== "agreements_due")
63
+ return null;
64
+ const documents = refusedDocuments(details.documents);
65
+ if (details.reason === "minor_payer") {
66
+ return { kind: "minor_payer", message: MINOR_PAYER_WORDS, documents };
67
+ }
68
+ return { kind: "due", message: "Something must be agreed to first.", documents };
69
+ }
70
+ /** Said where a screen that buys has no agreement step (a client app's own screen). */
71
+ export const NO_AGREEMENT_STEP_WORDS = "This needs an agreement that can't be given here yet. Ask the business how to agree to it first.";
72
+ /**
73
+ * For a screen that buys but cannot show the agreement step: the words for the host's refusal of
74
+ * what must be agreed to first (or for a minor, a parent or guardian buys it), or null when the
75
+ * error is something else.
76
+ */
77
+ export function agreementBlockedWords(error) {
78
+ const refusal = agreementRefusal(error);
79
+ if (!refusal)
80
+ return null;
81
+ if (refusal.kind === "minor_payer")
82
+ return refusal.message;
83
+ if (refusal.kind === "due")
84
+ return NO_AGREEMENT_STEP_WORDS;
85
+ return refusal.message;
86
+ }
87
+ /**
88
+ * Makes a mutation's call and then forgets it: the mutation's state (its variables: a name typed,
89
+ * a signature, health answers) is reset whether the call succeeded or failed, so the app's cache
90
+ * holds none of it once the call is over. What the person entered stays only in the screen's own
91
+ * state, for as long as the screen needs it.
92
+ */
93
+ export async function forgetAfter(mutation, input) {
94
+ try {
95
+ return await mutation.mutateAsync(input);
96
+ }
97
+ finally {
98
+ mutation.reset?.();
99
+ }
100
+ }
101
+ /**
102
+ * What to tell a person whose purchase or booking did not go through, as far as agreements and the
103
+ * connection go: null for anything else (the screen says its own words).
104
+ */
105
+ export function purchaseErrorWords(error) {
106
+ const refusal = agreementRefusal(error);
107
+ if (refusal?.kind === "changed" || refusal?.kind === "read_again") {
108
+ return "What must be agreed to changed just now. Please start again and read it once more.";
109
+ }
110
+ if (refusal?.kind === "minor_payer")
111
+ return refusal.message;
112
+ if (record(error)?.name === "NetworkError") {
113
+ return "We could not reach the business just now. Check your connection and try again: what you entered is still here.";
114
+ }
115
+ return null;
116
+ }
117
+ /**
118
+ * Makes a buying or booking call and reads the host's answer for agreements. When what is due
119
+ * changed while it was made (`changed`), or a visitor's agreements were for an older version
120
+ * (`read_again`), it calls once more, told why (a visitor drops what is stale on `read_again`);
121
+ * a second such refusal is thrown. Any other error is thrown as it is.
122
+ */
123
+ export async function withAgreements(call) {
124
+ let previous = null;
125
+ for (let attempt = 0;; attempt += 1) {
126
+ try {
127
+ return { kind: "done", value: await call(previous) };
128
+ }
129
+ catch (error) {
130
+ const refusal = agreementRefusal(error);
131
+ if (!refusal)
132
+ throw error;
133
+ if (refusal.kind === "due")
134
+ return { kind: "due", documents: refusal.documents };
135
+ if (refusal.kind === "minor_payer") {
136
+ return { kind: "minor_payer", message: refusal.message, documents: refusal.documents };
137
+ }
138
+ if (attempt > 0)
139
+ throw error;
140
+ previous = refusal;
141
+ }
142
+ }
143
+ }
144
+ /**
145
+ * The documents a refusal named, matched to what `me.agreements.due` says for each person: what a
146
+ * signed-in member (or a guardian, for a child) reads and agrees to inline. A document no longer
147
+ * due is left out; a person who cannot agree themselves comes back with `canAgree: false`.
148
+ */
149
+ export function dueForRefusal(people, documents) {
150
+ const out = [];
151
+ const self = people.find((p) => p.self);
152
+ for (const doc of documents) {
153
+ const person = doc.personId ? people.find((p) => p.personId === doc.personId) : self;
154
+ const item = person?.due.find((d) => d.documentId === doc.documentId);
155
+ if (person &&
156
+ item &&
157
+ !out.some((o) => o.item.documentId === item.documentId && o.person === person)) {
158
+ out.push({ person, item });
159
+ }
160
+ }
161
+ return out;
162
+ }
163
+ /** "Before you go on": each due document in turn, the caller's first, then each child's. */
164
+ export function dueSteps(people) {
165
+ const ordered = [...people].sort((a, b) => Number(b.self) - Number(a.self));
166
+ return ordered.flatMap((person) => person.due.map((item) => ({ person, item })));
167
+ }
168
+ // --- Words (display only) ----------------------------------------------------------------------------
169
+ /** Why a document is asked of a person, in words, or null for a first time. */
170
+ export function dueReasonWords(reason) {
171
+ switch (reason) {
172
+ case "agree_again":
173
+ return "This has changed since you agreed: please read it and agree again.";
174
+ case "ask_again":
175
+ return "It is time to answer these again.";
176
+ case "guardian":
177
+ return "A parent or guardian agrees to this for you.";
178
+ default:
179
+ return null;
180
+ }
181
+ }
182
+ /** How an acceptance was made, for the person or a guardian reading it ("Agreed by you"). */
183
+ export function agreedByWords(acceptance, me) {
184
+ if (acceptance.by === "paper") {
185
+ return acceptance.signedOn
186
+ ? `Recorded from a paper form signed on ${acceptance.signedOn}`
187
+ : "Recorded from a paper form";
188
+ }
189
+ if (acceptance.channel === "desk")
190
+ return "Agreed in person on the business's device";
191
+ if (acceptance.by === "guardian") {
192
+ return acceptance.agentPersonId && acceptance.agentPersonId === me
193
+ ? "Agreed by you, as their parent or guardian"
194
+ : "Agreed by a parent or guardian";
195
+ }
196
+ if (acceptance.by === "guest")
197
+ return "Agreed when buying without an account";
198
+ return acceptance.personId === me ? "Agreed by you" : "Agreed by them";
199
+ }
200
+ /** "A copy is on its way to …", or a plain confirmation when no copy is sent. */
201
+ export function copyWords(accepted) {
202
+ return accepted.copyTo
203
+ ? `Thank you. A copy is on its way to ${accepted.copyTo}.`
204
+ : "Thank you: that is recorded.";
205
+ }
206
+ /**
207
+ * What to tell a person whose agreeing did not go through: in plain words, never a value they
208
+ * gave (the host's messages name a rule only).
209
+ */
210
+ export function agreeErrorWords(error) {
211
+ const refusal = agreementRefusal(error);
212
+ if (refusal?.kind === "changed" || refusal?.kind === "read_again") {
213
+ return "This changed while you were reading it. Please read it again.";
214
+ }
215
+ const e = record(error);
216
+ const details = hostDetails(error);
217
+ if (details?.rule === "agreement_minor")
218
+ return "A parent or guardian agrees to this for you.";
219
+ if (e?.name === "NetworkError") {
220
+ return "We could not reach the business just now. Check your connection and try again: what you entered is still here.";
221
+ }
222
+ if (e?.code === "invalid_input" && typeof e.message === "string")
223
+ return e.message;
224
+ return "That did not go through. Please try again.";
225
+ }
226
+ /** A moment in the person's own zone, for display ("24 Nov 2026, 09:30"). */
227
+ export function agreementTime(iso, locale = "en-AU") {
228
+ return new Intl.DateTimeFormat(locale, {
229
+ day: "numeric",
230
+ month: "short",
231
+ year: "numeric",
232
+ hour: "2-digit",
233
+ minute: "2-digit",
234
+ hourCycle: "h23",
235
+ }).format(new Date(iso));
236
+ }
237
+ /** Where a person's own signed PDF downloads from on the app's site (the host's route, ADR 0645). */
238
+ export function agreementPdfPath(acceptanceId) {
239
+ return `/api/v1/agreements/acceptances/${encodeURIComponent(acceptanceId)}.pdf`;
240
+ }
241
+ /**
242
+ * The blocks of a version's body a screen draws. A body holds no picture, embed or button (the
243
+ * host refuses them at publish); anything not known here is left out rather than guessed at.
244
+ */
245
+ export function documentBlocks(body) {
246
+ const blocks = record(body)?.blocks;
247
+ if (!Array.isArray(blocks))
248
+ return [];
249
+ return blocks.flatMap((b) => {
250
+ const block = record(b);
251
+ switch (block?.type) {
252
+ case "paragraph":
253
+ case "heading":
254
+ case "quote":
255
+ case "callout":
256
+ case "list":
257
+ case "divider":
258
+ return [block];
259
+ default:
260
+ return [];
261
+ }
262
+ });
263
+ }
264
+ /** A run's text: a link shows its address in full (the host allows only a link whose text it is). */
265
+ export function runText(run) {
266
+ return run.type === "break" ? "\n" : (run.text ?? "");
267
+ }
268
+ export function emptyAgreeForm(version) {
269
+ const answers = {};
270
+ for (const q of version.questions ?? [])
271
+ answers[q.key] = { yes: null, note: "" };
272
+ return { ticked: false, typedName: "", answers };
273
+ }
274
+ /** The longest name and note the host takes (it checks again). */
275
+ export const TYPED_NAME_MAX = 200;
276
+ export const NOTE_MAX = 1_000;
277
+ /** What is missing before agreeing, field by field, in the order the screen shows them. */
278
+ export function agreeProblems(version, form, signature) {
279
+ const problems = [];
280
+ for (const q of version.questions ?? []) {
281
+ const answer = form.answers[q.key];
282
+ if (!answer || answer.yes === null) {
283
+ problems.push({ field: `answer:${q.key}`, message: "Answer yes or no" });
284
+ }
285
+ else if (answer.yes && answer.note.trim().length > NOTE_MAX) {
286
+ problems.push({ field: `note:${q.key}`, message: "A note is at most 1,000 characters" });
287
+ }
288
+ }
289
+ if (!form.ticked)
290
+ problems.push({ field: "ticked", message: "Tick the box to agree" });
291
+ const name = form.typedName.trim();
292
+ if (!name)
293
+ problems.push({ field: "typedName", message: "Type your name" });
294
+ else if (name.length > TYPED_NAME_MAX) {
295
+ problems.push({ field: "typedName", message: "A name is at most 200 characters" });
296
+ }
297
+ if (version.how === "drawn" && !signatureEnough(signature)) {
298
+ problems.push({ field: "signature", message: "Draw your signature in the box" });
299
+ }
300
+ return problems;
301
+ }
302
+ /** The call's input: the version the screen showed, and only what this version asks for. */
303
+ export function agreeInput(version, form, signature) {
304
+ const input = { versionId: version.id, typedName: form.typedName.trim() };
305
+ if (version.how === "drawn" && signature)
306
+ input.signature = signature;
307
+ if (version.questions?.length) {
308
+ input.answers = version.questions.map((q) => {
309
+ const answer = form.answers[q.key];
310
+ const yes = answer?.yes === true;
311
+ const note = yes && q.noteOnYes ? (answer?.note.trim() ?? "") : "";
312
+ return note ? { key: q.key, yes, note } : { key: q.key, yes };
313
+ });
314
+ }
315
+ return input;
316
+ }
317
+ // --- A drawn signature -----------------------------------------------------------------------------
318
+ /** The box a signature is drawn in, and the most it may hold (the host's limits, ADR 0642). */
319
+ export const SIGNATURE_BOX = { width: 1000, height: 400 };
320
+ export const SIGNATURE_LIMITS = {
321
+ strokes: 30,
322
+ points: 5_000,
323
+ bytes: 32_768,
324
+ /** The least ink, in box units, the host takes as a signature (not a dot or a tap). */
325
+ minLength: 120,
326
+ };
327
+ /** Points closer than this to the last one (box units) add nothing a screen can show. */
328
+ const MIN_STEP = 2;
329
+ /** Room kept under the host's byte limit. */
330
+ const BYTES_BUDGET = SIGNATURE_LIMITS.bytes - 256;
331
+ /** `{"width":1000,"height":400,"strokes":[` and `]}`. */
332
+ const BASE_BYTES = 39;
333
+ /** The length of the lines a signature draws (a dot draws none). */
334
+ export function inkLength(strokes) {
335
+ let total = 0;
336
+ for (const stroke of strokes) {
337
+ for (let i = 1; i < stroke.length; i++) {
338
+ const [x0, y0] = stroke[i - 1];
339
+ const [x1, y1] = stroke[i];
340
+ total += Math.hypot(x1 - x0, y1 - y0);
341
+ }
342
+ }
343
+ return total;
344
+ }
345
+ /** Whether a signature has the ink the host takes as one (it checks again). */
346
+ export function signatureEnough(signature) {
347
+ return !!signature && inkLength(signature.strokes) >= SIGNATURE_LIMITS.minLength;
348
+ }
349
+ /**
350
+ * A point on the drawing area, in the signature's box: `x` and `y` are the pointer's position
351
+ * relative to the area's top-left corner, `width` and `height` the area's size on screen.
352
+ * Integer, and kept inside the box.
353
+ */
354
+ export function boxPoint(x, y, width, height) {
355
+ const scale = (v, size, max) => {
356
+ if (!Number.isFinite(v) || !Number.isFinite(size) || size <= 0)
357
+ return 0;
358
+ return Math.min(max, Math.max(0, Math.round((v / size) * max)));
359
+ };
360
+ return [scale(x, width, SIGNATURE_BOX.width), scale(y, height, SIGNATURE_BOX.height)];
361
+ }
362
+ const pointBytes = ([x, y]) => 3 + String(x).length + String(y).length;
363
+ /**
364
+ * Records a drawn signature as the host takes it: strokes of integer points in the box, within
365
+ * its limits on strokes, points and size. Drawing past a limit stops adding (`full`), so what is
366
+ * sent is never refused for its size. The web pad feeds it pointer events, the native one its
367
+ * touch responder's.
368
+ */
369
+ export class StrokeRecorder {
370
+ lines = [];
371
+ points = 0;
372
+ bytes = BASE_BYTES;
373
+ drawing = false;
374
+ /** The pointer drawing the stroke now (a finger, a pen): others are ignored until it lifts. */
375
+ active = null;
376
+ /** Drawing went past a limit: nothing more is added until it is cleared. */
377
+ full = false;
378
+ /**
379
+ * A new stroke at `point` (a pen, a finger or the mouse button down). `pointer` names the
380
+ * pointer: while one is drawing, another (a second finger, a palm) starts nothing. False when
381
+ * nothing was started.
382
+ */
383
+ begin(point, pointer) {
384
+ if (this.drawing && this.active !== null && pointer !== this.active)
385
+ return false;
386
+ if (this.full)
387
+ return false;
388
+ const cost = 2 + (this.lines.length ? 1 : 0) + pointBytes(point);
389
+ if (this.lines.length >= SIGNATURE_LIMITS.strokes ||
390
+ this.points + 1 > SIGNATURE_LIMITS.points ||
391
+ this.bytes + cost > BYTES_BUDGET) {
392
+ this.full = true;
393
+ return false;
394
+ }
395
+ this.lines.push([[point[0], point[1]]]);
396
+ this.points += 1;
397
+ this.bytes += cost;
398
+ this.drawing = true;
399
+ this.active = pointer ?? null;
400
+ return true;
401
+ }
402
+ /** The stroke goes on to `point`. False when nothing was added (another pointer's move too). */
403
+ extend(point, pointer) {
404
+ if (!this.drawing || this.full)
405
+ return false;
406
+ if (this.active !== null && pointer !== this.active)
407
+ return false;
408
+ const stroke = this.lines[this.lines.length - 1];
409
+ const last = stroke?.[stroke.length - 1];
410
+ if (!stroke || !last)
411
+ return false;
412
+ if (Math.hypot(point[0] - last[0], point[1] - last[1]) < MIN_STEP)
413
+ return false;
414
+ const cost = 1 + pointBytes(point);
415
+ if (this.points + 1 > SIGNATURE_LIMITS.points || this.bytes + cost > BYTES_BUDGET) {
416
+ this.full = true;
417
+ this.drawing = false;
418
+ return false;
419
+ }
420
+ stroke.push([point[0], point[1]]);
421
+ this.points += 1;
422
+ this.bytes += cost;
423
+ return true;
424
+ }
425
+ /** The pen, finger or button is lifted (another pointer lifting ends nothing). */
426
+ end(pointer) {
427
+ if (this.active !== null && pointer !== undefined && pointer !== this.active)
428
+ return;
429
+ this.drawing = false;
430
+ this.active = null;
431
+ }
432
+ /** Starts again, with nothing drawn. */
433
+ clear() {
434
+ this.lines = [];
435
+ this.points = 0;
436
+ this.bytes = BASE_BYTES;
437
+ this.drawing = false;
438
+ this.active = null;
439
+ this.full = false;
440
+ }
441
+ /** The strokes so far (for drawing them on screen). */
442
+ get strokes() {
443
+ return this.lines;
444
+ }
445
+ /** The signature to send, or null when nothing is drawn. */
446
+ signature() {
447
+ if (!this.lines.length)
448
+ return null;
449
+ return {
450
+ width: SIGNATURE_BOX.width,
451
+ height: SIGNATURE_BOX.height,
452
+ strokes: this.lines.map((s) => s.map(([x, y]) => [x, y])),
453
+ };
454
+ }
455
+ }
456
+ /** An SVG path for one stroke, in the box's units ("M x y L x y …"; a dot is a short line). */
457
+ export function strokePath(stroke) {
458
+ const [first, ...rest] = stroke;
459
+ if (!first)
460
+ return "";
461
+ if (!rest.length)
462
+ return `M ${first[0]} ${first[1]} l 0.5 0`;
463
+ return `M ${first[0]} ${first[1]} ${rest.map(([x, y]) => `L ${x} ${y}`).join(" ")}`;
464
+ }
465
+ /** The operations each hook calls (ADR 0453). */
466
+ export const AGREEMENTS_HOOKS_CALL = {
467
+ useDue: ["me.agreements.due"],
468
+ useMine: ["me.agreements.list"],
469
+ useAcceptance: ["me.agreements.get"],
470
+ useAccept: ["me.agreements.accept"],
471
+ useGuestVersions: ["agreement.guestVersions"],
472
+ };
473
+ /**
474
+ * Hooks for a React or React Native app:
475
+ * `const agreements = createAgreementsHooks({ useQuery, useMutation }, api)`, with the customer's
476
+ * generated client. The hooks it cannot back are not there.
477
+ */
478
+ export function createAgreementsHooks(react, client) {
479
+ return packHooks(client, AGREEMENTS_HOOKS_CALL, (api) => allAgreementsHooks(react, api));
480
+ }
481
+ function allAgreementsHooks(react, api) {
482
+ const { useQuery, useMutation } = react;
483
+ return {
484
+ /** What the signed-in customer, and each child linked to them, still has to agree to. */
485
+ useDue() {
486
+ return useQuery(api.query("me.agreements.due", {}));
487
+ },
488
+ /** Their agreements and their children's, newest first. */
489
+ useMine() {
490
+ return useQuery(api.query("me.agreements.list", {}));
491
+ },
492
+ /**
493
+ * One acceptance, with what it holds (a name typed, a signature, health answers): kept in
494
+ * the app's cache no longer than it is on screen.
495
+ */
496
+ useAcceptance(id) {
497
+ return useQuery({
498
+ ...api.query("me.agreements.get", { id: id ?? "" }),
499
+ enabled: !!id,
500
+ gcTime: 0,
501
+ });
502
+ },
503
+ /**
504
+ * Agree to a version, for themselves or a child (`forPersonId`). What was sent is not kept
505
+ * once the call is over.
506
+ */
507
+ useAccept() {
508
+ return useMutation({ ...api.mutation("me.agreements.accept"), gcTime: 0 });
509
+ },
510
+ /** A visitor's: the words of the versions a buying call's refusal named. */
511
+ useGuestVersions(versionIds) {
512
+ return useQuery({
513
+ ...api.query("agreement.guestVersions", { versionIds: [...versionIds] }),
514
+ enabled: versionIds.length > 0,
515
+ });
516
+ },
517
+ };
518
+ }
package/dist/binding.d.ts CHANGED
@@ -7,6 +7,33 @@ export declare const CUSTOMER_AUTH_PATH = "/api/customer-auth";
7
7
  export declare function customerCookies(cookieHeader: string | null | undefined): string;
8
8
  /** Headers for a call made for the browser's customer: their session cookie, if any. */
9
9
  export declare function customerSession(cookieHeader: string | null | undefined): Record<string, string>;
10
+ /**
11
+ * The header a web app names its visitor's address in, on every call over the binding (ADR 0940).
12
+ * The host limits calls to public operations, and sign-in, per client address; over the binding
13
+ * every call comes from the web app, so the host takes the visitor's address from a forwarded
14
+ * `cf-connecting-ip`, else from this header, and only over the binding (on the public HTTP surface
15
+ * it is the connection's, and this header is ignored). A web app that sends none is counted as one
16
+ * shared bucket: its visitors share it. Never forward the browser's own request headers as they
17
+ * came with this header in them: a browser could then name any address.
18
+ */
19
+ export declare const VISITOR_ADDRESS_HEADER = "cos-visitor-address";
20
+ /**
21
+ * Headers naming the browser's address to the host: Cloudflare's `cf-connecting-ip` on the web
22
+ * app's own request (set by Cloudflare, not by the browser), or nothing when there is none (local
23
+ * development).
24
+ */
25
+ export declare function visitorAddress(requestHeaders: {
26
+ get(name: string): string | null;
27
+ } | null | undefined): Record<string, string>;
28
+ /**
29
+ * Everything a call made for the browser's visitor forwards over the binding: their customer
30
+ * session cookie, if any (`customerSession`), and their address (`visitorAddress`).
31
+ */
32
+ export declare function forVisitor(request: {
33
+ headers: {
34
+ get(name: string): string | null;
35
+ };
36
+ }): Record<string, string>;
10
37
  /** The web app's own marker: when it last checked the customer's session (not a credential). */
11
38
  export declare const SESSION_CHECKED_COOKIE = "cos-session-checked";
12
39
  /** At most this often, the session is checked and its cookie given a fresh lifetime. */
package/dist/binding.js CHANGED
@@ -8,14 +8,18 @@
8
8
  // const api = createCustomerClient({
9
9
  // baseUrl: "https://host", // any origin: a binding ignores it
10
10
  // fetch: (url, init) => env.HOST.fetch(url, init),
11
- // headers: () => customerSession(request.headers.get("cookie")),
11
+ // headers: () => forVisitor(request), // the session cookie and the visitor's address
12
12
  // });
13
13
  /** Customer session cookies are `cos-customer.*`, `__Secure-` prefixed on https (the host's). */
14
14
  export const CUSTOMER_COOKIE_PREFIX = "cos-customer";
15
15
  /** Customer sign-in, served by the host and reached over the binding: forward these paths. */
16
16
  export const CUSTOMER_AUTH_PATH = "/api/customer-auth";
17
+ /** A cookie's name (or name=value pair) without the browser's `__Secure-`/`__Host-` prefix. */
18
+ function unprefixed(cookie) {
19
+ return cookie.replace(/^__(Secure|Host)-/, "");
20
+ }
17
21
  function isCustomerCookie(pair) {
18
- return pair.replace(/^__(Secure|Host)-/, "").startsWith(`${CUSTOMER_COOKIE_PREFIX}.`);
22
+ return unprefixed(pair).startsWith(`${CUSTOMER_COOKIE_PREFIX}.`);
19
23
  }
20
24
  /** The customer cookies in a `Cookie` header, as one header value ("" when there are none). */
21
25
  export function customerCookies(cookieHeader) {
@@ -29,15 +33,47 @@ export function customerSession(cookieHeader) {
29
33
  const cookie = customerCookies(cookieHeader);
30
34
  return cookie ? { cookie } : {};
31
35
  }
36
+ /**
37
+ * The header a web app names its visitor's address in, on every call over the binding (ADR 0940).
38
+ * The host limits calls to public operations, and sign-in, per client address; over the binding
39
+ * every call comes from the web app, so the host takes the visitor's address from a forwarded
40
+ * `cf-connecting-ip`, else from this header, and only over the binding (on the public HTTP surface
41
+ * it is the connection's, and this header is ignored). A web app that sends none is counted as one
42
+ * shared bucket: its visitors share it. Never forward the browser's own request headers as they
43
+ * came with this header in them: a browser could then name any address.
44
+ */
45
+ export const VISITOR_ADDRESS_HEADER = "cos-visitor-address";
46
+ /**
47
+ * Headers naming the browser's address to the host: Cloudflare's `cf-connecting-ip` on the web
48
+ * app's own request (set by Cloudflare, not by the browser), or nothing when there is none (local
49
+ * development).
50
+ */
51
+ export function visitorAddress(requestHeaders) {
52
+ // Only Cloudflare's own header: a `cos-visitor-address` the browser sent is never read or passed
53
+ // on (a bound Worker that forwarded it would let a browser choose its own limit, ADR 0940).
54
+ const address = requestHeaders?.get("cf-connecting-ip")?.trim();
55
+ return address ? { [VISITOR_ADDRESS_HEADER]: address } : {};
56
+ }
57
+ /**
58
+ * Everything a call made for the browser's visitor forwards over the binding: their customer
59
+ * session cookie, if any (`customerSession`), and their address (`visitorAddress`).
60
+ */
61
+ export function forVisitor(request) {
62
+ return {
63
+ ...customerSession(request.headers.get("cookie")),
64
+ ...visitorAddress(request.headers),
65
+ };
66
+ }
32
67
  /** The web app's own marker: when it last checked the customer's session (not a credential). */
33
68
  export const SESSION_CHECKED_COOKIE = "cos-session-checked";
34
69
  /** At most this often, the session is checked and its cookie given a fresh lifetime. */
35
70
  export const SESSION_CHECK_INTERVAL_MS = 24 * 60 * 60 * 1000;
71
+ /** The header's `name=value` pairs; a pair with no `=` or no name is not a cookie. */
36
72
  function cookiePairs(header) {
37
- return (header ?? "")
38
- .split(/;\s*/)
39
- .map((pair) => [pair.slice(0, pair.indexOf("=")), pair.slice(pair.indexOf("=") + 1)])
40
- .filter(([name]) => Boolean(name));
73
+ return (header ?? "").split(/;\s*/).flatMap((pair) => {
74
+ const at = pair.indexOf("=");
75
+ return at > 0 ? [[pair.slice(0, at), pair.slice(at + 1)]] : [];
76
+ });
41
77
  }
42
78
  /**
43
79
  * Keeps a signed-in customer signed in on the web app's hostname (stage 24, ADR 0421). The host
@@ -49,7 +85,7 @@ function cookiePairs(header) {
49
85
  */
50
86
  export async function keepCustomerSignedIn(options) {
51
87
  const pairs = cookiePairs(options.cookieHeader);
52
- const session = pairs.find(([name]) => name.replace(/^__(Secure|Host)-/, "") === `${CUSTOMER_COOKIE_PREFIX}.session_token`);
88
+ const session = pairs.find(([name]) => unprefixed(name) === `${CUSTOMER_COOKIE_PREFIX}.session_token`);
53
89
  if (!session)
54
90
  return [];
55
91
  const now = (options.now ?? new Date()).getTime();
@@ -58,8 +94,15 @@ export async function keepCustomerSignedIn(options) {
58
94
  return [];
59
95
  const [name, value] = session;
60
96
  const attributes = `; Path=/; HttpOnly; SameSite=Lax${name.startsWith("__Secure-") ? "; Secure" : ""}`;
61
- const response = await options.fetch(`${options.baseUrl.replace(/\/+$/, "")}${CUSTOMER_AUTH_PATH}/get-session`, { method: "GET", headers: { cookie: customerCookies(options.cookieHeader) } });
62
- // The host could not answer: leave the cookie as it is, and try again on a later request.
97
+ let response;
98
+ try {
99
+ response = await options.fetch(`${options.baseUrl.replace(/\/+$/, "")}${CUSTOMER_AUTH_PATH}/get-session`, { method: "GET", headers: { cookie: customerCookies(options.cookieHeader) } });
100
+ }
101
+ catch {
102
+ return [];
103
+ }
104
+ // The host could not answer (or was not reached, above): leave the cookie as it is, and try
105
+ // again on a later request.
63
106
  if (response.status >= 500)
64
107
  return [];
65
108
  let expiresAt = Number.NaN;
package/dist/client.d.ts CHANGED
@@ -58,6 +58,7 @@ export declare function createClient<T extends OperationTypes>(specs: {
58
58
  };
59
59
  invalidates: (name: MutationName<T>) => (readonly [string])[];
60
60
  operations: { readonly [K in keyof T & string]: OperationSpec; };
61
+ baseUrl: string;
61
62
  };
62
63
  export type Client<T extends OperationTypes> = ReturnType<typeof createClient<T>>;
63
64
  /**