merge(app): land native web sign-in

This commit is contained in:
2026-10-23 19:52:49 +01:00
13 changed files with 335 additions and 1 deletions
+4
View File
@@ -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<void> 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,
+2
View File
@@ -468,6 +468,8 @@ class _PipelinesAppState extends State<PipelinesApp>
),
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,
+80
View File
@@ -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<String, String> get headers {
final value = cookie;
return value == null || value.isEmpty ? const {} : {'Cookie': value};
}
static Future<void> load() async {
try {
final prefs = await SharedPreferences.getInstance();
cookie = prefs.getString(_key);
} catch (_) {
cookie = null;
}
}
static Future<void> _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<String?> 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<void> 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',
);
}
@@ -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<void>();
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);
}
}
@@ -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.');
@@ -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);
@@ -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);
@@ -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);
+2 -1
View File
@@ -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;
@@ -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<ArtifactFetchResult> 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) {
@@ -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<SettingsScreen> {
serverUrlField: _serverUrlField,
),
),
// A phone signs in at the web login; a browser has its own.
if (widget.showSignIn) ...<Widget>[
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',
@@ -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<SettingsSignInSection> createState() => _SettingsSignInSectionState();
}
class _SettingsSignInSectionState extends State<SettingsSignInSection> {
final _password = TextEditingController();
bool _busy = false;
String? _message;
@override
void dispose() {
_password.dispose();
super.dispose();
}
Future<void> _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<void> _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!)),
),
],
);
}
}
@@ -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);
},
);
}