From 18807b8ac230dcc495c566d89eaa001db007a941 Mon Sep 17 00:00:00 2001 From: Alan Silva Date: Sun, 29 Nov 2026 19:06:58 +0000 Subject: [PATCH] Clipboard on http: copy and paste work without the Clipboard API Over plain http on a tailnet address the page is not a secure context and navigator.clipboard is undefined, so the web engine refused every copy. ClipboardReportingMessenger now answers clipboard calls through the browser's legacy clipboard when the API is missing (web only, conditional import): copy uses execCommand('copy') with a one-shot copy-event listener (no focus or selection change); a paste key's Clipboard.getData takes the browser's own paste event, the key reported not-handled so the browser still fires it. A Paste button/menu says to use Ctrl+V or the https address. Secure pages keep the engine path. Capture kit: --insecure and clipboard=. Co-Authored-By: Claude Opus 5.5 --- app/lib/application/clipboard_failures.dart | 57 +++-- app/lib/application/insecure_clipboard.dart | 132 ++++++++++ .../application/insecure_clipboard_host.dart | 9 + .../insecure_clipboard_host_stub.dart | 3 + .../insecure_clipboard_host_web.dart | 96 ++++++++ app/lib/application/pipelines_binding.dart | 14 +- app/notes/clipboard-keys.md | 49 ++++ .../application/clipboard_failures_test.dart | 5 +- .../application/insecure_clipboard_test.dart | 228 ++++++++++++++++++ app/tool/capture/README.md | 6 + app/tool/capture/browser.mjs | 11 +- app/tool/capture/capture.mjs | 48 +++- .../examples/clipboard-insecure-chat.json | 26 ++ .../examples/clipboard-insecure-terminal.json | 56 +++++ 14 files changed, 714 insertions(+), 26 deletions(-) create mode 100644 app/lib/application/insecure_clipboard.dart create mode 100644 app/lib/application/insecure_clipboard_host.dart create mode 100644 app/lib/application/insecure_clipboard_host_stub.dart create mode 100644 app/lib/application/insecure_clipboard_host_web.dart create mode 100644 app/test/application/insecure_clipboard_test.dart create mode 100644 app/tool/capture/examples/clipboard-insecure-chat.json create mode 100644 app/tool/capture/examples/clipboard-insecure-terminal.json diff --git a/app/lib/application/clipboard_failures.dart b/app/lib/application/clipboard_failures.dart index 83d23ebb..c9fb506e 100644 --- a/app/lib/application/clipboard_failures.dart +++ b/app/lib/application/clipboard_failures.dart @@ -1,6 +1,8 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; +import 'insecure_clipboard.dart'; + /// The app's root messenger, for messages no screen owns. final GlobalKey appScaffoldMessengerKey = GlobalKey(); @@ -10,10 +12,20 @@ final GlobalKey appScaffoldMessengerKey = GlobalKey(); /// The web reports a refused clipboard write or read (no permission, an /// insecure page, a browser without the clipboard API) as an error reply. String? clipboardFailureMessage(String method, PlatformException error) { + if (error.code == insecureClipboardCode) return error.message; + final detail = error.message?.trim() ?? ''; + // The engine's refusal on a page without the Clipboard API (one the + // legacy clipboard did not answer). + if (detail == 'Clipboard is not available in the context.') { + return switch (method) { + 'Clipboard.setData' => insecureCopyMessage(), + 'Clipboard.getData' => insecurePasteMessage(), + _ => null, + }; + } // The web's own reason ("Clipboard is not available in the context." on a // page that is not secure) helps; its generic "Clipboard.setData failed." // does not. - final detail = error.message?.trim() ?? ''; final why = detail.isEmpty || detail.startsWith('Clipboard.') ? 'the browser refused access to the clipboard' : detail; @@ -40,11 +52,19 @@ bool showAppMessage(String message) { /// the terminal) writes through [Clipboard] on the platform channel, and /// most never look at the result: a refusal would otherwise only reach the /// console. The reply still reaches the caller unchanged. +/// +/// With [insecure] (the web), a page without the Clipboard API copies and +/// pastes through the browser's legacy clipboard instead ([InsecureClipboard]). class ClipboardReportingMessenger implements BinaryMessenger { - ClipboardReportingMessenger(this._inner, {void Function(String)? report}) - : _report = report ?? _show; + ClipboardReportingMessenger( + this._inner, { + void Function(String)? report, + InsecureClipboard? insecure, + }) : _report = report ?? _show, + _insecure = insecure; // ignore: prefer_initializing_formals final BinaryMessenger _inner; + final InsecureClipboard? _insecure; final void Function(String message) _report; static void _show(String message) => showAppMessage(message); @@ -53,19 +73,19 @@ class ClipboardReportingMessenger implements BinaryMessenger { @override Future? send(String channel, ByteData? message) { - final reply = _inner.send(channel, message); - if (reply == null || - channel != SystemChannels.platform.name || - message == null) { - return reply; + if (channel != SystemChannels.platform.name || message == null) { + return _inner.send(channel, message); } - final String method; + final MethodCall call; try { - method = _codec.decodeMethodCall(message).method; + call = _codec.decodeMethodCall(message); } on Object { - return reply; + return _inner.send(channel, message); } - if (!method.startsWith('Clipboard.')) return reply; + final method = call.method; + if (!method.startsWith('Clipboard.')) return _inner.send(channel, message); + final reply = _insecure?.answer(call) ?? _inner.send(channel, message); + if (reply == null) return reply; return reply.then((data) { _check(method, data); return data; @@ -95,6 +115,15 @@ class ClipboardReportingMessenger implements BinaryMessenger { _inner.handlePlatformMessage(channel, data, callback); @override - void setMessageHandler(String channel, MessageHandler? handler) => - _inner.setMessageHandler(channel, handler); + void setMessageHandler(String channel, MessageHandler? handler) { + final insecure = _insecure; + _inner.setMessageHandler( + channel, + handler != null && + insecure != null && + channel == SystemChannels.keyEvent.name + ? insecure.keyEventHandler(handler) + : handler, + ); + } } diff --git a/app/lib/application/insecure_clipboard.dart b/app/lib/application/insecure_clipboard.dart new file mode 100644 index 00000000..19481f27 --- /dev/null +++ b/app/lib/application/insecure_clipboard.dart @@ -0,0 +1,132 @@ +import 'package:flutter/foundation.dart'; +import 'package:flutter/services.dart'; + +/// The browser's clipboard without the Clipboard API: on a page that is not +/// a secure context (plain http on a non-localhost address) the browser has +/// no `navigator.clipboard`, so Flutter's web engine refuses every +/// `Clipboard.setData` and `Clipboard.getData`. +abstract class InsecureClipboardHost { + /// Whether the Clipboard API is missing, so this host must answer. + bool get unavailable; + + /// Writes [text] with the legacy copy command; false when the browser + /// refused it (no user activation). + bool copy(String text); + + /// The text of the next browser `paste` event within [timeout] (which it + /// consumes, so nothing else pastes it), empty for a paste with no text, + /// or null when none came. + Future nextPaste(Duration timeout); +} + +/// The error code of a clipboard reply refused because the page is not +/// secure; its message is the whole explanation. +const insecureClipboardCode = 'insecure_context'; + +bool _apple() => + defaultTargetPlatform == TargetPlatform.macOS || + defaultTargetPlatform == TargetPlatform.iOS; + +/// Why a copy failed on a page that is not secure. +String insecureCopyMessage() => + "Could not copy: this page isn't secure (http), so the browser blocks " + 'the clipboard here. Open the https address to copy.'; + +/// Why a paste failed on a page that is not secure, and what works instead. +String insecurePasteMessage() { + final key = _apple() ? 'Cmd+V' : 'Ctrl+V'; + return "Could not paste: this page isn't secure (http), so the browser " + 'blocks reading the clipboard here. Paste with $key, or open the ' + 'https address.'; +} + +/// Answers the app's clipboard calls when the Clipboard API is missing. +/// +/// - `Clipboard.setData` copies with the legacy copy command, which the +/// browser allows during a user activation (a key press or a click), as +/// every copy in the app is. +/// - `Clipboard.getData` asked for while a key event is being handled (the +/// terminal's Ctrl+V, Shift+Insert, the desktop's injected paste key) +/// takes the text of the browser's own `paste` event for that key: the +/// key event is reported to the engine as not handled, so the browser +/// still runs its paste. Asked for at any other time (a Paste button or +/// menu item) there is no paste event to read, and the reply says to use +/// the paste key. +/// +/// On a secure page ([InsecureClipboardHost.unavailable] false) nothing is +/// answered here and the engine's Clipboard API path runs unchanged. +class InsecureClipboard { + InsecureClipboard( + this.host, { + this.pasteWait = const Duration(milliseconds: 500), + }); + + final InsecureClipboardHost host; + + /// How long a paste key's clipboard read waits for its paste event. + final Duration pasteWait; + + static const _methods = JSONMethodCodec(); + static const _keys = JSONMessageCodec(); + + bool _inKeyEvent = false; + bool _readDuringKey = false; + + /// The reply to platform-channel [call], or null when the engine answers. + Future? answer(MethodCall call) { + if (!host.unavailable) return null; + switch (call.method) { + case 'Clipboard.setData': + final arguments = call.arguments; + final text = arguments is Map ? arguments['text'] : null; + if (text is! String) return null; + // Copied now, inside the key or click that asked for it; only the + // reply is asynchronous. + final copied = host.copy(text); + return Future.value( + copied + ? _methods.encodeSuccessEnvelope(null) + : _refused(insecureCopyMessage()), + ); + case 'Clipboard.getData': + final format = call.arguments; + if (format != null && format != Clipboard.kTextPlain) return null; + if (!_inKeyEvent) { + return Future.value(_refused(insecurePasteMessage())); + } + _readDuringKey = true; + return host + .nextPaste(pasteWait) + .then( + (text) => text == null + ? _refused(insecurePasteMessage()) + : _methods.encodeSuccessEnvelope({'text': text}), + ); + } + return null; + } + + static ByteData _refused(String message) => + _methods.encodeErrorEnvelope(code: insecureClipboardCode, message: message); + + /// [handler] for the engine's key events (`flutter/keyevent`), reporting a + /// key event whose handling read the clipboard as not handled, so the + /// browser does not cancel the paste it is about to run. + MessageHandler keyEventHandler(MessageHandler handler) { + return (message) { + if (!host.unavailable) return handler(message); + final outer = _inKeyEvent; + _inKeyEvent = true; + _readDuringKey = false; + final Future? reply; + try { + reply = handler(message); + } finally { + _inKeyEvent = outer; + } + if (!_readDuringKey || reply == null) return reply; + _readDuringKey = false; + return reply.then((_) => _keys.encodeMessage({'handled': false})); + }; + } +} diff --git a/app/lib/application/insecure_clipboard_host.dart b/app/lib/application/insecure_clipboard_host.dart new file mode 100644 index 00000000..c50b583e --- /dev/null +++ b/app/lib/application/insecure_clipboard_host.dart @@ -0,0 +1,9 @@ +import 'insecure_clipboard.dart'; +import 'insecure_clipboard_host_stub.dart' + if (dart.library.js_interop) 'insecure_clipboard_host_web.dart' + as platform; + +/// The browser's legacy clipboard on the web; null elsewhere, where the +/// platform's clipboard always answers. +InsecureClipboardHost? insecureClipboardHost() => + platform.insecureClipboardHost(); diff --git a/app/lib/application/insecure_clipboard_host_stub.dart b/app/lib/application/insecure_clipboard_host_stub.dart new file mode 100644 index 00000000..a6c3b5ee --- /dev/null +++ b/app/lib/application/insecure_clipboard_host_stub.dart @@ -0,0 +1,3 @@ +import 'insecure_clipboard.dart'; + +InsecureClipboardHost? insecureClipboardHost() => null; diff --git a/app/lib/application/insecure_clipboard_host_web.dart b/app/lib/application/insecure_clipboard_host_web.dart new file mode 100644 index 00000000..8cc15d57 --- /dev/null +++ b/app/lib/application/insecure_clipboard_host_web.dart @@ -0,0 +1,96 @@ +import 'dart:async'; +import 'dart:js_interop'; +import 'dart:js_interop_unsafe'; + +import 'package:web/web.dart' as web; + +import 'insecure_clipboard.dart'; + +InsecureClipboardHost? insecureClipboardHost() => _BrowserClipboard(); + +/// The legacy clipboard of a page without the Clipboard API. +class _BrowserClipboard implements InsecureClipboardHost { + /// `navigator.clipboard` exists only in a secure context (and a browser + /// new enough to have it); neither changes while the page is open. + @override + late final bool unavailable = + !web.window.isSecureContext || + (web.window.navigator as JSObject) + .getProperty('clipboard'.toJS) + .isUndefinedOrNull; + + /// The copy command writes what its `copy` event puts on the event's + /// clipboard data, so no element is focused or selected for it: the + /// Flutter text field keeps its focus, caret and any IME composition, and + /// a selection in it is not copied instead. + @override + bool copy(String text) { + var written = false; + void onCopy(web.Event event) { + final data = (event as web.ClipboardEvent).clipboardData; + if (data == null) return; + data.setData('text/plain', text); + event.preventDefault(); + event.stopImmediatePropagation(); + written = true; + } + + final listener = onCopy.toJS; + web.window.addEventListener( + 'copy', + listener, + web.AddEventListenerOptions(capture: true), + ); + try { + // False (or no copy event) without a user activation. + return web.document.execCommand('copy') && written; + } on Object { + return false; + } finally { + web.window.removeEventListener( + 'copy', + listener, + web.EventListenerOptions(capture: true), + ); + } + } + + /// Listens on the window in the capture phase, ahead of the composer's + /// document listener and the focused element's own insertion. + @override + Future nextPaste(Duration timeout) { + final result = Completer(); + late final JSFunction listener; + Timer? timer; + void finish(String? text) { + if (result.isCompleted) return; + timer?.cancel(); + web.window.removeEventListener( + 'paste', + listener, + web.EventListenerOptions(capture: true), + ); + result.complete(text); + } + + void onPaste(web.Event event) { + final data = (event as web.ClipboardEvent).clipboardData; + final text = data?.getData('text/plain') ?? ''; + if (text.isNotEmpty) { + event.preventDefault(); + event.stopImmediatePropagation(); + } + // A paste with no text (files) is left to the page's other listeners. + finish(text); + } + + listener = onPaste.toJS; + web.window.addEventListener( + 'paste', + listener, + web.AddEventListenerOptions(capture: true), + ); + timer = Timer(timeout, () => finish(null)); + return result.future; + } +} diff --git a/app/lib/application/pipelines_binding.dart b/app/lib/application/pipelines_binding.dart index ff67144f..53e86a0e 100644 --- a/app/lib/application/pipelines_binding.dart +++ b/app/lib/application/pipelines_binding.dart @@ -3,9 +3,12 @@ import 'package:flutter/widgets.dart'; import '../core/keyboard/key_modifier_sync.dart'; import 'clipboard_failures.dart'; +import 'insecure_clipboard.dart'; +import 'insecure_clipboard_host.dart'; /// The app's binding: Flutter's, with clipboard failures reported -/// ([ClipboardReportingMessenger]) and, on the web, key events carrying the +/// ([ClipboardReportingMessenger]), the browser's legacy clipboard on a page +/// without the Clipboard API ([InsecureClipboard]) and, on the web, key events carrying the /// modifiers their browser events hold ([KeyModifierSync]). /// /// An entry point calls [ensureInitialized] before anything else creates a @@ -33,6 +36,11 @@ class PipelinesBinding extends WidgetsFlutterBinding { } @override - BinaryMessenger createBinaryMessenger() => - ClipboardReportingMessenger(super.createBinaryMessenger()); + BinaryMessenger createBinaryMessenger() { + final host = insecureClipboardHost(); + return ClipboardReportingMessenger( + super.createBinaryMessenger(), + insecure: host == null ? null : InsecureClipboard(host), + ); + } } diff --git a/app/notes/clipboard-keys.md b/app/notes/clipboard-keys.md index 6f621924..982d4469 100644 --- a/app/notes/clipboard-keys.md +++ b/app/notes/clipboard-keys.md @@ -68,3 +68,52 @@ chord is covered both ways); text fields when the browser reports Ctrl and Meta together (the browser's native paste may not run then). With Flutter semantics enabled, copying the transcript after typing in the composer did not copy before or after this change (semantics off works); not addressed. + +## Copy and paste on an insecure (http) page + +Operator report: over plain http on the tailnet address the page is not a +secure context, `navigator.clipboard` is undefined, and Flutter's web engine +refused every `Clipboard.setData`/`getData` ("Could not copy: Clipboard is +not available in the context."), so no copy worked. + +`ClipboardReportingMessenger` now takes an `InsecureClipboard` +(`lib/application/insecure_clipboard.dart`; browser side +`insecure_clipboard_host_web.dart`, conditional import, null on VM/native), +which answers clipboard calls only when the Clipboard API is missing: + +- `Clipboard.setData`: `document.execCommand('copy')` with a one-shot + capture `copy` listener that puts the text on the event's clipboardData. + No textarea is focused or selected, so the Flutter text-editing element + keeps focus, caret and any IME composition. Needs user activation (keys + and clicks give it). Every caller (keys, menus, buttons, terminal) goes + through it. +- `Clipboard.getData` during a key event (the terminal's Ctrl+V, + Ctrl+Shift+V, Shift+Insert, the injected Super+V): the `flutter/keyevent` + reply is rewritten to not-handled so the engine does not + `preventDefault` the key; the browser then fires `paste`, which a capture + listener on window consumes (preventDefault + stopImmediatePropagation, so + no double insertion) and returns as the clipboard text. +- `Clipboard.getData` outside a key event (terminal menu/toolbar Paste) has + no paste event: the reply is an error the messenger shows as "Could not + paste: this page isn't secure (http), ... Paste with Ctrl+V, or open the + https address." (Cmd+V on Apple). A refused copy says the same for copy. +- Secure pages: nothing is answered here; engine path unchanged. + +Text fields (composer) already paste natively; the browser context menu's +Copy on a transcript selection is the browser's own copy (no Clipboard API). + +Evidence (headless Chromium, `--insecure true`, clipboard read back from a +loopback scratch page): `tool/capture/examples/clipboard-insecure-chat.json` +(code-block and message copy buttons; composer Ctrl+V once) and +`clipboard-insecure-terminal.json` (Ctrl+V, Shift+Insert, Ctrl+Shift+V each +paste once; Ctrl+Shift+C and menu Copy copy; typing after a copy still +reaches the terminal; menu Paste shows the message). The super-c chat keys +(physical Ctrl+C, Super+C both flag forms, Ctrl+Insert) copy "Answer 19"; +the same steps on a build without the handler leave the clipboard +unchanged. Secure-page examples (`clipboard-super-c-*`, `-super-v-composer`, +`-copy-refused`) behave as before. Tests: `test/application/ +insecure_clipboard_test.dart`. + +Not verified: Firefox/Safari; the browser's native context menu (headless +cannot drive it); a copy issued long after its click (an awaited network +call first, e.g. artifact URL copy) may outlive the user activation. diff --git a/app/test/application/clipboard_failures_test.dart b/app/test/application/clipboard_failures_test.dart index fb7ec87e..18fbd529 100644 --- a/app/test/application/clipboard_failures_test.dart +++ b/app/test/application/clipboard_failures_test.dart @@ -4,6 +4,7 @@ import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:pipelines_app/application/clipboard_failures.dart'; +import 'package:pipelines_app/application/insecure_clipboard.dart'; /// A platform side that answers every platform-channel call with [reply]. class _Platform implements BinaryMessenger { @@ -75,9 +76,7 @@ void main() { message: 'Clipboard is not available in the context.', ), ); - expect(reports, [ - 'Could not paste: Clipboard is not available in the context.', - ]); + expect(reports, [insecurePasteMessage()]); }); test('successes and passive checks are not reported', () async { diff --git a/app/test/application/insecure_clipboard_test.dart b/app/test/application/insecure_clipboard_test.dart new file mode 100644 index 00000000..67a87605 --- /dev/null +++ b/app/test/application/insecure_clipboard_test.dart @@ -0,0 +1,228 @@ +import 'dart:async'; +import 'dart:ui' as ui; + +import 'package:flutter/services.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/application/clipboard_failures.dart'; +import 'package:pipelines_app/application/insecure_clipboard.dart'; + +/// A browser page whose clipboard [unavailable] says whether it has the +/// Clipboard API; [copied] records legacy copies, [paste] answers reads. +class _Host implements InsecureClipboardHost { + _Host({this.unavailable = true, this.copies = true}); + + @override + final bool unavailable; + final bool copies; + final List copied = []; + final List waits = []; + Completer paste = Completer(); + + @override + bool copy(String text) { + copied.add(text); + return copies; + } + + @override + Future nextPaste(Duration timeout) { + waits.add(timeout); + return paste.future; + } +} + +/// The engine: records what reaches it and answers every call successfully; +/// keeps the handlers set on it. +class _Engine implements BinaryMessenger { + final List methods = []; + final Map handlers = {}; + static const codec = JSONMethodCodec(); + + @override + Future? send(String channel, ByteData? message) async { + methods.add(codec.decodeMethodCall(message).method); + return codec.encodeSuccessEnvelope({'text': 'from the engine'}); + } + + @override + Future handlePlatformMessage( + String channel, + ByteData? data, + ui.PlatformMessageResponseCallback? callback, + ) async {} + + @override + void setMessageHandler(String channel, MessageHandler? handler) { + if (handler == null) { + handlers.remove(channel); + } else { + handlers[channel] = handler; + } + } +} + +void main() { + const keys = JSONMessageCodec(); + late _Host host; + late _Engine engine; + late List reports; + late MethodChannel platform; + Future? pasted; + + void setUpPage({bool unavailable = true, bool copies = true}) { + host = _Host(unavailable: unavailable, copies: copies); + engine = _Engine(); + reports = []; + final messenger = ClipboardReportingMessenger( + engine, + report: reports.add, + insecure: InsecureClipboard(host), + ); + platform = MethodChannel( + SystemChannels.platform.name, + const JSONMethodCodec(), + messenger, + ); + // The framework's key handler: its handling of a key event may read the + // clipboard (the terminal's paste key) and it reports the key handled. + messenger.setMessageHandler(SystemChannels.keyEvent.name, (message) async { + final read = keys.decodeMessage(message) == 'paste'; + if (read) { + pasted = platform.invokeMethod( + 'Clipboard.getData', + Clipboard.kTextPlain, + ); + } + return keys.encodeMessage({'handled': true}); + }); + } + + Future pressKey(String what) async { + final reply = await engine.handlers[SystemChannels.keyEvent.name]!( + keys.encodeMessage(what), + ); + return keys.decodeMessage(reply); + } + + setUp(() { + pasted = null; + setUpPage(); + }); + + test('a copy on an insecure page uses the legacy copy, not the engine', () async { + await platform.invokeMethod('Clipboard.setData', {'text': 'hello'}); + expect(host.copied, ['hello']); + expect(engine.methods, isEmpty); + expect(reports, isEmpty); + }); + + test('a refused legacy copy says the page is not secure', () async { + setUpPage(copies: false); + await expectLater( + platform.invokeMethod('Clipboard.setData', {'text': 'hello'}), + throwsA( + isA().having( + (e) => e.code, + 'code', + insecureClipboardCode, + ), + ), + ); + expect(reports, [insecureCopyMessage()]); + expect(insecureCopyMessage(), contains("isn't secure (http)")); + }); + + test('a secure page keeps the engine clipboard', () async { + setUpPage(unavailable: false); + await platform.invokeMethod('Clipboard.setData', {'text': 'hello'}); + final data = await platform.invokeMethod( + 'Clipboard.getData', + Clipboard.kTextPlain, + ); + expect(host.copied, isEmpty); + expect(engine.methods, ['Clipboard.setData', 'Clipboard.getData']); + expect(data, {'text': 'from the engine'}); + }); + + test('a read outside a key event (a Paste button) says to use the paste ' + 'key', () async { + await expectLater( + platform.invokeMethod('Clipboard.getData', Clipboard.kTextPlain), + throwsA(isA()), + ); + expect(host.waits, isEmpty); + expect(reports, [insecurePasteMessage()]); + expect(insecurePasteMessage(), contains('Ctrl+V')); + }); + + group('a paste key', () { + test('reads its browser paste event and lets the browser paste', () async { + final reply = pressKey('paste'); + // The read was asked for during the key event; it waits for the paste. + expect(host.waits, hasLength(1)); + expect(await reply, {'handled': false}); + host.paste.complete('pasted text'); + expect(await pasted, {'text': 'pasted text'}); + expect(engine.methods, isEmpty); + expect(reports, isEmpty); + }); + + test('other keys keep their handled reply', () async { + expect(await pressKey('other'), {'handled': true}); + expect(host.waits, isEmpty); + }); + + test('a secure page leaves the key reply alone', () async { + setUpPage(unavailable: false); + expect(await pressKey('paste'), {'handled': true}); + expect(await pasted, {'text': 'from the engine'}); + }); + }); + + test('a read during a key event yields the paste event text', () async { + final clipboard = InsecureClipboard(host); + Future? read; + final handler = clipboard.keyEventHandler((message) { + read = clipboard.answer( + const MethodCall('Clipboard.getData', Clipboard.kTextPlain), + ); + return Future.value(keys.encodeMessage({'handled': true})); + }); + final reply = await handler(keys.encodeMessage('key')); + expect(keys.decodeMessage(reply), {'handled': false}); + host.paste.complete('pasted'); + final data = const JSONMethodCodec().decodeEnvelope((await read)!); + expect(data, {'text': 'pasted'}); + }); + + test('a paste key with no paste event says why', () async { + final clipboard = InsecureClipboard(host); + Future? read; + await clipboard.keyEventHandler((message) { + read = clipboard.answer( + const MethodCall('Clipboard.getData', Clipboard.kTextPlain), + ); + return Future.value(keys.encodeMessage({'handled': true})); + })(keys.encodeMessage('key')); + host.paste.complete(null); + expect( + () async => const JSONMethodCodec().decodeEnvelope((await read)!), + throwsA( + isA().having( + (e) => e.message, + 'message', + insecurePasteMessage(), + ), + ), + ); + }); + + test('other formats and methods are left to the engine', () { + final clipboard = InsecureClipboard(host); + expect( + clipboard.answer(const MethodCall('Clipboard.getData', 'text/html')), + isNull, + ); + expect(clipboard.answer(const MethodCall('Clipboard.hasStrings')), isNull); + }); +} diff --git a/app/tool/capture/README.md b/app/tool/capture/README.md index 1b764ba1..4ff1f5b4 100644 --- a/app/tool/capture/README.md +++ b/app/tool/capture/README.md @@ -45,6 +45,11 @@ assistive technology: only point targets (`x,y`) work, and the web's text input is Flutter's own hidden field, which reports IME composition (with semantics on, a text field's input is its semantics element, which does not). +`--insecure true` opens the build at `http://pipelines-insecure.test:` +(Chrome maps that name to the loopback server), so the page is not a secure +context and has no Clipboard API, as the app over plain http on a LAN or +tailnet address (`examples/clipboard-insecure-*.json`). + `--user-agent ''` overrides the browser's user agent before loading, so an Android phone's (with `--touch true`) makes Flutter's `defaultTargetPlatform` Android, for touch-only UI such as the terminal's key row. @@ -74,6 +79,7 @@ In JSON, a step can also set `wait` (ms), `timeout`, `name`, `ms` and `frames`. | `wait=ms` | sleep | | `keys=[...]` | raw key events (JSON `Input.dispatchKeyEvent` params, each with an optional `after` ms), e.g. modifier flags without their key events as a compositor's injected shortcut sends them (`examples/clipboard-*.json`) | | `grant=clipboard` | let the page read and write the clipboard (`navigator.clipboard` in `eval`) | +| `clipboard=read[:label]` / `clipboard=write:` | read or write the browser's clipboard from a scratch page on the loopback origin (a secure context), then bring the page back; JSON `expect` fails the run unless the read text matches. Works for an `--insecure` page, which has no `navigator.clipboard` | | `files=a.ttf[,b.ttf]` | answer the next file chooser the page opens with these files (paths relative to the working directory); put it before the click that opens the picker | | `swipe=>dx,dy` | one-finger touch swipe (needs `--touch true`, which emulates a touch screen once semantics is on) | | `pinch=>scale` | two-finger touch pinch, spreading (>1) or closing (<1) (needs `--touch true`) | diff --git a/app/tool/capture/browser.mjs b/app/tool/capture/browser.mjs index 66572e3d..c44b2103 100644 --- a/app/tool/capture/browser.mjs +++ b/app/tool/capture/browser.mjs @@ -11,7 +11,7 @@ import { setTimeout as delay } from 'node:timers/promises'; const CALL_TIMEOUT_MS = 30000; const DEFAULT_CHROME ='/Applications/Google Chrome.app/Contents/MacOS/Google Chrome'; -async function launch(chromePath, gpu) { +async function launch(chromePath, gpu, args = []) { const profile = await mkdtemp(join(tmpdir(), 'pipelines-capture-chrome-')); const chrome = spawn(chromePath, [ '--headless=new', '--no-first-run', '--no-default-browser-check', @@ -21,7 +21,7 @@ async function launch(chromePath, gpu) { ...(gpu ? [process.platform === 'darwin' ? '--use-angle=metal' : '--use-angle=vulkan', ...(process.platform === 'darwin' ? [] : ['--enable-features=Vulkan']), '--enable-gpu-rasterization', '--ignore-gpu-blocklist'] : ['--disable-gpu']), - '--hide-scrollbars', '--mute-audio', + '--hide-scrollbars', '--mute-audio', ...args, '--remote-debugging-port=0', `--user-data-dir=${profile}`, 'about:blank', ], { stdio: ['ignore', 'ignore', 'pipe'] }); let stderr = ''; @@ -55,8 +55,8 @@ async function attach(cdp) { * talks to the page session; `on(method, fn)` subscribes to its events and * returns the unsubscribe function; `newPage()` opens a scratch page. */ -export async function openBrowser({ cdp, gpu = false, chromePath = process.env.CHROME_PATH ?? DEFAULT_CHROME } = {}) { - const { ws: endpoint, cleanup } = cdp ? await attach(cdp) : await launch(chromePath, gpu); +export async function openBrowser({ cdp, gpu = false, args = [], chromePath = process.env.CHROME_PATH ?? DEFAULT_CHROME } = {}) { + const { ws: endpoint, cleanup } = cdp ? await attach(cdp) : await launch(chromePath, gpu, args); const ws = new WebSocket(endpoint); try { await new Promise((ok, fail) => { ws.onopen = ok; ws.onerror = () => fail(new Error(`Cannot open ${endpoint}`)); }); @@ -107,9 +107,12 @@ export async function openBrowser({ cdp, gpu = false, chromePath = process.env.C const { sessionId: sid } = await raw('Target.attachToTarget', { targetId: page.targetId, flatten: true }); return { send: (method, params) => raw(method, params, sid), + targetId: page.targetId, close: () => raw('Target.closeTarget', { targetId: page.targetId }).catch(() => {}), }; }, + /** Brings the kit's own page to the front again (after a scratch page). */ + front: () => raw('Target.activateTarget', { targetId }), close: async () => { await raw('Target.closeTarget', { targetId }).catch(() => {}); ws.close(); diff --git a/app/tool/capture/capture.mjs b/app/tool/capture/capture.mjs index 7597d534..f13affec 100644 --- a/app/tool/capture/capture.mjs +++ b/app/tool/capture/capture.mjs @@ -23,17 +23,22 @@ options: --script --size WxH (880x1000) --touch true (emulate a touch screen: mobile metrics, touch input) --semantics false (leave Flutter semantics off; point targets only) --user-agent (e.g. an Android phone's, for defaultTargetPlatform) + --insecure true (open the build at http://pipelines-insecure.test:, + mapped to the loopback server: not a secure context, no Clipboard API) steps: open=[@WxH] wait= shot= click= waitfor= type= press= scroll= size=WxH files=[,] (answers the next file chooser) film= labels= tabs= eval= expect= hover= keys= grant=clipboard + clipboard=read|write: (the browser's clipboard, from a scratch + page on the loopback origin, so it works for an --insecure page) rightclick= (secondary button: context menus) drag=>, (JSON: drag, dx, dy, steps, gap, hold) swipe=>, pinch=> (with --touch true) target: