Skip to content

Authenticate the user when they click on the Dart Debug Extension icon #1795

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Nov 28, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 56 additions & 0 deletions dwds/debug_extension_mv3/web/background.dart
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import 'dart:async';
import 'dart:html';

import 'package:dwds/data/debug_info.dart';
import 'package:dwds/data/extension_request.dart';
import 'package:js/js.dart';

import 'chrome_api.dart';
Expand All @@ -18,6 +19,8 @@ import 'messaging.dart';
import 'storage.dart';
import 'web_api.dart';

const _authSuccessResponse = 'Dart Debug Authentication Success!';

void main() {
_registerListeners();
}
Expand All @@ -33,13 +36,46 @@ void _registerListeners() {

// TODO(elliette): Start a debug session instead.
Future<void> _startDebugSession(Tab currentTab) async {
final tabId = currentTab.id;
final debugInfo = await _fetchDebugInfo(tabId);
final extensionUrl = debugInfo?.extensionUrl;
if (extensionUrl == null) {
_showWarningNotification('Can\'t debug Dart app. Extension URL not found.');
return;
}
final isAuthenticated = await _authenticateUser(extensionUrl, tabId);
if (!isAuthenticated) return;

maybeCreateLifelinePort(currentTab.id);
final devToolsOpener = await fetchStorageObject<DevToolsOpener>(
type: StorageObject.devToolsOpener);
await _createTab('https://dart.dev/',
inNewWindow: devToolsOpener?.newWindow ?? false);
}

Future<bool> _authenticateUser(String extensionUrl, int tabId) async {
final authUrl = _constructAuthUrl(extensionUrl).toString();
final response = await fetchRequest(authUrl);
final responseBody = response.body ?? '';
if (!responseBody.contains(_authSuccessResponse)) {
_showWarningNotification('Please re-authenticate and try again.');
await _createTab(authUrl, inNewWindow: false);
return false;
}
return true;
}

Uri _constructAuthUrl(String extensionUrl) {
final authUri = Uri.parse(extensionUrl).replace(path: authenticationPath);
if (authUri.scheme == 'ws') {
return authUri.replace(scheme: 'http');
}
if (authUri.scheme == 'wss') {
return authUri.replace(scheme: 'https');
}
return authUri;
}

void _handleRuntimeMessages(
dynamic jsRequest, MessageSender sender, Function sendResponse) async {
if (jsRequest is! String) return;
Expand Down Expand Up @@ -71,6 +107,26 @@ void _handleRuntimeMessages(
});
}

Future<DebugInfo?> _fetchDebugInfo(int tabId) {
return fetchStorageObject<DebugInfo>(
type: StorageObject.debugInfo,
tabId: tabId,
);
}

void _showWarningNotification(String message) {
chrome.notifications.create(
/*notificationId*/ null,
NotificationOptions(
title: '[Error] Dart Debug Extension',
message: message,
iconUrl: 'dart.png',
type: 'basic',
),
/*callback*/ null,
);
}

Future<Tab?> _getTab() async {
final query = QueryInfo(active: true, currentWindow: true);
final tabs = List<Tab>.from(await promiseToFuture(chrome.tabs.query(query)));
Expand Down
22 changes: 22 additions & 0 deletions dwds/debug_extension_mv3/web/chrome_api.dart
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,7 @@ external Chrome get chrome;
@anonymous
class Chrome {
external Action get action;
external Notifications get notifications;
external Runtime get runtime;
external Scripting get scripting;
external Storage get storage;
Expand Down Expand Up @@ -42,6 +43,27 @@ class IconInfo {
external factory IconInfo({String path});
}

/// chrome.notification APIs:
/// https://developer.chrome.com/docs/extensions/reference/notifications

@JS()
@anonymous
class Notifications {
external void create(
String? notificationId, NotificationOptions options, Function? callback);
}

@JS()
@anonymous
class NotificationOptions {
external factory NotificationOptions({
String title,
String message,
String iconUrl,
String type,
});
}

/// chrome.runtime APIs:
/// https://developer.chrome.com/docs/extensions/reference/runtime

Expand Down
1 change: 1 addition & 0 deletions dwds/debug_extension_mv3/web/manifest.json
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
},
"permissions": [
"debugger",
"notifications",
"scripting",
"storage",
"tabs"
Expand Down
55 changes: 55 additions & 0 deletions dwds/debug_extension_mv3/web/web_api.dart
Original file line number Diff line number Diff line change
@@ -1,8 +1,10 @@
// Copyright (c) 2022, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:html';

import 'package:js/js.dart';
import 'dart:js_util' as js_util;

@JS()
external Console get console;
Expand All @@ -16,3 +18,56 @@ class Console {
external void warn(String header,
[String style1, String style2, String style3]);
}

// Custom implementation of Fetch API until the Dart implementation supports
// credentials. See https://github.com/dart-lang/http/issues/595.
@JS('fetch')
external Object _nativeJsFetch(String resourceUrl, FetchOptions options);

Future<FetchResponse> fetchRequest(String resourceUrl) async {
try {
final options = FetchOptions(
method: 'GET',
credentialsOptions: CredentialsOptions(credentials: 'include'),
);
final response =
await promiseToFuture(_nativeJsFetch(resourceUrl, options));
final body =
await promiseToFuture(js_util.callMethod(response, 'text', []));
final ok = js_util.getProperty<bool>(response, 'ok');
final status = js_util.getProperty<int>(response, 'status');
return FetchResponse(status: status, ok: ok, body: body);
} catch (error) {
return FetchResponse(
status: 400, ok: false, body: 'Error fetching $resourceUrl: $error');
}
}

@JS()
@anonymous
class FetchOptions {
external factory FetchOptions({
required String method, // e.g., 'GET', 'POST'
required CredentialsOptions credentialsOptions,
});
}

@JS()
@anonymous
class CredentialsOptions {
external factory CredentialsOptions({
required String credentials, // e.g., 'omit', 'same-origin', 'include'
});
}

class FetchResponse {
final int status;
final bool ok;
final String? body;

FetchResponse({
required this.status,
required this.ok,
required this.body,
});
}
6 changes: 5 additions & 1 deletion dwds/test/puppeteer/extension_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -41,7 +41,11 @@ void main() async {
setUpAll(() async {
// TODO(elliette): Only start a TestServer, that way we can get rid of
// the launchChrome parameter: https://github.com/dart-lang/webdev/issues/1779
await context.setUp(launchChrome: false, useSse: useSse);
await context.setUp(
launchChrome: false,
useSse: useSse,
enableDebugExtension: true,
);
browser = await puppeteer.launch(
headless: false,
timeout: Duration(seconds: 60),
Expand Down
5 changes: 4 additions & 1 deletion dwds/test/puppeteer/lifeline_test.dart
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,10 @@ void main() async {
group('MV3 Debug Extension Lifeline Connection', () {
setUpAll(() async {
extensionPath = await buildDebugExtension();
await context.setUp(launchChrome: false);
await context.setUp(
launchChrome: false,
enableDebugExtension: true,
);
browser = await puppeteer.launch(
headless: false,
timeout: Duration(seconds: 60),
Expand Down