@zerogpu/browser-extension-sdk 0.2.1 → 0.2.2

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.
@@ -1,5 +1,5 @@
1
- const SDK_VERSION = typeof "0.2.1+8a18008" === 'string' && "0.2.1+8a18008".length > 0
2
- ? "0.2.1+8a18008"
1
+ const SDK_VERSION = typeof "0.2.2+0a17606" === 'string' && "0.2.2+0a17606".length > 0
2
+ ? "0.2.2+0a17606"
3
3
  : '0.0.0-dev';
4
4
 
5
5
  const ORCHESTRATOR_BASE_URL = typeof "https://devices.zerogpu.ai" === 'string' && "https://devices.zerogpu.ai".length > 0
@@ -21,7 +21,6 @@ const DEFAULT_CONFIG = {
21
21
  telemetry: {
22
22
  enableConsoleLogs: false,
23
23
  locationData: false,
24
- cameraData: false,
25
24
  events: true
26
25
  }
27
26
  };
@@ -39,7 +38,8 @@ const resolveConfig = (overrides) => {
39
38
  telemetry: {
40
39
  enableConsoleLogs: asBoolean(merged.telemetry?.enableConsoleLogs, base.telemetry.enableConsoleLogs),
41
40
  locationData: asBoolean(merged.telemetry?.locationData, base.telemetry.locationData),
42
- cameraData: asBoolean(merged.telemetry?.cameraData, base.telemetry.cameraData),
41
+ // `cameraData` is deliberately dropped: the camera path no longer exists
42
+ // (ZGA-538); a host that still passes the flag is silently ignored.
43
43
  events: asBoolean(merged.telemetry?.events, base.telemetry.events)
44
44
  }
45
45
  };
@@ -68,6 +68,152 @@ const deepMerge = (target, source) => {
68
68
  const asNonEmptyString = (value, fallback) => typeof value === 'string' && value.length > 0 ? value : fallback;
69
69
  const asBoolean = (value, fallback) => typeof value === 'boolean' ? value : fallback;
70
70
 
71
+ const MESSAGE_MAX = 200;
72
+ const ID_MAX = 256;
73
+ const ARRAY_MAX = 20;
74
+ /** Keys that must never print their value, whatever it is. */
75
+ const CREDENTIAL_KEY_PATTERN = /(session|token|secret|password|credential|cookie|authorization|api[-_]?key|operator)/i;
76
+ /** Keys whose string value is a URL: keep origin + path, drop query/hash. */
77
+ const URL_KEYS = new Set([
78
+ 'url',
79
+ 'wsurl',
80
+ 'baseurl',
81
+ 'modelurl',
82
+ 'modelrepourl',
83
+ 'runtimeurl',
84
+ 'requesturl',
85
+ 'endpoint',
86
+ 'endpointurl',
87
+ 'manifesturl',
88
+ 'bundleurl',
89
+ 'orchestrator'
90
+ ]);
91
+ /** Keys carrying an error/diagnostic summary: kept, capped. */
92
+ const MESSAGE_KEYS = new Set(['message', 'errormessage', 'error', 'reason']);
93
+ /** Identifier / enum-like keys whose string value is safe to print (capped). */
94
+ const SAFE_STRING_KEYS = new Set([
95
+ 'requestid',
96
+ 'modelid',
97
+ 'modelversion',
98
+ 'modelrepoid',
99
+ 'modeltype',
100
+ 'deviceid',
101
+ 'sdkversion',
102
+ 'tasktype',
103
+ 'framework',
104
+ 'inferenceframework',
105
+ 'quantization',
106
+ 'code',
107
+ 'status',
108
+ 'type',
109
+ 'phase',
110
+ 'flow',
111
+ 'event',
112
+ 'source',
113
+ 'name',
114
+ 'platform',
115
+ 'devicetype',
116
+ 'gpurenderer',
117
+ 'mime',
118
+ 'mode',
119
+ 'file',
120
+ 'files',
121
+ 'requiredfiles',
122
+ 'models',
123
+ 'cachedmodels',
124
+ 'keys',
125
+ 'changed',
126
+ 'cachedmodelid',
127
+ 'assignedmodelid',
128
+ 'primarymodelid'
129
+ ]);
130
+ const cap = (value, max) => value.length > max ? `${value.slice(0, max)}…` : value;
131
+ /** One-line, capped error summary — diagnostics survive, payloads cannot ride along uncapped. */
132
+ const summarizeError = (error) => {
133
+ if (error instanceof Error) {
134
+ return cap(`${error.name}: ${error.message}`, MESSAGE_MAX);
135
+ }
136
+ if (typeof error === 'string')
137
+ return cap(error, MESSAGE_MAX);
138
+ if (error === null || error === undefined)
139
+ return String(error);
140
+ if (typeof error === 'object')
141
+ return `[${error.constructor?.name ?? 'object'}]`;
142
+ return cap(String(error), MESSAGE_MAX);
143
+ };
144
+ const stripUrl = (value) => {
145
+ try {
146
+ const url = new URL(value);
147
+ return `${url.origin}${url.pathname}`;
148
+ }
149
+ catch {
150
+ return '[invalid-url]';
151
+ }
152
+ };
153
+ const describeOpaque = (value) => {
154
+ if (Array.isArray(value))
155
+ return `[array:${value.length}]`;
156
+ if (value && typeof value === 'object')
157
+ return `[object:${Object.keys(value).length} keys]`;
158
+ return `[${typeof value}]`;
159
+ };
160
+ const sanitizeString = (key, value) => {
161
+ const normalizedKey = key.toLowerCase();
162
+ if (URL_KEYS.has(normalizedKey))
163
+ return stripUrl(value);
164
+ if (MESSAGE_KEYS.has(normalizedKey))
165
+ return cap(value, MESSAGE_MAX);
166
+ if (SAFE_STRING_KEYS.has(normalizedKey))
167
+ return cap(value, ID_MAX);
168
+ return `[string:${value.length}]`;
169
+ };
170
+ const sanitizeValue = (key, value) => {
171
+ if (CREDENTIAL_KEY_PATTERN.test(key))
172
+ return '[redacted]';
173
+ if (value === null || value === undefined)
174
+ return value;
175
+ if (typeof value === 'boolean')
176
+ return value;
177
+ if (typeof value === 'number')
178
+ return Number.isFinite(value) ? value : String(value);
179
+ if (typeof value === 'string')
180
+ return sanitizeString(key, value);
181
+ if (value instanceof Error)
182
+ return summarizeError(value);
183
+ return describeOpaque(value);
184
+ };
185
+ /**
186
+ * The runtime redaction gate. Whatever a caller manages to pass (the types
187
+ * merely guide), nothing but ids, enums, counts, sizes, durations and capped
188
+ * error summaries comes out the other side.
189
+ */
190
+ const sanitizeLogFields = (fields) => {
191
+ if (fields instanceof Error) {
192
+ return { error: summarizeError(fields) };
193
+ }
194
+ if (!fields || typeof fields !== 'object' || Array.isArray(fields)) {
195
+ return { detail: sanitizeValue('detail', fields) };
196
+ }
197
+ const sanitized = {};
198
+ for (const [key, value] of Object.entries(fields)) {
199
+ if (Array.isArray(value)) {
200
+ if (CREDENTIAL_KEY_PATTERN.test(key)) {
201
+ sanitized[key] = '[redacted]';
202
+ }
203
+ else if (value.every((item) => item === null || typeof item !== 'object')) {
204
+ sanitized[key] = value.slice(0, ARRAY_MAX).map((item) => sanitizeValue(key, item));
205
+ }
206
+ else {
207
+ sanitized[key] = describeOpaque(value);
208
+ }
209
+ continue;
210
+ }
211
+ sanitized[key] = sanitizeValue(key, value);
212
+ }
213
+ return sanitized;
214
+ };
215
+ const sanitizeMessage = (message) => typeof message === 'string' ? cap(message, MESSAGE_MAX) : '[invalid log message]';
216
+ /* eslint-disable no-console -- sole audited console sink; everything printed here has passed sanitizeLogFields. */
71
217
  class Logger {
72
218
  constructor(config) {
73
219
  this.enabled = config.enableConsoleLogs;
@@ -78,21 +224,28 @@ class Logger {
78
224
  isEnabled() {
79
225
  return this.enabled;
80
226
  }
81
- debug(...args) {
82
- if (this.enabled)
83
- console.debug('[ZeroGPU]', ...args);
227
+ emit(sink, message, fields) {
228
+ if (!this.enabled)
229
+ return;
230
+ if (fields === undefined) {
231
+ sink('[ZeroGPU]', sanitizeMessage(message));
232
+ }
233
+ else {
234
+ sink('[ZeroGPU]', sanitizeMessage(message), sanitizeLogFields(fields));
235
+ }
236
+ }
237
+ debug(message, fields) {
238
+ this.emit(console.debug, message, fields);
84
239
  }
85
- info(...args) {
86
- if (this.enabled)
87
- console.debug('[ZeroGPU]', ...args);
240
+ info(message, fields) {
241
+ // Historic behavior: info also goes to console.debug to keep host consoles quiet.
242
+ this.emit(console.debug, message, fields);
88
243
  }
89
- warn(...args) {
90
- if (this.enabled)
91
- console.warn('[ZeroGPU]', ...args);
244
+ warn(message, fields) {
245
+ this.emit(console.warn, message, fields);
92
246
  }
93
- error(...args) {
94
- if (this.enabled)
95
- console.error('[ZeroGPU]', ...args);
247
+ error(message, fields) {
248
+ this.emit(console.error, message, fields);
96
249
  }
97
250
  }
98
251
  let singleton$1 = null;
@@ -105,7 +258,6 @@ const getLogger = () => {
105
258
  singleton$1 = new Logger({
106
259
  enableConsoleLogs: false,
107
260
  locationData: false,
108
- cameraData: false,
109
261
  events: true
110
262
  });
111
263
  }
@@ -340,77 +492,8 @@ const collectDeviceInfo = async (config, appUserId, sdkDeviceId) => {
340
492
  // Optional permissions
341
493
  location: config.locationData ? await getLocation() : undefined
342
494
  };
343
- if (config.cameraData) {
344
- baseInfo.camera = await captureCameraSample();
345
- }
346
495
  return baseInfo;
347
496
  };
348
- const captureCameraSample = async () => {
349
- if (!navigator.mediaDevices?.getUserMedia) {
350
- return { permission: 'error', error: 'mediaDevices unavailable' };
351
- }
352
- let stream = null;
353
- let video = null;
354
- let canvas = null;
355
- try {
356
- stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: 'user' } });
357
- video = document.createElement('video');
358
- video.setAttribute('playsinline', 'true');
359
- video.playsInline = true;
360
- video.muted = true;
361
- video.style.cssText = 'position:fixed;left:-9999px;top:-9999px;width:1px;height:1px;opacity:0';
362
- document.body.appendChild(video);
363
- video.srcObject = stream;
364
- await video.play().catch(() => { });
365
- await new Promise((resolve) => {
366
- const ready = () => resolve();
367
- video.onloadeddata = ready;
368
- video.oncanplay = ready;
369
- setTimeout(ready, 800);
370
- });
371
- const vw = video.videoWidth || 640;
372
- const vh = video.videoHeight || 480;
373
- canvas = document.createElement('canvas');
374
- canvas.width = vw;
375
- canvas.height = vh;
376
- const ctx = canvas.getContext('2d');
377
- ctx?.drawImage(video, 0, 0, vw, vh);
378
- const mime = 'image/jpeg';
379
- const dataUrl = canvas.toDataURL(mime, 0.85);
380
- const bytes = Math.floor((dataUrl.length * 3) / 4);
381
- return {
382
- permission: 'granted',
383
- width: vw,
384
- height: vh,
385
- bytes,
386
- mime,
387
- timestamp: Date.now(),
388
- previewDataUrl: dataUrl
389
- };
390
- }
391
- catch (err) {
392
- const errorObj = err;
393
- return {
394
- permission: errorObj?.name === 'NotAllowedError' ? 'denied' : 'error',
395
- error: errorObj?.message || String(err)
396
- };
397
- }
398
- finally {
399
- try {
400
- stream?.getTracks().forEach((track) => track.stop());
401
- }
402
- catch {
403
- // Best-effort cleanup.
404
- }
405
- try {
406
- video?.remove();
407
- }
408
- catch {
409
- // Best-effort cleanup.
410
- }
411
- canvas = null;
412
- }
413
- };
414
497
 
415
498
  class RegisterError extends Error {
416
499
  constructor(status, body) {
@@ -451,14 +534,6 @@ const detectSoftRefusal = (payload) => {
451
534
  }
452
535
  return null;
453
536
  };
454
- const escapeShellSingleQuotes = (value) => value.replace(/'/g, "'\\''");
455
- const buildCurl = (url, body, headers) => {
456
- const payload = escapeShellSingleQuotes(JSON.stringify(body));
457
- const headerFlags = Object.entries(headers)
458
- .map(([key, value]) => `-H '${escapeShellSingleQuotes(`${key}: ${value}`)}'`)
459
- .join(' ');
460
- return `curl -X POST '${url}' ${headerFlags} -d '${payload}'`;
461
- };
462
537
  const registerDevice = async (config, payload, auth) => {
463
538
  const logger = getLogger();
464
539
  const orchestrator = config?.orchestrator;
@@ -475,20 +550,31 @@ const registerDevice = async (config, payload, auth) => {
475
550
  headers,
476
551
  body: JSON.stringify(payload)
477
552
  });
478
- logger.info('Register request sent:', { url, status: response.status });
479
- getLogger().debug('Register API blueprint (curl):', buildCurl(url, payload, headers));
553
+ // ZGA-538: never log the request body or headers — the payload carries the
554
+ // full device profile and the x-edge-operator-key credential.
555
+ logger.info('Register request sent', {
556
+ url,
557
+ status: response.status,
558
+ bodyBytes: JSON.stringify(payload).length
559
+ });
480
560
  const registerResponseBody = await parseRegisterResponseBody(response);
481
561
  const refusalReason = detectSoftRefusal(registerResponseBody);
482
562
  if (!response.ok && !refusalReason) {
483
563
  const text = typeof registerResponseBody === 'string'
484
564
  ? registerResponseBody
485
565
  : JSON.stringify(registerResponseBody ?? '');
486
- logger.error('Register request failed:', { status: response.status, text });
566
+ logger.error('Register request failed', { status: response.status, message: text });
487
567
  throw new RegisterError(response.status, text);
488
568
  }
489
569
  if (registerResponseBody && typeof registerResponseBody === 'object' && !refusalReason) {
490
570
  const registerResponse = registerResponseBody;
491
- logger.info('Register response parsed:', registerResponse);
571
+ // Shape only — the body carries the session key and the model sample text.
572
+ logger.info('Register response parsed', {
573
+ deviceId: registerResponse.deviceId,
574
+ hasWsUrl: Boolean(registerResponse.wsUrl),
575
+ models: registerResponse.slmConfig?.length ?? 0,
576
+ ttlSeconds: registerResponse.ttlSeconds
577
+ });
492
578
  return registerResponse;
493
579
  }
494
580
  if (refusalReason) {
@@ -522,23 +608,35 @@ const registerDevice = async (config, payload, auth) => {
522
608
  throw new RegisterError(response.status, 'Register response body is not valid JSON');
523
609
  };
524
610
 
611
+ /**
612
+ * Frame logging is metadata-only (ZGA-538): message type, request ids, byte
613
+ * size — never the frame body. Task frames carry customer input/output and the
614
+ * hello carries the session key, so a content dump here would hand both to any
615
+ * crash reporter watching the host console.
616
+ */
617
+ const frameType = (frame) => {
618
+ if (frame && typeof frame === 'object') {
619
+ const candidate = frame.type;
620
+ if (typeof candidate === 'string' && candidate.length > 0)
621
+ return candidate;
622
+ if (Array.isArray(frame.requests))
623
+ return 'task_batch';
624
+ }
625
+ return 'unknown';
626
+ };
525
627
  class WebSocketClient {
526
628
  constructor(options) {
527
629
  this.options = options;
528
630
  this.logger = getLogger();
529
631
  this.pingTimer = null;
530
- this.consoleWithVerbose = console;
531
632
  this.handleOpen = () => {
532
633
  this.logger.info('WebSocket connection opened');
533
634
  this.options.onOpen?.();
534
- this.logger.debug('Sending hello message:', this.options.hello);
535
- this.logger.info('[WS OUT] hello:', JSON.stringify(this.options.hello));
536
635
  this.send(this.options.hello);
537
636
  // Keepalive starts only once the hello is on the wire.
538
637
  this.startPing();
539
638
  if (this.options.ack) {
540
639
  // Send readiness/error ack immediately after hello.
541
- this.logger.info('[WS OUT] hello_ack:', JSON.stringify(this.options.ack));
542
640
  this.send(this.options.ack);
543
641
  if (this.options.closeAfterAck) {
544
642
  // Optionally close after ack (used for error cases).
@@ -560,24 +658,23 @@ class WebSocketClient {
560
658
  if (trimmed === 'pong')
561
659
  return;
562
660
  if (trimmed.length > 0 && trimmed[0] !== '{' && trimmed[0] !== '[') {
563
- this.logger.debug('[WS IN] ignoring non-JSON frame:', trimmed.slice(0, 64));
661
+ this.logger.debug('[WS IN] ignoring non-JSON frame', { bytes: trimmed.length });
564
662
  return;
565
663
  }
566
664
  }
567
665
  try {
568
666
  const data = JSON.parse(raw);
569
- if (this.logger.isEnabled()) {
570
- if (typeof this.consoleWithVerbose.verbose === 'function') {
571
- this.consoleWithVerbose.verbose('[ZeroGPU]', '[WS IN] payload:', data);
572
- }
573
- else {
574
- console.debug('[ZeroGPU]', '[WS IN] payload:', data);
575
- }
576
- }
667
+ this.logger.debug('[WS IN] frame', {
668
+ type: frameType(data),
669
+ requests: Array.isArray(data.requests)
670
+ ? data.requests.length
671
+ : undefined,
672
+ bytes: typeof raw === 'string' ? raw.length : undefined
673
+ });
577
674
  this.options.onMessage(data);
578
675
  }
579
676
  catch (error) {
580
- this.logger.error('Failed to parse WS message', error);
677
+ this.logger.error('Failed to parse WS message', { error: summarizeError(error) });
581
678
  }
582
679
  };
583
680
  this.handleError = (event) => {
@@ -602,7 +699,7 @@ class WebSocketClient {
602
699
  this.options.onClose(event);
603
700
  };
604
701
  this.pingIntervalMs = normalizePingIntervalMs(options.pingIntervalSeconds);
605
- this.logger.info('Creating WebSocket connection to:', options.url);
702
+ this.logger.info('Creating WebSocket connection', { url: options.url });
606
703
  this.socket = new WebSocket(options.url);
607
704
  this.socket.onopen = this.handleOpen;
608
705
  this.socket.onmessage = this.handleMessage;
@@ -636,7 +733,7 @@ class WebSocketClient {
636
733
  this.socket.send('ping');
637
734
  }
638
735
  catch (error) {
639
- this.logger.debug('Keepalive ping failed', error);
736
+ this.logger.debug('Keepalive ping failed', { error: summarizeError(error) });
640
737
  }
641
738
  try {
642
739
  this.options.onPingTick?.();
@@ -656,8 +753,13 @@ class WebSocketClient {
656
753
  return (this.socket.readyState === WebSocket.OPEN || this.socket.readyState === WebSocket.CONNECTING);
657
754
  }
658
755
  send(payload) {
659
- this.logger.debug('[WS OUT] payload:', JSON.stringify(payload));
660
- this.socket.send(JSON.stringify(payload));
756
+ const json = JSON.stringify(payload);
757
+ this.logger.debug('[WS OUT] frame', {
758
+ type: frameType(payload),
759
+ requests: Array.isArray(payload.requests) ? payload.requests.length : undefined,
760
+ bytes: json.length
761
+ });
762
+ this.socket.send(json);
661
763
  }
662
764
  close(code, reason) {
663
765
  this.stopPing();
@@ -1234,8 +1336,7 @@ const resolveWasmSettings = (probe = probeWasmEnvironment()) => {
1234
1336
  * Host-facing lifecycle status and events. The SDK is a guest in someone
1235
1337
  * else's app: this module is how the host observes guardrail state (degraded /
1236
1338
  * recovered / shutdown) without the SDK ever throwing into it. Script-tag
1237
- * consumers get the same signals as `zerogpu:*` window events, matching the
1238
- * existing `zerogpu:cameraPreview` pattern.
1339
+ * consumers get the same signals as `zerogpu:*` window events.
1239
1340
  */
1240
1341
  let lifecycleStatus = 'starting';
1241
1342
  const listeners = {
@@ -1818,9 +1919,12 @@ const fireTrackingPixel = (url, timeoutMs = DEFAULT_TIMEOUT_MS) => {
1818
1919
  *
1819
1920
  * Progressive:
1820
1921
  * 1. If a runner URL is configured, run the tag in the framed runner.
1821
- * 2. Otherwise fall back to a credentialed request beacon so the impression at
1822
- * least reaches the ad server with the user's real IP/UA/cookies (the tag's
1823
- * JS does not run).
1922
+ * 2. Otherwise, on an ordinary web page or WebView (including a Telegram Mini
1923
+ * App) with no restrictive `script-src` CSP, inject a real `<script>`
1924
+ * element so the tag executes directly in the page.
1925
+ * 3. Failing both (no DOM, or a CSP that blocks the injected script), fall back
1926
+ * to a credentialed request beacon so the impression at least reaches the ad
1927
+ * server with the user's real IP/UA/cookies (the tag's JS does not run).
1824
1928
  *
1825
1929
  * Never rejects: a tag is best-effort and must not affect inference.
1826
1930
  */
@@ -1967,18 +2071,107 @@ const fireBeacon = (url, timeoutMs) => {
1967
2071
  });
1968
2072
  };
1969
2073
  /**
1970
- * Fire a JavaScript tracking tag. Runs it in the framed runner when one is
1971
- * available; otherwise fires the request as a beacon. Never rejects.
2074
+ * Execute the tag by injecting a real `<script>` element into the host document.
2075
+ *
2076
+ * This is how a JS tag is *meant* to run on an ordinary web page — including a
2077
+ * Telegram Mini App or any other WebView, which is just a normal DOM with no
2078
+ * extension-style `script-src 'self'` lockdown. The browser fetches the tag with
2079
+ * `Sec-Fetch-Dest: script` and runs it in the page, so the tag's own logic
2080
+ * (impression beacons, etc.) actually executes.
2081
+ *
2082
+ * Unlike a pixel, `load` means the code ran and `error` means it did not: a CSP
2083
+ * `script-src` that forbids the origin (e.g. the MV3 extension's offscreen
2084
+ * document) blocks the load. On error we resolve `null` so the caller can fall
2085
+ * back to the beacon; on load we resolve 'fired' and do NOT beacon, so an
2086
+ * executed tag is never counted twice.
2087
+ *
2088
+ * Resolves:
2089
+ * - 'fired' the script loaded and executed
2090
+ * - 'timeout' it neither loaded nor errored in time (genuinely unknown)
2091
+ * - null no DOM, or the injection failed/was blocked → try the beacon
2092
+ *
2093
+ * Never rejects.
2094
+ */
2095
+ // Only https tags are ever executed in-page. Tier 2 runs the tag in the host
2096
+ // document's context (full DOM / same-origin storage / cookies), so a non-https
2097
+ // URL — http:, data:, blob:, javascript: — must never reach `script.src`. Such
2098
+ // tags resolve `null` here and fall through to the beacon, which still delivers
2099
+ // the impression without running any code.
2100
+ const isExecutableTagUrl = (url) => {
2101
+ try {
2102
+ return new URL(url).protocol === 'https:';
2103
+ }
2104
+ catch {
2105
+ return false;
2106
+ }
2107
+ };
2108
+ const fireViaScriptTag = (url, timeoutMs) => {
2109
+ if (typeof document === 'undefined' || !isExecutableTagUrl(url)) {
2110
+ return Promise.resolve(null);
2111
+ }
2112
+ return new Promise((resolve) => {
2113
+ let settled = false;
2114
+ let script;
2115
+ let timer;
2116
+ const settle = (status) => {
2117
+ if (settled)
2118
+ return;
2119
+ settled = true;
2120
+ if (timer !== undefined)
2121
+ clearTimeout(timer);
2122
+ if (script) {
2123
+ script.onload = null;
2124
+ script.onerror = null;
2125
+ script.remove();
2126
+ }
2127
+ resolve(status);
2128
+ };
2129
+ try {
2130
+ timer = setTimeout(() => settle('timeout'), timeoutMs);
2131
+ script = document.createElement('script');
2132
+ script.async = true;
2133
+ // A tag's JS runs synchronously as it loads, so `onload` fires *after* it
2134
+ // has executed. `error` — a network failure or a CSP `script-src` block —
2135
+ // means it did not run: resolve null and let the caller beacon instead.
2136
+ script.onload = () => settle('fired');
2137
+ script.onerror = () => settle(null);
2138
+ script.src = url;
2139
+ (document.head ?? document.documentElement).appendChild(script);
2140
+ }
2141
+ catch {
2142
+ settle(null);
2143
+ }
2144
+ });
2145
+ };
2146
+ /**
2147
+ * Fire a JavaScript tracking tag. Executes it wherever it can — the framed
2148
+ * runner, or an injected `<script>` on a normal page/WebView — and only falls
2149
+ * back to a non-executing beacon when neither can run it. Never rejects.
1972
2150
  */
1973
2151
  const fireTrackingScript = async (url, timeoutMs = DEFAULT_TIMEOUT_MS) => {
2152
+ // 1. Framed runner: executes off the extension origin when a runner is
2153
+ // configured (the MV3 extension path).
1974
2154
  try {
1975
2155
  const win = await ensureRunner();
1976
- if (win)
1977
- return await runInRunner(win, url, timeoutMs);
2156
+ if (win) {
2157
+ // 'skipped' means the runner could not execute the tag, so it did not
2158
+ // run — fall through to the remaining tiers. 'fired'/'timeout' are terminal.
2159
+ const outcome = await runInRunner(win, url, timeoutMs);
2160
+ if (outcome !== 'skipped')
2161
+ return outcome;
2162
+ }
1978
2163
  }
1979
2164
  catch {
1980
- // Fall through to the beacon on any runner failure.
1981
- }
2165
+ // Fall through on any runner failure.
2166
+ }
2167
+ // 2. Inject a real <script> so the tag executes in the page. This is the
2168
+ // normal path for the SDK loaded on a site via the loader, and for a
2169
+ // Telegram Mini App / other WebViews.
2170
+ const executed = await fireViaScriptTag(url, timeoutMs);
2171
+ if (executed !== null)
2172
+ return executed;
2173
+ // 3. Last resort: fire the request without executing it, so the impression
2174
+ // still reaches the ad server with the user's real IP/UA/cookies.
1982
2175
  return fireBeacon(url, timeoutMs);
1983
2176
  };
1984
2177
 
@@ -2130,7 +2323,7 @@ const executeSingleRequest = async (request) => {
2130
2323
  };
2131
2324
  }
2132
2325
  catch (error) {
2133
- logger.error('Task failed', error);
2326
+ logger.error('Task failed', { error: summarizeError(error) });
2134
2327
  const message = error.message ?? '';
2135
2328
  const isAllocationFailure = error instanceof RangeError || /out of memory|oom|wasm.*abort|allocation failed/i.test(message);
2136
2329
  getEventReporter().report('task.failed', {
@@ -2209,12 +2402,15 @@ const handleIncomingMessage = async (msg) => {
2209
2402
  const results = [];
2210
2403
  for (const request of msg.requests) {
2211
2404
  const result = await executeSingleRequest(request);
2212
- logger.info('[WS OUT] task result:', {
2405
+ // Metadata only (ZGA-538): the response body is customer model output
2406
+ // and must never reach the console — log its size instead.
2407
+ logger.info('[WS OUT] task result', {
2213
2408
  requestId: result.requestId,
2214
2409
  modelId: result.modelId,
2215
- response: result.response,
2410
+ responseBytes: JSON.stringify(result.response ?? null).length,
2411
+ processingTimeMs: result.metadata.processingTime,
2216
2412
  error: result.error,
2217
- errorMessage: result.errorMessage
2413
+ errorMessage: result.errorMessage || undefined
2218
2414
  });
2219
2415
  results.push(result);
2220
2416
  }
@@ -2706,7 +2902,7 @@ const scheduleReconnect = (options, reason) => {
2706
2902
  }
2707
2903
  logger.info('[WS] Re-registration timer fired; restarting lifecycle');
2708
2904
  startLifecycle(options).catch((err) => {
2709
- logger.error('[WS] Re-registration attempt failed; will retry', err);
2905
+ logger.error('[WS] Re-registration attempt failed; will retry', { error: summarizeError(err) });
2710
2906
  // Keep the loop alive on transient failures (register/network/model
2711
2907
  // errors). Auth failures and crash-loop cool-downs return cleanly from
2712
2908
  // startLifecycle without throwing, so they end the loop here.
@@ -2734,7 +2930,7 @@ const triggerFullReregister = (options, reason) => {
2734
2930
  // Best effort — the register flow below supersedes the session anyway.
2735
2931
  }
2736
2932
  startLifecycle(options).catch((err) => {
2737
- logger.error('[WS] Full re-register failed; scheduling retry', err);
2933
+ logger.error('[WS] Full re-register failed; scheduling retry', { error: summarizeError(err) });
2738
2934
  scheduleReconnect(options, 'socket_closed');
2739
2935
  });
2740
2936
  };
@@ -2770,7 +2966,7 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
2770
2966
  };
2771
2967
  // Deterministic preflight validation runs before the crash-loop guard so a
2772
2968
  // misconfigured integration never consumes a crash-loop attempt (and never
2773
- // triggers the camera/geo prompts below).
2969
+ // triggers the geolocation prompt below).
2774
2970
  if (!edgeOperatorKey) {
2775
2971
  throw new Error('Missing required header: x-edge-operator-key');
2776
2972
  }
@@ -2805,39 +3001,24 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
2805
3001
  providedDeviceId: Boolean(providedDeviceId),
2806
3002
  orchestrator: config.orchestrator?.baseUrl
2807
3003
  });
2808
- const rawDeviceInfo = await collectDeviceInfo(config.telemetry, appUserId, deviceId);
2809
- const sanitizedDeviceInfo = stripCameraPreview(rawDeviceInfo);
2810
- setDeviceContext(deviceId, sanitizedDeviceInfo);
3004
+ const deviceInfo = await collectDeviceInfo(config.telemetry, appUserId, deviceId);
3005
+ setDeviceContext(deviceId, deviceInfo);
2811
3006
  initEventReporter({
2812
3007
  enabled: config.telemetry.events,
2813
3008
  endpointUrl: `${config.orchestrator.baseUrl}${config.orchestrator.eventsPath}`,
2814
3009
  operatorKey: edgeOperatorKey,
2815
3010
  deviceId,
2816
3011
  sdkVersion: config.sdkVersion,
2817
- platform: sanitizedDeviceInfo.platform
3012
+ platform: deviceInfo.platform
2818
3013
  });
2819
3014
  const reporter = getEventReporter();
2820
3015
  reporter.report('sdk.init_started', { data: { sdkVersion: config.sdkVersion } });
2821
3016
  reportCrashFromPreviousSession(guard.crash);
2822
3017
  logger.info('[Init] Device info collected', {
2823
- platform: sanitizedDeviceInfo.platform,
2824
- deviceType: sanitizedDeviceInfo.deviceType,
2825
- gpuRenderer: sanitizedDeviceInfo.gpuRenderer
3018
+ platform: deviceInfo.platform,
3019
+ deviceType: deviceInfo.deviceType,
3020
+ gpuRenderer: deviceInfo.gpuRenderer
2826
3021
  });
2827
- if (rawDeviceInfo.camera?.previewDataUrl) {
2828
- try {
2829
- window.dispatchEvent(new CustomEvent('zerogpu:cameraPreview', {
2830
- detail: {
2831
- deviceId,
2832
- previewDataUrl: rawDeviceInfo.camera.previewDataUrl,
2833
- camera: sanitizedDeviceInfo.camera
2834
- }
2835
- }));
2836
- }
2837
- catch {
2838
- logger.warn('Unable to dispatch camera preview event');
2839
- }
2840
- }
2841
3022
  const cachedModelId = isFreshDevice ? null : getCachedModelId();
2842
3023
  setCachedModelId(cachedModelId);
2843
3024
  let cachedInfo = cachedModelId ? getCachedModelInfo(cachedModelId) : null;
@@ -3011,7 +3192,7 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
3011
3192
  cachedModels: cachedInfo && !cacheInvalid
3012
3193
  ? [{ modelId: cachedInfo.modelId, modelVersion: cachedInfo.modelVersion || '1' }]
3013
3194
  : [],
3014
- device: sanitizedDeviceInfo
3195
+ device: deviceInfo
3015
3196
  };
3016
3197
  let registerResponse;
3017
3198
  let assignedModels = [];
@@ -3022,7 +3203,7 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
3022
3203
  let postRegisterSample;
3023
3204
  logger.info('[Register] Sending register request', {
3024
3205
  deviceId,
3025
- cachedModels: registerPayload.cachedModels,
3206
+ cachedModels: registerPayload.cachedModels.map((model) => model.modelId),
3026
3207
  sdkVersion: config.sdkVersion
3027
3208
  });
3028
3209
  reporter.report('register.started');
@@ -3073,7 +3254,10 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
3073
3254
  // TODO(global-types): emit ws.policy_applied once available in the shared
3074
3255
  // event vocabulary (data: {source: 'register', v, changed}).
3075
3256
  if (registrationSettings) {
3076
- logger.info('[Register] Registration settings received', registrationSettings);
3257
+ // Keys only: served settings are operator config, not for host consoles.
3258
+ logger.info('[Register] Registration settings received', {
3259
+ keys: Object.keys(registrationSettings)
3260
+ });
3077
3261
  }
3078
3262
  if (registerResponse.refusalReason) {
3079
3263
  // The server deliberately declined this device (admission rules) — the
@@ -3092,7 +3276,7 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
3092
3276
  reporter.report('register.succeeded', { durationMs: Math.round(performance.now() - registerStartedAt) });
3093
3277
  markRegisterSuccess();
3094
3278
  reporter.setSessionKey(registerResponse.sessionKey);
3095
- logger.info('Register response received:', {
3279
+ logger.info('Register response received', {
3096
3280
  deviceId: registerResponse.deviceId,
3097
3281
  wsUrl: registerResponse.wsUrl
3098
3282
  });
@@ -3111,13 +3295,8 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
3111
3295
  }
3112
3296
  logger.info('[Register] Models assigned', {
3113
3297
  count: assignedModels.length,
3114
- models: assignedModels.map((m) => ({
3115
- modelId: m.modelId,
3116
- framework: m.inferenceFramework,
3117
- taskType: m.taskType,
3118
- quantized: m.quantized,
3119
- sizeBytes: m.sizeBytes
3120
- }))
3298
+ models: assignedModels.map((m) => m.modelId),
3299
+ totalBytes: assignedModels.reduce((sum, m) => sum + (m.sizeBytes ?? 0), 0)
3121
3300
  });
3122
3301
  for (const model of assignedModels) {
3123
3302
  modelStatuses[getModelStatusKey(model)] = 'idle';
@@ -3135,10 +3314,10 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
3135
3314
  setModelInfosByModelId(modelInfosByModelId);
3136
3315
  setModelInfo(primaryModel);
3137
3316
  setSample(primaryModel.sample);
3317
+ // ZGA-538: no session key (credential) and no sample body (task content).
3138
3318
  logger.info('Runtime globals updated from register response', {
3139
- sessionKey: registerResponse.sessionKey,
3140
3319
  taskType: primaryModel.taskType,
3141
- sample: primaryModel.sample
3320
+ hasSample: Boolean(primaryModel.sample)
3142
3321
  });
3143
3322
  if (!cachedInfo || cachedInfo.modelId !== primaryModel.modelId || cacheInvalid) {
3144
3323
  if (cachedInfo && cachedInfo.modelId !== primaryModel.modelId) {
@@ -3411,7 +3590,7 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
3411
3590
  };
3412
3591
  logger.info('[WS] Connecting WebSocket', {
3413
3592
  wsUrl: registerResponse.wsUrl,
3414
- models: helloSlmConfig
3593
+ models: helloSlmConfig.map((model) => `${model.modelId}:${model.status}`)
3415
3594
  });
3416
3595
  reporter.report('ws.connect_started');
3417
3596
  const connectionPolicy = getConnectionPolicy();
@@ -3442,7 +3621,12 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
3442
3621
  }
3443
3622
  else if ('type' in message && message.type === 'hello_ack') {
3444
3623
  const ack = message;
3445
- logger.info('[WS] Received hello_ack', ack);
3624
+ // Fields, not the frame — the ack echoes the session key.
3625
+ logger.info('[WS] Received hello_ack', {
3626
+ status: ack.status,
3627
+ deviceId: ack.deviceId,
3628
+ errorMessage: ack.errorMessage
3629
+ });
3446
3630
  reporter.report('ws.hello_ack', {
3447
3631
  code: ack.status,
3448
3632
  message: ack.errorMessage
@@ -3485,7 +3669,9 @@ const startLifecycle = async ({ config, appUserId, edgeOperatorKey, deviceId: pr
3485
3669
  }, delayMs);
3486
3670
  }
3487
3671
  else {
3488
- logger.debug('[WS] Unhandled message', message);
3672
+ logger.debug('[WS] Unhandled message', {
3673
+ type: 'type' in message && typeof message.type === 'string' ? message.type : 'unknown'
3674
+ });
3489
3675
  }
3490
3676
  },
3491
3677
  onClose: (event) => {
@@ -3737,15 +3923,6 @@ const reportInitFailureOverWebSocket = async (options) => {
3737
3923
  }
3738
3924
  });
3739
3925
  };
3740
- const stripCameraPreview = (info) => {
3741
- if (!info.camera?.previewDataUrl) {
3742
- return info;
3743
- }
3744
- return {
3745
- ...info,
3746
- camera: { ...info.camera, previewDataUrl: undefined }
3747
- };
3748
- };
3749
3926
 
3750
3927
  const measure = async (fn) => {
3751
3928
  const start = performance.now();
@@ -3755,12 +3932,6 @@ const measure = async (fn) => {
3755
3932
 
3756
3933
  const TRANSFORMERS_CDN = 'https://cdn.jsdelivr.net/npm/@xenova/transformers@2.17.2/dist/transformers.min.js';
3757
3934
  let transformersRuntimePromise = null;
3758
- const serializeError$5 = (error) => {
3759
- if (error instanceof Error) {
3760
- return { name: error.name, message: error.message, stack: error.stack };
3761
- }
3762
- return { message: String(error) };
3763
- };
3764
3935
  const ensureTransformersRuntime = () => {
3765
3936
  if (window.TransformersPipeline) {
3766
3937
  return Promise.resolve();
@@ -3796,7 +3967,7 @@ const ensureTransformersRuntime = () => {
3796
3967
  transformersRuntimePromise = null;
3797
3968
  logger.error('[SLM] Failed to import Transformers runtime', {
3798
3969
  runtimeUrl: TRANSFORMERS_CDN,
3799
- error: serializeError$5(error)
3970
+ error: summarizeError(error)
3800
3971
  });
3801
3972
  throw error;
3802
3973
  }
@@ -3905,7 +4076,7 @@ const probeOnnxWasmOverridePath = async (fetchImpl) => {
3905
4076
  }
3906
4077
  if (sawNonWasmPayloadAtBase) {
3907
4078
  getLogger().warn('[SLM] ONNX wasm probe got non-wasm payload', {
3908
- wasmBase: baseWithSlash
4079
+ url: baseWithSlash
3909
4080
  });
3910
4081
  }
3911
4082
  }
@@ -3933,12 +4104,6 @@ const withTransformersEnvLock = async (work) => {
3933
4104
  }
3934
4105
  };
3935
4106
 
3936
- const serializeError$4 = (error) => {
3937
- if (error instanceof Error) {
3938
- return { name: error.name, message: error.message, stack: error.stack };
3939
- }
3940
- return { message: String(error) };
3941
- };
3942
4107
  const sessionCache = {};
3943
4108
  const createEnvFetch = (modelId, fileBase, cachedFiles, onFileDownloaded, requiredFiles, originalFetch) => {
3944
4109
  const requiredFileList = requiredFiles
@@ -4038,7 +4203,7 @@ const createEnvFetch = (modelId, fileBase, cachedFiles, onFileDownloaded, requir
4038
4203
  logger.error('[SLM][fetch] non-model wasm/ort request failed', {
4039
4204
  modelId,
4040
4205
  requestUrl: originalRequestUrl,
4041
- error: serializeError$4(error)
4206
+ error: summarizeError(error)
4042
4207
  });
4043
4208
  throw error;
4044
4209
  }
@@ -4046,7 +4211,7 @@ const createEnvFetch = (modelId, fileBase, cachedFiles, onFileDownloaded, requir
4046
4211
  const relative = resolveRequestedRelative(requestedRelative);
4047
4212
  if (!relative) {
4048
4213
  logger.warn('[SLM] Unexpected model file request; falling back to original fetch', {
4049
- requestedRelative,
4214
+ file: requestedRelative,
4050
4215
  modelId
4051
4216
  });
4052
4217
  return originalFetch(url, init);
@@ -4094,10 +4259,11 @@ const createEnvFetch = (modelId, fileBase, cachedFiles, onFileDownloaded, requir
4094
4259
  // That string means "every candidate URL threw", i.e. a network/abort
4095
4260
  // failure against the real model host — not an upstream 502 and not a
4096
4261
  // malformed URL actually being requested.
4097
- logger.warn(`[SLM] Model file fetch failed for ${relative}`, {
4262
+ logger.warn('[SLM] Model file fetch failed', {
4098
4263
  modelId,
4099
- candidates: requestUrls,
4100
- error: serializeError$4(err)
4264
+ file: relative,
4265
+ candidateCount: requestUrls.length,
4266
+ error: summarizeError(err)
4101
4267
  });
4102
4268
  return new Response('model_file_fetch_failed', { status: 502, statusText: 'Bad Gateway' });
4103
4269
  }
@@ -4110,12 +4276,6 @@ const TASK_PIPELINE_MAP = {
4110
4276
  classification: 'zero-shot-classification',
4111
4277
  text_generation: 'text2text-generation'
4112
4278
  };
4113
- const serializeError$3 = (error) => {
4114
- if (error instanceof Error) {
4115
- return { name: error.name, message: error.message, stack: error.stack };
4116
- }
4117
- return { message: String(error) };
4118
- };
4119
4279
  const isInvalidArrayLengthError = (error) => {
4120
4280
  const message = error instanceof Error ? error.message : String(error);
4121
4281
  return message.toLowerCase().includes('invalid array length');
@@ -4487,7 +4647,7 @@ const loadOnnxAdapter = async (slm, options) => {
4487
4647
  modelRepoId: slm.modelRepoId,
4488
4648
  modelUrl: slm.modelUrl,
4489
4649
  requiredFiles: (slm.requiredFiles ?? []).map((file) => file.name),
4490
- error: serializeError$3(error)
4650
+ error: summarizeError(error)
4491
4651
  });
4492
4652
  await clearModel(slm.modelId, slm.modelVersion).catch(() => { });
4493
4653
  return { error: error, metrics: {} };
@@ -4508,12 +4668,6 @@ registerAdapter(factory$2);
4508
4668
 
4509
4669
  const DEFAULT_THRESHOLD = 0.4;
4510
4670
  const DEFAULT_MASK = '[REDACTED]';
4511
- const serializeError$2 = (error) => {
4512
- if (error instanceof Error) {
4513
- return { name: error.name, message: error.message, stack: error.stack };
4514
- }
4515
- return { message: String(error) };
4516
- };
4517
4671
  const parseTokenClassificationOutput = (raw, sourceText) => {
4518
4672
  if (!Array.isArray(raw))
4519
4673
  return [];
@@ -4776,7 +4930,7 @@ const loadTransformersAdapter = async (slm, options) => {
4776
4930
  modelVersion: slm.modelVersion,
4777
4931
  modelRepoId: slm.modelRepoId,
4778
4932
  modelUrl: slm.modelUrl,
4779
- error: serializeError$2(error)
4933
+ error: summarizeError(error)
4780
4934
  });
4781
4935
  await clearModel(slm.modelId, slm.modelVersion).catch(() => { });
4782
4936
  return { error: error, metrics: {} };
@@ -4795,12 +4949,6 @@ registerAdapter(factory$1);
4795
4949
 
4796
4950
  const WLLAMA_CDN = 'https://cdn.jsdelivr.net/npm/@wllama/wllama@2.3.5/esm/index.js';
4797
4951
  let wllamaRuntimePromise = null;
4798
- const serializeError$1 = (error) => {
4799
- if (error instanceof Error) {
4800
- return { name: error.name, message: error.message, stack: error.stack };
4801
- }
4802
- return { message: String(error) };
4803
- };
4804
4952
  const ensureWllamaRuntime = () => {
4805
4953
  if (window.WllamaModule) {
4806
4954
  return Promise.resolve(window.WllamaModule);
@@ -4819,7 +4967,7 @@ const ensureWllamaRuntime = () => {
4819
4967
  wllamaRuntimePromise = null;
4820
4968
  getLogger().error('[GGUF] Failed to import wllama runtime', {
4821
4969
  runtimeUrl: WLLAMA_CDN,
4822
- error: serializeError$1(error)
4970
+ error: summarizeError(error)
4823
4971
  });
4824
4972
  throw error;
4825
4973
  }
@@ -4830,12 +4978,6 @@ const ensureWllamaRuntime = () => {
4830
4978
  const WLLAMA_CDN_BASE = WLLAMA_CDN.replace(/\/esm\/index\.js$/, '/esm');
4831
4979
 
4832
4980
  const DEFAULT_MAX_NEW_TOKENS = 128;
4833
- const serializeError = (error) => {
4834
- if (error instanceof Error) {
4835
- return { name: error.name, message: error.message, stack: error.stack };
4836
- }
4837
- return { message: String(error) };
4838
- };
4839
4981
  const pickGgufFileName = (requiredFiles) => {
4840
4982
  if (!Array.isArray(requiredFiles) || requiredFiles.length === 0)
4841
4983
  return null;
@@ -5040,7 +5182,7 @@ const loadGgufAdapter = async (slm, options) => {
5040
5182
  modelId: slm.modelId,
5041
5183
  modelVersion: slm.modelVersion,
5042
5184
  modelUrl: slm.modelUrl,
5043
- error: serializeError(error)
5185
+ error: summarizeError(error)
5044
5186
  });
5045
5187
  await clearModel(slm.modelId, slm.modelVersion).catch(() => { });
5046
5188
  return { error: error, metrics: {} };
@@ -5080,7 +5222,9 @@ const initZeroGpuSdk = async (options) => {
5080
5222
  if (options?.resourcePolicy) {
5081
5223
  setResourcePolicy(options.resourcePolicy);
5082
5224
  if (options.resourcePolicy.disableGuardrails) {
5083
- // Loud by design: a host running without guardrails should know it.
5225
+ // Loud by design: a host running without guardrails should know it, even
5226
+ // with console logs disabled. Static text only — nothing to redact.
5227
+ // eslint-disable-next-line no-console
5084
5228
  console.warn('[ZeroGPU] resourcePolicy.disableGuardrails is set — ALL memory/storage/battery guardrails are OFF. Lab use only.');
5085
5229
  }
5086
5230
  }
@@ -5096,7 +5240,7 @@ const initZeroGpuSdk = async (options) => {
5096
5240
  catch (err) {
5097
5241
  // Already reported inside the lifecycle (register.failed / sdk.init_failed
5098
5242
  // / init-failure hello); surface for the host without throwing into it.
5099
- getLogger().error('[Init] SDK initialization failed', err);
5243
+ getLogger().error('[Init] SDK initialization failed', { error: summarizeError(err) });
5100
5244
  }
5101
5245
  return handle;
5102
5246
  };