buffr-blink-cdp 0.1.2

Headless Chromium CDP backend for buffr-engine (Phase 4 spike)
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
//! Permission prompt wiring for the blink-cdp backend (Phase 8a, #88).
//!
//! # Approach
//!
//! Chromium 147's CDP `Browser` domain does not expose a stable
//! `Browser.permissionRequested` event. Instead, a small JS shim is
//! injected via `Page.addScriptToEvaluateOnNewDocument` that wraps the
//! four permission APIs:
//!
//! - `navigator.geolocation.getCurrentPosition` / `watchPosition`
//! - `Notification.requestPermission`
//! - `navigator.permissions.query`
//! - `navigator.mediaDevices.getUserMedia`
//!
//! When a page calls one of these, the shim:
//!
//! 1. Generates a unique request-id (`buffr-<n>`).
//! 2. Posts to the CDP binding `__buffrPermissionRequest` with a JSON
//!    payload `{ id, capability, origin }`.
//! 3. Returns a Promise that resolves when the worker calls
//!    `window.__buffrPermissionResolve(id, "granted"|"denied")` via
//!    `Runtime.evaluate`.
//!
//! The worker thread listens for `Runtime.bindingCalled` events and
//! pushes a neutral [`buffr_engine::permissions::PendingPermission`]
//! onto the shared [`buffr_engine::PermissionsQueue`].  When the UI
//! thread answers the prompt it calls
//! [`BlinkCdpEngine::resolve_permission`] which sends a
//! `Runtime.evaluate` to the correct session to resolve the in-page
//! Promise.
//!
//! # Capability string mapping
//!
//! | JS source                           | capability string  | Capability          |
//! |-------------------------------------|--------------------|---------------------|
//! | `geolocation.getCurrentPosition`    | `"geolocation"`    | `Geolocation`       |
//! | `geolocation.watchPosition`         | `"geolocation"`    | `Geolocation`       |
//! | `Notification.requestPermission`    | `"notifications"`  | `Notifications`     |
//! | `permissions.query({name:"…"})`     | query name         | (name-mapped)       |
//! | `mediaDevices.getUserMedia(video:…)`| `"camera"`         | `Camera`            |
//! | `mediaDevices.getUserMedia(audio:…)`| `"microphone"`     | `Microphone`        |
//!
//! # Deferred items
//!
//! - Auto-grant by URL match: future work.
//! - Persistent permission storage across sessions: deferred to a
//!   `buffr-permissions` extension; Phase 8a is in-memory only.
//! - `Browser.permissionRequested` event-based approach: investigate
//!   in a future patch if more reliable than the shim.

use buffr_permissions::Capability;

// ── Capability mapping ────────────────────────────────────────────────────────

/// Convert a capability name string (from the JS shim) to a
/// [`Capability`] value. Returns `None` for unrecognised names —
/// callers should fall through to `Capability::Other(0)` or skip.
pub fn capability_from_str(name: &str) -> Option<Capability> {
    match name {
        "geolocation" => Some(Capability::Geolocation),
        "notifications" | "push" => Some(Capability::Notifications),
        "camera" => Some(Capability::Camera),
        "microphone" => Some(Capability::Microphone),
        "clipboard-read" | "clipboard-write" | "clipboard" => Some(Capability::Clipboard),
        "midi" | "midi-sysex" => Some(Capability::Midi),
        _ => None,
    }
}

// ── JS shim ───────────────────────────────────────────────────────────────────

/// Generate the JS shim source injected via
/// `Page.addScriptToEvaluateOnNewDocument`.
///
/// The shim replaces the four permission-request APIs with wrappers that
/// post a `__buffrPermissionRequest` binding call and return a Promise
/// that resolves when `window.__buffrPermissionResolve(id, outcome)` is
/// called by the worker thread.
///
/// The shim is intentionally minimal — no dependencies on external
/// libraries, no `eval`, no dynamic code generation beyond the binding
/// name which is a compile-time constant.
pub fn permission_shim_js() -> String {
    r#"
(function () {
  'use strict';

  // Map from request-id → { resolve, reject } for pending permission
  // Promises. Keyed by a monotonic counter prefixed "buffr-".
  const _pendingPerms = {};
  let _permCounter = 0;

  // Called by the Rust worker via Runtime.evaluate to resolve a
  // pending Promise.
  window.__buffrPermissionResolve = function (id, outcome) {
    const entry = _pendingPerms[id];
    if (!entry) return;
    delete _pendingPerms[id];
    entry.resolve(outcome === 'granted' ? 'granted' : 'denied');
  };

  // Post a binding call to the Rust worker and return a Promise.
  function _requestPerm(capability, origin) {
    const id = 'buffr-' + (++_permCounter);
    // P1-2: data: URLs report window.location.origin as the string "null".
    // Replace with a human-readable label so the permission prompt does not
    // show an uninformative "null" as the requesting origin.
    var resolvedOrigin = origin || (window.location && window.location.origin) || '';
    if (resolvedOrigin === 'null') {
      resolvedOrigin = '(internal page)';
    }
    return new Promise(function (resolve, reject) {
      _pendingPerms[id] = { resolve, reject };
      try {
        window.__buffrPermissionRequest(JSON.stringify({
          id: id,
          capability: capability,
          origin: resolvedOrigin
        }));
      } catch (e) {
        // If the binding isn't registered yet, deny immediately so
        // the page doesn't hang.
        delete _pendingPerms[id];
        reject(e);
      }
    });
  }

  // ── Geolocation ─────────────────────────────────────────────────────────────
  if (navigator.geolocation) {
    const _origGeo = navigator.geolocation;
    const _origGetCurrent = _origGeo.getCurrentPosition.bind(_origGeo);
    const _origWatch = _origGeo.watchPosition.bind(_origGeo);

    navigator.geolocation.getCurrentPosition = function (success, error, opts) {
      _requestPerm('geolocation', '').then(function (outcome) {
        if (outcome === 'granted') {
          _origGetCurrent(success, error, opts);
        } else if (error) {
          error({ code: 1, message: 'Permission denied by buffr' });
        }
      });
    };

    navigator.geolocation.watchPosition = function (success, error, opts) {
      let watchId = -1;
      _requestPerm('geolocation', '').then(function (outcome) {
        if (outcome === 'granted') {
          watchId = _origWatch(success, error, opts);
        } else if (error) {
          error({ code: 1, message: 'Permission denied by buffr' });
        }
      });
      return watchId;
    };
  }

  // ── Notifications ────────────────────────────────────────────────────────────
  if (window.Notification) {
    const _origNotifReq = Notification.requestPermission.bind(Notification);
    Notification.requestPermission = function (callback) {
      const p = _requestPerm('notifications', '').then(function (outcome) {
        if (callback) callback(outcome);
        return outcome;
      });
      return p;
    };
  }

  // ── navigator.permissions.query ──────────────────────────────────────────────
  if (navigator.permissions) {
    const _origQuery = navigator.permissions.query.bind(navigator.permissions);
    navigator.permissions.query = function (desc) {
      const name = desc && desc.name ? desc.name : '';
      return _requestPerm(name, '').then(function (outcome) {
        return { state: outcome === 'granted' ? 'granted' : 'denied', name: name };
      });
    };
  }

  // ── mediaDevices.getUserMedia ─────────────────────────────────────────────────
  if (navigator.mediaDevices && navigator.mediaDevices.getUserMedia) {
    const _origGUM = navigator.mediaDevices.getUserMedia.bind(navigator.mediaDevices);
    navigator.mediaDevices.getUserMedia = function (constraints) {
      // P1-3: build a list of capabilities requested so each gets its own prompt.
      const caps = [];
      if (constraints) {
        if (constraints.video) caps.push('camera');
        if (constraints.audio) caps.push('microphone');
      }
      if (caps.length === 0) {
        // No recognised constraint — fall through to the real API (let it fail
        // with its own error rather than issuing a pointless permission prompt).
        return _origGUM(constraints);
      }
      // Issue one _requestPerm call per capability and gate _origGUM on ALL
      // of them resolving to 'granted' (Promise.all).
      var permPromises = caps.map(function (cap) { return _requestPerm(cap, ''); });
      return Promise.all(permPromises).then(function (outcomes) {
        var allGranted = outcomes.every(function (o) { return o === 'granted'; });
        if (allGranted) {
          return _origGUM(constraints);
        }
        return Promise.reject(new DOMException('Permission denied', 'NotAllowedError'));
      });
    };
  }
})();
"#
    .to_string()
}

// ── Tests ─────────────────────────────────────────────────────────────────────

#[cfg(test)]
mod tests {
    use super::*;
    use buffr_permissions::Capability;

    // ── capability_from_str tests ─────────────────────────────────────────────

    #[test]
    fn capability_from_str_geolocation() {
        assert_eq!(
            capability_from_str("geolocation"),
            Some(Capability::Geolocation)
        );
    }

    #[test]
    fn capability_from_str_notifications() {
        assert_eq!(
            capability_from_str("notifications"),
            Some(Capability::Notifications)
        );
        assert_eq!(capability_from_str("push"), Some(Capability::Notifications));
    }

    #[test]
    fn capability_from_str_camera() {
        assert_eq!(capability_from_str("camera"), Some(Capability::Camera));
    }

    #[test]
    fn capability_from_str_microphone() {
        assert_eq!(
            capability_from_str("microphone"),
            Some(Capability::Microphone)
        );
    }

    #[test]
    fn capability_from_str_clipboard() {
        assert_eq!(
            capability_from_str("clipboard-read"),
            Some(Capability::Clipboard)
        );
        assert_eq!(
            capability_from_str("clipboard-write"),
            Some(Capability::Clipboard)
        );
        assert_eq!(
            capability_from_str("clipboard"),
            Some(Capability::Clipboard)
        );
    }

    #[test]
    fn capability_from_str_midi() {
        assert_eq!(capability_from_str("midi"), Some(Capability::Midi));
        assert_eq!(capability_from_str("midi-sysex"), Some(Capability::Midi));
    }

    #[test]
    fn capability_from_str_unknown_returns_none() {
        assert!(capability_from_str("storage-access").is_none());
        assert!(capability_from_str("").is_none());
        assert!(capability_from_str("payment-handler").is_none());
    }

    // ── shim JS generation tests ──────────────────────────────────────────────

    #[test]
    fn shim_js_contains_binding_name() {
        let js = permission_shim_js();
        assert!(
            js.contains("__buffrPermissionRequest"),
            "shim must reference the CDP binding name"
        );
    }

    #[test]
    fn shim_js_contains_resolve_fn() {
        let js = permission_shim_js();
        assert!(
            js.contains("__buffrPermissionResolve"),
            "shim must define the resolve function"
        );
    }

    #[test]
    fn shim_js_covers_geolocation() {
        let js = permission_shim_js();
        assert!(
            js.contains("navigator.geolocation"),
            "shim must wrap geolocation"
        );
        assert!(
            js.contains("getCurrentPosition"),
            "shim must wrap getCurrentPosition"
        );
        assert!(js.contains("watchPosition"), "shim must wrap watchPosition");
    }

    #[test]
    fn shim_js_covers_notifications() {
        let js = permission_shim_js();
        assert!(
            js.contains("Notification.requestPermission"),
            "shim must wrap Notification.requestPermission"
        );
    }

    #[test]
    fn shim_js_covers_permissions_query() {
        let js = permission_shim_js();
        assert!(
            js.contains("navigator.permissions.query"),
            "shim must wrap navigator.permissions.query"
        );
    }

    #[test]
    fn shim_js_covers_get_user_media() {
        let js = permission_shim_js();
        assert!(js.contains("getUserMedia"), "shim must wrap getUserMedia");
    }

    #[test]
    fn shim_js_not_empty() {
        let js = permission_shim_js();
        assert!(!js.trim().is_empty(), "shim JS must not be empty");
    }

    // ── bindingCalled payload → PendingPermission mapping test ───────────────

    #[test]
    fn binding_payload_parse_geolocation() {
        // Simulate the JSON payload posted by the shim.
        let payload =
            r#"{"id":"buffr-1","capability":"geolocation","origin":"https://example.com"}"#;
        let v: serde_json::Value = serde_json::from_str(payload).unwrap();
        let id = v["id"].as_str().unwrap();
        let cap_str = v["capability"].as_str().unwrap();
        let origin = v["origin"].as_str().unwrap();

        assert_eq!(id, "buffr-1");
        assert_eq!(origin, "https://example.com");
        let cap = capability_from_str(cap_str).unwrap();
        assert_eq!(cap, Capability::Geolocation);
    }

    #[test]
    fn binding_payload_parse_camera() {
        let payload =
            r#"{"id":"buffr-2","capability":"camera","origin":"https://meet.example.com"}"#;
        let v: serde_json::Value = serde_json::from_str(payload).unwrap();
        let cap = capability_from_str(v["capability"].as_str().unwrap()).unwrap();
        assert_eq!(cap, Capability::Camera);
    }

    #[test]
    fn binding_payload_parse_unknown_capability() {
        let payload = r#"{"id":"buffr-3","capability":"payment-handler","origin":"https://shop.example.com"}"#;
        let v: serde_json::Value = serde_json::from_str(payload).unwrap();
        let cap = capability_from_str(v["capability"].as_str().unwrap());
        assert!(cap.is_none(), "unknown capability should return None");
    }

    // ── P1-2: null origin replacement ─────────────────────────────────────────

    #[test]
    fn shim_js_replaces_null_origin() {
        let js = permission_shim_js();
        assert!(
            js.contains("(internal page)"),
            "shim must replace 'null' origin with '(internal page)'"
        );
        assert!(
            js.contains("=== 'null'"),
            "shim must special-case the string 'null' from data: URL origin"
        );
    }

    // ── P1-3: getUserMedia dual-cap prompts ───────────────────────────────────

    #[test]
    fn shim_js_getusermedia_uses_promise_all() {
        let js = permission_shim_js();
        assert!(
            js.contains("Promise.all"),
            "shim getUserMedia must use Promise.all for dual-cap requests"
        );
    }

    #[test]
    fn shim_js_getusermedia_prompts_both_caps() {
        let js = permission_shim_js();
        // Both 'camera' and 'microphone' must be pushed when the constraint
        // includes both video and audio.
        assert!(
            js.contains("caps.push('camera')"),
            "shim must push 'camera' cap"
        );
        assert!(
            js.contains("caps.push('microphone')"),
            "shim must push 'microphone' cap"
        );
    }
}