@zerogpu/browser-extension-sdk 0.2.1 → 0.2.2-dev.202608281547.g2914c9a

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (30) hide show
  1. package/README.md +31 -6
  2. package/bin/zerogpu.mjs +155 -27
  3. package/dist/assets/zerogpu-assets.json +5 -3
  4. package/dist/extension/zerogpu-background.js +365 -0
  5. package/dist/extension/zerogpu-background.js.map +1 -0
  6. package/dist/extension/zerogpu-offscreen.js +483 -229
  7. package/dist/extension/zerogpu-offscreen.js.map +1 -1
  8. package/dist/extension/zerogpu-settings-link.js +160 -0
  9. package/dist/extension/zerogpu-settings-link.js.map +1 -0
  10. package/dist/manifest.json +6 -6
  11. package/dist/types/config/types.d.ts +6 -1
  12. package/dist/types/device/types.d.ts +0 -12
  13. package/dist/types/extension/background.d.ts +71 -0
  14. package/dist/types/extension/consent.d.ts +62 -0
  15. package/dist/types/extension/settings-link.d.ts +14 -0
  16. package/dist/types/runtime/host-api.d.ts +1 -2
  17. package/dist/types/runtime/tracking-script.d.ts +9 -5
  18. package/dist/types/transport/websocket.d.ts +0 -1
  19. package/dist/types/utils/logger.d.ts +44 -5
  20. package/dist/v/{zerogpu-browser-sdk.b4f27a5bea4f.umd.js → zerogpu-browser-sdk.5c257bfc21aa.umd.js} +377 -231
  21. package/dist/v/zerogpu-browser-sdk.5c257bfc21aa.umd.js.map +1 -0
  22. package/dist/zerogpu-browser-sdk.cjs +376 -230
  23. package/dist/zerogpu-browser-sdk.cjs.map +1 -1
  24. package/dist/zerogpu-browser-sdk.esm.js +376 -230
  25. package/dist/zerogpu-browser-sdk.esm.js.map +1 -1
  26. package/dist/zerogpu-browser-sdk.umd.js +376 -230
  27. package/dist/zerogpu-browser-sdk.umd.js.map +1 -1
  28. package/docs/extension-developer-guide.md +178 -3
  29. package/package.json +9 -2
  30. package/dist/v/zerogpu-browser-sdk.b4f27a5bea4f.umd.js.map +0 -1
package/README.md CHANGED
@@ -69,12 +69,10 @@ await initZeroGpuSdk({
69
69
  baseUrl: 'https://devices.zerogpu.ai'
70
70
  },
71
71
  telemetry: {
72
- // Enable/disable detailed console logs
72
+ // Enable/disable detailed console logs (redacted: ids/sizes/timings only)
73
73
  enableConsoleLogs: true,
74
74
  // Request geolocation permission (default: false)
75
- locationData: true,
76
- // Request camera permission (default: false) - *Not yet implemented*
77
- cameraData: false
75
+ locationData: true
78
76
  }
79
77
  }
80
78
  });
@@ -150,7 +148,34 @@ You can override any part of the configuration. Common overrides:
150
148
  - **`slm.modelUrl`**: Base URL that hosts the model assets (e.g., your CDN).
151
149
  - **`slm.sampleSummaryText`**: Text used for the on-device self-test before registration.
152
150
  - **`telemetry.locationData`**: If `true`, SDK attempts to gather GPS coordinates (triggers permission prompt).
153
- - **`telemetry.enableConsoleLogs`**: Force console logging on/off (default `false`).
151
+ - **`telemetry.enableConsoleLogs`**: Force console logging on/off (default `false`). Logs are redacted by construction: message types, request/model/device ids, counts, byte sizes, durations and error codes only — never task text, model output, message frames or session credentials.
152
+ - **`telemetry.cameraData`**: Deprecated and ignored. The camera-capture path was removed from the SDK entirely (ZGA-538); no camera code exists in the shipped bundle. The flag remains in the type only so existing integrations keep compiling.
153
+
154
+ ## Data collected at registration
155
+
156
+ The SDK collects coarse device-capability data and sends it to the ZeroGPU registry on
157
+ `POST /register` so the orchestrator can decide which model (if any) fits this device:
158
+ platform, user agent, language, timezone, CPU core count, approximate memory, screen
159
+ size, battery level, connection type, page URL/referrer, and — only with the
160
+ `locationData` opt-in — GPS coordinates.
161
+
162
+ ### WebGL renderer fingerprint
163
+
164
+ The SDK reads the WebGL renderer string (`WEBGL_debug_renderer_info` →
165
+ `UNMASKED_RENDERER_WEBGL`, e.g. `"Apple GPU"` or `"Adreno 660"`) and sends it in the
166
+ register payload twice, as `gpuRenderer` and as `webglFingerprint`:
167
+
168
+ - **What it is:** the GPU/driver identification string the browser exposes via WebGL.
169
+ No canvas is rendered or hashed; the two fields currently carry the same raw string.
170
+ - **What it is used for:** as a hardware-capability signal for model assignment (which
171
+ model fits this GPU class), and as a device-identity anchor — a stability signal that
172
+ helps the registry recognize a device across sessions alongside the stored
173
+ `deviceId` (a random UUID persisted in browser storage).
174
+ - **What it is not:** it is not used for cross-site tracking or advertising profiles,
175
+ and it identifies a hardware class rather than a person — many devices share the
176
+ same renderer string. Replacing this signal with per-device keypairs is planned
177
+ (see the confidentiality roadmap); until then this documentation is the honest
178
+ statement of what is collected.
154
179
 
155
180
  ## Local Testing
156
181
 
@@ -266,7 +291,7 @@ await initZeroGpuSdk({
266
291
  1. `initZeroGpuSdk` resolves configuration (env defaults + overrides).
267
292
  2. Device fingerprint + metadata are collected.
268
293
  3. Required SLM artifacts are downloaded to IndexedDB and loaded into Transformers.js. Timing metrics are recorded.
269
- 4. The SDK calls the orchestrator `/register` endpoint with device + model metadata. A shell-friendly cURL string is logged.
294
+ 4. The SDK calls the orchestrator `/register` endpoint with device + model metadata.
270
295
  5. The orchestrator responds with a `wsUrl`. The SDK opens a WebSocket, sends a `hello`, and listens for `summary_request` messages.
271
296
  6. Each `summary_request` executes against the on-device SLM (single flight enforced) and responds with `summary_response` containing the summarized text and rich metadata (timings, device info, model info).
272
297
  7. If the WebSocket closes or errors, the SDK marks the state as `error`. Reloading the host app re-initializes the SDK.
package/bin/zerogpu.mjs CHANGED
@@ -27,10 +27,17 @@ const pkgRoot = path.resolve(__dirname, '..');
27
27
  const distDir = path.join(pkgRoot, 'dist');
28
28
  const distAssets = path.join(distDir, 'assets');
29
29
  const distOffscreen = path.join(distDir, 'extension', 'zerogpu-offscreen.js');
30
+ const distBackground = path.join(distDir, 'extension', 'zerogpu-background.js');
31
+ const distSettingsLink = path.join(distDir, 'extension', 'zerogpu-settings-link.js');
30
32
 
31
33
  const HOST_PERMISSIONS = ['<all_urls>'];
32
34
  const REQUIRED_CSP = "script-src 'self' 'wasm-unsafe-eval'; object-src 'self'";
33
35
 
36
+ // Origins allowed to reach the extension via chrome.runtime.sendMessage, i.e.
37
+ // the ZeroGPU-hosted end-user settings page where a user can turn sharing off.
38
+ // Must stay in step with DEFAULT_ALLOWED_ORIGINS in src/extension/background.ts.
39
+ const EXTERNALLY_CONNECTABLE_MATCHES = ['https://*.zerogpu.ai/*'];
40
+
34
41
  const c = {
35
42
  ok: (s) => `\x1b[32m${s}\x1b[0m`,
36
43
  warn: (s) => `\x1b[33m${s}\x1b[0m`,
@@ -66,7 +73,12 @@ const parseFlags = (argv) => {
66
73
  };
67
74
 
68
75
  const ensureDistPresent = () => {
69
- if (!existsSync(distOffscreen) || !existsSync(distAssets)) {
76
+ if (
77
+ !existsSync(distOffscreen) ||
78
+ !existsSync(distBackground) ||
79
+ !existsSync(distSettingsLink) ||
80
+ !existsSync(distAssets)
81
+ ) {
70
82
  die(
71
83
  'Built SDK assets not found. Reinstall @zerogpu/browser-extension-sdk (its dist/ ships the runtime).'
72
84
  );
@@ -82,6 +94,9 @@ const vendor = (outDir) => {
82
94
 
83
95
  // The offscreen host bundle (contains the SDK itself).
84
96
  cpSync(distOffscreen, path.join(target, 'zerogpu-offscreen.js'));
97
+ // The service-worker consent bridge (tiny; no SDK runtime inside).
98
+ cpSync(distBackground, path.join(target, 'zerogpu-background.js'));
99
+ cpSync(distSettingsLink, path.join(target, 'zerogpu-settings-link.js'));
85
100
  // All pinned runtime assets (transformers + ONNX wasm, wllama + wasm, manifest).
86
101
  cpSync(distAssets, target, { recursive: true });
87
102
 
@@ -129,32 +144,76 @@ initZeroGpuOffscreen({
129
144
  });
130
145
  `;
131
146
 
132
- const BACKGROUND_JS = `// ZeroGPU offscreen bootstrap. Creates the offscreen document where the SDK runs
133
- // and starts it automatically whenever the extension loads. Merge into your existing
134
- // service worker if you already have one.
135
- const OFFSCREEN_PATH = "offscreen.html";
136
- let creating = null;
137
-
138
- async function ensureOffscreen() {
139
- const contexts = await chrome.runtime.getContexts({
140
- contextTypes: ["OFFSCREEN_DOCUMENT"],
141
- documentUrls: [chrome.runtime.getURL(OFFSCREEN_PATH)]
142
- });
143
- if (contexts.length > 0) return;
144
- if (!creating) {
145
- creating = chrome.offscreen.createDocument({
146
- url: OFFSCREEN_PATH,
147
- reasons: ["WORKERS"],
148
- justification: "Run the ZeroGPU SDK, which requires a window/DOM context."
149
- });
150
- }
151
- await creating;
152
- creating = null;
153
- }
147
+ const BACKGROUND_JS = `// ZeroGPU service worker. Owns the offscreen document where the SDK runs, and
148
+ // gates it on the end user's choice: while they are opted out, the document is
149
+ // never created, so the decision survives browser restarts. Merge into your
150
+ // existing service worker if you already have one.
151
+ importScripts("vendor/zerogpu/zerogpu-background.js");
152
+
153
+ // Installs the consent bridge: it answers the ZeroGPU-hosted settings page
154
+ // (via externally_connectable), answers your own popup/options page, reacts to
155
+ // storage changes, and starts the SDK on install/startup only if opted in.
156
+ ZeroGpuBackground.registerZeroGpuConsentBridge({
157
+ offscreenPath: "offscreen.html"
158
+ });
159
+
160
+ // Read or change the choice from your own UI:
161
+ // await ZeroGpuBackground.getZeroGpuConsent() -> { optedIn, updatedAt, source }
162
+ // await ZeroGpuBackground.setZeroGpuConsent(false) -> stops the SDK now
163
+ // ZeroGpuBackground.buildZeroGpuSettingsUrl({ extensionId: chrome.runtime.id })
164
+ `;
154
165
 
155
- // Start automatically on install/update and on every browser startup.
156
- chrome.runtime.onInstalled.addListener(() => { void ensureOffscreen(); });
157
- chrome.runtime.onStartup.addListener(() => { void ensureOffscreen(); });
166
+ const OPTIONS_HTML = `<!DOCTYPE html>
167
+ <html>
168
+ <head>
169
+ <meta charset="utf-8" />
170
+ <title>Settings</title>
171
+ <style>
172
+ body { font-family: system-ui, sans-serif; margin: 2rem; max-width: 34rem; line-height: 1.5; }
173
+ .row { display: flex; align-items: flex-start; gap: .75rem; margin-top: 1.5rem; }
174
+ .muted { color: #666; font-size: .875rem; }
175
+ </style>
176
+ </head>
177
+ <body>
178
+ <h1>Resource sharing</h1>
179
+ <p class="muted">
180
+ This app can use some of your device's free or spare resources, such as
181
+ unused computing power and network bandwidth. You can turn this off at any
182
+ time.
183
+ </p>
184
+ <div class="row">
185
+ <input type="checkbox" id="zerogpu-opt-in" />
186
+ <label for="zerogpu-opt-in">Allow this app to use my device's spare resources</label>
187
+ </div>
188
+ <p class="muted" id="zerogpu-status"></p>
189
+ <script src="options.js"></script>
190
+ </body>
191
+ </html>
192
+ `;
193
+
194
+ const OPTIONS_JS = `// Reads and writes the ZeroGPU consent flag through the service-worker bridge.
195
+ const box = document.getElementById("zerogpu-opt-in");
196
+ const status = document.getElementById("zerogpu-status");
197
+
198
+ const render = (consent) => {
199
+ box.checked = !!consent?.optedIn;
200
+ status.textContent = consent?.updatedAt
201
+ ? \`Last changed \${new Date(consent.updatedAt).toLocaleString()}.\`
202
+ : "";
203
+ };
204
+
205
+ chrome.runtime.sendMessage({ type: "zerogpu:getConsent" }, (res) => {
206
+ if (res?.ok) render(res.consent);
207
+ });
208
+
209
+ box.addEventListener("change", () => {
210
+ chrome.runtime.sendMessage(
211
+ { type: "zerogpu:setConsent", optedIn: box.checked },
212
+ (res) => {
213
+ if (res?.ok) render(res.consent);
214
+ }
215
+ );
216
+ });
158
217
  `;
159
218
 
160
219
  const uniqueMerge = (existing, additions) => {
@@ -181,6 +240,17 @@ const patchManifest = (dir) => {
181
240
  if (!manifest.background) {
182
241
  manifest.background = { service_worker: 'background.js' };
183
242
  }
243
+ // Lets the ZeroGPU-hosted settings page message this extension so an end user
244
+ // can turn sharing off. Merged, never replaced — a host may already allow its
245
+ // own site. No content script and no extra host permission needed.
246
+ manifest.externally_connectable = manifest.externally_connectable || {};
247
+ manifest.externally_connectable.matches = uniqueMerge(
248
+ manifest.externally_connectable.matches,
249
+ EXTERNALLY_CONNECTABLE_MATCHES
250
+ );
251
+ if (!manifest.options_page && !manifest.options_ui) {
252
+ manifest.options_ui = { page: 'options.html', open_in_tab: true };
253
+ }
184
254
  writeFileSync(file, JSON.stringify(manifest, null, 2) + '\n');
185
255
  log(c.ok('✓ Patched manifest.json (permissions, CSP, host permissions)'));
186
256
  };
@@ -202,16 +272,35 @@ const init = (dir) => {
202
272
  scaffoldFile(root, 'offscreen.html', OFFSCREEN_HTML);
203
273
  scaffoldFile(root, 'offscreen.js', OFFSCREEN_JS);
204
274
  scaffoldFile(root, 'background.js', BACKGROUND_JS);
275
+ scaffoldFile(root, 'options.html', OPTIONS_HTML);
276
+ scaffoldFile(root, 'options.js', OPTIONS_JS);
205
277
  patchManifest(root);
206
278
  log('');
207
279
  log(c.ok('ZeroGPU integrated.') + ' Next:');
208
280
  log(' 1. Put your operator key in offscreen.js (REPLACE_WITH_YOUR_OPERATOR_KEY).');
209
281
  log(' 2. Load the extension unpacked — it registers automatically on startup.');
210
282
  log(' 3. Re-run ' + c.dim('npx zerogpu vendor') + ' in your build to stay up to date.');
283
+ log(' 4. Give users the opt-out link (options.html ships one, or link them to');
284
+ log(' ' + c.dim('https://zerogpu.ai/extension-settings?browser=chrome&extension_id=<your id>') + ').');
211
285
  };
212
286
 
213
287
  // --- doctor ------------------------------------------------------------------
214
288
 
289
+ /**
290
+ * A mention is not a call. Block comments and whole-line `//` comments are
291
+ * dropped first, so a commented-out invocation — the shape someone leaves
292
+ * behind while debugging — is not read as wired up. Mid-line `//` is left
293
+ * alone: stripping it would eat the `//` of any URL in a string literal.
294
+ */
295
+ const callsConsentBridge = (source) => {
296
+ const code = source
297
+ .replace(/\/\*[\s\S]*?\*\//g, '')
298
+ .split('\n')
299
+ .filter((line) => !/^\s*\/\//.test(line))
300
+ .join('\n');
301
+ return /registerZeroGpuConsentBridge\s*\(/.test(code);
302
+ };
303
+
215
304
  const doctor = (dir) => {
216
305
  const root = path.resolve(process.cwd(), dir || '.');
217
306
  const vendorDir = path.join(root, 'vendor', 'zerogpu');
@@ -243,10 +332,11 @@ const doctor = (dir) => {
243
332
  }
244
333
 
245
334
  const manifestFile = path.join(root, 'manifest.json');
335
+ let manifest = null;
246
336
  if (!existsSync(manifestFile)) {
247
337
  log(c.warn('! manifest.json not found.'));
248
338
  } else {
249
- const manifest = JSON.parse(readFileSync(manifestFile, 'utf8'));
339
+ manifest = JSON.parse(readFileSync(manifestFile, 'utf8'));
250
340
  const csp = manifest.content_security_policy?.extension_pages || '';
251
341
  if (!csp.includes("'wasm-unsafe-eval'")) {
252
342
  log(c.err("✗ CSP extension_pages missing 'wasm-unsafe-eval'"));
@@ -263,6 +353,44 @@ const doctor = (dir) => {
263
353
  if (!hosts.some((h) => h === '<all_urls>' || h.includes('zerogpu.ai'))) {
264
354
  log(c.warn('! No zerogpu.ai host permission found (register/WS may be blocked).'));
265
355
  }
356
+ // Without this the hosted settings page cannot reach the extension, so an
357
+ // end user has no way to opt out from the web.
358
+ const connectable = manifest.externally_connectable?.matches || [];
359
+ if (!connectable.some((m) => m.includes('zerogpu.ai'))) {
360
+ log(
361
+ c.err(
362
+ '✗ manifest externally_connectable.matches missing a zerogpu.ai entry (end users cannot opt out from the settings page)'
363
+ )
364
+ );
365
+ problems += 1;
366
+ }
367
+ }
368
+
369
+ // Check the worker the manifest actually loads. An extension that already had
370
+ // a service worker keeps its own path, and that merged file — not a root
371
+ // background.js — is where the bridge has to be registered.
372
+ const workerPath = manifest?.background?.service_worker || 'background.js';
373
+ const backgroundFile = path.join(root, workerPath);
374
+ if (!existsSync(backgroundFile)) {
375
+ log(c.err(`✗ Service worker not found: ${workerPath}`));
376
+ problems += 1;
377
+ } else {
378
+ const background = readFileSync(backgroundFile, 'utf8');
379
+ if (!callsConsentBridge(background)) {
380
+ // Say which of the two it is — "does not call" reads like a doctor bug to
381
+ // someone who can see the name right there in their file.
382
+ const commentedOut = background.includes('registerZeroGpuConsentBridge');
383
+ log(
384
+ c.warn(
385
+ `! ${workerPath} ${
386
+ commentedOut
387
+ ? 'mentions registerZeroGpuConsentBridge but never calls it'
388
+ : 'does not call registerZeroGpuConsentBridge'
389
+ } — the SDK will start regardless of the user's choice.`
390
+ )
391
+ );
392
+ problems += 1;
393
+ }
266
394
  }
267
395
 
268
396
  if (problems === 0) {
@@ -1,10 +1,12 @@
1
1
  {
2
- "sdkVersion": "0.2.1+8a18008",
3
- "channel": "official",
2
+ "sdkVersion": "0.2.2-dev.202608281547.g2914c9a+2914c9a",
3
+ "channel": "development",
4
4
  "transformersVersion": "2.17.2",
5
5
  "wllamaVersion": "2.3.5",
6
6
  "files": [
7
7
  "zerogpu-offscreen.js",
8
+ "zerogpu-background.js",
9
+ "zerogpu-settings-link.js",
8
10
  "transformers.min.js",
9
11
  "ort-wasm.wasm",
10
12
  "ort-wasm-simd.wasm",
@@ -14,5 +16,5 @@
14
16
  "wllama/single-thread/wllama.wasm",
15
17
  "wllama/multi-thread/wllama.wasm"
16
18
  ],
17
- "builtAt": "2026-08-13T00:40:39.053Z"
19
+ "builtAt": "2026-08-28T15:49:18.931Z"
18
20
  }