@asstio-dev/storefront 0.46.0 → 0.48.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +28 -2
- package/dist/account/browser.d.ts +65 -3
- package/dist/account/browser.js +79 -5
- package/dist/account/cookies.d.ts +10 -0
- package/dist/account/cookies.js +7 -0
- package/dist/account/index.d.ts +7 -1
- package/dist/account/index.js +9 -8
- package/dist/account/next.d.ts +123 -2
- package/dist/account/next.js +289 -4
- package/dist/analytics/events.d.ts +8 -2
- package/dist/analytics/events.js +7 -2
- package/dist/cart-codes.d.ts +38 -0
- package/dist/cart-codes.js +28 -0
- package/dist/consent/codec.d.ts +141 -0
- package/dist/consent/codec.js +239 -0
- package/dist/consent/coordinator.d.ts +107 -0
- package/dist/consent/coordinator.js +608 -0
- package/dist/consent/index.d.ts +8 -0
- package/dist/consent/index.js +8 -0
- package/dist/consent/notice.d.ts +10 -0
- package/dist/consent/notice.js +11 -0
- package/dist/consent/server.d.ts +36 -0
- package/dist/consent/server.js +45 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +2 -0
- package/dist/schema.d.ts +3706 -428
- package/dist/shopper/index.d.ts +54 -0
- package/dist/shopper/index.js +36 -0
- package/package.json +17 -3
- package/src/schema.d.ts +3706 -428
|
@@ -0,0 +1,608 @@
|
|
|
1
|
+
import { CONSENT_COOKIE_SECONDS, CONSENT_OFF_COOKIE_SECONDS, ConsentCookieTooLarge, consentCookieNames, fold, grantedFor, isFallback, parseConsent, parseRefusal, PENDING_TTL_MS, PURPOSES, PUT_TIMEOUT_MS, refusalBlocks, refusalMark, SEQ_LIMIT, serializeConsent, serializeRefusal, withEntry, withoutEntries, } from "./codec.js";
|
|
2
|
+
const LOCK_NAME = "sf-consent";
|
|
3
|
+
const RESEND_BACKOFF_MS = [1_000, 4_000, 16_000];
|
|
4
|
+
const TOKEN_GONE = new Set(["SHOPPER_TOKEN_UNKNOWN", "SHOPPER_TOKEN_ADOPTED"]);
|
|
5
|
+
const SEVERITY = ["storage_failed", "refused_meanwhile", "consent_unavailable", "not_saved", "saved"];
|
|
6
|
+
function documentJar(secure) {
|
|
7
|
+
return {
|
|
8
|
+
get(name) {
|
|
9
|
+
for (const part of document.cookie.split(";")) {
|
|
10
|
+
const i = part.indexOf("=");
|
|
11
|
+
if (i > 0 && part.slice(0, i).trim() === name)
|
|
12
|
+
return part.slice(i + 1).trim();
|
|
13
|
+
}
|
|
14
|
+
return undefined;
|
|
15
|
+
},
|
|
16
|
+
set(name, value, maxAge) {
|
|
17
|
+
document.cookie = `${name}=${value}; Max-Age=${maxAge}; Path=/; SameSite=Lax${secure ? "; Secure" : ""}`;
|
|
18
|
+
},
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
const hex = (bytes) => Array.from(bytes, (b) => b.toString(16).padStart(2, "0")).join("");
|
|
22
|
+
const acknowledged = (a, p) => a.applied[p] === true || a.current[p] === "withdrawn";
|
|
23
|
+
function overall(purposes) {
|
|
24
|
+
const present = new Set(Object.values(purposes));
|
|
25
|
+
return SEVERITY.find((s) => present.has(s)) ?? "saved";
|
|
26
|
+
}
|
|
27
|
+
function withoutPending(c, p) {
|
|
28
|
+
const s = c.purposes[p];
|
|
29
|
+
if (!s?.pending)
|
|
30
|
+
return c;
|
|
31
|
+
const { pending: _dropped, ...rest } = s;
|
|
32
|
+
return { ...c, purposes: { ...c.purposes, [p]: rest } };
|
|
33
|
+
}
|
|
34
|
+
class Coordinator {
|
|
35
|
+
owner;
|
|
36
|
+
site;
|
|
37
|
+
transport;
|
|
38
|
+
locks;
|
|
39
|
+
jar;
|
|
40
|
+
now;
|
|
41
|
+
random;
|
|
42
|
+
names;
|
|
43
|
+
/** This page's withdrawals by decision time: refused at once, cleared only by a later grant applied in this page. */
|
|
44
|
+
deny = new Map();
|
|
45
|
+
/** null = unknown (deny everything until `setAccount`). */
|
|
46
|
+
account;
|
|
47
|
+
/** Re-sends per entry in this page, by the entry's current identity (carried over when a re-send rewrites it). */
|
|
48
|
+
resends = new Map();
|
|
49
|
+
constructor(opts) {
|
|
50
|
+
const browser = typeof window !== "undefined";
|
|
51
|
+
if (!browser && !opts.cookies)
|
|
52
|
+
throw new Error("createConsentCoordinator is browser-only: no window and no cookies jar.");
|
|
53
|
+
this.site = opts.site;
|
|
54
|
+
this.owner = opts.owner;
|
|
55
|
+
this.transport = opts.transport;
|
|
56
|
+
this.names = consentCookieNames(browser ? window.location.origin : undefined);
|
|
57
|
+
this.jar = opts.cookies ?? documentJar(this.names.consent.startsWith("__Host-"));
|
|
58
|
+
this.locks = opts.locks !== undefined ? opts.locks : (globalThis.navigator?.locks ?? null);
|
|
59
|
+
this.now = opts.now ?? (() => Date.now());
|
|
60
|
+
this.random = opts.random ?? ((n) => crypto.getRandomValues(new Uint8Array(n)));
|
|
61
|
+
this.account = opts.owner.startsWith("a.") ? null : { record: null, signedIn: false };
|
|
62
|
+
}
|
|
63
|
+
// ---- reading -------------------------------------------------------------------------------------------------------------
|
|
64
|
+
effective() {
|
|
65
|
+
const cookie = parseConsent(this.jar.get(this.names.consent));
|
|
66
|
+
const off = parseRefusal(this.jar.get(this.names.off));
|
|
67
|
+
const result = {};
|
|
68
|
+
for (const p of PURPOSES) {
|
|
69
|
+
const device = grantedFor(cookie, off, p) && !this.deny.has(p);
|
|
70
|
+
const account = this.account !== null && (!this.account.signedIn || this.account.record?.[p] === "granted");
|
|
71
|
+
result[p] = device && account;
|
|
72
|
+
}
|
|
73
|
+
return result;
|
|
74
|
+
}
|
|
75
|
+
unsynced() {
|
|
76
|
+
const c = parseConsent(this.jar.get(this.names.consent));
|
|
77
|
+
if (!c)
|
|
78
|
+
return { entries: [], overflow: 0 };
|
|
79
|
+
return { entries: c.unsynced.filter((e) => e.site === this.site).map((e) => ({ ...e })), overflow: c.overflow };
|
|
80
|
+
}
|
|
81
|
+
setOwner(owner) {
|
|
82
|
+
if (owner === null)
|
|
83
|
+
return;
|
|
84
|
+
this.owner = owner;
|
|
85
|
+
}
|
|
86
|
+
setAccount(record, signedIn) {
|
|
87
|
+
this.account = { record: record ? { ...record } : null, signedIn };
|
|
88
|
+
}
|
|
89
|
+
invalidate() {
|
|
90
|
+
this.account = null;
|
|
91
|
+
}
|
|
92
|
+
// ---- decisions -----------------------------------------------------------------------------------------------------------
|
|
93
|
+
async set(purposes, notice) {
|
|
94
|
+
// Decision identity, synchronously at invocation and before any await.
|
|
95
|
+
const decision = {
|
|
96
|
+
decidedAt: this.now(), owner: this.owner, ref: notice?.ref ?? null, off: refusalMark(this.readOff()),
|
|
97
|
+
grants: PURPOSES.filter((p) => purposes[p] === "granted"),
|
|
98
|
+
withdrawals: PURPOSES.filter((p) => purposes[p] === "withdrawn"),
|
|
99
|
+
};
|
|
100
|
+
for (const p of decision.withdrawals)
|
|
101
|
+
this.deny.set(p, decision.decidedAt);
|
|
102
|
+
const early = {};
|
|
103
|
+
if (decision.ref === null) {
|
|
104
|
+
// The API requires `notice.ref` for any grant: fail locally instead of sending a request it must refuse.
|
|
105
|
+
for (const p of decision.grants)
|
|
106
|
+
early[p] = "not_saved";
|
|
107
|
+
decision.grants = [];
|
|
108
|
+
}
|
|
109
|
+
if (decision.grants.length + decision.withdrawals.length === 0)
|
|
110
|
+
return { status: overall(early), purposes: early };
|
|
111
|
+
const allocation = await this.locked(() => this.allocate(decision));
|
|
112
|
+
if (!allocation.ok) {
|
|
113
|
+
const r = await this.lockless(decision);
|
|
114
|
+
const purposes = { ...early, ...r.purposes };
|
|
115
|
+
return { status: overall(purposes), purposes };
|
|
116
|
+
}
|
|
117
|
+
const { sent, capacity } = allocation.value;
|
|
118
|
+
const statuses = { ...early, ...allocation.value.statuses };
|
|
119
|
+
if (sent?.storageFailed) {
|
|
120
|
+
// Local first, then the PUT: the withdrawals still go at the allocated (device, seq); the page's deny map holds them and
|
|
121
|
+
// the shopper is told `storage_failed`. The unwritten counter means a later decision may reuse this seq (applied: false,
|
|
122
|
+
// handled by the usual rules).
|
|
123
|
+
const outcome = await this.submit({
|
|
124
|
+
clientLabel: null, notice: null, order: { device: sent.device, seq: sent.seq },
|
|
125
|
+
purposes: Object.fromEntries(sent.withdrawals.map((p) => [p, "withdrawn"])),
|
|
126
|
+
}, decision.owner, decision.owner === "none");
|
|
127
|
+
if (outcome.kind === "answer" && outcome.answer.ok)
|
|
128
|
+
this.bindMinted(decision, outcome.answer.data.shopper.owner);
|
|
129
|
+
}
|
|
130
|
+
else if (sent) {
|
|
131
|
+
const body = {
|
|
132
|
+
clientLabel: null,
|
|
133
|
+
notice: sent.grants.length > 0 ? { ref: decision.ref } : null,
|
|
134
|
+
order: { device: sent.device, seq: sent.seq },
|
|
135
|
+
purposes: Object.fromEntries([...sent.grants.map((p) => [p, "granted"]), ...sent.withdrawals.map((p) => [p, "withdrawn"])]),
|
|
136
|
+
};
|
|
137
|
+
const outcome = await this.submit(body, decision.owner, decision.owner === "none");
|
|
138
|
+
if (outcome.kind === "answer" && outcome.answer.ok)
|
|
139
|
+
this.bindMinted(decision, outcome.answer.data.shopper.owner);
|
|
140
|
+
const [grantStatuses, withdrawalStatuses] = await Promise.all([
|
|
141
|
+
sent.grants.length > 0 ? this.grantAnswer(decision, sent, outcome) : Promise.resolve({}),
|
|
142
|
+
Promise.all(sent.withdrawals.map(async (p) => {
|
|
143
|
+
const id = { site: this.site, purpose: p, owner: decision.owner, device: sent.device, seq: sent.seq };
|
|
144
|
+
const status = await this.withdrawalAnswer(id, outcome);
|
|
145
|
+
return [p, capacity.includes(p) ? "not_saved" : status];
|
|
146
|
+
})),
|
|
147
|
+
]);
|
|
148
|
+
Object.assign(statuses, grantStatuses, Object.fromEntries(withdrawalStatuses));
|
|
149
|
+
}
|
|
150
|
+
return { status: overall(statuses), purposes: statuses };
|
|
151
|
+
}
|
|
152
|
+
/** The lock callback of a decision: cookie reads and writes only. */
|
|
153
|
+
async allocate(d) {
|
|
154
|
+
const statuses = {};
|
|
155
|
+
const capacity = [];
|
|
156
|
+
const off = this.readOff();
|
|
157
|
+
const parsed = parseConsent(this.jar.get(this.names.consent));
|
|
158
|
+
const foundFallback = parsed !== null && isFallback(parsed);
|
|
159
|
+
const prepared = this.prepare(parsed, off);
|
|
160
|
+
const dirty = parsed !== null && prepared !== parsed;
|
|
161
|
+
let grants = d.grants.filter((p) => {
|
|
162
|
+
const abort = foundFallback || refusalBlocks(off, d.decidedAt, d.off);
|
|
163
|
+
if (abort)
|
|
164
|
+
statuses[p] = "refused_meanwhile";
|
|
165
|
+
return !abort;
|
|
166
|
+
});
|
|
167
|
+
const withdrawals = d.withdrawals;
|
|
168
|
+
if (grants.length + withdrawals.length === 0) {
|
|
169
|
+
if (dirty && prepared)
|
|
170
|
+
await this.commit(prepared);
|
|
171
|
+
return { statuses, sent: null, capacity };
|
|
172
|
+
}
|
|
173
|
+
let c = prepared ?? this.fresh([], 0);
|
|
174
|
+
let seq = c.seq + 1;
|
|
175
|
+
if (seq >= SEQ_LIMIT - 1) {
|
|
176
|
+
c = this.fresh(c.unsynced, c.overflow);
|
|
177
|
+
seq = 1;
|
|
178
|
+
}
|
|
179
|
+
c = { ...c, seq, at: d.decidedAt, purposes: { ...c.purposes } };
|
|
180
|
+
for (const p of withdrawals) {
|
|
181
|
+
c.purposes[p] = { state: "withdrawn", seq, at: d.decidedAt };
|
|
182
|
+
if (d.owner !== "none") {
|
|
183
|
+
const r = withEntry(c, { site: this.site, purpose: p, owner: d.owner, device: c.device, seq });
|
|
184
|
+
c = r.cookie;
|
|
185
|
+
if (!r.stored)
|
|
186
|
+
capacity.push(p);
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
for (const p of grants) {
|
|
190
|
+
const existing = c.purposes[p];
|
|
191
|
+
// The state stays exactly what it was until the answer, its refusal mark included (review 2 #3).
|
|
192
|
+
const base = existing
|
|
193
|
+
? { state: existing.state, seq: existing.seq, at: existing.at, ...(existing.off !== undefined ? { off: existing.off } : {}) }
|
|
194
|
+
: { state: "unset", seq: 0, at: d.decidedAt };
|
|
195
|
+
const pending = { seq, at: d.decidedAt, owner: d.owner, startedAt: this.now(), ...(d.off !== undefined ? { off: d.off } : {}) };
|
|
196
|
+
c = { ...c, purposes: { ...c.purposes, [p]: { ...base, pending } } };
|
|
197
|
+
// The newer decision replaces this owner's older withdrawal of the purpose, whatever happens to the grant's request.
|
|
198
|
+
c = withoutEntries(c, (e) => e.site === this.site && e.purpose === p && e.owner === d.owner);
|
|
199
|
+
}
|
|
200
|
+
const written = await this.commit(c);
|
|
201
|
+
if (written.result !== "ok") {
|
|
202
|
+
for (const p of [...grants, ...withdrawals])
|
|
203
|
+
statuses[p] = "storage_failed";
|
|
204
|
+
// Never a grant; the withdrawals are still submitted (see `set`).
|
|
205
|
+
const sent = withdrawals.length > 0 ? { device: c.device, seq, grants: [], withdrawals, storageFailed: true } : null;
|
|
206
|
+
return { statuses, sent, capacity };
|
|
207
|
+
}
|
|
208
|
+
// The re-read refusal time may have folded a grant just allocated: it aborts.
|
|
209
|
+
grants = grants.filter((p) => {
|
|
210
|
+
const kept = written.cookie.purposes[p]?.pending?.seq === seq;
|
|
211
|
+
if (!kept)
|
|
212
|
+
statuses[p] = "refused_meanwhile";
|
|
213
|
+
return kept;
|
|
214
|
+
});
|
|
215
|
+
if (grants.length + withdrawals.length === 0)
|
|
216
|
+
return { statuses, sent: null, capacity };
|
|
217
|
+
return { statuses, sent: { device: c.device, seq, grants, withdrawals, storageFailed: false }, capacity };
|
|
218
|
+
}
|
|
219
|
+
/** A minting answer binds a decision captured with owner `none` to the minted token's owner (and only to it). */
|
|
220
|
+
bindMinted(d, owner) {
|
|
221
|
+
if (d.owner !== "none" || owner === null || !owner.startsWith("t."))
|
|
222
|
+
return;
|
|
223
|
+
d.owner = owner;
|
|
224
|
+
if (this.owner === "none")
|
|
225
|
+
this.owner = owner;
|
|
226
|
+
}
|
|
227
|
+
async grantAnswer(d, req, outcome) {
|
|
228
|
+
const statuses = {};
|
|
229
|
+
const answer = outcome.kind === "answer" && outcome.answer.ok ? outcome.answer.data : null;
|
|
230
|
+
const compensate = [];
|
|
231
|
+
const done = await this.locked(async () => {
|
|
232
|
+
const off = this.readOff();
|
|
233
|
+
const parsed = parseConsent(this.jar.get(this.names.consent));
|
|
234
|
+
if (!answer) {
|
|
235
|
+
// A failed, timed-out or refused submission: drop this request's marker; the state is untouched.
|
|
236
|
+
for (const p of req.grants)
|
|
237
|
+
statuses[p] = "not_saved";
|
|
238
|
+
if (parsed && !isFallback(parsed) && parsed.device === req.device) {
|
|
239
|
+
let c = this.dropAbandoned(parsed);
|
|
240
|
+
for (const p of req.grants)
|
|
241
|
+
if (c.purposes[p]?.pending?.seq === req.seq)
|
|
242
|
+
c = withoutPending(c, p);
|
|
243
|
+
if (c !== parsed)
|
|
244
|
+
await this.commit(c);
|
|
245
|
+
}
|
|
246
|
+
return;
|
|
247
|
+
}
|
|
248
|
+
if (parsed === null || isFallback(parsed) || parsed.device !== req.device) {
|
|
249
|
+
// Invalidated: a missing, replaced or fallback cookie. Never touch another device's markers.
|
|
250
|
+
for (const p of req.grants) {
|
|
251
|
+
statuses[p] = "refused_meanwhile";
|
|
252
|
+
if (answer.applied[p] === true)
|
|
253
|
+
compensate.push(p);
|
|
254
|
+
}
|
|
255
|
+
return;
|
|
256
|
+
}
|
|
257
|
+
let c = this.dropAbandoned(parsed);
|
|
258
|
+
const applying = [];
|
|
259
|
+
for (const p of req.grants) {
|
|
260
|
+
const s = c.purposes[p];
|
|
261
|
+
if (s?.pending?.seq === req.seq) {
|
|
262
|
+
if (refusalBlocks(off, s.pending.at, s.pending.off)) {
|
|
263
|
+
c = withoutPending(c, p);
|
|
264
|
+
statuses[p] = "refused_meanwhile";
|
|
265
|
+
if (answer.applied[p] === true)
|
|
266
|
+
compensate.push(p);
|
|
267
|
+
}
|
|
268
|
+
else if (answer.applied[p] === true) {
|
|
269
|
+
const granted = { state: "granted", seq: req.seq, at: s.pending.at, ...(s.pending.off !== undefined ? { off: s.pending.off } : {}) };
|
|
270
|
+
c = { ...c, ref: d.ref ?? c.ref, purposes: { ...c.purposes, [p]: granted } };
|
|
271
|
+
applying.push(p);
|
|
272
|
+
}
|
|
273
|
+
else {
|
|
274
|
+
c = withoutPending(c, p);
|
|
275
|
+
statuses[p] = "not_saved";
|
|
276
|
+
}
|
|
277
|
+
}
|
|
278
|
+
else if (s && (s.seq > req.seq || (s.pending !== undefined && s.pending.seq > req.seq))) {
|
|
279
|
+
statuses[p] = "not_saved"; // superseded: a newer decision of this device took the slot; its answer decides
|
|
280
|
+
}
|
|
281
|
+
else if (refusalBlocks(off, d.decidedAt, d.off)) {
|
|
282
|
+
statuses[p] = "refused_meanwhile"; // the marker was folded away by a lock holder: invalidated
|
|
283
|
+
if (answer.applied[p] === true)
|
|
284
|
+
compensate.push(p);
|
|
285
|
+
}
|
|
286
|
+
else {
|
|
287
|
+
statuses[p] = "not_saved"; // the marker was dropped (abandoned): no local grant, no compensation
|
|
288
|
+
}
|
|
289
|
+
}
|
|
290
|
+
// A compensation of this request goes at `seq + 1` on this device: reserve it in the counter so the next decision of the
|
|
291
|
+
// device never reuses it (the server would ignore that decision as stale).
|
|
292
|
+
if (req.grants.some((p) => answer.applied[p] === true) && c.seq < req.seq + 1)
|
|
293
|
+
c = { ...c, seq: req.seq + 1 };
|
|
294
|
+
if (c === parsed)
|
|
295
|
+
return;
|
|
296
|
+
const written = await this.commit(c);
|
|
297
|
+
const offAfter = this.readOff();
|
|
298
|
+
for (const p of applying) {
|
|
299
|
+
const s = written.cookie.purposes[p];
|
|
300
|
+
if (written.result !== "ok")
|
|
301
|
+
statuses[p] = "storage_failed";
|
|
302
|
+
else if (s?.state !== "granted" || s.seq !== req.seq || !grantedFor(written.cookie, offAfter, p)) {
|
|
303
|
+
// Folded by the refusal time re-read just before the write, or a newer refusal time landed while the write was in
|
|
304
|
+
// flight (the stale snapshot no reader counts): the device refuses, so the server's grant is compensated.
|
|
305
|
+
statuses[p] = "refused_meanwhile";
|
|
306
|
+
compensate.push(p);
|
|
307
|
+
}
|
|
308
|
+
else {
|
|
309
|
+
statuses[p] = "saved";
|
|
310
|
+
const denied = this.deny.get(p);
|
|
311
|
+
if (denied !== undefined && s.at > denied)
|
|
312
|
+
this.deny.delete(p);
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
});
|
|
316
|
+
if (!done.ok)
|
|
317
|
+
for (const p of req.grants)
|
|
318
|
+
statuses[p] = "not_saved";
|
|
319
|
+
if (compensate.length > 0) {
|
|
320
|
+
await this.submit({
|
|
321
|
+
clientLabel: null, notice: null, order: { device: req.device, seq: req.seq + 1 },
|
|
322
|
+
purposes: Object.fromEntries(compensate.map((p) => [p, "withdrawn"])),
|
|
323
|
+
}, d.owner, false);
|
|
324
|
+
}
|
|
325
|
+
return statuses;
|
|
326
|
+
}
|
|
327
|
+
/**
|
|
328
|
+
* A withdrawal's answer, matched by the entry's full identity `(site, purpose, owner, device, seq)`. An ambiguous answer
|
|
329
|
+
* (`applied: false` showing `granted`) re-sends at most 3 times with a fresh `seq` of the current cookie.
|
|
330
|
+
*/
|
|
331
|
+
async withdrawalAnswer(id, outcome) {
|
|
332
|
+
for (;;) {
|
|
333
|
+
if (outcome.kind === "failed")
|
|
334
|
+
return "not_saved";
|
|
335
|
+
const answer = outcome.answer;
|
|
336
|
+
if (!answer.ok) {
|
|
337
|
+
if ("status" in answer && TOKEN_GONE.has(answer.problem.code) && id.owner.startsWith("t.")) {
|
|
338
|
+
await this.locked(() => this.dropEntries((e) => e.owner === id.owner));
|
|
339
|
+
}
|
|
340
|
+
return "not_saved";
|
|
341
|
+
}
|
|
342
|
+
const p = id.purpose;
|
|
343
|
+
if (acknowledged(answer.data, p)) {
|
|
344
|
+
await this.locked(() => this.dropEntries((e) => sameIdentity(e, id)));
|
|
345
|
+
return "saved";
|
|
346
|
+
}
|
|
347
|
+
if (answer.data.current[p] !== "granted")
|
|
348
|
+
return "not_saved";
|
|
349
|
+
const n = this.resends.get(identityKey(id)) ?? 0;
|
|
350
|
+
if (n >= RESEND_BACKOFF_MS.length)
|
|
351
|
+
return "not_saved";
|
|
352
|
+
await new Promise((resolve) => setTimeout(resolve, RESEND_BACKOFF_MS[n]));
|
|
353
|
+
const next = await this.locked(() => this.reallocate(id));
|
|
354
|
+
if (!next.ok || next.value === null)
|
|
355
|
+
return "not_saved";
|
|
356
|
+
this.resends.delete(identityKey(id));
|
|
357
|
+
this.resends.set(identityKey(next.value), n + 1);
|
|
358
|
+
id = next.value;
|
|
359
|
+
outcome = await this.submit({
|
|
360
|
+
clientLabel: null, notice: null, order: { device: id.device, seq: id.seq }, purposes: { [p]: "withdrawn" },
|
|
361
|
+
}, id.owner, false);
|
|
362
|
+
}
|
|
363
|
+
}
|
|
364
|
+
/** Under the lock: if the entry still exists with that identity, rewrite it to the current cookie's next `(device, seq)`. */
|
|
365
|
+
async reallocate(id) {
|
|
366
|
+
const parsed = parseConsent(this.jar.get(this.names.consent));
|
|
367
|
+
if (!parsed || !parsed.unsynced.some((e) => sameIdentity(e, id)))
|
|
368
|
+
return null;
|
|
369
|
+
let c = this.prepare(parsed, this.readOff());
|
|
370
|
+
let seq = c.seq + 1;
|
|
371
|
+
if (seq >= SEQ_LIMIT - 1) {
|
|
372
|
+
c = this.fresh(c.unsynced, c.overflow);
|
|
373
|
+
seq = 1;
|
|
374
|
+
}
|
|
375
|
+
const next = { ...id, device: c.device, seq };
|
|
376
|
+
c = { ...c, seq, unsynced: c.unsynced.map((e) => (sameIdentity(e, id) ? next : e)) };
|
|
377
|
+
const written = await this.commit(c);
|
|
378
|
+
return written.result === "ok" ? next : null;
|
|
379
|
+
}
|
|
380
|
+
// ---- lockless ------------------------------------------------------------------------------------------------------------
|
|
381
|
+
async lockless(d) {
|
|
382
|
+
const statuses = {};
|
|
383
|
+
for (const p of d.grants)
|
|
384
|
+
statuses[p] = "consent_unavailable";
|
|
385
|
+
if (d.withdrawals.length === 0)
|
|
386
|
+
return { status: overall(statuses), purposes: statuses };
|
|
387
|
+
// Read main once, only for the device key and the counter (or an existing fallback's fence).
|
|
388
|
+
const read = parseConsent(this.jar.get(this.names.consent));
|
|
389
|
+
let device;
|
|
390
|
+
let fence;
|
|
391
|
+
let fencedAt;
|
|
392
|
+
if (read && isFallback(read)) {
|
|
393
|
+
({ device, fence, fencedAt } = read);
|
|
394
|
+
}
|
|
395
|
+
else {
|
|
396
|
+
device = read?.device ?? hex(this.random(16));
|
|
397
|
+
fence = (read?.seq ?? 0) + SEQ_LIMIT;
|
|
398
|
+
fencedAt = d.decidedAt;
|
|
399
|
+
}
|
|
400
|
+
// Blind writes: a fresh refusal first, then the fallback value.
|
|
401
|
+
const offWritten = await this.writeRefusal(d.decidedAt);
|
|
402
|
+
const value = {
|
|
403
|
+
v: 1, fallback: true, device, fence, fencedAt, unsynced: read?.unsynced ?? [], overflow: read?.overflow ?? 0,
|
|
404
|
+
};
|
|
405
|
+
let raw = null;
|
|
406
|
+
try {
|
|
407
|
+
raw = serializeConsent(value);
|
|
408
|
+
}
|
|
409
|
+
catch (e) {
|
|
410
|
+
if (!(e instanceof ConsentCookieTooLarge))
|
|
411
|
+
throw e;
|
|
412
|
+
}
|
|
413
|
+
if (raw !== null)
|
|
414
|
+
await this.jar.set(this.names.consent, raw, CONSENT_COOKIE_SECONDS);
|
|
415
|
+
const storageFailed = !offWritten || raw === null || this.jar.get(this.names.consent) !== raw;
|
|
416
|
+
const fencedSeq = (floor) => Math.max(floor, fence + Math.max(1, this.now() - fencedAt));
|
|
417
|
+
let pending = [...d.withdrawals];
|
|
418
|
+
let seq = fencedSeq(0);
|
|
419
|
+
for (let attempt = 0; attempt < 2 && pending.length > 0; attempt++) {
|
|
420
|
+
if (!Number.isSafeInteger(seq))
|
|
421
|
+
break;
|
|
422
|
+
const outcome = await this.submit({
|
|
423
|
+
clientLabel: null, notice: null, order: { device, seq }, purposes: Object.fromEntries(pending.map((p) => [p, "withdrawn"])),
|
|
424
|
+
}, d.owner, d.owner === "none");
|
|
425
|
+
if (outcome.kind !== "answer" || !outcome.answer.ok)
|
|
426
|
+
break;
|
|
427
|
+
const data = outcome.answer.data;
|
|
428
|
+
this.bindMinted(d, data.shopper.owner);
|
|
429
|
+
for (const p of pending)
|
|
430
|
+
if (acknowledged(data, p))
|
|
431
|
+
statuses[p] = "saved";
|
|
432
|
+
pending = pending.filter((p) => statuses[p] !== "saved" && data.current[p] === "granted");
|
|
433
|
+
seq = fencedSeq(seq + 1);
|
|
434
|
+
}
|
|
435
|
+
for (const p of d.withdrawals)
|
|
436
|
+
statuses[p] = storageFailed ? "storage_failed" : (statuses[p] ?? "not_saved");
|
|
437
|
+
return { status: overall(statuses), purposes: statuses };
|
|
438
|
+
}
|
|
439
|
+
// ---- replay, erasure, adoption -------------------------------------------------------------------------------------------
|
|
440
|
+
start() {
|
|
441
|
+
return this.replay(() => true);
|
|
442
|
+
}
|
|
443
|
+
beforeSignOut() {
|
|
444
|
+
return this.replay((e) => e.owner.startsWith("t."));
|
|
445
|
+
}
|
|
446
|
+
async replay(select) {
|
|
447
|
+
const copied = await this.locked(async () => {
|
|
448
|
+
const parsed = parseConsent(this.jar.get(this.names.consent));
|
|
449
|
+
if (!parsed)
|
|
450
|
+
return [];
|
|
451
|
+
const c = this.prepare(parsed, this.readOff());
|
|
452
|
+
if (c !== parsed)
|
|
453
|
+
await this.commit(c);
|
|
454
|
+
return c.unsynced.filter((e) => e.site === this.site && select(e)).map((e) => ({ ...e }));
|
|
455
|
+
});
|
|
456
|
+
if (!copied.ok)
|
|
457
|
+
return;
|
|
458
|
+
await Promise.all(copied.value.map(async (e) => {
|
|
459
|
+
const outcome = await this.submit({
|
|
460
|
+
clientLabel: null, notice: null, order: { device: e.device, seq: e.seq }, purposes: { [e.purpose]: "withdrawn" },
|
|
461
|
+
}, e.owner, false);
|
|
462
|
+
await this.withdrawalAnswer(e, outcome);
|
|
463
|
+
}));
|
|
464
|
+
}
|
|
465
|
+
async erased() {
|
|
466
|
+
// Synchronously, before any await: this page refuses every purpose until a later grant is applied in it.
|
|
467
|
+
const at = this.now();
|
|
468
|
+
for (const p of PURPOSES)
|
|
469
|
+
this.deny.set(p, at);
|
|
470
|
+
// A fresh refusal before the delete: a grant answer already past its checks (in any tab, lockless or not) can still write its
|
|
471
|
+
// snapshot after the delete, but that snapshot observed another mark, so no reader counts it (review #2).
|
|
472
|
+
const clear = async () => {
|
|
473
|
+
await this.writeRefusal(at);
|
|
474
|
+
await this.jar.set(this.names.consent, "", 0);
|
|
475
|
+
};
|
|
476
|
+
const done = await this.locked(clear);
|
|
477
|
+
if (!done.ok)
|
|
478
|
+
await clear();
|
|
479
|
+
}
|
|
480
|
+
async adopted(tokenOwner) {
|
|
481
|
+
await this.locked(() => this.dropEntries((e) => e.owner === tokenOwner));
|
|
482
|
+
}
|
|
483
|
+
// ---- lock and cookie helpers ---------------------------------------------------------------------------------------------
|
|
484
|
+
/** Runs `fn` under the `sf-consent` lock: one retry of a rejected request, then `{ ok: false }`. */
|
|
485
|
+
async locked(fn) {
|
|
486
|
+
if (!this.locks)
|
|
487
|
+
return { ok: false };
|
|
488
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
489
|
+
let entered = false;
|
|
490
|
+
let result;
|
|
491
|
+
try {
|
|
492
|
+
await this.locks.request(LOCK_NAME, { mode: "exclusive" }, async () => {
|
|
493
|
+
entered = true;
|
|
494
|
+
try {
|
|
495
|
+
result = { value: await fn() };
|
|
496
|
+
}
|
|
497
|
+
catch (error) {
|
|
498
|
+
result = { error };
|
|
499
|
+
}
|
|
500
|
+
});
|
|
501
|
+
}
|
|
502
|
+
catch {
|
|
503
|
+
if (!entered)
|
|
504
|
+
continue;
|
|
505
|
+
}
|
|
506
|
+
if (!entered || result === undefined)
|
|
507
|
+
continue;
|
|
508
|
+
if ("error" in result)
|
|
509
|
+
throw result.error;
|
|
510
|
+
return { ok: true, value: result.value };
|
|
511
|
+
}
|
|
512
|
+
return { ok: false };
|
|
513
|
+
}
|
|
514
|
+
readOff() {
|
|
515
|
+
return parseRefusal(this.jar.get(this.names.off));
|
|
516
|
+
}
|
|
517
|
+
/**
|
|
518
|
+
* Blind-writes a refusal with a fresh, never reused mark (review #1): `at` is the decision time, never lowered below a refusal
|
|
519
|
+
* time read just before (a concurrent writer may still land an older time; the mark, not the time, is what makes that safe).
|
|
520
|
+
* Returns whether a refusal written at or after this call is in the cookie now: ours, or another refusal's that replaced it (it
|
|
521
|
+
* carries a fresh mark too, so it blocks every grant ours blocks). The value read before the write still there = rejected.
|
|
522
|
+
*/
|
|
523
|
+
async writeRefusal(decidedAt) {
|
|
524
|
+
const priorRaw = this.jar.get(this.names.off);
|
|
525
|
+
const prior = parseRefusal(priorRaw);
|
|
526
|
+
const at = prior !== null && prior !== "malformed" ? Math.max(prior.at, decidedAt) : decidedAt;
|
|
527
|
+
const value = serializeRefusal({ at, mark: hex(this.random(8)) });
|
|
528
|
+
await this.jar.set(this.names.off, value, CONSENT_OFF_COOKIE_SECONDS);
|
|
529
|
+
const now = this.jar.get(this.names.off);
|
|
530
|
+
return now === value || (now !== priorRaw && parseRefusal(now) !== null && parseRefusal(now) !== "malformed");
|
|
531
|
+
}
|
|
532
|
+
fresh(unsynced, overflow) {
|
|
533
|
+
return { v: 1, device: hex(this.random(16)), seq: 0, purposes: {}, ref: null, at: this.now(), unsynced: unsynced.map((e) => ({ ...e })), overflow };
|
|
534
|
+
}
|
|
535
|
+
/** What every lock holder does first: drop abandoned markers, recover from a fallback value (new generation), fold. */
|
|
536
|
+
prepare(parsed, off) {
|
|
537
|
+
if (parsed === null)
|
|
538
|
+
return null;
|
|
539
|
+
const c = isFallback(parsed) ? this.fresh(parsed.unsynced, parsed.overflow) : this.dropAbandoned(parsed);
|
|
540
|
+
return fold(c, off);
|
|
541
|
+
}
|
|
542
|
+
dropAbandoned(c) {
|
|
543
|
+
const t = this.now();
|
|
544
|
+
let next = c;
|
|
545
|
+
for (const p of PURPOSES) {
|
|
546
|
+
const pending = next.purposes[p]?.pending;
|
|
547
|
+
if (pending && t - pending.startedAt > PENDING_TTL_MS)
|
|
548
|
+
next = withoutPending(next, p);
|
|
549
|
+
}
|
|
550
|
+
return next;
|
|
551
|
+
}
|
|
552
|
+
/** Re-reads the refusal time and folds immediately before the write (PL6), writes, reads back. */
|
|
553
|
+
async commit(c) {
|
|
554
|
+
const cookie = fold(c, this.readOff());
|
|
555
|
+
let raw;
|
|
556
|
+
try {
|
|
557
|
+
raw = serializeConsent(cookie);
|
|
558
|
+
}
|
|
559
|
+
catch (e) {
|
|
560
|
+
if (e instanceof ConsentCookieTooLarge)
|
|
561
|
+
return { result: "too_large", cookie };
|
|
562
|
+
throw e;
|
|
563
|
+
}
|
|
564
|
+
await this.jar.set(this.names.consent, raw, CONSENT_COOKIE_SECONDS);
|
|
565
|
+
return { result: this.jar.get(this.names.consent) === raw ? "ok" : "rejected", cookie };
|
|
566
|
+
}
|
|
567
|
+
/** Under the lock: drops this site's entries `pred` selects (an acknowledgement, a `404`, an adoption). */
|
|
568
|
+
async dropEntries(pred) {
|
|
569
|
+
const parsed = parseConsent(this.jar.get(this.names.consent));
|
|
570
|
+
if (!parsed)
|
|
571
|
+
return;
|
|
572
|
+
let c = isFallback(parsed) ? parsed : this.dropAbandoned(parsed);
|
|
573
|
+
c = withoutEntries(c, (e) => e.site === this.site && pred(e));
|
|
574
|
+
if (c !== parsed)
|
|
575
|
+
await this.commit(c);
|
|
576
|
+
}
|
|
577
|
+
/** Sends one `PUT` outside the lock; a throw, a rejection or `PUT_TIMEOUT_MS` without an answer is `failed`. */
|
|
578
|
+
async submit(body, owner, mayMint) {
|
|
579
|
+
const controller = new AbortController();
|
|
580
|
+
let timer;
|
|
581
|
+
const timeout = new Promise((resolve) => {
|
|
582
|
+
timer = setTimeout(() => {
|
|
583
|
+
controller.abort();
|
|
584
|
+
resolve({ kind: "failed" });
|
|
585
|
+
}, PUT_TIMEOUT_MS);
|
|
586
|
+
});
|
|
587
|
+
let call;
|
|
588
|
+
try {
|
|
589
|
+
call = Promise.resolve(this.transport.put(body, owner, { mayMint, signal: controller.signal }))
|
|
590
|
+
.then((answer) => ({ kind: "answer", answer }), () => ({ kind: "failed" }));
|
|
591
|
+
}
|
|
592
|
+
catch {
|
|
593
|
+
call = Promise.resolve({ kind: "failed" });
|
|
594
|
+
}
|
|
595
|
+
try {
|
|
596
|
+
return await Promise.race([call, timeout]);
|
|
597
|
+
}
|
|
598
|
+
finally {
|
|
599
|
+
clearTimeout(timer);
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
const identityKey = (e) => `${e.site}|${e.purpose}|${e.owner}|${e.device}|${e.seq}`;
|
|
604
|
+
const sameIdentity = (a, b) => a.site === b.site && a.purpose === b.purpose && a.owner === b.owner && a.device === b.device && a.seq === b.seq;
|
|
605
|
+
/** The browser's consent coordinator (S36). Throws when `window` is undefined and no `cookies` jar is injected. */
|
|
606
|
+
export function createConsentCoordinator(opts) {
|
|
607
|
+
return new Coordinator(opts);
|
|
608
|
+
}
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@asstio-dev/storefront/consent` — the consent cookie codec, the published notice helper and the browser-only consent
|
|
3
|
+
* coordinator (shopper-state spec §7.4, S36). The codec and the notice helper work in the browser and on the server;
|
|
4
|
+
* `createConsentCoordinator` throws without `window`. The server readers are in `@asstio-dev/storefront/consent/server`.
|
|
5
|
+
*/
|
|
6
|
+
export { CONSENT_COOKIE, CONSENT_COOKIE_SECONDS, CONSENT_OFF_COOKIE, CONSENT_OFF_COOKIE_SECONDS, ConsentCookieTooLarge, consentCookieNames, fold, grantedFor, isFallback, MAX_CONSENT_COOKIE_LENGTH, MAX_UNSYNCED, parseConsent, parseRefusal, PENDING_TTL_MS, PURPOSES, refusalBlocks, refusalMark, PUT_TIMEOUT_MS, SEQ_LIMIT, serializeConsent, serializeRefusal, withEntry, withoutEntries, type ConsentCookie, type FallbackConsentCookie, type LockedConsentCookie, type Purpose, type PurposeState, type Refusal, type UnsyncedEntry, } from "./codec.js";
|
|
7
|
+
export { consentNotice, type ConsentNoticeDto } from "./notice.js";
|
|
8
|
+
export { createConsentCoordinator, type AccountConsentRecord, type ConsentCoordinator, type ConsentCoordinatorOptions, type ConsentDecision, type ConsentPutBody, type ConsentTransport, type CookieJar, type SetResult, type SetStatus, type TransportAnswer, } from "./coordinator.js";
|
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `@asstio-dev/storefront/consent` — the consent cookie codec, the published notice helper and the browser-only consent
|
|
3
|
+
* coordinator (shopper-state spec §7.4, S36). The codec and the notice helper work in the browser and on the server;
|
|
4
|
+
* `createConsentCoordinator` throws without `window`. The server readers are in `@asstio-dev/storefront/consent/server`.
|
|
5
|
+
*/
|
|
6
|
+
export { CONSENT_COOKIE, CONSENT_COOKIE_SECONDS, CONSENT_OFF_COOKIE, CONSENT_OFF_COOKIE_SECONDS, ConsentCookieTooLarge, consentCookieNames, fold, grantedFor, isFallback, MAX_CONSENT_COOKIE_LENGTH, MAX_UNSYNCED, parseConsent, parseRefusal, PENDING_TTL_MS, PURPOSES, refusalBlocks, refusalMark, PUT_TIMEOUT_MS, SEQ_LIMIT, serializeConsent, serializeRefusal, withEntry, withoutEntries, } from "./codec.js";
|
|
7
|
+
export { consentNotice } from "./notice.js";
|
|
8
|
+
export { createConsentCoordinator, } from "./coordinator.js";
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { components } from "../schema";
|
|
2
|
+
export type ConsentNoticeDto = components["schemas"]["ConsentNoticeDto"];
|
|
3
|
+
type SiteDto = components["schemas"]["SiteDto"];
|
|
4
|
+
/**
|
|
5
|
+
* The published consent notice to render (shopper-state spec §7.2, §9.1): `site.shopper.consentNotice` when the site publishes one
|
|
6
|
+
* and, when `language` is given, only if the notice is in that language; else null (consent grants then answer `CONSENT_DISABLED`).
|
|
7
|
+
* Fetch `/v1/site` with the page's own `Accept-Language`, render the notice's text exactly, and send its `ref` with every grant.
|
|
8
|
+
*/
|
|
9
|
+
export declare function consentNotice(site: SiteDto, language?: string): ConsentNoticeDto | null;
|
|
10
|
+
export {};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The published consent notice to render (shopper-state spec §7.2, §9.1): `site.shopper.consentNotice` when the site publishes one
|
|
3
|
+
* and, when `language` is given, only if the notice is in that language; else null (consent grants then answer `CONSENT_DISABLED`).
|
|
4
|
+
* Fetch `/v1/site` with the page's own `Accept-Language`, render the notice's text exactly, and send its `ref` with every grant.
|
|
5
|
+
*/
|
|
6
|
+
export function consentNotice(site, language) {
|
|
7
|
+
const notice = site.shopper?.consentNotice ?? null;
|
|
8
|
+
if (!notice)
|
|
9
|
+
return null;
|
|
10
|
+
return language === undefined || notice.language === language ? notice : null;
|
|
11
|
+
}
|