Skip to content
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
10 changes: 5 additions & 5 deletions CLAUDE.md

Large diffs are not rendered by default.

30 changes: 17 additions & 13 deletions docs/RELEASE_NOTES_next.md
Original file line number Diff line number Diff line change
@@ -1,24 +1,28 @@
# StashTube 1.0.0-beta.8
# StashTube 1.0.0-beta.9

Pre-release. The pipeline picks the version (next beta after `v1.0.0-beta.7`).
Pre-release. The pipeline picks the version (next beta after `v1.0.0-beta.8`).

## What's new

- **Subtitles** – pick the captions your Stash has for a video from the new button in the player's top bar. The language is remembered for the next videos. The built-in demo has English and German subtitles to try it.
- **Zoom without black bars** – spread two fingers to fill the whole screen. The zoom grows continuously (up to 4×) and snaps at the fitted size and at full width/height, the position snaps to the center and the edges, each with a light haptic tick. Works inline, in fullscreen and after turning the phone.
- **Double tap to skip** – a half disc over the tapped side (like YouTube) with the total jump, fading in and out.
- **Playback** – videos can buffer fully before playing, position and picture are kept when you return to the app, the position is saved at once, a countdown runs before the next video of a queue, and the current frame can be saved.
- **Feedback and bugs** – Settings → About opens the GitHub issue forms.
- **Back where you were** – lists keep their place when you turn the phone for fullscreen and come back to them.
- **Favorites** – the avatars at the top pick "All" or one performer (a long press opens the channel), with a header and "View channel".
- **Zoom snap feedback** – "Original" and "Fill" show when the pinch zoom snaps, and guide lines where the picture snaps to the center or an edge.
- **PIN with biometrics** – changing the PIN or turning the app lock off also accepts Face ID or the fingerprint, so a forgotten PIN can be replaced.
- **Proxy warning** – a banner names both addresses when the server hands out media URLs on another address than the one StashTube connects to (a reverse proxy without `Host` / `X-Forwarded-Proto`), and how to fix it.

## Fixes and internals
## Security

- CI: generated l10n files regenerated with the CI's Flutter version (the generated-files check failed on `develop`).
- The pinch zoom is drawn by Flutter instead of mpv (`video-zoom` stays inside the video's rectangle); the controls keep their size.
- The API key and the session cookie only go to the server's own address (scheme, host and port): never to media URLs pointing elsewhere, and not along a redirect that leaves the server.
- The PIN is stored as PBKDF2-HMAC-SHA256. PINs of earlier versions keep working and are converted after the next correct entry.
- If the PIN can't be read (e.g. after restoring a backup), the app stays locked instead of opening: biometrics lead to a new PIN, otherwise the app can be reset.
- A password in a server address (`https://user:pass@host`) is kept in the secure storage instead of the settings; existing servers move on the first start.

## Issues
## Fixes and internals

Closes #57 (subtitles) and #58 (zoom/crop).
- GraphQL responses are no longer written into a cache that was never read.
- The preview check stops after the status instead of downloading whole files from servers that ignore `Range`.
- The password login gives up after 20 s instead of waiting forever.

## Not tested on a device yet

Pinch snapping and haptics (inline, fullscreen, turning), the skip half disc, subtitles on a real server, buffering and the queue countdown.
Proxy warning on a misconfigured server, the lost-PIN screen, and upgrading a PIN set by beta.8 or earlier.
19 changes: 16 additions & 3 deletions lib/core/config/image_cache.dart
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,30 @@ import 'dart:async';
import 'package:flutter/painting.dart';
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:http/http.dart' as http;

import '../network/origin_guard.dart';

/// The cache behind every `CachedNetworkImage` of server images: the
/// default cache's files and limits, but its downloads go through an
/// [OriginGuardClient], so a redirect away from the server doesn't take
/// the API key or session cookie along. Pass it as `cacheManager` to every
/// cached image; `DefaultCacheManager` itself must not be used next to it
/// (same key, same files).
final stashImageCacheManager = CacheManager(
Config(DefaultCacheManager.key, fileService: HttpFileService(httpClient: OriginGuardClient(http.Client()))),
);

/// Empties the image cache, e.g. when a server is removed: its thumbnails
/// must not stay on the device. Overridden in `main()` with
/// [clearDeviceImageCache]; does nothing elsewhere (tests have no cache).
final clearImageCacheProvider = Provider<void Function()>((ref) => () {});

/// Clears the images held in memory and the files `CachedNetworkImage`
/// keeps in the default cache manager. Best effort, and not awaited.
/// Clears the images held in memory and the files of
/// [stashImageCacheManager]. Best effort, and not awaited.
void clearDeviceImageCache() {
PaintingBinding.instance.imageCache
..clear()
..clearLiveImages();
unawaited(DefaultCacheManager().emptyCache().catchError((Object _) {}));
unawaited(stashImageCacheManager.emptyCache().catchError((Object _) {}));
}
19 changes: 18 additions & 1 deletion lib/core/config/secret_store.dart
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,9 @@ abstract interface class SecretStore {

/// Deletes every secret whose key passes [test], e.g. a removed server's.
Future<void> deleteWhere(bool Function(String key) test);

/// Deletes every secret, also ones that couldn't be read.
Future<void> clear();
}

class SecureSecretStore implements SecretStore {
Expand All @@ -28,7 +31,8 @@ class SecureSecretStore implements SecretStore {
values = await storage.readAll();
} catch (e) {
// Unreadable (e.g. a restored Android backup): start empty, the user
// enters the key again.
// enters the key again. A PIN lost with it keeps the app locked
// (AppLockSettings.pinLost).
debugPrint('Secure storage unreadable: $e');
values = {};
}
Expand Down Expand Up @@ -59,6 +63,16 @@ class SecureSecretStore implements SecretStore {
await write(key, null);
}
}

@override
Future<void> clear() async {
_cache.clear();
try {
await _storage.deleteAll();
} catch (e) {
debugPrint('Secure storage not cleared: $e');
}
}
}

/// In memory only: the default in tests, which don't override
Expand All @@ -82,6 +96,9 @@ class MemorySecretStore implements SecretStore {

@override
Future<void> deleteWhere(bool Function(String key) test) async => values.removeWhere((key, _) => test(key));

@override
Future<void> clear() async => values.clear();
}

/// Overridden in `main()` with the [SecureSecretStore] loaded before `runApp`.
Expand Down
59 changes: 52 additions & 7 deletions lib/core/config/server_config.dart
Original file line number Diff line number Diff line change
Expand Up @@ -55,6 +55,26 @@ class ServerConfig {
return key == null || key.isEmpty ? const {} : {'ApiKey': key};
}

/// [baseUrl] without the user info (`user:password@`) a URL may carry
/// for a proxy's basic auth: for showing, and for links that leave the
/// app.
String get displayUrl => withoutUserInfo(baseUrl);

/// [url] without `user:password@`.
static String withoutUserInfo(String url) {
final uri = Uri.tryParse(url);
if (uri == null || uri.userInfo.isEmpty) return url;
return uri.replace(userInfo: '').toString();
}

/// [url] with [userInfo] (`user:password`) put back, as stored apart
/// from it.
static String withUserInfo(String url, String? userInfo) {
final uri = Uri.tryParse(url);
if (uri == null || userInfo == null || userInfo.isEmpty) return url;
return uri.replace(userInfo: userInfo).toString();
}

/// True for plain HTTP to a server outside the home network: the API key
/// and everything watched would cross the internet unencrypted.
bool get isUnencryptedOverInternet {
Expand Down Expand Up @@ -136,7 +156,9 @@ class ServerConfig {
}

/// A saved Stash server (2.6). Its API key and password live in the
/// [SecretStore] (2.5), not in the stored JSON.
/// [SecretStore] (2.5), not in the stored JSON; so does user info in its
/// URL (`https://user:password@host`, a proxy's basic auth): the JSON keeps
/// the URL without it ([urlAuthSecret]).
@immutable
class ServerProfile {
const ServerProfile({
Expand Down Expand Up @@ -185,23 +207,45 @@ class ServerProfile {

static String apiKeySecret(String id) => 'api_key:$id';
static String passwordSecret(String id) => 'password:$id';
static String urlAuthSecret(String id) => 'url_auth:$id';

/// The user info of [baseUrl] (`user:password`), kept as a secret; null
/// without.
String? get urlAuth {
final info = Uri.tryParse(baseUrl)?.userInfo;
return info == null || info.isEmpty ? null : info;
}

/// Without the secrets.
Map<String, dynamic> toJson() => {'id': id, 'name': name, 'url': baseUrl, if (username != null) 'username': username};
Map<String, dynamic> toJson() => {
'id': id,
'name': name,
'url': ServerConfig.withoutUserInfo(baseUrl),
if (username != null) 'username': username,
};

/// Whether a stored entry still has secrets in its JSON (API key of
/// versions before 2.5, user info in the URL, stored by older versions),
/// which saving it again moves to the secret store.
static bool hasSecretsInJson(Map<String, dynamic> json) {
final url = json['url'];
return json.containsKey('apiKey') || (url is String && (Uri.tryParse(url)?.userInfo.isNotEmpty ?? false));
}

/// Null for an entry that can't be read. Versions before 2.5 stored the
/// API key in the JSON; it is moved to the secret store on load.
/// Null for an entry that can't be read. Secrets still in the JSON
/// ([hasSecretsInJson]) are used and moved to the secret store on load.
static ServerProfile? tryFromJson(Map<String, dynamic> json, SecretStore secrets) {
final id = json['id'];
final url = json['url'];
final name = json['name'];
final legacyKey = json['apiKey'];
final username = json['username'];
if (id is! String || id.isEmpty || url is! String || url.isEmpty) return null;
final storedAuth = Uri.tryParse(url)?.userInfo ?? '';
return ServerProfile(
id: id,
name: name is String && name.isNotEmpty ? name : defaultName(url),
baseUrl: url,
baseUrl: storedAuth.isNotEmpty ? url : ServerConfig.withUserInfo(url, secrets.read(urlAuthSecret(id))),
apiKey: secrets.read(apiKeySecret(id)) ?? (legacyKey is String ? legacyKey : null),
username: username is String ? username : null,
password: secrets.read(passwordSecret(id)),
Expand Down Expand Up @@ -244,8 +288,8 @@ class ServerProfilesNotifier extends Notifier<ServerProfiles> {
profiles: [for (final p in json) ?ServerProfile.tryFromJson(p, _secrets)],
activeId: prefs.getString(_activeKey),
);
// Move API keys of older versions out of the preferences.
if (json.any((p) => p.containsKey('apiKey'))) _persist(profiles);
// Move API keys and URL passwords of older versions out of the preferences.
if (json.any(ServerProfile.hasSecretsInJson)) _persist(profiles);
_moveLegacyLists(prefs, profiles.profiles.firstOrNull?.id);
return profiles;
}
Expand Down Expand Up @@ -311,6 +355,7 @@ class ServerProfilesNotifier extends Notifier<ServerProfiles> {
for (final p in value.profiles) {
await _secrets.write(ServerProfile.apiKeySecret(p.id), p.apiKey);
await _secrets.write(ServerProfile.passwordSecret(p.id), p.password);
await _secrets.write(ServerProfile.urlAuthSecret(p.id), p.urlAuth);
}
await prefs.setString(_profilesKey, jsonEncode([for (final p in value.profiles) p.toJson()]));
if (value.activeId == null) {
Expand Down
126 changes: 126 additions & 0 deletions lib/core/network/origin_guard.dart
Original file line number Diff line number Diff line change
@@ -0,0 +1,126 @@
import 'dart:convert';

import 'package:flutter/foundation.dart';
import 'package:http/http.dart' as http;

/// Headers that carry the server's credentials: never sent to another
/// origin (another scheme, host or port), e.g. a media URL the server
/// returned that points elsewhere, or a redirect away from the server.
const credentialHeaders = {'apikey', 'cookie', 'authorization', 'proxy-authorization'};

/// Whether [a] and [b] have the same scheme, host and port (the port
/// counts with its default, so `https://s` and `https://s:443` match).
bool sameOrigin(Uri a, Uri b) =>
a.scheme.toLowerCase() == b.scheme.toLowerCase() &&
a.host.toLowerCase() == b.host.toLowerCase() &&
a.port == b.port;

/// The URL mpv actually fetches for [url]: an EDL clip (`edl://%<len>%<url>,…`,
/// see `Short.playbackUrl`) wraps the stream's URL.
@visibleForTesting
Uri? fetchedUri(String url) {
final edl = RegExp(r'^edl://%(\d+)%').firstMatch(url);
if (edl == null) return Uri.tryParse(url);
final bytes = utf8.encode(url.substring(edl.end));
final length = int.parse(edl.group(1)!);
if (length > bytes.length) return null;
return Uri.tryParse(utf8.decode(bytes.sublist(0, length), allowMalformed: true));
}

/// The active server's credential headers (API key or session cookie),
/// bound to the server's origin: [forUrl] gives them only for URLs on the
/// server itself, so a scene, image or stream URL pointing elsewhere never
/// gets them.
@immutable
class AuthHeaders {
const AuthHeaders(this.origin, this.headers);

/// No server, or no credentials.
static const none = AuthHeaders(null, {});

final Uri? origin;
final Map<String, String> headers;

/// The headers to send with a request to [url]: all of them on the
/// server's origin, none elsewhere.
Map<String, String> forUrl(String url) {
final origin = this.origin;
if (headers.isEmpty || origin == null) return const {};
final uri = fetchedUri(url);
return uri != null && sameOrigin(uri, origin) ? headers : const {};
}

@override
bool operator ==(Object other) => other is AuthHeaders && other.origin == origin && mapEquals(other.headers, headers);

@override
int get hashCode => Object.hash(origin, Object.hashAllUnordered(headers.entries.map((e) => (e.key, e.value))));
}

/// Keeps credentials on their origin: drops the [credentialHeaders] of a
/// request that doesn't go to [origin] (when given), and follows redirects
/// itself, dropping them as soon as a redirect leaves the origin the request
/// started on. `dart:io` would forward a custom header such as `ApiKey` to
/// whatever host a redirect names.
class OriginGuardClient extends http.BaseClient {
OriginGuardClient(this._inner, {this.origin});

final http.Client _inner;

/// The only origin credentials may go to; null: the request's own.
final Uri? origin;

static const _redirects = {301, 302, 303, 307, 308};

@override
Future<http.StreamedResponse> send(http.BaseRequest request) async {
final allowed = origin ?? request.url;
if (!sameOrigin(request.url, allowed)) _strip(request.headers);
// Only plain requests can be sent again; others don't follow redirects.
if (request is! http.Request || !request.followRedirects) {
request.followRedirects = false;
return _inner.send(request);
}

var current = request;
for (var hops = 0;; hops++) {
final next = _copy(current)..followRedirects = false;
final response = await _inner.send(next);
final location = response.headers['location'];
if (!_redirects.contains(response.statusCode) || location == null) return response;
if (hops >= request.maxRedirects) {
await response.stream.drain<void>();
throw http.ClientException('Redirect limit exceeded', request.url);
}
await response.stream.drain<void>();
final target = current.url.resolve(location);
// 303, and 301/302 after a POST, continue as GET without a body, like browsers.
final keepMethod = response.statusCode == 307 ||
response.statusCode == 308 ||
(current.method == 'GET' || current.method == 'HEAD');
final redirected = http.Request(keepMethod ? current.method : 'GET', target)
..headers.addAll(current.headers)
..maxRedirects = request.maxRedirects
..persistentConnection = request.persistentConnection;
if (keepMethod) {
redirected.bodyBytes = current.bodyBytes;
} else {
redirected.headers.removeWhere((k, _) => k.toLowerCase() == 'content-type');
}
if (!sameOrigin(target, allowed)) _strip(redirected.headers);
current = redirected;
}
}

static void _strip(Map<String, String> headers) =>
headers.removeWhere((key, _) => credentialHeaders.contains(key.toLowerCase()));

static http.Request _copy(http.Request request) => http.Request(request.method, request.url)
..headers.addAll(request.headers)
..bodyBytes = request.bodyBytes
..maxRedirects = request.maxRedirects
..persistentConnection = request.persistentConnection;

@override
void close() => _inner.close();
}
Loading
Loading