@wavebirdai/api 0.1.0-beta.1 → 0.1.0-beta.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/server.js CHANGED
@@ -1,47 +1,92 @@
1
+ import { Buffer } from "node:buffer";
1
2
  import { generationTransport } from "./generation.js";
3
+ export { createPublisherTurnJournal, derivePublisherTurnKeySecret } from "./turn-journal.js";
4
+ export { createPostgresTurnStorage } from "./postgres-turn-storage.js";
2
5
 
3
6
  const PREFERENCE_VERSION = "contextual-choice/v2";
4
7
  const PREFERENCE_TTL = 30 * 24 * 60 * 60;
5
8
  const MAX_PUBLISHER_BODY_BYTES = 16 * 1024;
6
9
  const MAX_WAVEBIRD_RESPONSE_BYTES = 256 * 1024;
7
10
  const MAX_PARALLEL_WAVEBIRD_REQUESTS = 2;
11
+ const MAX_ALLOWED_SIZES = 8;
12
+ const MAX_SIZE_EDGE = 4096;
13
+ const MAX_ENVELOPE_EDGE = 8192;
8
14
  const ID = /^[A-Za-z0-9_-]{1,128}$/;
9
15
  const JOB_ID = /^job_[A-Za-z0-9_-]{1,128}$/;
10
16
  const PLACEMENT_KEY = /^[a-z0-9][a-z0-9_-]{0,63}$/;
17
+ const SERVER_OPTION_KEYS = new Set(["apiBaseUrl", "clientId", "secretKey", "preferenceSecret", "authorize",
18
+ "sessionIdForRequest", "turnJournal", "onDiagnostic", "publicOrigins", "surfaceId", "placementKey",
19
+ "jobType", "locale", "timing", "consentMode", "gdprApplies", "publisher", "allowedFormats",
20
+ "positionHint", "maxWidth", "maxHeight", "allowedSizes", "responsiveSizeSelection", "bidfloor",
21
+ "bidfloorCurrency", "blockedCategories"]);
11
22
 
12
23
  function response(error, status, headers = {}) {
13
24
  return Response.json({ error }, { status, headers: { "Cache-Control": "no-store", ...headers } });
14
25
  }
15
26
 
16
27
  function normalizeOptions(options) {
17
- if (typeof window !== "undefined") throw new Error("publisher_server_only");
28
+ if (typeof document !== "undefined") throw new Error("publisher_server_only");
29
+ if (options && Object.keys(options).some(key => !SERVER_OPTION_KEYS.has(key))) throw new Error("publisher_option_unknown");
18
30
  if (!options || typeof options.authorize !== "function") throw new Error("publisher_authorize_required");
19
- if (!String(options.clientId || "").startsWith("wbproj_")) throw new Error("publisher_project_invalid");
20
- if (!String(options.secretKey || "").trim()) throw new Error("publisher_server_key_required");
21
- if (!ID.test(options.surfaceId || "") || !PLACEMENT_KEY.test(options.placementKey || "")) throw new Error("publisher_placement_invalid");
31
+ if (typeof options.preferenceSecret !== "string" || new TextEncoder().encode(options.preferenceSecret).byteLength < 32) throw new Error("preference_secret_required");
32
+ if ((options.turnJournal === undefined) !== (options.sessionIdForRequest === undefined) ||
33
+ (options.turnJournal !== undefined && (typeof options.sessionIdForRequest !== "function" ||
34
+ ["claimPlacement", "releaseRejectedPlacement", "bind", "claimGeneration", "phase"].some(name => typeof options.turnJournal?.[name] !== "function"))))
35
+ throw new Error("publisher_turn_journal_invalid");
36
+ if (typeof options.clientId !== "string" || !options.clientId.startsWith("wbproj_")) throw new Error("publisher_project_invalid");
37
+ if (typeof options.secretKey !== "string") throw new Error("publisher_server_key_invalid");
38
+ if (!options.secretKey.trim()) throw new Error("publisher_server_key_required");
39
+ if (!/^sk_(?:test|live)_/.test(options.secretKey)) throw new Error("publisher_server_key_invalid");
40
+ if (typeof options.surfaceId !== "string" || typeof options.placementKey !== "string" || !ID.test(options.surfaceId) || !PLACEMENT_KEY.test(options.placementKey)) throw new Error("publisher_placement_invalid");
22
41
  if (!["before", "during", "after"].includes(options.timing)) throw new Error("publisher_timing_invalid");
23
42
  if (!["wavebird_consent", "own_cmp"].includes(options.consentMode)) throw new Error("publisher_consent_mode_invalid");
24
- if (!Array.isArray(options.allowedFormats) || options.allowedFormats.length === 0 || options.allowedFormats.some(value => !["banner", "native"].includes(value))) throw new Error("publisher_formats_invalid");
43
+ if (options.gdprApplies !== undefined && typeof options.gdprApplies !== "boolean") throw new Error("publisher_gdpr_invalid");
44
+ if (!Array.isArray(options.allowedFormats) || options.allowedFormats.length === 0 || options.allowedFormats.some(value => !["banner", "native", "clip"].includes(value))) throw new Error("publisher_formats_invalid");
25
45
  if (!["above", "below", "sidebar", "between"].includes(options.positionHint)) throw new Error("publisher_position_invalid");
26
- if (!Number.isSafeInteger(options.maxWidth) || options.maxWidth < 1 || !Number.isSafeInteger(options.maxHeight) || options.maxHeight < 1) throw new Error("publisher_envelope_invalid");
27
- if (!Array.isArray(options.allowedSizes) || options.allowedSizes.length === 0 || options.allowedSizes.some(size => !Number.isSafeInteger(size.width) || !Number.isSafeInteger(size.height) || size.width < 1 || size.height < 1 || size.width > options.maxWidth || size.height > options.maxHeight ||
46
+ if (!Array.isArray(options.allowedSizes) || options.allowedSizes.length === 0 || options.allowedSizes.length > MAX_ALLOWED_SIZES || options.allowedSizes.some(size => !size || typeof size !== "object" || Object.keys(size).some(key => !["width", "height", "formats"].includes(key)) || !Number.isSafeInteger(size.width) || !Number.isSafeInteger(size.height) || size.width < 1 || size.height < 1 || size.width > MAX_SIZE_EDGE || size.height > MAX_SIZE_EDGE ||
28
47
  (size.formats !== undefined && (!Array.isArray(size.formats) || size.formats.length === 0 || size.formats.some(format => !options.allowedFormats.includes(format)))))) throw new Error("publisher_sizes_invalid");
48
+ if (new Set(options.allowedSizes.map(size => `${size.width}x${size.height}`)).size !== options.allowedSizes.length)
49
+ throw new Error("publisher_sizes_invalid");
50
+ const maxWidth = options.maxWidth === undefined ? options.allowedSizes.reduce((max, size) => Math.max(max, size.width), 0) : options.maxWidth;
51
+ const maxHeight = options.maxHeight === undefined ? options.allowedSizes.reduce((max, size) => Math.max(max, size.height), 0) : options.maxHeight;
52
+ if (!Number.isSafeInteger(maxWidth) || maxWidth < 1 || maxWidth > MAX_ENVELOPE_EDGE ||
53
+ !Number.isSafeInteger(maxHeight) || maxHeight < 1 || maxHeight > MAX_ENVELOPE_EDGE)
54
+ throw new Error("publisher_envelope_invalid");
55
+ const eligibleSizes = options.allowedSizes.filter(size => size.width <= maxWidth && size.height <= maxHeight);
56
+ const hasFloor = Object.hasOwn(options, "bidfloor");
57
+ const hasCurrency = Object.hasOwn(options, "bidfloorCurrency");
58
+ if (hasFloor !== hasCurrency || (hasFloor && (!Number.isFinite(options.bidfloor) || options.bidfloor < 0 || typeof options.bidfloorCurrency !== "string" || !/^[A-Za-z]{3}$/.test(options.bidfloorCurrency))))
59
+ throw new Error("publisher_bidfloor_override_invalid");
29
60
  if (options.responsiveSizeSelection !== undefined && typeof options.responsiveSizeSelection !== "boolean") throw new Error("publisher_responsive_selection_invalid");
30
- if (!options.publisher || typeof options.publisher.app_name !== "string" || typeof options.publisher.app_domain !== "string" || !Array.isArray(options.publisher.categories)) throw new Error("publisher_identity_invalid");
31
- if (typeof options.jobType !== "string" || !options.jobType || typeof options.locale !== "string" || !options.locale) throw new Error("publisher_job_invalid");
32
- const base = String(options.apiBaseUrl || "https://api.wavebird.ai").trim().replace(/\/+$/, "").replace(/\/v1$/, "") + "/v1";
33
- if (!/^https:\/\//.test(base)) throw new Error("publisher_api_https_required");
61
+ if (!options.publisher || typeof options.publisher !== "object" || Object.keys(options.publisher).some(key => !["app_name", "app_domain", "categories"].includes(key)) ||
62
+ typeof options.publisher.app_name !== "string" || !options.publisher.app_name.trim() ||
63
+ typeof options.publisher.app_domain !== "string" || !options.publisher.app_domain.trim() ||
64
+ !Array.isArray(options.publisher.categories) ||
65
+ options.publisher.categories.some(value => typeof value !== "string" || !value.trim())) throw new Error("publisher_identity_invalid");
66
+ if (options.blockedCategories !== undefined && (!Array.isArray(options.blockedCategories) ||
67
+ options.blockedCategories.some(value => typeof value !== "string" || !value.trim())))
68
+ throw new Error("publisher_blocked_categories_invalid");
69
+ if (!["chat", "code", "image", "voice", "agent"].includes(options.jobType) || typeof options.locale !== "string" || !options.locale) throw new Error("publisher_job_invalid");
70
+ const apiBaseUrl = options.apiBaseUrl === undefined ? "https://api.wavebird.ai" : options.apiBaseUrl;
71
+ if (typeof apiBaseUrl !== "string" || !apiBaseUrl.trim() || /[\\?#]/.test(apiBaseUrl)) throw new Error("publisher_api_https_required");
72
+ const endpoint = apiBaseUrl.trim();
73
+ let parsedEndpoint;
74
+ try { parsedEndpoint = new URL(endpoint); } catch { throw new Error("publisher_api_https_required"); }
75
+ if (parsedEndpoint.protocol !== "https:" || !parsedEndpoint.hostname || parsedEndpoint.username || parsedEndpoint.password ||
76
+ parsedEndpoint.search || parsedEndpoint.hash) throw new Error("publisher_api_https_required");
77
+ const base = endpoint.replace(/\/+$/, "").replace(/\/v1$/, "") + "/v1";
34
78
  {
35
79
  if (!Array.isArray(options.publicOrigins) || options.publicOrigins.length < 1 || options.publicOrigins.length > 8) throw new Error("publisher_public_origins_invalid");
36
80
  for (const origin of options.publicOrigins) {
37
81
  let url;
38
82
  try { url = new URL(origin); } catch { throw new Error("publisher_public_origins_invalid"); }
39
83
  const loopback = url.hostname === "localhost" || url.hostname === "127.0.0.1";
40
- if (url.origin !== origin || (url.protocol !== "https:" && !(loopback && url.protocol === "http:"))) throw new Error("publisher_public_origins_invalid");
84
+ if (url.origin !== origin || (url.protocol !== "https:" && !(loopback && url.protocol === "http:" && options.secretKey.startsWith("sk_test_")))) throw new Error("publisher_public_origins_invalid");
41
85
  }
42
86
  if (new Set(options.publicOrigins).size !== options.publicOrigins.length) throw new Error("publisher_public_origins_invalid");
43
87
  }
44
- return { ...options, base, consentSource: options.consentMode === "wavebird_consent" ? "wavebird_consent" : "wrapper_cmp" };
88
+ return { ...options, allowedSizes: eligibleSizes, maxWidth, maxHeight, base,
89
+ consentSource: options.consentMode === "wavebird_consent" ? "wavebird_consent" : "wrapper_cmp" };
45
90
  }
46
91
 
47
92
  function publicOrigin(request, options) {
@@ -163,12 +208,17 @@ function boundedGenerationReporter() {
163
208
  };
164
209
  }
165
210
 
166
- function observeGeneration(response, request, onLifecycle) {
167
- if (typeof onLifecycle !== "function" || response.headers.get("x-wavebird-generation-transport") !== "1" || !response.body) return response;
211
+ function observeGeneration(response, request, onLifecycle, onCritical) {
212
+ if (typeof onLifecycle !== "function" && typeof onCritical !== "function") return response;
213
+ if (response.headers.get("x-wavebird-generation-transport") !== "1" || !response.body) return response;
168
214
  const reader = response.body.getReader();
169
215
  const decoder = new TextDecoder();
170
216
  let terminal = false;
171
- const notify = event => {
217
+ const notify = async event => {
218
+ if (typeof onCritical === "function") {
219
+ try { await onCritical(event); } catch {}
220
+ }
221
+ if (typeof onLifecycle !== "function") return;
172
222
  try { Promise.resolve(onLifecycle(event)).catch(() => {}); } catch {}
173
223
  };
174
224
  const body = new ReadableStream({
@@ -181,7 +231,7 @@ function observeGeneration(response, request, onLifecycle) {
181
231
  const record = JSON.parse(decoder.decode(next.value));
182
232
  if (["started", "done", "error", "abort"].includes(record.type)) {
183
233
  if (record.type !== "started") terminal = true;
184
- notify({ type: record.type, sessionId: record.session_id, generationId: record.generation_id });
234
+ await notify({ type: record.type, sessionId: record.session_id, generationId: record.generation_id });
185
235
  }
186
236
  } catch {}
187
237
  controller.enqueue(next.value);
@@ -190,7 +240,7 @@ function observeGeneration(response, request, onLifecycle) {
190
240
  async cancel(reason) {
191
241
  if (!terminal) {
192
242
  terminal = true;
193
- notify({ type: "abort", sessionId: request.headers.get("x-wavebird-session-id"), generationId: request.headers.get("x-wavebird-generation-id") });
243
+ await notify({ type: "abort", sessionId: request.headers.get("x-wavebird-session-id"), generationId: request.headers.get("x-wavebird-generation-id") });
194
244
  }
195
245
  try { await reader.cancel(reason); } catch {}
196
246
  }
@@ -203,12 +253,40 @@ export function createPublisherServer(inputOptions) {
203
253
  const placementFetch = boundedFetcher();
204
254
  const consentFetch = boundedFetcher();
205
255
  const generationReportFetch = boundedGenerationReporter();
256
+ const diagnostic = code => { try { options.onDiagnostic?.(code); } catch {} };
257
+ if (typeof options.turnJournal?.reconcilePending === "function") {
258
+ void Promise.resolve().then(() => options.turnJournal.reconcilePending(options.clientId, options.surfaceId))
259
+ .catch(() => diagnostic("turn_journal_unavailable"));
260
+ }
261
+ async function journalCall(operation) {
262
+ let timer;
263
+ try { return await Promise.race([
264
+ Promise.resolve().then(operation),
265
+ new Promise((_, reject) => { timer = setTimeout(() => reject(new Error("turn_journal_timeout")), 1500); })
266
+ ]); } finally { clearTimeout(timer); }
267
+ }
268
+ async function trustedTurn(request, sessionId, turnId) {
269
+ if (!ID.test(sessionId || "") || !ID.test(turnId || "")) return null;
270
+ let trusted;
271
+ try { trusted = await journalCall(() => options.sessionIdForRequest(request)); } catch { return null; }
272
+ return trusted === sessionId ? { projectId: options.clientId, surfaceId: options.surfaceId, sessionId, turnId } : null;
273
+ }
274
+ async function sessionGET(request) {
275
+ if (!options.turnJournal) return response("turn_binding_unavailable", 404);
276
+ if (!await authorized(request)) return response("authentication_required", 401);
277
+ if (!validOrigin(request, options, false)) return response("invalid_origin", 403);
278
+ let sessionId;
279
+ try { sessionId = await journalCall(() => options.sessionIdForRequest(request)); }
280
+ catch { diagnostic("publisher_session_unavailable"); return response("publisher_session_unavailable", 503); }
281
+ if (!ID.test(sessionId || "")) return response("publisher_session_unavailable", 401);
282
+ return Response.json({ session_id: sessionId }, { headers: { "Cache-Control": "no-store", Vary: "Cookie" } });
283
+ }
206
284
  const cookieName = `__Host-wavebird-preference-${options.clientId}-${options.surfaceId}`;
207
285
  const cookie = (value, ttl = PREFERENCE_TTL) => `${cookieName}=${value}; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=${ttl}`;
208
286
  const scope = request => ({ project: options.clientId, surface: options.surfaceId, version: PREFERENCE_VERSION,
209
287
  profile: options.consentMode === "wavebird_consent" ? "wavebird_dialog" : "publisher_custom", origin: publicOrigin(request, options) });
210
288
  async function preferenceKey() {
211
- if (!options.preferenceSecret || options.preferenceSecret.length < 32) throw new Error("preference_secret_required");
289
+ if (new TextEncoder().encode(options.preferenceSecret).byteLength < 32) throw new Error("preference_secret_required");
212
290
  return crypto.subtle.importKey("raw", new TextEncoder().encode(options.preferenceSecret), { name: "HMAC", hash: "SHA-256" }, false, ["sign", "verify"]);
213
291
  }
214
292
  async function signPreference(request, state) {
@@ -229,11 +307,14 @@ export function createPublisherServer(inputOptions) {
229
307
  if (qaOutcomes.length && !options.secretKey.startsWith("sk_test_")) return response("qa_test_outcome_requires_test_key", 403);
230
308
  const input = await readPublisherJson(request);
231
309
  if (input instanceof Response) return input;
310
+ const turn = options.turnJournal ? await trustedTurn(request, input?.session_id, input?.turn_id) : null;
311
+ if (options.turnJournal && !turn) return response("publisher_turn_context_invalid", 401);
232
312
  let allowedSizes = options.allowedSizes.map(({ width, height }) => ({ width, height }));
233
313
  let allowedFormats = options.allowedFormats;
234
314
  let maxWidth = options.maxWidth;
235
315
  let maxHeight = options.maxHeight;
236
- if (options.responsiveSizeSelection === true) {
316
+ const noFit = () => Response.json({ decision: { fill: false, reason: "no_fit" }, placement: null }, { headers: { "Cache-Control": "no-store" } });
317
+ if (options.responsiveSizeSelection !== false) {
237
318
  const bounds = input?.container_size;
238
319
  if (!bounds || !Number.isSafeInteger(bounds.width) || !Number.isSafeInteger(bounds.height) ||
239
320
  bounds.width < 1 || bounds.height < 1 || bounds.width > 8192 || bounds.height > 8192) {
@@ -241,10 +322,11 @@ export function createPublisherServer(inputOptions) {
241
322
  }
242
323
  const requestedFormat = input?.format ?? "auto";
243
324
  if (requestedFormat !== "auto" && !options.allowedFormats.includes(requestedFormat)) return response("publisher_format_invalid", 400);
325
+ if (allowedSizes.length === 0) return noFit();
244
326
  const fitting = options.allowedSizes.filter(size => size.width <= bounds.width && size.height <= bounds.height &&
245
327
  (requestedFormat === "auto" || (size.formats ?? options.allowedFormats).includes(requestedFormat)))
246
328
  .sort((a, b) => b.width - a.width || b.height - a.height);
247
- if (fitting.length === 0) return Response.json({ decision: { fill: false, reason: "no_fit" }, placement: null }, { headers: { "Cache-Control": "no-store" } });
329
+ if (fitting.length === 0) return noFit();
248
330
  const selected = fitting[0];
249
331
  allowedSizes = [{ width: selected.width, height: selected.height }];
250
332
  allowedFormats = requestedFormat === "auto"
@@ -253,6 +335,13 @@ export function createPublisherServer(inputOptions) {
253
335
  maxWidth = Math.min(maxWidth, bounds.width);
254
336
  maxHeight = Math.min(maxHeight, bounds.height);
255
337
  }
338
+ else if (allowedSizes.length === 0) return noFit();
339
+ if (turn) {
340
+ let claimed;
341
+ try { claimed = await journalCall(() => options.turnJournal.claimPlacement(turn)); }
342
+ catch { diagnostic("turn_journal_unavailable"); return response("turn_journal_unavailable", 503); }
343
+ if (!claimed) return response("publisher_turn_replayed", 409);
344
+ }
256
345
  const sessionId = typeof input?.session_id === "string" && input.session_id.trim() ? input.session_id.trim() : crypto.randomUUID();
257
346
  const body = {
258
347
  client_id: options.clientId, session_id: sessionId, job_type: options.jobType, locale: options.locale,
@@ -260,8 +349,7 @@ export function createPublisherServer(inputOptions) {
260
349
  slot_hint: { position: options.positionHint, max_width: maxWidth, max_height: maxHeight,
261
350
  allowed_sizes: allowedSizes, presentation_version: "sponsored_moment_v2" },
262
351
  overrides: { allowed_formats: allowedFormats, timing: options.timing,
263
- bidfloor: options.bidfloor ?? 0.5, bidfloor_currency: options.bidfloorCurrency ?? "EUR",
264
- gdpr_applies: options.gdprApplies === true,
352
+ ...(Object.hasOwn(options, "bidfloor") ? { bidfloor: options.bidfloor, bidfloor_currency: options.bidfloorCurrency.toUpperCase() } : {}),
265
353
  publisher: { app_name: options.publisher.app_name, app_domain: options.publisher.app_domain,
266
354
  ...(options.publisher.categories.length ? { categories: options.publisher.categories } : {}) },
267
355
  ...(options.blockedCategories?.length ? { blocked_categories: options.blockedCategories } : {}) },
@@ -269,9 +357,27 @@ export function createPublisherServer(inputOptions) {
269
357
  consent_source: options.consentSource }
270
358
  };
271
359
  try {
272
- return await placementFetch(`${options.base}/placements?wait_ms=1500${qaOutcomes.length ? "&test_outcome=no_fill" : ""}`, { method: "POST", headers: {
360
+ const result = await placementFetch(`${options.base}/placements?wait_ms=1500${qaOutcomes.length ? "&test_outcome=no_fill" : ""}`, { method: "POST", headers: {
273
361
  Authorization: `Bearer ${options.secretKey}`, "Content-Type": "application/json"
274
362
  }, body: JSON.stringify(body), cache: "no-store" });
363
+ if (turn && [400, 401, 403].includes(result.status)) {
364
+ try { await journalCall(() => options.turnJournal.releaseRejectedPlacement(turn)); }
365
+ catch { diagnostic("turn_journal_unavailable"); }
366
+ }
367
+ if (turn && result.status === 200) {
368
+ let payload;
369
+ try { payload = await result.clone().json(); } catch {}
370
+ const jobId = payload?.job_id;
371
+ if (JOB_ID.test(jobId || "")) {
372
+ try { await journalCall(() => options.turnJournal.bind(turn, jobId)); }
373
+ catch { diagnostic("turn_binding_unavailable"); return response("turn_binding_unavailable", 502); }
374
+ } else if (!(payload?.decision?.fill === false &&
375
+ Object.hasOwn(payload ?? {}, "placement") && payload.placement === null)) {
376
+ diagnostic("turn_binding_unavailable");
377
+ return response("turn_binding_unavailable", 502);
378
+ }
379
+ }
380
+ return result;
275
381
  } catch { return response("wavebird_placement_unavailable", 502); }
276
382
  }
277
383
  async function consentGET(request) {
@@ -336,8 +442,24 @@ export function createPublisherServer(inputOptions) {
336
442
  async function withGeneration({ request, run, onLifecycle }) {
337
443
  if (!await authorized(request)) return response("authentication_required", 401);
338
444
  if (!validOrigin(request, options)) return response("invalid_origin", 403);
445
+ const turn = options.turnJournal ? await trustedTurn(request,
446
+ request.headers.get("x-wavebird-session-id"), request.headers.get("x-wavebird-generation-id")) : null;
447
+ if (options.turnJournal && !turn) return response("publisher_turn_context_invalid", 401);
448
+ if (turn) {
449
+ let claimed;
450
+ try { claimed = await journalCall(() => options.turnJournal.claimGeneration(turn)); }
451
+ catch { diagnostic("turn_journal_unavailable"); return run(request.signal); }
452
+ if (!claimed) return response("publisher_turn_replayed", 409);
453
+ try { await journalCall(() => options.turnJournal.phase(turn, "started")); }
454
+ catch { diagnostic("turn_journal_unavailable"); return run(request.signal); }
455
+ }
339
456
  const result = await generationTransport({ request, run });
340
- return observeGeneration(result, request, onLifecycle);
457
+ const critical = turn ? async event => {
458
+ if (event.type === "started") return;
459
+ try { await journalCall(() => options.turnJournal.phase(turn, event.type === "done" ? "finished" : "failed")); }
460
+ catch { diagnostic("turn_journal_unavailable"); }
461
+ } : null;
462
+ return observeGeneration(result, request, onLifecycle, critical);
341
463
  }
342
464
  async function reportGeneration(jobId, event) {
343
465
  if (!JOB_ID.test(jobId) || !["started", "finished", "failed"].includes(event)) throw new Error("invalid_generation_report");
@@ -345,5 +467,5 @@ export function createPublisherServer(inputOptions) {
345
467
  method: "POST", headers: { Authorization: `Bearer ${options.secretKey}`, "Content-Type": "application/json" }, body: "{}"
346
468
  });
347
469
  }
348
- return { placementPOST, consentGET, consentPOST, withGeneration, reportGeneration };
470
+ return { sessionGET, placementPOST, consentGET, consentPOST, withGeneration, reportGeneration };
349
471
  }
@@ -0,0 +1,155 @@
1
+ import { Buffer } from "node:buffer";
2
+ import { createHash, createHmac, randomUUID } from "node:crypto";
3
+
4
+ const ID = /^[A-Za-z0-9_-]{1,128}$/;
5
+ const JOB_ID = /^job_[A-Za-z0-9_-]{1,128}$/;
6
+
7
+ /** Domain-separate the stable server preference secret for pseudonymous turn keys. */
8
+ export function derivePublisherTurnKeySecret(preferenceSecret) {
9
+ if (typeof preferenceSecret !== "string" || Buffer.byteLength(preferenceSecret, "utf8") < 32)
10
+ throw new Error("publisher_preference_secret_invalid");
11
+ return createHmac("sha256", preferenceSecret).update("wavebird/turn-journal-key/v1").digest("hex");
12
+ }
13
+
14
+ /** Package-owned state machine over a publisher's existing atomic, durable store. */
15
+ export function createPublisherTurnJournal({ storage, reportGeneration, keySecret, onDiagnostic }) {
16
+ if (typeof storage?.atomic !== "function" || typeof storage?.scan !== "function" ||
17
+ typeof reportGeneration !== "function") throw new Error("publisher_turn_storage_invalid");
18
+ if (typeof keySecret !== "string" || Buffer.byteLength(keySecret, "utf8") < 32)
19
+ throw new Error("publisher_turn_key_secret_invalid");
20
+ const tasks = new Set();
21
+ let activeReports = 0;
22
+ const reportWaiters = [];
23
+ const diagnostic = code => { try { onDiagnostic?.(code); } catch {} };
24
+ const verifiedScopes = new Set();
25
+ const versionKey = createHash("sha256").update("wavebird/turn-journal-version-row/v1").digest("hex");
26
+ const keyFingerprint = createHmac("sha256", keySecret).update("wavebird/turn-journal-key-version/v1").digest("hex");
27
+ async function verifyKeyVersion(scope) {
28
+ if (verifiedScopes.has(scope)) return;
29
+ // A separate scope keeps this guard outside ordinary turn retention pruning.
30
+ const versionScope = createHash("sha256").update(JSON.stringify(["wavebird/turn-journal-meta/v1", scope])).digest("hex");
31
+ await storage.atomic(versionScope, versionKey, previous => {
32
+ if (previous && previous.keyFingerprint !== keyFingerprint)
33
+ throw new Error("publisher_turn_key_version_conflict");
34
+ return { state: previous || { keyFingerprint }, result: null };
35
+ });
36
+ verifiedScopes.add(scope);
37
+ }
38
+ function identity(turn) {
39
+ if (![turn?.projectId, turn?.surfaceId, turn?.sessionId, turn?.turnId].every(value => ID.test(value || "")))
40
+ throw new Error("publisher_turn_context_invalid");
41
+ const scope = createHash("sha256").update(JSON.stringify([turn.projectId, turn.surfaceId])).digest("hex");
42
+ const key = createHmac("sha256", keySecret).update(JSON.stringify([turn.projectId, turn.surfaceId, turn.sessionId, turn.turnId])).digest("hex");
43
+ return { scope, key };
44
+ }
45
+ function initial(scope) {
46
+ return { scope, createdAtMs: Date.now(), placementClaimed: false, generationClaimed: false,
47
+ jobId: null, phase: "idle", startedReported: false, terminalReported: false,
48
+ leaseId: null, leaseUntilMs: 0 };
49
+ }
50
+ async function change(turn, update) {
51
+ const { scope, key } = identity(turn);
52
+ await verifyKeyVersion(scope);
53
+ return storage.atomic(scope, key, previous => {
54
+ if (previous && previous.scope !== scope) throw new Error("publisher_turn_scope_conflict");
55
+ const state = { ...(previous || initial(scope)) };
56
+ const result = update(state);
57
+ return { state, result };
58
+ });
59
+ }
60
+ async function claimPlacement(turn) {
61
+ return change(turn, state => {
62
+ if (state.placementClaimed) return false;
63
+ state.placementClaimed = true;
64
+ return true;
65
+ });
66
+ }
67
+ async function releaseRejectedPlacement(turn) {
68
+ await change(turn, state => { if (!state.jobId) state.placementClaimed = false; });
69
+ }
70
+ async function claimGeneration(turn) {
71
+ return change(turn, state => {
72
+ if (state.generationClaimed) return false;
73
+ state.generationClaimed = true;
74
+ return true;
75
+ });
76
+ }
77
+ function schedule(scope, key) {
78
+ const task = drain(scope, key).catch(() => diagnostic("turn_journal_unavailable"));
79
+ tasks.add(task);
80
+ void task.finally(() => tasks.delete(task));
81
+ }
82
+ async function bind(turn, jobId) {
83
+ if (!JOB_ID.test(jobId || "")) throw new Error("publisher_job_id_invalid");
84
+ const { scope, key } = identity(turn);
85
+ const bound = await change(turn, state => {
86
+ if (!state.placementClaimed || state.jobId && state.jobId !== jobId) return false;
87
+ state.jobId = jobId;
88
+ return true;
89
+ });
90
+ if (!bound) throw new Error("publisher_turn_job_conflict");
91
+ schedule(scope, key);
92
+ }
93
+ async function phase(turn, event) {
94
+ if (!["started", "finished", "failed"].includes(event)) throw new Error("publisher_phase_invalid");
95
+ const { scope, key } = identity(turn);
96
+ const changed = await change(turn, state => {
97
+ if (!state.generationClaimed || state.phase !== (event === "started" ? "idle" : "started")) return false;
98
+ state.phase = event;
99
+ return true;
100
+ });
101
+ if (changed) schedule(scope, key);
102
+ }
103
+ async function lease(scope, key) {
104
+ return storage.atomic(scope, key, previous => {
105
+ if (!previous || previous.scope !== scope || !previous.jobId || previous.phase === "idle" ||
106
+ previous.leaseUntilMs > Date.now()) return { state: previous, result: null };
107
+ const event = !previous.startedReported ? "started" :
108
+ ["finished", "failed"].includes(previous.phase) && !previous.terminalReported ? previous.phase : null;
109
+ if (!event) return { state: previous, result: null };
110
+ const leaseId = randomUUID();
111
+ return { state: { ...previous, leaseId, leaseUntilMs: Date.now() + 10_000 },
112
+ result: { jobId: previous.jobId, event, leaseId } };
113
+ });
114
+ }
115
+ async function ack(scope, key, event, leaseId, accepted) {
116
+ await storage.atomic(scope, key, previous => {
117
+ if (!previous || previous.scope !== scope || previous.leaseId !== leaseId)
118
+ return { state: previous, result: null };
119
+ const state = { ...previous, leaseId: null, leaseUntilMs: 0 };
120
+ if (accepted) state[event === "started" ? "startedReported" : "terminalReported"] = true;
121
+ return { state, result: null };
122
+ });
123
+ }
124
+ async function drain(scope, key) {
125
+ while (true) {
126
+ const next = await lease(scope, key);
127
+ if (!next) return;
128
+ if (activeReports >= 4) await new Promise(resolve => reportWaiters.push(resolve));
129
+ activeReports++;
130
+ let accepted = false;
131
+ try { await reportGeneration(next.jobId, next.event); accepted = true; }
132
+ catch { diagnostic("generation_report_unavailable"); }
133
+ finally { activeReports--; reportWaiters.shift()?.(); }
134
+ await ack(scope, key, next.event, next.leaseId, accepted);
135
+ if (!accepted) return;
136
+ }
137
+ }
138
+ async function reconcilePending(projectId, surfaceId) {
139
+ if (!ID.test(projectId || "") || !ID.test(surfaceId || "")) throw new Error("publisher_turn_scope_invalid");
140
+ const scope = createHash("sha256").update(JSON.stringify([projectId, surfaceId])).digest("hex");
141
+ if (typeof storage.prune === "function" && await storage.prune(scope) > 0)
142
+ diagnostic("generation_report_retention_expired");
143
+ let cursor = "";
144
+ while (true) {
145
+ const keys = await storage.scan(scope, cursor, 100);
146
+ if (!Array.isArray(keys) || keys.length > 100 || keys.some((key, index) => typeof key !== "string" ||
147
+ !/^[a-f0-9]{64}$/.test(key) || key <= (index ? keys[index - 1] : cursor)))
148
+ throw new Error("publisher_turn_scan_invalid");
149
+ if (keys.length === 0) return;
150
+ await Promise.all(keys.map(key => drain(scope, key)));
151
+ cursor = keys.at(-1);
152
+ }
153
+ }
154
+ return { claimPlacement, releaseRejectedPlacement, bind, claimGeneration, phase, reconcilePending };
155
+ }
@@ -0,0 +1,5 @@
1
+ import { getPublisher } from "../../../lib/publisher.js";
2
+
3
+ export async function GET(request) {
4
+ return getPublisher().sessionGET(request);
5
+ }
@@ -9,7 +9,15 @@ export default function Page() {
9
9
  const abort = useRef(null);
10
10
  const [answer, setAnswer] = useState("");
11
11
  useEffect(() => {
12
- const current = createPublisherAds({
12
+ if (!slot.current) return;
13
+ const controller = new AbortController();
14
+ let disposed = false;
15
+ let current = null;
16
+ void fetch("/api/sponsor-session", { cache: "no-store", signal: controller.signal }).then(async response => {
17
+ if (!response.ok) return;
18
+ const sessionId = (await response.json()).session_id;
19
+ if (disposed || !/^[A-Za-z0-9_-]{1,128}$/.test(sessionId)) return;
20
+ current = createPublisherAds({
13
21
  target: slot.current,
14
22
  clientId: "wbproj_replace_from_dashboard",
15
23
  surfaceId: "chat_assistant",
@@ -18,13 +26,16 @@ export default function Page() {
18
26
  consentMode: "wavebird_consent",
19
27
  userId: "replace-with-authenticated-user-id",
20
28
  conversationId: "replace-with-current-conversation-id",
29
+ sessionId,
30
+ turnBinding: true,
21
31
  rendererUrl: "https://api.wavebird.ai/v1/render.js",
22
32
  placementEndpoint: "/api/sponsor-slot",
23
33
  consentEndpoint: "/api/sponsor-consent",
24
34
  privacySettingsTarget: "#privacy-settings"
25
- });
26
- ads.current = current;
27
- return () => { abort.current?.abort(); current.dispose(); ads.current = null; };
35
+ });
36
+ ads.current = current;
37
+ }).catch(() => {});
38
+ return () => { disposed = true; controller.abort(); abort.current?.abort(); current?.dispose(); ads.current = null; };
28
39
  }, []);
29
40
  async function generate() {
30
41
  if (!ads.current) return;
@@ -1,12 +1,33 @@
1
+ import "server-only";
2
+
3
+ const cache = new WeakMap();
4
+ const ID = /^[A-Za-z0-9_-]{1,128}$/;
5
+
6
+ /** Resolve a non-credential correlation ID from the app's authenticated session. */
7
+ export function sessionIdForRequest(request) {
8
+ const prior = cache.get(request);
9
+ if (prior) return prior;
10
+ const pending = (async () => {
11
+ const path = process.env.PUBLISHER_AUTH_CHECK_PATH;
12
+ if (!path || !/^\/(?!\/)[A-Za-z0-9/_-]+$/.test(path) ||
13
+ path.startsWith("/api/sponsor") || path === "/api/generate") return null;
14
+ try {
15
+ const requestOrigin = new URL(request.url).origin;
16
+ const trustedOrigin = (process.env.WAVEBIRD_PUBLIC_ORIGINS ?? "").split(",")
17
+ .map(value => value.trim()).find(value => value === requestOrigin);
18
+ if (!trustedOrigin) return null;
19
+ const result = await fetch(new URL(path, trustedOrigin), {
20
+ headers: { cookie: request.headers.get("cookie") || "" },
21
+ cache: "no-store", redirect: "manual", signal: AbortSignal.timeout(1500),
22
+ });
23
+ const id = result.headers.get("x-publisher-session-id");
24
+ return result.status === 204 && ID.test(id || "") ? id : null;
25
+ } catch { return null; }
26
+ })();
27
+ cache.set(request, pending);
28
+ return pending;
29
+ }
30
+
1
31
  export async function authorizePublisherRequest(request) {
2
- const path = process.env.PUBLISHER_AUTH_CHECK_PATH;
3
- if (!path || !/^\/(?!\/)[A-Za-z0-9/_-]+$/.test(path) || path.startsWith("/api/sponsor") || path === "/api/generate") return false;
4
- try {
5
- const result = await fetch(new URL(path, request.url), {
6
- headers: { cookie: request.headers.get("cookie") || "" },
7
- cache: "no-store",
8
- redirect: "manual"
9
- });
10
- return result.status === 204;
11
- } catch { return false; }
32
+ return (await sessionIdForRequest(request)) !== null;
12
33
  }
@@ -1,16 +1,25 @@
1
1
  import "server-only";
2
- import { createPublisherServer } from "@wavebirdai/api/server";
3
- import { authorizePublisherRequest } from "./auth.js";
2
+ import { createPublisherServer, createPublisherTurnJournal, derivePublisherTurnKeySecret } from "@wavebirdai/api/server";
3
+ import { authorizePublisherRequest, sessionIdForRequest } from "./auth.js";
4
+ import { publisherTurnStorage } from "./turn-store.js";
4
5
 
5
6
  let publisher;
6
7
 
7
8
  export function getPublisher() {
8
- return publisher ??= createPublisherServer({
9
+ if (publisher) return publisher;
10
+ const turnJournal = createPublisherTurnJournal({
11
+ storage: publisherTurnStorage(),
12
+ keySecret: derivePublisherTurnKeySecret(process.env.WAVEBIRD_PREFERENCE_SECRET ?? ""),
13
+ reportGeneration: (jobId, event) => getPublisher().reportGeneration(jobId, event),
14
+ });
15
+ return publisher = createPublisherServer({
9
16
  apiBaseUrl: process.env.WAVEBIRD_API_BASE_URL,
10
17
  clientId: process.env.WAVEBIRD_CLIENT_ID,
11
18
  secretKey: process.env.WAVEBIRD_SECRET_KEY,
12
19
  preferenceSecret: process.env.WAVEBIRD_PREFERENCE_SECRET,
13
20
  authorize: authorizePublisherRequest,
21
+ sessionIdForRequest,
22
+ turnJournal,
14
23
  publicOrigins: (process.env.WAVEBIRD_PUBLIC_ORIGINS ?? "").split(",").map(value => value.trim()).filter(Boolean),
15
24
  surfaceId: "chat_assistant",
16
25
  placementKey: "default",
@@ -22,8 +31,6 @@ export function getPublisher() {
22
31
  publisher: { app_name: "Your saved app name", app_domain: "your.example", categories: [] },
23
32
  allowedFormats: ["banner"],
24
33
  positionHint: "between",
25
- maxWidth: 728,
26
- maxHeight: 90,
27
34
  allowedSizes: [{ width: 728, height: 90 }, { width: 320, height: 50 }],
28
35
  responsiveSizeSelection: true
29
36
  });
@@ -0,0 +1,9 @@
1
+ import "server-only";
2
+
3
+ /** Replace this fail-closed stub with createPostgresTurnStorage(your existing pg pool). */
4
+ export function publisherTurnStorage() {
5
+ return {
6
+ async atomic() { throw new Error("Connect your existing durable turn store"); },
7
+ async scan() { throw new Error("Connect your existing durable turn store"); },
8
+ };
9
+ }
@@ -0,0 +1,5 @@
1
+ import { getPublisher } from "../../../lib/publisher";
2
+
3
+ export async function GET(request: Request): Promise<Response> {
4
+ return getPublisher().sessionGET(request);
5
+ }