diff --git a/app/lib/application/bootstrap.dart b/app/lib/application/bootstrap.dart index 15ad0070..8e9a2bbd 100644 --- a/app/lib/application/bootstrap.dart +++ b/app/lib/application/bootstrap.dart @@ -1,3 +1,4 @@ +import '../core/session/server_session.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/widgets.dart'; @@ -43,6 +44,9 @@ Future runPipelinesApp({ SettingsStore? settingsStore, }) async { useAppUrlStrategy(); + WidgetsFlutterBinding.ensureInitialized(); + // A phone behind the web login reconnects with its kept session. + await ServerSession.load(); final server = await resolveLaunchServer( base: base, configured: configured, diff --git a/app/lib/application/pipelines_app.dart b/app/lib/application/pipelines_app.dart index 5d984352..bfba4037 100644 --- a/app/lib/application/pipelines_app.dart +++ b/app/lib/application/pipelines_app.dart @@ -468,6 +468,8 @@ class _PipelinesAppState extends State ), AppDestination.settings: (_) => SettingsScreen( client: _session.client, + // A phone signs in at the web login; a browser has its own. + showSignIn: !kIsWeb, initialEndpoint: _session.endpoint, embedded: true, onOpenTemplates: _delegate.openTemplates, diff --git a/app/lib/core/session/server_session.dart b/app/lib/core/session/server_session.dart new file mode 100644 index 00000000..008d4507 --- /dev/null +++ b/app/lib/core/session/server_session.dart @@ -0,0 +1,80 @@ +import 'package:shared_preferences/shared_preferences.dart'; + +import 'server_session_stub.dart' + if (dart.library.io) 'server_session_io.dart' + as impl; + +/// The web sign-in the app carries on a phone. +/// +/// A browser keeps the server's login cookie itself. The native app signs in +/// with the same password, keeps the returned session cookie, and sends it on +/// the websocket and on file downloads, so it can reach a server that sits +/// behind the web login (for example over Tailscale). A server with no login +/// needs none of this. +class ServerSession { + ServerSession._(); + + static const _key = 'pipelines.session.cookie'; + + /// The `name=value` session cookie, or null when signed out. + static String? cookie; + + /// Headers that carry the session, empty when signed out. + static Map get headers { + final value = cookie; + return value == null || value.isEmpty ? const {} : {'Cookie': value}; + } + + static Future load() async { + try { + final prefs = await SharedPreferences.getInstance(); + cookie = prefs.getString(_key); + } catch (_) { + cookie = null; + } + } + + static Future _save(String? value) async { + cookie = value; + try { + final prefs = await SharedPreferences.getInstance(); + if (value == null) { + await prefs.remove(_key); + } else { + await prefs.setString(_key, value); + } + } catch (_) {} + } + + /// Signs in at the web login beside [endpoint] (its `/login` page) with + /// [password] and keeps the session. Returns null on success, otherwise + /// what went wrong in words. + static Future signIn(Uri endpoint, String password) async { + final login = loginUriFor(endpoint); + if (login == null) return 'The server address has no web login.'; + final result = await impl.postLogin(login, password); + if (result.cookie != null) { + await _save(result.cookie); + return null; + } + return result.error ?? 'Sign-in failed.'; + } + + static Future signOut() => _save(null); +} + +/// The web login page for a websocket endpoint: same host and port, http(s). +Uri? loginUriFor(Uri endpoint) { + final scheme = switch (endpoint.scheme) { + 'wss' || 'https' => 'https', + 'ws' || 'http' => 'http', + _ => null, + }; + if (scheme == null || endpoint.host.isEmpty) return null; + return Uri( + scheme: scheme, + host: endpoint.host, + port: endpoint.hasPort ? endpoint.port : null, + path: '/login', + ); +} diff --git a/app/lib/core/session/server_session_io.dart b/app/lib/core/session/server_session_io.dart new file mode 100644 index 00000000..5d7e3885 --- /dev/null +++ b/app/lib/core/session/server_session_io.dart @@ -0,0 +1,42 @@ +import 'dart:io'; + +/// Posts the password to the web login and returns its session cookie. +Future<({String? cookie, String? error})> postLogin( + Uri login, + String password, +) async { + final client = HttpClient()..connectionTimeout = const Duration(seconds: 15); + try { + final request = await client.postUrl(login); + request.followRedirects = false; + request.headers.contentType = ContentType( + 'application', + 'x-www-form-urlencoded', + charset: 'utf-8', + ); + request.write( + Uri(queryParameters: {'password': password, 'remember': 'on'}).query, + ); + final response = await request.close(); + await response.drain(); + for (final cookie in response.cookies) { + if (cookie.name == 'pipelines_session' && cookie.value.isNotEmpty) { + return (cookie: '${cookie.name}=${cookie.value}', error: null); + } + } + return ( + cookie: null, + error: switch (response.statusCode) { + 401 => 'Wrong password.', + 429 => 'Too many attempts. Wait 30 seconds.', + _ => 'Sign-in failed (HTTP ${response.statusCode}).', + }, + ); + } on IOException catch (error) { + return (cookie: null, error: 'Could not reach the server: $error'); + } on FormatException catch (error) { + return (cookie: null, error: error.message); + } finally { + client.close(force: true); + } +} diff --git a/app/lib/core/session/server_session_stub.dart b/app/lib/core/session/server_session_stub.dart new file mode 100644 index 00000000..5f437a99 --- /dev/null +++ b/app/lib/core/session/server_session_stub.dart @@ -0,0 +1,5 @@ +/// The browser keeps its own login cookie, so there is nothing to post here. +Future<({String? cookie, String? error})> postLogin( + Uri login, + String password, +) async => (cookie: null, error: 'Sign in through the browser page.'); diff --git a/app/lib/core/transport/channel_connect.dart b/app/lib/core/transport/channel_connect.dart new file mode 100644 index 00000000..716998be --- /dev/null +++ b/app/lib/core/transport/channel_connect.dart @@ -0,0 +1,8 @@ +import 'package:web_socket_channel/web_socket_channel.dart'; + +import 'channel_connect_stub.dart' + if (dart.library.io) 'channel_connect_io.dart' + as impl; + +/// Opens the server websocket; on a phone it carries the web sign-in. +WebSocketChannel connectPipelinesChannel(Uri uri) => impl.connect(uri); diff --git a/app/lib/core/transport/channel_connect_io.dart b/app/lib/core/transport/channel_connect_io.dart new file mode 100644 index 00000000..1b79274b --- /dev/null +++ b/app/lib/core/transport/channel_connect_io.dart @@ -0,0 +1,8 @@ +import 'package:web_socket_channel/io.dart'; +import 'package:web_socket_channel/web_socket_channel.dart'; + +import '../session/server_session.dart'; + +/// A native socket sends the kept session cookie with the upgrade. +WebSocketChannel connect(Uri uri) => + IOWebSocketChannel.connect(uri, headers: ServerSession.headers); diff --git a/app/lib/core/transport/channel_connect_stub.dart b/app/lib/core/transport/channel_connect_stub.dart new file mode 100644 index 00000000..3fd4fb65 --- /dev/null +++ b/app/lib/core/transport/channel_connect_stub.dart @@ -0,0 +1,4 @@ +import 'package:web_socket_channel/web_socket_channel.dart'; + +/// The browser sends its own login cookie with the upgrade. +WebSocketChannel connect(Uri uri) => WebSocketChannel.connect(uri); diff --git a/app/lib/core/transport/pipelines_client.dart b/app/lib/core/transport/pipelines_client.dart index 49134588..5e2eaf8d 100644 --- a/app/lib/core/transport/pipelines_client.dart +++ b/app/lib/core/transport/pipelines_client.dart @@ -1,3 +1,4 @@ +import 'channel_connect.dart'; import 'dart:async'; import 'dart:convert'; @@ -18,7 +19,7 @@ class PipelinesClient implements ApiGateway { this.requestTimeout = const Duration(seconds: 30), this.backoffBase = const Duration(seconds: 1), this.backoffMax = const Duration(seconds: 30), - }) : _factory = channelFactory ?? WebSocketChannel.connect; + }) : _factory = channelFactory ?? connectPipelinesChannel; final ChannelFactory _factory; final Duration requestTimeout, backoffBase, backoffMax; diff --git a/app/lib/features/artifacts/ui/artifact_viewer_fetch_stub.dart b/app/lib/features/artifacts/ui/artifact_viewer_fetch_stub.dart index 8c1bb237..524d72f8 100644 --- a/app/lib/features/artifacts/ui/artifact_viewer_fetch_stub.dart +++ b/app/lib/features/artifacts/ui/artifact_viewer_fetch_stub.dart @@ -1,6 +1,7 @@ import 'dart:io'; import 'dart:typed_data'; +import '../../../core/session/server_session.dart'; import 'artifact_viewer_fetch.dart'; /// Native fetch for an already resolved same-origin artifact. @@ -12,6 +13,8 @@ Future fetchArtifact(Uri uri) async { try { final request = await client.getUrl(uri); request.followRedirects = false; + // A phone behind the web login carries its kept session. + ServerSession.headers.forEach(request.headers.set); final response = await request.close(); final bytes = BytesBuilder(copy: false); await for (final chunk in response) { diff --git a/app/lib/features/settings/settings_screen.dart b/app/lib/features/settings/settings_screen.dart index 3ca6e565..caaca6d9 100644 --- a/app/lib/features/settings/settings_screen.dart +++ b/app/lib/features/settings/settings_screen.dart @@ -13,6 +13,7 @@ import 'settings_layout.dart'; import 'settings_notifications_section.dart'; import 'settings_schedules_section.dart'; import 'settings_sections.dart'; +import 'settings_sign_in_section.dart'; import 'settings_store.dart'; import 'settings_templates_section.dart'; @@ -35,10 +36,14 @@ class SettingsScreen extends StatefulWidget { this.onOpenTemplates, this.onOpenSchedules, this.notifications, + this.showSignIn = false, }); final transport.PipelinesClient client; + /// Whether to offer the web sign-in (the native app; a browser has its own). + final bool showSignIn; + /// A fixture/preview seed for the URL field. Persisted settings still load; /// this value takes precedence for the draft and is never written by itself. final Uri? initialEndpoint; @@ -140,6 +145,20 @@ class _SettingsScreenState extends State { serverUrlField: _serverUrlField, ), ), + // A phone signs in at the web login; a browser has its own. + if (widget.showSignIn) ...[ + const SizedBox(height: settingsSectionGap), + _SettingsSection( + title: 'Sign in', + child: SettingsSignInSection( + endpoint: _controller.serverUrl, + onChanged: () { + final endpoint = widget.client.endpoint; + if (endpoint != null) widget.client.connect(endpoint); + }, + ), + ), + ], const SizedBox(height: settingsSectionGap), _SettingsSection( title: 'Workspace', diff --git a/app/lib/features/settings/settings_sign_in_section.dart b/app/lib/features/settings/settings_sign_in_section.dart new file mode 100644 index 00000000..d567196e --- /dev/null +++ b/app/lib/features/settings/settings_sign_in_section.dart @@ -0,0 +1,126 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../../core/session/server_session.dart'; +import '../../ui/adaptive/host.dart'; + +/// Signs the phone in at the server's web login with the same password the +/// browser uses, so the app can reach a server behind it (over Tailscale, for +/// example). A server without a login needs no sign-in. +class SettingsSignInSection extends StatefulWidget { + const SettingsSignInSection({ + super.key, + required this.endpoint, + required this.onChanged, + }); + + /// The server's websocket address; its `/login` sits beside it. + final String endpoint; + + /// Reconnects once the session changed. + final VoidCallback onChanged; + + @override + State createState() => _SettingsSignInSectionState(); +} + +class _SettingsSignInSectionState extends State { + final _password = TextEditingController(); + bool _busy = false; + String? _message; + + @override + void dispose() { + _password.dispose(); + super.dispose(); + } + + Future _signIn() async { + final endpoint = Uri.tryParse(widget.endpoint.trim()); + if (endpoint == null) { + setState(() => _message = 'Set the server address first.'); + return; + } + setState(() { + _busy = true; + _message = null; + }); + final error = await ServerSession.signIn(endpoint, _password.text); + if (!mounted) return; + setState(() { + _busy = false; + _message = error ?? 'Signed in.'; + if (error == null) _password.clear(); + }); + if (error == null) widget.onChanged(); + } + + Future _signOut() async { + await ServerSession.signOut(); + if (!mounted) return; + setState(() => _message = 'Signed out.'); + widget.onChanged(); + } + + @override + Widget build(BuildContext context) { + final cupertino = usesCupertinoHost(context); + final signedIn = ServerSession.cookie != null; + final field = cupertino + ? CupertinoTextField( + key: const Key('settings-sign-in-password'), + controller: _password, + obscureText: true, + placeholder: 'Web password', + onSubmitted: (_) => _signIn(), + ) + : TextField( + key: const Key('settings-sign-in-password'), + controller: _password, + obscureText: true, + decoration: const InputDecoration(labelText: 'Web password'), + onSubmitted: (_) => _signIn(), + ); + final signIn = cupertino + ? CupertinoButton.filled( + key: const Key('settings-sign-in'), + onPressed: _busy ? null : _signIn, + child: const Text('Sign in'), + ) + : FilledButton( + key: const Key('settings-sign-in'), + onPressed: _busy ? null : _signIn, + child: const Text('Sign in'), + ); + final signOut = cupertino + ? CupertinoButton( + key: const Key('settings-sign-out'), + onPressed: _signOut, + child: const Text('Sign out'), + ) + : TextButton( + key: const Key('settings-sign-out'), + onPressed: _signOut, + child: const Text('Sign out'), + ); + return Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text( + signedIn + ? 'Signed in to the server\'s web login.' + : 'Only needed when the server sits behind the web login.', + ), + const SizedBox(height: 8), + field, + const SizedBox(height: 8), + Wrap(spacing: 8, children: [signIn, if (signedIn) signOut]), + if (_message != null) + Padding( + padding: const EdgeInsets.only(top: 4), + child: Semantics(liveRegion: true, child: Text(_message!)), + ), + ], + ); + } +} diff --git a/app/test/core/session/server_session_test.dart b/app/test/core/session/server_session_test.dart new file mode 100644 index 00000000..b15e1caf --- /dev/null +++ b/app/test/core/session/server_session_test.dart @@ -0,0 +1,32 @@ +import 'package:flutter_test/flutter_test.dart'; +import 'package:pipelines_app/core/session/server_session.dart'; +import 'package:shared_preferences/shared_preferences.dart'; + +void main() { + test('the web login sits beside the websocket endpoint', () { + expect( + loginUriFor(Uri.parse('wss://host.ts.net:8443/connect')).toString(), + 'https://host.ts.net:8443/login', + ); + expect( + loginUriFor(Uri.parse('ws://192.168.1.2:8081/connect')).toString(), + 'http://192.168.1.2:8081/login', + ); + expect(loginUriFor(Uri.parse('file:///x')), isNull); + }); + + test( + 'a kept session is sent as a cookie header and survives a restart', + () async { + SharedPreferences.setMockInitialValues({ + 'pipelines.session.cookie': 'pipelines_session=abc', + }); + await ServerSession.load(); + expect(ServerSession.headers, {'Cookie': 'pipelines_session=abc'}); + await ServerSession.signOut(); + expect(ServerSession.headers, isEmpty); + await ServerSession.load(); + expect(ServerSession.cookie, isNull); + }, + ); +}