Skip to content

Offline gym log for Android. No account, no ads, no internet.

Self-host: several people on one server and a sign-in page

InlitXf06e1c52277b
diff --git a/compose.yaml b/compose.yaml
index 9340b4a..1a297a8 100644
--- a/compose.yaml
+++ b/compose.yaml
@@ -11,6 +11,7 @@ services:
- ./gymmane-data:/data
environment:
GYMMANE_PASSWORD: ${GYMMANE_PASSWORD:-}
+ GYMMANE_PEOPLE: ${GYMMANE_PEOPLE:-}
GYMMANE_SYNC: ${GYMMANE_SYNC:-}
GYMMANE_KEEP_DAYS: ${GYMMANE_KEEP_DAYS:-}
@@ -31,3 +32,4 @@ services:
volumes:
- ./syncthing:/var/syncthing
- ./gymmane-data/sync:/var/syncthing/GymMane
+ - ./gymmane-data:/var/syncthing/data
diff --git a/lib/services/local_store.dart b/lib/services/local_store.dart
index 721c5f8..f1f5780 100644
--- a/lib/services/local_store.dart
+++ b/lib/services/local_store.dart
@@ -14,6 +14,8 @@ class Store {
SharedPreferences? _prefs;
Future<void> init() async {
+ final person = ServerLink.person;
+ if (_prefs == null && person != null) SharedPreferences.setPrefix('flutter.$person.');
_prefs ??= await SharedPreferences.getInstance();
if (kIsWeb) await ServerLink.instance.connect();
}
diff --git a/lib/services/server/server_link.dart b/lib/services/server/server_link.dart
index 734eef9..a4c8cc4 100644
--- a/lib/services/server/server_link.dart
+++ b/lib/services/server/server_link.dart
@@ -24,6 +24,10 @@ class ServerLink extends ChangeNotifier {
bool get busy => _sending || _pending != null;
+ static String? get person => kIsWeb ? net.personName : null;
+
+ void signOut() => net.signOut();
+
Future<void> connect() async {
if (!kIsWeb || !net.transportAvailable) return;
final r = await net.send('GET', 'api/state');
diff --git a/lib/services/server/transport_stub.dart b/lib/services/server/transport_stub.dart
index c92e2e2..5d46209 100644
--- a/lib/services/server/transport_stub.dart
+++ b/lib/services/server/transport_stub.dart
@@ -9,6 +9,10 @@ Future<Reply> send(String method, String path, {Uint8List? body, Map<String, Str
String mediaUrl(String name) => '';
+String? get personName => null;
+
+void signOut() {}
+
void onPageVisible(void Function() callback) {}
void beforeLeave(void Function() callback) {}
diff --git a/lib/services/server/transport_web.dart b/lib/services/server/transport_web.dart
index 082628b..6fc2d68 100644
--- a/lib/services/server/transport_web.dart
+++ b/lib/services/server/transport_web.dart
@@ -7,7 +7,13 @@ import 'transport.dart';
bool get transportAvailable => true;
-String _url(String path) => Uri.base.resolve(path).toString();
+String _url(String path) => Uri.parse(web.document.baseURI).resolve(path).toString();
+
+String? get personName {
+ final tag = web.document.querySelector('meta[name="gymmane-person"]');
+ final name = tag?.getAttribute('content')?.trim();
+ return name == null || name.isEmpty ? null : name;
+}
String mediaUrl(String name) => _url('api/media/${Uri.encodeComponent(name)}');
@@ -27,6 +33,7 @@ Future<Reply> send(String method, String path, {Uint8List? body, Map<String, Str
),
)
.toDart;
+ if (res.status == 401) web.window.location.reload();
final buffer = await res.arrayBuffer().toDart;
return Reply(res.status, buffer.toDart.asUint8List(), {
'x-gymmane-rev': res.headers.get('x-gymmane-rev') ?? '',
@@ -38,6 +45,8 @@ Future<Reply> send(String method, String path, {Uint8List? body, Map<String, Str
}
}
+void signOut() => web.window.location.assign(_url('logout'));
+
void onPageVisible(void Function() callback) {
web.document.addEventListener(
'visibilitychange',
diff --git a/lib/widgets/server_card.dart b/lib/widgets/server_card.dart
index 3995b23..351e855 100644
--- a/lib/widgets/server_card.dart
+++ b/lib/widgets/server_card.dart
@@ -177,13 +177,29 @@ class _ServerCardState extends State<ServerCard> {
]),
],
const SizedBox(height: 6),
- Align(
- alignment: AlignmentDirectional.centerStart,
- child: TextButton(
- onPressed: () => launchUrl(Uri.parse(_guideUrl), mode: LaunchMode.externalApplication),
- child: Text(t.webPhoneGuide, style: AppTheme.f(13, weight: FontWeight.w700, color: gc.accent)),
+ Row(children: [
+ Flexible(
+ child: TextButton(
+ onPressed: () => launchUrl(Uri.parse(_guideUrl), mode: LaunchMode.externalApplication),
+ child: Text(t.webPhoneGuide,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: AppTheme.f(13, weight: FontWeight.w700, color: gc.accent)),
+ ),
),
- ),
+ if (_info?['auth'] == true) ...[
+ const Spacer(),
+ Flexible(
+ child: TextButton(
+ onPressed: link.signOut,
+ child: Text(t.webSignOut,
+ maxLines: 1,
+ overflow: TextOverflow.ellipsis,
+ style: AppTheme.f(13, weight: FontWeight.w700, color: gc.textSecondary)),
+ ),
+ ),
+ ],
+ ]),
]),
),
);
diff --git a/server/bin/server.dart b/server/bin/server.dart
index 63b5175..21e9e1a 100644
--- a/server/bin/server.dart
+++ b/server/bin/server.dart
@@ -13,6 +13,7 @@ Environment:
GYMMANE_DATA folder for your data (default ./data next to the server)
GYMMANE_WEB folder with the web app (default ./web next to the server)
GYMMANE_PASSWORD ask for this password in the browser (optional)
+ GYMMANE_PEOPLE several people, each with their own data: "Ana, Pablo" or "Ana:pass1, Pablo:pass2"
GYMMANE_SYNC folder shared with your phone through Syncthing (default DATA/sync, "off" to disable)
GYMMANE_KEEP_DAYS daily copies of your data to keep (default 30)
@@ -22,13 +23,29 @@ Environment:
if (args.contains('--health')) {
exit(await _healthy(Config.fromEnvironment()) ? 0 : 1);
}
- final config = Config.fromEnvironment();
+ final Config config;
+ try {
+ config = Config.fromEnvironment();
+ } on FormatException catch (e) {
+ stderr.writeln('GYMMANE_PEOPLE: ${e.message}');
+ exit(1);
+ }
final server = GymManeServer(config);
try {
await server.start();
+ } on FormatException catch (e) {
+ stderr.writeln('GYMMANE_PEOPLE: ${e.message}');
+ exit(1);
} on FileSystemException catch (e) {
stderr.writeln('GymMane cannot write to ${e.path ?? config.dataDir}.');
- stderr.writeln('Give the user that runs GymMane write access to that folder, or set GYMMANE_DATA to another one.');
+ if (File('/.dockerenv').existsSync() || config.dataDir == '/data') {
+ stderr.writeln('The folder you mounted on /data belongs to another user. Either:');
+ stderr.writeln(' - give it to the user GymMane runs as: chown -R 1000:1000 <that folder>');
+ stderr.writeln(' - or run GymMane as the folder owner: --user <uid>:<gid> (in compose, user: "<uid>:<gid>")');
+ stderr.writeln(' - or use a Docker volume instead of a folder: -v gymmane-data:/data');
+ } else {
+ stderr.writeln('Give the user that runs GymMane write access to that folder, or set GYMMANE_DATA to another one.');
+ }
exit(1);
} on SocketException catch (e) {
stderr.writeln('GymMane cannot listen on port ${config.port}: ${e.osError?.message ?? e.message}');
@@ -40,9 +57,19 @@ Environment:
for (final ip in await _lanAddresses()) {
stdout.writeln(' http://$ip:${server.port}');
}
- stdout.writeln(' Data: ${Directory(config.dataDir).absolute.path}');
- if (config.syncDir != null) stdout.writeln(' Phone: ${Directory(config.syncDir!).absolute.path}');
- if (config.password != null) stdout.writeln(' Password required.');
+ if (server.shared) {
+ for (final s in server.spaces) {
+ stdout.writeln(' ${s.person!.display}:');
+ stdout.writeln(' Open: http://localhost:${server.port}${s.base}');
+ stdout.writeln(' Data: ${Directory(s.dataDir).absolute.path}');
+ if (s.syncDir != null) stdout.writeln(' Phone: ${Directory(s.syncDir!).absolute.path}');
+ stdout.writeln(s.password != null ? ' Password required.' : ' No password.');
+ }
+ } else {
+ stdout.writeln(' Data: ${Directory(config.dataDir).absolute.path}');
+ if (config.syncDir != null) stdout.writeln(' Phone: ${Directory(config.syncDir!).absolute.path}');
+ if (config.password != null) stdout.writeln(' Password required.');
+ }
for (final signal in [ProcessSignal.sigint, if (!Platform.isWindows) ProcessSignal.sigterm]) {
signal.watch().listen((_) async {
diff --git a/server/lib/src/config.dart b/server/lib/src/config.dart
index 0125cea..ddf44f2 100644
--- a/server/lib/src/config.dart
+++ b/server/lib/src/config.dart
@@ -1,5 +1,35 @@
import 'dart:io';
+class Person {
+ const Person(this.name, this.label, this.password);
+
+ final String name;
+ final String label;
+ final String? password;
+
+ String get display => label;
+
+ static const _plain = {
+ 'á': 'a', 'à': 'a', 'â': 'a', 'ä': 'a', 'ã': 'a', 'å': 'a',
+ 'é': 'e', 'è': 'e', 'ê': 'e', 'ë': 'e',
+ 'í': 'i', 'ì': 'i', 'î': 'i', 'ï': 'i',
+ 'ó': 'o', 'ò': 'o', 'ô': 'o', 'ö': 'o', 'õ': 'o', 'ø': 'o',
+ 'ú': 'u', 'ù': 'u', 'û': 'u', 'ü': 'u',
+ 'ñ': 'n', 'ç': 'c', 'ß': 'ss', 'æ': 'ae', 'œ': 'oe',
+ };
+
+ static String slug(String label) {
+ final out = StringBuffer();
+ for (final ch in label.toLowerCase().split('')) {
+ out.write(_plain[ch] ?? ch);
+ }
+ return out
+ .toString()
+ .replaceAll(RegExp(r'[^a-z0-9]+'), '-')
+ .replaceAll(RegExp(r'^-+|-+$'), '');
+ }
+}
+
class Config {
Config({
required this.port,
@@ -9,6 +39,7 @@ class Config {
required this.syncDir,
required this.password,
required this.keepDays,
+ this.people = const [],
});
final int port;
@@ -18,6 +49,7 @@ class Config {
final String? syncDir;
final String? password;
final int keepDays;
+ final List<Person> people;
factory Config.fromEnvironment([Map<String, String>? env]) {
final e = env ?? Platform.environment;
@@ -37,6 +69,29 @@ class Config {
syncDir: sync == 'off' ? null : sync ?? '$data${Platform.pathSeparator}sync',
password: read('GYMMANE_PASSWORD'),
keepDays: int.tryParse(read('GYMMANE_KEEP_DAYS') ?? '') ?? 30,
+ people: parsePeople(read('GYMMANE_PEOPLE')),
);
}
+
+ static List<Person> parsePeople(String? text) {
+ if (text == null) return const [];
+ var raw = text.trim();
+ if (raw.length >= 2 && (raw[0] == '"' || raw[0] == "'") && raw[raw.length - 1] == raw[0]) {
+ raw = raw.substring(1, raw.length - 1);
+ }
+ final out = <Person>[];
+ for (final item in raw.split(',')) {
+ if (item.trim().isEmpty) continue;
+ final cut = item.indexOf(':');
+ final label = (cut < 0 ? item : item.substring(0, cut)).trim().replaceAll(RegExp(r'\s+'), ' ');
+ final pass = cut < 0 ? null : item.substring(cut + 1).trim();
+ final name = Person.slug(label);
+ if (name.isEmpty || name.length > 40) {
+ throw FormatException('"$label" cannot be a name: use letters or digits, up to 40.');
+ }
+ if (out.any((p) => p.name == name)) throw FormatException('"$label" is in GYMMANE_PEOPLE twice.');
+ out.add(Person(name, label, pass == null || pass.isEmpty ? null : pass));
+ }
+ return out;
+ }
}
diff --git a/server/lib/src/pages.dart b/server/lib/src/pages.dart
new file mode 100644
index 0000000..bd562a8
--- /dev/null
+++ b/server/lib/src/pages.dart
@@ -0,0 +1,121 @@
+import 'dart:convert';
+
+import 'config.dart';
+
+String _esc(String s) => const HtmlEscape().convert(s);
+
+String personalPage(String html, Person person) => html
+ .replaceFirst(RegExp(r'<base href="[^"]*"\s*/?>'),
+ '<base href="/${person.name}/">\n <meta name="gymmane-person" content="${person.name}">')
+ .replaceFirst('<title>GymMane</title>', '<title>GymMane · ${_esc(person.display)}</title>');
+
+String personalManifest(String text, Person person) {
+ try {
+ final m = jsonDecode(text) as Map<String, dynamic>;
+ final label = person.display;
+ m['name'] = 'GymMane · $label';
+ m['short_name'] = label.length <= 12 ? label : 'GymMane';
+ m['id'] = '/${person.name}/';
+ return jsonEncode(m);
+ } catch (_) {
+ return text;
+ }
+}
+
+const _style = '''
+@font-face { font-family: "Nunito"; font-weight: 800; font-display: swap; src: url("/assets/assets/fonts/Nunito-ExtraBold.ttf") format("truetype"); }
+@font-face { font-family: "Nunito"; font-weight: 600; font-display: swap; src: url("/assets/assets/fonts/Nunito-SemiBold.ttf") format("truetype"); }
+* { box-sizing: border-box; }
+html, body { margin: 0; min-height: 100%; background: #0A0A0A; color: #F2EEE9; }
+body { display: flex; align-items: center; justify-content: center; min-height: 100vh; padding: 32px 16px;
+ font-family: "Nunito", -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, sans-serif; }
+main { width: 100%; max-width: 360px; display: flex; flex-direction: column; align-items: center; }
+.icon { width: 72px; height: 72px; border-radius: 16px; }
+h1 { margin: 22px 0 6px; max-width: 100%; font-size: 28px; font-weight: 800; letter-spacing: -.02em; text-align: center;
+ overflow-wrap: anywhere; }
+p { margin: 0 0 22px; color: #8C857F; font-size: 14px; font-weight: 600; text-align: center; }
+nav, form { width: 100%; display: flex; flex-direction: column; gap: 8px; }
+.row { display: flex; align-items: center; gap: 12px; min-height: 56px; padding: 10px 16px 10px 10px;
+ border-radius: 16px; background: #161514; color: inherit; text-decoration: none; transition: background .15s ease; }
+.row:hover, .row:focus-visible { background: #1F1D1B; outline: none; }
+.row:active { background: #262321; }
+.dot { flex: none; width: 36px; height: 36px; border-radius: 50%; display: grid; place-items: center;
+ background: #241F1C; color: #D9A184; font-size: 16px; font-weight: 800; }
+.name { flex: 1; min-width: 0; font-size: 17px; font-weight: 800; letter-spacing: -.01em;
+ overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.row svg { flex: none; width: 16px; height: 16px; color: #8C857F; }
+input[type=password] { width: 100%; height: 52px; padding: 0 16px; border-radius: 16px; border: 1.5px solid transparent;
+ background: #161514; color: #F2EEE9; font: inherit; font-size: 16px; font-weight: 600; outline: none;
+ transition: border-color .15s ease; }
+input[type=password]::placeholder { color: #5E5853; }
+input[type=password]:focus { border-color: #D9A184; }
+.bad input[type=password] { border-color: #D97A6C; }
+.err { display: none; margin: 2px 4px 0; color: #D97A6C; font-size: 13px; font-weight: 600; }
+.bad .err { display: block; }
+button { height: 52px; margin-top: 8px; border: 0; border-radius: 999px; background: #F2EEE9; color: #0A0A0A;
+ font: inherit; font-size: 16px; font-weight: 800; cursor: pointer; transition: transform .1s ease, opacity .15s ease; }
+button:active { transform: scale(.98); opacity: .9; }
+.back { margin-top: 22px; color: #8C857F; font-size: 14px; font-weight: 600; text-decoration: none; }
+.back:hover { color: #F2EEE9; }
+.hide { position: absolute; width: 1px; height: 1px; opacity: 0; pointer-events: none; }
+''';
+
+String _page(String body, String script) => '''<!DOCTYPE html>
+<html lang="en">
+<head>
+<meta charset="UTF-8">
+<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover">
+<meta name="theme-color" content="#0A0A0A">
+<meta name="color-scheme" content="dark">
+<link rel="icon" type="image/png" href="/favicon.png">
+<title>GymMane</title>
+<style>$_style</style>
+</head>
+<body>
+<main>
+<img class="icon" src="/icons/Icon-192.png" alt="">
+$body
+</main>
+<script>
+var es = (navigator.language || '').toLowerCase().indexOf('es') === 0;
+function say(id, en, sp) { var e = document.getElementById(id); if (e) e[e.tagName === 'INPUT' ? 'placeholder' : 'textContent'] = es ? sp : en; }
+if (es) document.documentElement.lang = 'es';
+$script
+</script>
+</body>
+</html>''';
+
+String pickerPage(List<Person> people) {
+ final rows = StringBuffer();
+ for (final p in people) {
+ final label = _esc(p.display);
+ rows.write('<a class="row" href="/${p.name}/"><span class="dot">${_esc(p.display.substring(0, 1).toUpperCase())}</span>'
+ '<span class="name">$label</span>'
+ '<svg viewBox="0 0 256 256" aria-hidden="true"><path d="M96 48l80 80-80 80" fill="none" '
+ 'stroke="currentColor" stroke-width="20" stroke-linecap="round" stroke-linejoin="round"/></svg></a>');
+ }
+ return _page(
+ '<h1 id="t">Who\'s training?</h1>\n<p id="s">Each person has their own data.</p>\n<nav>$rows</nav>',
+ "say('t', \"Who's training?\", '¿Quién entrena?');\nsay('s', 'Each person has their own data.', 'Cada persona tiene sus propios datos.');",
+ );
+}
+
+String loginPage({required String action, Person? person, bool wrong = false, bool wait = false, bool shared = false}) {
+ final title = person == null ? 'GymMane' : _esc(person.display);
+ final user = person?.name ?? 'gymmane';
+ final back = shared ? '<a class="back" id="b" href="/">Not you?</a>' : '';
+ return _page(
+ '<h1>$title</h1>\n<p id="s">Enter your password to continue.</p>\n'
+ '<form method="post" action="$action"${wrong || wait ? ' class="bad"' : ''}${wait ? ' data-wait="1"' : ''}>'
+ '<input class="hide" type="text" name="username" value="$user" autocomplete="username" tabindex="-1" aria-hidden="true">'
+ '<input id="p" type="password" name="password" placeholder="Password" autocomplete="current-password" autofocus required>'
+ '<div class="err" id="e" role="alert">${wait ? 'Too many tries. Wait a few minutes and try again.' : 'That password isn\'t right.'}</div>'
+ '<button id="go" type="submit">Sign in</button></form>$back',
+ "say('s', 'Enter your password to continue.', 'Escribe tu contraseña para entrar.');\n"
+ "say('p', 'Password', 'Contraseña');\n"
+ "if (document.querySelector('form[data-wait]')) say('e', 'Too many tries. Wait a few minutes and try again.', 'Demasiados intentos. Espera unos minutos y vuelve a probar.');\n"
+ "else say('e', \"That password isn't right.\", 'Esa contraseña no es correcta.');\n"
+ "say('go', 'Sign in', 'Entrar');\n"
+ "say('b', 'Not you?', '¿No eres tú?');",
+ );
+}
diff --git a/server/lib/src/server.dart b/server/lib/src/server.dart
index cadade3..15b1d88 100644
--- a/server/lib/src/server.dart
+++ b/server/lib/src/server.dart
@@ -1,39 +1,103 @@
import 'dart:async';
import 'dart:convert';
import 'dart:io';
+import 'dart:math';
import 'dart:typed_data';
+import 'package:crypto/crypto.dart';
+
import 'config.dart';
import 'media_store.dart';
import 'phone_sync.dart';
+import 'pages.dart';
import 'state_store.dart';
-const serverVersion = '1.0.0';
+const serverVersion = '1.1.0';
-class GymManeServer {
- GymManeServer(this.config)
- : store = StateStore(config.dataDir, keepDays: config.keepDays),
- media = MediaFiles('${config.dataDir}/media');
+class Space {
+ Space({required this.person, required this.dataDir, required this.syncDir, required this.password, required int keepDays})
+ : store = StateStore(dataDir, keepDays: keepDays),
+ media = MediaFiles('$dataDir/media');
- final Config config;
+ final Person? person;
+ final String dataDir;
+ final String? syncDir;
+ final String? password;
final StateStore store;
final MediaFiles media;
PhoneSync? sync;
- HttpServer? _http;
+ String? _token;
- static const _maxState = 64 * 1024 * 1024;
- static const _maxMedia = 80 * 1024 * 1024;
+ String get base => person == null ? '/' : '/${person!.name}/';
- int get port => _http?.port ?? config.port;
+ String get cookie => person == null ? 'gymmane' : 'gymmane-${person!.name}';
+
+ String? get token => _token;
+
+ static const maxFails = 20;
+ static const failWindow = Duration(minutes: 10);
+ final List<DateTime> _fails = [];
+
+ bool get locked {
+ final since = DateTime.now().subtract(failWindow);
+ _fails.removeWhere((at) => at.isBefore(since));
+ return _fails.length >= maxFails;
+ }
+
+ void failed() => _fails.add(DateTime.now());
Future<void> start() async {
await store.open();
await media.open();
- final dir = config.syncDir;
+ final pass = password;
+ if (pass != null) {
+ final file = File('$dataDir/login.key');
+ List<int> key;
+ try {
+ key = base64.decode((await file.readAsString()).trim());
+ } catch (_) {
+ final random = Random.secure();
+ key = List<int>.generate(32, (_) => random.nextInt(256));
+ await file.writeAsString(base64.encode(key), flush: true);
+ }
+ _token = base64Url.encode(Hmac(sha256, key).convert(utf8.encode(pass)).bytes).replaceAll('=', '');
+ }
+ final dir = syncDir;
if (dir != null) {
- sync = PhoneSync(syncDir: dir, dataDir: config.dataDir, store: store, media: media);
+ sync = PhoneSync(syncDir: dir, dataDir: dataDir, store: store, media: media);
await sync!.start();
}
+ }
+}
+
+class GymManeServer {
+ GymManeServer(this.config);
+
+ final Config config;
+ final List<Space> spaces = [];
+ HttpServer? _http;
+
+ static const _maxState = 64 * 1024 * 1024;
+ static const _maxMedia = 80 * 1024 * 1024;
+
+ int get port => _http?.port ?? config.port;
+
+ bool get shared => config.people.isNotEmpty;
+
+ Space? spaceOf(String name) {
+ for (final s in spaces) {
+ if (s.person?.name == name) return s;
+ }
+ return null;
+ }
+
+ Future<void> start() async {
+ spaces
+ ..clear()
+ ..addAll(await _layout());
+ for (final s in spaces) {
+ await s.start();
+ }
final http = await HttpServer.bind(config.host, config.port, shared: true);
http.autoCompress = true;
http.idleTimeout = const Duration(seconds: 30);
@@ -42,29 +106,66 @@ class GymManeServer {
}
Future<void> stop() async {
- sync?.stop();
+ for (final s in spaces) {
+ s.sync?.stop();
+ }
await _http?.close(force: true);
}
+ Future<List<Space>> _layout() async {
+ if (!shared) {
+ return [
+ Space(
+ person: null,
+ dataDir: config.dataDir,
+ syncDir: config.syncDir,
+ password: config.password,
+ keepDays: config.keepDays),
+ ];
+ }
+ final taken = {'api', 'index.html'};
+ final web = Directory(config.webDir);
+ if (await web.exists()) {
+ await for (final e in web.list()) {
+ taken.add(e.uri.pathSegments.lastWhere((p) => p.isNotEmpty).toLowerCase());
+ }
+ }
+ for (final p in config.people) {
+ if (taken.contains(p.name)) {
+ throw FormatException('"${p.label}" cannot be a name in GYMMANE_PEOPLE, pick another one.');
+ }
+ }
+ await Directory(config.dataDir).create(recursive: true);
+ final mark = File('${config.dataDir}/owner.txt');
+ var owner = await mark.exists() ? (await mark.readAsString()).trim() : '';
+ if (owner.isEmpty) {
+ owner = config.people.first.name;
+ await mark.writeAsString(owner, flush: true);
+ }
+ Space at(Person p, String dir, String? sync) => Space(
+ person: p, dataDir: dir, syncDir: sync, password: p.password ?? config.password, keepDays: config.keepDays);
+ return [
+ for (final p in config.people)
+ if (p.name == owner)
+ at(p, config.dataDir, config.syncDir)
+ else
+ at(p, '${config.dataDir}/people/${p.name}',
+ config.syncDir == null ? null : '${config.dataDir}/people/${p.name}/sync'),
+ ];
+ }
+
Future<void> _handle(HttpRequest req) async {
final res = req.response;
res.headers
..set('x-content-type-options', 'nosniff')
..set('referrer-policy', 'no-referrer');
try {
- if (!_authorized(req)) {
- res.statusCode = HttpStatus.unauthorized;
- res.headers.set('www-authenticate', 'Basic realm="GymMane", charset="UTF-8"');
- res.write('Sign in to open GymMane.');
- return;
- }
final path = req.uri.path;
- if (path.startsWith('/api/')) {
- res.headers.set('cache-control', 'no-store');
- await _api(req, path.substring(5));
- } else {
- await _static(req, path);
+ if (shared) {
+ await _route(req, path);
+ return;
}
+ await _serve(req, spaces.first, path);
} catch (e) {
try {
res.statusCode = HttpStatus.internalServerError;
@@ -77,15 +178,129 @@ class GymManeServer {
}
}
- bool _authorized(HttpRequest req) {
- final password = config.password;
+ Future<void> _route(HttpRequest req, String path) async {
+ final res = req.response;
+ final parts = path.split('/').where((p) => p.isNotEmpty).toList();
+ final space = parts.isEmpty ? null : spaceOf(parts.first.toLowerCase());
+ if (space == null) {
+ if (path == '/api/health') return _json(res, {'ok': true});
+ if (parts.isNotEmpty && parts.first != 'api' && parts.last.contains('.') && parts.last != 'index.html') {
+ return _static(req, path, null);
+ }
+ if (parts.isNotEmpty) {
+ res.statusCode = HttpStatus.found;
+ res.headers.set(HttpHeaders.locationHeader, '/');
+ return;
+ }
+ if (req.method != 'GET' && req.method != 'HEAD') {
+ res.statusCode = HttpStatus.methodNotAllowed;
+ return;
+ }
+ res.headers
+ ..contentType = ContentType.html
+ ..set('cache-control', 'no-cache');
+ if (req.method == 'GET') res.write(pickerPage([for (final s in spaces) s.person!]));
+ return;
+ }
+ final cut = path.indexOf('/', 1);
+ final rest = cut < 0 ? '' : path.substring(cut);
+ if (rest.isEmpty) {
+ res.statusCode = HttpStatus.movedPermanently;
+ res.headers.set(HttpHeaders.locationHeader, '${space.base}${req.uri.hasQuery ? '?${req.uri.query}' : ''}');
+ return;
+ }
+ await _serve(req, space, rest);
+ }
+
+ Future<void> _serve(HttpRequest req, Space space, String rest) async {
+ final res = req.response;
+ if (rest == '/api/health') return _json(res, {'ok': true});
+ if (rest == '/login' && req.method == 'POST') return _login(req, space);
+ if (rest == '/logout') {
+ _setCookie(req, space, '', 0);
+ res.statusCode = HttpStatus.seeOther;
+ res.headers
+ ..set('cache-control', 'no-store')
+ ..set(HttpHeaders.locationHeader, shared ? '/' : space.base);
+ return;
+ }
+ if (!_authorized(req, space)) {
+ if (rest.startsWith('/api/')) return _json(res, {'error': 'sign in'}, status: HttpStatus.unauthorized);
+ final last = rest.substring(rest.lastIndexOf('/') + 1);
+ if (last.contains('.') && last != 'index.html') return _static(req, rest, space);
+ if (req.method != 'GET' && req.method != 'HEAD') {
+ res.statusCode = HttpStatus.unauthorized;
+ return;
+ }
+ return _loginPage(res, space);
+ }
+ if (rest.startsWith('/api/')) {
+ res.headers.set('cache-control', 'no-store');
+ return _api(req, space, rest.substring(5));
+ }
+ await _static(req, rest, space);
+ }
+
+ void _loginPage(HttpResponse res, Space space, {bool wrong = false}) {
+ final wait = space.locked;
+ res.statusCode = wait ? HttpStatus.tooManyRequests : (wrong ? HttpStatus.unauthorized : HttpStatus.ok);
+ res.headers
+ ..contentType = ContentType.html
+ ..set('cache-control', 'no-store');
+ res.write(loginPage(
+ action: '${space.base}login', person: space.person, wrong: wrong && !wait, wait: wait, shared: shared));
+ }
+
+ Future<void> _login(HttpRequest req, Space space) async {
+ final res = req.response;
+ final bytes = await _body(req, 8192);
+ var given = '';
+ try {
+ given = Uri.splitQueryString(utf8.decode(bytes ?? const []))['password'] ?? '';
+ } catch (_) {}
+ final pass = space.password;
+ if (pass != null && space.locked) return _loginPage(res, space);
+ if (pass != null && !_same(given, pass)) {
+ space.failed();
+ await Future<void>.delayed(const Duration(milliseconds: 800));
+ return _loginPage(res, space, wrong: true);
+ }
+ if (pass != null) _setCookie(req, space, space.token!, 400 * 24 * 3600);
+ res.statusCode = HttpStatus.seeOther;
+ res.headers
+ ..set('cache-control', 'no-store')
+ ..set(HttpHeaders.locationHeader, space.base);
+ }
+
+ void _setCookie(HttpRequest req, Space space, String value, int maxAge) {
+ final secure = req.requestedUri.scheme == 'https' ||
+ (req.headers.value('x-forwarded-proto') ?? '').toLowerCase().startsWith('https');
+ req.response.headers.add(
+ 'set-cookie',
+ '${space.cookie}=$value; Path=${space.base}; Max-Age=$maxAge; HttpOnly; SameSite=Lax'
+ '${secure ? '; Secure' : ''}');
+ }
+
+ bool _authorized(HttpRequest req, Space space) {
+ final password = space.password;
if (password == null) return true;
+ final token = space.token;
+ for (final line in req.headers[HttpHeaders.cookieHeader] ?? const <String>[]) {
+ for (final part in line.split(';')) {
+ final eq = part.indexOf('=');
+ if (eq < 0 || part.substring(0, eq).trim() != space.cookie) continue;
+ if (token != null && _same(part.substring(eq + 1).trim(), token)) return true;
+ }
+ }
final header = req.headers.value(HttpHeaders.authorizationHeader) ?? '';
if (!header.toLowerCase().startsWith('basic ')) return false;
try {
final decoded = utf8.decode(base64.decode(header.substring(6).trim()));
final given = decoded.contains(':') ? decoded.substring(decoded.indexOf(':') + 1) : decoded;
- return _same(given, password);
+ if (space.locked) return false;
+ if (_same(given, password)) return true;
+ space.failed();
+ return false;
} catch (_) {
return false;
}
@@ -116,9 +331,12 @@ class GymManeServer {
return out.takeBytes();
}
- Future<void> _api(HttpRequest req, String route) async {
+ Future<void> _api(HttpRequest req, Space space, String route) async {
final res = req.response;
final method = req.method;
+ final store = space.store;
+ final media = space.media;
+ final sync = space.sync;
if (route == 'health') return _json(res, {'ok': true});
if (route == 'info' && method == 'GET') {
final now = store.current;
@@ -128,7 +346,8 @@ class GymManeServer {
'rev': now.rev,
if (now.savedAt != null) 'savedAt': now.savedAt!.toIso8601String(),
'source': now.source,
- 'auth': config.password != null,
+ 'auth': space.password != null,
+ if (space.person != null) 'person': space.person!.display,
'sync': sync?.info ?? {'enabled': false},
});
}
@@ -218,7 +437,7 @@ class GymManeServer {
'frag': 'application/octet-stream',
};
- Future<void> _static(HttpRequest req, String path) async {
+ Future<void> _static(HttpRequest req, String path, Space? space) async {
final res = req.response;
if (req.method != 'GET' && req.method != 'HEAD') {
res.statusCode = HttpStatus.methodNotAllowed;
@@ -253,19 +472,34 @@ class GymManeServer {
final modified = stat.modified.toUtc();
final since = req.headers.ifModifiedSince;
final entry = name == 'index.html' || name == 'flutter_bootstrap.js' || name == 'flutter_service_worker.js';
+ final person = space?.person;
+ final own = person != null &&
+ (name == 'index.html' || name == 'manifest.json') &&
+ file.path == '$root${Platform.pathSeparator}$name';
res.headers
..set('content-type', _types[ext] ?? 'application/octet-stream')
- ..set('cache-control', entry ? 'no-cache' : 'public, max-age=3600')
+ ..set('cache-control', entry || own ? 'no-cache' : 'public, max-age=3600')
..set('cross-origin-opener-policy', 'same-origin')
..set('cross-origin-embedder-policy', 'require-corp')
..set('cross-origin-resource-policy', 'same-origin')
- ..set(HttpHeaders.varyHeader, 'accept-encoding')
- ..set(HttpHeaders.lastModifiedHeader, HttpDate.format(modified));
+ ..set(HttpHeaders.varyHeader, 'accept-encoding');
+ final accepts = req.headers[HttpHeaders.acceptEncodingHeader]?.join(',').contains('gzip') ?? false;
+ if (own) {
+ final text = await file.readAsString();
+ var bytes = utf8.encode(name == 'index.html' ? personalPage(text, person) : personalManifest(text, person));
+ if (accepts) {
+ bytes = Uint8List.fromList(gzip.encode(bytes));
+ res.headers.set(HttpHeaders.contentEncodingHeader, 'gzip');
+ }
+ res.contentLength = bytes.length;
+ if (req.method == 'GET') res.add(bytes);
+ return;
+ }
+ res.headers.set(HttpHeaders.lastModifiedHeader, HttpDate.format(modified));
if (since != null && !modified.isAfter(since.add(const Duration(seconds: 1)))) {
res.statusCode = HttpStatus.notModified;
return;
}
- final accepts = req.headers[HttpHeaders.acceptEncodingHeader]?.join(',').contains('gzip') ?? false;
if (accepts && _packable.contains(ext) && stat.size > 1024) {
final packed = await _packed(file, modified);
res.headers.set(HttpHeaders.contentEncodingHeader, 'gzip');
diff --git a/server/pubspec.lock b/server/pubspec.lock
index 73b089d..815d2df 100644
--- a/server/pubspec.lock
+++ b/server/pubspec.lock
@@ -90,7 +90,7 @@ packages:
source: hosted
version: "1.16.0"
crypto:
- dependency: transitive
+ dependency: "direct main"
description:
name: crypto
sha256: e3626ae6270383c9e3a549f34c9e4cd26c09ae6a9adaab2bf4737a00340efdc4
diff --git a/server/pubspec.yaml b/server/pubspec.yaml
index 1731a69..6247597 100644
--- a/server/pubspec.yaml
+++ b/server/pubspec.yaml
@@ -8,6 +8,7 @@ environment:
dependencies:
archive: ^4.0.9
+ crypto: ^3.0.6
sync:
path: ../packages/sync
diff --git a/server/test/server_test.dart b/server/test/server_test.dart
index 1ab1ffe..2b63b48 100644
--- a/server/test/server_test.dart
+++ b/server/test/server_test.dart
@@ -10,10 +10,12 @@ void main() {
late GymManeServer server;
late HttpClient client;
- Future<GymManeServer> boot({String? password}) async {
+ Future<GymManeServer> boot({String? password, String? people}) async {
final web = Directory('${tmp.path}/web')..createSync(recursive: true);
- File('${web.path}/index.html').writeAsStringSync('<html>gymmane</html>');
+ File('${web.path}/index.html')
+ .writeAsStringSync('<html><head><base href="/"><title>GymMane</title></head>gymmane</html>');
File('${web.path}/main.dart.js').writeAsStringSync('console.log(1)');
+ File('${web.path}/manifest.json').writeAsStringSync('{"name":"GymMane","short_name":"GymMane","start_url":"."}');
final s = GymManeServer(Config(
port: 0,
host: '127.0.0.1',
@@ -22,6 +24,7 @@ void main() {
syncDir: '${tmp.path}/sync',
password: password,
keepDays: 3,
+ people: Config.parsePeople(people),
));
await s.start();
return s;
@@ -29,7 +32,8 @@ void main() {
Future<(int, String, HttpHeaders)> call(String method, String path,
{String? body, List<int>? bytes, Map<String, String> headers = const {}}) async {
- final req = await client.openUrl(method, Uri.parse('http://127.0.0.1:${server.port}$path'));
+ final req = await client.openUrl(method, Uri.parse('http://127.0.0.1:${server.port}$path'))
+ ..followRedirects = false;
headers.forEach(req.headers.set);
if (body != null) req.write(body);
if (bytes != null) req.add(bytes);
@@ -105,12 +109,41 @@ void main() {
expect(escape, isNot(200));
});
- test('con contraseña pide entrar y deja pasar con la correcta', () async {
+ test('con contraseña enseña su propia pantalla de entrar y recuerda la sesión', () async {
await server.stop();
server = await boot(password: 'pesas');
final (closed, _, h) = await call('GET', '/api/info');
expect(closed, 401);
- expect(h.value('www-authenticate'), contains('Basic'));
+ expect(h.value('www-authenticate'), isNull);
+ final (page, html, _) = await call('GET', '/progress');
+ expect(page, 200);
+ expect(html, contains('type="password"'));
+ expect(html, contains('action="/login"'));
+ expect(html, isNot(contains('gymmane</html>')));
+ final (asset, _, _) = await call('GET', '/main.dart.js');
+ expect(asset, 200);
+ final form = {'content-type': 'application/x-www-form-urlencoded'};
+ final (bad, badHtml, badH) = await call('POST', '/login', body: 'password=otra', headers: form);
+ expect(bad, 401);
+ expect(badHtml, contains('class="bad"'));
+ expect(badH.value('set-cookie'), isNull);
+ final (good, _, goodH) = await call('POST', '/login', body: 'password=pesas', headers: form);
+ expect(good, 303);
+ expect(goodH.value('location'), '/');
+ final cookie = goodH.value('set-cookie')!;
+ expect(cookie, contains('HttpOnly'));
+ expect(cookie, contains('Path=/;'));
+ final session = {'cookie': cookie.split(';').first};
+ final (inside, _, _) = await call('GET', '/api/info', headers: session);
+ expect(inside, 200);
+ final (app, appHtml, _) = await call('GET', '/', headers: session);
+ expect(app, 200);
+ expect(appHtml, contains('gymmane</html>'));
+ final (out, _, outH) = await call('GET', '/logout', headers: session);
+ expect(out, 303);
+ expect(outH.value('set-cookie'), contains('Max-Age=0'));
+ final (forged, _, _) = await call('GET', '/api/info', headers: {'cookie': 'gymmane=pesas'});
+ expect(forged, 401);
final wrong = base64.encode(utf8.encode('yo:otra'));
final (no, _, _) = await call('GET', '/api/info', headers: {'authorization': 'Basic $wrong'});
expect(no, 401);
@@ -119,6 +152,23 @@ void main() {
expect(ok, 200);
});
+ test('tras muchos intentos fallidos deja de aceptar contraseñas un rato', () async {
+ await server.stop();
+ server = await boot(password: 'pesas');
+ final space = server.spaces.single;
+ for (var i = 0; i < Space.maxFails; i++) {
+ space.failed();
+ }
+ final form = {'content-type': 'application/x-www-form-urlencoded'};
+ final (status, html, h) = await call('POST', '/login', body: 'password=pesas', headers: form);
+ expect(status, 429);
+ expect(html, contains('data-wait'));
+ expect(h.value('set-cookie'), isNull);
+ final right = base64.encode(utf8.encode('yo:pesas'));
+ final (basic, _, _) = await call('GET', '/api/info', headers: {'authorization': 'Basic $right'});
+ expect(basic, 401);
+ });
+
test('junta la copia del móvil con lo de la web, con sus fotos, y deja la suya', () async {
await call('PUT', '/api/state', body: jsonEncode({
'notes': [
@@ -185,4 +235,113 @@ void main() {
expect(history, hasLength(1));
expect(history.single.readAsStringSync(), '{"a":1}');
});
+
+ group('varias personas', () {
+ String basic(String pass) => 'Basic ${base64.encode(utf8.encode('x:$pass'))}';
+
+ test('lee GYMMANE_PEOPLE con y sin contraseña y rechaza nombres raros', () {
+ final people = Config.parsePeople('"Ana María José:uno:1 , pablo"');
+ expect(people.map((p) => p.name), ['ana-maria-jose', 'pablo']);
+ expect(people.first.label, 'Ana María José');
+ expect(people.first.password, 'uno:1');
+ expect(people.last.password, isNull);
+ expect(() => Config.parsePeople('ana, Ana'), throwsFormatException);
+ expect(() => Config.parsePeople('ana, ???'), throwsFormatException);
+ expect(Config.parsePeople(null), isEmpty);
+ });
+
+ test('la portada lista a cada uno y cada uno tiene su dirección', () async {
+ await server.stop();
+ server = await boot(people: 'Ana, Pablo');
+ final (status, html, _) = await call('GET', '/');
+ expect(status, 200);
+ expect(html, contains('href="/ana/"'));
+ expect(html, contains('href="/pablo/"'));
+ final (moved, _, h) = await call('GET', '/ana');
+ expect(moved, 301);
+ expect(h.value('location'), '/ana/');
+ final (ok, page, _) = await call('GET', '/ana/');
+ expect(ok, 200);
+ expect(page, contains('<base href="/ana/">'));
+ expect(page, contains('<meta name="gymmane-person" content="ana">'));
+ expect(page, contains('GymMane · Ana'));
+ final (deep, page2, _) = await call('GET', '/pablo/progress');
+ expect(deep, 200);
+ expect(page2, contains('<base href="/pablo/">'));
+ final (js, code, _) = await call('GET', '/pablo/main.dart.js');
+ expect(js, 200);
+ expect(code, 'console.log(1)');
+ final (_, manifest, _) = await call('GET', '/pablo/manifest.json');
+ expect(jsonDecode(manifest)['short_name'], 'Pablo');
+ final (unknown, _, h2) = await call('GET', '/carla/');
+ expect(unknown, 302);
+ expect(h2.value('location'), '/');
+ final (rootApi, _, _) = await call('GET', '/api/state');
+ expect(rootApi, 302);
+ final (health, _, _) = await call('GET', '/api/health');
+ expect(health, 200);
+ });
+
+ test('los datos de cada persona no se mezclan y el primero se queda con lo que había', () async {
+ await call('PUT', '/api/state', body: '{"mine":"before"}');
+ await server.stop();
+ server = await boot(people: 'ana, Pablo');
+ final (_, ana, _) = await call('GET', '/ana/api/state');
+ expect(jsonDecode(ana)['mine'], 'before');
+ final (empty, _, _) = await call('GET', '/pablo/api/state');
+ expect(empty, 204);
+ await call('PUT', '/pablo/api/state', body: '{"mine":"pablo"}');
+ await call('PUT', '/pablo/api/media/p-1.jpg', bytes: [7]);
+ final (_, again, _) = await call('GET', '/ana/api/state');
+ expect(jsonDecode(again)['mine'], 'before');
+ final (noPhoto, _, _) = await call('GET', '/ana/api/media/p-1.jpg');
+ expect(noPhoto, 404);
+ expect(File('${tmp.path}/data/people/pablo/state.json').readAsStringSync(), '{"mine":"pablo"}');
+ expect(Directory('${tmp.path}/data/people/pablo/sync').existsSync(), isTrue);
+
+ await server.stop();
+ server = await boot(people: 'Pablo, ana');
+ final (_, swapped, _) = await call('GET', '/ana/api/state');
+ expect(jsonDecode(swapped)['mine'], 'before');
+ final (_, info, _) = await call('GET', '/pablo/api/info');
+ expect(jsonDecode(info)['person'], 'Pablo');
+ });
+
+ test('cada persona entra con su contraseña', () async {
+ await server.stop();
+ server = await boot(password: 'casa-1234', people: 'Ana:ana-1234, pablo');
+ final (picker, _, _) = await call('GET', '/');
+ expect(picker, 200);
+ final (closed, _, _) = await call('GET', '/ana/api/info');
+ expect(closed, 401);
+ final (page, html, _) = await call('GET', '/ana/');
+ expect(page, 200);
+ expect(html, contains('<h1>Ana</h1>'));
+ expect(html, contains('action="/ana/login"'));
+ expect(html, contains('href="/"'));
+ final form = {'content-type': 'application/x-www-form-urlencoded'};
+ final (_, _, other) = await call('POST', '/ana/login', body: 'password=casa-1234', headers: form);
+ expect(other.value('set-cookie'), isNull);
+ final (_, _, mine) = await call('POST', '/ana/login', body: 'password=ana-1234', headers: form);
+ expect(mine.value('set-cookie'), contains('gymmane-ana='));
+ expect(mine.value('set-cookie'), contains('Path=/ana/;'));
+ final session = {'cookie': mine.value('set-cookie')!.split(';').first};
+ final (inside, _, _) = await call('GET', '/ana/api/info', headers: session);
+ expect(inside, 200);
+ final (notPablo, _, _) = await call('GET', '/pablo/api/info', headers: session);
+ expect(notPablo, 401);
+ final (wrong, _, _) = await call('GET', '/ana/api/info', headers: {'authorization': basic('casa-1234')});
+ expect(wrong, 401);
+ final (ok, _, _) = await call('GET', '/ana/api/info', headers: {'authorization': basic('ana-1234')});
+ expect(ok, 200);
+ final (shared, _, _) = await call('GET', '/pablo/api/info', headers: {'authorization': basic('casa-1234')});
+ expect(shared, 200);
+ });
+
+ test('no deja usar un nombre que choca con la web', () async {
+ await server.stop();
+ await expectLater(boot(people: 'ana, api'), throwsFormatException);
+ server = await boot();
+ });
+ });
}