@gradial/aci 0.1.52-rc.16 → 0.1.52-rc.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (48) hide show
  1. package/README.md +4 -4
  2. package/dist/astro/preview.js +2 -17
  3. package/dist/audience-data-models.d.ts +193 -16
  4. package/dist/audience-data-models.js +47 -2
  5. package/dist/collect/batcher.d.ts +6 -5
  6. package/dist/collect/batcher.js +6 -5
  7. package/dist/edge/expression-capabilities.v1.d.ts +106 -0
  8. package/dist/edge/expression-capabilities.v1.js +165 -0
  9. package/dist/internal/domain/edge/identity.js +1 -1
  10. package/dist/internal/domain/edge/mimic_token.js +1 -2
  11. package/dist/internal/domain/edge/personalization-core.d.ts +14 -4
  12. package/dist/internal/domain/edge/personalization-core.js +472 -54
  13. package/dist/internal/domain/edge/record/codec.d.ts +5 -2
  14. package/dist/internal/domain/edge/record/codec.js +83 -10
  15. package/dist/internal/domain/edge/resolve.js +13 -2
  16. package/dist/internal/domain/edge/testdata/flat_only_validator_v1.d.ts +10 -0
  17. package/dist/internal/domain/edge/testdata/flat_only_validator_v1.js +253 -0
  18. package/dist/internal/domain/edge/types.d.ts +36 -9
  19. package/dist/internal/domain/edge/types.js +3 -3
  20. package/dist/mimic/core.d.ts +0 -32
  21. package/dist/mimic/core.js +12 -108
  22. package/dist/next/vercel-edge-projection-v1.d.ts +0 -9
  23. package/dist/next/vercel-edge-projection-v1.js +9 -545
  24. package/dist/preview/core.d.ts +1 -0
  25. package/dist/preview/core.js +27 -0
  26. package/dist/react/VideoPlayer.d.ts +1 -1
  27. package/dist/react/index.d.ts +1 -1
  28. package/package.json +16 -7
  29. package/templates/common/.agents/skills/aci/SKILL.md +6 -0
  30. package/templates/common/.agents/skills/dam-delivery/SKILL.md +228 -0
  31. package/templates/common/.agents/skills/dam-delivery/references/parameter-contract.md +107 -0
  32. package/templates/common/.agents/skills/dam-delivery/references/permalink-grammar.md +131 -0
  33. package/dist/edge/personalization-core.d.ts +0 -35
  34. package/dist/edge/personalization-core.js +0 -483
  35. package/dist/next/collect-route.d.ts +0 -25
  36. package/dist/next/collect-route.js +0 -479
  37. package/dist/next/envelope-digest.d.ts +0 -21
  38. package/dist/next/envelope-digest.js +0 -58
  39. package/dist/next/personalization-host.d.ts +0 -138
  40. package/dist/next/personalization-host.js +0 -280
  41. package/dist/next/root-layout.d.ts +0 -4
  42. package/dist/next/root-layout.js +0 -5
  43. package/dist/next/vercel-collect-sdk-route.d.ts +0 -27
  44. package/dist/next/vercel-collect-sdk-route.js +0 -181
  45. package/dist/next/vercel-personalization.d.ts +0 -4
  46. package/dist/next/vercel-personalization.js +0 -4
  47. package/dist/next/vercel-s3-personalization.d.ts +0 -80
  48. package/dist/next/vercel-s3-personalization.js +0 -571
@@ -1,479 +0,0 @@
1
- import { MAX_BATCH_EVENTS } from '../collect/batcher.js';
2
- import { computeEnvelopeDigest } from './envelope-digest.js';
3
- import { validateMimicToken } from '../mimic/core.js';
4
- import { deviceClassFromHeaders } from '../edge/personalization-core.js';
5
- import { consentSignals, IdentityErasureFencedError, identityHashHex, parseCookieHeader, verifyClaims, verifyIdentityCookie, } from './personalization-host.js';
6
- const MAX_COLLECT_BODY_BYTES = 64 * 1024;
7
- const DEFAULT_RETENTION_SECONDS = 13 * 30 * 24 * 60 * 60;
8
- const ULID = /^[0-7][0-9A-HJKMNP-TV-Z]{25}$/i;
9
- const UTM_KEYS = ['source', 'medium', 'campaign', 'term', 'content', 'id'];
10
- const ENVELOPE_FIELDS = new Set(['envelopeId', 'events']);
11
- const EVENT_FIELDS = new Set([
12
- 'eventId',
13
- 'eventName',
14
- 'occurredAt',
15
- 'properties',
16
- 'url',
17
- 'referrer',
18
- 'title',
19
- 'path',
20
- 'utm',
21
- 'viewport',
22
- 'experiment',
23
- ]);
24
- function identityHashShard(identityHash) {
25
- const hash = identityHash.trim().toLowerCase();
26
- if (hash.length < 2)
27
- throw new Error('identity hash is too short');
28
- return hash.slice(0, 2);
29
- }
30
- export function createPersonalizationCollectRoute(config) {
31
- return async function collect(request) {
32
- if (request.method === 'OPTIONS')
33
- return new Response(null, { status: 204 });
34
- if (request.method !== 'POST')
35
- return new Response(null, { status: 405, headers: { allow: 'POST, OPTIONS' } });
36
- const bytes = new Uint8Array(await request.arrayBuffer());
37
- if (bytes.byteLength > MAX_COLLECT_BODY_BYTES)
38
- return new Response(null, { status: 413 });
39
- let envelopeId;
40
- let events;
41
- try {
42
- const envelope = JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes));
43
- if (!envelope || typeof envelope !== 'object' || Array.isArray(envelope)) {
44
- throw new CollectValidationError('collect envelope must be an object');
45
- }
46
- for (const key of Object.keys(envelope)) {
47
- if (!ENVELOPE_FIELDS.has(key)) {
48
- throw new CollectValidationError(`field ${key} is not allowed on the collect envelope`);
49
- }
50
- }
51
- if (typeof envelope.envelopeId !== 'string' || !ULID.test(envelope.envelopeId.trim())) {
52
- throw new CollectValidationError('envelopeId must be a valid ULID');
53
- }
54
- envelopeId = envelope.envelopeId.trim().toUpperCase();
55
- if (!Array.isArray(envelope.events))
56
- throw new CollectValidationError('events must be an array');
57
- // The TS runtime has no cross-instance quota checker (Go's REQ-14/
58
- // REQ-20 guard); the 64KiB body cap plus this per-batch event cap and
59
- // the platform WAF are the abuse bounds. The cap is the client
60
- // batcher's MAX_BATCH_EVENTS — one constant, both sides of the wire.
61
- if (envelope.events.length > MAX_BATCH_EVENTS)
62
- throw new CollectValidationError('too many events in one batch');
63
- events = envelope.events;
64
- const eventIds = new Set();
65
- for (const event of events) {
66
- validateEvent(event);
67
- const eventId = event.eventId.trim().toUpperCase();
68
- if (eventId === envelopeId) {
69
- throw new CollectValidationError('envelopeId must be distinct from every eventId');
70
- }
71
- if (eventIds.has(eventId)) {
72
- throw new CollectValidationError('eventId must be unique within an envelope');
73
- }
74
- eventIds.add(eventId);
75
- }
76
- }
77
- catch (error) {
78
- return validationResponse(error);
79
- }
80
- const cookies = parseCookieHeader(request.headers.get('cookie'));
81
- // Mimic suppression (audience-mimic REQ-5): a validly signed, unexpired
82
- // aci_mimic cookie marks a marketer's view-as session — accept uniformly,
83
- // store nothing, and never rotate the visitor's real aci_claims. Placed
84
- // after schema validation so the 400/202 split stays independent of
85
- // session type; an invalid cookie is ignored (events process normally).
86
- if (config.mimicSignKey) {
87
- const mimicCookie = cookies.get('aci_mimic') || '';
88
- if (mimicCookie) {
89
- const mimic = await validateMimicToken(mimicCookie, config.mimicSignKey, config.siteId);
90
- if (mimic) {
91
- return accepted(new Headers({ 'cache-control': 'no-store', 'content-type': 'application/json' }));
92
- }
93
- }
94
- }
95
- const signals = consentSignals(request, cookies);
96
- const rawIdentity = await verifyIdentityCookie(cookies.get('aci_id') || '', config.identityKeys);
97
- const now = (config.now ?? (() => new Date()))();
98
- const secure = config.secureCookies ?? new URL(request.url).protocol === 'https:';
99
- const responseHeaders = new Headers({ 'cache-control': 'no-store', 'content-type': 'application/json' });
100
- try {
101
- // Withdrawal EVIDENCE (anonymous-experiments REQ-6): a signature-
102
- // verified aci_claims cookie proves prior identity-tier state exists
103
- // to suppress. Never-consented visitors present no verifiable claims
104
- // and stay measurement-only.
105
- const evidence = rawIdentity
106
- ? await verifyClaims(cookies.get('aci_claims') || '', config.claimsKeys || {}, now) !== null
107
- : false;
108
- const putSuppression = async (trigger) => {
109
- const hash = await identityHashHex('aci_id', rawIdentity);
110
- await config.store.putSuppression(`audience/suppression/${identityHashShard(hash)}/${config.siteId}/aci_id/${hash}/${trigger}.json`, { schemaVersion: 1, trigger, observedAt: now.toISOString() });
111
- };
112
- if (signals.privacyDenied) {
113
- if (rawIdentity && evidence) {
114
- await putSuppression('gpc');
115
- }
116
- if (cookies.has('aci_claims'))
117
- appendCookie(responseHeaders, expiredClaimsCookie(secure));
118
- return accepted(responseHeaders);
119
- }
120
- if (!rawIdentity)
121
- return accepted(responseHeaders);
122
- // Measurement tier (anonymous-experiments REQ-5): a verified aci_id
123
- // stores events even without a personalization grant — the snapshot
124
- // records what was (not) granted. An explicit denial with verified
125
- // evidence is an observed withdrawal; measurement storage continues.
126
- const personalization = signals.allowsIdentityTier;
127
- if (!personalization && signals.hasConsent && evidence) {
128
- await putSuppression('withdrawal');
129
- }
130
- const identityHash = await identityHashHex('aci_id', rawIdentity);
131
- const geo = collectGeo(request);
132
- // Server-derived from the request's own headers by the SAME classifier
133
- // request-scope targeting uses (ADR 0035), so a reported class and a
134
- // targeted class agree by construction. Never read from the body.
135
- const deviceClass = collectDeviceClass(request);
136
- const collectedAt = now.toISOString();
137
- const expiresAt = new Date(now.getTime() +
138
- (config.retentionSeconds ?? DEFAULT_RETENTION_SECONDS) * 1000).toISOString();
139
- const consent = signals.snapshot
140
- ? {
141
- v: signals.snapshot.version,
142
- p: signals.snapshot.purposes,
143
- ...(signals.snapshot.grantedAt ? { t: signals.snapshot.grantedAt } : {}),
144
- ...(signals.snapshot.source ? { src: signals.snapshot.source } : {}),
145
- }
146
- : { v: 0, p: [] };
147
- const records = events.map((event) => {
148
- const normalized = normalizeEvent(event, now);
149
- return {
150
- schemaVersion: 2,
151
- eventId: normalized.eventId,
152
- eventName: normalized.eventName,
153
- eventCategory: normalized.eventCategory,
154
- siteId: config.siteId,
155
- identity: { namespace: 'aci_id', hash: identityHash },
156
- // Go decodes `t` as time.Time and CANNOT parse an empty string —
157
- // an empty-t record permanently poisons that identity's
158
- // classification and DSAR reads. Omit t unless a real timestamp
159
- // was observed (legacy bare tokens have none).
160
- consent,
161
- ...(normalized.properties ? { properties: normalized.properties } : {}),
162
- page: normalized.page,
163
- ...(normalized.utm ? { utm: normalized.utm } : {}),
164
- ...(normalized.viewport ? { viewport: normalized.viewport } : {}),
165
- ...(normalized.experiment ? { experiment: normalized.experiment } : {}),
166
- // Server-stamped geo (country + region only, D-PDP-14) from the
167
- // platform-injected viewer headers; never from the event body.
168
- ...(geo ? { geo } : {}),
169
- deviceClass,
170
- occurredAt: normalized.occurredAt,
171
- collectedAt,
172
- expiresAt,
173
- };
174
- });
175
- if (records.length > 0) {
176
- const key = `audience/first-party/${identityHashShard(identityHash)}/${config.siteId}/aci_id/${identityHash}/${envelopeId}.json`;
177
- const digest = await computeEnvelopeDigest({
178
- siteId: config.siteId,
179
- acceptedBody: bytes,
180
- identity: { namespace: 'aci_id', hash: identityHash },
181
- consent: {
182
- version: signals.snapshot?.version ?? 0,
183
- purposes: signals.snapshot?.purposes ?? [],
184
- grantedAt: signals.snapshot?.grantedAt,
185
- source: signals.snapshot?.source,
186
- },
187
- });
188
- try {
189
- await config.store.appendEnvelope({
190
- key,
191
- envelopeId,
192
- siteId: config.siteId,
193
- identityNamespace: 'aci_id',
194
- identityHash,
195
- records,
196
- digest,
197
- });
198
- }
199
- catch (error) {
200
- if (error instanceof IdentityErasureFencedError) {
201
- if (cookies.has('aci_claims'))
202
- appendCookie(responseHeaders, expiredClaimsCookie(secure));
203
- return accepted(responseHeaders);
204
- }
205
- throw error;
206
- }
207
- }
208
- if (personalization) {
209
- const claims = await config.store.readClaims(config.siteId, 'aci_id', identityHash);
210
- if (claims)
211
- appendCookie(responseHeaders, claimsCookie(claims, secure));
212
- else if (cookies.has('aci_claims'))
213
- appendCookie(responseHeaders, expiredClaimsCookie(secure));
214
- }
215
- else if (cookies.has('aci_claims')) {
216
- // Claims are personalization; a non-granting touch expires them.
217
- appendCookie(responseHeaders, expiredClaimsCookie(secure));
218
- }
219
- return accepted(responseHeaders);
220
- }
221
- catch {
222
- return Response.json({ error: 'internal error', status: 500 }, { status: 500, headers: { 'cache-control': 'no-store' } });
223
- }
224
- };
225
- }
226
- function validateEvent(value) {
227
- if (!value || typeof value !== 'object' || Array.isArray(value))
228
- throw new CollectValidationError('event must be an object');
229
- for (const key of Object.keys(value)) {
230
- if (!EVENT_FIELDS.has(key))
231
- throw new CollectValidationError(`field ${key} is not allowed on the public collect route`);
232
- }
233
- if (typeof value.eventId !== 'string' || !ULID.test(value.eventId.trim()))
234
- throw new CollectValidationError('eventId must be a valid ULID');
235
- if (typeof value.eventName !== 'string')
236
- throw new CollectValidationError('event name is required');
237
- normalizeEventName(value.eventName);
238
- for (const field of ['url', 'referrer', 'title', 'path']) {
239
- if (value[field] !== undefined && typeof value[field] !== 'string')
240
- throw new CollectValidationError(`${field} must be a string`);
241
- }
242
- if (value.properties !== undefined && (!value.properties || typeof value.properties !== 'object' || Array.isArray(value.properties))) {
243
- throw new CollectValidationError('properties must be an object');
244
- }
245
- if (value.properties !== undefined)
246
- sanitizeProperties(value.properties, 'properties', 0);
247
- if (value.occurredAt !== undefined && (typeof value.occurredAt !== 'string' || Number.isNaN(Date.parse(value.occurredAt)))) {
248
- throw new CollectValidationError('occurredAt must be an RFC3339 timestamp');
249
- }
250
- if (value.utm !== undefined && (!value.utm || typeof value.utm !== 'object' || Array.isArray(value.utm))) {
251
- throw new CollectValidationError('utm must be an object');
252
- }
253
- normalizeViewport(value.viewport);
254
- normalizeExperiment(value.experiment);
255
- }
256
- function normalizeEvent(event, now) {
257
- const [eventName, eventCategory] = normalizeEventName(String(event.eventName));
258
- const rawURL = typeof event.url === 'string' ? event.url.trim() : '';
259
- const pageURL = sanitizeURL(rawURL, 'url');
260
- const referrer = sanitizeURL(typeof event.referrer === 'string' ? event.referrer.trim() : '', 'referrer');
261
- const parsedURL = rawURL ? new URL(rawURL, 'https://aci.invalid') : null;
262
- let path = typeof event.path === 'string' ? event.path.trim() : parsedURL?.pathname || '';
263
- if (path && !path.startsWith('/'))
264
- path = `/${path}`;
265
- const utm = normalizeUTM(event.utm, parsedURL);
266
- const occurredAt = typeof event.occurredAt === 'string' && !Number.isNaN(Date.parse(event.occurredAt))
267
- ? new Date(event.occurredAt).toISOString()
268
- : now.toISOString();
269
- return {
270
- eventId: String(event.eventId).trim().toUpperCase(),
271
- eventName,
272
- eventCategory,
273
- occurredAt,
274
- properties: event.properties === undefined ? undefined : sanitizeProperties(event.properties, 'properties', 0),
275
- page: {
276
- ...(pageURL ? { url: pageURL } : {}),
277
- ...(referrer ? { referrer } : {}),
278
- ...(typeof event.title === 'string' && event.title.trim() ? { title: event.title.trim() } : {}),
279
- ...(path ? { path } : {}),
280
- },
281
- utm,
282
- viewport: normalizeViewport(event.viewport),
283
- experiment: normalizeExperiment(event.experiment),
284
- };
285
- }
286
- // collectGeo stamps the request geo from the platform-injected viewer
287
- // headers (Vercel overwrites x-vercel-ip-* on every request, so they are
288
- // trusted). Country + region only — city is never captured (D-PDP-14).
289
- // Returns undefined when neither dimension normalizes, so the lake record
290
- // keeps its historical byte shape for no-source requests.
291
- function collectGeo(request) {
292
- const country = normalizeGeoCountry(request.headers.get('x-vercel-ip-country'));
293
- // A region without its country keys nothing (see runtime/collect.ts).
294
- if (!country)
295
- return undefined;
296
- const region = normalizeGeoRegion(request.headers.get('x-vercel-ip-country-region'));
297
- return { country, ...(region ? { region } : {}) };
298
- }
299
- function normalizeGeoCountry(value) {
300
- const clean = (value ?? '').trim();
301
- return /^[a-zA-Z]{2}$/.test(clean) ? clean.toUpperCase() : '';
302
- }
303
- function normalizeGeoRegion(value) {
304
- const clean = (value ?? '').trim();
305
- return /^[a-zA-Z0-9]{1,3}$/.test(clean) ? clean.toUpperCase() : '';
306
- }
307
- // collectDeviceClass classifies the request through the shared edge/SDK
308
- // classifier. Capture has no "absent" bucket — the class joins a rollup key —
309
- // so a request with nothing to classify floors to the enum's 'unknown', while
310
- // request-scope targeting keeps absence distinct.
311
- function collectDeviceClass(request) {
312
- const headers = {};
313
- request.headers.forEach((value, name) => {
314
- headers[name.toLowerCase()] = value;
315
- });
316
- return deviceClassFromHeaders(headers) || 'unknown';
317
- }
318
- function normalizeEventName(value) {
319
- const name = value.trim().toLowerCase();
320
- if (!name || name.length > 128 || /[\s/\\]/.test(name))
321
- throw new CollectValidationError('event name must be dot-delimited');
322
- const rum = new Set(['rum.page_view', 'rum.link_click', 'rum.variation_view', 'rum.web_vital']);
323
- const experiment = new Set(['experiment.exposure', 'experiment.conversion', 'experiment.engagement']);
324
- if (rum.has(name))
325
- return [name, 'rum'];
326
- if (experiment.has(name))
327
- return [name, 'experiment'];
328
- if (name.startsWith('custom.') && name.length > 'custom.'.length)
329
- return [name, 'custom'];
330
- throw new CollectValidationError('event name must be one of the supported rum.* or experiment.* events, or use the custom.* namespace');
331
- }
332
- function sanitizeURL(value, field) {
333
- if (!value)
334
- return '';
335
- if (value.length > 2048)
336
- throw new CollectValidationError(`${field} is too long`);
337
- let parsed;
338
- try {
339
- parsed = new URL(value, 'https://aci.invalid');
340
- }
341
- catch {
342
- throw new CollectValidationError(`${field} is invalid`);
343
- }
344
- if (!['http:', 'https:'].includes(parsed.protocol))
345
- throw new CollectValidationError(`${field} scheme is not allowed`);
346
- parsed.search = '';
347
- parsed.hash = '';
348
- if (parsed.origin === 'https://aci.invalid')
349
- return parsed.pathname;
350
- return parsed.toString().replace(/\/$/, parsed.pathname === '/' ? '/' : '');
351
- }
352
- function normalizeUTM(value, url) {
353
- const source = value && typeof value === 'object' && !Array.isArray(value) ? value : {};
354
- const out = {};
355
- for (const key of UTM_KEYS) {
356
- const raw = source[key] ?? source[`utm_${key}`] ?? url?.searchParams.get(`utm_${key}`);
357
- if (typeof raw === 'string' && raw.trim())
358
- out[key] = raw.trim();
359
- }
360
- return Object.keys(out).length > 0 ? out : undefined;
361
- }
362
- function sanitizeProperties(value, field, depth) {
363
- if (depth > 4)
364
- throw new CollectValidationError(`${field} is nested too deeply`);
365
- if (value === null || typeof value === 'boolean' || typeof value === 'number')
366
- return value;
367
- if (typeof value === 'string')
368
- return sanitizeString(value, field, 2048);
369
- if (Array.isArray(value)) {
370
- if (value.length > 32)
371
- throw new CollectValidationError(`${field} has too many values`);
372
- return value.map((item, index) => sanitizeProperties(item, `${field}[${index}]`, depth + 1));
373
- }
374
- if (typeof value !== 'object')
375
- throw new CollectValidationError(`${field} has unsupported value type`);
376
- const entries = Object.entries(value);
377
- if (entries.length > 64)
378
- throw new CollectValidationError(`${field} has too many keys`);
379
- const sanitized = {};
380
- for (const [rawKey, item] of entries) {
381
- const key = sanitizeString(rawKey, `${field} key`, 256);
382
- if (!key)
383
- throw new CollectValidationError(`${field} contains an empty key`);
384
- if (secretLikeKey(key))
385
- throw new CollectValidationError(`${field} contains a sensitive key`);
386
- sanitized[key] = sanitizeProperties(item, `${field}.${key}`, depth + 1);
387
- }
388
- return sanitized;
389
- }
390
- function secretLikeKey(key) {
391
- const normalized = key.toLowerCase().replace(/[-. ]/g, '_');
392
- const compact = normalized.replace(/_/g, '');
393
- const normalizedMarkers = [
394
- 'authorization', 'access_token', 'refresh_token', 'id_token', 'api_key',
395
- 'private_key', 'secret', 'password', 'passwd', 'credential', 'cookie', 'set_cookie',
396
- ];
397
- const compactMarkers = [
398
- 'authorization', 'accesstoken', 'refreshtoken', 'idtoken', 'apikey',
399
- 'privatekey', 'secret', 'password', 'passwd', 'credential', 'cookie', 'setcookie',
400
- ];
401
- return normalizedMarkers.some((marker) => normalized.includes(marker))
402
- || compactMarkers.some((marker) => compact.includes(marker));
403
- }
404
- function sanitizeString(value, field, limit) {
405
- const clean = value.trim();
406
- if (clean.length > limit)
407
- throw new CollectValidationError(`${field} is too long`);
408
- if (/[\u0000-\u001F\u007F-\u009F]/u.test(clean))
409
- throw new CollectValidationError(`${field} contains control characters`);
410
- return clean;
411
- }
412
- function normalizeViewport(value) {
413
- if (value === undefined || value === null)
414
- return undefined;
415
- if (typeof value !== 'object' || Array.isArray(value))
416
- throw new CollectValidationError('viewport is invalid');
417
- const viewport = value;
418
- const width = viewport.width ?? 0;
419
- const height = viewport.height ?? 0;
420
- if (!Number.isInteger(width) || !Number.isInteger(height) || Number(width) < 0 || Number(height) < 0 || Number(width) > 20_000 || Number(height) > 20_000) {
421
- throw new CollectValidationError('viewport is invalid');
422
- }
423
- if (width === 0 && height === 0)
424
- return undefined;
425
- return { width: Number(width), height: Number(height) };
426
- }
427
- function normalizeExperiment(value) {
428
- if (value === undefined || value === null)
429
- return undefined;
430
- if (typeof value !== 'object' || Array.isArray(value))
431
- throw new CollectValidationError('experiment is invalid');
432
- const source = value;
433
- const experimentId = shortOptionalString(source.experimentId, 'experiment.experimentId');
434
- const armId = shortOptionalString(source.armId, 'experiment.armId');
435
- const allocationVersion = shortOptionalString(source.allocationVersion, 'experiment.allocationVersion');
436
- const goalId = shortOptionalString(source.goalId, 'experiment.goalId');
437
- const bucket = source.assignmentBucket;
438
- if (!experimentId && !armId && !allocationVersion && !goalId && bucket === undefined)
439
- return undefined;
440
- if (!experimentId)
441
- throw new CollectValidationError('experiment.experimentId is required when experiment context is present');
442
- if (!armId)
443
- throw new CollectValidationError('experiment.armId is required when experiment context is present');
444
- if (bucket !== undefined && (!Number.isInteger(bucket) || Number(bucket) < 0 || Number(bucket) > 9999)) {
445
- throw new CollectValidationError('experiment.assignmentBucket must be between 0 and 9999');
446
- }
447
- return {
448
- experimentId,
449
- armId,
450
- ...(allocationVersion ? { allocationVersion } : {}),
451
- ...(goalId ? { goalId } : {}),
452
- ...(bucket !== undefined ? { assignmentBucket: bucket } : {}),
453
- };
454
- }
455
- function shortOptionalString(value, field) {
456
- if (value === undefined || value === null)
457
- return '';
458
- if (typeof value !== 'string')
459
- throw new CollectValidationError(`${field} must be a string`);
460
- return sanitizeString(value, field, 128);
461
- }
462
- function accepted(headers) {
463
- return new Response('{"accepted":true}', { status: 202, headers });
464
- }
465
- function validationResponse(error) {
466
- const message = error instanceof CollectValidationError ? error.message : 'invalid JSON body';
467
- return Response.json({ error: message, status: 400 }, { status: 400, headers: { 'cache-control': 'no-store' } });
468
- }
469
- function claimsCookie(value, secure) {
470
- return `aci_claims=${value}; Path=/; HttpOnly; SameSite=Lax; Max-Age=86400${secure ? '; Secure' : ''}`;
471
- }
472
- function expiredClaimsCookie(secure) {
473
- return `aci_claims=; Path=/; HttpOnly; SameSite=Lax; Max-Age=0; Expires=Thu, 01 Jan 1970 00:00:00 GMT${secure ? '; Secure' : ''}`;
474
- }
475
- function appendCookie(headers, cookie) {
476
- headers.append('set-cookie', cookie);
477
- }
478
- class CollectValidationError extends Error {
479
- }
@@ -1,21 +0,0 @@
1
- export interface EnvelopeDigestInput {
2
- siteId: string;
3
- acceptedBody: Uint8Array;
4
- identity: {
5
- namespace: string;
6
- hash: string;
7
- };
8
- consent: {
9
- version: number;
10
- purposes: readonly string[];
11
- grantedAt?: string;
12
- source?: string;
13
- };
14
- }
15
- /**
16
- * Computes the cross-runtime digest used to distinguish an identical
17
- * envelope retry from reuse of the same envelope ID with different accepted
18
- * inputs. Every field is framed with an unsigned 8-byte big-endian length so
19
- * concatenation cannot create ambiguous inputs.
20
- */
21
- export declare function computeEnvelopeDigest(input: EnvelopeDigestInput): Promise<string>;
@@ -1,58 +0,0 @@
1
- const ENVELOPE_DIGEST_ALGORITHM = 'aci-envelope-digest-v1';
2
- const RFC3339 = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2})(?:\.(\d{1,9}))?(Z|[+-]\d{2}:\d{2})$/;
3
- const encoder = new TextEncoder();
4
- const CONSENT_EDGE_WHITESPACE = /^[\t\n\v\f\r ]+|[\t\n\v\f\r ]+$/g;
5
- /**
6
- * Computes the cross-runtime digest used to distinguish an identical
7
- * envelope retry from reuse of the same envelope ID with different accepted
8
- * inputs. Every field is framed with an unsigned 8-byte big-endian length so
9
- * concatenation cannot create ambiguous inputs.
10
- */
11
- export async function computeEnvelopeDigest(input) {
12
- if (!Number.isInteger(input.consent.version)) {
13
- throw new Error('consent version must be an integer');
14
- }
15
- const purposes = input.consent.purposes
16
- .map((purpose) => trimConsentWhitespace(purpose).toLowerCase())
17
- .sort();
18
- const fields = [
19
- encoder.encode(ENVELOPE_DIGEST_ALGORITHM),
20
- encoder.encode(input.siteId.trim()),
21
- input.acceptedBody,
22
- encoder.encode(input.identity.namespace.trim()),
23
- encoder.encode(input.identity.hash.trim()),
24
- encoder.encode(String(input.consent.version)),
25
- encoder.encode(String(purposes.length)),
26
- ...purposes.map((purpose) => encoder.encode(purpose)),
27
- encoder.encode(canonicalGrantedAt(input.consent.grantedAt || '')),
28
- encoder.encode(trimConsentWhitespace(input.consent.source || '')),
29
- ];
30
- const byteLength = fields.reduce((total, field) => total + 8 + field.byteLength, 0);
31
- const framed = new Uint8Array(byteLength);
32
- const view = new DataView(framed.buffer);
33
- let offset = 0;
34
- for (const field of fields) {
35
- view.setBigUint64(offset, BigInt(field.byteLength), false);
36
- offset += 8;
37
- framed.set(field, offset);
38
- offset += field.byteLength;
39
- }
40
- const digest = await globalThis.crypto.subtle.digest('SHA-256', framed);
41
- return Array.from(new Uint8Array(digest), (byte) => byte.toString(16).padStart(2, '0')).join('');
42
- }
43
- function canonicalGrantedAt(value) {
44
- const clean = trimConsentWhitespace(value);
45
- if (!clean)
46
- return '';
47
- const match = RFC3339.exec(clean);
48
- const epochMillis = Date.parse(clean);
49
- if (!match || Number.isNaN(epochMillis)) {
50
- throw new Error('consent grantedAt must be an RFC3339 timestamp');
51
- }
52
- const fraction = (match[7] || '').replace(/0+$/, '');
53
- const seconds = new Date(epochMillis).toISOString().slice(0, 19);
54
- return `${seconds}${fraction ? `.${fraction}` : ''}Z`;
55
- }
56
- function trimConsentWhitespace(value) {
57
- return value.replace(CONSENT_EDGE_WHITESPACE, '');
58
- }