@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.
@@ -4,8 +4,8 @@
4
4
  (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.ZeroGpuBrowserSdk = {}));
5
5
  })(this, (function (exports) { 'use strict';
6
6
 
7
- const SDK_VERSION = typeof "0.2.1+8a18008" === 'string' && "0.2.1+8a18008".length > 0
8
- ? "0.2.1+8a18008"
7
+ const SDK_VERSION = typeof "0.2.2+0a17606" === 'string' && "0.2.2+0a17606".length > 0
8
+ ? "0.2.2+0a17606"
9
9
  : '0.0.0-dev';
10
10
 
11
11
  const ORCHESTRATOR_BASE_URL = typeof "https://devices.zerogpu.ai" === 'string' && "https://devices.zerogpu.ai".length > 0
@@ -27,7 +27,6 @@
27
27
  telemetry: {
28
28
  enableConsoleLogs: false,
29
29
  locationData: false,
30
- cameraData: false,
31
30
  events: true
32
31
  }
33
32
  };
@@ -45,7 +44,8 @@
45
44
  telemetry: {
46
45
  enableConsoleLogs: asBoolean(merged.telemetry?.enableConsoleLogs, base.telemetry.enableConsoleLogs),
47
46
  locationData: asBoolean(merged.telemetry?.locationData, base.telemetry.locationData),
48
- cameraData: asBoolean(merged.telemetry?.cameraData, base.telemetry.cameraData),
47
+ // `cameraData` is deliberately dropped: the camera path no longer exists
48
+ // (ZGA-538); a host that still passes the flag is silently ignored.
49
49
  events: asBoolean(merged.telemetry?.events, base.telemetry.events)
50
50
  }
51
51
  };
@@ -74,6 +74,152 @@
74
74
  const asNonEmptyString = (value, fallback) => typeof value === 'string' && value.length > 0 ? value : fallback;
75
75
  const asBoolean = (value, fallback) => typeof value === 'boolean' ? value : fallback;
76
76
 
77
+ const MESSAGE_MAX = 200;
78
+ const ID_MAX = 256;
79
+ const ARRAY_MAX = 20;
80
+ /** Keys that must never print their value, whatever it is. */
81
+ const CREDENTIAL_KEY_PATTERN = /(session|token|secret|password|credential|cookie|authorization|api[-_]?key|operator)/i;
82
+ /** Keys whose string value is a URL: keep origin + path, drop query/hash. */
83
+ const URL_KEYS = new Set([
84
+ 'url',
85
+ 'wsurl',
86
+ 'baseurl',
87
+ 'modelurl',
88
+ 'modelrepourl',
89
+ 'runtimeurl',
90
+ 'requesturl',
91
+ 'endpoint',
92
+ 'endpointurl',
93
+ 'manifesturl',
94
+ 'bundleurl',
95
+ 'orchestrator'
96
+ ]);
97
+ /** Keys carrying an error/diagnostic summary: kept, capped. */
98
+ const MESSAGE_KEYS = new Set(['message', 'errormessage', 'error', 'reason']);
99
+ /** Identifier / enum-like keys whose string value is safe to print (capped). */
100
+ const SAFE_STRING_KEYS = new Set([
101
+ 'requestid',
102
+ 'modelid',
103
+ 'modelversion',
104
+ 'modelrepoid',
105
+ 'modeltype',
106
+ 'deviceid',
107
+ 'sdkversion',
108
+ 'tasktype',
109
+ 'framework',
110
+ 'inferenceframework',
111
+ 'quantization',
112
+ 'code',
113
+ 'status',
114
+ 'type',
115
+ 'phase',
116
+ 'flow',
117
+ 'event',
118
+ 'source',
119
+ 'name',
120
+ 'platform',
121
+ 'devicetype',
122
+ 'gpurenderer',
123
+ 'mime',
124
+ 'mode',
125
+ 'file',
126
+ 'files',
127
+ 'requiredfiles',
128
+ 'models',
129
+ 'cachedmodels',
130
+ 'keys',
131
+ 'changed',
132
+ 'cachedmodelid',
133
+ 'assignedmodelid',
134
+ 'primarymodelid'
135
+ ]);
136
+ const cap = (value, max) => value.length > max ? `${value.slice(0, max)}…` : value;
137
+ /** One-line, capped error summary — diagnostics survive, payloads cannot ride along uncapped. */
138
+ const summarizeError = (error) => {
139
+ if (error instanceof Error) {
140
+ return cap(`${error.name}: ${error.message}`, MESSAGE_MAX);
141
+ }
142
+ if (typeof error === 'string')
143
+ return cap(error, MESSAGE_MAX);
144
+ if (error === null || error === undefined)
145
+ return String(error);
146
+ if (typeof error === 'object')
147
+ return `[${error.constructor?.name ?? 'object'}]`;
148
+ return cap(String(error), MESSAGE_MAX);
149
+ };
150
+ const stripUrl = (value) => {
151
+ try {
152
+ const url = new URL(value);
153
+ return `${url.origin}${url.pathname}`;
154
+ }
155
+ catch {
156
+ return '[invalid-url]';
157
+ }
158
+ };
159
+ const describeOpaque = (value) => {
160
+ if (Array.isArray(value))
161
+ return `[array:${value.length}]`;
162
+ if (value && typeof value === 'object')
163
+ return `[object:${Object.keys(value).length} keys]`;
164
+ return `[${typeof value}]`;
165
+ };
166
+ const sanitizeString = (key, value) => {
167
+ const normalizedKey = key.toLowerCase();
168
+ if (URL_KEYS.has(normalizedKey))
169
+ return stripUrl(value);
170
+ if (MESSAGE_KEYS.has(normalizedKey))
171
+ return cap(value, MESSAGE_MAX);
172
+ if (SAFE_STRING_KEYS.has(normalizedKey))
173
+ return cap(value, ID_MAX);
174
+ return `[string:${value.length}]`;
175
+ };
176
+ const sanitizeValue = (key, value) => {
177
+ if (CREDENTIAL_KEY_PATTERN.test(key))
178
+ return '[redacted]';
179
+ if (value === null || value === undefined)
180
+ return value;
181
+ if (typeof value === 'boolean')
182
+ return value;
183
+ if (typeof value === 'number')
184
+ return Number.isFinite(value) ? value : String(value);
185
+ if (typeof value === 'string')
186
+ return sanitizeString(key, value);
187
+ if (value instanceof Error)
188
+ return summarizeError(value);
189
+ return describeOpaque(value);
190
+ };
191
+ /**
192
+ * The runtime redaction gate. Whatever a caller manages to pass (the types
193
+ * merely guide), nothing but ids, enums, counts, sizes, durations and capped
194
+ * error summaries comes out the other side.
195
+ */
196
+ const sanitizeLogFields = (fields) => {
197
+ if (fields instanceof Error) {
198
+ return { error: summarizeError(fields) };
199
+ }
200
+ if (!fields || typeof fields !== 'object' || Array.isArray(fields)) {
201
+ return { detail: sanitizeValue('detail', fields) };
202
+ }
203
+ const sanitized = {};
204
+ for (const [key, value] of Object.entries(fields)) {
205
+ if (Array.isArray(value)) {
206
+ if (CREDENTIAL_KEY_PATTERN.test(key)) {
207
+ sanitized[key] = '[redacted]';
208
+ }
209
+ else if (value.every((item) => item === null || typeof item !== 'object')) {
210
+ sanitized[key] = value.slice(0, ARRAY_MAX).map((item) => sanitizeValue(key, item));
211
+ }
212
+ else {
213
+ sanitized[key] = describeOpaque(value);
214
+ }
215
+ continue;
216
+ }
217
+ sanitized[key] = sanitizeValue(key, value);
218
+ }
219
+ return sanitized;
220
+ };
221
+ const sanitizeMessage = (message) => typeof message === 'string' ? cap(message, MESSAGE_MAX) : '[invalid log message]';
222
+ /* eslint-disable no-console -- sole audited console sink; everything printed here has passed sanitizeLogFields. */
77
223
  class Logger {
78
224
  constructor(config) {
79
225
  this.enabled = config.enableConsoleLogs;
@@ -84,21 +230,28 @@
84
230
  isEnabled() {
85
231
  return this.enabled;
86
232
  }
87
- debug(...args) {
88
- if (this.enabled)
89
- console.debug('[ZeroGPU]', ...args);
233
+ emit(sink, message, fields) {
234
+ if (!this.enabled)
235
+ return;
236
+ if (fields === undefined) {
237
+ sink('[ZeroGPU]', sanitizeMessage(message));
238
+ }
239
+ else {
240
+ sink('[ZeroGPU]', sanitizeMessage(message), sanitizeLogFields(fields));
241
+ }
242
+ }
243
+ debug(message, fields) {
244
+ this.emit(console.debug, message, fields);
90
245
  }
91
- info(...args) {
92
- if (this.enabled)
93
- console.debug('[ZeroGPU]', ...args);
246
+ info(message, fields) {
247
+ // Historic behavior: info also goes to console.debug to keep host consoles quiet.
248
+ this.emit(console.debug, message, fields);
94
249
  }
95
- warn(...args) {
96
- if (this.enabled)
97
- console.warn('[ZeroGPU]', ...args);
250
+ warn(message, fields) {
251
+ this.emit(console.warn, message, fields);
98
252
  }
99
- error(...args) {
100
- if (this.enabled)
101
- console.error('[ZeroGPU]', ...args);
253
+ error(message, fields) {
254
+ this.emit(console.error, message, fields);
102
255
  }
103
256
  }
104
257
  let singleton$1 = null;
@@ -111,7 +264,6 @@
111
264
  singleton$1 = new Logger({
112
265
  enableConsoleLogs: false,
113
266
  locationData: false,
114
- cameraData: false,
115
267
  events: true
116
268
  });
117
269
  }
@@ -346,77 +498,8 @@
346
498
  // Optional permissions
347
499
  location: config.locationData ? await getLocation() : undefined
348
500
  };
349
- if (config.cameraData) {
350
- baseInfo.camera = await captureCameraSample();
351
- }
352
501
  return baseInfo;
353
502
  };
354
- const captureCameraSample = async () => {
355
- if (!navigator.mediaDevices?.getUserMedia) {
356
- return { permission: 'error', error: 'mediaDevices unavailable' };
357
- }
358
- let stream = null;
359
- let video = null;
360
- let canvas = null;
361
- try {
362
- stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: 'user' } });
363
- video = document.createElement('video');
364
- video.setAttribute('playsinline', 'true');
365
- video.playsInline = true;
366
- video.muted = true;
367
- video.style.cssText = 'position:fixed;left:-9999px;top:-9999px;width:1px;height:1px;opacity:0';
368
- document.body.appendChild(video);
369
- video.srcObject = stream;
370
- await video.play().catch(() => { });
371
- await new Promise((resolve) => {
372
- const ready = () => resolve();
373
- video.onloadeddata = ready;
374
- video.oncanplay = ready;
375
- setTimeout(ready, 800);
376
- });
377
- const vw = video.videoWidth || 640;
378
- const vh = video.videoHeight || 480;
379
- canvas = document.createElement('canvas');
380
- canvas.width = vw;
381
- canvas.height = vh;
382
- const ctx = canvas.getContext('2d');
383
- ctx?.drawImage(video, 0, 0, vw, vh);
384
- const mime = 'image/jpeg';
385
- const dataUrl = canvas.toDataURL(mime, 0.85);
386
- const bytes = Math.floor((dataUrl.length * 3) / 4);
387
- return {
388
- permission: 'granted',
389
- width: vw,
390
- height: vh,
391
- bytes,
392
- mime,
393
- timestamp: Date.now(),
394
- previewDataUrl: dataUrl
395
- };
396
- }
397
- catch (err) {
398
- const errorObj = err;
399
- return {
400
- permission: errorObj?.name === 'NotAllowedError' ? 'denied' : 'error',
401
- error: errorObj?.message || String(err)
402
- };
403
- }
404
- finally {
405
- try {
406
- stream?.getTracks().forEach((track) => track.stop());
407
- }
408
- catch {
409
- // Best-effort cleanup.
410
- }
411
- try {
412
- video?.remove();
413
- }
414
- catch {
415
- // Best-effort cleanup.
416
- }
417
- canvas = null;
418
- }
419
- };
420
503
 
421
504
  class RegisterError extends Error {
422
505
  constructor(status, body) {
@@ -457,14 +540,6 @@
457
540
  }
458
541
  return null;
459
542
  };
460
- const escapeShellSingleQuotes = (value) => value.replace(/'/g, "'\\''");
461
- const buildCurl = (url, body, headers) => {
462
- const payload = escapeShellSingleQuotes(JSON.stringify(body));
463
- const headerFlags = Object.entries(headers)
464
- .map(([key, value]) => `-H '${escapeShellSingleQuotes(`${key}: ${value}`)}'`)
465
- .join(' ');
466
- return `curl -X POST '${url}' ${headerFlags} -d '${payload}'`;
467
- };
468
543
  const registerDevice = async (config, payload, auth) => {
469
544
  const logger = getLogger();
470
545
  const orchestrator = config?.orchestrator;
@@ -481,20 +556,31 @@
481
556
  headers,
482
557
  body: JSON.stringify(payload)
483
558
  });
484
- logger.info('Register request sent:', { url, status: response.status });
485
- getLogger().debug('Register API blueprint (curl):', buildCurl(url, payload, headers));
559
+ // ZGA-538: never log the request body or headers — the payload carries the
560
+ // full device profile and the x-edge-operator-key credential.
561
+ logger.info('Register request sent', {
562
+ url,
563
+ status: response.status,
564
+ bodyBytes: JSON.stringify(payload).length
565
+ });
486
566
  const registerResponseBody = await parseRegisterResponseBody(response);
487
567
  const refusalReason = detectSoftRefusal(registerResponseBody);
488
568
  if (!response.ok && !refusalReason) {
489
569
  const text = typeof registerResponseBody === 'string'
490
570
  ? registerResponseBody
491
571
  : JSON.stringify(registerResponseBody ?? '');
492
- logger.error('Register request failed:', { status: response.status, text });
572
+ logger.error('Register request failed', { status: response.status, message: text });
493
573
  throw new RegisterError(response.status, text);
494
574
  }
495
575
  if (registerResponseBody && typeof registerResponseBody === 'object' && !refusalReason) {
496
576
  const registerResponse = registerResponseBody;
497
- logger.info('Register response parsed:', registerResponse);
577
+ // Shape only — the body carries the session key and the model sample text.
578
+ logger.info('Register response parsed', {
579
+ deviceId: registerResponse.deviceId,
580
+ hasWsUrl: Boolean(registerResponse.wsUrl),
581
+ models: registerResponse.slmConfig?.length ?? 0,
582
+ ttlSeconds: registerResponse.ttlSeconds
583
+ });
498
584
  return registerResponse;
499
585
  }
500
586
  if (refusalReason) {
@@ -528,23 +614,35 @@
528
614
  throw new RegisterError(response.status, 'Register response body is not valid JSON');
529
615
  };
530
616
 
617
+ /**
618
+ * Frame logging is metadata-only (ZGA-538): message type, request ids, byte
619
+ * size — never the frame body. Task frames carry customer input/output and the
620
+ * hello carries the session key, so a content dump here would hand both to any
621
+ * crash reporter watching the host console.
622
+ */
623
+ const frameType = (frame) => {
624
+ if (frame && typeof frame === 'object') {
625
+ const candidate = frame.type;
626
+ if (typeof candidate === 'string' && candidate.length > 0)
627
+ return candidate;
628
+ if (Array.isArray(frame.requests))
629
+ return 'task_batch';
630
+ }
631
+ return 'unknown';
632
+ };
531
633
  class WebSocketClient {
532
634
  constructor(options) {
533
635
  this.options = options;
534
636
  this.logger = getLogger();
535
637
  this.pingTimer = null;
536
- this.consoleWithVerbose = console;
537
638
  this.handleOpen = () => {
538
639
  this.logger.info('WebSocket connection opened');
539
640
  this.options.onOpen?.();
540
- this.logger.debug('Sending hello message:', this.options.hello);
541
- this.logger.info('[WS OUT] hello:', JSON.stringify(this.options.hello));
542
641
  this.send(this.options.hello);
543
642
  // Keepalive starts only once the hello is on the wire.
544
643
  this.startPing();
545
644
  if (this.options.ack) {
546
645
  // Send readiness/error ack immediately after hello.
547
- this.logger.info('[WS OUT] hello_ack:', JSON.stringify(this.options.ack));
548
646
  this.send(this.options.ack);
549
647
  if (this.options.closeAfterAck) {
550
648
  // Optionally close after ack (used for error cases).
@@ -566,24 +664,23 @@
566
664
  if (trimmed === 'pong')
567
665
  return;
568
666
  if (trimmed.length > 0 && trimmed[0] !== '{' && trimmed[0] !== '[') {
569
- this.logger.debug('[WS IN] ignoring non-JSON frame:', trimmed.slice(0, 64));
667
+ this.logger.debug('[WS IN] ignoring non-JSON frame', { bytes: trimmed.length });
570
668
  return;
571
669
  }
572
670
  }
573
671
  try {
574
672
  const data = JSON.parse(raw);
575
- if (this.logger.isEnabled()) {
576
- if (typeof this.consoleWithVerbose.verbose === 'function') {
577
- this.consoleWithVerbose.verbose('[ZeroGPU]', '[WS IN] payload:', data);
578
- }
579
- else {
580
- console.debug('[ZeroGPU]', '[WS IN] payload:', data);
581
- }
582
- }
673
+ this.logger.debug('[WS IN] frame', {
674
+ type: frameType(data),
675
+ requests: Array.isArray(data.requests)
676
+ ? data.requests.length
677
+ : undefined,
678
+ bytes: typeof raw === 'string' ? raw.length : undefined
679
+ });
583
680
  this.options.onMessage(data);
584
681
  }
585
682
  catch (error) {
586
- this.logger.error('Failed to parse WS message', error);
683
+ this.logger.error('Failed to parse WS message', { error: summarizeError(error) });
587
684
  }
588
685
  };
589
686
  this.handleError = (event) => {
@@ -608,7 +705,7 @@
608
705
  this.options.onClose(event);
609
706
  };
610
707
  this.pingIntervalMs = normalizePingIntervalMs(options.pingIntervalSeconds);
611
- this.logger.info('Creating WebSocket connection to:', options.url);
708
+ this.logger.info('Creating WebSocket connection', { url: options.url });
612
709
  this.socket = new WebSocket(options.url);
613
710
  this.socket.onopen = this.handleOpen;
614
711
  this.socket.onmessage = this.handleMessage;
@@ -642,7 +739,7 @@
642
739
  this.socket.send('ping');
643
740
  }
644
741
  catch (error) {
645
- this.logger.debug('Keepalive ping failed', error);
742
+ this.logger.debug('Keepalive ping failed', { error: summarizeError(error) });
646
743
  }
647
744
  try {
648
745
  this.options.onPingTick?.();
@@ -662,8 +759,13 @@
662
759
  return (this.socket.readyState === WebSocket.OPEN || this.socket.readyState === WebSocket.CONNECTING);
663
760
  }
664
761
  send(payload) {
665
- this.logger.debug('[WS OUT] payload:', JSON.stringify(payload));
666
- this.socket.send(JSON.stringify(payload));
762
+ const json = JSON.stringify(payload);
763
+ this.logger.debug('[WS OUT] frame', {
764
+ type: frameType(payload),
765
+ requests: Array.isArray(payload.requests) ? payload.requests.length : undefined,
766
+ bytes: json.length
767
+ });
768
+ this.socket.send(json);
667
769
  }
668
770
  close(code, reason) {
669
771
  this.stopPing();
@@ -1240,8 +1342,7 @@
1240
1342
  * Host-facing lifecycle status and events. The SDK is a guest in someone
1241
1343
  * else's app: this module is how the host observes guardrail state (degraded /
1242
1344
  * recovered / shutdown) without the SDK ever throwing into it. Script-tag
1243
- * consumers get the same signals as `zerogpu:*` window events, matching the
1244
- * existing `zerogpu:cameraPreview` pattern.
1345
+ * consumers get the same signals as `zerogpu:*` window events.
1245
1346
  */
1246
1347
  let lifecycleStatus = 'starting';
1247
1348
  const listeners = {
@@ -1824,9 +1925,12 @@
1824
1925
  *
1825
1926
  * Progressive:
1826
1927
  * 1. If a runner URL is configured, run the tag in the framed runner.
1827
- * 2. Otherwise fall back to a credentialed request beacon so the impression at
1828
- * least reaches the ad server with the user's real IP/UA/cookies (the tag's
1829
- * JS does not run).
1928
+ * 2. Otherwise, on an ordinary web page or WebView (including a Telegram Mini
1929
+ * App) with no restrictive `script-src` CSP, inject a real `<script>`
1930
+ * element so the tag executes directly in the page.
1931
+ * 3. Failing both (no DOM, or a CSP that blocks the injected script), fall back
1932
+ * to a credentialed request beacon so the impression at least reaches the ad
1933
+ * server with the user's real IP/UA/cookies (the tag's JS does not run).
1830
1934
  *
1831
1935
  * Never rejects: a tag is best-effort and must not affect inference.
1832
1936
  */
@@ -1918,18 +2022,107 @@
1918
2022
  });
1919
2023
  };
1920
2024
  /**
1921
- * Fire a JavaScript tracking tag. Runs it in the framed runner when one is
1922
- * available; otherwise fires the request as a beacon. Never rejects.
2025
+ * Execute the tag by injecting a real `<script>` element into the host document.
2026
+ *
2027
+ * This is how a JS tag is *meant* to run on an ordinary web page — including a
2028
+ * Telegram Mini App or any other WebView, which is just a normal DOM with no
2029
+ * extension-style `script-src 'self'` lockdown. The browser fetches the tag with
2030
+ * `Sec-Fetch-Dest: script` and runs it in the page, so the tag's own logic
2031
+ * (impression beacons, etc.) actually executes.
2032
+ *
2033
+ * Unlike a pixel, `load` means the code ran and `error` means it did not: a CSP
2034
+ * `script-src` that forbids the origin (e.g. the MV3 extension's offscreen
2035
+ * document) blocks the load. On error we resolve `null` so the caller can fall
2036
+ * back to the beacon; on load we resolve 'fired' and do NOT beacon, so an
2037
+ * executed tag is never counted twice.
2038
+ *
2039
+ * Resolves:
2040
+ * - 'fired' the script loaded and executed
2041
+ * - 'timeout' it neither loaded nor errored in time (genuinely unknown)
2042
+ * - null no DOM, or the injection failed/was blocked → try the beacon
2043
+ *
2044
+ * Never rejects.
2045
+ */
2046
+ // Only https tags are ever executed in-page. Tier 2 runs the tag in the host
2047
+ // document's context (full DOM / same-origin storage / cookies), so a non-https
2048
+ // URL — http:, data:, blob:, javascript: — must never reach `script.src`. Such
2049
+ // tags resolve `null` here and fall through to the beacon, which still delivers
2050
+ // the impression without running any code.
2051
+ const isExecutableTagUrl = (url) => {
2052
+ try {
2053
+ return new URL(url).protocol === 'https:';
2054
+ }
2055
+ catch {
2056
+ return false;
2057
+ }
2058
+ };
2059
+ const fireViaScriptTag = (url, timeoutMs) => {
2060
+ if (typeof document === 'undefined' || !isExecutableTagUrl(url)) {
2061
+ return Promise.resolve(null);
2062
+ }
2063
+ return new Promise((resolve) => {
2064
+ let settled = false;
2065
+ let script;
2066
+ let timer;
2067
+ const settle = (status) => {
2068
+ if (settled)
2069
+ return;
2070
+ settled = true;
2071
+ if (timer !== undefined)
2072
+ clearTimeout(timer);
2073
+ if (script) {
2074
+ script.onload = null;
2075
+ script.onerror = null;
2076
+ script.remove();
2077
+ }
2078
+ resolve(status);
2079
+ };
2080
+ try {
2081
+ timer = setTimeout(() => settle('timeout'), timeoutMs);
2082
+ script = document.createElement('script');
2083
+ script.async = true;
2084
+ // A tag's JS runs synchronously as it loads, so `onload` fires *after* it
2085
+ // has executed. `error` — a network failure or a CSP `script-src` block —
2086
+ // means it did not run: resolve null and let the caller beacon instead.
2087
+ script.onload = () => settle('fired');
2088
+ script.onerror = () => settle(null);
2089
+ script.src = url;
2090
+ (document.head ?? document.documentElement).appendChild(script);
2091
+ }
2092
+ catch {
2093
+ settle(null);
2094
+ }
2095
+ });
2096
+ };
2097
+ /**
2098
+ * Fire a JavaScript tracking tag. Executes it wherever it can — the framed
2099
+ * runner, or an injected `<script>` on a normal page/WebView — and only falls
2100
+ * back to a non-executing beacon when neither can run it. Never rejects.
1923
2101
  */
1924
2102
  const fireTrackingScript = async (url, timeoutMs = DEFAULT_TIMEOUT_MS) => {
2103
+ // 1. Framed runner: executes off the extension origin when a runner is
2104
+ // configured (the MV3 extension path).
1925
2105
  try {
1926
2106
  const win = await ensureRunner();
1927
- if (win)
1928
- return await runInRunner(win, url, timeoutMs);
2107
+ if (win) {
2108
+ // 'skipped' means the runner could not execute the tag, so it did not
2109
+ // run — fall through to the remaining tiers. 'fired'/'timeout' are terminal.
2110
+ const outcome = await runInRunner(win, url, timeoutMs);
2111
+ if (outcome !== 'skipped')
2112
+ return outcome;
2113
+ }
1929
2114
  }
1930
2115
  catch {
1931
- // Fall through to the beacon on any runner failure.
1932
- }
2116
+ // Fall through on any runner failure.
2117
+ }
2118
+ // 2. Inject a real <script> so the tag executes in the page. This is the
2119
+ // normal path for the SDK loaded on a site via the loader, and for a
2120
+ // Telegram Mini App / other WebViews.
2121
+ const executed = await fireViaScriptTag(url, timeoutMs);
2122
+ if (executed !== null)
2123
+ return executed;
2124
+ // 3. Last resort: fire the request without executing it, so the impression
2125
+ // still reaches the ad server with the user's real IP/UA/cookies.
1933
2126
  return fireBeacon(url, timeoutMs);
1934
2127
  };
1935
2128
 
@@ -2081,7 +2274,7 @@
2081
2274
  };
2082
2275
  }
2083
2276
  catch (error) {
2084
- logger.error('Task failed', error);
2277
+ logger.error('Task failed', { error: summarizeError(error) });
2085
2278
  const message = error.message ?? '';
2086
2279
  const isAllocationFailure = error instanceof RangeError || /out of memory|oom|wasm.*abort|allocation failed/i.test(message);
2087
2280
  getEventReporter().report('task.failed', {
@@ -2160,12 +2353,15 @@
2160
2353
  const results = [];
2161
2354
  for (const request of msg.requests) {
2162
2355
  const result = await executeSingleRequest(request);
2163
- logger.info('[WS OUT] task result:', {
2356
+ // Metadata only (ZGA-538): the response body is customer model output
2357
+ // and must never reach the console — log its size instead.
2358
+ logger.info('[WS OUT] task result', {
2164
2359
  requestId: result.requestId,
2165
2360
  modelId: result.modelId,
2166
- response: result.response,
2361
+ responseBytes: JSON.stringify(result.response ?? null).length,
2362
+ processingTimeMs: result.metadata.processingTime,
2167
2363
  error: result.error,
2168
- errorMessage: result.errorMessage
2364
+ errorMessage: result.errorMessage || undefined
2169
2365
  });
2170
2366
  results.push(result);
2171
2367
  }
@@ -2657,7 +2853,7 @@
2657
2853
  }
2658
2854
  logger.info('[WS] Re-registration timer fired; restarting lifecycle');
2659
2855
  startLifecycle(options).catch((err) => {
2660
- logger.error('[WS] Re-registration attempt failed; will retry', err);
2856
+ logger.error('[WS] Re-registration attempt failed; will retry', { error: summarizeError(err) });
2661
2857
  // Keep the loop alive on transient failures (register/network/model
2662
2858
  // errors). Auth failures and crash-loop cool-downs return cleanly from
2663
2859
  // startLifecycle without throwing, so they end the loop here.
@@ -2685,7 +2881,7 @@
2685
2881
  // Best effort — the register flow below supersedes the session anyway.
2686
2882
  }
2687
2883
  startLifecycle(options).catch((err) => {
2688
- logger.error('[WS] Full re-register failed; scheduling retry', err);
2884
+ logger.error('[WS] Full re-register failed; scheduling retry', { error: summarizeError(err) });
2689
2885
  scheduleReconnect(options, 'socket_closed');
2690
2886
  });
2691
2887
  };
@@ -2721,7 +2917,7 @@
2721
2917
  };
2722
2918
  // Deterministic preflight validation runs before the crash-loop guard so a
2723
2919
  // misconfigured integration never consumes a crash-loop attempt (and never
2724
- // triggers the camera/geo prompts below).
2920
+ // triggers the geolocation prompt below).
2725
2921
  if (!edgeOperatorKey) {
2726
2922
  throw new Error('Missing required header: x-edge-operator-key');
2727
2923
  }
@@ -2756,39 +2952,24 @@
2756
2952
  providedDeviceId: Boolean(providedDeviceId),
2757
2953
  orchestrator: config.orchestrator?.baseUrl
2758
2954
  });
2759
- const rawDeviceInfo = await collectDeviceInfo(config.telemetry, appUserId, deviceId);
2760
- const sanitizedDeviceInfo = stripCameraPreview(rawDeviceInfo);
2761
- setDeviceContext(deviceId, sanitizedDeviceInfo);
2955
+ const deviceInfo = await collectDeviceInfo(config.telemetry, appUserId, deviceId);
2956
+ setDeviceContext(deviceId, deviceInfo);
2762
2957
  initEventReporter({
2763
2958
  enabled: config.telemetry.events,
2764
2959
  endpointUrl: `${config.orchestrator.baseUrl}${config.orchestrator.eventsPath}`,
2765
2960
  operatorKey: edgeOperatorKey,
2766
2961
  deviceId,
2767
2962
  sdkVersion: config.sdkVersion,
2768
- platform: sanitizedDeviceInfo.platform
2963
+ platform: deviceInfo.platform
2769
2964
  });
2770
2965
  const reporter = getEventReporter();
2771
2966
  reporter.report('sdk.init_started', { data: { sdkVersion: config.sdkVersion } });
2772
2967
  reportCrashFromPreviousSession(guard.crash);
2773
2968
  logger.info('[Init] Device info collected', {
2774
- platform: sanitizedDeviceInfo.platform,
2775
- deviceType: sanitizedDeviceInfo.deviceType,
2776
- gpuRenderer: sanitizedDeviceInfo.gpuRenderer
2969
+ platform: deviceInfo.platform,
2970
+ deviceType: deviceInfo.deviceType,
2971
+ gpuRenderer: deviceInfo.gpuRenderer
2777
2972
  });
2778
- if (rawDeviceInfo.camera?.previewDataUrl) {
2779
- try {
2780
- window.dispatchEvent(new CustomEvent('zerogpu:cameraPreview', {
2781
- detail: {
2782
- deviceId,
2783
- previewDataUrl: rawDeviceInfo.camera.previewDataUrl,
2784
- camera: sanitizedDeviceInfo.camera
2785
- }
2786
- }));
2787
- }
2788
- catch {
2789
- logger.warn('Unable to dispatch camera preview event');
2790
- }
2791
- }
2792
2973
  const cachedModelId = isFreshDevice ? null : getCachedModelId();
2793
2974
  setCachedModelId(cachedModelId);
2794
2975
  let cachedInfo = cachedModelId ? getCachedModelInfo(cachedModelId) : null;
@@ -2962,7 +3143,7 @@
2962
3143
  cachedModels: cachedInfo && !cacheInvalid
2963
3144
  ? [{ modelId: cachedInfo.modelId, modelVersion: cachedInfo.modelVersion || '1' }]
2964
3145
  : [],
2965
- device: sanitizedDeviceInfo
3146
+ device: deviceInfo
2966
3147
  };
2967
3148
  let registerResponse;
2968
3149
  let assignedModels = [];
@@ -2973,7 +3154,7 @@
2973
3154
  let postRegisterSample;
2974
3155
  logger.info('[Register] Sending register request', {
2975
3156
  deviceId,
2976
- cachedModels: registerPayload.cachedModels,
3157
+ cachedModels: registerPayload.cachedModels.map((model) => model.modelId),
2977
3158
  sdkVersion: config.sdkVersion
2978
3159
  });
2979
3160
  reporter.report('register.started');
@@ -3024,7 +3205,10 @@
3024
3205
  // TODO(global-types): emit ws.policy_applied once available in the shared
3025
3206
  // event vocabulary (data: {source: 'register', v, changed}).
3026
3207
  if (registrationSettings) {
3027
- logger.info('[Register] Registration settings received', registrationSettings);
3208
+ // Keys only: served settings are operator config, not for host consoles.
3209
+ logger.info('[Register] Registration settings received', {
3210
+ keys: Object.keys(registrationSettings)
3211
+ });
3028
3212
  }
3029
3213
  if (registerResponse.refusalReason) {
3030
3214
  // The server deliberately declined this device (admission rules) — the
@@ -3043,7 +3227,7 @@
3043
3227
  reporter.report('register.succeeded', { durationMs: Math.round(performance.now() - registerStartedAt) });
3044
3228
  markRegisterSuccess();
3045
3229
  reporter.setSessionKey(registerResponse.sessionKey);
3046
- logger.info('Register response received:', {
3230
+ logger.info('Register response received', {
3047
3231
  deviceId: registerResponse.deviceId,
3048
3232
  wsUrl: registerResponse.wsUrl
3049
3233
  });
@@ -3062,13 +3246,8 @@
3062
3246
  }
3063
3247
  logger.info('[Register] Models assigned', {
3064
3248
  count: assignedModels.length,
3065
- models: assignedModels.map((m) => ({
3066
- modelId: m.modelId,
3067
- framework: m.inferenceFramework,
3068
- taskType: m.taskType,
3069
- quantized: m.quantized,
3070
- sizeBytes: m.sizeBytes
3071
- }))
3249
+ models: assignedModels.map((m) => m.modelId),
3250
+ totalBytes: assignedModels.reduce((sum, m) => sum + (m.sizeBytes ?? 0), 0)
3072
3251
  });
3073
3252
  for (const model of assignedModels) {
3074
3253
  modelStatuses[getModelStatusKey(model)] = 'idle';
@@ -3086,10 +3265,10 @@
3086
3265
  setModelInfosByModelId(modelInfosByModelId);
3087
3266
  setModelInfo(primaryModel);
3088
3267
  setSample(primaryModel.sample);
3268
+ // ZGA-538: no session key (credential) and no sample body (task content).
3089
3269
  logger.info('Runtime globals updated from register response', {
3090
- sessionKey: registerResponse.sessionKey,
3091
3270
  taskType: primaryModel.taskType,
3092
- sample: primaryModel.sample
3271
+ hasSample: Boolean(primaryModel.sample)
3093
3272
  });
3094
3273
  if (!cachedInfo || cachedInfo.modelId !== primaryModel.modelId || cacheInvalid) {
3095
3274
  if (cachedInfo && cachedInfo.modelId !== primaryModel.modelId) {
@@ -3362,7 +3541,7 @@
3362
3541
  };
3363
3542
  logger.info('[WS] Connecting WebSocket', {
3364
3543
  wsUrl: registerResponse.wsUrl,
3365
- models: helloSlmConfig
3544
+ models: helloSlmConfig.map((model) => `${model.modelId}:${model.status}`)
3366
3545
  });
3367
3546
  reporter.report('ws.connect_started');
3368
3547
  const connectionPolicy = getConnectionPolicy();
@@ -3393,7 +3572,12 @@
3393
3572
  }
3394
3573
  else if ('type' in message && message.type === 'hello_ack') {
3395
3574
  const ack = message;
3396
- logger.info('[WS] Received hello_ack', ack);
3575
+ // Fields, not the frame — the ack echoes the session key.
3576
+ logger.info('[WS] Received hello_ack', {
3577
+ status: ack.status,
3578
+ deviceId: ack.deviceId,
3579
+ errorMessage: ack.errorMessage
3580
+ });
3397
3581
  reporter.report('ws.hello_ack', {
3398
3582
  code: ack.status,
3399
3583
  message: ack.errorMessage
@@ -3436,7 +3620,9 @@
3436
3620
  }, delayMs);
3437
3621
  }
3438
3622
  else {
3439
- logger.debug('[WS] Unhandled message', message);
3623
+ logger.debug('[WS] Unhandled message', {
3624
+ type: 'type' in message && typeof message.type === 'string' ? message.type : 'unknown'
3625
+ });
3440
3626
  }
3441
3627
  },
3442
3628
  onClose: (event) => {
@@ -3688,15 +3874,6 @@
3688
3874
  }
3689
3875
  });
3690
3876
  };
3691
- const stripCameraPreview = (info) => {
3692
- if (!info.camera?.previewDataUrl) {
3693
- return info;
3694
- }
3695
- return {
3696
- ...info,
3697
- camera: { ...info.camera, previewDataUrl: undefined }
3698
- };
3699
- };
3700
3877
 
3701
3878
  const measure = async (fn) => {
3702
3879
  const start = performance.now();
@@ -3706,12 +3883,6 @@
3706
3883
 
3707
3884
  const TRANSFORMERS_CDN = 'https://cdn.jsdelivr.net/npm/@xenova/transformers@2.17.2/dist/transformers.min.js';
3708
3885
  let transformersRuntimePromise = null;
3709
- const serializeError$5 = (error) => {
3710
- if (error instanceof Error) {
3711
- return { name: error.name, message: error.message, stack: error.stack };
3712
- }
3713
- return { message: String(error) };
3714
- };
3715
3886
  const ensureTransformersRuntime = () => {
3716
3887
  if (window.TransformersPipeline) {
3717
3888
  return Promise.resolve();
@@ -3747,7 +3918,7 @@
3747
3918
  transformersRuntimePromise = null;
3748
3919
  logger.error('[SLM] Failed to import Transformers runtime', {
3749
3920
  runtimeUrl: TRANSFORMERS_CDN,
3750
- error: serializeError$5(error)
3921
+ error: summarizeError(error)
3751
3922
  });
3752
3923
  throw error;
3753
3924
  }
@@ -3856,7 +4027,7 @@
3856
4027
  }
3857
4028
  if (sawNonWasmPayloadAtBase) {
3858
4029
  getLogger().warn('[SLM] ONNX wasm probe got non-wasm payload', {
3859
- wasmBase: baseWithSlash
4030
+ url: baseWithSlash
3860
4031
  });
3861
4032
  }
3862
4033
  }
@@ -3884,12 +4055,6 @@
3884
4055
  }
3885
4056
  };
3886
4057
 
3887
- const serializeError$4 = (error) => {
3888
- if (error instanceof Error) {
3889
- return { name: error.name, message: error.message, stack: error.stack };
3890
- }
3891
- return { message: String(error) };
3892
- };
3893
4058
  const sessionCache = {};
3894
4059
  const createEnvFetch = (modelId, fileBase, cachedFiles, onFileDownloaded, requiredFiles, originalFetch) => {
3895
4060
  const requiredFileList = requiredFiles
@@ -3989,7 +4154,7 @@
3989
4154
  logger.error('[SLM][fetch] non-model wasm/ort request failed', {
3990
4155
  modelId,
3991
4156
  requestUrl: originalRequestUrl,
3992
- error: serializeError$4(error)
4157
+ error: summarizeError(error)
3993
4158
  });
3994
4159
  throw error;
3995
4160
  }
@@ -3997,7 +4162,7 @@
3997
4162
  const relative = resolveRequestedRelative(requestedRelative);
3998
4163
  if (!relative) {
3999
4164
  logger.warn('[SLM] Unexpected model file request; falling back to original fetch', {
4000
- requestedRelative,
4165
+ file: requestedRelative,
4001
4166
  modelId
4002
4167
  });
4003
4168
  return originalFetch(url, init);
@@ -4045,10 +4210,11 @@
4045
4210
  // That string means "every candidate URL threw", i.e. a network/abort
4046
4211
  // failure against the real model host — not an upstream 502 and not a
4047
4212
  // malformed URL actually being requested.
4048
- logger.warn(`[SLM] Model file fetch failed for ${relative}`, {
4213
+ logger.warn('[SLM] Model file fetch failed', {
4049
4214
  modelId,
4050
- candidates: requestUrls,
4051
- error: serializeError$4(err)
4215
+ file: relative,
4216
+ candidateCount: requestUrls.length,
4217
+ error: summarizeError(err)
4052
4218
  });
4053
4219
  return new Response('model_file_fetch_failed', { status: 502, statusText: 'Bad Gateway' });
4054
4220
  }
@@ -4061,12 +4227,6 @@
4061
4227
  classification: 'zero-shot-classification',
4062
4228
  text_generation: 'text2text-generation'
4063
4229
  };
4064
- const serializeError$3 = (error) => {
4065
- if (error instanceof Error) {
4066
- return { name: error.name, message: error.message, stack: error.stack };
4067
- }
4068
- return { message: String(error) };
4069
- };
4070
4230
  const isInvalidArrayLengthError = (error) => {
4071
4231
  const message = error instanceof Error ? error.message : String(error);
4072
4232
  return message.toLowerCase().includes('invalid array length');
@@ -4438,7 +4598,7 @@
4438
4598
  modelRepoId: slm.modelRepoId,
4439
4599
  modelUrl: slm.modelUrl,
4440
4600
  requiredFiles: (slm.requiredFiles ?? []).map((file) => file.name),
4441
- error: serializeError$3(error)
4601
+ error: summarizeError(error)
4442
4602
  });
4443
4603
  await clearModel(slm.modelId, slm.modelVersion).catch(() => { });
4444
4604
  return { error: error, metrics: {} };
@@ -4459,12 +4619,6 @@
4459
4619
 
4460
4620
  const DEFAULT_THRESHOLD = 0.4;
4461
4621
  const DEFAULT_MASK = '[REDACTED]';
4462
- const serializeError$2 = (error) => {
4463
- if (error instanceof Error) {
4464
- return { name: error.name, message: error.message, stack: error.stack };
4465
- }
4466
- return { message: String(error) };
4467
- };
4468
4622
  const parseTokenClassificationOutput = (raw, sourceText) => {
4469
4623
  if (!Array.isArray(raw))
4470
4624
  return [];
@@ -4727,7 +4881,7 @@
4727
4881
  modelVersion: slm.modelVersion,
4728
4882
  modelRepoId: slm.modelRepoId,
4729
4883
  modelUrl: slm.modelUrl,
4730
- error: serializeError$2(error)
4884
+ error: summarizeError(error)
4731
4885
  });
4732
4886
  await clearModel(slm.modelId, slm.modelVersion).catch(() => { });
4733
4887
  return { error: error, metrics: {} };
@@ -4746,12 +4900,6 @@
4746
4900
 
4747
4901
  const WLLAMA_CDN = 'https://cdn.jsdelivr.net/npm/@wllama/wllama@2.3.5/esm/index.js';
4748
4902
  let wllamaRuntimePromise = null;
4749
- const serializeError$1 = (error) => {
4750
- if (error instanceof Error) {
4751
- return { name: error.name, message: error.message, stack: error.stack };
4752
- }
4753
- return { message: String(error) };
4754
- };
4755
4903
  const ensureWllamaRuntime = () => {
4756
4904
  if (window.WllamaModule) {
4757
4905
  return Promise.resolve(window.WllamaModule);
@@ -4770,7 +4918,7 @@
4770
4918
  wllamaRuntimePromise = null;
4771
4919
  getLogger().error('[GGUF] Failed to import wllama runtime', {
4772
4920
  runtimeUrl: WLLAMA_CDN,
4773
- error: serializeError$1(error)
4921
+ error: summarizeError(error)
4774
4922
  });
4775
4923
  throw error;
4776
4924
  }
@@ -4781,12 +4929,6 @@
4781
4929
  const WLLAMA_CDN_BASE = WLLAMA_CDN.replace(/\/esm\/index\.js$/, '/esm');
4782
4930
 
4783
4931
  const DEFAULT_MAX_NEW_TOKENS = 128;
4784
- const serializeError = (error) => {
4785
- if (error instanceof Error) {
4786
- return { name: error.name, message: error.message, stack: error.stack };
4787
- }
4788
- return { message: String(error) };
4789
- };
4790
4932
  const pickGgufFileName = (requiredFiles) => {
4791
4933
  if (!Array.isArray(requiredFiles) || requiredFiles.length === 0)
4792
4934
  return null;
@@ -4991,7 +5133,7 @@
4991
5133
  modelId: slm.modelId,
4992
5134
  modelVersion: slm.modelVersion,
4993
5135
  modelUrl: slm.modelUrl,
4994
- error: serializeError(error)
5136
+ error: summarizeError(error)
4995
5137
  });
4996
5138
  await clearModel(slm.modelId, slm.modelVersion).catch(() => { });
4997
5139
  return { error: error, metrics: {} };
@@ -5031,7 +5173,9 @@
5031
5173
  if (options?.resourcePolicy) {
5032
5174
  setResourcePolicy(options.resourcePolicy);
5033
5175
  if (options.resourcePolicy.disableGuardrails) {
5034
- // Loud by design: a host running without guardrails should know it.
5176
+ // Loud by design: a host running without guardrails should know it, even
5177
+ // with console logs disabled. Static text only — nothing to redact.
5178
+ // eslint-disable-next-line no-console
5035
5179
  console.warn('[ZeroGPU] resourcePolicy.disableGuardrails is set — ALL memory/storage/battery guardrails are OFF. Lab use only.');
5036
5180
  }
5037
5181
  }
@@ -5047,7 +5191,7 @@
5047
5191
  catch (err) {
5048
5192
  // Already reported inside the lifecycle (register.failed / sdk.init_failed
5049
5193
  // / init-failure hello); surface for the host without throwing into it.
5050
- getLogger().error('[Init] SDK initialization failed', err);
5194
+ getLogger().error('[Init] SDK initialization failed', { error: summarizeError(err) });
5051
5195
  }
5052
5196
  return handle;
5053
5197
  };
@@ -5169,7 +5313,9 @@
5169
5313
  // the integrator asked for logs — the failure is reported as an
5170
5314
  // `sdk.init_failed` device event regardless.
5171
5315
  if (enableConsoleLogs) {
5172
- console.error('[ZeroGpuSdk] Auto-init failed', error);
5316
+ // Pre-logger fallback; the error is a summarized diagnostic, never payload.
5317
+ // eslint-disable-next-line no-console
5318
+ console.error('[ZeroGpuSdk] Auto-init failed', error instanceof Error ? `${error.name}: ${error.message}` : String(error));
5173
5319
  }
5174
5320
  });
5175
5321
  };