diff --git a/README.md b/README.md index d2e815e2..9ddcaaac 100644 --- a/README.md +++ b/README.md @@ -42,7 +42,8 @@ - [ ] Soooo many... - API - [x] GeekPie SSO (Casdoor) login + token refresh - - [x] eGate binding / CpDaily keep-alive (via /api/auth/renew) + - [x] eGate support (local IDS Passkey authentication) + - [x] IDS Passkey binding / local campus session renewal - [ ] Schedule - [ ] Homework / Resources - [ ] GradeScope diff --git a/assets/help/ids_passkey.png b/assets/help/ids_passkey.png new file mode 100644 index 00000000..d98362b9 Binary files /dev/null and b/assets/help/ids_passkey.png differ diff --git a/ios/Runner/AppDelegate.swift b/ios/Runner/AppDelegate.swift index c68666c5..e671c53e 100644 --- a/ios/Runner/AppDelegate.swift +++ b/ios/Runner/AppDelegate.swift @@ -6,6 +6,7 @@ import WidgetKit @main @objc class AppDelegate: FlutterAppDelegate { private var ecardDeepLinkChannel: FlutterMethodChannel? + private var platformChannel: FlutterMethodChannel? private var pendingEcardRoute: String? private var ecardFeedback: EcardFeedback? private var ecardBindTunnel: EcardBindTunnelPlugin? @@ -62,6 +63,23 @@ import WidgetKit watchBridge = WatchConnectivityBridge(registrar: registrar) deadlineWidgetBridge.configure(messenger: registrar.messenger()) + let platformChannel = FlutterMethodChannel( + name: "techpie/platform", binaryMessenger: registrar.messenger() + ) + platformChannel.setMethodCallHandler { call, result in + guard call.method == "getUserAgentInfo" else { + result(FlutterMethodNotImplemented) + return + } + result([ + "device": UIDevice.current.model, + "system": UIDevice.current.systemName, + "systemVersion": UIDevice.current.systemVersion, + "scale": window.screen.scale, + ]) + } + self.platformChannel = platformChannel + let deepLinkChannel = FlutterMethodChannel( name: "techpie/ecard_deep_link", binaryMessenger: registrar.messenger() diff --git a/lib/main.dart b/lib/main.dart index af85bf5a..f87e697c 100644 --- a/lib/main.dart +++ b/lib/main.dart @@ -20,6 +20,7 @@ import 'services/ecard_bind_service.dart'; import 'services/ecard_widget_service.dart'; import 'services/egate_app_service.dart'; import 'services/http_client.dart'; +import 'services/ids/ids_client.dart'; import 'services/oa_gym_service.dart'; import 'services/schedule_service.dart'; import 'services/service_provider.dart'; @@ -42,6 +43,7 @@ void main(List args) async { WidgetsFlutterBinding.ensureInitialized(); await initializePlatformCapabilities(); + await initializeCampusUserAgent(); // OHOS white-screen probe disabled to speed up startup. Re-enable by // restoring the runApp(_BootProbe...) calls and wrapping init in try/catch. // runApp(const _BootProbe(message: '启动中…')); @@ -77,6 +79,7 @@ Future _realMain(SharedPreferences prefs) async { final thirdPartyAuthService = ThirdPartyAuthService( storageService, httpClient, + idsClient: IdsClient(logger: debugLogger), ); final scheduleService = ScheduleService( storageService, @@ -127,7 +130,7 @@ Future _realMain(SharedPreferences prefs) async { // state (throttled). Wired via post-construction setter to avoid a circular // dependency between ThirdPartyAuthService and SyncService. thirdPartyAuthService.onBindingsChanged = ({force = false}) { - // The timetable is drawn from the eGate binding, and `fetchAll` does nothing + // The timetable is drawn from the IDS binding, and `fetchAll` does nothing // at all while there is none — silently, which is how a freshly bound account // used to sit on an empty table with nothing to suggest it should reload. This // runs for every binding, though, and a timetable does not care about @@ -247,7 +250,7 @@ Future _realMain(SharedPreferences prefs) async { ); } - if (thirdPartyAuthService.hasCpdailyBinding) { + if (thirdPartyAuthService.hasIdsBinding) { // Through the funnel: the token renewals just above fire the same trigger, // and this used to be a second round on top of theirs. scheduleService.requestFetch(force: true); diff --git a/lib/models/ids_passkey.dart b/lib/models/ids_passkey.dart new file mode 100644 index 00000000..d5df4a13 --- /dev/null +++ b/lib/models/ids_passkey.dart @@ -0,0 +1,102 @@ +import 'third_party_account.dart'; + +/// Exportable software credential. Only secure storage and encrypted Cloud Sync +/// may persist this object; never include it in API payloads or debug logs. +class IdsPasskey { + static const rpId = 'ids.shanghaitech.edu.cn'; + final String credentialId; + final String privateKey; + final String userHandle; + final String anonBiometricsId; + final String username; + + const IdsPasskey({ + required this.credentialId, + required this.privateKey, + required this.userHandle, + required this.anonBiometricsId, + required this.username, + }); + + Map toJson() => { + 'credentialId': credentialId, + 'privateKey': privateKey, + 'userHandle': userHandle, + 'anonBiometricsId': anonBiometricsId, + 'username': username, + 'rpId': rpId, + 'alg': -7, + }; + + factory IdsPasskey.fromJson(Map json) { + if (json['rpId'] != rpId || json['alg'] != -7) { + throw const FormatException('Unsupported IDS credential'); + } + return IdsPasskey( + credentialId: json['credentialId'] as String, + privateKey: json['privateKey'] as String, + userHandle: json['userHandle'] as String, + anonBiometricsId: json['anonBiometricsId'] as String, + username: json['username'] as String, + ); + } +} + +/// A null credential is an explicit unbind; no binding means no sync opinion. +/// Session renewals never change this version or participate in its merge. +class IdsSyncBinding { + final IdsPasskey? credential; + final DateTime updatedAt; + final String deviceId; + + const IdsSyncBinding({required this.credential, required this.updatedAt, required this.deviceId}); + + ThirdPartyAccount toAccount() { + final key = credential!; + return ThirdPartyAccount( + platform: ThirdPartyPlatform.ids, + account: key.username, + sid: key.username, + token: '', + raw: { + 'authMethod': 'passkey', + 'idsCredentialId': key.credentialId, + 'credential': key.toJson(), + }, + boundAt: updatedAt.toUtc(), + updatedAt: updatedAt.toUtc(), + deviceId: deviceId, + ); + } + + Map toJson() => credential == null + ? { + 'platform': ThirdPartyPlatform.ids.id, + 'deletedAt': updatedAt.toUtc().toIso8601String(), + 'deviceId': deviceId, + } + : toAccount().toJson(); + + static IdsSyncBinding? fromAccount(ThirdPartyAccount? account) { + if (account?.platform != ThirdPartyPlatform.ids || + account!.raw['authMethod'] != 'passkey' || + account.raw['credential'] is! Map) { + return null; + } + return IdsSyncBinding( + credential: IdsPasskey.fromJson((account.raw['credential'] as Map).cast()), + updatedAt: account.updatedAt, + deviceId: account.deviceId, + ); + } + + IdsSyncBinding merge(IdsSyncBinding? other) { + if (other == null) return this; + final time = updatedAt.compareTo(other.updatedAt); + if (time != 0) return time > 0 ? this : other; + final device = deviceId.compareTo(other.deviceId); + if (device != 0) return device > 0 ? this : other; + if (credential == null || other.credential == null) return credential == null ? this : other; + return credential!.credentialId.compareTo(other.credential!.credentialId) >= 0 ? this : other; + } +} diff --git a/lib/models/renew_status.dart b/lib/models/renew_status.dart index 92340c63..d2d82aa0 100644 --- a/lib/models/renew_status.dart +++ b/lib/models/renew_status.dart @@ -1,5 +1,5 @@ /// Outcome of the most recent renewal attempt for a session node (top-level -/// bindings cpdaily/gradescope/hydro, or derived children eams/elearning). +/// bindings ids/gradescope/hydro, or derived children eams/elearning). /// Local-only — never part of the cloud-sync envelope (renewal history is /// device-specific and irrelevant to restoring bindings on another device). class RenewStatus { diff --git a/lib/models/third_party_account.dart b/lib/models/third_party_account.dart index f72ac440..38b31648 100644 --- a/lib/models/third_party_account.dart +++ b/lib/models/third_party_account.dart @@ -1,31 +1,22 @@ enum ThirdPartyPlatform { gradescope, hydro, - cpdaily; + ids; - /// Stable id used for storage keys and cloud-sync payloads. Note: the - /// backend bind route for cpdaily is still 'egate' (unrenamed); see - /// [apiPath]. + /// Stable id used for storage keys and cloud-sync payloads. String get id => name; String get label => switch (this) { ThirdPartyPlatform.gradescope => 'Gradescope', ThirdPartyPlatform.hydro => 'Hydro', - ThirdPartyPlatform.cpdaily => 'CpDaily / IDS', + ThirdPartyPlatform.ids => 'IDS', }; - /// Backend bind/renew route name. cpdaily maps to 'egate' (the backend - /// route was not renamed); all others map to their own [id]. - String get apiPath => switch (this) { - ThirdPartyPlatform.cpdaily => 'egate', - _ => id, - }; - - /// Parse a platform id, accepting the legacy 'egate' alias for cpdaily. + /// Published campus-account ids remain readable for the Passkey upgrade. static ThirdPartyPlatform? fromId(String id) { return switch (id) { 'gradescope' => ThirdPartyPlatform.gradescope, 'hydro' => ThirdPartyPlatform.hydro, - 'cpdaily' || 'egate' => ThirdPartyPlatform.cpdaily, + 'ids' || 'cpdaily' || 'egate' => ThirdPartyPlatform.ids, _ => null, }; } @@ -93,18 +84,18 @@ class ThirdPartyAccount { return account; } - /// School identity is distinct from CpDaily's internal user UUID. Older - /// backends put that UUID in sid and omitted it from raw.userId. - String get cpdailyStudentId { - if (platform != ThirdPartyPlatform.cpdaily) return ''; + /// Old upgrade records can contain an opaque UUID in sid. Only expose a + /// school ID, never that UUID or a phone number. + String get idsStudentId { + if (platform != ThirdPartyPlatform.ids) return ''; for (final value in [raw['studentId'], raw['openId'], account, sid]) { - final id = cpdailySchoolId(value); + final id = idsSchoolId(value); if (id.isNotEmpty) return id; } return ''; } - static String cpdailySchoolId(Object? value) { + static String idsSchoolId(Object? value) { if (value is! String) return ''; final id = value.trim(); return RegExp(r'^\d+$').hasMatch(id) && @@ -113,17 +104,6 @@ class ThirdPartyAccount { : ''; } - String get cpdailyUserId { - if (platform != ThirdPartyPlatform.cpdaily) return ''; - final value = raw['userId']; - if (value is String && value.isNotEmpty) return value; - final legacy = sid ?? ''; - return RegExp(r'^[a-fA-F0-9]{8}(?:-[a-fA-F0-9]{4}){3}-[a-fA-F0-9]{12}$') - .hasMatch(legacy) - ? legacy - : ''; - } - /// Comparison key for LWW merge: newer [updatedAt] wins; on a tie the /// lexicographically-larger [deviceId] wins (deterministic, total order). /// An empty deviceId is treated as oldest of all so legacy data loses to diff --git a/lib/pages/campus_card_page.dart b/lib/pages/campus_card_page.dart index 16a09183..e912d60f 100644 --- a/lib/pages/campus_card_page.dart +++ b/lib/pages/campus_card_page.dart @@ -15,7 +15,7 @@ import 'campus_card_account_page.dart'; /// Presents the campus-card routes inside TechPie's theme and navigation. /// /// The OpenID/JSESSIONID account remains independent from TechPie's primary -/// SSO and CpDaily sessions, while the feature runtime is owned by TechPie. +/// SSO and IDS sessions, while the feature runtime is owned by TechPie. class CampusCardPage extends StatelessWidget { const CampusCardPage({ super.key, diff --git a/lib/pages/campus_session_handle.dart b/lib/pages/campus_session_handle.dart index 0b19986b..f46d83af 100644 --- a/lib/pages/campus_session_handle.dart +++ b/lib/pages/campus_session_handle.dart @@ -23,7 +23,7 @@ class CampusSessionHandle { final ThirdPartyAuthService tpAuth; /// The node this page reads cookies from. Each feature uses a different - /// derived session: ecourse runs on the CpDaily/CASTGC session directly, eams + /// derived session: ecourse runs on the IDS/CASTGC session directly, eams /// and the egate apps on their own downstream cookies. final SessionNode node; @@ -59,7 +59,7 @@ class CampusSessionHandle { /// The session node an app feature authenticates against. SessionNode _nodeFor(ThirdPartyAuthService tpAuth, CookieType cookieType) => switch (cookieType) { - CookieType.ecourse => tpAuth.cpdailyNode, + CookieType.ecourse => tpAuth.idsNode, CookieType.eams => tpAuth.eamsNode, CookieType.egateApp => tpAuth.egateAppNode, }; diff --git a/lib/pages/egate_app_page.dart b/lib/pages/egate_app_page.dart index 14073b1d..11f6351b 100644 --- a/lib/pages/egate_app_page.dart +++ b/lib/pages/egate_app_page.dart @@ -15,7 +15,7 @@ import 'third_party_accounts_page.dart'; /// "校园签到" — queries the egate-app (xshdapp) sign-in announcement + /// history and lets the user submit a check-in for a scanned WID. Session -/// cookies are derived from the cpdaily binding (see EgateAppService), so +/// cookies are derived from the ids binding (see EgateAppService), so /// this page mirrors OaGymPage's ready/unready gating. class EgateAppPage extends StatefulWidget { const EgateAppPage({super.key}); @@ -176,7 +176,7 @@ class _EgateAppPageState extends State { listenable: Listenable.merge([auth, tpAuth]), builder: (context, _) => PageRefreshButton( onRefresh: () => _refresh(service), - enabled: auth.isLoggedIn && tpAuth.hasCpdailyBinding, + enabled: auth.isLoggedIn && tpAuth.hasIdsBinding, refreshing: _loading, ), ), @@ -185,7 +185,7 @@ class _EgateAppPageState extends State { body: ListenableBuilder( listenable: Listenable.merge([auth, tpAuth]), builder: (context, _) { - final ready = auth.isLoggedIn && tpAuth.hasCpdailyBinding; + final ready = auth.isLoggedIn && tpAuth.hasIdsBinding; if (!ready) { return ListView( padding: EdgeInsets.fromLTRB(16, topInset + 16, 16, 120), @@ -203,21 +203,21 @@ class _EgateAppPageState extends State { ), const SizedBox(height: 16), Text( - auth.isLoggedIn ? '需要绑定 eGate 账号' : '需要先登录 TechPie', + auth.isLoggedIn ? '需要绑定 IDS 账号' : '需要先登录 TechPie', style: Theme.of(context).textTheme.titleLarge, ), const SizedBox(height: 8), Text( auth.isLoggedIn - ? '校园签到复用 eGate 绑定的校园网登录态,请在「第三方账号」中绑定 eGate 后再使用。' - : '校园签到复用 eGate 绑定的校园网登录态,不需要单独保存密码。', + ? '校园签到复用 IDS 绑定的校园网登录态,请在「第三方账号」中绑定 IDS 后再使用。' + : '校园签到复用 IDS 绑定的校园网登录态,不需要单独保存密码。', style: Theme.of(context).textTheme.bodyMedium, ), const SizedBox(height: 16), FilledButton.icon( onPressed: _handleLogin, icon: const Icon(Icons.login), - label: Text(auth.isLoggedIn ? '去绑定 eGate' : '去登录'), + label: Text(auth.isLoggedIn ? '去绑定 IDS' : '去登录'), ), ], ), diff --git a/lib/pages/elrc_recordings_page.dart b/lib/pages/elrc_recordings_page.dart index 6c5d3c48..951a7119 100644 --- a/lib/pages/elrc_recordings_page.dart +++ b/lib/pages/elrc_recordings_page.dart @@ -117,13 +117,13 @@ class _ElrcRecordingsPageState extends State { if (_supported) unawaited(_prepare()); } - /// Brings the shared store and the CpDaily session up to date, then writes the + /// Brings the shared store and the IDS session up to date, then writes the /// session's cookies into the store the given controller will use: the hidden /// webview below writes nothing itself, so it cannot answer a 401 either. /// Best effort — both callers fall back to the SSO redirect. Future _writeCampusSession(WebViewController controller) async { try { - final session = CampusSessionHandle(_tpAuth!, _tpAuth!.cpdailyNode); + final session = CampusSessionHandle(_tpAuth!, _tpAuth!.idsNode); await session.prepare(); await _tpAuth!.campusWebSession.clearLocalStorageIfDue(controller); final cookieManager = WebViewCookieManager(); @@ -170,7 +170,7 @@ class _ElrcRecordingsPageState extends State { } if (_isLogin(uri) && !_campusAttempted && - _tpAuth!.hasCpdailyBinding) { + _tpAuth!.hasIdsBinding) { _expectedMainFrameCancellations++; unawaited(_openLogin()); return NavigationDecision.prevent; diff --git a/lib/pages/ids_bind_page.dart b/lib/pages/ids_bind_page.dart new file mode 100644 index 00000000..61089198 --- /dev/null +++ b/lib/pages/ids_bind_page.dart @@ -0,0 +1,478 @@ +import 'dart:async'; +import 'dart:typed_data'; + +import 'package:flutter/material.dart'; +import 'package:url_launcher/url_launcher.dart'; + +import '../models/third_party_account.dart'; +import '../services/ids/ids_client.dart' show IdsCaptchaRefresh, IdsVerificationAnswer; +import '../services/service_provider.dart'; +import '../utils/platform.dart'; +import '../widgets/adaptive_page_navigation.dart'; +import '../widgets/adaptive_text_field_group.dart'; +import '../widgets/blurred_app_bar.dart'; +import '../widgets/ios/ios_native_navigation_bar.dart'; +import '../widgets/secure_password_field.dart'; + +final idsAccountSecurityUrl = Uri.parse( + 'https://ids.shanghaitech.edu.cn/personalInfo/personCenter/index.html#/accountsecurity', +); +const idsPasskeyNotice = + '您可以在 IDS 账号安全页面查看已创建的 Passkey,并随时解绑。解绑后,需要在 TechPie 重新绑定,才能继续使用 IDS 相关功能。'; + +class IdsBindPage extends StatelessWidget { + const IdsBindPage({super.key, this.legacyAccount}); + final ThirdPartyAccount? legacyAccount; + @override + Widget build(BuildContext context) => Scaffold( + appBar: isIos() + ? IosNativeNavigationBar( + title: '绑定 IDS Passkey', + leadingItems: [ + if (Navigator.canPop(context)) + const IosNativeNavigationBarItem( + id: 'back', + title: '返回', + sfSymbol: 'chevron.left', + ), + ], + onItemPressed: (_) => unawaited(maybePopAdaptivePage(context)), + ) + : const BlurredAppBar(title: Text('绑定 IDS Passkey')), + body: SafeArea( + child: SingleChildScrollView( + padding: const EdgeInsets.all(20), + child: IdsBindForm(legacyAccount: legacyAccount), + ), + ), + ); +} + +class IdsBindForm extends StatefulWidget { + const IdsBindForm({super.key, this.legacyAccount}); + final ThirdPartyAccount? legacyAccount; + @override + State createState() => _IdsBindFormState(); +} + +class _IdsBindFormState extends State { + final _account = TextEditingController(); + final _password = TextEditingController(); + bool _busy = false; + String? _error; + bool _manual = false; + + bool get _canUpgrade { + final account = widget.legacyAccount; + return !_manual && + account?.platform == ThirdPartyPlatform.ids && + account!.raw['authMethod'] != 'passkey' && + account.account.trim().isNotEmpty && + (account.password?.isNotEmpty ?? false); + } + + @override + void dispose() { + _account.dispose(); + _password.dispose(); + super.dispose(); + } + + Future _bind({String? account, String? password, bool upgrading = false}) async { + if (_busy) return; + final loginAccount = (account ?? _account.text).trim(); + final loginPassword = password ?? _password.text; + if (loginAccount.isEmpty || loginPassword.isEmpty) { + setState(() => _error = '请填写 IDS 账号和密码'); + return; + } + FocusScope.of(context).unfocus(); + setState(() { + _busy = true; + _error = null; + }); + final prompts = IdsDialogSession(context); + try { + await ServiceProvider.of(context).thirdPartyAuthService.bindIds( + account: loginAccount, + password: loginPassword, + isCancelled: () => !mounted, + promptCaptcha: (image, error, {required refresh}) async { + if (!mounted) return null; + return prompts.captcha(image, error, refresh: refresh); + }, + ); + if (!mounted) return; + _password.clear(); + await prompts.close(); + if (!mounted) return; + await maybePopAdaptivePage(context); + } catch (error) { + if (mounted) { + setState(() { + if (upgrading) { + _manual = true; + _account.text = loginAccount; + _password.clear(); + } + _error = error.toString(); + }); + } + } finally { + await prompts.close(); + prompts.dispose(); + if (mounted) setState(() => _busy = false); + } + } + + @override + Widget build(BuildContext context) => Column( + crossAxisAlignment: CrossAxisAlignment.stretch, + children: [ + Text( + _canUpgrade + ? '检测到已保存的旧版校园账号,是否升级为 Passkey?确认后将由本机使用已保存的账号和密码登录学校 IDS。' + : '首次绑定需要登录学校 IDS,并为 TechPie 创建一个 Passkey。之后由 TechPie 自动使用它登录。', + ), + const SizedBox(height: 20), + if (_canUpgrade) ...[ + FilledButton( + onPressed: _busy + ? null + : () => unawaited( + _bind( + account: widget.legacyAccount!.account, + password: widget.legacyAccount!.password, + upgrading: true, + ), + ), + child: Text(_busy ? '正在升级…' : '确认升级为 Passkey'), + ), + TextButton( + onPressed: _busy + ? null + : () => setState(() { + _manual = true; + _account.text = widget.legacyAccount!.account; + }), + child: const Text('手动绑定'), + ), + ] else + AdaptiveTextFieldGroup( + items: [ + AdaptiveTextFieldGroupItem( + controller: _account, + placeholder: 'IDS 账号(学号或手机号)', + enabled: !_busy, + ), + AdaptiveTextFieldGroupItem( + controller: _password, + placeholder: 'IDS 密码', + obscureText: true, + enabled: !_busy, + textInputAction: TextInputAction.done, + onSubmitted: (_) => unawaited(_bind()), + ), + ], + ), + if (_error != null) + Padding( + padding: const EdgeInsets.only(top: 12), + child: Text(_error!, style: TextStyle(color: Theme.of(context).colorScheme.error)), + ), + const SizedBox(height: 20), + if (!_canUpgrade) + FilledButton( + onPressed: _busy ? null : () => unawaited(_bind()), + child: _busy + ? const SizedBox( + width: 20, + height: 20, + child: CircularProgressIndicator(strokeWidth: 2), + ) + : const Text('创建并绑定 Passkey'), + ), + const SizedBox(height: 16), + Text( + '账号、密码和验证码由本机直接提交给学校。密码不会保存;Passkey 保存在本机安全存储中,开启 Cloud Sync 后会端到端加密同步。', + style: Theme.of(context).textTheme.bodySmall, + ), + const SizedBox(height: 20), + const IdsPasskeyHelp(), + ], + ); +} + +/// One modal stays mounted while IDS validates answers and returns retries. +class IdsDialogSession extends ChangeNotifier { + IdsDialogSession(BuildContext context, {this.withPassword = false}) + : _context = Navigator.of(context, rootNavigator: true).context; + final BuildContext _context; + final bool withPassword; + Completer? _pending; + Future? _dialog; + BuildContext? _dialogContext; + Uint8List? _image; + String? _error; + IdsCaptchaRefresh? _refresh; + bool _busy = false; + bool _closed = false; + + Future captcha( + Uint8List image, + String? error, { + required IdsCaptchaRefresh refresh, + }) async => + (await verification(image, error, refresh: refresh))?.captcha; + + Future verification( + Uint8List image, + String? error, { + required IdsCaptchaRefresh refresh, + }) { + if (_closed || !_context.mounted) return Future.value(null); + final answer = Completer(); + _pending = answer; + _image = image; + _error = error; + _refresh = refresh; + _busy = false; + notifyListeners(); + _dialog ??= showDialog( + context: _context, + barrierDismissible: false, + builder: (context) { + _dialogContext = context; + return ListenableBuilder( + listenable: this, + builder: (context, _) => PopScope( + canPop: !_busy, + child: _IdsVerificationDialog( + withPassword: withPassword, + image: _image!, + error: _error, + busy: _busy, + onAnswer: _submit, + onRefresh: _reloadCaptcha, + ), + ), + ); + }, + ).whenComplete(() { + _closed = true; + _pending?.complete(null); + _pending = null; + }); + return answer.future; + } + + Future _reloadCaptcha() async { + if (_busy || _closed || _refresh == null) return; + _busy = true; + notifyListeners(); + try { + final image = await _refresh!(); + if (_closed) return; + _image = image; + _error = null; + } catch (error) { + if (_closed) return; + _error = '获取验证码失败,请点击图片重试'; + } + if (_closed) return; + _busy = false; + notifyListeners(); + } + + void _submit(IdsVerificationAnswer answer) { + final pending = _pending; + if (pending == null || _busy || _closed) return; + _pending = null; + _busy = true; + _error = null; + notifyListeners(); + pending.complete(answer); + } + + Future close() async { + _closed = true; + _pending?.complete(null); + _pending = null; + final context = _dialogContext; + if (context != null && context.mounted && ModalRoute.of(context)?.isCurrent == true) { + Navigator.of(context).pop(); + } + await _dialog; + } +} + +class _IdsVerificationDialog extends StatefulWidget { + const _IdsVerificationDialog({ + required this.withPassword, + required this.image, + this.error, + required this.busy, + required this.onAnswer, + required this.onRefresh, + }); + final bool withPassword; + final Uint8List image; + final String? error; + final bool busy; + final ValueChanged onAnswer; + final VoidCallback onRefresh; + @override + State<_IdsVerificationDialog> createState() => _IdsVerificationDialogState(); +} + +class _IdsVerificationDialogState extends State<_IdsVerificationDialog> { + final _password = TextEditingController(); + final _captcha = TextEditingController(); + @override + void dispose() { + _password.dispose(); + _captcha.dispose(); + super.dispose(); + } + + @override + void didUpdateWidget(covariant _IdsVerificationDialog oldWidget) { + super.didUpdateWidget(oldWidget); + if (widget.image != oldWidget.image) _captcha.clear(); + } + + void _submit() { + if (widget.busy || + _captcha.text.trim().isEmpty || + (widget.withPassword && _password.text.isEmpty)) { + return; + } + widget.onAnswer((password: _password.text, captcha: _captcha.text.trim())); + } + + @override + Widget build(BuildContext context) => AlertDialog( + title: Text(widget.withPassword ? 'IDS 解绑验证' : '输入验证码'), + scrollable: true, + content: SizedBox( + width: 400, + child: Column( + mainAxisSize: MainAxisSize.min, + children: [ + if (widget.withPassword) ...[ + const Text('本地绑定已删除。完成验证可同时在 IDS 解绑此 Passkey;取消或验证失败不影响本地删除。'), + const SizedBox(height: 12), + ], + if (widget.error != null) ...[ + Text(widget.error!, style: TextStyle(color: Theme.of(context).colorScheme.error)), + const SizedBox(height: 12), + ], + if (widget.withPassword) ...[ + SecurePasswordField( + controller: _password, + placeholder: 'IDS 密码', + enabled: !widget.busy, + decoration: const InputDecoration(labelText: 'IDS 密码'), + textInputAction: TextInputAction.next, + ), + const SizedBox(height: 12), + ], + _IdsCaptchaInput( + image: widget.image, + controller: _captcha, + autofocus: !widget.withPassword, + onSubmitted: _submit, + enabled: !widget.busy, + onRefresh: widget.onRefresh, + ), + if (widget.busy) + const Padding(padding: EdgeInsets.only(top: 12), child: LinearProgressIndicator()), + ], + ), + ), + actions: [ + TextButton( + onPressed: widget.busy ? null : () => Navigator.pop(context), + child: Text(widget.withPassword ? '仅删除本地' : '取消'), + ), + FilledButton( + onPressed: widget.busy ? null : _submit, + child: Text(widget.busy + ? '正在验证…' + : widget.withPassword + ? '验证并解绑 IDS' + : '继续',), + ), + ], + ); +} + +class IdsPasskeyHelp extends StatelessWidget { + const IdsPasskeyHelp({super.key}); + @override + Widget build(BuildContext context) => Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + const Text(idsPasskeyNotice), + const SizedBox(height: 12), + AspectRatio( + aspectRatio: 2414 / 856, + child: Image.asset( + 'assets/help/ids_passkey.png', + semanticLabel: 'IDS 账号安全页面中 Techpie Passkey 的查看和解绑位置', + fit: BoxFit.contain, + ), + ), + TextButton.icon( + onPressed: () => + unawaited(launchUrl(idsAccountSecurityUrl, mode: LaunchMode.externalApplication)), + icon: const Icon(Icons.open_in_new, size: 18), + label: const Text('打开 IDS 账号安全页面'), + ), + ], + ); +} + +class _IdsCaptchaInput extends StatelessWidget { + const _IdsCaptchaInput({ + required this.image, + required this.controller, + required this.onSubmitted, + this.autofocus = false, + this.enabled = true, + this.onRefresh, + }); + final Uint8List image; + final TextEditingController controller; + final VoidCallback onSubmitted; + final bool autofocus; + final bool enabled; + final VoidCallback? onRefresh; + + @override + Widget build(BuildContext context) => Row( + children: [ + Expanded( + child: TextField( + controller: controller, + autofocus: autofocus, + enabled: enabled, + autocorrect: false, + enableSuggestions: false, + autofillHints: null, + textInputAction: TextInputAction.done, + decoration: const InputDecoration(labelText: '验证码'), + onSubmitted: (_) => onSubmitted(), + ), + ), + const SizedBox(width: 12), + Tooltip( + message: '更换验证码', + child: InkWell( + onTap: enabled ? onRefresh : null, + child: Image.memory(image, width: 112, height: 56, fit: BoxFit.contain), + ), + ), + ], + ); +} diff --git a/lib/pages/oa_gym_page.dart b/lib/pages/oa_gym_page.dart index 2dad1c1e..45aeb270 100644 --- a/lib/pages/oa_gym_page.dart +++ b/lib/pages/oa_gym_page.dart @@ -102,7 +102,7 @@ class _OaGymPageState extends State body: ListenableBuilder( listenable: Listenable.merge([auth, tpAuth]), builder: (context, _) { - final ready = auth.isLoggedIn && tpAuth.hasCpdailyBinding; + final ready = auth.isLoggedIn && tpAuth.hasIdsBinding; return ready ? Column( children: [ @@ -168,15 +168,15 @@ class _OaGymPageState extends State const SizedBox(height: 16), Text( auth.isLoggedIn - ? '需要绑定 eGate 账号' + ? '需要绑定 IDS 账号' : '需要先登录 TechPie', style: Theme.of(context).textTheme.titleLarge, ), const SizedBox(height: 8), Text( auth.isLoggedIn - ? '场馆预约复用 eGate 绑定的校园网登录态,请在「第三方账号」中绑定 eGate 后再使用。' - : '场馆预约复用 eGate 绑定的校园网登录态,不需要单独保存 OA 密码。', + ? '场馆预约复用 IDS 绑定的校园网登录态,请在「第三方账号」中绑定 IDS 后再使用。' + : '场馆预约复用 IDS 绑定的校园网登录态,不需要单独保存 OA 密码。', style: Theme.of(context).textTheme.bodyMedium, ), const SizedBox(height: 16), @@ -188,10 +188,10 @@ class _OaGymPageState extends State sfSymbol: auth.isLoggedIn ? 'key.horizontal' : 'person.crop.circle.badge.plus', - label: auth.isLoggedIn ? '去绑定 eGate' : '去登录', + label: auth.isLoggedIn ? '去绑定 IDS' : '去登录', role: AdaptiveButtonRole.prominent, accessibilityLabel: - auth.isLoggedIn ? '前往绑定 eGate' : '登录 TechPie', + auth.isLoggedIn ? '前往绑定 IDS' : '登录 TechPie', ), ], ), @@ -1166,17 +1166,17 @@ class _ProfileTabState extends State<_ProfileTab> { final sp = ServiceProvider.of(context); final tpAuth = sp.thirdPartyAuthService; final service = sp.oaGymService; - final cpdaily = tpAuth.cpdailyBinding; + final ids = tpAuth.idsAccount; - // Identity card prefers cpdaily binding (real name + student id) over the + // Identity card prefers ids binding (real name + student id) over the // primary SSO account, whose userName/userId are Casdoor UUIDs with no // meaning in the OA booking context. final displayName = service.bookingProfile().name.isNotEmpty ? service.bookingProfile().name - : cpdaily?.name?.isNotEmpty == true - ? cpdaily!.name! - : (cpdaily?.account.isNotEmpty == true - ? cpdaily!.account + : ids?.name?.isNotEmpty == true + ? ids!.name! + : (ids?.account.isNotEmpty == true + ? ids!.account : 'TechPie 用户'); final studentId = service.bookingStudentId; final avatarText = displayName.characters.firstOrNull ?? 'U'; @@ -1222,7 +1222,7 @@ class _ProfileTabState extends State<_ProfileTab> { Text('预约提交信息', style: Theme.of(context).textTheme.titleMedium), const SizedBox(height: 8), Text( - '绑定 eGate 后自动从 OA 同步,用于场馆预约。姓名和手机号必填,邮箱可选,也可手动修改。', + '绑定 IDS 后自动从 OA 同步,用于场馆预约。姓名和手机号必填,邮箱可选,也可手动修改。', style: Theme.of(context).textTheme.bodySmall, ), const SizedBox(height: 12), diff --git a/lib/pages/schedule_page.dart b/lib/pages/schedule_page.dart index da3e89af..913df062 100644 --- a/lib/pages/schedule_page.dart +++ b/lib/pages/schedule_page.dart @@ -692,7 +692,7 @@ class _SchedulePageState extends State { if (isDesktop()) PageRefreshButton( onRefresh: _refresh, - enabled: auth.isLoggedIn && tpAuth.hasCpdailyBinding, + enabled: auth.isLoggedIn && tpAuth.hasIdsBinding, refreshing: _schedule.loading || _assignments.loading, ), IconButton( @@ -764,7 +764,7 @@ class _SchedulePageState extends State { ? 0 : adaptiveTopBarHeight() + MediaQuery.viewPaddingOf(context).top, ), - child: !auth.isLoggedIn || !tpAuth.hasCpdailyBinding + child: !auth.isLoggedIn || !tpAuth.hasIdsBinding ? Center( child: Column( mainAxisSize: MainAxisSize.min, @@ -776,14 +776,14 @@ class _SchedulePageState extends State { ), const SizedBox(height: 16), Text( - auth.isLoggedIn ? '绑定 eGate 以查看课表' : '登录以查看课表', + auth.isLoggedIn ? '绑定 IDS 以查看课表' : '登录以查看课表', style: theme.textTheme.bodyLarge?.copyWith( color: theme.colorScheme.onSurfaceVariant, ), ), const SizedBox(height: 20), AdaptiveButton( - label: auth.isLoggedIn ? '去绑定 eGate' : '登录', + label: auth.isLoggedIn ? '去绑定 IDS' : '登录', icon: auth.isLoggedIn ? Icons.account_tree_outlined : Icons.login, sfSymbol: auth.isLoggedIn ? 'person.crop.circle.badge.plus' @@ -802,7 +802,7 @@ class _SchedulePageState extends State { unawaited(startUniAuthLogin(context)); } }, - accessibilityLabel: auth.isLoggedIn ? '绑定 eGate 账号' : '登录 TechPie', + accessibilityLabel: auth.isLoggedIn ? '绑定 IDS 账号' : '登录 TechPie', ), ], ), diff --git a/lib/pages/settings_page.dart b/lib/pages/settings_page.dart index 18a42df3..dabca46e 100644 --- a/lib/pages/settings_page.dart +++ b/lib/pages/settings_page.dart @@ -8,6 +8,7 @@ import 'package:package_info_plus/package_info_plus.dart'; import 'package:techpie/services/auth_service.dart'; import 'package:url_launcher/url_launcher.dart'; +import '../models/third_party_account.dart'; import '../services/api_base_url.dart'; import '../services/feedback_service.dart'; import '../services/service_provider.dart'; @@ -27,6 +28,7 @@ import '../widgets/adaptive_switch.dart'; import '../widgets/app_shell/app_shell_metrics.dart'; import '../widgets/blurred_app_bar.dart'; import '../widgets/desktop_popup.dart'; +import '../widgets/ids_rebind_banner.dart'; import '../widgets/ios/ios_native_navigation_bar.dart'; import '../widgets/uni_auth_login.dart'; import '../widgets/update_dialogs.dart'; @@ -37,6 +39,7 @@ import 'developer_lab_page.dart'; import 'feedback_page.dart'; import 'sync_settings_page.dart'; import 'third_party_accounts_page.dart'; +import 'third_party_bind_page.dart'; import 'watch_settings_page.dart'; class SettingsPage extends StatefulWidget { @@ -207,6 +210,10 @@ class _SettingsPageState extends State { bottom: AppShellMetrics.bottomContentPaddingOf(context), ), children: [ + if (tpAuth.needsIdsRebind || storage.debugForceIdsRebindBanner) + IdsRebindBanner(onRebind: () => unawaited(pushAdaptivePage( + context, builder: (_) => const ThirdPartyBindPage(platform: ThirdPartyPlatform.ids), + ),),), // Account section _sectionHeader(theme, 'Account'), if (session != null) ...[ @@ -429,6 +436,7 @@ class _SettingsPageState extends State { // General section _sectionHeader(theme, 'General'), _AdaptiveSwitchTile( + key: const ValueKey('settings.mask-personal-info'), usesIosLiquidGlass: useIosChrome, secondary: const Icon(Icons.visibility_off_outlined), title: 'Mask personal info', @@ -468,6 +476,20 @@ class _SettingsPageState extends State { if (!kReleaseMode) _sectionHeader(theme, 'Developer'), if (!kReleaseMode) _AdaptiveSwitchTile( + key: const ValueKey('settings.ids-rebind-preview'), + usesIosLiquidGlass: useIosChrome, + secondary: const Icon(Icons.key_outlined), + title: '强制显示 IDS 重绑横幅', + subtitle: '仅用于调试迁移提示', + value: storage.debugForceIdsRebindBanner, + onChanged: (value) { + unawaited(storage.setDebugForceIdsRebindBanner(value)); + setState(() {}); + }, + ), + if (!kReleaseMode) + _AdaptiveSwitchTile( + key: const ValueKey('settings.debug-mode'), usesIosLiquidGlass: useIosChrome, secondary: const Icon(Icons.bug_report_outlined), title: 'Debug mode', @@ -480,6 +502,7 @@ class _SettingsPageState extends State { ), if (!kReleaseMode) _AdaptiveSwitchTile( + key: const ValueKey('settings.use-localhost'), usesIosLiquidGlass: useIosChrome, secondary: const Icon(Icons.dns_outlined), title: 'Use localhost', @@ -810,6 +833,7 @@ class _ThemeModeOptions extends StatelessWidget { class _AdaptiveSwitchTile extends StatelessWidget { const _AdaptiveSwitchTile({ + super.key, required this.usesIosLiquidGlass, required this.secondary, required this.title, diff --git a/lib/pages/sync_settings_page.dart b/lib/pages/sync_settings_page.dart index fab7f4d8..feb38b34 100644 --- a/lib/pages/sync_settings_page.dart +++ b/lib/pages/sync_settings_page.dart @@ -477,7 +477,7 @@ class _SyncSettingsPageState extends State { } const String _e2eExplanation = - '启用后,你的 eGate 会话(含 CASTGC)、Gradescope/Hydro token 及(若开启自动续期)密码' + '启用后,你的 IDS Passkey、Gradescope/Hydro token 及(若开启自动续期)密码' '将以端到端加密形式存于 Casdoor,仅你能用主密码解密,TechPie 与 Casdoor 服务器均无法读取。' '请妥善保管主密码——遗忘将无法在其它设备恢复。'; diff --git a/lib/pages/third_party_accounts_page.dart b/lib/pages/third_party_accounts_page.dart index fd46eb10..0c4b76e0 100644 --- a/lib/pages/third_party_accounts_page.dart +++ b/lib/pages/third_party_accounts_page.dart @@ -20,11 +20,12 @@ import '../widgets/blurred_app_bar.dart'; import '../widgets/ios/ios_native_navigation_bar.dart'; import '../widgets/schedule_picker_sheet.dart'; import 'campus_card_account_page.dart'; +import 'ids_bind_page.dart'; import 'third_party_bind_page.dart'; /// The three states the linked-accounts status dot can show. `null` (no /// dot) means "not applicable" — unbound top-level platform, or a derived -/// child whose parent (cpdaily) isn't bound yet. +/// child whose parent (ids) isn't bound yet. enum _LinkHealth { normal, recentFailure, error } Color _healthColor(BuildContext context, _LinkHealth health) { @@ -36,7 +37,7 @@ Color _healthColor(BuildContext context, _LinkHealth health) { }; } -/// Health for a top-level binding (cpdaily/gradescope/hydro): null when +/// Health for a top-level binding (ids/gradescope/hydro): null when /// unbound (no dot — that's a distinct "not configured" state, not an /// error). _LinkHealth? _topLevelHealth(ThirdPartyAccount? account, RenewStatus? status) { @@ -47,13 +48,13 @@ _LinkHealth? _topLevelHealth(ThirdPartyAccount? account, RenewStatus? status) { } /// Health for a derived child (eams/elearning): null when the parent -/// (cpdaily) isn't bound — there's nothing to evaluate yet. +/// (ids) isn't bound — there's nothing to evaluate yet. _LinkHealth? _childHealth({ - required bool cpdailyBound, + required bool idsBound, required bool nodeAvailable, required RenewStatus? status, }) { - if (!cpdailyBound) return null; + if (!idsBound) return null; if (!nodeAvailable && status?.success != true) return _LinkHealth.error; if (status?.success == false) return _LinkHealth.recentFailure; return _LinkHealth.normal; @@ -102,28 +103,28 @@ class ThirdPartyAccountsPage extends StatelessWidget { body: ListenableBuilder( listenable: Listenable.merge([tpAuth, auth, campusCard]), builder: (context, _) { - final cpdailyBound = tpAuth.hasCpdailyBinding; + final idsBound = tpAuth.hasIdsBinding; return ListView( padding: EdgeInsets.only( top: topInset, bottom: AppShellMetrics.bottomContentPaddingOf(context), ), children: [ - // CpDaily/IDS is the parent session — Blackboard (elearning), + // IDS is the parent session — Blackboard (elearning), // 教务系统 (eams), and eGate 签到 (egateApp) below are all // derived from its tgc, not independent bindings, hence the // nested/indented rendering. _TopLevelTile( - platform: ThirdPartyPlatform.cpdaily, - account: tpAuth.account(ThirdPartyPlatform.cpdaily), - node: tpAuth.cpdailyNode, - renewStatus: tpAuth.renewStatus('cpdaily'), + platform: ThirdPartyPlatform.ids, + account: tpAuth.account(ThirdPartyPlatform.ids), + node: tpAuth.idsNode, + renewStatus: tpAuth.renewStatus('ids'), ), _ChildSessionTile( nodeId: 'elearning', label: 'Blackboard', icon: Icons.school_outlined, - cpdailyBound: cpdailyBound, + idsBound: idsBound, node: tpAuth.elearningNode, renewStatus: tpAuth.renewStatus('elearning'), ), @@ -131,7 +132,7 @@ class ThirdPartyAccountsPage extends StatelessWidget { nodeId: 'eams', label: '教务系统', icon: Icons.account_balance_outlined, - cpdailyBound: cpdailyBound, + idsBound: idsBound, node: tpAuth.eamsNode, renewStatus: tpAuth.renewStatus('eams'), ), @@ -139,7 +140,7 @@ class ThirdPartyAccountsPage extends StatelessWidget { nodeId: 'egateApp', label: 'eGate', icon: Icons.apps_outlined, - cpdailyBound: cpdailyBound, + idsBound: idsBound, node: tpAuth.egateAppNode, renewStatus: tpAuth.renewStatus('egateApp'), ), @@ -259,7 +260,7 @@ class _TopLevelTileState extends State<_TopLevelTile> { IconData get _icon => switch (widget.platform) { ThirdPartyPlatform.gradescope => Icons.grading_outlined, ThirdPartyPlatform.hydro => Icons.terminal_outlined, - ThirdPartyPlatform.cpdaily => Icons.vpn_key_outlined, + ThirdPartyPlatform.ids => Icons.vpn_key_outlined, }; @override @@ -282,11 +283,14 @@ class _TopLevelTileState extends State<_TopLevelTile> { ); } - final health = _topLevelHealth(acc, widget.renewStatus); + final needsUpgrade = + widget.platform == ThirdPartyPlatform.ids && acc.raw['authMethod'] != 'passkey'; + final health = needsUpgrade ? _LinkHealth.error : _topLevelHealth(acc, widget.renewStatus); final subtitleParts = [ acc.displayName, + if (needsUpgrade) '需要升级为 Passkey', if (acc.expireAt != null) _expireLabel(acc.expireAt!), - if (acc.autoRenew) '自动更新 Token 已开启', + if (acc.autoRenew && !needsUpgrade) '自动更新 Token 已开启', ]; if (widget.platform == ThirdPartyPlatform.hydro) { final origin = acc.hydroOrigin ?? ''; @@ -315,12 +319,15 @@ class _TopLevelTileState extends State<_TopLevelTile> { : IconButton( icon: const Icon(Icons.refresh, size: 20), tooltip: '立即刷新', - onPressed: () => unawaited(_refresh(context)), + onPressed: needsUpgrade ? null : () => unawaited(_refresh(context)), ), isIos() ? AdaptiveConfirmationButton( label: 'Unbind', - confirmTitle: '解绑 ${widget.platform.label}?', + confirmTitle: widget.platform == ThirdPartyPlatform.ids && + acc.raw['authMethod'] == 'passkey' + ? '解绑本地及 IDS Passkey?' + : '解绑 ${widget.platform.label}?', confirmLabel: '解绑', destructive: true, onConfirmed: () => @@ -339,14 +346,14 @@ class _TopLevelTileState extends State<_TopLevelTile> { Future _refresh(BuildContext context) async { setState(() => _refreshing = true); - final ok = await widget.node.renew(); + final ok = await ServiceProvider.of(context).thirdPartyAuthService.refreshNode(widget.node); if (!context.mounted) return; setState(() => _refreshing = false); showAdaptiveFeedback( context: context, message: ok ? '${widget.platform.label} 刷新成功' - : '${widget.platform.label} 刷新失败', + : (widget.node.lastRenewError ?? '${widget.platform.label} 刷新失败'), style: ok ? AdaptiveFeedbackStyle.success : AdaptiveFeedbackStyle.error, ); } @@ -372,23 +379,34 @@ class _TopLevelTileState extends State<_TopLevelTile> { if (acc == null) return; final rows = >[ MapEntry('账号', acc.displayName), - if (acc.sid != null && acc.sid!.isNotEmpty) MapEntry('学号', acc.sid!), + if (widget.platform == ThirdPartyPlatform.ids && acc.idsStudentId.isNotEmpty) + MapEntry('学号', acc.idsStudentId) + else if (acc.sid != null && acc.sid!.isNotEmpty) MapEntry('学号', acc.sid!), + if (widget.platform == ThirdPartyPlatform.ids) + MapEntry('登录方式', acc.raw['authMethod'] == 'passkey' ? 'Passkey' : '待升级为 Passkey'), MapEntry('绑定时间', _formatDateTime(acc.boundAt)), MapEntry('更新时间', _formatDateTime(acc.updatedAt)), MapEntry('最近刷新', _renewStatusLabel(widget.renewStatus)), MapEntry('下次刷新', _nextRenewLabel(widget.node.nextRenewTimestamp)), MapEntry('Token 有效期', acc.expireAt != null ? _formatDateTime(acc.expireAt!) : '无',), - MapEntry('自动续期', acc.autoRenew ? '已开启' : '未开启'), + MapEntry( + '自动续期', + widget.platform == ThirdPartyPlatform.ids + ? (acc.raw['authMethod'] == 'passkey' ? '已开启' : '未开启') + : (acc.autoRenew ? '已开启' : '未开启'), + ), if (widget.platform == ThirdPartyPlatform.hydro) ...[ MapEntry('Hydro 站点', acc.hydroOrigin ?? ''), MapEntry('Hydro 域名', (acc.hydroDomains ?? const []).join(', ')), ], ]; - await _showAccountDetailSheet( + final upgrade = await _showAccountDetailSheet( context, title: widget.platform.label, rows: rows, + needsUpgrade: widget.platform == ThirdPartyPlatform.ids && acc.raw['authMethod'] != 'passkey', + idsNotice: widget.platform == ThirdPartyPlatform.ids && acc.raw['authMethod'] == 'passkey', onRefresh: () => unawaited(_refresh(context)), onUnbind: () => unawaited(_confirmUnbind(context, widget.platform)), onProbe: widget.node.keepaliveConfig != null @@ -398,6 +416,13 @@ class _TopLevelTileState extends State<_TopLevelTile> { ? widget.node.cookieProvider?.cookies : null, ); + if (upgrade == true && context.mounted) { + await pushAdaptivePage( + context, + builder: (_) => + const ThirdPartyBindPage(platform: ThirdPartyPlatform.ids), + ); + } } } @@ -405,7 +430,7 @@ class _ChildSessionTile extends StatefulWidget { final String nodeId; // 'eams' | 'elearning' final String label; final IconData icon; - final bool cpdailyBound; + final bool idsBound; final SessionNode node; final RenewStatus? renewStatus; @@ -413,7 +438,7 @@ class _ChildSessionTile extends StatefulWidget { required this.nodeId, required this.label, required this.icon, - required this.cpdailyBound, + required this.idsBound, required this.node, required this.renewStatus, }); @@ -429,7 +454,7 @@ class _ChildSessionTileState extends State<_ChildSessionTile> { Widget build(BuildContext context) { final theme = Theme.of(context); - if (!widget.cpdailyBound) { + if (!widget.idsBound) { return ListTile( dense: true, contentPadding: const EdgeInsets.only(left: 40, right: 16), @@ -440,7 +465,7 @@ class _ChildSessionTileState extends State<_ChildSessionTile> { style: TextStyle(color: theme.colorScheme.onSurfaceVariant), ), subtitle: Text( - '需要先绑定 CpDaily/IDS', + '需要先绑定校园账号', style: theme.textTheme.bodySmall ?.copyWith(color: theme.colorScheme.onSurfaceVariant), ), @@ -448,14 +473,14 @@ class _ChildSessionTileState extends State<_ChildSessionTile> { pushAdaptivePage( context, builder: (_) => - const ThirdPartyBindPage(platform: ThirdPartyPlatform.cpdaily), + const ThirdPartyBindPage(platform: ThirdPartyPlatform.ids), ), ), ); } final health = _childHealth( - cpdailyBound: widget.cpdailyBound, + idsBound: widget.idsBound, nodeAvailable: widget.node.isAvailable, status: widget.renewStatus, ); @@ -488,7 +513,7 @@ class _ChildSessionTileState extends State<_ChildSessionTile> { Future _refresh(BuildContext context) async { setState(() => _refreshing = true); - final ok = await widget.node.renew(); + final ok = await ServiceProvider.of(context).thirdPartyAuthService.refreshNode(widget.node); if (!context.mounted) return; setState(() => _refreshing = false); showAdaptiveFeedback( @@ -517,10 +542,9 @@ class _ChildSessionTileState extends State<_ChildSessionTile> { Future _openDetails(BuildContext context) async { final rows = >[ MapEntry('状态', widget.node.isAvailable ? '可用' : '不可用'), - MapEntry('保活探测', widget.node.displayName), + MapEntry('保活探测', widget.node.probeDisplay), MapEntry('最近刷新', _renewStatusLabel(widget.renewStatus)), MapEntry('下次刷新', _nextRenewLabel(widget.node.nextRenewTimestamp)), - const MapEntry('说明', '由 CpDaily/IDS 会话派生,不单独绑定账号'), ]; await _showAccountDetailSheet( context, @@ -565,7 +589,9 @@ Future _confirmUnbind( final ok = await showAdaptiveAlertDialog( context: context, title: '解绑 ${platform.label}?', - message: '将清除本地保存的 token 与账号信息,不会注销远端账号。', + message: platform == ThirdPartyPlatform.ids && tpAuth.usesIdsPasskey + ? '将删除本地绑定,并尝试在 IDS 解绑此 Passkey。学校验证取消或删除失败时,本地绑定仍会删除。' + : '将清除本地保存的 token 与账号信息,不会注销远端账号。', actions: const [ AdaptiveAlertAction(label: '取消', value: false), AdaptiveAlertAction( @@ -575,9 +601,7 @@ Future _confirmUnbind( ), ], ); - if (ok == true) { - await tpAuth.unbind(platform); - } + if (ok == true && context.mounted) await _unbind(context, platform); } Future _unbind( @@ -585,10 +609,28 @@ Future _unbind( ThirdPartyPlatform platform, ) async { final tpAuth = ServiceProvider.of(context).thirdPartyAuthService; - await tpAuth.unbind(platform); + if (platform != ThirdPartyPlatform.ids || !tpAuth.usesIdsPasskey) { + await tpAuth.unbind(platform); + return; + } + final prompts = IdsDialogSession(context, withPassword: true); + final bool removed; + try { + removed = await tpAuth.unbindIdsWithRemote(promptVerification: prompts.verification); + } finally { + await prompts.close(); + prompts.dispose(); + } + if (!context.mounted) return; + showAdaptiveFeedback( + context: context, + message: removed ? '本地与 IDS Passkey 均已解绑' : '本地绑定已删除,IDS 解绑未完成,可在账号安全页面手动删除', + style: removed ? AdaptiveFeedbackStyle.success : AdaptiveFeedbackStyle.info, + ); } -Future _showAccountDetailSheet( +/// Returns true when the user chooses to upgrade the stored IDS account. +Future _showAccountDetailSheet( BuildContext context, { required String title, required List> rows, @@ -596,6 +638,8 @@ Future _showAccountDetailSheet( VoidCallback? onUnbind, VoidCallback? onProbe, String? cookieText, + bool idsNotice = false, + bool needsUpgrade = false, }) { if (isIos()) { return _showIosAccountDetailSheet( @@ -606,10 +650,12 @@ Future _showAccountDetailSheet( onUnbind: onUnbind, onProbe: onProbe, cookieText: cookieText, + idsNotice: idsNotice, + needsUpgrade: needsUpgrade, ); } final theme = Theme.of(context); - return CNBottomSheet.show( + return CNBottomSheet.show( context: context, useRootNavigator: true, showDragHandle: true, @@ -646,6 +692,10 @@ Future _showAccountDetailSheet( ], ), ), + if (idsNotice) ...[ + const SizedBox(height: 12), + const IdsPasskeyHelp(), + ], if (cookieText != null && cookieText.isNotEmpty) ...[ const SizedBox(height: 12), Row( @@ -697,14 +747,20 @@ Future _showAccountDetailSheet( Row( children: [ Expanded( - child: OutlinedButton.icon( - icon: const Icon(Icons.refresh), - label: const Text('立即刷新'), - onPressed: () { - Navigator.pop(sheetContext); - onRefresh(); - }, - ), + child: needsUpgrade + ? FilledButton.icon( + icon: const Icon(Icons.key_outlined), + label: const Text('升级为 Passkey'), + onPressed: () => Navigator.pop(sheetContext, true), + ) + : OutlinedButton.icon( + icon: const Icon(Icons.refresh), + label: const Text('立即刷新'), + onPressed: () { + Navigator.pop(sheetContext); + onRefresh(); + }, + ), ), if (onProbe != null) ...[ const SizedBox(width: 12), @@ -748,7 +804,7 @@ Future _showAccountDetailSheet( /// and its actions as a second group of tappable rows — unbinding last, in the /// destructive red — under a sheet toolbar with a ✕ to close. No grabber: the /// sheet has one height. -Future _showIosAccountDetailSheet( +Future _showIosAccountDetailSheet( BuildContext context, { required String title, required List> rows, @@ -756,8 +812,10 @@ Future _showIosAccountDetailSheet( VoidCallback? onUnbind, VoidCallback? onProbe, String? cookieText, + bool idsNotice = false, + bool needsUpgrade = false, }) { - return CNBottomSheet.show( + return CNBottomSheet.show( context: context, useRootNavigator: true, isScrollControlled: true, @@ -829,9 +887,25 @@ Future _showIosAccountDetailSheet( ), ], ), + if (idsNotice) + const Padding( + padding: EdgeInsets.symmetric(horizontal: 20), + child: Column( + children: [ + IdsPasskeyHelp(), + ], + ), + ), CupertinoListSection.insetGrouped( children: [ - actionRow(CupertinoIcons.arrow_clockwise, '立即刷新', tint, onRefresh), + if (needsUpgrade) + CupertinoListTile( + leading: Icon(CupertinoIcons.lock, color: tint), + title: Text('升级为 Passkey', style: TextStyle(color: tint)), + onTap: () => Navigator.pop(sheetContext, true), + ) + else + actionRow(CupertinoIcons.arrow_clockwise, '立即刷新', tint, onRefresh), if (onProbe != null) actionRow(CupertinoIcons.heart, '检测', tint, onProbe), if (onUnbind != null) diff --git a/lib/pages/third_party_bind_page.dart b/lib/pages/third_party_bind_page.dart index f720e684..1d809e05 100644 --- a/lib/pages/third_party_bind_page.dart +++ b/lib/pages/third_party_bind_page.dart @@ -10,12 +10,12 @@ import '../utils/platform.dart'; import '../widgets/adaptive_alert_dialog.dart'; import '../widgets/adaptive_feedback.dart'; import '../widgets/adaptive_page_navigation.dart'; -import '../widgets/adaptive_segmented_control.dart'; import '../widgets/adaptive_switch.dart'; import '../widgets/adaptive_text_area.dart'; import '../widgets/adaptive_text_field_group.dart'; import '../widgets/blurred_app_bar.dart'; import '../widgets/ios/ios_native_navigation_bar.dart'; +import 'ids_bind_page.dart'; class ThirdPartyBindPage extends StatefulWidget { final ThirdPartyPlatform platform; @@ -39,17 +39,10 @@ class _ThirdPartyBindPageState extends State { bool _autoRenew = false; String? _inlineError; - // cpdaily SMS state - int _cpdailyLoginMethod = 0; // 0 = password, 1 = SMS - final _cpdailyPhoneCtrl = TextEditingController(); - final _cpdailyCodeCtrl = TextEditingController(); - bool _sendingSms = false; - int _smsCooldown = 0; - Timer? _smsCooldownTimer; + bool get _isIds => widget.platform == ThirdPartyPlatform.ids; bool get _isHydro => widget.platform == ThirdPartyPlatform.hydro; bool get _isGradescope => widget.platform == ThirdPartyPlatform.gradescope; - bool get _isCpdaily => widget.platform == ThirdPartyPlatform.cpdaily; Future _dismissKeyboard() async { FocusManager.instance.primaryFocus?.unfocus(); @@ -64,9 +57,6 @@ class _ThirdPartyBindPageState extends State { _passwordCtrl.dispose(); _hydroOriginCtrl.dispose(); _hydroDomainsCtrl.dispose(); - _cpdailyPhoneCtrl.dispose(); - _cpdailyCodeCtrl.dispose(); - _smsCooldownTimer?.cancel(); super.dispose(); } @@ -104,43 +94,6 @@ class _ThirdPartyBindPageState extends State { setState(() => _autoRenew = ok == true); } - // -- cpdaily SMS methods -- - - Future _sendCpdailySms() async { - final phone = _cpdailyPhoneCtrl.text.trim(); - if (phone.isEmpty) return; - - setState(() => _sendingSms = true); - try { - await ServiceProvider.of(context) - .thirdPartyAuthService - .sendCpdailySmsCode(phone); - if (mounted) { - setState(() => _inlineError = null); - _smsCooldown = 60; - _smsCooldownTimer?.cancel(); - _smsCooldownTimer = Timer.periodic(const Duration(seconds: 1), (t) { - if (!mounted) { - t.cancel(); - return; - } - if (_smsCooldown <= 1) { - t.cancel(); - setState(() => _smsCooldown = 0); - } else { - setState(() => _smsCooldown--); - } - }); - } - } catch (e) { - if (mounted) { - setState(() => _inlineError = '发送失败:$e'); - } - } finally { - if (mounted) setState(() => _sendingSms = false); - } - } - Future _submit() async { if (!_validateForSubmit()) return; await _dismissKeyboard(); @@ -159,22 +112,14 @@ class _ThirdPartyBindPageState extends State { } try { - if (_isCpdaily && _cpdailyLoginMethod == 1) { - // SMS mode - await tpAuth.bindCpdailySms( - phone: _cpdailyPhoneCtrl.text.trim(), - code: _cpdailyCodeCtrl.text.trim(), - ); - } else { - await tpAuth.bind( - platform: widget.platform, - account: _accountCtrl.text.trim(), - password: _passwordCtrl.text, - hydroOrigin: _isHydro ? _hydroOriginCtrl.text.trim() : null, - hydroDomains: domains, - autoRenew: _autoRenew, - ); - } + await tpAuth.bind( + platform: widget.platform, + account: _accountCtrl.text.trim(), + password: _passwordCtrl.text, + hydroOrigin: _isHydro ? _hydroOriginCtrl.text.trim() : null, + hydroDomains: domains, + autoRenew: _autoRenew, + ); if (!mounted) return; setState(() => _inlineError = null); await _dismissKeyboard(); @@ -215,18 +160,6 @@ class _ThirdPartyBindPageState extends State { } bool _validateForSubmit() { - if (_isCpdaily && _cpdailyLoginMethod == 1) { - // SMS mode validation - String? message; - if (_cpdailyPhoneCtrl.text.trim().isEmpty) { - message = '请填写手机号码'; - } else if (_cpdailyCodeCtrl.text.trim().isEmpty) { - message = '请填写验证码'; - } - setState(() => _inlineError = message); - return message == null; - } - if (!isIos()) { return _formKey.currentState?.validate() ?? true; } @@ -251,6 +184,11 @@ class _ThirdPartyBindPageState extends State { @override Widget build(BuildContext context) { + if (_isIds) { + return IdsBindPage( + legacyAccount: ServiceProvider.of(context).thirdPartyAuthService.idsAccount, + ); + } if (isIos()) { return _buildIosBindPage(context); } @@ -277,155 +215,67 @@ class _ThirdPartyBindPageState extends State { _InlineBindFeedback(message: _inlineError!), const SizedBox(height: 12), ], - if (_isCpdaily) ...[ - // cpdaily: tabbed password / SMS interface - SegmentedButton( - segments: const [ - ButtonSegment(value: 0, label: Text('密码登录')), - ButtonSegment(value: 1, label: Text('短信登录')), - ], - selected: {_cpdailyLoginMethod}, - onSelectionChanged: (v) => - setState(() => _cpdailyLoginMethod = v.first), + TextFormField( + controller: _accountCtrl, + autofillHints: const [AutofillHints.username], + keyboardType: _isGradescope + ? TextInputType.emailAddress + : TextInputType.text, + decoration: InputDecoration( + labelText: _isGradescope ? '邮箱' : '用户名', + border: const OutlineInputBorder(), ), - const SizedBox(height: 16), - if (_cpdailyLoginMethod == 0) ...[ - TextFormField( - controller: _accountCtrl, - decoration: const InputDecoration( - labelText: '学号', - border: OutlineInputBorder(), - ), - validator: (v) => - (v == null || v.trim().isEmpty) ? '必填' : null, - ), - const SizedBox(height: 12), - TextFormField( - controller: _passwordCtrl, - obscureText: _obscure, - decoration: InputDecoration( - labelText: '密码', - border: const OutlineInputBorder(), - suffixIcon: IconButton( - icon: Icon( - _obscure ? Icons.visibility_off : Icons.visibility, - ), - onPressed: () => setState(() => _obscure = !_obscure), - ), - ), - validator: (v) => (v == null || v.isEmpty) ? '必填' : null, - ), - ] else ...[ - TextFormField( - controller: _cpdailyPhoneCtrl, - keyboardType: TextInputType.phone, - decoration: const InputDecoration( - labelText: '手机号码', - border: OutlineInputBorder(), + validator: (v) => (v == null || v.trim().isEmpty) ? '必填' : null, + ), + const SizedBox(height: 12), + TextFormField( + controller: _passwordCtrl, + autofillHints: const [AutofillHints.password], + obscureText: _obscure, + decoration: InputDecoration( + labelText: '密码', + border: const OutlineInputBorder(), + suffixIcon: IconButton( + icon: Icon( + _obscure ? Icons.visibility_off : Icons.visibility, ), - validator: (v) => - (v == null || v.trim().isEmpty) ? '必填' : null, - ), - const SizedBox(height: 12), - Row( - children: [ - Expanded( - child: TextFormField( - controller: _cpdailyCodeCtrl, - keyboardType: TextInputType.number, - decoration: const InputDecoration( - labelText: '验证码', - border: OutlineInputBorder(), - ), - validator: (v) => - (v == null || v.trim().isEmpty) ? '必填' : null, - ), - ), - const SizedBox(width: 12), - FilledButton.tonal( - onPressed: (_smsCooldown > 0 || _sendingSms) - ? null - : () => unawaited(_sendCpdailySms()), - style: FilledButton.styleFrom( - minimumSize: const Size(100, 56), - ), - child: _sendingSms - ? const SizedBox( - height: 20, - width: 20, - child: CircularProgressIndicator(strokeWidth: 2), - ) - : Text( - _smsCooldown > 0 ? '${_smsCooldown}s' : '发送验证码', - ), - ), - ], + onPressed: () => setState(() => _obscure = !_obscure), ), - ], - const SizedBox(height: 8), - ] else ...[ + ), + validator: (v) => (v == null || v.isEmpty) ? '必填' : null, + ), + if (_isHydro) ...[ + const SizedBox(height: 12), TextFormField( - controller: _accountCtrl, - autofillHints: const [AutofillHints.username], - keyboardType: _isGradescope - ? TextInputType.emailAddress - : TextInputType.text, - decoration: InputDecoration( - labelText: _isGradescope ? '邮箱' : '用户名', - border: const OutlineInputBorder(), + controller: _hydroOriginCtrl, + decoration: const InputDecoration( + labelText: 'Hydro 站点 origin', + helperText: '默认 https://acm.shanghaitech.edu.cn', + border: OutlineInputBorder(), ), - validator: (v) => (v == null || v.trim().isEmpty) ? '必填' : null, + validator: (v) => + (v == null || v.trim().isEmpty) ? '必填' : null, ), const SizedBox(height: 12), TextFormField( - controller: _passwordCtrl, - autofillHints: const [AutofillHints.password], - obscureText: _obscure, - decoration: InputDecoration( - labelText: '密码', - border: const OutlineInputBorder(), - suffixIcon: IconButton( - icon: Icon( - _obscure ? Icons.visibility_off : Icons.visibility, - ), - onPressed: () => setState(() => _obscure = !_obscure), - ), + controller: _hydroDomainsCtrl, + minLines: 2, + maxLines: 6, + decoration: const InputDecoration( + labelText: '课程 domain (每行一个,或用逗号分隔)', + helperText: '例: SI100B_2025_Autumn', + border: OutlineInputBorder(), + alignLabelWithHint: true, ), - validator: (v) => (v == null || v.isEmpty) ? '必填' : null, + validator: (v) { + final list = (v ?? '') + .split(RegExp(r'[\s,]+')) + .where((e) => e.trim().isNotEmpty); + return list.isEmpty ? '至少填一个 domain' : null; + }, ), - if (_isHydro) ...[ - const SizedBox(height: 12), - TextFormField( - controller: _hydroOriginCtrl, - decoration: const InputDecoration( - labelText: 'Hydro 站点 origin', - helperText: '默认 https://acm.shanghaitech.edu.cn', - border: OutlineInputBorder(), - ), - validator: (v) => - (v == null || v.trim().isEmpty) ? '必填' : null, - ), - const SizedBox(height: 12), - TextFormField( - controller: _hydroDomainsCtrl, - minLines: 2, - maxLines: 6, - decoration: const InputDecoration( - labelText: '课程 domain (每行一个,或用逗号分隔)', - helperText: '例: SI100B_2025_Autumn', - border: OutlineInputBorder(), - alignLabelWithHint: true, - ), - validator: (v) { - final list = (v ?? '') - .split(RegExp(r'[\s,]+')) - .where((e) => e.trim().isNotEmpty); - return list.isEmpty ? '至少填一个 domain' : null; - }, - ), - ], - const SizedBox(height: 8), ], + const SizedBox(height: 8), if (isIos()) MergeSemantics( child: ListTile( @@ -504,106 +354,28 @@ class _ThirdPartyBindPageState extends State { _InlineBindFeedback(message: _inlineError!), const SizedBox(height: 16), ], - if (_isCpdaily) ...[ - AdaptiveSegmentedControl( - value: _cpdailyLoginMethod, - segments: const ['密码登录', '短信登录'], - onChanged: (value) { - setState(() { - _cpdailyLoginMethod = value; - _inlineError = null; - }); - }, - ), - const SizedBox(height: 18), - if (_cpdailyLoginMethod == 0) - AdaptiveTextFieldGroup( - items: [ - AdaptiveTextFieldGroupItem( - placeholder: '学号', - controller: _accountCtrl, - textInputAction: TextInputAction.next, - ), - AdaptiveTextFieldGroupItem( - placeholder: '密码', - controller: _passwordCtrl, - obscureText: _obscure, - textInputAction: TextInputAction.done, - onSubmitted: (_) => unawaited(_submit()), - ), - ], - ) - else ...[ - AdaptiveTextFieldGroup( - items: [ - AdaptiveTextFieldGroupItem( - placeholder: '手机号码', - controller: _cpdailyPhoneCtrl, - keyboardType: TextInputType.phone, - textInputAction: TextInputAction.next, - ), - ], + AdaptiveTextFieldGroup( + items: [ + AdaptiveTextFieldGroupItem( + placeholder: _isGradescope ? '邮箱' : '用户名', + controller: _accountCtrl, + keyboardType: _isGradescope + ? TextInputType.emailAddress + : TextInputType.text, + textInputAction: TextInputAction.next, ), - const SizedBox(height: 10), - Row( - children: [ - Expanded( - child: AdaptiveTextFieldGroup( - items: [ - AdaptiveTextFieldGroupItem( - placeholder: '验证码', - controller: _cpdailyCodeCtrl, - keyboardType: TextInputType.number, - textInputAction: TextInputAction.done, - onSubmitted: (_) => unawaited(_submit()), - ), - ], - ), - ), - const SizedBox(width: 8), - FilledButton.tonal( - onPressed: (_smsCooldown > 0 || _sendingSms) - ? null - : () => unawaited(_sendCpdailySms()), - style: FilledButton.styleFrom( - minimumSize: const Size(100, 56), - ), - child: _sendingSms - ? const SizedBox( - height: 20, - width: 20, - child: CircularProgressIndicator(strokeWidth: 2), - ) - : Text( - _smsCooldown > 0 ? '${_smsCooldown}s' : '发送验证码', - ), - ), - ], + AdaptiveTextFieldGroupItem( + placeholder: '密码', + controller: _passwordCtrl, + obscureText: _obscure, + textInputAction: + _isHydro ? TextInputAction.next : TextInputAction.done, + onSubmitted: (_) { + if (!_isHydro) unawaited(_submit()); + }, ), ], - ] else - AdaptiveTextFieldGroup( - items: [ - AdaptiveTextFieldGroupItem( - placeholder: _isGradescope ? '邮箱' : '用户名', - controller: _accountCtrl, - keyboardType: _isGradescope - ? TextInputType.emailAddress - : TextInputType.text, - textInputAction: TextInputAction.next, - ), - AdaptiveTextFieldGroupItem( - placeholder: '密码', - controller: _passwordCtrl, - obscureText: _obscure, - textInputAction: - _isHydro ? TextInputAction.next : TextInputAction.done, - onSubmitted: (_) { - if (!_isHydro) unawaited(_submit()); - }, - ), - ], - ), + ), if (_isHydro) ...[ const SizedBox(height: 16), AdaptiveTextFieldGroup( @@ -639,24 +411,22 @@ class _ThirdPartyBindPageState extends State { ), ), ], - if (!_isCpdaily || _cpdailyLoginMethod == 0) ...[ - const SizedBox(height: 16), - MergeSemantics( - child: ListTile( - contentPadding: EdgeInsets.zero, - title: const Text('自动更新 Token'), - subtitle: Text( - '过期前 48 小时内自动重登,免去手动重绑', - style: TextStyle(color: secondaryLabel), - ), - trailing: AdaptiveSwitch( - value: _autoRenew, - onChanged: (value) => unawaited(_onAutoRenewChanged(value)), - ), - onTap: () => unawaited(_onAutoRenewChanged(!_autoRenew)), + const SizedBox(height: 16), + MergeSemantics( + child: ListTile( + contentPadding: EdgeInsets.zero, + title: const Text('自动更新 Token'), + subtitle: Text( + '过期前 48 小时内自动重登,免去手动重绑', + style: TextStyle(color: secondaryLabel), + ), + trailing: AdaptiveSwitch( + value: _autoRenew, + onChanged: (value) => unawaited(_onAutoRenewChanged(value)), ), + onTap: () => unawaited(_onAutoRenewChanged(!_autoRenew)), ), - ], + ), const SizedBox(height: 18), FilledButton( onPressed: _busy ? null : () => unawaited(_submit()), diff --git a/lib/services/assignment_service.dart b/lib/services/assignment_service.dart index 4de7865f..e5c14b16 100644 --- a/lib/services/assignment_service.dart +++ b/lib/services/assignment_service.dart @@ -114,7 +114,7 @@ class AssignmentService extends ChangeNotifier { : _assignments.where((a) { final source = (a.platform == 'blackboard' || a.platform == 'exam') - ? 'cpdaily' + ? ThirdPartyPlatform.ids.id : a.platform; return !changed.contains(source); }).toList(); @@ -144,10 +144,8 @@ class AssignmentService extends ChangeNotifier { unawaited(fetchAssignments()); } - /// Who each binding is, not which session it holds: renewals rotate the - /// Hydro `sid` cookie and the egateApp probe rewrites the cpdaily `sid`, so - /// neither may count as an account change (nor may anything derived from it, - /// such as `cpdailyStudentId`). + /// Who each binding is, not which session it holds. Token rotations and + /// derived campus sessions must not count as an account change. Map _currentSources() => { for (final account in _tpAuth.accounts) account.platform.id: jsonEncode([ @@ -283,7 +281,7 @@ class AssignmentService extends ChangeNotifier { final futures = >[]; - if (_tpAuth.hasCpdailyBinding) { + if (_tpAuth.hasIdsBinding) { futures.add( _fetchBlackboard().then((items) { if (items != null) successfulResults['blackboard'] = items; @@ -312,8 +310,8 @@ class AssignmentService extends ChangeNotifier { }), ); break; - case ThirdPartyPlatform.cpdaily: - // cpdaily provides the CpDaily session, not deadline data — skip. + case ThirdPartyPlatform.ids: + // ids provides the IDS session, not deadline data — skip. break; } } @@ -369,11 +367,11 @@ class AssignmentService extends ChangeNotifier { final successfulResults = >{}; Future? future; - if (platformId == 'blackboard' && _tpAuth.hasCpdailyBinding) { + if (platformId == 'blackboard' && _tpAuth.hasIdsBinding) { future = _fetchBlackboard().then((items) { if (items != null) successfulResults['blackboard'] = items; }); - } else if (platformId == 'exam' && _tpAuth.hasCpdailyBinding) { + } else if (platformId == 'exam' && _tpAuth.hasIdsBinding) { future = _fetchExamTable().then((items) { if (items != null) successfulResults['exam'] = items; }); @@ -424,14 +422,14 @@ class AssignmentService extends ChangeNotifier { Future?> _fetchBlackboard() async { final node = _tpAuth.elearningNode; // withCookie handles initial minting if the downstream cookie isn't set. - if (!_tpAuth.hasCpdailyBinding) return null; + if (!_tpAuth.hasIdsBinding) return null; try { final resp = await _tpAuth.sessionTree.withCookie( node, (cp) async { // cp.cookies is the elearning cookie string minted from the - // cpdaily CASTGC. The backend uses it directly to query + // ids CASTGC. The backend uses it directly to query // Blackboard (no SSO bounce needed). final r = await _http.post( Uri.parse('$_baseUrl/deadlines/blackboard'), @@ -453,7 +451,7 @@ class AssignmentService extends ChangeNotifier { Future?> _fetchExamTable() async { final semesterId = _selectedSemesterId(); final node = _tpAuth.eamsNode; - if (!_tpAuth.hasCpdailyBinding || + if (!_tpAuth.hasIdsBinding || semesterId == null || semesterId.isEmpty) { return null; diff --git a/lib/services/auth_service.dart b/lib/services/auth_service.dart index fdd235d1..2162563f 100644 --- a/lib/services/auth_service.dart +++ b/lib/services/auth_service.dart @@ -11,8 +11,8 @@ import 'storage_service.dart'; import 'uni_auth_service.dart'; /// AuthService owns ONLY the primary account: the GeekPie Uni-Auth (Casdoor) -/// SSO identity session. It knows nothing about CASTGC, CpDaily, or any -/// campus-system credential — those live in [ThirdPartyAuthService] (the eGate +/// SSO identity session. It knows nothing about CASTGC, IDS, or any +/// campus-system credential — those live in [ThirdPartyAuthService] (the IDS /// binding) and are the single source of truth for every CASTGC-dependent /// feature. Keeping that boundary means an SSO-only user is correctly "logged /// in" without implying they can reach eGate-gated services. diff --git a/lib/services/campus_user_agent.dart b/lib/services/campus_user_agent.dart new file mode 100644 index 00000000..19864bff --- /dev/null +++ b/lib/services/campus_user_agent.dart @@ -0,0 +1,15 @@ +/// Shared by campus authentication and session probes. The app supplies its +/// actual version, OS and display scale before starting any network requests. +class CampusUserAgent { + static String value = 'TechPie'; + + static String format({ + required String version, + required String build, + required String device, + required String system, + required String systemVersion, + required double scale, + }) => + 'TechPie/$version.$build ($device; $system $systemVersion; Scale/${scale.toStringAsFixed(2)}) techpie/$version'; +} diff --git a/lib/services/campus_web_session.dart b/lib/services/campus_web_session.dart index 89fa670a..9f3b64d5 100644 --- a/lib/services/campus_web_session.dart +++ b/lib/services/campus_web_session.dart @@ -15,7 +15,7 @@ import 'storage_service.dart'; /// It is deliberately *not* a credential store — credentials live in the /// [SessionNode] tree, and pages read their cookies from there (see /// `CampusSessionHandle`). What this class does is reset that shared store when -/// the primary account or its eGate binding changes, so a page opened under a +/// the primary account or its IDS binding changes, so a page opened under a /// new account cannot inherit the previous one's campus session. /// /// The reset is a full wipe of the store: Android and OHOS cannot enumerate @@ -49,7 +49,7 @@ class CampusWebSession { String get _owner { final userId = _auth?.session?.userId; if (userId == null) return 'signed-out'; - final binding = node.account == null + final binding = node.account == null || node.account!.raw['authMethod'] != 'passkey' ? 'unbound' : '${node.account!.account}:${node.account!.boundAt.toIso8601String()}'; return jsonEncode([userId, binding]); diff --git a/lib/services/egate_app_service.dart b/lib/services/egate_app_service.dart index b4b20f0f..0763b2d2 100644 --- a/lib/services/egate_app_service.dart +++ b/lib/services/egate_app_service.dart @@ -53,7 +53,7 @@ class EgateAppCheckinResult { /// Native "校园签到" feature: queries the egate-app (xshdapp) sign-in /// announcement + history, and submits a check-in for a scanned WID. Session -/// cookies (MOD_AUTH_CAS/_WEU) are derived from the cpdaily CASTGC via +/// cookies (MOD_AUTH_CAS/_WEU) are derived from the ids CASTGC via /// [ThirdPartyAuthService.egateAppNode], the same pattern AssignmentService /// uses for eams/elearning. class EgateAppService extends ChangeNotifier { @@ -72,14 +72,14 @@ class EgateAppService extends ChangeNotifier { String get _baseUrl => apiBaseUrl(_storage); /// Guard for any egate-app call: requires a logged-in primary account AND - /// a bound cpdaily account (the source of the CASTGC that egate-app's + /// a bound ids account (the source of the CASTGC that egate-app's /// session is derived from). void _requireReady() { if (!_auth.isLoggedIn) { throw EgateAppException('请先登录 TechPie 主账号'); } - if (!_tpAuth.hasCpdailyBinding) { - throw EgateAppException('校园签到需要绑定 eGate 账号,请在「第三方账号」中绑定'); + if (!_tpAuth.hasIdsBinding) { + throw EgateAppException('校园签到需要绑定 IDS 账号,请在「第三方账号」中绑定'); } } @@ -89,9 +89,9 @@ class EgateAppService extends ChangeNotifier { } Future> fetchSignHistory() async { - final studentId = _tpAuth.cpdailyStudentId; + final studentId = _tpAuth.idsStudentId; if (studentId.isEmpty) { - throw EgateAppException('当前 eGate 绑定缺少学号,请重新绑定 eGate'); + throw EgateAppException('当前 IDS 绑定缺少学号,请重新绑定 IDS'); } final data = await _postJson('egate-app/history', {'studentId': studentId}); final rows = (data['data'] as Map?)?['rows'] as List? ?? const []; @@ -117,7 +117,7 @@ class EgateAppService extends ChangeNotifier { /// POST `$_baseUrl/[path]` with the egate-app derived cookie + [extra] body /// fields. On 401 the egateApp node (and, if its own tgc turns out stale, - /// the parent cpdaily node) is renewed via [SessionTree.withCookie]'s + /// the parent ids node) is renewed via [SessionTree.withCookie]'s /// two-level retry, then the request is retried once. Future> _postJson( String path, @@ -142,7 +142,7 @@ class EgateAppService extends ChangeNotifier { }, ); if (response == null) { - throw EgateAppException('当前 eGate 登录态已失效,请重新绑定 eGate'); + throw EgateAppException('当前 eGate 登录态已失效,请重新绑定 IDS'); } final decoded = response.body.isEmpty ? {} diff --git a/lib/services/http_client.dart b/lib/services/http_client.dart index 72799b95..cfc366f6 100644 --- a/lib/services/http_client.dart +++ b/lib/services/http_client.dart @@ -2,6 +2,7 @@ import 'dart:convert'; import 'package:http/http.dart' as http; +import 'campus_user_agent.dart'; import 'debug_logger.dart'; class LoggingHttpClient { @@ -18,7 +19,7 @@ class LoggingHttpClient { }) async { _logger.log(method: 'GET', url: url.toString(), tag: tag); try { - final response = await _inner.get(url, headers: headers); + final response = await _inner.get(url, headers: {'User-Agent': CampusUserAgent.value, ...?headers}); _logger.log( method: 'GET', url: url.toString(), @@ -56,7 +57,7 @@ class LoggingHttpClient { try { final response = await _inner.post( url, - headers: headers, + headers: {'User-Agent': CampusUserAgent.value, ...?headers}, body: bodyStr, encoding: encoding, ); @@ -86,7 +87,7 @@ class LoggingHttpClient { }) async { _logger.log(method: 'HEAD', url: url.toString(), tag: tag); try { - final response = await _inner.head(url, headers: headers); + final response = await _inner.head(url, headers: {'User-Agent': CampusUserAgent.value, ...?headers}); _logger.log( method: 'HEAD', url: url.toString(), diff --git a/lib/services/ids/campus_http.dart b/lib/services/ids/campus_http.dart new file mode 100644 index 00000000..e4b865ba --- /dev/null +++ b/lib/services/ids/campus_http.dart @@ -0,0 +1,201 @@ +import 'dart:convert'; +import 'dart:io'; + +import 'package:cookie_jar/cookie_jar.dart'; +import 'package:dio/dio.dart'; + +import '../campus_user_agent.dart'; +import '../debug_logger.dart'; + +class IdsException implements Exception { + final String message; + final bool credentialRejected; + const IdsException(this.message, {this.credentialRejected = false}); + @override + String toString() => message; +} + +/// App-owned HTTP session with host, path, expiry and Secure cookie scoping. +/// Authentication logs contain diagnostics only, never payloads or cookies. +class CampusHttp { + CampusHttp(this.http, {DebugLogger? logger}) : _logger = logger; + final Dio http; + final DebugLogger? _logger; + final CookieJar jar = CookieJar(); + final Map> _stored = {}; + static const hosts = { + 'ids.shanghaitech.edu.cn', + 'eams.shanghaitech.edu.cn', + 'elearning.shanghaitech.edu.cn', + 'egate.shanghaitech.edu.cn', + 'oa.shanghaitech.edu.cn', + }; + + List> get snapshot => _stored.values.toList(); + + Future restore(List records) async { + for (final record in records) { + final uri = Uri.parse(record['url'] as String); + await _save(uri, [record['cookie'] as String]); + } + } + + Future _save(Uri uri, List values) async { + for (final value in values) { + Cookie cookie; + try { + cookie = Cookie.fromSetCookieValue(value); + } on HttpException { + continue; + } + final domain = cookie.domain?.replaceFirst(RegExp(r'^\.'), '') ?? uri.host; + if (uri.host != domain && !uri.host.endsWith('.$domain')) continue; + if (cookie.path == null) { + final slash = uri.path.lastIndexOf('/'); + cookie.path = slash <= 0 ? '/' : uri.path.substring(0, slash); + } + if (cookie.maxAge != null) { + cookie.expires = DateTime.now().toUtc().add(Duration(seconds: cookie.maxAge!)); + cookie.maxAge = null; + } + final key = '${cookie.name}|$domain|${cookie.path ?? '/'}'; + _stored[key] = { + 'url': uri.replace(query: '', fragment: '').toString(), + 'cookie': cookie.toString(), + }; + await jar.saveFromResponse(uri, [cookie]); + } + } + + Future cookieHeader(Uri uri) async => + (await jar.loadForRequest(uri)).map((c) => '${c.name}=${c.value}').join('; '); + Future cookie(Uri uri, String name) async { + for (final value in await jar.loadForRequest(uri)) { + if (value.name == name) return value.value; + } + return null; + } + + Future>> request( + Uri uri, { + String method = 'GET', + Object? data, + Map? headers, + bool allowErrorResponse = false, + }) async { + for (var hop = 0; hop < 10; hop++) { + if (uri.scheme != 'https' || !hosts.contains(uri.host) || uri.userInfo.isNotEmpty) { + throw const IdsException('学校登录跳转到了不支持的地址'); + } + Response> response; + // Query parameters can contain a username or CAS ticket. Request bodies, + // headers and HTML can contain passwords, captcha or assertion material. + final logUrl = '${uri.origin}${uri.path}'; + final timer = Stopwatch()..start(); + _logger?.log(method: method, url: logUrl, tag: 'IDS'); + try { + response = await http.request>( + uri.toString(), + data: data, + options: Options( + method: method, + responseType: ResponseType.bytes, + followRedirects: false, + validateStatus: (_) => true, + headers: { + 'User-Agent': CampusUserAgent.value, + ...?headers, + 'Cookie': await cookieHeader(uri), + }, + ), + ); + } on DioException { + _logger?.log( + method: method, + url: logUrl, + error: '无法连接学校认证服务,请检查网络后重试', + durationMicros: timer.elapsedMicroseconds, + tag: 'IDS', + ); + throw const IdsException('无法连接学校认证服务,请检查网络后重试'); + } + if (_logger?.enabled == true) { + _logger!.log( + method: method, + url: logUrl, + statusCode: response.statusCode, + responseBody: _responseCode(response), + durationMicros: timer.elapsedMicroseconds, + tag: 'IDS', + ); + } + await _save(uri, response.headers['set-cookie'] ?? []); + final status = response.statusCode ?? 0; + final location = response.headers.value('location'); + if ([301, 302, 303, 307, 308].contains(status) && location != null) { + uri = uri.resolve(location); + if (status == 303 || ((status == 301 || status == 302) && method == 'POST')) { + method = 'GET'; + data = null; + headers = null; + } + continue; + } + if (allowErrorResponse) return response; + if (status >= 500) throw const IdsException('学校认证服务暂时不可用'); + if (status == 401 || status == 403) { + throw const IdsException('学校登录态已失效,请重新绑定 IDS Passkey', credentialRejected: true); + } + if (status < 200 || status >= 400) throw const IdsException('学校认证请求失败'); + return response; + } + throw const IdsException('学校登录跳转次数过多'); + } + + static String text(Response> response) => + utf8.decode(response.data ?? [], allowMalformed: true); + + String? _responseCode(Response> response) { + if (!(response.headers.value('content-type') ?? '').contains('application/json')) return null; + try { + final data = jsonDecode(text(response)); + final code = data is Map ? int.tryParse('${data['code']}') : null; + return code == null ? null : jsonEncode({'code': code}); + } on FormatException { + return null; + } + } + + Future> object(String path, [Map? body]) async { + final uri = Uri.parse('https://ids.shanghaitech.edu.cn$path'); + final personal = uri.path.startsWith('/personalInfo/'); + final reference = personal ? await cookie(uri, 'REFERERCE_TOKEN') : null; + final response = await request( + uri, + method: body == null ? 'GET' : 'POST', + headers: { + 'Accept': 'application/json', + 'X-Requested-With': 'XMLHttpRequest', + if (body != null) 'Content-Type': 'application/json', + if (personal) 'Origin': 'https://ids.shanghaitech.edu.cn', + if (personal) + 'Referer': 'https://ids.shanghaitech.edu.cn/personalInfo/personCenter/index.html', + if (reference != null) 'refererToken': reference, + }, + // IDS reports rejected password/captcha verification as JSON with HTTP + // 500. Its business code must reach the verification flow unchanged. + allowErrorResponse: uri.path == '/personalInfo/common/recheckUserInfo', + data: body == null + ? null + : jsonEncode({...body, if (personal) 'n': '0.${DateTime.now().microsecondsSinceEpoch}'}), + ); + try { + return (jsonDecode(text(response)) as Map).cast(); + } on FormatException { + if ((response.statusCode ?? 0) >= 500) { + throw const IdsException('学校认证服务暂时不可用'); + } + throw const IdsException('IDS 未返回有效登录结果,请重新绑定', credentialRejected: true); + } + } +} diff --git a/lib/services/ids/ids_client.dart b/lib/services/ids/ids_client.dart new file mode 100644 index 00000000..1420936c --- /dev/null +++ b/lib/services/ids/ids_client.dart @@ -0,0 +1,462 @@ +// Protocol port from Geekpie Auth Portal; see licenses/shanghaitech-ids-passkey.txt. +import 'dart:convert'; +import 'dart:math'; +import 'dart:typed_data'; + +import 'package:dio/dio.dart'; +import 'package:html/parser.dart'; +import 'package:pointycastle/export.dart'; + +import '../../models/ids_passkey.dart'; +import '../debug_logger.dart'; +import 'campus_http.dart'; +import 'software_passkey.dart'; + +export 'campus_http.dart' show IdsException; + +typedef IdsCaptchaRefresh = Future Function(); +typedef IdsCaptchaPrompt = Future Function( + Uint8List image, + String? error, { + required IdsCaptchaRefresh refresh, +}); +typedef IdsVerificationAnswer = ({String password, String captcha}); +typedef IdsVerificationPrompt = Future Function( + Uint8List image, + String? error, { + required IdsCaptchaRefresh refresh, +}); + +enum _PasswordFailure { password, captcha, locked, unknown } + +// Same known IDS error messages as the Auth Portal; never display raw HTML. +const _passwordMessages = { + 'accountlogin_account_pwd_error': _PasswordFailure.password, + '该账号非常用账号或用户名密码有误': _PasswordFailure.password, + '用户名或密码错误': _PasswordFailure.password, + '账号或密码错误': _PasswordFailure.password, + '您提供的用户名或者密码有误': _PasswordFailure.password, + 'invalid username or password': _PasswordFailure.password, + 'incorrect username or password': _PasswordFailure.password, + '验证码错误': _PasswordFailure.captcha, + '验证码不正确': _PasswordFailure.captcha, + '验证码不能为空': _PasswordFailure.captcha, + 'verification code error': _PasswordFailure.captcha, + 'invalid captcha': _PasswordFailure.captcha, + '账号已锁定': _PasswordFailure.locked, + '账户已锁定': _PasswordFailure.locked, + '账号被锁定': _PasswordFailure.locked, + 'account locked': _PasswordFailure.locked, + 'account is locked': _PasswordFailure.locked, +}; + +class IdsSession { + final String username; + final Map raw; + final String? name; + const IdsSession(this.username, this.raw, {this.name}); +} + +class IdsClient { + IdsClient({Dio? http, Random? nameRandom, DebugLogger? logger}) + : _http = http ?? + Dio( + BaseOptions( + connectTimeout: const Duration(seconds: 15), + receiveTimeout: const Duration(seconds: 20), + ), + ), + _nameRandom = nameRandom ?? Random.secure(), + _logger = logger; + final Dio _http; + final Random _nameRandom; + final DebugLogger? _logger; + static final _login = Uri.parse('${SoftwarePasskey.origin}/authserver/login'); + + Map _fields(String html) { + final document = parse(html); + final result = {}; + for (final name in ['execution', 'lt', 'pwdEncryptSalt']) { + result[name] = document.querySelector('[name="$name"],#$name')?.attributes['value'] ?? ''; + } + if (result['execution']!.isEmpty) throw const IdsException('IDS 登录页面已变化或要求修改密码,请先到学校网站处理'); + return result; + } + + String _encryptPassword(String password, String salt) { + if (utf8.encode(salt).length != 16) throw const IdsException('IDS 密码加密参数无效'); + final cipher = PaddedBlockCipher('AES/CBC/PKCS7') + ..init( + true, + PaddedBlockCipherParameters( + ParametersWithIV( + KeyParameter(Uint8List.fromList(utf8.encode(salt))), + Uint8List.fromList(utf8.encode('Nu1L' * 4)), + ), + null, + ), + ); + return base64.encode( + cipher.process( + Uint8List.fromList( + utf8.encode('${base64.encode(SoftwarePasskey.randomBytes(48))}$password'), + ), + ), + ); + } + + Future _captcha( + CampusHttp client, + String path, + IdsCaptchaPrompt prompt, { + String? error, + }) async { + final refresh = _captchaLoader(client, path); + final answer = await prompt(await refresh(), error, refresh: refresh); + if (answer == null) throw const IdsException('已取消绑定'); + return answer.trim(); + } + + IdsCaptchaRefresh _captchaLoader(CampusHttp client, String path) => () async { + final base = Uri.parse('${SoftwarePasskey.origin}$path'); + final nonce = '${DateTime.now().millisecondsSinceEpoch}'; + final uri = + base.replace(query: base.path.startsWith('/personalInfo/') ? 'data=$nonce' : nonce); + final response = await client.request(uri); + return Uint8List.fromList(response.data ?? []); + }; + + _PasswordFailure _passwordFailure(String html) { + final document = parse(html); + for (final node in document.querySelectorAll('script,style,input,textarea,template,noscript')) { + node.remove(); + } + final failures = <_PasswordFailure>{}; + for (final node in document + .querySelectorAll('#showErrorTip,#formErrorTip,#msg,.errors,.login-error,[role=alert]')) { + final message = node.text.trim().replaceAll(RegExp(r'[。.!!]$'), '').toLowerCase(); + final failure = _passwordMessages[message]; + if (failure != null) failures.add(failure); + } + return failures.length == 1 ? failures.single : _PasswordFailure.unknown; + } + + Future> _devices(CampusHttp client) async { + final response = await client.object('/personalInfo/accountSecurity/queryAllDevices', { + 'pageNumber': 1, + 'pageSize': 1000, + }); + final devices = response['datas']; + if (response['code'].toString() != '0' || devices is! List) { + throw const IdsException('无法读取 IDS 已绑定的 Passkey 名称,请重试'); + } + return devices; + } + + Future _newDeviceName(CampusHttp client) async { + final devices = await _devices(client); + final existing = {for (final device in devices) device['deviceName'] as String}; + const characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789'; + String name; + do { + final suffix = + List.generate(6, (_) => characters[_nameRandom.nextInt(characters.length)]).join(); + name = 'Techpie-$suffix'; + } while (existing.contains(name)); + return name; + } + + Future revoke(IdsPasskey key, {required IdsVerificationPrompt promptVerification}) async { + final session = await login(key); + final client = CampusHttp(_http, logger: _logger); + await client.restore(session.raw['cookieJar'] as List); + final devices = await _devices(client); + // IDS's device ID is the anonbiometricsd registered alongside this key. + // Never select a device by its name or delete another credential. + final device = devices.where((d) => d['id'] == key.anonBiometricsId).firstOrNull; + if (device == null) return; + final ownerId = device['userId']; + if (ownerId is! String || ownerId.isEmpty) throw const IdsException('IDS 未返回此 Passkey 的解绑信息'); + final recheck = await client.object( + '/personalInfo/common/isUserRecheckNecessary?t=${DateTime.now().millisecondsSinceEpoch}', + ); + if (recheck['code'].toString() != '0') { + final approach = await client.object('/personalInfo/common/recheckApproach', {}); + if (!((approach['datas'] as Map?)?['approachName']?.toString().split(',') ?? []) + .contains('password')) { + throw const IdsException('请在 IDS 账号安全页面完成额外验证后解绑'); + } + String? error; + final refresh = _captchaLoader(client, '/personalInfo/captcha/checkCode'); + while (true) { + final answer = await promptVerification(await refresh(), error, refresh: refresh); + if (answer == null) throw const IdsException('已取消 IDS 验证,本地绑定已删除'); + final salt = await client.cookie( + Uri.parse('${SoftwarePasskey.origin}/personalInfo/'), + 'WIS_PER_ENC', + ); + if (salt == null) throw const IdsException('IDS 二次验证会话已失效'); + final checked = await client.object('/personalInfo/common/recheckUserInfo', { + 'reauthType': 'password', + 'password': _encryptPassword(answer.password, salt), + 'captcha': answer.captcha, + }); + final code = checked['code'].toString(); + if (code == '0') break; + if (code != '2106010003' && code != '2106040000') throw const IdsException('IDS 二次验证失败'); + error = code == '2106040000' ? '密码错误,请重试' : '验证码错误,请重试'; + } + } + // Same payload as the IDS account-security device management page. + final removed = await client.object('/personalInfo/accountSecurity/deleteDevice', { + 'id': key.anonBiometricsId, + 'response': ownerId, + }); + if (removed['code'].toString() != '0') throw const IdsException('IDS 未接受解绑,请在账号安全页面手动删除'); + } + + Future<({IdsPasskey credential, IdsSession session})> register( + String username, + String password, { + required IdsCaptchaPrompt promptCaptcha, + required Future Function(IdsPasskey credential) saveCandidate, + }) async { + final client = CampusHttp(_http, logger: _logger); + var fields = _fields(CampusHttp.text(await client.request(_login))); + final needed = await client + .object('/authserver/checkNeedCaptcha.htl?username=${Uri.encodeQueryComponent(username)}'); + var needsCaptcha = needed['isNeed'] == true; + String? captchaError; + while (true) { + final captcha = needsCaptcha + ? await _captcha( + client, + '/authserver/getCaptcha.htl?${DateTime.now().millisecondsSinceEpoch}', + promptCaptcha, + error: captchaError, + ) + : ''; + final response = await client.request( + _login, + method: 'POST', + // A rejected password/captcha returns a login HTML page with HTTP 401. + allowErrorResponse: true, + headers: {'Content-Type': 'application/x-www-form-urlencoded'}, + data: Uri( + queryParameters: { + 'username': username, + 'password': _encryptPassword(password, fields['pwdEncryptSalt']!), + 'captcha': captcha, + 'execution': fields['execution']!, + 'lt': fields['lt']!, + '_eventId': 'submit', + 'cllt': 'userNameLogin', + 'dllt': 'generalLogin', + }, + ).query, + ); + if (await client.cookie(_login, 'CASTGC') != null) break; + final html = CampusHttp.text(response); + final failure = _passwordFailure(html); + if (failure == _PasswordFailure.captcha) { + fields = _fields(html); + needsCaptcha = true; + captchaError = '验证码错误,请重试'; + continue; + } + throw IdsException( + switch (failure) { + _PasswordFailure.password => 'IDS 账号或密码错误,请重新输入', + _PasswordFailure.locked => 'IDS 账号已锁定,请在学校 IDS 处理后重试', + _ => 'IDS 登录失败,请检查学校账号状态后重试', + }, + ); + } + final profile = await client.object('/personalInfo/common/getUserConf', {}); + final canonical = (profile['datas'] as Map?)?['uid'] as String?; + if (profile['code'].toString() != '0' || canonical == null || canonical.isEmpty) { + throw const IdsException('无法确认 IDS 账号身份'); + } + final recheck = await client.object( + '/personalInfo/common/isUserRecheckNecessary?t=${DateTime.now().millisecondsSinceEpoch}', + ); + if (recheck['code'].toString() != '0') { + final approach = await client.object('/personalInfo/common/recheckApproach', {}); + if (!((approach['datas'] as Map?)?['approachName']?.toString().split(',') ?? []) + .contains('password')) { + throw const IdsException('IDS 要求额外身份验证,请先在学校账号安全页面处理'); + } + String? captchaError; + while (true) { + final code = await _captcha( + client, + '/personalInfo/captcha/checkCode?data=${DateTime.now().millisecondsSinceEpoch}', + promptCaptcha, + error: captchaError, + ); + final salt = await client.cookie( + Uri.parse('${SoftwarePasskey.origin}/personalInfo/'), + 'WIS_PER_ENC', + ); + if (salt == null) throw const IdsException('IDS 二次验证会话已失效,请重试'); + final checked = await client.object('/personalInfo/common/recheckUserInfo', { + 'reauthType': 'password', + 'password': _encryptPassword(password, salt), + 'captcha': code, + }); + if (checked['code'].toString() == '0') break; + if (checked['code'].toString() == '2106040000') { + throw const IdsException('IDS 密码错误,请重新输入'); + } + if (checked['code'].toString() != '2106010003') { + throw const IdsException('IDS 二次验证失败,请检查密码后重试'); + } + captchaError = '验证码错误,请重试'; + } + } + final deviceName = await _newDeviceName(client); + final started = await client.object('/personalInfo/accountSecurity/startRegister', {}); + final request = ((started['datas'] as Map?)?['request'] as Map?)?.cast(); + if (request?['requestId'] == null || request?['publicKeyCredentialCreationOptions'] == null) { + throw const IdsException('IDS 无法开始 Passkey 注册'); + } + final candidate = SoftwarePasskey.registration( + (request!['publicKeyCredentialCreationOptions'] as Map).cast(), + canonical, + ); + // Retain the candidate locally before submitting its public key. A lost + // finishRegister response can then be recovered by logging in with it. + await saveCandidate(candidate.secret); + final finished = await client.object('/personalInfo/accountSecurity/finishRegister', { + 'deviceName': deviceName, + 'anonbiometricsd': candidate.secret.anonBiometricsId, + 'response': jsonEncode({ + 'requestId': request['requestId'], + 'credential': candidate.credential, + 'sessionToken': null, + }), + }); + if (finished['code'].toString() != '0') throw const IdsException('IDS 未接受 Passkey 注册'); + return (credential: candidate.secret, session: await login(candidate.secret)); + } + + Future login(IdsPasskey secret, {bool backedUp = false}) async { + final client = CampusHttp(_http, logger: _logger); + final fields = _fields(CampusHttp.text(await client.request(_login))); + final started = await client.object( + '/authserver/startAssertion', + {'userId': base64.encode(utf8.encode(secret.username)), 'id': secret.anonBiometricsId}, + ); + final request = ((started['result'] as Map?)?['request'] as Map?)?.cast(); + if (request?['requestId'] == null || request?['publicKeyCredentialRequestOptions'] == null) { + throw const IdsException('IDS Passkey 已被解绑或不可用,请在 TechPie 重新绑定', credentialRejected: true); + } + final credential = SoftwarePasskey.authentication( + (request!['publicKeyCredentialRequestOptions'] as Map).cast(), + secret, + backedUp: backedUp, + ); + await client.request( + _login, + method: 'POST', + headers: {'Content-Type': 'application/x-www-form-urlencoded'}, + data: Uri( + queryParameters: { + '_eventId': 'submit', + 'responseJson': jsonEncode( + {'requestId': request['requestId'], 'credential': credential, 'sessionToken': null}, + ), + 'username': base64.encode(utf8.encode(secret.username)), + 'cllt': 'fidoLogin', + 'dllt': 'generalLogin', + 'lt': '', + 'execution': fields['execution']!, + }, + ).query, + ); + final tgc = await client.cookie(_login, 'CASTGC'); + if (tgc == null) throw const IdsException('IDS Passkey 登录失败,请重新绑定', credentialRejected: true); + final profile = await client.object('/personalInfo/common/getUserConf', {}); + if (profile['code'].toString() != '0' || + (profile['datas'] as Map?)?['uid'] != secret.username) { + throw const IdsException('IDS 登录身份不匹配', credentialRejected: true); + } + final name = (profile['datas'] as Map?)?['cn'] as String?; + return IdsSession( + secret.username, + {'tgc': tgc, 'cookies': await client.cookieHeader(_login), 'cookieJar': client.snapshot}, + name: name?.trim().isNotEmpty == true ? name!.trim() : null, + ); + } + + Future mintCookie(String nodeId, Map root) async { + final client = CampusHttp(_http, logger: _logger); + await client.restore( + (root['cookieJar'] as List?) ?? + [ + { + 'url': _login.toString(), + 'cookie': 'CASTGC=${root['tgc']}; Path=/authserver; Secure; HttpOnly', + }, + ], + ); + final entry = switch (nodeId) { + 'eams' => 'https://eams.shanghaitech.edu.cn/eams/home.action', + 'elearning' => + '${SoftwarePasskey.origin}/authserver/login?service=${Uri.encodeQueryComponent('https://elearning.shanghaitech.edu.cn:8443/webapps/bb-BB-BBLEARN/index.jsp')}', + 'egateApp' => 'https://egate.shanghaitech.edu.cn/xsfw/sys/xshdapp/xshdApply/dqnxxqgrhz.do', + 'oa' => + '${SoftwarePasskey.origin}/authserver/login?service=${Uri.encodeQueryComponent('https://oa.shanghaitech.edu.cn/workflow/request/AddRequest.jsp?workflowid=14862')}', + _ => throw ArgumentError.value(nodeId), + }; + final response = await client.request(Uri.parse(entry)); + final html = CampusHttp.text(response); + if (parse(html).querySelector('[name="execution"]') != null) { + throw const IdsException('IDS 登录态已失效', credentialRejected: true); + } + if (nodeId == 'elearning') { + final fields = {}; + for (final input in parse(html).querySelectorAll('input[name]')) { + fields[input.attributes['name']!] = input.attributes['value'] ?? ''; + } + if (fields.isEmpty) throw const IdsException('Blackboard 未返回 SSO 登录表单'); + await client.request( + Uri.parse( + 'https://elearning.shanghaitech.edu.cn:8443/webapps/bb-sso-BBLEARN/execute/authValidate/customLogin', + ), + method: 'POST', + headers: {'Content-Type': 'application/x-www-form-urlencoded'}, + data: Uri(queryParameters: fields).query, + ); + await client.request( + Uri.parse('https://elearning.shanghaitech.edu.cn:8443/webapps/bb-BB-BBLEARN/index.jsp'), + ); + } + final target = Uri.parse( + switch (nodeId) { + 'eams' => 'https://eams.shanghaitech.edu.cn/eams/', + 'elearning' => 'https://elearning.shanghaitech.edu.cn:8443/webapps/', + 'egateApp' => 'https://egate.shanghaitech.edu.cn/xsfw/sys/xshdapp/xshdApply/dqnxxqgrhz.do', + _ => 'https://oa.shanghaitech.edu.cn/', + }, + ); + final required = switch (nodeId) { + 'eams' => 'JSESSIONID', + 'egateApp' => 'MOD_AUTH_CAS', + 'oa' => 'shkjdx_session', + _ => 'session_id' + }; + var cookies = await client.cookieHeader(target); + if (nodeId == 'elearning' && + await client.cookie(target, 'session_id') == null && + await client.cookie(target, 's_session_id') == null) { + final jsession = await client.cookie(target, 'JSESSIONID'); + if (jsession != null) cookies = '$cookies; session_id=$jsession'; + } + if (!cookies.contains('$required=') && + !(nodeId == 'elearning' && cookies.contains('s_session_id='))) { + throw const IdsException('未能建立学校业务系统会话'); + } + return cookies; + } +} diff --git a/lib/services/ids/software_passkey.dart b/lib/services/ids/software_passkey.dart new file mode 100644 index 00000000..ba5ae8d5 --- /dev/null +++ b/lib/services/ids/software_passkey.dart @@ -0,0 +1,154 @@ +// IDS protocol port from auth-portal / shanghaitech-ids-passkey (MIT). +import 'dart:convert'; +import 'dart:math'; +import 'dart:typed_data'; + +import 'package:cbor/cbor.dart'; +import 'package:crypto/crypto.dart'; +import 'package:pointycastle/asn1.dart'; +import 'package:pointycastle/export.dart'; + +import '../../models/ids_passkey.dart'; + +class SoftwarePasskey { + static const origin = 'https://ids.shanghaitech.edu.cn'; + + // Real IDS logins on 2026-11-03 accepted signCount 7, 7, 3, 0, 0, + // each with a fresh challenge, cookie jar and verified account session. + // Use WebAuthn's "counter unsupported" value so synced software credentials + // need no cross-device counter. Do not increment or sync this value. + static const signCount = 0; + + static final _curve = ECDomainParameters('prime256v1'); + static Uint8List randomBytes(int length) { + final random = Random.secure(); + return Uint8List.fromList(List.generate(length, (_) => random.nextInt(256))); + } + + static String encode(List value) => base64Url.encode(value).replaceAll('=', ''); + static Uint8List decode(String value) => base64Url.decode(base64Url.normalize(value)); + static BigInt _integer(List bytes) => + BigInt.parse(bytes.map((b) => b.toRadixString(16).padLeft(2, '0')).join(), radix: 16); + static Uint8List _bytes(BigInt value) { + final hex = value.toRadixString(16).padLeft(64, '0'); + return Uint8List.fromList( + List.generate(32, (i) => int.parse(hex.substring(i * 2, i * 2 + 2), radix: 16)), + ); + } + + static Uint8List _clientData(String type, String challenge) => Uint8List.fromList( + utf8.encode( + jsonEncode({ + 'type': type, + 'challenge': challenge, + 'origin': origin, + 'crossOrigin': false, + }), + ), + ); + + static ({IdsPasskey secret, Map credential}) registration( + Map options, + String username, + ) { + if ((options['rp'] as Map)['id'] != IdsPasskey.rpId || + (options['user'] as Map)['name'] != username) { + throw const FormatException('IDS registration identity mismatch'); + } + if (!(options['pubKeyCredParams'] as List).any((p) => p['alg'] == -7) || + (options['authenticatorSelection'] as Map?)?['userVerification'] == 'required') { + throw const FormatException('IDS requires unsupported user verification'); + } + BigInt d; + do { + d = _integer(randomBytes(32)); + } while (d == BigInt.zero || d >= _curve.n); + final point = _curve.G * d; + String credentialId; + do { + credentialId = encode(randomBytes(32)); + } while ((options['excludeCredentials'] as List? ?? []).any((c) => c['id'] == credentialId)); + final secret = IdsPasskey( + credentialId: credentialId, + privateKey: encode(_bytes(d)), + userHandle: (options['user'] as Map)['id'] as String, + anonBiometricsId: randomBytes(16).map((b) => b.toRadixString(16).padLeft(2, '0')).join(), + username: username, + ); + final cose = cbor.encode( + CborMap({ + const CborSmallInt(1): const CborSmallInt(2), + const CborSmallInt(3): const CborSmallInt(-7), + const CborSmallInt(-1): const CborSmallInt(1), + const CborSmallInt(-2): CborBytes(_bytes(point!.x!.toBigInteger()!)), + const CborSmallInt(-3): CborBytes(_bytes(point.y!.toBigInteger()!)), + }), + ); + final id = decode(credentialId); + final authData = Uint8List.fromList([ + ...sha256.convert(utf8.encode(IdsPasskey.rpId)).bytes, + 0x49, // UP + BE + AT; this software credential is backup eligible. + ...Uint8List(4), ...Uint8List(16), id.length >> 8, id.length & 255, ...id, ...cose, + ]); + final attestation = cbor.encode( + CborMap({ + CborString('fmt'): CborString('none'), + CborString('attStmt'): CborMap({}), + CborString('authData'): CborBytes(authData), + }), + ); + return ( + secret: secret, + credential: { + 'type': 'public-key', + 'id': credentialId, + 'response': { + 'attestationObject': encode(attestation), + 'clientDataJSON': encode(_clientData('webauthn.create', options['challenge'] as String)), + }, + 'clientExtensionResults': {}, + } + ); + } + + static Map authentication( + Map options, + IdsPasskey secret, { + bool backedUp = false, + }) { + if (options['rpId'] != IdsPasskey.rpId || options['userVerification'] == 'required') { + throw const FormatException('Unsupported IDS assertion'); + } + final allowed = options['allowCredentials'] as List?; + if (allowed != null && + allowed.isNotEmpty && + !allowed.any((c) => c['id'] == secret.credentialId)) { + throw const FormatException('IDS Passkey has been removed; bind again'); + } + final counter = ByteData(4)..setUint32(0, signCount); + final authData = Uint8List.fromList([ + ...sha256.convert(utf8.encode(IdsPasskey.rpId)).bytes, + 0x09 | (backedUp ? 0x10 : 0), // UP + BE, and actual backup state. + ...counter.buffer.asUint8List(), + ]); + final data = _clientData('webauthn.get', options['challenge'] as String); + final signer = Signer('SHA-256/DET-ECDSA') + ..init(true, PrivateKeyParameter(ECPrivateKey(_integer(decode(secret.privateKey)), _curve))); + final signature = + signer.generateSignature(Uint8List.fromList([...authData, ...sha256.convert(data).bytes])) + as ECSignature; + final der = + ASN1Sequence(elements: [ASN1Integer(signature.r), ASN1Integer(signature.s)]).encode(); + return { + 'type': 'public-key', + 'id': secret.credentialId, + 'response': { + 'authenticatorData': encode(authData), + 'clientDataJSON': encode(data), + 'signature': encode(der), + 'userHandle': secret.userHandle, + }, + 'clientExtensionResults': {}, + }; + } +} diff --git a/lib/services/oa_gym_local_client.dart b/lib/services/oa_gym_local_client.dart new file mode 100644 index 00000000..d1d4608e --- /dev/null +++ b/lib/services/oa_gym_local_client.dart @@ -0,0 +1,473 @@ +import 'dart:async'; +import 'dart:convert'; + +import 'package:cookie_jar/cookie_jar.dart'; +import 'package:html/parser.dart'; +import 'package:http/http.dart' as http; + +import '../models/oa_gym.dart'; +import 'campus_user_agent.dart'; + +class OaGymLocalException implements Exception { + final String message; + final bool sessionExpired; + const OaGymLocalException(this.message, {this.sessionExpired = false}); +} + +/// OA business requests for an already authenticated, client-owned session. +/// Authentication and renewal remain in the existing IDS session tree. +class OaGymLocalClient { + OaGymLocalClient(this._client); + final http.Client _client; + + Future> request( + String path, + Map parameters, { + required String cookies, + Map venues = const {}, + Map timeSlots = const {}, + }) async { + final session = _OaSession(_client); + await session.restore(cookies); + try { + final Object data; + switch (path) { + case 'oa/gym/metadata': + data = await _metadata(session); + case 'oa/gym/availability': + data = await _availability(session, parameters); + case 'oa/gym/search': + data = await _search(session, parameters, venues, timeSlots); + case 'oa/gym/book': + data = await _book(session, (parameters['booking'] as Map).cast()); + case 'oa/gym/profile': + data = await _profile(session); + default: + throw const OaGymLocalException('不支持的 OA 请求'); + } + return {'success': true, 'data': data}; + } on TimeoutException { + throw OaGymLocalException( + path.endsWith('/book') ? '预约提交超时,请先查询预约记录确认结果,避免重复提交' : '学校 OA 查询超时,请稍后重试或缩小日期范围', + ); + } on http.ClientException { + throw OaGymLocalException( + path.endsWith('/book') ? '预约连接中断,请先查询预约记录确认结果,避免重复提交' : '无法连接学校 OA,请检查网络后重试', + ); + } + } + + Future> _profile(_OaSession session) async { + var userId = await session.cookie('loginidweaver'); + if (userId == null || userId.isEmpty) { + await session.send('/workflow/request/AddRequest.jsp', query: {'workflowid': '14862'}); + userId = await session.cookie('loginidweaver'); + } + if (userId == null || userId.isEmpty) { + throw const OaGymLocalException('无法确认 OA 当前用户,请刷新登录态后重试'); + } + // The public resource card masks phone numbers. Read the signed-in user's + // own contact form, without submitting it or accepting a caller-supplied ID. + final html = await session.send( + '/hrm/resource/HrmResourceContactEdit.jsp', + query: {'isfromtab': 'true', 'id': userId, 'isView': '1'}, + ); + final form = parse(html).querySelector('form#resource'); + if (form?.querySelector('input[name="id"]')?.attributes['value'] != userId) { + throw const OaGymLocalException('OA 未返回当前用户的联系信息,请重试或手动填写'); + } + String value(String name) => + form!.querySelector('input[name="$name"]')?.attributes['value']?.trim() ?? ''; + return {'phone': value('mobile'), 'email': value('email')}; + } + + Future> _metadata(_OaSession session) async { + final timestamp = '${DateTime.now().millisecondsSinceEpoch}'; + Future browser(String id, String type) async { + final html = await session.send( + '/formmode/browser/CommonSingleBrowser.jsp', + query: { + 'customid': id, + 'browsertype': type, + 'sqlwhere': '', + 'workflowid': '-1', + 'currenttime': timestamp, + 'sqlcondition': '', + }, + headers: {'Origin': _OaSession.origin.origin}, + ); + return _tableString(html); + } + + final timeTable = await browser('7102', 'browser.sysjd'); + final venueTable = await browser('7101', 'browser.tygcg'); + final timeRows = await _tableRows(session, timeTable); + final venueRows = await _tableRows(session, venueTable); + final times = { + for (final row in timeRows) + if (row.length > 2) _timeRange(row[2]): row[0], + }; + final all = { + for (final row in venueRows) + if (row.length > 2) row[2]: row[0], + }; + final venues = { + '所有场地': 'all', + '室内羽毛球场': 'badminton_group', + '室内乒乓球场': 'pingpong_group', + '网球场': 'tennis_group', + '匹克球场': 'pickleball_group', + for (final entry in all.entries) + if (entry.value != '44' && + !oaIsUnusedVenue(entry.key) && + OaSport.values.any((sport) => oaVenueMatchesSport(entry.key, sport))) + entry.key: entry.value, + }; + if (times.isEmpty || venues.length <= 5) { + throw const OaGymLocalException('加载 OA 场馆数据失败,请稍后重试'); + } + return {'venues': venues, 'allVenues': all, 'timeSlots': times}; + } + + Future>> _availability( + _OaSession session, + Map parameters, + ) async { + final result = >[]; + for (final id in parameters['sports'] as List) { + final sport = OaSport.values.byName(id as String); + final config = oaSportConfigs[sport]!; + for (var slot = parameters['startSlot'] as int; + slot <= (parameters['endSlot'] as int); + slot++) { + final query = { + 'id': '63', + 'init': 'false', + 'showtype': '1', + 'isselsub': '0', + 'isonlyleaf': '1', + 'dataconditionParam': '_sfn_31901_sfv_${parameters['date']}' + '_sfn_31902_sfv_${slot}_sfn_32340_sfv_${config.field32340}', + 'treerootnode': '', + 'selectedids': '', + 'time': '${DateTime.now().millisecondsSinceEpoch}', + }; + Future> tree(String pid, String name) async { + final body = await session.send( + '/formmode/tree/treebrowser/CustomTreeBrowserAjax.jsp', + query: query, + form: [MapEntry('pid', pid), MapEntry('name', name)], + headers: { + 'Accept': 'text/plain, */*; q=0.01', + 'Content-Type': 'application/x-www-form-urlencoded', + 'X-Requested-With': 'XMLHttpRequest', + 'Referer': '${_OaSession.origin}wui/main.jsp?templateId=1', + }, + ); + return jsonDecode(body.replaceFirst('\uFEFF', '')) as List; + } + + final parents = await tree('63_1', '体育馆'); + final parent = parents + .cast>() + .where((item) => item['name'] == config.parentName) + .firstOrNull; + final numbers = {}; + if (parent != null && parent['isParent'].toString() != 'false') { + for (final item in await tree(parent['id'].toString(), config.parentName)) { + final name = (item['name'] as String?) ?? ''; + if (!name.startsWith(config.courtNamePrefix)) continue; + final number = int.tryParse(RegExp(r'\d+').firstMatch(name)?.group(0) ?? ''); + if (number != null && number >= 1 && number <= config.courtCount) numbers.add(number); + } + } + result.add({ + 'sport': id, + 'date': parameters['date'], + 'timeSlot': slot, + 'availableCourts': numbers.toList()..sort(), + 'totalCourts': config.courtCount, + }); + } + } + return result; + } + + Future>> _search( + _OaSession session, + Map parameters, + Map venues, + Map timeSlots, + ) async { + final results = >[]; + for (final venue in parameters['venueNames'] as List) { + for (final range in parameters['timeRanges'] as List) { + final fields = >[ + const MapEntry('customid', '16201'), + const MapEntry('viewtype', '0'), + const MapEntry('issimple', 'true'), + const MapEntry('formmodeid', '11684'), + const MapEntry('formid', '-247'), + const MapEntry('template', '-1'), + const MapEntry('check_con', '31869'), + const MapEntry('con31869_htmltype', '3'), + const MapEntry('con31869_type', '161'), + const MapEntry('con31869_colname', 'sycd'), + const MapEntry('con31869_viewtype', '0'), + const MapEntry('con31869_opt', '1'), + MapEntry('con31869_value', venues[venue]!), + MapEntry('con31869_name', venue as String), + const MapEntry('check_con', '31870'), + const MapEntry('con31870_htmltype', '3'), + const MapEntry('con31870_type', '2'), + const MapEntry('con31870_colname', 'syrq'), + const MapEntry('con31870_viewtype', '0'), + const MapEntry('datetype_31870_opt', '6'), + const MapEntry('con31870_opt', '2'), + MapEntry('con31870_value', parameters['startDate'] as String), + const MapEntry('con31870_opt1', '4'), + MapEntry('con31870_value1', parameters['endDate'] as String), + const MapEntry('tableMax', '20'), + if ((range as String).isNotEmpty) ...[ + const MapEntry('check_con', '31871'), + const MapEntry('con31871_htmltype', '3'), + const MapEntry('con31871_type', '161'), + const MapEntry('con31871_colname', 'sysjd'), + const MapEntry('con31871_viewtype', '0'), + const MapEntry('con31871_opt', '1'), + MapEntry('con31871_value', timeSlots[_timeRange(range)]!), + MapEntry('con31871_name', _timeRange(range)), + ], + ]; + final html = await session.send( + '/formmode/search/CustomSearchBySimpleIframe.jsp', + query: {'customid': '16201', 'mainid': '0'}, + form: fields, + headers: { + 'Content-Type': 'application/x-www-form-urlencoded', + 'Origin': _OaSession.origin.origin, + }, + ); + // Let session-expiry errors reach SessionTree; never return partial + // results after a login redirect or 401 during a multi-court query. + results.add({ + 'venue': venue, + 'timeRange': range, + 'rows': await _tableRows(session, _tableString(html)), + }); + } + } + return results; + } + + Future> _book(_OaSession session, Map booking) async { + final sport = OaSport.values.byName(booking['sport'] as String); + final config = oaSportConfigs[sport]!; + final slot = oaTimeSlots.firstWhere((slot) => slot.id == booking['timeSlot']); + await session.send('/workflow/request/AddRequest.jsp', query: {'workflowid': '14862'}); + final userId = await session.cookie('loginidweaver'); + if (userId == null || userId.isEmpty) { + throw const OaGymLocalException('无法确认 OA 当前用户,请刷新登录态后重试'); + } + final today = + DateTime.now().toUtc().add(const Duration(hours: 8)).toIso8601String().substring(0, 10); + final timestamp = DateTime.now().millisecondsSinceEpoch; + final court = config.courtOffset + (booking['courtNumber'] as int); + final fields = { + 'requestname': '学生和教工场馆借用申请-${booking['userName']}-$today', + 'field31876': userId, + 'field31877': '885', + 'field34283': booking['studentId'], + 'field31879': booking['phone'], + 'field31880': booking['email'] ?? '', + 'field32340': config.field32340, + 'field31901': booking['date'], + 'field31902': '${booking['timeSlot']}', + 'field31883': '63_$court', + 'field31884': '${booking['playersCount']}', + 'field31885': '0', + 'field31888': booking['userName'], + 'field31889': booking['phone'], + 'field31892': '1', + 'field31904': slot.start, + 'field31905': slot.end, + 'field31878': today, + 'mainId': '41', + 'subId': '11482', + 'secId': '11483', + 'workflowid': '14862', + 'workflowtype': '61', + 'nodeid': '16385', + 'nodetype': '0', + 'src': 'submit', + 'iscreate': '1', + 'formid': '-248', + 'isbill': '1', + 'needcheck': ',requestname,field31883,field31884,field31885,field31888,' + 'field31889,field31892,field31901,field31902,field32340,,,,', + 'requestid': '-1', + 'rand': '$timestamp', + 'needwfback': '1', + 'f_weaver_belongto_userid': 'null', + 'f_weaver_belongto_usertype': 'null', + '${userId}_14862_addrequest_submit_token': '${timestamp + 1}', + 'freeNode': '0', + 'freeDuty': '1', + }; + final html = await session.send( + '/workflow/request/RequestOperation.jsp', + form: fields.entries.map((e) => MapEntry(e.key, e.value as String)).toList(), + headers: {'Content-Type': 'application/x-www-form-urlencoded'}, + ); + final success = html.contains("wfforward('/workflow/request/WorkflowDirection.jsp?"); + final label = '${config.courtNamePrefix}${booking['courtNumber']}${config.courtNameSuffix}'; + return { + 'success': success, + 'message': '${sport.label} $label ${slot.range} ' + '${success ? '预约成功' : '提交失败,请检查 OA 系统状态'}', + }; + } + + Future>> _tableRows(_OaSession session, String table) async { + final rows = >[]; + for (var page = 0; page <= 20; page++) { + final fields = {'tableString': table, 'pageIndex': '$page', 'mode': 'run'}; + const path = '/weaver/weaver.common.util.taglib.SplitPageXmlServlet'; + final headers = {'Origin': _OaSession.origin.origin}; + var body = await session.send(path, form: fields.entries.toList(), headers: headers); + var next = _xmlRows(body); + if (body.trim().isNotEmpty && next.isEmpty) { + body = await session.send(path, query: fields, form: const [], headers: headers); + next = _xmlRows(body); + } + rows.addAll(next); + if (next.length < 10) break; + } + return rows; + } +} + +/// One operation owns its OA cookies. It cannot follow a redirect into IDS or +/// send cookies to another host. SessionTree supplies a fresh session on expiry. +class _OaSession { + _OaSession(this.client); + final http.Client client; + final CookieJar jar = CookieJar(); + static final origin = Uri.parse('https://oa.shanghaitech.edu.cn/'); + + Future restore(String raw) async { + await jar.saveFromResponse(origin, [ + for (final part in raw.split(';')) + if (part.indexOf('=') > 0) + Cookie(part.trim().split('=').first, part.substring(part.indexOf('=') + 1).trim()) + ..path = '/' + ..secure = true, + ]); + if (await cookie('shkjdx_session') == null) _expired(); + } + + Future cookie(String name) async => + (await jar.loadForRequest(origin)).where((c) => c.name == name).firstOrNull?.value; + + Never _expired() => throw const OaGymLocalException( + 'OA 登录态已失效,请刷新登录态后重试', + sessionExpired: true, + ); + + Future send( + String path, { + Map? query, + List>? form, + Map? headers, + }) async { + var uri = origin.resolve(path).replace(queryParameters: query); + var body = + form?.map((e) => '${Uri.encodeComponent(e.key)}=${Uri.encodeComponent(e.value)}').join('&'); + for (var redirect = 0; redirect < 10; redirect++) { + if (uri.scheme != 'https' || + uri.host != origin.host || + uri.userInfo.isNotEmpty || + uri.path.startsWith('/login/')) { + _expired(); + } + final request = http.Request(body == null ? 'GET' : 'POST', uri) + ..followRedirects = false + ..headers.addAll({ + 'User-Agent': CampusUserAgent.value, + 'Referer': origin.toString(), + 'Cookie': (await jar.loadForRequest(uri)).map((c) => '${c.name}=${c.value}').join('; '), + if (body != null) 'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8', + ...?headers, + }); + if (body != null) request.bodyBytes = utf8.encode(body); + final response = await client + .send(request) + .then(http.Response.fromStream) + .timeout(const Duration(seconds: 20)); + final setCookie = response.headers['set-cookie']; + if (setCookie != null) { + await jar.saveFromResponse(uri, [ + for (final value in setCookie.split(RegExp(r',(?=\s*[^;,=\s]+=[^;,]+)'))) + Cookie.fromSetCookieValue(value.trim()), + ]); + } + final status = response.statusCode; + if (status == 401 || status == 403) _expired(); + if ([301, 302, 303, 307, 308].contains(status) && response.headers['location'] != null) { + uri = uri.resolve(response.headers['location']!); + if ([301, 302, 303].contains(status)) body = null; + continue; + } + if (status < 200 || status >= 400) { + throw OaGymLocalException('学校 OA 请求失败(HTTP $status),请稍后重试'); + } + final text = utf8.decode(response.bodyBytes, allowMalformed: true); + if (RegExp(r''']*type\s*=\s*["']?password\b''', caseSensitive: false) + .hasMatch(text) || + RegExp( + r'''(?:top|window|parent)\.location(?:\.href)?\s*=\s*["'][^"']*/login/''', + caseSensitive: false, + ).hasMatch(text)) { + _expired(); + } + return text; + } + _expired(); + } +} + +String _tableString(String html) { + for (final pattern in [ + r'''var\s+__tableStringKey__\s*=\s*['"]([0-9A-F]+)['"]''', + r'''name=["']?tableString["']?\s+value=["']?([0-9A-F]+)["']?''', + r'''tableString\s*=\s*["']?([0-9A-F]+)["']?''', + ]) { + final match = RegExp(pattern, caseSensitive: false).firstMatch(html); + if (match != null) return match.group(1)!; + } + throw const OaGymLocalException('OA 未返回场馆查询数据,请刷新后重试'); +} + +List> _xmlRows(String xml) => [ + for (final row + in RegExp(r']*>([\s\S]*?)', caseSensitive: false).allMatches(xml)) + [ + for (final col in RegExp(r']*?)(?:/>|>([\s\S]*?))', caseSensitive: false) + .allMatches(row.group(1)!)) + _cleanHtml( + RegExp(r'''showvalue\s*=\s*(['"])(.*?)\1''', caseSensitive: false, dotAll: true) + .firstMatch(col.group(1)!) + ?.group(2) ?? + col.group(2) ?? + '', + ), + ], + ]; + +String _cleanHtml(String value) { + final decoded = parseFragment(value.replaceAll('', '')).text ?? ''; + return (parseFragment(decoded).text ?? '').replaceAll(RegExp(r'\s+'), ' ').trim(); +} + +String _timeRange(String value) => + _cleanHtml(value).replaceAll(RegExp('[–—-]'), '-').replaceAll(RegExp(r'\s+'), ''); diff --git a/lib/services/oa_gym_service.dart b/lib/services/oa_gym_service.dart index 1c769fed..69220ddb 100644 --- a/lib/services/oa_gym_service.dart +++ b/lib/services/oa_gym_service.dart @@ -1,14 +1,12 @@ import 'dart:async'; -import 'dart:convert'; import 'package:flutter/foundation.dart'; import 'package:http/http.dart' as http; import '../models/oa_gym.dart'; import '../models/third_party_account.dart'; -import 'api_base_url.dart'; import 'auth_service.dart'; -import 'session/cookie_provider.dart'; +import 'oa_gym_local_client.dart'; import 'session/session_tree.dart'; import 'storage_service.dart'; import 'third_party_auth_service.dart'; @@ -25,7 +23,7 @@ class OaGymService extends ChangeNotifier { final AuthService _auth; final StorageService _storage; final ThirdPartyAuthService _tpAuth; - final http.Client _client; + final OaGymLocalClient _localClient; bool _sessionReady = false; bool _metadataReady = false; @@ -34,9 +32,7 @@ class OaGymService extends ChangeNotifier { int _generation = 0; Future? _metadataRequest; Future _availabilityTail = Future.value(); - String _oaCookies = ''; String _oaIdentity = ''; - bool _bulkSearchSupported = false; Map _venues = {}; Map _allVenues = {}; Map _timeSlots = {}; @@ -54,9 +50,7 @@ class OaGymService extends ChangeNotifier { this._storage, this._tpAuth, { http.Client? client, - }) : _client = client ?? http.Client(); - - String get _baseUrl => apiBaseUrl(_storage); + }) : _localClient = OaGymLocalClient(client ?? http.Client()); bool get loading => _loading; bool get sessionReady => _sessionReady; @@ -68,28 +62,18 @@ class OaGymService extends ChangeNotifier { String? get profileSyncError => _profileSyncError; String get profileOwner { - if (!_auth.isLoggedIn || !_tpAuth.hasCpdailyBinding) return ''; - final campusId = _tpAuth.cpdailyStudentId.isNotEmpty - ? _tpAuth.cpdailyStudentId - : _tpAuth.cpdailyBinding!.cpdailyUserId.isNotEmpty - ? _tpAuth.cpdailyBinding!.cpdailyUserId - : _tpAuth.cpdailyBinding!.account; + if (!_auth.isLoggedIn || !_tpAuth.hasIdsBinding) return ''; + final campusId = _tpAuth.idsStudentId.isNotEmpty + ? _tpAuth.idsStudentId + : _tpAuth.idsAccount!.account; return '${_auth.session!.userId}|$campusId'; } - String get bookingStudentId { - if (profileOwner.isEmpty) return ''; - if (_tpAuth.cpdailyStudentId.isNotEmpty) return _tpAuth.cpdailyStudentId; - // Legacy SMS bindings have a UUID and phone but no school ID. Only a - // successful current-user OA response can supply their missing ID. - return ThirdPartyAccount.cpdailySchoolId( - _storage.loadOaBookingProfile(owner: profileOwner).studentId, - ); - } + String get bookingStudentId => profileOwner.isEmpty ? '' : _tpAuth.idsStudentId; String get _currentProfileBinding => profileOwner.isEmpty ? '' - : '$profileOwner|${_tpAuth.cpdailyBinding!.boundAt.toIso8601String()}'; + : '$profileOwner|${_tpAuth.idsAccount!.boundAt.toIso8601String()}'; /// Attach after boot hydration. Binding/rebinding starts a separate, /// best-effort read; login and court queries never wait for contact sync. @@ -145,11 +129,11 @@ class OaGymService extends ChangeNotifier { if (generation != _profileGeneration || owner != profileOwner) return; final data = (response['data'] as Map?)?.cast(); if (data == null) throw OaGymException('OA 个人信息响应不完整,请手动填写或重试'); - final studentId = ThirdPartyAccount.cpdailySchoolId(data['studentId']); + final studentId = ThirdPartyAccount.idsSchoolId(data['studentId']); if (studentId.isNotEmpty && - _tpAuth.cpdailyStudentId.isNotEmpty && - studentId != _tpAuth.cpdailyStudentId) { - throw OaGymException('OA 资料与当前 eGate 账号不匹配,请重新绑定'); + _tpAuth.idsStudentId.isNotEmpty && + studentId != _tpAuth.idsStudentId) { + throw OaGymException('OA 资料与当前 IDS 账号不匹配,请重新绑定'); } final incoming = OaBookingProfile.fromJson(data); if (revision != _profileRevision) return; @@ -214,10 +198,8 @@ class OaGymService extends ChangeNotifier { void clearSession() { _generation++; - _oaCookies = ''; _oaIdentity = ''; _metadataRequest = null; - _bulkSearchSupported = false; _sessionReady = false; _metadataReady = false; _venues = {}; @@ -232,14 +214,14 @@ class OaGymService extends ChangeNotifier { } final saved = _storage.loadOaBookingProfile(owner: profileOwner); // Contact sync enriches the bound school identity, never the Casdoor UUID. - final cpdailyName = _tpAuth.cpdailyBinding?.name; + final idsName = _tpAuth.idsAccount?.name; return saved.copyWith( name: saved.name.isNotEmpty ? saved.name - : (cpdailyName?.isNotEmpty == true ? cpdailyName! : ''), + : (idsName?.isNotEmpty == true ? idsName! : ''), email: saved.email.isNotEmpty ? saved.email - : (_tpAuth.cpdailyBinding?.email ?? ''), + : (_tpAuth.idsAccount?.email ?? ''), ); } @@ -291,7 +273,7 @@ class OaGymService extends ChangeNotifier { await previous; return await _withLoadingResult(() async { final result = []; - // Bound each backend call to one hour. OA's tree picker is stateful, + // Bound each local query to one hour. OA's tree picker is stateful, // so requests share one serial queue, including superseded UI checks. for (var slot = startSlot; slot <= endSlot; slot++) { if (generation != _generation || shouldContinue?.call() == false) { @@ -369,7 +351,7 @@ class OaGymService extends ChangeNotifier { throw OaGymException('请先在「个人信息」里补全姓名和手机号'); } if (studentId.isEmpty) { - throw OaGymException('当前 eGate 绑定缺少学号,请重新绑定 eGate'); + throw OaGymException('当前 IDS 绑定缺少学号,请重新绑定 IDS'); } final data = await _withLoadingResult( @@ -459,13 +441,7 @@ class OaGymService extends ChangeNotifier { } return _withLoadingResult(() async { - if (_bulkSearchSupported) { - final result = await query(venues, ranges); - onProgress?.call(result); - return result; - } - // Compatibility with older deployments: never send their unbounded - // venue × hour loop in one 30-second request. Three workers is enough. + // Bound local query batches so progress and cancellation can stop queued work. final jobs = [ for (final venue in venues) for (var i = 0; i < ranges.length; i += 3) @@ -518,8 +494,6 @@ class OaGymService extends ChangeNotifier { _allVenues = _stringMap(payload['allVenues']) ..removeWhere((name, id) => oaIsUnusedVenue(name) || id == '44'); _timeSlots = _stringMap(payload['timeSlots']); - _bulkSearchSupported = - (data['capabilities'] as Map?)?['bulkSearch'] == true; if (_venues.isEmpty || _timeSlots.isEmpty) { throw OaGymException('加载 OA 场馆数据失败,请稍后重试'); } @@ -545,115 +519,66 @@ class OaGymService extends ChangeNotifier { } /// Guard for any gym call: requires a logged-in primary account AND a - /// bound cpdaily account (the source of the CpDaily/CASTGC session the OA + /// bound ids account (the source of the IDS/CASTGC session the OA /// system authenticates against). AuthService _requireAuth() { if (!_auth.isLoggedIn) { throw OaGymException('请先登录 TechPie 主账号'); } - if (!_tpAuth.hasCpdailyBinding) { - throw OaGymException('场馆预约需要绑定 eGate 账号,请在「第三方账号」中绑定'); + if (!_tpAuth.hasIdsBinding) { + throw OaGymException('场馆预约需要绑定校园账号,请在「第三方账号」中绑定'); } return _auth; } - /// CpDaily auth payload built from a [CookieProvider] snapshot plus the - /// cpdaily node's raw session fields (tgc/sessionToken/userId/tenantId). The - /// cookie + epoch captured at request time drive the storm-safe renew-retry - /// in [_postJson]. - Map _authPayload(CookieProvider cp) { - final raw = _tpAuth.cpdailyNode.rawFields; - return { - 'tgc': (raw['tgc'] as String?) ?? '', - 'cookies': cp.cookies, - 'sessionToken': (raw['sessionToken'] as String?) ?? '', - 'userId': (raw['userId'] as String?) ?? '', - 'tenantId': (raw['tenantId'] as String?) ?? '', - if (_oaCookies.isNotEmpty) 'oaCookies': _oaCookies, - }; - } - - /// POST `$_baseUrl/[path]` with CpDaily auth + [extra] body fields. On 401 - /// the cpdaily node is renewed exactly once (single-flighted across all - /// concurrent callers) and the request retried with the fresh cookie. Future> _postJson( String path, - Map extra, + Map parameters, ) async { _requireAuth(); - final node = _tpAuth.cpdailyNode; - var identity = _identity; final generation = _generation; - final response = await _tpAuth.sessionTree.withCookie( - node, - (cp) async { - _syncIdentity(); - identity = _identity; - final body = {...extra, 'auth': _authPayload(cp)}; - http.Response r; - try { - r = await _client - .post( - Uri.parse('$_baseUrl/$path'), - headers: const { - 'Content-Type': 'application/json; charset=UTF-8', - }, - body: jsonEncode(body), - ) - .timeout(const Duration(seconds: 30)); - } on TimeoutException { - throw OaGymException( - path.endsWith('/book') - ? '预约提交超时,请先查询预约记录确认结果,避免重复提交' - : '学校 OA 查询超时,请稍后重试或缩小日期范围', - ); - } on http.ClientException { - throw OaGymException('无法连接场馆服务,请检查网络后重试'); - } - return CookieAction(r, expired: r.statusCode == 401); - }, - ); - if (response == null) { - throw OaGymException('当前 eGate 登录态已失效,请重新绑定 eGate'); - } - if (response.statusCode == 401) { - _sessionReady = false; - } - if (generation != _generation || identity != _identity) { - throw OaGymException('账号或登录态已变更,请重新查询'); - } - if (path == 'oa/gym/profile' && response.statusCode == 404) { - throw OaGymException('当前后端暂不支持自动同步,请手动填写个人信息'); - } - Map decoded; + var identity = _identity; try { - decoded = (jsonDecode(response.body) as Map).cast(); - } catch (_) { - throw OaGymException('场馆服务返回异常(HTTP ${response.statusCode}),请稍后重试'); - } - if (response.statusCode < 200 || - response.statusCode >= 300 || - decoded['success'] == false) { - throw OaGymException( - decoded['error'] as String? ?? 'OA 场馆服务请求失败,请稍后重试', + final result = await _tpAuth.sessionTree.withCookie?>( + _tpAuth.oaNode, + (cp) async { + _syncIdentity(); + identity = _identity; + try { + final data = await _localClient.request( + path, + parameters, + cookies: cp.cookies, + venues: _venues, + timeSlots: _timeSlots, + ); + return CookieAction(data, expired: false); + } on OaGymLocalException catch (error) { + if (!error.sessionExpired) rethrow; + return const CookieAction(null, expired: true); + } + }, ); + if (generation != _generation || identity != _identity) { + throw OaGymException('账号或登录态已变更,请重新查询'); + } + if (result == null) { + throw OaGymException('当前 OA 登录态已失效,请刷新 IDS 登录态后重试'); + } + return result; + } on OaGymLocalException catch (error) { + throw OaGymException(error.message); } - final session = decoded['session']; - if (session is Map && session['oaCookies'] is String) { - _oaCookies = session['oaCookies'] as String; - } - return decoded; } String get _identity => '${_auth.session?.userId}|' - '${_tpAuth.cpdailyBinding?.account}|${_tpAuth.cpdailyNode.epoch}|' - '${_tpAuth.cpdailyNode.rawFields['tgc']}'; + '${_tpAuth.idsAccount?.account}|${_tpAuth.idsNode.epoch}|' + '${_tpAuth.idsNode.rawFields['tgc']}'; void _syncIdentity() { _requireAuth(); if (_oaIdentity == _identity) return; _oaIdentity = _identity; - _oaCookies = ''; // Metadata contains school-wide IDs. It can survive an automatic token // renewal, but an explicit logout/unbind calls clearSession. } diff --git a/lib/services/schedule_service.dart b/lib/services/schedule_service.dart index 3bc8910d..2c0165e2 100644 --- a/lib/services/schedule_service.dart +++ b/lib/services/schedule_service.dart @@ -74,7 +74,7 @@ class ScheduleService extends ChangeNotifier { Timer? _pendingFetch; String? _campusAccount() { - final account = _tpAuth.cpdailyNode.account; + final account = _tpAuth.idsNode.account; if (account == null) return null; return '${account.sid}|${account.account}'; } @@ -147,12 +147,12 @@ class ScheduleService extends ChangeNotifier { /// time. The epoch captured alongside is what makes the renew-retry /// storm-safe (see [_postWithRetry]). Map _authBody(CookieProvider cp) => { - // eams downstream cookie; studentId comes from the cpdaily binding. - 'studentId': _tpAuth.cpdailyNode.account?.sid ?? '', + // eams downstream cookie; studentId comes from the ids binding. + 'studentId': _tpAuth.idsNode.account?.sid ?? '', 'cookies': cp.cookies, }; - bool get _hasCpdailyBinding => _tpAuth.cpdailyNode.isAvailable; + bool get _hasIdsBinding => _tpAuth.hasIdsBinding; // ── Sessions the user entered by hand ── // Read straight from storage, so no second copy can go stale on a semester @@ -219,7 +219,7 @@ class ScheduleService extends ChangeNotifier { Future fetchAll() async { if (_loading) return; // 避免启动时并发重复调用 - if (!_hasCpdailyBinding) return; + if (!_hasIdsBinding) return; _loading = true; _error = null; notifyListeners(); @@ -348,7 +348,7 @@ class ScheduleService extends ChangeNotifier { _suppressAssignmentRefetch = true; notifyListeners(); - if (!_hasCpdailyBinding) { + if (!_hasIdsBinding) { _suppressAssignmentRefetch = false; return; } @@ -375,11 +375,11 @@ class ScheduleService extends ChangeNotifier { } } - /// POST [url] with CpDaily auth + [extra] body fields. On 401 the eams + /// POST [url] with IDS auth + [extra] body fields. On 401 the eams /// node is renewed exactly once (single-flighted across all concurrent /// callers) and the request retried with the fresh cookie. For a stale /// parent tgc, [SessionTree.withCookie] falls back to renewing the - /// cpdaily parent then re-minting the eams cookie. Throws on any non-200 + /// ids parent then re-minting the eams cookie. Throws on any non-200 /// after the retry budget is exhausted. Future _postWithRetry( String url, @@ -404,7 +404,7 @@ class ScheduleService extends ChangeNotifier { }, ); if (resp == null) { - throw Exception('cpdaily session unavailable'); + throw Exception('ids session unavailable'); } if (resp.statusCode != 200) { throw Exception('Request failed with status ${resp.statusCode}'); diff --git a/lib/services/session/cookie_provider.dart b/lib/services/session/cookie_provider.dart index 80372bcd..d2f32d54 100644 --- a/lib/services/session/cookie_provider.dart +++ b/lib/services/session/cookie_provider.dart @@ -3,8 +3,8 @@ import 'package:flutter/foundation.dart'; /// A read-only snapshot of cookies + identity a downstream consumer (campus /// service, webview feature) injects into its requests. /// -/// Implementations: [CpdailyCookieProvider] (CASTGC-bearing CpDaily session), -/// [IdsCookieProvider] (IDS SSO cookies minted from the CpDaily session), and +/// Implementations: [IdsCookieProvider] (CASTGC-bearing IDS session), +/// [IdsCookieProvider] (IDS SSO cookies minted from the IDS session), and /// a no-op empty view for leaf nodes that expose no cookies (Gradescope/Hydro /// work via bearer tokens server-side, not browser cookies). @immutable diff --git a/lib/services/session/session_node.dart b/lib/services/session/session_node.dart index 72132b2e..3a244d50 100644 --- a/lib/services/session/session_node.dart +++ b/lib/services/session/session_node.dart @@ -7,13 +7,14 @@ import 'package:http/http.dart' as http_pkg; import '../../models/renew_status.dart'; import '../../models/third_party_account.dart'; import '../http_client.dart'; +import '../ids/campus_http.dart'; import 'cookie_provider.dart'; /// Callback the facade ([ThirdPartyAuthService]) installs so a top-level /// node can persist a refreshed [ThirdPartyAccount] back into secure storage /// and fire the external change notification (listeners + cloud-sync push /// hook) in one place. Returns nothing; the node owns the in-memory account -/// afterwards. Only meaningful for top-level nodes (renewMode cpdailySession +/// afterwards. Only meaningful for top-level nodes (renewMode idsPasskey /// or password); non-top-level nodes skip persist (derived cookies are /// ephemeral). [force] requests the cloud-sync push bypass its throttle — /// set by renew() call sites since a successful renew must not wait for the @@ -51,7 +52,7 @@ typedef BaseUrlGetter = String Function(); /// Determines how a node calculates its next scheduled renewal. enum RenewSchedule { none, - cpdailyDefault, + idsDefault, accountExpiry, derivedCookie, } @@ -167,16 +168,14 @@ String _mergeSetCookie(String existing, String setCookieHeader) { /// How a [SessionNode] renews its credentials. enum RenewMode { - /// CpDaily session keep-alive: POST /auth/renew with stored - /// sessionToken/tgc/userId/tenantId. Top-level only. - cpdailySession, + /// Local IDS software Passkey login. Top-level campus session only. + idsPasskey, /// Password re-authentication: POST /auth/third-party/`` with /// account/password. Top-level only (gradescope, hydro). password, - /// Downstream cookie minting: POST /auth/third-party/`` with the parent - /// node's tgc. Non-top-level only (eams, elearning). + /// Local CAS cookie exchange using the parent IDS session. parentCookie, } @@ -185,17 +184,18 @@ enum RenewMode { /// Topology: /// ``` /// SessionTree -/// ├── cpdaily (top-level, account+password/SMS bind, /auth/renew) -/// │ ├── eams (child, /auth/third-party/eams, parent tgc) -/// │ ├── elearning (child, /auth/third-party/elearning, parent tgc) -/// │ └── egateApp (child, /auth/third-party/egate-app, parent tgc) +/// ├── ids (local IDS software Passkey login) +/// │ ├── eams (child, local CAS login) +/// │ ├── elearning (child, local CAS login) +/// │ ├── egateApp (child, local CAS login) +/// │ └── oa (child, local CAS login) /// ├── gradescope (top-level, account+password bind, bearer token) /// └── hydro (top-level, account+password bind, sid cookie) /// ``` /// /// Every node exposes: /// - [cookieProvider] — the [CookieProvider] view downstream apps read. For -/// top-level nodes the credential comes from the bound account (cpdaily: +/// top-level nodes the credential comes from the bound account (ids: /// CASTGC+cookies; gradescope/hydro: bearer token). For non-top-level /// nodes it comes from the derived downstream cookie string. /// - [renew()] — refresh this node's credentials. Single-flighted: concurrent @@ -217,6 +217,9 @@ class SessionNode extends ChangeNotifier { this.renewPath, this.renewMode, this.apiPath, + this.localAccountRenew, + this.localCanRenew, + this.localCookieMint, this.persistDerived, this.recordRenewStatus, this.persistProbe, @@ -225,25 +228,25 @@ class SessionNode extends ChangeNotifier { this.keepaliveConfig, }); - /// Stable identifier (matches storage key / platform id, except cpdaily - /// whose storage id is 'cpdaily' but whose backend bind route is 'egate'). + /// Stable identifier matching the platform id for top-level nodes. final String id; /// Optional parent — set when this node's session is derived from another - /// (e.g. eams/elearning cookies are minted from the cpdaily CASTGC). Null + /// (e.g. eams/elearning cookies are minted from the ids CASTGC). Null /// for roots. SessionNode? parent; - /// Full backend renew path (e.g. '/auth/renew', '/auth/third-party/eams'). + /// Backend renew path for non-campus token services (Gradescope/Hydro). final String? renewPath; /// How this node renews. Null only for nodes that never renew. final RenewMode? renewMode; - /// Backend bind route name. For cpdaily this is 'egate' (the backend route - /// was not renamed); for gradescope/hydro it equals [id]. Null for - /// non-top-level nodes. + /// Backend bind route name for password services (Gradescope/Hydro). final String? apiPath; + final Future Function(ThirdPartyAccount current)? localAccountRenew; + final bool Function()? localCanRenew; + final Future Function(String nodeId, Map root)? localCookieMint; final PersistAccount persist; final PersistDerivedCookie? persistDerived; final PersistRenewStatus? recordRenewStatus; @@ -278,11 +281,7 @@ class SessionNode extends ChangeNotifier { /// (OA gym) and child nodes read tgc/sessionToken/userId/tenantId through /// this. Returns an empty map for non-top-level nodes. Map get rawFields { - final acc = _account; - if (id == 'cpdaily' && acc != null && acc.cpdailyUserId.isNotEmpty) { - return {...acc.raw, 'userId': acc.cpdailyUserId}; - } - return acc?.raw ?? const {}; + return _account?.raw ?? const {}; } void setAccount(ThirdPartyAccount? acc) { @@ -296,6 +295,7 @@ class SessionNode extends ChangeNotifier { void setDerivedCookie(String? cookie) { if (parent == null) return; // top-level: no derived cookie _derivedCookie = (cookie != null && cookie.isNotEmpty) ? cookie : null; + if (_derivedCookie == null) _lastProbeDisplay = null; _nextRenewTimestamp = _derivedCookie == null ? null : (_nextRenewTimestamp ?? _defaultNextRenewTimestamp()); @@ -326,21 +326,23 @@ class SessionNode extends ChangeNotifier { if (cookie.isEmpty) return null; return CookieProvider( cookies: cookie, - studentId: id == 'cpdaily' ? acc.cpdailyStudentId : acc.sid ?? '', + studentId: id == 'ids' ? acc.idsStudentId : acc.sid ?? '', domain: _domain, ); } // Non-top-level: derived cookie final c = _derivedCookie; - if (c == null || c.isEmpty) return null; + if (parent?.isAvailable != true || c == null || c.isEmpty) return null; return CookieProvider(cookies: c, domain: _domain); } - /// Top-level credential extraction: cpdaily concatenates CASTGC onto the + /// Top-level credential extraction: ids concatenates CASTGC onto the /// session cookies; gradescope/hydro use the bearer token directly. String _cookieFromAccount(ThirdPartyAccount acc) { - if (id == 'cpdaily') { + if (id == 'ids') { + if (acc.raw['authMethod'] != 'passkey') return ''; final base = (acc.raw['cookies'] as String?) ?? ''; + if (RegExp(r'(^|;)\s*CASTGC=').hasMatch(base)) return base; final tgc = (acc.raw['tgc'] as String?) ?? ''; return tgc.isEmpty ? base @@ -350,10 +352,11 @@ class SessionNode extends ChangeNotifier { } String get _domain => switch (id) { - 'cpdaily' => 'ids.shanghaitech.edu.cn', + 'ids' => 'ids.shanghaitech.edu.cn', 'eams' => 'eams.shanghaitech.edu.cn', 'elearning' => 'elearning.shanghaitech.edu.cn', 'egateApp' => 'egate.shanghaitech.edu.cn', + 'oa' => 'oa.shanghaitech.edu.cn', _ => '', }; @@ -369,16 +372,33 @@ class SessionNode extends ChangeNotifier { } bool get canRenew { - if (parent != null) return parent!.isAvailable; - if (renewMode == RenewMode.cpdailySession) return _account != null; + if (parent != null) return parent!.isAvailable || parent!.canRenew; + if (renewMode == RenewMode.idsPasskey) { + return _account?.raw['authMethod'] == 'passkey' && (localCanRenew?.call() ?? true); + } return _account?.autoRenew == true && _account?.password?.isNotEmpty == true; } /// Human-readable display name for this node, suitable for UI labels. /// - /// Priority: most recent successful probe display > account name > id. - String get displayName => _lastProbeDisplay ?? _account?.name ?? id; + /// Campus identities come from the authenticated root profile. Probe text + /// describes connectivity and must never replace a user name or student ID. + String get displayName { + final owner = parent?.account; + if (parent != null) { + if (owner == null) return '未绑定'; + if (id == 'eams' || id == 'egateApp') { + final studentId = owner.idsStudentId; + if (studentId.isNotEmpty) return studentId; + } + return owner.displayName; + } + if (_account != null) return _account!.displayName; + return '未绑定'; + } + + String get probeDisplay => _lastProbeDisplay ?? '尚未检测'; /// The next scheduled renewal event for this node. DateTime? _nextRenewTimestamp; @@ -392,9 +412,7 @@ class SessionNode extends ChangeNotifier { DateTime? _defaultNextRenewTimestamp() { final now = DateTime.now(); return switch (renewSchedule) { - RenewSchedule.cpdailyDefault => _account?.expireAt?.subtract( - const Duration(days: 3), - ), + RenewSchedule.idsDefault => now.add(const Duration(minutes: 10)), RenewSchedule.accountExpiry => _account?.expireAt?.subtract( const Duration(hours: 48), ), @@ -414,7 +432,8 @@ class SessionNode extends ChangeNotifier { } Future renewIfDue() async { - if (!isAvailable || !canRenew) return false; + if (!canRenew) return false; + if (!isAvailable) return renew(); if (!isRenewDue) return true; return renew(); } @@ -437,6 +456,7 @@ class SessionNode extends ChangeNotifier { /// downstream endpoint won't be fixed by re-minting the parent tgc, so we /// skip the escalation entirely. bool _lastRenewWasCredentialError = false; + String? lastRenewError; bool get lastRenewWasCredentialError => _lastRenewWasCredentialError; /// Outcome of the most recent renew attempt (this session, or seeded from @@ -510,6 +530,15 @@ class SessionNode extends ChangeNotifier { if (cp == null || cp.isEmpty) { return const KeepaliveResult(false, display: 'no session'); } + final owner = _account; + final parentOwner = parent?.account; + final beforeEpoch = _epoch; + final parentEpoch = parent?.epoch; + bool stillCurrent() => + identical(_account, owner) && + identical(parent?.account, parentOwner) && + _epoch == beforeEpoch && + parent?.epoch == parentEpoch; String cookies = cp.cookies; // Pre-flight: hit config endpoint to refresh session tokens (e.g. _WEU). if (cfg.preFlightPath != null) { @@ -565,6 +594,7 @@ class SessionNode extends ChangeNotifier { tag: 'keepalive:$id', ); } + if (!stillCurrent()) return const KeepaliveResult(false, display: 'session changed'); final ok = cfg.successCheck?.call(resp) ?? cfg.bodyRegex?.hasMatch(resp.body) ?? (resp.statusCode == 200); @@ -577,8 +607,13 @@ class SessionNode extends ChangeNotifier { } else { display = 'HTTP ${resp.statusCode}'; } + if (display.trim().isEmpty) display = 'HTTP ${resp.statusCode}'; + _lastProbeDisplay = ok + ? display + : resp.statusCode == 403 + ? 'HTTP 403(当前账号无此页面权限)' + : 'HTTP ${resp.statusCode}'; if (ok) { - _lastProbeDisplay = display; if (silent && parent != null && cookies.isNotEmpty) { _derivedCookie = cookies; await scheduleNextRenew(); @@ -587,7 +622,7 @@ class SessionNode extends ChangeNotifier { } return KeepaliveResult( ok, - display: ok ? display : 'HTTP ${resp.statusCode}', + display: _lastProbeDisplay!, statusCode: resp.statusCode, rawBody: resp.body, cookies: cookies, @@ -602,8 +637,8 @@ class SessionNode extends ChangeNotifier { /// success. Returns true on success, false on failure. Future doRenew() async { switch (renewMode) { - case RenewMode.cpdailySession: - return _renewCpdailySession(); + case RenewMode.idsPasskey: + return _renewIdsSession(); case RenewMode.password: return _renewWithPassword(); case RenewMode.parentCookie: @@ -613,56 +648,21 @@ class SessionNode extends ChangeNotifier { } } - /// CpDaily keep-alive: POST /auth/renew with stored session fields. - Future _renewCpdailySession() async { - final acc = _account; - if (acc == null) return false; + /// Refresh IDS directly with the app-owned software credential. + Future _renewIdsSession() async { + final current = _account; + if (current == null || localAccountRenew == null) return false; try { - final resp = await http.post( - Uri.parse('${baseUrl()}${renewPath ?? '/auth/renew'}'), - headers: {'Content-Type': 'application/json; charset=UTF-8'}, - body: jsonEncode({ - 'sessionToken': acc.raw['sessionToken'] ?? '', - 'tgc': acc.raw['tgc'] ?? '', - 'userId': acc.cpdailyUserId, - 'tenantId': acc.raw['tenantId'] ?? '', - }), - tag: 'cpdailyRenew', - ); - if (resp.statusCode != 200) return false; - final data = jsonDecode(resp.body) as Map; - if (data['success'] != true) return false; - - final newRaw = { - ...acc.raw, - 'sessionToken': - data['sessionToken'] as String? ?? acc.raw['sessionToken'] ?? '', - 'tgc': data['tgc'] as String? ?? acc.raw['tgc'] ?? '', - 'userId': data['userId'] as String? ?? acc.cpdailyUserId, - 'tenantId': data['tenantId'] as String? ?? acc.raw['tenantId'] ?? '', - 'cookies': data['cookies'] as String? ?? acc.raw['cookies'] ?? '', - }; - final updated = ThirdPartyAccount( - platform: acc.platform, - account: acc.account, - sid: data['sid'] as String? ?? acc.sid, - name: data['name'] as String? ?? acc.name, - email: data['email'] as String? ?? acc.email, - token: acc.token, - expire: acc.expire, - raw: newRaw, - hydroOrigin: acc.hydroOrigin, - hydroDomains: acc.hydroDomains, - boundAt: acc.boundAt, - autoRenew: acc.autoRenew, - password: acc.password, - ); + final updated = await localAccountRenew!(current); + if (!identical(_account, current)) return false; _account = updated; - // force: true — a successful renew must push to the cloud immediately, - // not wait for the pushIfDue throttle window. - await persist(updated, force: true); markRenewed(); + await persist(updated); return true; + } on IdsException catch (error) { + _lastRenewWasCredentialError = error.credentialRejected; + lastRenewError = error.message; + return false; } catch (_) { return false; } @@ -723,42 +723,29 @@ class SessionNode extends ChangeNotifier { } } - /// Downstream cookie minting (eams, elearning): POST the parent's tgc, - /// receive a downstream cookie string. + /// Obtain the downstream session locally through its existing CAS flow. Future _renewWithParentCookie() async { - final tgc = parent?.rawFields['tgc'] as String? ?? ''; - if (tgc.isEmpty) { + final root = parent?.account; + final parentEpoch = parent?.epoch; + if (root == null || parent?.isAvailable != true || (root.raw['tgc'] as String? ?? '').isEmpty) { _lastRenewWasCredentialError = true; return false; } + if (localCookieMint == null) return false; try { - final resp = await http.post( - Uri.parse('${baseUrl()}${renewPath ?? '/auth/third-party/$id'}'), - headers: {'Content-Type': 'application/json; charset=UTF-8'}, - body: jsonEncode({'tgc': tgc}), - tag: 'downstreamRenew:$id', - ); - // 401 → parent tgc is stale/invalid → credential error (worth - // escalating to parent renew). 5xx → server/transient failure → - // NOT a credential error (escalation won't help). - _lastRenewWasCredentialError = resp.statusCode == 401; - if (resp.statusCode != 200) return false; - final data = jsonDecode(resp.body) as Map; - if (data['success'] != true) return false; - final d = (data['data'] as Map?)?.cast() ?? const {}; - final cookie = d['token'] as String?; - if (cookie == null || cookie.isEmpty) return false; + final cookie = await localCookieMint!(id, root.raw); + if (!identical(parent?.account, root) || parent?.epoch != parentEpoch) return false; _derivedCookie = cookie; - // Persist so cold start can skip the SSO bounce. final pd = persistDerived; - if (pd != null) { - unawaited(pd(id, cookie)); - } - // markRenewed cascades to children (none here) but does NOT notify - // this node — notify explicitly for the downstream cookie change. + if (pd != null) await pd(id, cookie); + if (!identical(parent?.account, root) || parent?.epoch != parentEpoch) return false; markRenewed(); notifyListeners(); return true; + } on IdsException catch (error) { + _lastRenewWasCredentialError = error.credentialRejected; + lastRenewError = error.message; + return false; } catch (_) { _lastRenewWasCredentialError = false; return false; @@ -786,10 +773,22 @@ class SessionNode extends ChangeNotifier { /// new notify here, to avoid the double-notify storm [markRenewed]'s doc /// comment already explains avoiding. Future _renewTracked() async { + _lastRenewWasCredentialError = false; + lastRenewError = null; final ok = await doRenew(); if (ok) await scheduleNextRenew(); if (ok && keepaliveConfig != null) { + final owner = _account; + final parentOwner = parent?.account; + final beforeEpoch = _epoch; + final parentEpoch = parent?.epoch; final result = await probe(silent: true); + if (!identical(_account, owner) || + !identical(parent?.account, parentOwner) || + _epoch != beforeEpoch || + parent?.epoch != parentEpoch) { + return false; + } if (result.success) { final persist = persistProbe; if (persist != null) await persist(id, result); @@ -800,7 +799,7 @@ class SessionNode extends ChangeNotifier { success: ok, error: ok ? null - : (_lastRenewWasCredentialError ? 'credential' : 'transient'), + : (lastRenewError ?? (_lastRenewWasCredentialError ? 'credential' : 'transient')), ); _lastRenewAt = status.at; _lastRenewSucceeded = ok; @@ -819,7 +818,7 @@ class SessionNode extends ChangeNotifier { /// concurrent caller (epoch advanced). Returns false only when a renew /// actually ran and failed, or the node is unavailable. Future renewIfNeeded(int beforeEpoch) async { - if (!isAvailable) return false; + if (!isAvailable && !canRenew) return false; // A concurrent renew already advanced past the caller's snapshot — // the cookies the caller will re-read are already fresh. Skip. if (_epoch > beforeEpoch) return true; diff --git a/lib/services/session/session_tree.dart b/lib/services/session/session_tree.dart index 96b28a81..eb076aa9 100644 --- a/lib/services/session/session_tree.dart +++ b/lib/services/session/session_tree.dart @@ -13,10 +13,11 @@ import 'session_node.dart'; /// Topology (built once at construction): /// ``` /// SessionTree -/// ├── cpdaily (top-level, account+password/SMS bind, /auth/renew) -/// │ ├── eams (child, /auth/third-party/eams, parent tgc) -/// │ ├── elearning (child, /auth/third-party/elearning, parent tgc) -/// │ └── egateApp (child, /auth/third-party/egate-app, parent tgc) +/// ├── ids (local IDS software Passkey login) +/// │ ├── eams (child, local CAS login) +/// │ ├── elearning (child, local CAS login) +/// │ ├── egateApp (child, local CAS login) +/// │ └── oa (child, local CAS login) /// ├── gradescope (top-level, account+password bind, bearer token) /// └── hydro (top-level, account+password bind, sid cookie) /// ``` @@ -29,23 +30,26 @@ class SessionTree extends ChangeNotifier { required this.persist, required this.http, required this.baseUrl, + this.localAccountRenew, + this.localCanRenew, + this.localCookieMint, this.persistDerived, this.recordRenewStatus, this.persistProbe, this.persistRenewTimestamp, }) { - cpdaily = SessionNode( - id: 'cpdaily', + ids = SessionNode( + id: 'ids', persist: persist, http: http, baseUrl: baseUrl, - renewPath: '/auth/renew', - renewMode: RenewMode.cpdailySession, - apiPath: 'egate', + renewMode: RenewMode.idsPasskey, + localAccountRenew: localAccountRenew, + localCanRenew: localCanRenew, recordRenewStatus: recordRenewStatus, persistProbe: persistProbe, persistRenewTimestamp: persistRenewTimestamp, - renewSchedule: RenewSchedule.cpdailyDefault, + renewSchedule: RenewSchedule.idsDefault, ); gradescope = SessionNode( id: 'gradescope', @@ -80,8 +84,8 @@ class SessionTree extends ChangeNotifier { persist: persist, http: http, baseUrl: baseUrl, - parent: cpdaily, - renewPath: '/auth/third-party/eams', + parent: ids, + localCookieMint: localCookieMint, renewMode: RenewMode.parentCookie, persistDerived: persistDerived, recordRenewStatus: recordRenewStatus, @@ -98,8 +102,8 @@ class SessionTree extends ChangeNotifier { persist: persist, http: http, baseUrl: baseUrl, - parent: cpdaily, - renewPath: '/auth/third-party/elearning', + parent: ids, + localCookieMint: localCookieMint, renewMode: RenewMode.parentCookie, persistProbe: persistProbe, persistRenewTimestamp: persistRenewTimestamp, @@ -118,8 +122,8 @@ class SessionTree extends ChangeNotifier { persist: persist, http: http, baseUrl: baseUrl, - parent: cpdaily, - renewPath: '/auth/third-party/egate-app', + parent: ids, + localCookieMint: localCookieMint, persistProbe: persistProbe, renewSchedule: RenewSchedule.derivedCookie, persistRenewTimestamp: persistRenewTimestamp, @@ -142,13 +146,21 @@ class SessionTree extends ChangeNotifier { final data = jsonDecode(r.body); final rows = ((data['datas'] as Map?)?['hqdlxsjpcxx'] as Map?)?['rows'] as List?; - return (rows?.firstOrNull as Map?)?['XSBH'] as String? ?? 'egateApp'; + return (rows?.firstOrNull as Map?)?['XSBH'] as String? ?? ''; }, ), ); - cpdaily.attachChild(eams); - cpdaily.attachChild(elearning); - cpdaily.attachChild(egateApp); + oa = SessionNode( + id: 'oa', persist: persist, http: http, baseUrl: baseUrl, + parent: ids, renewMode: RenewMode.parentCookie, + localCookieMint: localCookieMint, persistDerived: persistDerived, + recordRenewStatus: recordRenewStatus, persistRenewTimestamp: persistRenewTimestamp, + renewSchedule: RenewSchedule.derivedCookie, + ); + ids.attachChild(oa); + ids.attachChild(eams); + ids.attachChild(elearning); + ids.attachChild(egateApp); // Only top-level node notifications propagate up to the tree (facade → // UI / sync / auto-refetch). Child nodes (eams/elearning) mint cookies @@ -156,10 +168,13 @@ class SessionTree extends ChangeNotifier { // trigger _onDepsChanged → fetchAssignments → re-mint, a feedback loop. // Child notifications still fire for direct listeners on the node itself // (e.g. withCookie's epoch checks read node state directly, not via tree). - for (final n in [cpdaily, gradescope, hydro]) { + for (final n in [ids, gradescope, hydro]) { n.addListener(notifyListeners); } } + final Future Function(ThirdPartyAccount current)? localAccountRenew; + final bool Function()? localCanRenew; + final Future Function(String nodeId, Map root)? localCookieMint; final PersistAccount persist; final PersistDerivedCookie? persistDerived; final PersistProbe? persistProbe; @@ -168,20 +183,21 @@ class SessionTree extends ChangeNotifier { final LoggingHttpClient http; final BaseUrlGetter baseUrl; - late final SessionNode cpdaily; + late final SessionNode ids; late final SessionNode gradescope; late final SessionNode hydro; late final SessionNode eams; late final SessionNode elearning; late final SessionNode egateApp; + late final SessionNode oa; /// All top-level nodes in a stable order. - List get roots => [cpdaily, gradescope, hydro]; + List get roots => [ids, gradescope, hydro]; /// Lookup a top-level node by [ThirdPartyPlatform]. Child nodes (eams/ /// elearning) are accessed directly via [eams]/[elearning]. SessionNode nodeFor(ThirdPartyPlatform p) => switch (p) { - ThirdPartyPlatform.cpdaily => cpdaily, + ThirdPartyPlatform.ids => ids, ThirdPartyPlatform.gradescope => gradescope, ThirdPartyPlatform.hydro => hydro, }; @@ -201,6 +217,7 @@ class SessionTree extends ChangeNotifier { 'eams' => eams, 'elearning' => elearning, 'egateApp' => egateApp, + 'oa' => oa, _ => null, }; node?.setDerivedCookie(cookie); @@ -219,7 +236,7 @@ class SessionTree extends ChangeNotifier { /// a credential error (HTTP 401 = parent tgc stale). Server errors (5xx) /// and network failures do NOT escalate — re-minting the parent tgc won't /// fix a broken backend, so the escalation is skipped to avoid wasteful - /// /auth/renew calls. + /// parent authentication attempts. /// /// Retry budget: at most 1 child renew (first level) + 1 parent renew + /// 1 child re-mint (second level) per withCookie call. The single-flight @@ -244,7 +261,7 @@ class SessionTree extends ChangeNotifier { // credential error (HTTP 401 = parent tgc stale). A 500 from the // downstream endpoint is a server error — re-minting the parent tgc // won't fix it, so we skip the escalation and return null immediately. - // This prevents wasteful /auth/renew calls on transient backend errors. + // Transient service errors do not need a new IDS login. if (node.parent == null) return null; if (!node.lastRenewWasCredentialError) return null; final parentOk = await node.parent!.renewIfNeeded(node.parent!.epoch); @@ -301,7 +318,7 @@ class SessionTree extends ChangeNotifier { Future _ensureUsable(SessionNode node) async { if (node.parent != null && node.parent!.canRenew && - node.parent!.isRenewDue) { + (!node.parent!.isAvailable || node.parent!.isRenewDue)) { final parentOk = await node.parent!.renewIfDue(); if (!parentOk) return false; } @@ -312,10 +329,10 @@ class SessionTree extends ChangeNotifier { @override void dispose() { - for (final n in [cpdaily, gradescope, hydro]) { + for (final n in [ids, gradescope, hydro]) { n.removeListener(notifyListeners); } - for (final n in [cpdaily, gradescope, hydro, eams, elearning, egateApp]) { + for (final n in [ids, gradescope, hydro, eams, elearning, egateApp, oa]) { n.dispose(); } super.dispose(); diff --git a/lib/services/storage_service.dart b/lib/services/storage_service.dart index 9037dc6b..7c4e2bab 100644 --- a/lib/services/storage_service.dart +++ b/lib/services/storage_service.dart @@ -14,11 +14,13 @@ import 'package:shared_preferences/shared_preferences.dart'; import '../models/assignment_overrides.dart'; import '../models/course_table.dart'; import '../models/custom_course.dart'; +import '../models/ids_passkey.dart'; import '../models/oa_gym.dart'; import '../models/renew_status.dart'; import '../models/third_party_account.dart'; import '../models/user_session.dart'; import '../utils/secure_storage.dart'; +import 'sync_envelope.dart'; class StorageService { static const _sessionKey = 'user_session'; @@ -57,8 +59,32 @@ class StorageService { await _secure.delete(key: _sessionKey); } + Future saveIdsCandidate(String account, IdsPasskey credential) => + _secure.write(key: 'third_party_ids_pending', value: jsonEncode({'account': account, 'credential': credential.toJson()})); + + Future<({String account, IdsPasskey credential})?> loadIdsCandidate() async { + final value = await _secure.read(key: 'third_party_ids_pending'); + if (value == null) return null; + final json = jsonDecode(value) as Map; + return (account: json['account'] as String, credential: IdsPasskey.fromJson((json['credential'] as Map).cast())); + } + + Future clearIdsCandidate() => _secure.delete(key: 'third_party_ids_pending'); + String? get idsBackedUpId => _prefs.getString('third_party_ids_backed_up_id'); + Future markIdsBackedUp(String id) => _prefs.setString('third_party_ids_backed_up_id', id); + + List loadThirdPartyTombstones() => + (jsonDecode(_prefs.getString('third_party_tombstones') ?? '[]') as List) + .map((entry) => SyncTombstone.fromJson((entry as Map).cast())).toList(); + Future saveThirdPartyTombstones(List tombstones) => + _prefs.setString('third_party_tombstones', jsonEncode(tombstones.map((t) => t.toJson()).toList())); + // Secure third-party account storage (one secure key per platform) static const _thirdPartyKeyPrefix = 'third_party_'; + static const _legacyCampusKeys = [ + '${_thirdPartyKeyPrefix}cpdaily', + '${_thirdPartyKeyPrefix}egate', + ]; String _thirdPartyKey(ThirdPartyPlatform p) => '$_thirdPartyKeyPrefix${p.id}'; Future saveThirdPartyAccount(ThirdPartyAccount acc) async { @@ -84,23 +110,21 @@ class StorageService { final result = []; for (final p in ThirdPartyPlatform.values) { var acc = await loadThirdPartyAccount(p); - // One-time migration: cpdaily was previously stored under the legacy - // 'egate' key (platform id before the rename). If the new key is empty - // but the legacy key has data, adopt it and delete the old key. - if (p == ThirdPartyPlatform.cpdaily && acc == null) { - const legacyKey = '${_thirdPartyKeyPrefix}egate'; - final raw = await _secure.read(key: legacyKey); - if (raw != null) { + // Read published campus accounts under their old keys. All writes use ids. + if (p == ThirdPartyPlatform.ids && acc == null) { + for (final legacyKey in _legacyCampusKeys) { + final raw = await _secure.read(key: legacyKey); + if (raw == null) continue; try { acc = ThirdPartyAccount.fromJson( jsonDecode(raw) as Map, ); - await _secure.write(key: _thirdPartyKey(p), value: raw); - await _secure.delete(key: legacyKey); } catch (_) { - // Corrupt legacy entry — leave it; clearThirdPartyAccount can - // still remove it via the fromId alias path. + continue; } + await saveThirdPartyAccount(acc); + await _secure.delete(key: legacyKey); + break; } } if (acc != null) result.add(acc); @@ -110,11 +134,16 @@ class StorageService { Future clearThirdPartyAccount(ThirdPartyPlatform p) async { await _secure.delete(key: _thirdPartyKey(p)); + if (p == ThirdPartyPlatform.ids) { + for (final key in _legacyCampusKeys) { + await _secure.delete(key: key); + } + } } Future clearAllThirdPartyAccounts() async { for (final p in ThirdPartyPlatform.values) { - await _secure.delete(key: _thirdPartyKey(p)); + await clearThirdPartyAccount(p); } } @@ -138,12 +167,12 @@ class StorageService { } Future clearAllDerivedCookies() async { - for (final id in const ['eams', 'elearning', 'egateApp']) { + for (final id in const ['eams', 'elearning', 'egateApp', 'oa']) { await _secure.delete(key: '$_derivedCookieKeyPrefix$id'); } } - // Renew status (last attempt outcome per session-node id: cpdaily, + // Renew status (last attempt outcome per session-node id: ids, // gradescope, hydro, eams, elearning). Local-only UI signal, never synced. static const _renewStatusKeyPrefix = 'renew_status_'; @@ -187,6 +216,11 @@ class StorageService { !kReleaseMode && (_prefs.getBool(_debugModeKey) ?? false); Future setDebugMode(bool value) => _prefs.setBool(_debugModeKey, value); + bool get debugForceIdsRebindBanner => + !kReleaseMode && (_prefs.getBool('debug_force_ids_rebind_banner') ?? false); + Future setDebugForceIdsRebindBanner(bool value) => + _prefs.setBool('debug_force_ids_rebind_banner', value); + String get cachedSchoolName => _prefs.getString(_schoolNameKey) ?? ''; Future setCachedSchoolName(String name) => _prefs.setString(_schoolNameKey, name); diff --git a/lib/services/sync_crypto.dart b/lib/services/sync_crypto.dart index f0a3531b..3583b0f3 100644 --- a/lib/services/sync_crypto.dart +++ b/lib/services/sync_crypto.dart @@ -6,7 +6,7 @@ import 'package:cryptography/cryptography.dart'; /// End-to-end encryption helpers for the cloud-sync feature. /// /// The sync blob stored in Casdoor `User.properties["techpie_sync"]` holds the -/// user's third-party account bindings (eGate CASTGC session, Gradescope/Hydro +/// user's third-party account bindings (IDS software Passkey, Gradescope/Hydro /// tokens, and optionally their stored passwords). It MUST be unreadable to the /// server. We use a user-chosen master password — the only secret that never /// leaves the device — to derive an AES-256-GCM key via PBKDF2. The server diff --git a/lib/services/sync_envelope.dart b/lib/services/sync_envelope.dart index 33181059..d199f8ca 100644 --- a/lib/services/sync_envelope.dart +++ b/lib/services/sync_envelope.dart @@ -1,6 +1,7 @@ import 'dart:convert'; import '../models/ecard_sync_binding.dart'; +import '../models/ids_passkey.dart'; import '../models/third_party_account.dart'; /// Schema version of the cloud-sync blob's plaintext envelope. @@ -15,10 +16,13 @@ import '../models/third_party_account.dart'; /// so per-platform LWW merge can distinguish "deleted on device A" /// from "never had it on device A". Per-account `updatedAt` + /// `deviceId` drive the merge. -/// v3 — current: adds the optional `ecard` binding, which carries the eCard +/// v3: adds the optional `ecard` binding, which carries the eCard /// *login parameter* only — cookies, identity pins and keys stay on the /// device — and keeps top-level fields this build does not know, so a /// blob written by a newer build survives a round trip through this one. +/// v4: campus accounts use the `ids` platform id and can carry an exportable +/// software Passkey in `raw.credential`. Passkey session cookies stay +/// device-local; bindings and deletions still use `accounts` and `tombstones`. /// /// Reading is one-way compatible in both directions, deliberately: every /// version is accepted and normalised up to [current] (a v0 bare array, a v1 or @@ -30,7 +34,7 @@ import '../models/third_party_account.dart'; /// exists: this build never deletes what a newer one wrote. class SyncSchema { /// Current schema version produced by this build. - static const int current = 3; + static const int current = 4; /// Top-level keys [migrate] understands; everything else is preserved. static const Set _knownKeys = { @@ -148,6 +152,16 @@ class SyncEnvelope { final List accounts; final List tombstones; final EcardSyncBinding? ecard; + /// In-memory projection of the standard campus account/deletion records. + IdsSyncBinding? get ids { + var binding = IdsSyncBinding.fromAccount(accounts.where((a) => + a.platform == ThirdPartyPlatform.ids && a.raw['authMethod'] == 'passkey',).firstOrNull,); + for (final tomb in tombstones.where((t) => t.platform == ThirdPartyPlatform.ids)) { + final deleted = IdsSyncBinding(credential: null, updatedAt: tomb.deletedAt, deviceId: tomb.deviceId); + binding = binding?.merge(deleted) ?? deleted; + } + return binding; + } /// Top-level fields a newer build wrote and this one does not interpret. /// Decoded from the cloud blob and written back unchanged: an older build @@ -244,10 +258,12 @@ class SyncEnvelope { // Collect candidate events: (kind, version-key, payload). // kind 0 = tombstone, kind 1 = account. final candidates = <_MergeCandidate>[]; - if (localAcc != null) { + final hasPasskey = p == ThirdPartyPlatform.ids && + [localAcc, remoteAcc].any((account) => IdsSyncBinding.fromAccount(account) != null); + if (localAcc != null && (!hasPasskey || IdsSyncBinding.fromAccount(localAcc) != null)) { candidates.add(_MergeCandidate(1, localAcc.deviceId, localAcc.updatedAt, localAcc)); } - if (remoteAcc != null) { + if (remoteAcc != null && (!hasPasskey || IdsSyncBinding.fromAccount(remoteAcc) != null)) { candidates.add(_MergeCandidate(1, remoteAcc.deviceId, remoteAcc.updatedAt, remoteAcc)); } if (localTomb != null) { diff --git a/lib/services/sync_service.dart b/lib/services/sync_service.dart index b55995f3..453f537f 100644 --- a/lib/services/sync_service.dart +++ b/lib/services/sync_service.dart @@ -87,9 +87,8 @@ class SyncService extends ChangeNotifier { // Stable per-device id, loaded once at boot and stamped onto every // locally-touched account / tombstone so the LWW merge converges. String _deviceId = ''; - // In-memory tombstones for platforms unbound on THIS device since the last - // push. Cleared after a successful push. Survives across pulls so a remote - // account older than our deletion is not resurrected. + // Latest per-platform deletion versions survive restart and successful + // uploads, so a late old cloud copy cannot resurrect an unbound account. final List _tombstones = []; SyncService( @@ -101,7 +100,9 @@ class SyncService extends ChangeNotifier { DebugLogger? logger, }) : _ecard = ecard, _client = client ?? http.Client(), - _logger = logger; + _logger = logger { + _tombstones.addAll(_storage.loadThirdPartyTombstones()); + } bool get enabled => _storage.syncEnabled; bool get hasLocalKey => _cachedKey != null; @@ -112,11 +113,14 @@ class SyncService extends ChangeNotifier { /// for comparison against [cloudLastModified] in the sync settings UI. /// Null when there are no local bindings at all. DateTime? get localLastModified { - final accounts = _tpAuth.accounts; - if (accounts.isEmpty) return null; - return accounts.map((a) => a.updatedAt).reduce( - (a, b) => a.isAfter(b) ? a : b, - ); + final times = [ + ..._tpAuth.accountsForSync.map((a) => a.updatedAt), + ..._tombstones.map((t) => t.deletedAt), + ]; + if (times.isEmpty) return null; + return times.reduce( + (a, b) => a.isAfter(b) ? a : b, + ); } /// Best-effort read of the cloud blob's most recent modification time, @@ -437,14 +441,14 @@ class SyncService extends ChangeNotifier { /// Does not decrypt — just checks presence. Cheap probe for the UI. Future cloudHasBlob() async => (await _readBlob()) != null; - /// Serialize the current local bindings + pending tombstones into the v2 + /// Serialize the current local bindings + retained tombstones into the /// envelope plaintext. Accounts are stamped with this device's id and a /// fresh [updatedAt] only via [touchLocal]; already-stamped accounts pass /// through unchanged. Future _serializeEnvelope() async { final env = SyncEnvelope.fromLocal( ecard: await _ecard?.readSyncBinding(), - accounts: _tpAuth.accounts, + accounts: _tpAuth.accountsForSync, tombstones: _tombstones, ); return env.encode(); @@ -463,24 +467,55 @@ class SyncService extends ChangeNotifier { /// Record that [platform] was deliberately unbound on this device. The /// tombstone is carried in the next push and participates in LWW merge so a /// remote account older than this deletion is not resurrected on pull. - void recordTombstone(ThirdPartyPlatform platform) { - final now = DateTime.now(); + Future recordTombstone(ThirdPartyPlatform platform) async { + final deviceId = await _storage.ensureDeviceId(); + final now = DateTime.now().toUtc(); + final tombstone = SyncTombstone(platform: platform, deletedAt: now, deviceId: deviceId); // Replace any existing tombstone for the same platform (keep newest). _tombstones.removeWhere((t) => t.platform == platform); - _tombstones.add( - SyncTombstone( - platform: platform, - deletedAt: now, - deviceId: _deviceId, - ), - ); + _tombstones.add(tombstone); + await _storage.saveThirdPartyTombstones(_tombstones); + return tombstone; + } + + Future _mergeTombstones(List incoming) async { + for (final tomb in incoming) { + final current = _tombstones.where((t) => t.platform == tomb.platform).firstOrNull; + if (current != null && current.compareVersionTo(tomb) >= 0) continue; + _tombstones.removeWhere((t) => t.platform == tomb.platform); + _tombstones.add(tomb); + } + await _storage.saveThirdPartyTombstones(_tombstones); } /// Push current local bindings to the cloud (encrypted). Requires a cached /// key (i.e. the device has already been set up / restored). Returns a result /// whose [msg] carries Casdoor's error text on failure. On success pending - /// tombstones are cleared (they are now persisted in the cloud blob). - Future push() async { + /// deletion versions remain local as well as in the cloud blob. + Future? _pushInFlight; + bool _pushPending = false; + + Future push() { + final current = _pushInFlight; + if (current != null) { + _pushPending = true; + return current; + } + final pending = _drainPushes().whenComplete(() => _pushInFlight = null); + _pushInFlight = pending; + return pending; + } + + Future _drainPushes() async { + late SyncCasdoorResult result; + do { + _pushPending = false; + result = await _pushOnce(); + } while (_pushPending); + return result; + } + + Future _pushOnce() async { if (!enabled || _cachedKey == null) { return const SyncCasdoorResult(false, msg: '云同步未开启或缺少主密码'); } @@ -496,10 +531,17 @@ class SyncService extends ChangeNotifier { final remote = plain == null ? null : SyncEnvelope.decode(plain); if (remote == null) throw StateError('无法解密云端同步状态,请先恢复云同步'); final local = SyncEnvelope.decode(payload)!; + final merged = local.mergeWith(remote); payload = SyncEnvelope( v: local.v, - accounts: local.accounts, - tombstones: local.tombstones, + accounts: [ + ...local.accounts.where((a) => a.platform != ThirdPartyPlatform.ids), + ...merged.accounts.where((a) => a.platform == ThirdPartyPlatform.ids), + ], + tombstones: [ + ...local.tombstones.where((a) => a.platform != ThirdPartyPlatform.ids), + ...merged.tombstones.where((a) => a.platform == ThirdPartyPlatform.ids), + ], // Without an eCard store this build has no opinion on the binding, so // the cloud's copy is the one that stands. ecard: _ecard == null @@ -520,7 +562,10 @@ class SyncService extends ChangeNotifier { final res = await _writeBlob(blob); _lastError = res.ok ? null : res.msg; if (res.ok) { - _tombstones.clear(); + final uploaded = SyncEnvelope.decode(payload)!; + await _mergeTombstones(uploaded.tombstones); + await _tpAuth.markIdsBackedUp(uploaded.ids); + await _applyCampusSync(uploaded); _lastSyncAt = DateTime.now(); await _storage.setSyncLastAt(_lastSyncAt!.toIso8601String()); notifyListeners(); @@ -559,10 +604,11 @@ class SyncService extends ChangeNotifier { if (remote == null) return; final local = SyncEnvelope.fromLocal( ecard: await _ecard?.readSyncBinding(), - accounts: _tpAuth.accounts, + accounts: _tpAuth.accountsForSync, tombstones: _tombstones, ); final merged = local.mergeWith(remote); + await _mergeTombstones(merged.tombstones); // Apply the merged account set locally. applySyncMerge does NOT record // tombstones (the merge already accounted for them); it just writes the // winning account per platform and clears platforms whose tombstone won. @@ -572,40 +618,20 @@ class SyncService extends ChangeNotifier { ) .toSet(); await _tpAuth.applySyncMerge(merged.accounts, removed); + await _tpAuth.markIdsBackedUp(remote.ids); + await _applyCampusSync(merged); await _ecard?.applySyncBinding(merged.ecard); - // Adopt the merged tombstone set so the next push propagates any remote - // tombstones this device didn't have. Local tombstones that won are - // already in [merged.tombstones]; ones that lost (an account won) are - // correctly absent. - _tombstones - ..clear() - ..addAll(merged.tombstones); _lastSyncAt = DateTime.now(); await _storage.setSyncLastAt(_lastSyncAt!.toIso8601String()); _needsRestore = false; // If the merge produced a state that differs from the cloud (e.g. a local // account won), push the merged envelope back so other devices converge. if (!_envelopeEquals(remote, merged)) { - await _writeMergedEnvelope(merged); + await push(); } notifyListeners(); } - /// Encrypt [env] and write it to the cloud, reusing the cached salt. - Future _writeMergedEnvelope(SyncEnvelope env) async { - final payload = env.encode(); - final salted = base64.encode(_cachedKey!.salt); - final inner = await SyncCrypto.encrypt(payload, _cachedKey!.key); - final blob = '$salted.$inner'; - final res = await _writeBlob(blob); - _lastError = res.ok ? null : res.msg; - if (res.ok) { - _lastSyncAt = DateTime.now(); - await _storage.setSyncLastAt(_lastSyncAt!.toIso8601String()); - } - return res; - } - /// Cheap structural equality between two envelopes — enough to decide /// whether a pull changed anything worth pushing back. Compares the /// encoded form; envelope encode is deterministic. @@ -636,6 +662,14 @@ class SyncService extends ChangeNotifier { return true; } + Future _applyCampusSync(SyncEnvelope envelope) async { + await _tpAuth.applyIdsSyncBinding(envelope.ids); + await _tpAuth.applyLegacyCampusSync( + envelope.accounts.where((a) => a.platform == ThirdPartyPlatform.ids).firstOrNull, + envelope.tombstones.where((t) => t.platform == ThirdPartyPlatform.ids).firstOrNull, + ); + } + /// First-time setup on a device that is not syncing yet: derive a key from /// [password] (fresh salt), cache it, and push current bindings. /// @@ -671,10 +705,16 @@ class SyncService extends ChangeNotifier { ); } await _cacheKey(CachedSyncKey(salt, key)); + await _tpAuth.markIdsBackedUp(SyncEnvelope.decode(payload)?.ids); await _storage.setSyncEnabled(true); _lastSyncAt = DateTime.now(); await _storage.setSyncLastAt(_lastSyncAt!.toIso8601String()); _lastError = null; + if (jsonEncode(SyncEnvelope.decode(payload)?.ids?.toJson()) != + jsonEncode(_tpAuth.idsBinding?.toJson())) { + final latest = await push(); + if (!latest.ok) return SyncOutcome(ok: false, message: latest.describe('最新 IDS 绑定备份失败')); + } notifyListeners(); return SyncOutcome( ok: true, @@ -705,18 +745,18 @@ class SyncService extends ChangeNotifier { } final local = SyncEnvelope.fromLocal( ecard: await _ecard?.readSyncBinding(), - accounts: _tpAuth.accounts, + accounts: _tpAuth.accountsForSync, tombstones: _tombstones, ); final merged = local.mergeWith(remote); + await _mergeTombstones(merged.tombstones); final removed = ThirdPartyPlatform.values .where((p) => !merged.accounts.any((a) => a.platform == p)) .toSet(); await _tpAuth.applySyncMerge(merged.accounts, removed); + await _tpAuth.markIdsBackedUp(remote.ids); + await _applyCampusSync(merged); await _ecard?.applySyncBinding(merged.ecard); - _tombstones - ..clear() - ..addAll(merged.tombstones); await _storage.setSyncEnabled(true); _lastSyncAt = DateTime.now(); await _storage.setSyncLastAt(_lastSyncAt!.toIso8601String()); @@ -724,7 +764,7 @@ class SyncService extends ChangeNotifier { _lastError = null; // Push the merged envelope back so the cloud reflects this device's // local winners (and so other devices converge on the next pull). - await _writeMergedEnvelope(merged); + await push(); notifyListeners(); return const SyncOutcome(ok: true, message: '已从云端恢复绑定'); } @@ -773,6 +813,7 @@ class SyncService extends ChangeNotifier { } await _clearCachedKey(); _tombstones.clear(); + await _storage.saveThirdPartyTombstones(_tombstones); await _storage.setSyncEnabled(false); await _storage.setSyncLastAt(''); _lastSyncAt = null; diff --git a/lib/services/third_party_auth_service.dart b/lib/services/third_party_auth_service.dart index d570ac11..086a39c9 100644 --- a/lib/services/third_party_auth_service.dart +++ b/lib/services/third_party_auth_service.dart @@ -3,24 +3,28 @@ import 'dart:convert'; import 'package:flutter/foundation.dart'; +import '../models/ids_passkey.dart'; import '../models/renew_status.dart'; import '../models/third_party_account.dart'; import 'api_base_url.dart'; import 'campus_web_session.dart'; import 'http_client.dart'; +import 'ids/ids_client.dart'; import 'session/session_node.dart'; import 'session/session_tree.dart'; import 'storage_service.dart'; +import 'sync_envelope.dart' show SyncTombstone; /// Every session-node id, top-level and derived, in a stable order. Used to /// bulk-load persisted renew status at boot. const List _allSessionNodeIds = [ - 'cpdaily', + 'ids', 'gradescope', 'hydro', 'eams', 'elearning', 'egateApp', + 'oa', ]; class ThirdPartyBindException implements Exception { @@ -42,26 +46,52 @@ class ThirdPartyAuthService extends ChangeNotifier { // _onTreeChanged() call knows to bypass the pushIfDue throttle. Consumed // (reset to false) the moment _onTreeChanged reads it. bool _pendingForcePush = false; - // SMS context for cpdaily binding flow (set by sendCpdailySmsCode). - Map? _cpdailySmsContext; + final IdsClient _ids; + IdsSyncBinding? _idsBinding; + int _idsGeneration = 0; + Future _idsWrites = Future.value(); + + // Serialize the short persistence/commit phase, never network or captcha waits. + Future _writeIds(Future Function() action) { + final result = _idsWrites.then((_) => action()); + _idsWrites = result.then((_) {}, onError: (Object _, StackTrace __) {}); + return result; + } + + IdsSyncBinding? get idsBinding => _idsBinding; + bool get hasIdsPasskey => _idsBinding?.credential != null; + bool get usesIdsPasskey => idsAccount?.raw['authMethod'] == 'passkey'; + bool get needsIdsRebind => idsAccount != null && !usesIdsPasskey; + Iterable get accountsForSync => accounts + .map( + (account) => + account.platform == ThirdPartyPlatform.ids && account.raw['authMethod'] == 'passkey' + ? IdsSyncBinding.fromAccount(account)?.toAccount() + : account, + ) + .whereType(); late final SessionTree _tree; CampusWebSession? _webSession; CampusWebSession get campusWebSession => - _webSession ??= CampusWebSession(cpdailyNode, _storage); + _webSession ??= CampusWebSession(idsNode, _storage); // Stable per-device id, loaded in [initialize]. Stamped onto every locally // mutated account so the cloud-sync LWW merge converges. String _deviceId = ''; - // Renew status per session-node id (cpdaily/gradescope/hydro/eams/ + // Renew status per session-node id (ids/gradescope/hydro/eams/ // elearning), for the linked-accounts status indicator. Loaded at boot, // updated in-memory + persisted on every renew attempt. Local-only. final Map _renewStatuses = {}; RenewStatus? renewStatus(String nodeId) => _renewStatuses[nodeId]; - ThirdPartyAuthService(this._storage, this._http) { + ThirdPartyAuthService(this._storage, this._http, {IdsClient? idsClient}) + : _ids = idsClient ?? IdsClient() { _tree = SessionTree( persist: _persistAccount, + localAccountRenew: _renewIdsAccount, + localCanRenew: () => hasIdsPasskey, + localCookieMint: _ids.mintCookie, http: _http, baseUrl: () => apiBaseUrl(_storage), persistDerived: _persistDerivedCookie, @@ -84,19 +114,20 @@ class ThirdPartyAuthService extends ChangeNotifier { /// [SessionTree.withCookie] for 401-renew-retry) go through here. SessionTree get sessionTree => _tree; - /// Convenience: the CpDaily session node — parent of [eamsNode] and - /// [elearningNode]. Source of CASTGC / CpDaily cookies. - SessionNode get cpdailyNode => _tree.cpdaily; + /// Convenience: the IDS session node — parent of [eamsNode] and + /// [elearningNode]. Source of CASTGC / IDS cookies. + SessionNode get idsNode => _tree.ids; - /// Convenience: the EAMS downstream node (child of cpdaily). + /// Convenience: the EAMS downstream node (child of ids). SessionNode get eamsNode => _tree.eams; - /// Convenience: the eLearning downstream node (child of cpdaily). + /// Convenience: the eLearning downstream node (child of ids). SessionNode get elearningNode => _tree.elearning; /// Convenience: the egate-app (xshdapp activity check-in) downstream node - /// (child of cpdaily). + /// (child of ids). SessionNode get egateAppNode => _tree.egateApp; + SessionNode get oaNode => _tree.oa; /// Convenience: the Gradescope top-level node. SessionNode get gradescopeNode => _tree.gradescope; @@ -110,13 +141,13 @@ class ThirdPartyAuthService extends ChangeNotifier { ThirdPartyAccount? account(ThirdPartyPlatform p) => _nodeAccount(p); List get _accountsSnapshot => [ - _tree.cpdaily.account, + _tree.ids.account, _tree.gradescope.account, _tree.hydro.account, ].whereType().toList(); ThirdPartyAccount? _nodeAccount(ThirdPartyPlatform p) => switch (p) { - ThirdPartyPlatform.cpdaily => _tree.cpdaily.account, + ThirdPartyPlatform.ids => _tree.ids.account, ThirdPartyPlatform.gradescope => _tree.gradescope.account, ThirdPartyPlatform.hydro => _tree.hydro.account, }; @@ -133,7 +164,7 @@ class ThirdPartyAuthService extends ChangeNotifier { /// [SyncService] to record a tombstone so the deletion survives the next /// LWW merge (instead of being resurrected by an older remote copy). /// Null until wired; safe to call. - void Function(ThirdPartyPlatform platform)? onUnbind; + Future Function(ThirdPartyPlatform platform)? onUnbind; void _onTreeChanged({bool force = false}) { // While [applySyncMerge] is replaying a merged snapshot, suppress ALL @@ -164,14 +195,30 @@ class ThirdPartyAuthService extends ChangeNotifier { Future _persistAccount( ThirdPartyAccount updated, { bool force = false, + ThirdPartyAccount? expectedAccount, }) async { - // Stamp the renewed/refreshed account with this device's id + a fresh - // updatedAt so the cloud-sync LWW merge treats it as the newest version. + if (updated.platform == ThirdPartyPlatform.ids) { + await _writeIds(() async { + if (expectedAccount != null && !identical(_tree.ids.account, expectedAccount)) return; + if (updated.raw['authMethod'] != 'passkey' || + _idsBinding?.credential == null || + updated.raw['idsCredentialId'] != _idsBinding!.credential!.credentialId) { + throw const IdsException('IDS 绑定已变更'); + } + await _storage.saveThirdPartyAccount(updated); + _suppressSyncPush = true; + try { + _tree.setAccount(updated.platform, updated); + } finally { + _suppressSyncPush = false; + } + }); + notifyListeners(); + return; + } final touched = _touch(updated); await _storage.saveThirdPartyAccount(touched); if (force) _pendingForcePush = true; - // Re-sync the node's in-memory copy so UI + cookieProvider see the - // stamped version. setAccount notifies; _onTreeChanged funnels it. _tree.setAccount(touched.platform, touched); } @@ -193,11 +240,17 @@ class ThirdPartyAuthService extends ChangeNotifier { /// [onBindingsChanged] — the cookies are local, and the cloud push has nothing /// to gain from them. Future _persistDerivedCookie(String nodeId, String? cookie) async { - if (cookie == null) { - await _storage.clearDerivedCookie(nodeId); - } else { - await _storage.saveDerivedCookie(nodeId, cookie); - } + final parent = _sessionNode(nodeId)?.parent; + final owner = parent?.account; + final epoch = parent?.epoch; + await _writeIds(() async { + if (!identical(parent?.account, owner) || parent?.epoch != epoch) return; + if (cookie == null) { + await _storage.clearDerivedCookie(nodeId); + } else { + await _storage.saveDerivedCookie(nodeId, cookie); + } + }); notifyListeners(); } @@ -207,90 +260,78 @@ class ThirdPartyAuthService extends ChangeNotifier { ) => _storage.saveNextRenewTimestamp(nodeId, timestamp); - /// Persist data discovered by the silent keepalive probe that follows renew. - /// Child cookies are stored locally; probe display values update the parent - /// account only when they contain a useful identity value. + /// Probes update a service's local cookie only. User identity comes from the + /// authenticated campus profile, never a child's display string. Future _persistProbe(String nodeId, KeepaliveResult result) async { - if (nodeId == 'eams' || nodeId == 'elearning' || nodeId == 'egateApp') { - final cookies = result.cookies; - if (cookies != null && cookies.isNotEmpty) { - await _persistDerivedCookie(nodeId, cookies); - } - } - - final identity = result.display.trim(); - if (identity.isEmpty || identity.startsWith('HTTP ')) return; - final parent = _treeForNode(nodeId).parent; - final account = parent?.account; - if (account == null) return; - - final updated = switch (nodeId) { - 'eams' || 'elearning' => account.copyWith(name: identity), - 'egateApp' => account.copyWith(sid: identity), - _ => null, - }; - if (updated == null) return; - if (updated.name == account.name && updated.sid == account.sid) return; - await _persistAccount(updated, force: false); + final cookies = result.cookies; + if (cookies != null && cookies.isNotEmpty) await _persistDerivedCookie(nodeId, cookies); } - SessionNode _treeForNode(String nodeId) => switch (nodeId) { - 'cpdaily' => _tree.cpdaily, - 'gradescope' => _tree.gradescope, - 'hydro' => _tree.hydro, - 'eams' => _tree.eams, - 'elearning' => _tree.elearning, - 'egateApp' => _tree.egateApp, - _ => _tree.cpdaily, - }; - /// Stamp [acc] with this device's id + current time, for LWW merge. ThirdPartyAccount _touch(ThirdPartyAccount acc) { return acc.copyWith(updatedAt: DateTime.now(), deviceId: _deviceId); } - // -- CpDaily binding (single source of CASTGC / CpDaily session) -- + // -- IDS binding (single source of CASTGC / IDS session) -- // - // The cpdaily binding is the ONLY place CASTGC lives in the new + // The ids binding is the ONLY place CASTGC lives in the new // architecture. The primary GeekPie SSO session has no tgc/cookies; every // campus-system feature (schedule, blackboard, exam, oa-gym, webview - // features) must read its CpDaily session through these accessors instead + // features) must read its IDS session through these accessors instead // of touching `AuthService.session` fields directly. - /// True when a cpdaily binding exists. This is the gate every + /// True when an IDS binding exists. This is the gate every /// CASTGC-dependent feature must check before doing work. - bool get hasCpdailyBinding => _tree.cpdaily.account != null; + bool get hasIdsBinding => hasIdsPasskey; - /// The bound cpdaily account, or null. - ThirdPartyAccount? get cpdailyBinding => _tree.cpdaily.account; + /// The bound ids account, or null. + ThirdPartyAccount? get idsAccount => _tree.ids.account; /// Cookie string for campus-system requests, always ending with - /// `CASTGC=` when a tgc is present (the form CpDaily/EAMS expects). + /// `CASTGC=` when a tgc is present (the form IDS/EAMS expects). /// Returns '' when there is no binding or no tgc — callers should treat /// that as "session unavailable". - String cpdailyCookies() => _tree.cpdaily.cookieProvider?.cookies ?? ''; + String idsCookies() => _tree.ids.cookieProvider?.cookies ?? ''; - /// Student id surfaced by the cpdaily binding, or '' if unbound. - String get cpdailyStudentId => _tree.cpdaily.account?.cpdailyStudentId ?? ''; + /// Student id surfaced by the ids binding, or '' if unbound. + String get idsStudentId => _tree.ids.account?.idsStudentId ?? ''; - /// Best-effort renewal of the cpdaily binding's CpDaily session. Delegates - /// to [SessionNode.renew], which is single-flighted: concurrent callers - /// (two services hitting 401 at once) share ONE `/auth/renew` POST. On - /// success the refreshed raw is persisted and listeners notified via the - /// tree → [Service._onTreeChanged] path. Returns true on success. + /// Hydrate bindings and per-device sessions without network requests. Future initialize() async { _deviceId = await _storage.ensureDeviceId(); final loaded = await _storage.loadAllThirdPartyAccounts(); + _idsBinding = IdsSyncBinding.fromAccount( + loaded.where((a) => a.platform == ThirdPartyPlatform.ids).firstOrNull, + ); + final deletions = _storage.loadThirdPartyTombstones(); + final idsDeletion = deletions.where((t) => t.platform == ThirdPartyPlatform.ids).firstOrNull; + if (idsDeletion != null) { + final deleted = IdsSyncBinding( + credential: null, + updatedAt: idsDeletion.deletedAt, + deviceId: idsDeletion.deviceId, + ); + _idsBinding = _idsBinding?.merge(deleted) ?? deleted; + } // Seed each node with its persisted account. setAccount routes to the // matching node and notifies (boot hydration — the sync hook is not wired // yet, so no cloud push fires). for (final acc in loaded) { + final deletion = deletions.where((t) => t.platform == acc.platform).firstOrNull; + if (deletion != null && + (deletion.deletedAt.isAfter(acc.updatedAt) || + (deletion.deletedAt == acc.updatedAt && + deletion.deviceId.compareTo(acc.deviceId) >= 0))) { + await _storage.clearThirdPartyAccount(acc.platform); + if (acc.platform == ThirdPartyPlatform.ids) await _storage.clearAllDerivedCookies(); + continue; + } _tree.setAccount(acc.platform, acc); } // Hydrate child node derived cookies so cold start can skip the SSO // bounce. These are best-effort — if stale, withCookie's 401 retry will // re-mint transparently. - for (final id in const ['eams', 'elearning', 'egateApp']) { + for (final id in const ['eams', 'elearning', 'egateApp', 'oa']) { final cookie = await _storage.loadDerivedCookie(id); _tree.setDerivedCookie(id, cookie); } @@ -307,17 +348,24 @@ class ThirdPartyAuthService extends ChangeNotifier { ); } for (final node in [ - _tree.cpdaily, + _tree.ids, _tree.gradescope, _tree.hydro, _tree.eams, _tree.elearning, _tree.egateApp, + _tree.oa, ]) { if (node.isAvailable && node.nextRenewTimestamp == null) { await node.scheduleNextRenew(); } } + final key = _idsBinding?.credential; + if (key != null && (!usesIdsPasskey || _tree.ids.account?.account != key.username)) { + await _setIdsSession(_idsAccount(const {})); + } else if (key == null && usesIdsPasskey) { + await _setIdsSession(null); + } _initialized = true; notifyListeners(); } @@ -325,15 +373,176 @@ class ThirdPartyAuthService extends ChangeNotifier { /// Look up a [SessionNode] by its stable string id (matches /// [ThirdPartyPlatform.id] for top-level nodes, plus 'eams'/'elearning'). SessionNode? _sessionNode(String nodeId) => switch (nodeId) { - 'cpdaily' => _tree.cpdaily, + 'ids' => _tree.ids, 'gradescope' => _tree.gradescope, 'hydro' => _tree.hydro, 'eams' => _tree.eams, 'elearning' => _tree.elearning, 'egateApp' => _tree.egateApp, + 'oa' => _tree.oa, _ => null, }; + ThirdPartyAccount _idsAccount(Map raw, {String? name}) { + final account = _idsBinding!.toAccount(); + final previous = idsAccount?.account == account.account ? idsAccount : null; + return account.copyWith( + name: name ?? previous?.name, + email: previous?.email, + raw: {...raw, ...account.raw}, + ); + } + + Future _renewIdsAccount(ThirdPartyAccount current) async { + final key = _idsBinding?.credential; + if (key == null) throw const IdsException('请重新绑定 IDS Passkey', credentialRejected: true); + final session = await _ids.login(key, backedUp: _storage.idsBackedUpId == key.credentialId); + if (_idsBinding?.credential?.credentialId != key.credentialId) { + throw const IdsException('IDS 绑定已变更'); + } + return _idsAccount(session.raw, name: session.name); + } + + Future refreshNode(SessionNode node) async { + final parent = node.parent; + final owner = parent?.account; + final epoch = parent?.epoch; + if (await node.renew()) return true; + if (parent != null && + parent.isAvailable && + (!identical(parent.account, owner) || parent.epoch != epoch)) { + return node.renew(); + } + if (node.parent == null || !node.lastRenewWasCredentialError) return false; + if (!await node.parent!.renew()) return false; + return node.renew(); + } + + Future _setIdsSession(ThirdPartyAccount? account) async { + // Invalidate the old owner and every child synchronously. Late CAS/probe + // results must fail their owner checks before any storage await below. + _tree.setAccount(ThirdPartyPlatform.ids, account); + for (final id in const ['eams', 'elearning', 'egateApp', 'oa']) { + _tree.setDerivedCookie(id, null); + } + if (account != null && !_tree.ids.isAvailable) _tree.ids.seedNextRenewTimestamp(DateTime.now()); + for (final id in const ['eams', 'elearning', 'egateApp', 'oa']) { + await _storage.clearDerivedCookie(id); + } + if (account == null) { + await _storage.clearThirdPartyAccount(ThirdPartyPlatform.ids); + } else { + await _storage.saveThirdPartyAccount(account); + } + } + + Future markIdsBackedUp(IdsSyncBinding? binding) async { + final id = binding?.credential?.credentialId; + if (id != null) await _storage.markIdsBackedUp(id); + } + + Future applyIdsSyncBinding(IdsSyncBinding? binding) async { + if (binding == null) return; + var changed = false; + await _writeIds(() async { + // Network results are snapshots. Reconcile against the state *now*, after + // any local bind/unbind that happened while the request was in flight. + final next = _idsBinding?.merge(binding) ?? binding; + if (jsonEncode(_idsBinding?.toJson()) == jsonEncode(next.toJson())) return; + final previous = _idsBinding?.credential?.credentialId; + final replacesKey = next.credential == null || previous != next.credential?.credentialId; + if (replacesKey) _idsGeneration++; + _idsBinding = next; + if (replacesKey) await _storage.clearIdsCandidate(); + _suppressSyncPush = true; + try { + if (replacesKey) { + final key = next.credential; + if (key != null) { + await _setIdsSession(_idsAccount(const {})); + } else if (usesIdsPasskey) { + await _setIdsSession(null); + } + } else if (next.credential != null && idsAccount != null) { + final account = _idsAccount(idsAccount!.raw); + await _storage.saveThirdPartyAccount(account); + _tree.setAccount(ThirdPartyPlatform.ids, account); + } + } finally { + _suppressSyncPush = false; + } + changed = true; + }); + if (changed) notifyListeners(); + } + + Future bindIds({ + required String account, + required String password, + required IdsCaptchaPrompt promptCaptcha, + bool Function()? isCancelled, + }) async { + final generation = ++_idsGeneration; + void ensureCurrent() { + if (generation != _idsGeneration || isCancelled?.call() == true) { + throw const IdsException('IDS 绑定操作已取消或被替换'); + } + } + + IdsPasskey? key; + IdsSession? session; + final pending = await _writeIds(() async { + ensureCurrent(); + return _storage.loadIdsCandidate(); + }); + if (pending?.account == account) { + try { + session = await _ids.login(pending!.credential); + ensureCurrent(); + key = pending.credential; + } on IdsException catch (error) { + if (!error.credentialRejected) rethrow; + await _writeIds(() async { + ensureCurrent(); + await _storage.clearIdsCandidate(); + }); + } + } + if (key == null) { + final registered = await _ids.register( + account, + password, + promptCaptcha: promptCaptcha, + saveCandidate: (credential) => _writeIds(() async { + ensureCurrent(); + await _storage.saveIdsCandidate(account, credential); + ensureCurrent(); + }), + ); + ensureCurrent(); + key = registered.credential; + session = registered.session; + } + final credential = key; + final bound = await _writeIds(() async { + ensureCurrent(); + _idsBinding = + IdsSyncBinding(credential: credential, updatedAt: DateTime.now(), deviceId: _deviceId); + _suppressSyncPush = true; + final account = _idsAccount(session!.raw, name: session.name); + try { + await _setIdsSession(account); + } finally { + _suppressSyncPush = false; + } + await _storage.clearIdsCandidate(); + return account; + }); + ensureCurrent(); + _onTreeChanged(force: true); + return bound; + } + Future bind({ required ThirdPartyPlatform platform, required String account, @@ -346,6 +555,9 @@ class ThirdPartyAuthService extends ChangeNotifier { // wait for the next throttle window. bool forceSyncPush = false, }) async { + if (platform == ThirdPartyPlatform.ids) { + throw ThirdPartyBindException(platform, '请使用 IDS Passkey 绑定校园账号'); + } final body = { 'account': account, 'password': password, @@ -356,8 +568,7 @@ class ThirdPartyAuthService extends ChangeNotifier { body['args'] = {'url': hydroOrigin}; } - // cpdaily binds via the legacy 'egate' backend route; others use their id. - final route = platform.apiPath; + final route = platform.id; final resp = await _http.post( Uri.parse('$_baseUrl/auth/third-party/$route'), headers: {'Content-Type': 'application/json; charset=UTF-8'}, @@ -415,20 +626,46 @@ class ThirdPartyAuthService extends ChangeNotifier { return touched; } + Future unbindIdsWithRemote({required IdsVerificationPrompt promptVerification}) async { + final key = _idsBinding?.credential; + // Local removal and sync tombstones commit independently of school access. + // Keep only this operation's key in memory until its remote attempt ends. + await unbind(ThirdPartyPlatform.ids); + if (key == null) return false; + try { + await _ids.revoke(key, promptVerification: promptVerification); + return true; + } catch (_) { + return false; + } + } + Future unbind(ThirdPartyPlatform platform) async { + if (platform == ThirdPartyPlatform.ids) { + ++_idsGeneration; + await _writeIds(() async { + final deletion = await onUnbind?.call(ThirdPartyPlatform.ids); + _idsBinding = IdsSyncBinding( + credential: null, + updatedAt: deletion?.deletedAt ?? DateTime.now(), + deviceId: deletion?.deviceId ?? _deviceId, + ); + await _storage.clearIdsCandidate(); + _suppressSyncPush = true; + try { + await _setIdsSession(null); + } finally { + _suppressSyncPush = false; + } + }); + _onTreeChanged(force: true); + return; + } + await onUnbind?.call(platform); _tree.setAccount(platform, null); await _storage.clearThirdPartyAccount(platform); - // Unbinding cpdaily invalidates all downstream derived cookies. - if (platform == ThirdPartyPlatform.cpdaily) { - for (final id in const ['eams', 'elearning', 'egateApp']) { - _tree.setDerivedCookie(id, null); - await _storage.clearDerivedCookie(id); - } - } // Record a tombstone for the cloud-sync merge so this deletion is not // resurrected by an older remote copy on the next pull. - final unbindHook = onUnbind; - if (unbindHook != null) unbindHook(platform); // Force-push so the removal is immediately reflected in the cloud blob, // bypassing the pushIfDue throttle. Without this, a throttled skip would // leave the stale binding in the cloud and the next boot's pull would @@ -446,7 +683,7 @@ class ThirdPartyAuthService extends ChangeNotifier { await _storage.clearThirdPartyAccount(p); } // Downstream derived cookies are invalidated when bindings are replaced. - for (final id in const ['eams', 'elearning', 'egateApp']) { + for (final id in const ['eams', 'elearning', 'egateApp', 'oa']) { _tree.setDerivedCookie(id, null); await _storage.clearDerivedCookie(id); } @@ -478,6 +715,7 @@ class ThirdPartyAuthService extends ChangeNotifier { for (final a in kept) a.platform: a, }; for (final p in ThirdPartyPlatform.values) { + if (p == ThirdPartyPlatform.ids) continue; // IDS is merged separately from local sessions. final next = byPlatform[p]; final cur = _nodeAccount(p); // Skip no-op writes: if the merged account equals the current one @@ -488,13 +726,6 @@ class ThirdPartyAuthService extends ChangeNotifier { await _storage.saveThirdPartyAccount(next); _tree.setAccount(p, next); } else { - // Clearing cpdaily invalidates downstream derived cookies. - if (p == ThirdPartyPlatform.cpdaily && cur != null) { - for (final id in const ['eams', 'elearning', 'egateApp']) { - _tree.setDerivedCookie(id, null); - await _storage.clearDerivedCookie(id); - } - } _tree.setAccount(p, null); await _storage.clearThirdPartyAccount(p); } @@ -519,110 +750,66 @@ class ThirdPartyAuthService extends ChangeNotifier { a.deviceId == b.deviceId; } - /// Update the raw data of a bound account (e.g. after CpDaily session renewal). + /// Update the raw data of a bound account (e.g. after IDS session renewal). Future updateRaw( ThirdPartyPlatform platform, Map newRaw, ) async { final acc = _nodeAccount(platform); if (acc == null) return; + if (platform == ThirdPartyPlatform.ids) { + final raw = { + ...newRaw, + 'authMethod': acc.raw['authMethod'], + 'idsCredentialId': acc.raw['idsCredentialId'], + 'credential': acc.raw['credential'], + }; + await _persistAccount(acc.copyWith(raw: raw), expectedAccount: acc); + return; + } final touched = _touch(acc.copyWith(raw: newRaw)); await _storage.saveThirdPartyAccount(touched); _tree.setAccount(platform, touched); } - // -- CpDaily SMS binding flow -- - - /// Step 1: Send an SMS verification code for cpdaily binding. - /// Reuses the existing /api/auth/mobile/send-sms endpoint. - Future sendCpdailySmsCode(String phone) async { - final resp = await _http.post( - Uri.parse('$_baseUrl/auth/mobile/send-sms'), - headers: {'Content-Type': 'application/json; charset=UTF-8'}, - body: jsonEncode({'phone': phone}), - tag: 'cpdailySendSms', - ); - - final data = jsonDecode(resp.body) as Map; - if (data['success'] != true) { - throw ThirdPartyBindException( - ThirdPartyPlatform.cpdaily, - data['error'] as String? ?? 'Failed to send SMS', - ); - } - - _cpdailySmsContext = data['context'] as Map?; - } - - /// Step 2: Complete cpdaily binding via SMS verification code. - Future bindCpdailySms({ - required String phone, - required String code, - bool autoRenew = false, - }) async { - if (_cpdailySmsContext == null) { - throw ThirdPartyBindException( - ThirdPartyPlatform.cpdaily, - 'Send SMS code first', - ); - } - - // cpdaily binds via the legacy 'egate' backend route. - final resp = await _http.post( - Uri.parse('$_baseUrl/auth/third-party/egate'), - headers: {'Content-Type': 'application/json; charset=UTF-8'}, - body: jsonEncode({ - 'phone': phone, - 'code': code, - 'context': _cpdailySmsContext, - }), - tag: 'cpdailyBindSms', - ); - - Map data; - try { - data = jsonDecode(resp.body) as Map; - } catch (_) { - throw ThirdPartyBindException( - ThirdPartyPlatform.cpdaily, - 'Invalid response (status ${resp.statusCode})', - ); - } - - if (data['success'] != true) { - throw ThirdPartyBindException( - ThirdPartyPlatform.cpdaily, - (data['error'] as String?) ?? 'login failed (${resp.statusCode})', - ); - } - - final d = (data['data'] as Map?)?.cast() ?? const {}; - final token = d['token'] as String?; - if (token == null || token.isEmpty) { - throw ThirdPartyBindException( - ThirdPartyPlatform.cpdaily, - 'response missing token', - ); - } - - final acc = ThirdPartyAccount( - platform: ThirdPartyPlatform.cpdaily, - account: phone, - sid: d['sid'] as String?, - name: d['name'] as String?, - email: d['email'] as String?, - token: token, - expire: (d['expire'] as num?)?.toInt(), - raw: (d['raw'] as Map?)?.cast() ?? const {}, - boundAt: DateTime.now(), - autoRenew: false, // SMS binding does not support auto-renew - ); - - final touched = _touch(acc); - await _storage.saveThirdPartyAccount(touched); - _tree.setAccount(ThirdPartyPlatform.cpdaily, touched); - _cpdailySmsContext = null; - return touched; + Future applyLegacyCampusSync(ThirdPartyAccount? incoming, SyncTombstone? deletion) async { + if (incoming == null && deletion == null) return; + var changed = false; + await _writeIds(() async { + if (hasIdsPasskey) return; + final current = idsAccount; + if (incoming != null && current == null && _idsBinding != null) { + final time = incoming.updatedAt.compareTo(_idsBinding!.updatedAt); + if (time < 0 || (time == 0 && incoming.deviceId.compareTo(_idsBinding!.deviceId) < 0)) { + return; + } + } + if (incoming != null && current != null && incoming.compareVersionTo(current) <= 0) return; + if (incoming == null && current != null && deletion != null) { + final time = deletion.deletedAt.compareTo(current.updatedAt); + if (time < 0 || (time == 0 && deletion.deviceId.compareTo(current.deviceId) < 0)) return; + } + if (incoming != null && incoming.raw['authMethod'] == 'passkey') return; + if (incoming == null && current == null) return; + if (current?.account != incoming?.account || current?.boundAt != incoming?.boundAt) { + ++_idsGeneration; + } + if (incoming == null && deletion != null) { + _idsBinding = IdsSyncBinding( + credential: null, + updatedAt: deletion.deletedAt, + deviceId: deletion.deviceId, + ); + } + _suppressSyncPush = true; + try { + await _setIdsSession(incoming); + } finally { + _suppressSyncPush = false; + } + changed = true; + }); + if (changed) notifyListeners(); } /// Renew nodes whose persisted [SessionNode.nextRenewTimestamp] is due. @@ -632,14 +819,16 @@ class ThirdPartyAuthService extends ChangeNotifier { Future> autoRenewIfNeeded() async { final failed = []; final nodes = [ - _tree.cpdaily, + _tree.ids, _tree.gradescope, _tree.hydro, _tree.eams, _tree.elearning, _tree.egateApp, + _tree.oa, ]; for (final node in nodes) { + if (node.id == 'oa' && !usesIdsPasskey) continue; if (!node.isRenewDue) continue; final ok = await node.renewIfDue(); if (!ok && node.parent == null && node.canRenew) { @@ -650,15 +839,38 @@ class ThirdPartyAuthService extends ChangeNotifier { } Future clearAll() async { - final unbindHook = onUnbind; - for (final p in ThirdPartyPlatform.values) { - if (_nodeAccount(p) != null) { - if (unbindHook != null) unbindHook(p); + ++_idsGeneration; + await _writeIds(() async { + _suppressSyncPush = true; + try { + if (hasIdsPasskey || idsAccount != null) { + _idsBinding = + IdsSyncBinding(credential: null, updatedAt: DateTime.now(), deviceId: _deviceId); + } + final unbindHook = onUnbind; + for (final p in ThirdPartyPlatform.values) { + if (_nodeAccount(p) != null) { + final deletion = await unbindHook?.call(p); + if (p == ThirdPartyPlatform.ids && deletion != null) { + _idsBinding = IdsSyncBinding( + credential: null, + updatedAt: deletion.deletedAt, + deviceId: deletion.deviceId, + ); + } + } + _tree.setAccount(p, null); + } + for (final id in const ['eams', 'elearning', 'egateApp', 'oa']) { + _tree.setDerivedCookie(id, null); + } + await _storage.clearIdsCandidate(); + await _storage.clearAllThirdPartyAccounts(); + await _storage.clearAllDerivedCookies(); + } finally { + _suppressSyncPush = false; } - _tree.setAccount(p, null); - } - await _storage.clearAllThirdPartyAccounts(); - await _storage.clearAllDerivedCookies(); + }); _onTreeChanged(force: true); } diff --git a/lib/utils/platform.dart b/lib/utils/platform.dart index 99707b31..1cdb9fff 100644 --- a/lib/utils/platform.dart +++ b/lib/utils/platform.dart @@ -1,6 +1,12 @@ +import 'dart:io'; + import 'package:cupertino_native_better/cupertino_native_better.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; +import 'package:flutter/services.dart'; +import 'package:package_info_plus/package_info_plus.dart'; + +import '../services/campus_user_agent.dart'; const double iosMinimumInteractiveDimension = 44; @@ -13,6 +19,28 @@ Future initializePlatformCapabilities() async { _supportsIosLiquidGlass = (PlatformVersion.iosVersion ?? 0) >= 26; } +Future initializeCampusUserAgent() async { + final package = await PackageInfo.fromPlatform(); + final scale = WidgetsBinding.instance.platformDispatcher.views.first.devicePixelRatio; + if (isIos()) { + final info = (await const MethodChannel('techpie/platform') + .invokeMapMethod('getUserAgentInfo'))!; + CampusUserAgent.value = CampusUserAgent.format( + version: package.version, build: package.buildNumber, + device: info['device'] as String, system: info['system'] as String, + systemVersion: info['systemVersion'] as String, + scale: (info['scale'] as num).toDouble(), + ); + } else { + CampusUserAgent.value = CampusUserAgent.format( + version: package.version, build: package.buildNumber, + device: Platform.operatingSystem, system: Platform.operatingSystem, + systemVersion: Platform.operatingSystemVersion.replaceAll(RegExp(r'[()\r\n]'), ''), + scale: scale, + ); + } +} + /// Tests run with no native runtime to ask; this picks the chrome they see. @visibleForTesting set debugUsesIosLiquidGlass(bool value) => _supportsIosLiquidGlass = value; diff --git a/lib/widgets/adaptive_text_field_group.dart b/lib/widgets/adaptive_text_field_group.dart index f9f85238..b6810720 100644 --- a/lib/widgets/adaptive_text_field_group.dart +++ b/lib/widgets/adaptive_text_field_group.dart @@ -2,6 +2,7 @@ import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import '../utils/platform.dart'; +import 'secure_password_field.dart'; class AdaptiveTextFieldGroupItem { const AdaptiveTextFieldGroupItem({ @@ -73,7 +74,10 @@ class AdaptiveTextFieldGroup extends StatelessWidget { ) { return SizedBox( height: 56, - child: CupertinoTextField( + child: item.obscureText + ? SecurePasswordField(controller: item.controller, placeholder: item.placeholder, + enabled: item.enabled, textInputAction: item.textInputAction, onSubmitted: item.onSubmitted,) + : CupertinoTextField( controller: item.controller, placeholder: item.placeholder, keyboardType: item.keyboardType, @@ -96,6 +100,10 @@ class AdaptiveTextFieldGroup extends StatelessWidget { } Widget _buildMaterialField(AdaptiveTextFieldGroupItem item) { + if (item.obscureText) { + return SecurePasswordField(controller: item.controller, placeholder: item.placeholder, + enabled: item.enabled, textInputAction: item.textInputAction, onSubmitted: item.onSubmitted,); + } return TextField( controller: item.controller, decoration: InputDecoration(hintText: item.placeholder), diff --git a/lib/widgets/app_shell/mobile_shell.dart b/lib/widgets/app_shell/mobile_shell.dart index da305c54..aaad4dcc 100644 --- a/lib/widgets/app_shell/mobile_shell.dart +++ b/lib/widgets/app_shell/mobile_shell.dart @@ -47,13 +47,18 @@ class _MobileShellState extends State { Widget _buildShell(BuildContext context, {required bool tabBarHidden}) { final usesIosChrome = isIos(); + final keyboardVisible = MediaQuery.viewInsetsOf(context).bottom > 0; final bottomInset = MediaQuery.viewPaddingOf(context).bottom; // While a page stands in for the bar it covers nothing, so the page's own // toolbar sits on the home indicator's safe area, where the bar was. - final bottomObstruction = tabBarHidden - ? bottomInset - : (usesIosChrome ? 49.0 : TgBottomNavBar.barHeight + TgBottomNavBar.margin * 2) + - bottomInset; + // Scaffold already stops the body at the keyboard. Reserving the tab bar + // here as well would leave a blank strip above every text input's keyboard. + final bottomObstruction = keyboardVisible + ? 0.0 + : tabBarHidden + ? bottomInset + : (usesIosChrome ? 49.0 : TgBottomNavBar.barHeight + TgBottomNavBar.margin * 2) + + bottomInset; return AppShellMetrics( bottomObstruction: bottomObstruction, diff --git a/lib/widgets/ids_rebind_banner.dart b/lib/widgets/ids_rebind_banner.dart new file mode 100644 index 00000000..41b8ee55 --- /dev/null +++ b/lib/widgets/ids_rebind_banner.dart @@ -0,0 +1,76 @@ +import 'package:flutter/material.dart'; + +class IdsRebindBanner extends StatelessWidget { + const IdsRebindBanner({super.key, required this.onRebind}); + final VoidCallback onRebind; + + @override + Widget build(BuildContext context) { + final colors = Theme.of(context).colorScheme; + return Padding( + padding: const EdgeInsets.fromLTRB(16, 8, 16, 20), + child: Semantics( + button: true, + child: Material( + color: colors.surfaceContainerLow, + borderRadius: BorderRadius.circular(12), + clipBehavior: Clip.antiAlias, + child: InkWell( + onTap: onRebind, + child: Padding( + padding: const EdgeInsets.fromLTRB(14, 12, 16, 12), + child: Row( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Padding( + padding: const EdgeInsets.only(top: 1), + child: Icon( + Icons.key_rounded, + size: MediaQuery.textScalerOf(context).scale(22), + color: colors.primary, + ), + ), + const SizedBox(width: 12), + Expanded( + child: Column( + crossAxisAlignment: CrossAxisAlignment.start, + children: [ + Text( + '更新校园登录方式', + style: TextStyle( + fontSize: 15, + height: 1.3, + fontWeight: FontWeight.w600, + color: colors.onSurface, + ), + ), + const SizedBox(height: 3), + Text( + '绑定 IDS Passkey,继续使用校园服务。', + style: TextStyle( + fontSize: 13, + height: 1.35, + color: colors.onSurfaceVariant, + ), + ), + const SizedBox(height: 8), + Text( + '重新绑定', + style: TextStyle( + fontSize: 15, + fontWeight: FontWeight.w500, + color: colors.primary, + ), + ), + ], + ), + ), + ], + ), + ), + ), + ), + ), + ); + } +} diff --git a/lib/widgets/ios/ios_native_tab_bar.dart b/lib/widgets/ios/ios_native_tab_bar.dart index 646d149d..d46c89f2 100644 --- a/lib/widgets/ios/ios_native_tab_bar.dart +++ b/lib/widgets/ios/ios_native_tab_bar.dart @@ -118,7 +118,9 @@ class _IosNativeTabBarState extends State { _firstFrameHoldTimer = null; if (!_holdingFirstFrame) return; _holdingFirstFrame = false; - WidgetsBinding.instance.allowFirstFrame(); + // Releasing during a frame would make Flutter drop its warm-up request. + // Let the current frame finish so allowFirstFrame can schedule normally. + scheduleMicrotask(WidgetsBinding.instance.allowFirstFrame); } int get _selected => widget.selectedIndex.clamp(0, widget.items.length - 1); diff --git a/lib/widgets/secure_password_field.dart b/lib/widgets/secure_password_field.dart new file mode 100644 index 00000000..d4ac2e65 --- /dev/null +++ b/lib/widgets/secure_password_field.dart @@ -0,0 +1,161 @@ +import 'package:flutter/cupertino.dart'; +import 'package:flutter/material.dart'; + +import '../utils/platform.dart'; + +/// A secure text input that never briefly paints the last typed character. +class SecurePasswordField extends StatefulWidget { + const SecurePasswordField({ + super.key, + required this.controller, + required this.placeholder, + this.decoration, + this.enabled = true, + this.textInputAction = TextInputAction.done, + this.onSubmitted, + }); + + final TextEditingController controller; + final String placeholder; + final InputDecoration? decoration; + final bool enabled; + final TextInputAction textInputAction; + final ValueChanged? onSubmitted; + + @override + State createState() => _SecurePasswordFieldState(); +} + +class _SecurePasswordFieldState extends State + implements TextSelectionGestureDetectorBuilderDelegate { + final _focus = FocusNode(); + final _editableKey = GlobalKey(); + late final _gestures = TextSelectionGestureDetectorBuilder(delegate: this); + bool _showSelectionHandles = false; + + @override + GlobalKey get editableTextKey => _editableKey; + @override + bool get forcePressEnabled => false; + @override + bool get selectionEnabled => widget.enabled; + + void _selectionChanged(TextSelection selection, SelectionChangedCause? cause) { + final show = widget.enabled && + cause != SelectionChangedCause.keyboard && + (cause == SelectionChangedCause.longPress || widget.controller.text.isNotEmpty); + if (_showSelectionHandles != show) setState(() => _showSelectionHandles = show); + } + + @override + void dispose() { + _focus.dispose(); + super.dispose(); + } + + @override + Widget build(BuildContext context) => ListenableBuilder( + listenable: Listenable.merge([widget.controller, _focus]), + builder: (context, _) { + final theme = Theme.of(context); + final cupertino = isIos() && widget.decoration == null; + final style = theme.textTheme.titleMedium!.copyWith( + fontSize: cupertino ? 17 : 16, + color: theme.colorScheme.onSurface, + ); + final editable = _MaskedEditableText( + key: _editableKey, + controller: widget.controller, + focusNode: _focus, + style: style, + cursorColor: theme.colorScheme.primary, + backgroundCursorColor: CupertinoColors.inactiveGray, + readOnly: !widget.enabled, + keyboardAppearance: theme.brightness, + showSelectionHandles: _showSelectionHandles, + onSelectionChanged: _selectionChanged, + selectionColor: TextSelectionTheme.of(context).selectionColor ?? + theme.colorScheme.primary.withValues(alpha: 0.3), + textInputAction: widget.textInputAction, + selectionControls: isIos() + ? cupertinoTextSelectionHandleControls + : materialTextSelectionHandleControls, + contextMenuBuilder: (context, state) => + AdaptiveTextSelectionToolbar.editableText(editableTextState: state), + onSubmitted: widget.onSubmitted, + ); + final field = cupertino + ? Padding( + padding: const EdgeInsets.symmetric(horizontal: 16, vertical: 12), + child: Stack( + alignment: Alignment.centerLeft, + children: [ + if (widget.controller.text.isEmpty) + Text( + widget.placeholder, + style: style.copyWith( + color: CupertinoColors.placeholderText.resolveFrom(context), + ), + ), + editable, + ], + ), + ) + : InputDecorator( + decoration: (widget.decoration ?? InputDecoration(hintText: widget.placeholder)) + .copyWith(enabled: widget.enabled), + isFocused: _focus.hasFocus, + isEmpty: widget.controller.text.isEmpty, + child: editable, + ); + return Semantics( + label: cupertino ? widget.placeholder : null, + child: _gestures.buildGestureDetector( + behavior: HitTestBehavior.translucent, + child: field, + ), + ); + }, + ); +} + +class _MaskedEditableText extends EditableText { + _MaskedEditableText({ + super.key, + required super.controller, + required super.focusNode, + required super.style, + required super.cursorColor, + required super.backgroundCursorColor, + required super.readOnly, + required super.keyboardAppearance, + required super.showSelectionHandles, + required super.onSelectionChanged, + required super.selectionColor, + required super.textInputAction, + required super.selectionControls, + required super.contextMenuBuilder, + required super.onSubmitted, + }) : super( + obscureText: true, + autocorrect: false, + enableSuggestions: false, + enableIMEPersonalizedLearning: false, + autofillHints: null, + smartDashesType: SmartDashesType.disabled, + smartQuotesType: SmartQuotesType.disabled, + keyboardType: TextInputType.visiblePassword, + rendererIgnoresPointer: true, + ); + + @override + EditableTextState createState() => _MaskedEditableTextState(); +} + +class _MaskedEditableTextState extends EditableTextState { + @override + TextSpan buildTextSpan() => TextSpan( + style: widget.style, + text: widget.obscuringCharacter * widget.controller.text.length, + ); +} diff --git a/pubspec.lock b/pubspec.lock index 0fa4ec96..149cb9c9 100644 --- a/pubspec.lock +++ b/pubspec.lock @@ -49,6 +49,14 @@ packages: url: "https://pub.flutter-io.cn" source: hosted version: "1.11.0" + cbor: + dependency: "direct main" + description: + name: cbor + sha256: e60380c7329da6b415841be93884b8d4380cbd86cd4cecb2067baa221b8d88b5 + url: "https://pub.flutter-io.cn" + source: hosted + version: "6.3.5" characters: dependency: transitive description: @@ -113,6 +121,14 @@ packages: url: "https://pub.flutter-io.cn" source: hosted version: "3.1.2" + cookie_jar: + dependency: "direct main" + description: + name: cookie_jar + sha256: "963da02c1ef64cb5ac20de948c9e5940aa351f1e34a12b1d327c83d85b7e8fff" + url: "https://pub.flutter-io.cn" + source: hosted + version: "4.0.9" cross_file: dependency: transitive description: @@ -137,6 +153,14 @@ packages: url: "https://pub.flutter-io.cn" source: hosted version: "2.9.0" + csslib: + dependency: transitive + description: + name: csslib + sha256: "09bad715f418841f976c77db72d5398dc1253c21fb9c0c7f0b0b985860b2d58e" + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.0.2" cupertino_icons: dependency: "direct main" description: @@ -419,6 +443,22 @@ packages: description: flutter source: sdk version: "0.0.0" + hex: + dependency: transitive + description: + name: hex + sha256: "4e7cd54e4b59ba026432a6be2dd9d96e4c5205725194997193bf871703b82c4a" + url: "https://pub.flutter-io.cn" + source: hosted + version: "0.2.0" + html: + dependency: "direct main" + description: + name: html + sha256: "43b67b8f43321ab066817dfac5619596c98bb1b61624e77203bb4351785f9699" + url: "https://pub.flutter-io.cn" + source: hosted + version: "0.15.7" http: dependency: "direct main" description: @@ -435,6 +475,14 @@ packages: url: "https://pub.flutter-io.cn" source: hosted version: "4.1.2" + ieee754: + dependency: transitive + description: + name: ieee754 + sha256: "7d87451c164a56c156180d34a4e93779372edd191d2c219206100b976203128c" + url: "https://pub.flutter-io.cn" + source: hosted + version: "1.0.3" image: dependency: transitive description: @@ -982,6 +1030,14 @@ packages: url: "https://pub.flutter-io.cn" source: hosted version: "1.4.0" + universal_io: + dependency: transitive + description: + name: universal_io + sha256: f63cbc48103236abf48e345e07a03ce5757ea86285ed313a6a032596ed9301e2 + url: "https://pub.flutter-io.cn" + source: hosted + version: "2.3.1" url_launcher: dependency: "direct main" description: diff --git a/pubspec.yaml b/pubspec.yaml index 6dd295ed..68e82494 100644 --- a/pubspec.yaml +++ b/pubspec.yaml @@ -30,8 +30,10 @@ environment: dependencies: animations: ^2.0.11 casdoor_flutter_sdk: ^1.0.0 + cbor: 6.3.5 clock: ">=1.1.1 <1.2.0" connectivity_plus: 6.1.4 + cookie_jar: ^4.0.8 # The following adds the Cupertino Icons font to your application. # Use with the CupertinoIcons class for iOS style icons. crypto: 3.0.7 @@ -50,6 +52,7 @@ dependencies: url: https://gitcode.com/openharmony-sig/fluttertpc_flutter_secure_storage.git path: flutter_secure_storage_ohos ref: br_v9.2.2_ohos + html: ^0.15.6 http: ^1.4.0 image_picker: git: @@ -202,6 +205,7 @@ flutter: uses-material-design: true assets: + - assets/help/ids_passkey.png - assets/campus_card/audio/ - assets/campus_card/data/ - assets/campus_card/images/card-full.png diff --git a/test/adaptive_text_controls_test.dart b/test/adaptive_text_controls_test.dart index 89e1f9e4..2bfa3b82 100644 --- a/test/adaptive_text_controls_test.dart +++ b/test/adaptive_text_controls_test.dart @@ -4,6 +4,7 @@ import 'package:flutter/material.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:techpie/widgets/adaptive_text_area.dart'; import 'package:techpie/widgets/adaptive_text_field_group.dart'; +import 'package:techpie/widgets/secure_password_field.dart'; void main() { tearDown(() => debugDefaultTargetPlatformOverride = null); @@ -13,6 +14,8 @@ void main() { WidgetTester tester, ) async { debugDefaultTargetPlatformOverride = TargetPlatform.iOS; + tester.binding.platformDispatcher.brieflyShowPasswordTestValue = true; + addTearDown(tester.binding.platformDispatcher.resetBrieflyShowPassword); final account = TextEditingController(); final password = TextEditingController(); addTearDown(account.dispose); @@ -40,7 +43,8 @@ void main() { ); expect(find.byType(UiKitView), findsNothing); - expect(find.byType(CupertinoTextField), findsNWidgets(2)); + expect(find.byType(CupertinoTextField), findsOneWidget); + expect(find.byType(SecurePasswordField), findsOneWidget); final groupRect = tester.getRect(find.byType(AdaptiveTextFieldGroup)); final lineRect = tester.getRect( find.descendant( @@ -54,6 +58,23 @@ void main() { expect(lineRect.center.dy, closeTo(groupRect.center.dy, 0.01)); await tester.enterText(find.byType(CupertinoTextField).first, '20260001'); expect(account.text, '20260001'); + final secureEditable = find.descendant( + of: find.byType(SecurePasswordField), + matching: find.byWidgetPredicate((widget) => widget is EditableText), + ); + await tester.tap(secureEditable); + await tester.pump(); + const secret = 'aB9!secret'; + for (var i = 1; i <= secret.length; i++) { + tester.testTextInput.enterText(secret.substring(0, i)); + await tester.pump(); + expect( + tester.state(secureEditable).renderEditable.text!.toPlainText(), + '•' * i, + ); + } + expect(password.text, secret); + expect(tester.state(secureEditable).copyEnabled, false); debugDefaultTargetPlatformOverride = null; }); diff --git a/test/assignment_service_test.dart b/test/assignment_service_test.dart index 7a477dcf..c9b0ad61 100644 --- a/test/assignment_service_test.dart +++ b/test/assignment_service_test.dart @@ -17,9 +17,31 @@ import 'package:techpie/services/storage_service.dart'; import 'package:techpie/services/third_party_auth_service.dart'; import 'package:techpie/services/uni_auth_service.dart'; +import 'support/fake_ids_client.dart'; + void main() { TestWidgetsFlutterBinding.ensureInitialized(); + test('IDS unbind clears campus deadlines and retains other cached sources', () async { + final fixture = await _identityFixture( + (_, __) => http.Response('unavailable', 503), + account: FakeIdsClient.account('20240001'), + cached: [ + for (final source in ['blackboard', 'exam', 'gradescope']) + _assignmentJson(id: source, platform: source, due: DateTime.utc(2027)), + ], + ); + + await fixture.thirdParty.unbind(ThirdPartyPlatform.ids); + await Future.delayed(Duration.zero); + + expect(fixture.service.assignments.map((a) => a.platform), ['gradescope']); + expect( + fixture.storage.loadCachedAssignments().map((a) => a['platform']), + ['gradescope'], + ); + }); + for (final singlePlatform in [false, true]) { for (final expired in [false, true]) { test( @@ -246,23 +268,10 @@ void main() { createdAt: DateTime.utc(2026), ), ); - // Blackboard/exam fetches are gated on the eGate binding, not on the + // Blackboard/exam fetches are gated on the IDS binding, not on the // primary UserSession. Bind one with the tgc the test expects. await storage.saveThirdPartyAccount( - ThirdPartyAccount( - platform: ThirdPartyPlatform.cpdaily, - account: 'student', - sid: 'student', - token: 'session', - raw: const { - 'tgc': 'tgc', - 'cookies': '', - 'sessionToken': 'session', - 'userId': 'user', - 'tenantId': 'tenant', - }, - boundAt: DateTime.utc(2026), - ), + FakeIdsClient.account('20240001'), ); await storage.saveThirdPartyAccount( ThirdPartyAccount( @@ -274,15 +283,6 @@ void main() { ); final httpClient = _AssignmentHttpClient((url, _) { - if (url.path.endsWith('/auth/third-party/elearning')) { - return http.Response( - jsonEncode({ - 'success': true, - 'data': {'token': 'session_id=elearning-mock'}, - }), - 200, - ); - } if (url.path.endsWith('/deadlines/blackboard')) { return http.Response( jsonEncode({ @@ -307,7 +307,7 @@ void main() { return http.Response('not found', 404); }); final auth = AuthService(storage, httpClient, UniAuthService()); - final tpAuth = ThirdPartyAuthService(storage, httpClient); + final tpAuth = ThirdPartyAuthService(storage, httpClient, idsClient: FakeIdsClient()); final schedule = ScheduleService(storage, httpClient, auth, tpAuth); await auth.loadSession(); await tpAuth.initialize(); @@ -348,45 +348,14 @@ void main() { createdAt: DateTime.utc(2026), ), ); - // Exam fetch reads cookies from the eGate binding, not UserSession. + // Exam fetch reads cookies from the IDS binding, not UserSession. await storage.saveThirdPartyAccount( - ThirdPartyAccount( - platform: ThirdPartyPlatform.cpdaily, - account: 'student', - sid: 'student', - token: 'session', - raw: const { - 'tgc': 'tgc', - 'cookies': 'SESSION=abc', - 'sessionToken': 'session', - 'userId': 'user', - 'tenantId': 'tenant', - }, - boundAt: DateTime.utc(2026), - ), + FakeIdsClient.account('20240001'), ); final seenBodies = >[]; final httpClient = _AssignmentHttpClient((url, body) { seenBodies.add(body); - if (url.path.endsWith('/auth/third-party/elearning')) { - return http.Response( - jsonEncode({ - 'success': true, - 'data': {'token': 'session_id=elearning-mock'}, - }), - 200, - ); - } - if (url.path.endsWith('/auth/third-party/eams')) { - return http.Response( - jsonEncode({ - 'success': true, - 'data': {'token': 'JSESSIONID=eams-mock'}, - }), - 200, - ); - } if (url.path.endsWith('/deadlines/blackboard')) { return http.Response( jsonEncode({'success': true, 'data': []}), @@ -426,7 +395,7 @@ void main() { return http.Response('not found', 404); }); final auth = AuthService(storage, httpClient, UniAuthService()); - final tpAuth = ThirdPartyAuthService(storage, httpClient); + final tpAuth = ThirdPartyAuthService(storage, httpClient, idsClient: FakeIdsClient()); final schedule = ScheduleService(storage, httpClient, auth, tpAuth); await auth.loadSession(); await tpAuth.initialize(); @@ -522,6 +491,7 @@ Future< })> _identityFixture( FutureOr Function(Uri, Map) handler, { ThirdPartyAccount? account, + List>? cached, }) async { SharedPreferences.setMockInitialValues({}); FlutterSecureStorage.setMockInitialValues({}); @@ -537,18 +507,20 @@ Future< await storage.saveThirdPartyAccount( account ?? _gradescopeAccount('old-account', 'old-token'), ); - await storage.saveCachedAssignments([ - _assignmentJson( - id: 'old-cache', - platform: 'gradescope', - due: DateTime.utc(2027), - ), - _assignmentJson( - id: 'unrelated', - platform: 'synthetic', - due: DateTime.utc(2027), - ), - ]); + await storage.saveCachedAssignments( + cached ?? [ + _assignmentJson( + id: 'old-cache', + platform: 'gradescope', + due: DateTime.utc(2027), + ), + _assignmentJson( + id: 'unrelated', + platform: 'synthetic', + due: DateTime.utc(2027), + ), + ], + ); final client = _AssignmentHttpClient(handler); final auth = AuthService(storage, client, UniAuthService()); final thirdParty = ThirdPartyAuthService(storage, client); diff --git a/test/campus_auth_modes_test.dart b/test/campus_auth_modes_test.dart new file mode 100644 index 00000000..76028697 --- /dev/null +++ b/test/campus_auth_modes_test.dart @@ -0,0 +1,191 @@ +import 'dart:convert'; + +import 'package:flutter_secure_storage_ohos/flutter_secure_storage_ohos.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:http/http.dart' as http; +import 'package:http/testing.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:techpie/models/ids_passkey.dart'; +import 'package:techpie/models/third_party_account.dart'; +import 'package:techpie/services/campus_user_agent.dart'; +import 'package:techpie/services/debug_logger.dart'; +import 'package:techpie/services/http_client.dart'; +import 'package:techpie/services/ids/ids_client.dart'; +import 'package:techpie/services/storage_service.dart'; +import 'package:techpie/services/third_party_auth_service.dart'; + +import 'support/fake_ids_client.dart'; + +const _legacyUserId = '11111111-2222-3333-4444-555555555555'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + test('UA combines the actual app build, iPhone OS and screen scale', () { + expect( + CampusUserAgent.format( + version: '1.0.1', + build: '42', + device: 'iPhone', + system: 'iOS', + systemVersion: '27.0.1', + scale: 3, + ), + 'TechPie/1.0.1.42 (iPhone; iOS 27.0.1; Scale/3.00) techpie/1.0.1', + ); + }); + + test('old campus records are upgrade-only and cannot expose or renew sessions', () async { + final fixture = await _Fixture.create(legacy: true); + expect(fixture.auth.needsIdsRebind, true); + expect(fixture.auth.hasIdsBinding, false); + expect(fixture.auth.idsAccount!.password, 'saved-password'); + for (final node in [ + fixture.auth.idsNode, + fixture.auth.eamsNode, + fixture.auth.elearningNode, + fixture.auth.egateAppNode, + fixture.auth.oaNode, + ]) { + expect(node.cookieProvider, isNull); + expect(node.canRenew, false); + expect(await fixture.auth.refreshNode(node), false); + } + expect(fixture.requests, isEmpty); + expect(fixture.ids.logins, 0); + }); + + test('root and child identities stay fixed across repeated large and small refreshes', () async { + final fixture = await _Fixture.create(); + await fixture.auth.applyIdsSyncBinding( + IdsSyncBinding( + credential: FakeIdsClient.key('20240001'), + updatedAt: DateTime.now().subtract(const Duration(days: 1)), + deviceId: 'test', + ), + ); + expect(await fixture.auth.refreshNode(fixture.auth.idsNode), true); + Map identities() => { + 'ids': fixture.auth.idsNode.displayName, + 'bb': fixture.auth.elearningNode.displayName, + 'eams': fixture.auth.eamsNode.displayName, + 'egate': fixture.auth.egateAppNode.displayName, + }; + const expected = { + 'ids': 'Profile User', + 'bb': 'Profile User', + 'eams': '20240001', + 'egate': '20240001', + }; + final frames = >[]; + fixture.auth.addListener(() => frames.add(identities())); + for (var i = 0; i < 5; i++) { + expect(await fixture.auth.refreshNode(fixture.auth.idsNode), true); + final results = await Future.wait([ + fixture.auth.refreshNode(fixture.auth.elearningNode), + fixture.auth.refreshNode(fixture.auth.eamsNode), + fixture.auth.refreshNode(fixture.auth.egateAppNode), + ]); + expect(results, everyElement(true)); + expect(identities(), expected); + expect(fixture.auth.idsAccount!.name, 'Profile User'); + expect(fixture.auth.idsAccount!.sid, '20240001'); + } + expect(frames, isNotEmpty); + expect(frames, everyElement(expected)); + // A graduate account's 403 on the EAMS feature probe must not hide its ID + // or cause another IDS login: the CAS session itself remains valid. + expect(fixture.ids.logins, 6); + }); +} + +class _Ids extends IdsClient { + int logins = 0; + @override + Future login(IdsPasskey key, {bool backedUp = false}) async => IdsSession( + key.username, + {'tgc': 'new-${++logins}'}, + name: logins == 1 ? 'Profile User' : null, + ); + @override + Future mintCookie(String id, Map root) async => switch (id) { + 'eams' => 'JSESSIONID=eams', + 'elearning' => 'session_id=bb', + 'egateApp' => 'MOD_AUTH_CAS=egate', + _ => 'shkjdx_session=oa', + }; +} + +class _Fixture { + _Fixture(this.auth, this.ids, this.requests); + final ThirdPartyAuthService auth; + final _Ids ids; + final List requests; + static Future<_Fixture> create({bool legacy = false}) async { + SharedPreferences.setMockInitialValues({}); + FlutterSecureStorage.setMockInitialValues({}); + final storage = StorageService(await SharedPreferences.getInstance()); + if (legacy) { + await storage.saveThirdPartyAccount( + ThirdPartyAccount( + platform: ThirdPartyPlatform.ids, + account: '20240001', + sid: _legacyUserId, + name: 'Legacy User', + password: 'saved-password', + autoRenew: true, + token: 'token', + raw: const { + 'tgc': 'old', + 'sessionToken': 'st', + 'tenantId': 'tenant', + }, + boundAt: DateTime.now(), + expire: DateTime.now().add(const Duration(days: 30)).millisecondsSinceEpoch ~/ 1000, + ), + ); + } + if (legacy) { + for (final node in ['eams', 'elearning', 'egateApp', 'oa']) { + await storage.saveDerivedCookie(node, 'cached-old-cookie=must-not-be-used'); + } + } + final requests = []; + final client = MockClient((request) async { + requests.add(request); + http.Response json(Map value) => http.Response( + jsonEncode(value), + 200, + headers: {'content-type': 'application/json; charset=utf-8'}, + ); + final path = request.url.path; + if (path.endsWith('/stdDetail.action')) return http.Response('forbidden', 403); + if (request.url.host == 'elearning.shanghaitech.edu.cn') { + return http.Response( + '欢迎,Different Name –', + 200, + headers: {'content-type': 'text/html; charset=utf-8'}, + ); + } + if (path.contains('getAppConfig')) return json({'code': '0'}); + if (path.endsWith('hqdlxsjpcxx.do')) { + return json({ + 'code': '0', + 'datas': { + 'hqdlxsjpcxx': { + 'rows': [ + {'XSBH': '999999'}, + ], + }, + }, + }); + } + return http.Response('', 404); + }); + final logging = LoggingHttpClient(DebugLogger(), inner: client); + final ids = _Ids(); + final auth = ThirdPartyAuthService(storage, logging, idsClient: ids); + await auth.initialize(); + return _Fixture(auth, ids, requests); + } +} diff --git a/test/ids_binding_race_test.dart b/test/ids_binding_race_test.dart new file mode 100644 index 00000000..810b6e59 --- /dev/null +++ b/test/ids_binding_race_test.dart @@ -0,0 +1,278 @@ +import 'dart:async'; + +import 'package:flutter_secure_storage_ohos/flutter_secure_storage_ohos.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:http/http.dart' as http; +import 'package:http/testing.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:techpie/models/ids_passkey.dart'; +import 'package:techpie/models/third_party_account.dart'; +import 'package:techpie/services/debug_logger.dart'; +import 'package:techpie/services/http_client.dart'; +import 'package:techpie/services/ids/ids_client.dart'; +import 'package:techpie/services/storage_service.dart'; +import 'package:techpie/services/third_party_auth_service.dart'; + +import 'support/fake_ids_client.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + test('a late A registration cannot replace a completed B binding or its candidate', () async { + final fixture = await _Fixture.create(); + final first = fixture.bind('A'); + final rejected = expectLater(first, throwsA(isA())); + await fixture.client.started('A'); + await fixture.client.pending['A']!.save(FakeIdsClient.key('A')); + final second = fixture.bind('B'); + await fixture.client.started('B'); + await fixture.client.pending['B']!.save(FakeIdsClient.key('B')); + fixture.client.finish('B'); + await second; + await expectLater( + fixture.client.pending['A']!.save(FakeIdsClient.key('A')), + throwsA(isA()), + ); + fixture.client.finish('A'); + await rejected; + expect(fixture.auth.idsBinding!.credential!.username, 'B'); + expect( + IdsSyncBinding.fromAccount( + await fixture.storage.loadThirdPartyAccount(ThirdPartyPlatform.ids),)! + .credential! + .username, + 'B',); + expect(fixture.auth.idsAccount!.account, 'B'); + expect(await fixture.storage.loadIdsCandidate(), isNull); + }); + + for (final action in ['unbind', 'clearAll', 'sync-delete']) { + test('$action invalidates an in-flight registration and its candidate writes', () async { + final fixture = await _Fixture.create(); + final pending = fixture.bind('A'); + final rejected = expectLater(pending, throwsA(isA())); + await fixture.client.started('A'); + if (action == 'unbind') { + await fixture.auth.unbind(ThirdPartyPlatform.ids); + } else if (action == 'clearAll') { + await fixture.auth.clearAll(); + } else { + await fixture.auth.applyIdsSyncBinding( + IdsSyncBinding(credential: null, updatedAt: DateTime.now(), deviceId: 'other'), + ); + } + await expectLater( + fixture.client.pending['A']!.save(FakeIdsClient.key('A')), + throwsA(isA()), + ); + fixture.client.finish('A'); + await rejected; + expect(fixture.auth.idsBinding?.credential, isNull); + expect( + IdsSyncBinding.fromAccount( + await fixture.storage.loadThirdPartyAccount(ThirdPartyPlatform.ids),) + ?.credential, + isNull,); + expect(fixture.auth.idsAccount, isNull); + expect(await fixture.storage.loadIdsCandidate(), isNull); + }); + } + + for (final replace in [false, true]) { + test('late CAS cannot restore cookies while ${replace ? "replacing" : "unbinding"} the root', + () async { + final fixture = await _Fixture.create(); + await fixture.bindNow('A'); + final mint = fixture.auth.eamsNode.renew(); + await fixture.client.mintStarted.future; + fixture.storage.pauseNextClear = true; + final change = replace + ? fixture.auth.applyIdsSyncBinding(IdsSyncBinding( + credential: FakeIdsClient.key('B'), + updatedAt: DateTime.now().add(const Duration(seconds: 1)), + deviceId: 'other',),) + : fixture.auth.unbind(ThirdPartyPlatform.ids); + await fixture.storage.clearStarted.future; + final ownerWhileClearing = fixture.auth.idsAccount?.account; + fixture.client.minted.complete('JSESSIONID=old-A'); + await Future.delayed(Duration.zero); + fixture.storage.releaseClear.complete(); + await change; + expect(await mint, false); + expect(ownerWhileClearing, replace ? 'B' : null); + expect(fixture.auth.eamsNode.cookieProvider, isNull); + expect(await fixture.storage.loadDerivedCookie('eams'), isNull); + }); + } + + test('an old child cookie storage write completes before the root deletion', () async { + final fixture = await _Fixture.create(); + await fixture.bindNow('A'); + fixture.storage.pauseNextDerivedWrite = true; + final mint = fixture.auth.eamsNode.renew(); + await fixture.client.mintStarted.future; + fixture.client.minted.complete('JSESSIONID=old-A'); + await fixture.storage.derivedWriteStarted.future; + final removal = fixture.auth.unbind(ThirdPartyPlatform.ids); + fixture.storage.releaseDerivedWrite.complete(); + await removal; + await mint; + expect(fixture.auth.eamsNode.cookieProvider, isNull); + expect(await fixture.storage.loadDerivedCookie('eams'), isNull); + }); + + test('a late silent probe cannot restore an unbound child session', () async { + final probeStarted = Completer(); + final response = Completer(); + final fixture = await _Fixture.create( + campusHttp: MockClient((_) { + probeStarted.complete(); + return response.future; + }), + ); + await fixture.bindNow('A'); + final mint = fixture.auth.eamsNode.renew(); + await fixture.client.mintStarted.future; + fixture.client.minted.complete('JSESSIONID=old-A'); + await probeStarted.future; + await fixture.auth.unbind(ThirdPartyPlatform.ids); + response.complete(http.Response('姓名:Synthetic Old User', 200, + headers: {'content-type': 'text/html; charset=utf-8'},),); + expect(await mint, false); + expect(fixture.auth.eamsNode.cookieProvider, isNull); + expect(await fixture.storage.loadDerivedCookie('eams'), isNull); + }); + + test('unbind during secure-storage commit wins after the earlier commit finishes', () async { + final fixture = await _Fixture.create(pauseCommit: true); + final pending = fixture.bind('A'); + final rejected = expectLater(pending, throwsA(isA())); + await fixture.client.started('A'); + fixture.client.finish('A'); + await fixture.storage.commitStarted.future; + final removal = fixture.auth.unbind(ThirdPartyPlatform.ids); + fixture.storage.releaseCommit.complete(); + await removal; + await rejected; + expect( + IdsSyncBinding.fromAccount( + await fixture.storage.loadThirdPartyAccount(ThirdPartyPlatform.ids),) + ?.credential, + isNull,); + expect(await fixture.storage.loadThirdPartyAccount(ThirdPartyPlatform.ids), isNull); + expect(fixture.auth.idsAccount, isNull); + }); +} + +class _Pending { + _Pending(this.save); + final Future Function(IdsPasskey) save; + final result = Completer<({IdsPasskey credential, IdsSession session})>(); +} + +class _ControlledIds extends IdsClient { + final mintStarted = Completer(); + final minted = Completer(); + @override + Future mintCookie(String id, Map root) { + mintStarted.complete(); + return minted.future; + } + + final pending = {}; + final _started = >{}; + Future started(String account) => (_started[account] ??= Completer()).future; + void finish(String account) => pending[account]!.result.complete( + ( + credential: FakeIdsClient.key(account), + session: IdsSession(account, {'tgc': 'synthetic-$account'}), + ), + ); + @override + Future<({IdsPasskey credential, IdsSession session})> register( + String username, + String password, { + required IdsCaptchaPrompt promptCaptcha, + required Future Function(IdsPasskey) saveCandidate, + }) { + final operation = pending[username] = _Pending(saveCandidate); + (_started[username] ??= Completer()).complete(); + return operation.result.future; + } +} + +class _Storage extends StorageService { + _Storage(super.prefs, this.pauseCommit); + final bool pauseCommit; + bool pauseNextClear = false; + final clearStarted = Completer(); + final releaseClear = Completer(); + bool pauseNextDerivedWrite = false; + final derivedWriteStarted = Completer(); + final releaseDerivedWrite = Completer(); + @override + Future clearDerivedCookie(String nodeId) async { + if (pauseNextClear && nodeId == 'eams') { + pauseNextClear = false; + clearStarted.complete(); + await releaseClear.future; + } + await super.clearDerivedCookie(nodeId); + } + + @override + Future saveDerivedCookie(String nodeId, String cookie) async { + if (pauseNextDerivedWrite && nodeId == 'eams') { + pauseNextDerivedWrite = false; + derivedWriteStarted.complete(); + await releaseDerivedWrite.future; + } + await super.saveDerivedCookie(nodeId, cookie); + } + + final commitStarted = Completer(); + final releaseCommit = Completer(); + @override + Future saveThirdPartyAccount(ThirdPartyAccount account) async { + if (pauseCommit && + account.platform == ThirdPartyPlatform.ids && + account.raw['authMethod'] == 'passkey' && + !commitStarted.isCompleted) { + commitStarted.complete(); + await releaseCommit.future; + } + await super.saveThirdPartyAccount(account); + } +} + +class _Fixture { + _Fixture(this.auth, this.storage, this.client); + final ThirdPartyAuthService auth; + final _Storage storage; + final _ControlledIds client; + Future bind(String account) => auth.bindIds( + account: account, + password: 'synthetic-password', + promptCaptcha: (_, __, {required refresh}) async => null, + ); + Future bindNow(String account) async { + final result = bind(account); + await client.started(account); + client.finish(account); + await result; + } + + static Future<_Fixture> create({bool pauseCommit = false, http.Client? campusHttp}) async { + SharedPreferences.setMockInitialValues({}); + FlutterSecureStorage.setMockInitialValues({}); + final storage = _Storage(await SharedPreferences.getInstance(), pauseCommit); + final client = _ControlledIds(); + final auth = ThirdPartyAuthService( + storage, + LoggingHttpClient(DebugLogger(), + inner: campusHttp ?? MockClient((_) async => http.Response('', 404)),), + idsClient: client,); + await auth.initialize(); + return _Fixture(auth, storage, client); + } +} diff --git a/test/ids_client_test.dart b/test/ids_client_test.dart new file mode 100644 index 00000000..347e86d3 --- /dev/null +++ b/test/ids_client_test.dart @@ -0,0 +1,681 @@ +import 'dart:convert'; +import 'dart:math'; +import 'dart:typed_data'; + +import 'package:dio/dio.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:techpie/models/ids_passkey.dart'; +import 'package:techpie/services/debug_logger.dart'; +import 'package:techpie/services/ids/campus_http.dart'; +import 'package:techpie/services/ids/ids_client.dart'; +import 'package:techpie/services/ids/software_passkey.dart'; + +void main() { + test('local authentication logs cover the lifecycle without recording credentials', () async { + final adapter = _School()..recheckCodes.addAll(['2106010003', '0']); + final logger = DebugLogger()..enabled = true; + final client = IdsClient(http: Dio()..httpClientAdapter = adapter, logger: logger); + final registered = await client.register( + '20240001', + 'synthetic-password', + promptCaptcha: (_, __, {required refresh}) async => 'manual-code', + saveCandidate: (key) async => adapter.key = key, + ); + for (final node in ['eams', 'elearning', 'egateApp', 'oa']) { + await client.mintCookie(node, registered.session.raw); + } + await client.revoke( + registered.credential, + promptVerification: (_, __, {required refresh}) async => + (password: 'synthetic-password', captcha: 'manual-code'), + ); + final completed = logger.entries.where((e) => e.statusCode != null).toList(); + expect(completed, hasLength(adapter.requests.length)); + expect( + completed.map((e) => e.url), adapter.requests.map((r) => '${r.uri.origin}${r.uri.path}'),); + expect(completed.every((e) => e.tag == 'IDS' && e.durationMicros! >= 0), true); + expect(completed.any((e) => e.statusCode == 302), true); + expect( + completed.any((e) => e.statusCode == 500 && e.responseBody == '{"code":2106010003}'), true,); + final logs = jsonEncode(logger.entries + .map((e) => { + 'url': e.url, + 'request': e.requestBody, + 'response': e.responseBody, + 'error': e.error, + },) + .toList(),); + for (final secret in [ + '20240001', + 'synthetic-password', + 'manual-code', + 'CASTGC', + 'REFERERCE_TOKEN', + 'registration-request', + 'assertion-', + 'authenticatorData', + registered.credential.privateKey, + registered.credential.credentialId, + ]) { + expect(logs, isNot(contains(secret))); + } + }); + + test('authentication logs omit query secrets and sanitize transport failures', () async { + final logger = DebugLogger()..enabled = true; + final dio = Dio() + ..interceptors.add(InterceptorsWrapper(onRequest: (options, handler) { + if (options.uri.path == '/authserver/login') { + handler.resolve(Response>( + requestOptions: options, + statusCode: 302, + data: const [], + headers: Headers.fromMap({ + 'location': ['/authserver/next?ticket=ST-synthetic-ticket'], + }), + ),); + } else { + handler + .reject(DioException(requestOptions: options, error: 'synthetic-transport-secret')); + } + },),); + final client = CampusHttp(dio, logger: logger); + Future>> request() => client.request( + Uri.parse('${SoftwarePasskey.origin}/authserver/login?username=synthetic-user'), + method: 'POST', + data: 'password=synthetic-password&captcha=manual-code', + ); + await expectLater(request(), throwsA(isA())); + expect(logger.entries, hasLength(4)); + expect(logger.entries[1].statusCode, 302); + expect(logger.entries.last.method, 'GET'); + expect(logger.entries.last.url, '${SoftwarePasskey.origin}/authserver/next'); + expect(logger.entries.last.error, '无法连接学校认证服务,请检查网络后重试'); + expect(logger.entries.last.durationMicros, isNotNull); + expect(logger.entries.every((e) => Uri.parse(e.url).query.isEmpty), true); + expect(logger.entries.every((e) => e.requestBody == null && e.responseBody == null), true); + logger.clear(); + logger.enabled = false; + await expectLater(request(), throwsA(isA())); + expect(logger.entries, isEmpty); + }); + + test('distinguishes a rejected password and asks for captcha after repeated failures', () async { + final adapter = _School()..passwordErrors.addAll(['您提供的用户名或者密码有误', '用户名或密码错误']); + final client = IdsClient(http: Dio()..httpClientAdapter = adapter); + Future<({IdsPasskey credential, IdsSession session})> attempt() => client.register( + '20240001', + 'synthetic-password', + promptCaptcha: (_, error, {required refresh}) async => 'manual-code', + saveCandidate: (key) async { + adapter.key = key; + }, + ); + for (var i = 0; i < 2; i++) { + await expectLater( + attempt(), + throwsA( + isA().having((e) => e.message, 'message', contains('账号或密码错误')), + ), + ); + } + expect(adapter.authCaptchaRequests, 0); + await attempt(); + expect(adapter.authCaptchaRequests, 1); + expect(adapter.passwordForms.last['captcha'], 'manual-code'); + expect( + adapter.requests.where((r) => r.uri.path.endsWith('checkNeedCaptcha.htl')), + hasLength(3), + ); + }); + + test('a wrong login captcha prompts again with a fresh execution and explicit error', () async { + final adapter = _School() + ..forceLoginCaptcha = true + ..passwordErrors.add('验证码错误'); + final client = IdsClient(http: Dio()..httpClientAdapter = adapter); + final errors = []; + await client.register( + '20240001', + 'synthetic-password', + promptCaptcha: (_, error, {required refresh}) async { + errors.add(error); + return 'manual-code'; + }, + saveCandidate: (key) async { + adapter.key = key; + }, + ); + expect(errors, [null, '验证码错误,请重试', null]); + expect(adapter.authCaptchaRequests, 2); + expect(adapter.passwordForms.map((f) => f['execution']), ['e1s1', 'e1s2']); + }); + + test('registration recheck distinguishes captcha and password rejection', () async { + final adapter = _School()..recheckCodes.addAll(['2106010003', '0']); + final client = IdsClient(http: Dio()..httpClientAdapter = adapter); + final errors = []; + await client.register( + '20240001', + 'synthetic-password', + promptCaptcha: (_, error, {required refresh}) async { + errors.add(error); + return 'manual-code'; + }, + saveCandidate: (key) async { + adapter.key = key; + }, + ); + expect(errors, [null, '验证码错误,请重试']); + adapter.recheckCodes.add('2106040000'); + await expectLater( + client.register( + '20240001', + 'synthetic-password', + promptCaptcha: (_, __, {required refresh}) async => 'manual-code', + saveCandidate: (_) async {}, + ), + throwsA(isA().having((e) => e.message, 'message', contains('密码错误'))), + ); + }); + + test('registers with manual recheck captcha, then logs in from independent cookie jars', + () async { + final adapter = _School(); + final client = IdsClient(http: Dio()..httpClientAdapter = adapter); + var prompts = 0; + final binding = await client.register( + '20240001', + 'synthetic-password', + promptCaptcha: (image, error, {required refresh}) async { + prompts++; + expect(image, isNotEmpty); + return 'manual-code'; + }, + saveCandidate: (key) async { + adapter.key = key; + }, + ); + expect(prompts, 1); + expect(adapter.finishedRegistration, true); + expect(adapter.registeredDeviceName, matches(r'^Techpie-[a-zA-Z0-9]{6}$')); + expect(binding.session.username, '20240001'); + expect(binding.session.name, 'IDS Profile Name'); + final second = await client.login(binding.credential, backedUp: true); + expect(second.raw['tgc'], isNot(binding.session.raw['tgc'])); + expect(adapter.assertionCounters, [0, 0]); + expect(adapter.assertionFlags, [0x09, 0x19]); + expect(adapter.emptyLoginStarts, 3); + expect(jsonEncode(second.raw), isNot(contains('synthetic-password'))); + expect(jsonEncode(second.raw), isNot(contains(binding.credential.privateKey))); + }); + + test('regenerates colliding names before registering a single Passkey', () async { + final adapter = _School() + ..deviceNames.addAll(['Techpie-aaaaaa', 'Techpie-bbbbbb', 'Other device']); + final client = IdsClient(http: Dio()..httpClientAdapter = adapter, nameRandom: _NameRandom()); + var candidates = 0; + await client.register( + '20240001', + 'synthetic-password', + promptCaptcha: (_, __, {required refresh}) async => 'manual-code', + saveCandidate: (key) async { + candidates++; + adapter.key = key; + }, + ); + expect(adapter.registeredDeviceName, 'Techpie-cccccc'); + expect(candidates, 1); + expect(adapter.registrations, 1); + expect(adapter.requests.where((r) => r.uri.path.endsWith('/queryAllDevices')), hasLength(1)); + }); + + test('does not start registration when existing device names cannot be read', () async { + final adapter = _School()..deviceQueryCode = 'error'; + final client = IdsClient(http: Dio()..httpClientAdapter = adapter); + var savedCandidate = false; + await expectLater( + client.register( + '20240001', + 'synthetic-password', + promptCaptcha: (_, __, {required refresh}) async => 'manual-code', + saveCandidate: (_) async { + savedCandidate = true; + }, + ), + throwsA(isA().having((e) => e.message, 'message', contains('无法读取 IDS'))), + ); + expect(savedCandidate, false); + expect(adapter.requests.any((r) => r.uri.path.endsWith('/startRegister')), false); + expect(adapter.registrations, 0); + }); + + test('remote unbind rechecks manually and deletes only this credential device ID', () async { + final adapter = _School(); + final client = IdsClient(http: Dio()..httpClientAdapter = adapter); + final registered = await client.register( + '20240001', + 'synthetic-password', + promptCaptcha: (_, __, {required refresh}) async => 'manual-code', + saveCandidate: (key) async { + adapter.key = key; + }, + ); + adapter.extraDevices.add({ + 'id': 'other-device', + 'userId': 'opaque-owner-id', + 'deviceName': adapter.registeredDeviceName, + }); + adapter.recheckCodes.addAll(['2106040000', '2106010003', '0']); + final errors = []; + await client.revoke( + registered.credential, + promptVerification: (image, error, {required refresh}) async { + expect(image, isNotEmpty); + errors.add(error); + return (password: 'synthetic-password', captcha: 'manual-code'); + }, + ); + expect(errors, [null, '密码错误,请重试', '验证码错误,请重试']); + expect(adapter.deleteCalls, 1); + expect(adapter.deletedId, registered.credential.anonBiometricsId); + expect(adapter.extraDevices.single['id'], 'other-device'); + }); + + test('cancelled school verification does not submit a delete request', () async { + final adapter = _School(); + final client = IdsClient(http: Dio()..httpClientAdapter = adapter); + final registered = await client.register( + '20240001', + 'synthetic-password', + promptCaptcha: (_, __, {required refresh}) async => 'manual-code', + saveCandidate: (key) async { + adapter.key = key; + }, + ); + await expectLater( + client.revoke( + registered.credential, + promptVerification: (_, __, {required refresh}) async => null, + ), + throwsA(isA()), + ); + expect(adapter.deleteCalls, 0); + }); + + test('school delete errors are reported without selecting another device', () async { + final adapter = _School()..deleteCode = 'error'; + final client = IdsClient(http: Dio()..httpClientAdapter = adapter); + final registered = await client.register( + '20240001', + 'synthetic-password', + promptCaptcha: (_, __, {required refresh}) async => 'manual-code', + saveCandidate: (key) async { + adapter.key = key; + }, + ); + await expectLater( + client.revoke( + registered.credential, + promptVerification: (_, __, {required refresh}) async => + (password: 'synthetic-password', captcha: 'manual-code'), + ), + throwsA(isA()), + ); + expect(adapter.deleteCalls, 1); + }); + + test('mints all four downstream cookies locally and scopes cookies per host/path', () async { + final adapter = _School(); + final client = IdsClient(http: Dio()..httpClientAdapter = adapter); + final bound = await client.register( + '20240001', + 'synthetic-password', + promptCaptcha: (_, __, {required refresh}) async => 'manual-code', + saveCandidate: (key) async { + adapter.key = key; + }, + ); + final expected = { + 'eams': 'JSESSIONID=eams-local', + 'elearning': 'session_id=bb-local', + 'egateApp': 'MOD_AUTH_CAS=egate-local', + 'oa': 'shkjdx_session=oa-local', + }; + for (final entry in expected.entries) { + expect(await client.mintCookie(entry.key, bound.session.raw), contains(entry.value)); + } + expect(adapter.primedEams, true); + expect(adapter.submittedBlackboardForm, true); + expect(adapter.requests.every((r) => CampusHttp.hosts.contains(r.uri.host)), true); + for (final request in adapter.requests.where((r) => r.uri.host != IdsPasskey.rpId)) { + expect(_cookie(request), isNot(contains('CASTGC='))); + expect(_cookie(request), isNot(contains('REFERERCE_TOKEN='))); + } + }); + + test('restoring a cookie jar retains host-only, path and expired-cookie semantics', () async { + final dio = Dio()..httpClientAdapter = _CookieResponse(); + final first = CampusHttp(dio); + await first.request(Uri.parse('${SoftwarePasskey.origin}/authserver/login')); + final restored = CampusHttp(dio); + await restored.restore(first.snapshot); + expect( + await restored.cookieHeader(Uri.parse('${SoftwarePasskey.origin}/authserver/login')), + 'CASTGC=scoped', + ); + expect( + await restored.cookieHeader(Uri.parse('${SoftwarePasskey.origin}/personalInfo/')), + isEmpty, + ); + expect( + await restored.cookieHeader(Uri.parse('https://eams.shanghaitech.edu.cn/eams/')), + isEmpty, + ); + }); +} + +String _cookie(RequestOptions request) => + (request.headers['Cookie'] ?? request.headers['cookie'] ?? '').toString(); + +class _NameRandom implements Random { + int _calls = 0; + @override + int nextInt(int max) => (_calls++ ~/ 6) % max; + @override + bool nextBool() => throw UnsupportedError('unused'); + @override + double nextDouble() => throw UnsupportedError('unused'); +} + +class _CookieResponse implements HttpClientAdapter { + @override + Future fetch( + RequestOptions options, + Stream? requestStream, + Future? cancelFuture, + ) async => + ResponseBody.fromString( + 'ok', + 200, + headers: { + 'set-cookie': [ + 'CASTGC=scoped; Path=/authserver; Secure; HttpOnly', + 'expired=gone; Path=/; Max-Age=0', + ], + }, + ); + @override + void close({bool force = false}) {} +} + +class _School implements HttpClientAdapter { + IdsPasskey? key; + final deviceNames = {}; + String deviceQueryCode = '0'; + String? registeredDeviceName; + int registrations = 0; + final extraDevices = >[]; + final recheckCodes = []; + final passwordErrors = []; + final passwordForms = >[]; + bool forceLoginCaptcha = false; + int passwordFailures = 0; + int authCaptchaRequests = 0; + String deleteCode = '0'; + int deleteCalls = 0; + String? deletedId; + final requests = []; + final assertionCounters = []; + final assertionFlags = []; + var finishedRegistration = false; + var emptyLoginStarts = 0; + var primedEams = false; + var submittedBlackboardForm = false; + var _sessions = 0; + var _challenge = 0; + @override + void close({bool force = false}) {} + + ResponseBody _json( + Map object, { + List cookies = const [], + int status = 200, + }) => + ResponseBody.fromString( + jsonEncode(object), + status, + headers: { + 'content-type': ['application/json'], + if (cookies.isNotEmpty) 'set-cookie': cookies, + }, + ); + ResponseBody _redirect(String target) => ResponseBody.fromString( + '', + 302, + headers: { + 'location': [target], + }, + ); + + @override + Future fetch( + RequestOptions options, + Stream? requestStream, + Future? cancelFuture, + ) async { + requests.add(options); + final path = options.uri.path; + if (options.uri.host != IdsPasskey.rpId) { + if (path == '/eams/home.action' && _cookie(options).contains('JSESSIONID=eams-local')) { + primedEams = true; + return ResponseBody.fromString('home', 200); + } + if (path == '/eams/home.action' || path.endsWith('/dqnxxqgrhz.do')) { + return _redirect( + '${SoftwarePasskey.origin}/authserver/login?service=${Uri.encodeQueryComponent('${options.uri.origin}/session')}', + ); + } + if (path == '/session') { + final cookie = switch (options.uri.host) { + 'eams.shanghaitech.edu.cn' => 'JSESSIONID=eams-local; Path=/eams; Secure', + 'egate.shanghaitech.edu.cn' => 'MOD_AUTH_CAS=egate-local; Path=/xsfw; Secure', + 'oa.shanghaitech.edu.cn' => 'shkjdx_session=oa-local; Path=/; Secure', + _ => '', + }; + return ResponseBody.fromString( + 'authenticated', + options.uri.host.startsWith('eams') ? 302 : 200, + headers: { + 'set-cookie': [cookie], + if (options.uri.host.startsWith('eams')) 'location': ['/eams/home.action'], + }, + ); + } + if (options.uri.host == 'elearning.shanghaitech.edu.cn') { + if (path == '/sso') { + return ResponseBody.fromString( + '
', + 200, + ); + } + if (path.endsWith('/customLogin')) { + expect(Uri.splitQueryString(options.data as String)['token'], 'synthetic&token'); + submittedBlackboardForm = true; + return ResponseBody.fromString( + 'ok', + 200, + headers: { + 'set-cookie': ['session_id=bb-local; Path=/; Secure'], + }, + ); + } + if (path.endsWith('/index.jsp')) return ResponseBody.fromString('portal', 200); + } + throw StateError('Unexpected downstream fixture request: $path'); + } + if (path == '/authserver/login' && options.method == 'GET') { + final service = options.uri.queryParameters['service']; + if (service != null) { + expect(_cookie(options), contains('CASTGC=')); + final target = Uri.parse(service); + return _redirect( + '${target.origin}/${target.host.startsWith('elearning') ? 'sso' : 'session'}', + ); + } + expect(_cookie(options), isEmpty); + emptyLoginStarts++; + return ResponseBody.fromString( + '', + 200, + ); + } + if (path == '/authserver/checkNeedCaptcha.htl') { + return _json({'isNeed': forceLoginCaptcha || passwordFailures >= 2}); + } + if (path == '/authserver/getCaptcha.htl') { + authCaptchaRequests++; + return ResponseBody.fromBytes([137, 80, 78, 71], 200); + } + if (path == '/authserver/login' && options.method == 'POST') { + final form = Uri.splitQueryString(options.data as String); + if (form['cllt'] == 'fidoLogin') { + final wire = jsonDecode(form['responseJson']!) as Map; + final response = wire['credential']['response'] as Map; + final auth = SoftwarePasskey.decode(response['authenticatorData'] as String); + assertionCounters.add(ByteData.sublistView(auth).getUint32(33)); + assertionFlags.add(auth[32]); + } else { + expect(form['password'], isNot('synthetic-password')); + passwordForms.add(form); + if (passwordErrors.isNotEmpty) { + final error = passwordErrors.removeAt(0); + if (error != '验证码错误') passwordFailures++; + return ResponseBody.fromString( + '$error' + '' + '', + 401, + ); + } + } + return _json( + { + 'ok': true, + }, + cookies: [ + 'CASTGC=session-${++_sessions}; Path=/authserver; Secure; HttpOnly', + 'WIS_PER_ENC=0123456789abcdef; Path=/personalInfo; Secure', + 'REFERERCE_TOKEN=ref; Path=/personalInfo; Secure', + ], + ); + } + if (path == '/personalInfo/common/getUserConf') { + return _json({ + 'code': '0', + 'datas': {'uid': '20240001', 'cn': 'IDS Profile Name'}, + }); + } + if (path == '/personalInfo/common/isUserRecheckNecessary') return _json({'code': '2106010001'}); + if (path == '/personalInfo/common/recheckApproach') { + return _json({ + 'code': '0', + 'datas': {'approachName': 'password'}, + }); + } + if (path == '/personalInfo/captcha/checkCode') { + return ResponseBody.fromString('synthetic-image', 200); + } + if (path == '/personalInfo/common/recheckUserInfo') { + expect(_cookie(options), contains('WIS_PER_ENC=')); + final body = jsonDecode(options.data as String) as Map; + expect(body['captcha'], 'manual-code'); + expect(options.headers['refererToken'], 'ref'); + expect(body['password'], isNot('synthetic-password')); + final code = recheckCodes.isEmpty ? '0' : recheckCodes.removeAt(0); + // Captured from IDS: a bad captcha is a business failure over HTTP 500; + // a bad password is HTTP 200 with code 2106040000. + return _json({'code': code}, status: code == '2106010003' ? 500 : 200); + } + if (path == '/personalInfo/accountSecurity/queryAllDevices') { + expect(options.method, 'POST'); + expect(options.headers['refererToken'], 'ref'); + final body = jsonDecode(options.data as String) as Map; + expect(body['pageNumber'], 1); + expect(body['pageSize'], 1000); + expect(body['n'], isA()); + return _json({ + 'code': deviceQueryCode, + 'datas': [ + for (final name in deviceNames) + { + 'deviceName': name, + 'id': key?.anonBiometricsId ?? 'existing-$name', + 'userId': 'opaque-owner-id', + }, + ...extraDevices, + ], + }); + } + if (path == '/personalInfo/accountSecurity/deleteDevice') { + final body = jsonDecode(options.data as String) as Map; + expect(body['id'], key!.anonBiometricsId); + expect(body['response'], 'opaque-owner-id'); + expect(options.headers['refererToken'], 'ref'); + deleteCalls++; + if (deleteCode == '0') deletedId = body['id'] as String; + return _json({'code': deleteCode}); + } + if (path == '/personalInfo/accountSecurity/startRegister') { + expect(requests.any((r) => r.uri.path.endsWith('/queryAllDevices')), true); + return _json({ + 'code': '0', + 'datas': { + 'request': { + 'requestId': 'registration-request', + 'publicKeyCredentialCreationOptions': { + 'challenge': SoftwarePasskey.encode(List.filled(32, 7)), + 'rp': {'id': IdsPasskey.rpId}, + 'user': {'id': 'c3R1ZGVudA', 'name': '20240001'}, + 'pubKeyCredParams': [ + {'alg': -7}, + ], + }, + }, + }, + }); + } + if (path == '/personalInfo/accountSecurity/finishRegister') { + expect(key, isNotNull, reason: 'candidate saved before submitting to IDS'); + final body = jsonDecode(options.data as String) as Map; + final name = body['deviceName'] as String; + expect(name, matches(r'^Techpie-[a-zA-Z0-9]{6}$')); + expect(deviceNames.contains(name), false); + deviceNames.add(name); + registeredDeviceName = name; + registrations++; + expect(body['anonbiometricsd'], key!.anonBiometricsId); + expect((jsonDecode(body['response'] as String) as Map)['requestId'], 'registration-request'); + expect(options.data, isNot(contains(key!.privateKey))); + finishedRegistration = true; + return _json({'code': '0'}); + } + if (path == '/authserver/startAssertion') { + return _json({ + 'result': { + 'request': { + 'requestId': 'assertion-${++_challenge}', + 'publicKeyCredentialRequestOptions': { + 'challenge': SoftwarePasskey.encode(List.filled(32, _challenge)), + 'rpId': IdsPasskey.rpId, + 'allowCredentials': [ + {'id': key!.credentialId}, + ], + }, + }, + }, + }); + } + throw StateError('Unexpected IDS fixture request: $path'); + } +} diff --git a/test/ids_storage_test.dart b/test/ids_storage_test.dart new file mode 100644 index 00000000..82036563 --- /dev/null +++ b/test/ids_storage_test.dart @@ -0,0 +1,62 @@ +import 'dart:convert'; + +import 'package:flutter_secure_storage_ohos/flutter_secure_storage_ohos.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:techpie/models/third_party_account.dart'; +import 'package:techpie/services/storage_service.dart'; +import 'package:techpie/utils/secure_storage.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + setUp(() { + SharedPreferences.setMockInitialValues({}); + FlutterSecureStorage.setMockInitialValues({}); + }); + + Map legacyAccount(String platform) => { + 'platform': platform, + 'account': '20240001', + 'token': 'synthetic-token', + 'autoRenew': true, + 'password': 'synthetic-password', + 'boundAt': '2026-01-01T00:00:00.000Z', + }; + + for (final alias in ['cpdaily', 'egate']) { + test('published $alias storage becomes an IDS account with upgrade credentials', () async { + final oldKey = 'third_party_$alias'; + await appSecureStorage.write(key: oldKey, value: jsonEncode(legacyAccount(alias))); + final storage = StorageService(await SharedPreferences.getInstance()); + + final account = (await storage.loadAllThirdPartyAccounts()).single; + expect(account.platform, ThirdPartyPlatform.ids); + expect(account.account, '20240001'); + expect(account.password, 'synthetic-password'); + final canonical = jsonDecode((await appSecureStorage.read(key: 'third_party_ids'))!) + as Map; + expect(canonical['platform'], 'ids'); + expect(await appSecureStorage.read(key: oldKey), isNull); + + await storage.clearThirdPartyAccount(ThirdPartyPlatform.ids); + expect(await storage.loadAllThirdPartyAccounts(), isEmpty); + }); + } + + test('removing IDS also removes stale aliases so they cannot reappear after restart', () async { + final storage = StorageService(await SharedPreferences.getInstance()); + await appSecureStorage.write(key: 'third_party_ids', value: jsonEncode(legacyAccount('ids'))); + for (final alias in ['cpdaily', 'egate']) { + await appSecureStorage.write( + key: 'third_party_$alias', + value: jsonEncode(legacyAccount(alias)), + ); + } + expect((await storage.loadAllThirdPartyAccounts()).single.platform, ThirdPartyPlatform.ids); + + await storage.clearThirdPartyAccount(ThirdPartyPlatform.ids); + final restarted = StorageService(await SharedPreferences.getInstance()); + expect(await restarted.loadAllThirdPartyAccounts(), isEmpty); + }); +} diff --git a/test/ids_unbind_test.dart b/test/ids_unbind_test.dart new file mode 100644 index 00000000..166e25dc --- /dev/null +++ b/test/ids_unbind_test.dart @@ -0,0 +1,98 @@ +import 'dart:async'; + +import 'package:flutter_secure_storage_ohos/flutter_secure_storage_ohos.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:shared_preferences/shared_preferences.dart'; +import 'package:techpie/models/ids_passkey.dart'; +import 'package:techpie/models/third_party_account.dart'; +import 'package:techpie/services/debug_logger.dart'; +import 'package:techpie/services/http_client.dart'; +import 'package:techpie/services/ids/ids_client.dart'; +import 'package:techpie/services/storage_service.dart'; +import 'package:techpie/services/third_party_auth_service.dart'; + +import 'support/fake_ids_client.dart'; + +void main() { + TestWidgetsFlutterBinding.ensureInitialized(); + + for (final fail in [false, true]) { + test('local deletion is complete before school unbind ${fail ? "fails" : "succeeds"}', + () async { + final fixture = await _Fixture.create(); + final result = fixture.auth + .unbindIdsWithRemote(promptVerification: (_, __, {required refresh}) async => null); + await fixture.client.started.future; + expect(fixture.auth.idsBinding!.credential, isNull); + expect(fixture.auth.idsAccount, isNull); + expect( + IdsSyncBinding.fromAccount( + await fixture.storage.loadThirdPartyAccount(ThirdPartyPlatform.ids),) + ?.credential, + isNull,); + expect(fixture.client.key!.credentialId, 'synthetic-A'); + if (fail) { + fixture.client.done.completeError(const IdsException('synthetic failure')); + } else { + fixture.client.done.complete(); + } + expect(await result, !fail); + expect(fixture.auth.idsBinding!.credential, isNull); + }); + } + + test('finishing an old school unbind does not remove a newer local Passkey', () async { + final fixture = await _Fixture.create(); + final result = fixture.auth + .unbindIdsWithRemote(promptVerification: (_, __, {required refresh}) async => null); + await fixture.client.started.future; + await fixture.auth.bindIds( + account: 'B', + password: 'synthetic-password', + promptCaptcha: (_, __, {required refresh}) async => null,); + fixture.client.done.complete(); + expect(await result, true); + expect(fixture.client.key!.username, 'A'); + expect(fixture.auth.idsBinding!.credential!.username, 'B'); + final stored = (await fixture.storage.loadThirdPartyAccount(ThirdPartyPlatform.ids))!; + expect(IdsSyncBinding.fromAccount(stored)!.credential!.username, 'B'); + expect(stored.password, isNull); + expect(stored.toJson().containsKey('password'), false); + }); +} + +class _RemoteIds extends FakeIdsClient { + final started = Completer(); + final done = Completer(); + IdsPasskey? key; + @override + Future revoke(IdsPasskey key, {required IdsVerificationPrompt promptVerification}) { + this.key = key; + started.complete(); + return done.future; + } +} + +class _Fixture { + _Fixture(this.auth, this.storage, this.client); + final ThirdPartyAuthService auth; + final StorageService storage; + final _RemoteIds client; + static Future<_Fixture> create() async { + SharedPreferences.setMockInitialValues({}); + FlutterSecureStorage.setMockInitialValues({}); + final storage = StorageService(await SharedPreferences.getInstance()); + final http = LoggingHttpClient(DebugLogger()); + final client = _RemoteIds(); + final auth = ThirdPartyAuthService(storage, http, idsClient: client); + await auth.initialize(); + await auth.applyIdsSyncBinding( + IdsSyncBinding( + credential: FakeIdsClient.key('A'), + updatedAt: DateTime.now().subtract(const Duration(days: 1)), + deviceId: 'fixture', + ), + ); + return _Fixture(auth, storage, client); + } +} diff --git a/test/ios_first_frame_test.dart b/test/ios_first_frame_test.dart new file mode 100644 index 00000000..fd277f3a --- /dev/null +++ b/test/ios_first_frame_test.dart @@ -0,0 +1,67 @@ +import 'package:flutter/material.dart'; +import 'package:flutter/scheduler.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:techpie/utils/platform.dart'; +import 'package:techpie/widgets/ios/ios_native_tab_bar.dart'; + +class _FirstFrameBinding extends AutomatedTestWidgetsFlutterBinding { + final warmUpPhases = []; + int idleWarmUps = 0; + + @override + void allowFirstFrame() { + final needsFrame = !sendFramesToEngine; + super.allowFirstFrame(); + // The test binding suppresses this automatic scheduling. Restore the + // production renderer contract so a manual pump cannot hide the bug. + if (needsFrame) scheduleWarmUpFrame(); + } + + @override + void scheduleWarmUpFrame() { + warmUpPhases.add(schedulerPhase); + // Production SchedulerBinding rejects warm-up requests within a frame; + // the standard widget-test binding otherwise bypasses that restriction. + if (schedulerPhase != SchedulerPhase.idle) return; + idleWarmUps++; + super.scheduleWarmUpFrame(); + } +} + +void main() { + final binding = _FirstFrameBinding(); + testWidgets( + 'releasing the native tab bar first-frame hold schedules a frame while idle', + (tester) async { + debugUsesIosLiquidGlass = true; + addTearDown(() => debugUsesIosLiquidGlass = false); + await tester.pumpWidget( + MaterialApp( + home: Scaffold( + bottomNavigationBar: IosNativeTabBar( + selectedIndex: 0, + items: const [ + IosNativeTabBarItem( + label: 'Home', + icon: Icons.home, + selectedIcon: Icons.home, + sfSymbol: 'house', + selectedSfSymbol: 'house.fill', + ), + ], + onSelected: (_) {}, + ), + ), + ), + ); + final before = binding.idleWarmUps; + // Dispose occurs inside the frame. No pump/gesture follows to rescue a + // missing frame: allowFirstFrame must schedule the warm-up on its own. + await tester.pumpWidget(const SizedBox()); + expect(binding.warmUpPhases, everyElement(SchedulerPhase.idle)); + expect(binding.idleWarmUps - before, 1); + expect(tester.takeException(), isNull); + }, + variant: TargetPlatformVariant.only(TargetPlatform.iOS), + ); +} diff --git a/test/oa_gym_local_client_test.dart b/test/oa_gym_local_client_test.dart new file mode 100644 index 00000000..d7b2e99f --- /dev/null +++ b/test/oa_gym_local_client_test.dart @@ -0,0 +1,272 @@ +import 'dart:async'; + +import 'package:flutter_test/flutter_test.dart'; +import 'package:techpie/services/campus_user_agent.dart'; +import 'package:techpie/services/oa_gym_local_client.dart'; + +import 'support/oa_school_client.dart'; + +const _cookies = 'shkjdx_session=synthetic-oa'; +const _venue = '羽毛球场地 1 号(东馆)'; + +void main() { + test('reads the current user contact form with GET and never submits an edit', () async { + final school = OaSchoolClient(); + final result = await OaGymLocalClient(school).request( + 'oa/gym/profile', + {'id': 'caller-must-not-select-another-user'}, + cookies: '$_cookies; loginidweaver=fixture-current-user', + ); + expect(result['data'], {'phone': '13900000000', 'email': 'student@shanghaitech.edu.cn'}); + expect(school.requests, hasLength(1)); + final request = school.requests.single; + expect(request.method, 'GET'); + expect(request.url.host, 'oa.shanghaitech.edu.cn'); + expect(request.url.path, '/hrm/resource/HrmResourceContactEdit.jsp'); + expect( + request.url.queryParameters, + {'isfromtab': 'true', 'id': 'fixture-current-user', 'isView': '1'}, + ); + expect(request.body, isEmpty); + }); + + test('initializes the OA current user when only the session cookie is available', () async { + final school = OaSchoolClient(); + final result = await OaGymLocalClient(school).request('oa/gym/profile', {}, cookies: _cookies); + expect(result['data']['phone'], '13900000000'); + expect(school.requests, hasLength(2)); + expect(school.requests.first.url.path, '/workflow/request/AddRequest.jsp'); + expect(school.requests.every((r) => r.method == 'GET'), true); + expect(school.requests.last.headers['Cookie'], contains('loginidweaver=fixture-current-user')); + }); + + test('does not read contacts from a form for a different OA user', () async { + final school = OaSchoolClient() + ..intercept = (_) async => OaSchoolClient.text( + '
' + '
', + ); + await expectLater( + OaGymLocalClient(school).request( + 'oa/gym/profile', + {}, + cookies: '$_cookies; loginidweaver=fixture-current-user', + ), + throwsA(isA().having((e) => e.message, 'message', contains('当前用户'))), + ); + expect(school.requests, hasLength(1)); + }); + + test('loads OA metadata locally and parses encoded XML without sending IDS credentials', + () async { + final school = OaSchoolClient(); + final result = await OaGymLocalClient(school).request('oa/gym/metadata', {}, cookies: _cookies); + expect(result['data']['venues'][_venue], '13'); + expect(result['data']['venues'].containsKey('匹克球2号场地'), false); + expect(result['data']['timeSlots'], {'18:00-19:00': '8'}); + expect(school.requests, hasLength(4)); + expect(school.requests.map((r) => r.url.path), [ + '/formmode/browser/CommonSingleBrowser.jsp', + '/formmode/browser/CommonSingleBrowser.jsp', + '/weaver/weaver.common.util.taglib.SplitPageXmlServlet', + '/weaver/weaver.common.util.taglib.SplitPageXmlServlet', + ]); + expect( + school.requests[0].url.queryParameters['currenttime'], + school.requests[1].url.queryParameters['currenttime'], + ); + for (final request in school.requests) { + expect(request.url.host, 'oa.shanghaitech.edu.cn'); + expect(request.followRedirects, false); + expect(request.headers['User-Agent'], CampusUserAgent.value); + expect(request.headers['Cookie'], _cookies); + expect(request.headers['Cookie'], isNot(contains('CASTGC'))); + expect(request.headers['Origin'], 'https://oa.shanghaitech.edu.cn'); + } + }); + + test('uses the OA tree picker and excludes the unused pickleball court', () async { + final school = OaSchoolClient(); + final result = await OaGymLocalClient(school).request( + 'oa/gym/availability', + { + 'sports': ['badminton', 'pickleball'], + 'date': '2026-11-03', + 'startSlot': 8, + 'endSlot': 8, + }, + cookies: _cookies, + ); + expect(result['data'][0]['availableCourts'], [1, 2]); + expect(result['data'][1]['availableCourts'], [1]); + expect(school.requests, hasLength(4)); + for (final request in school.requests) { + expect(request.headers['Accept'], 'text/plain, */*; q=0.01'); + expect(request.headers['Content-Type'], 'application/x-www-form-urlencoded'); + expect( + request.headers['Referer'], 'https://oa.shanghaitech.edu.cn/wui/main.jsp?templateId=1',); + expect(request.headers.containsKey('Origin'), false); + } + expect( + school.requests.last.url.queryParameters['dataconditionParam'], + '_sfn_31901_sfv_2026-11-03_sfn_31902_sfv_8_sfn_32340_sfv_11', + ); + }); + + test('search preserves repeated condition fields and decodes the result rows', () async { + final school = OaSchoolClient(); + final result = await _search(OaGymLocalClient(school)); + final form = Uri(query: school.requests.first.body).queryParametersAll; + expect(school.requests.first.headers['Content-Type'], 'application/x-www-form-urlencoded'); + expect(school.requests.first.body, contains('%20')); + expect(school.requests.first.body, isNot(contains('+'))); + expect(form['check_con'], ['31869', '31870', '31871']); + expect(form['con31869_value'], ['13']); + expect(form['con31871_value'], ['8']); + expect( + result['data'][0]['rows'], + [ + ['2026-11-03', '已通过'], + ], + ); + }); + + test('a mid-search 401 propagates even when an earlier time range succeeded', () async { + final school = OaSchoolClient(); + var queries = 0; + school.intercept = (request) async { + if (request.url.path.contains('CustomSearch') && ++queries == 2) { + return OaSchoolClient.text('expired', status: 401); + } + return null; + }; + await expectLater( + _search(OaGymLocalClient(school), ranges: ['', '18:00-19:00']), + throwsA(isA().having((e) => e.sessionExpired, 'sessionExpired', true)), + ); + expect(queries, 2); + }); + + for (final location in ['https://ids.shanghaitech.edu.cn/authserver/login', '/login/Login.jsp']) { + test('does not follow an OA expiry redirect to $location', () async { + final school = OaSchoolClient() + ..intercept = + (_) async => OaSchoolClient.text('', status: 302, headers: {'location': location}); + await expectLater( + OaGymLocalClient(school).request('oa/gym/metadata', {}, cookies: _cookies), + throwsA(isA().having((e) => e.sessionExpired, 'sessionExpired', true)), + ); + expect(school.requests, hasLength(1)); + }); + } + + test('submits the physical court and actual OA user in a mocked booking only', () async { + final school = OaSchoolClient(); + final result = await _book(OaGymLocalClient(school)); + expect(result['data']['success'], true); + final form = Uri.splitQueryString(school.requests.last.body); + expect(school.requests.last.headers['Content-Type'], 'application/x-www-form-urlencoded'); + expect(school.requests.last.headers.containsKey('Origin'), false); + expect(school.requests.last.body, contains('field31888=Fixture%20User')); + expect(form['field31876'], 'fixture-current-user'); + expect(form['field34283'], '20240001'); + expect(form['field31883'], '63_43'); + expect(form['field32340'], '11'); + expect(form['field31904'], '18:00'); + expect(form['field31905'], '19:00'); + expect(form['workflowid'], '14862'); + expect(form.containsKey('fixture-current-user_14862_addrequest_submit_token'), true); + expect(school.requests.last.headers['Cookie'], contains('loginidweaver=fixture-current-user')); + }); + + test('does not substitute a hardcoded user or submit when OA omits the user cookie', () async { + final school = OaSchoolClient() + ..intercept = (_) async => OaSchoolClient.text('workflow'); + await expectLater( + _book(OaGymLocalClient(school)), + throwsA( + isA().having((e) => e.message, 'message', contains('无法确认 OA 当前用户')), + ), + ); + expect(school.requests, hasLength(1)); + expect(school.requests.single.method, 'GET'); + }); + + test('a booking timeout is not retried and asks the user to check existing reservations', + () async { + final school = OaSchoolClient() + ..intercept = (request) async { + if (request.url.path.endsWith('RequestOperation.jsp')) throw TimeoutException('synthetic'); + return null; + }; + await expectLater( + _book(OaGymLocalClient(school)), + throwsA( + isA() + .having((e) => e.sessionExpired, 'sessionExpired', false) + .having((e) => e.message, 'message', contains('确认结果,避免重复提交')), + ), + ); + expect(school.requests.where((r) => r.method == 'POST'), hasLength(1)); + }); + + test('follows OA table pagination instead of dropping records after the first ten', () async { + final school = OaSchoolClient() + ..intercept = (request) async { + if (request.url.path.endsWith('SplitPageXmlServlet')) { + final fields = Uri.splitQueryString(request.body); + if (fields['tableString'] == 'AA') { + final page = int.parse(fields['pageIndex']!); + final count = page == 0 ? 10 : 1; + return OaSchoolClient.text( + '${List.generate(count, (i) => '${page * 10 + i + 1}').join()}', + ); + } + } + return null; + }; + final result = await OaGymLocalClient(school).request('oa/gym/metadata', {}, cookies: _cookies); + expect(result['data']['timeSlots'], hasLength(11)); + expect( + school.requests + .where((r) => r.body.contains('tableString=AA')) + .map((r) => Uri.splitQueryString(r.body)['pageIndex']), + ['0', '1'], + ); + }); +} + +Future> _search( + OaGymLocalClient client, { + List ranges = const ['18:00-19:00'], +}) => + client.request( + 'oa/gym/search', + { + 'startDate': '2026-11-03', + 'endDate': '2026-11-03', + 'venueNames': [_venue], + 'timeRanges': ranges, + }, + cookies: _cookies, + venues: {_venue: '13'}, + timeSlots: {'18:00-19:00': '8'}, + ); + +Future> _book(OaGymLocalClient client) => client.request( + 'oa/gym/book', + { + 'booking': { + 'sport': 'pickleball', + 'date': '2026-11-03', + 'timeSlot': 8, + 'courtNumber': 1, + 'playersCount': 2, + 'studentId': '20240001', + 'userName': 'Fixture User', + 'phone': '13800000000', + 'email': '', + }, + }, + cookies: _cookies, + ); diff --git a/test/oa_gym_service_test.dart b/test/oa_gym_service_test.dart index 41f1a4b1..875c0dd4 100644 --- a/test/oa_gym_service_test.dart +++ b/test/oa_gym_service_test.dart @@ -1,10 +1,10 @@ import 'dart:async'; -import 'dart:convert'; import 'package:flutter_secure_storage_ohos/flutter_secure_storage_ohos.dart'; import 'package:flutter_test/flutter_test.dart'; import 'package:http/http.dart' as http; import 'package:shared_preferences/shared_preferences.dart'; +import 'package:techpie/models/ids_passkey.dart'; import 'package:techpie/models/oa_gym.dart'; import 'package:techpie/models/third_party_account.dart'; import 'package:techpie/models/user_session.dart'; @@ -16,227 +16,30 @@ import 'package:techpie/services/storage_service.dart'; import 'package:techpie/services/third_party_auth_service.dart'; import 'package:techpie/services/uni_auth_service.dart'; -void main() { - test('queries availability through TechPie backend with CASTGC payload', - () async { - final fixture = await _serviceFixture(); - final requests = []; - final client = _FakeClient((request) async { - requests.add(request.url); - expect(request.url.host, anyOf('techpie.geekpie.club', 'localhost')); - expect(request.url.path, '/api/oa/gym/availability'); - expect(request.headers['Content-Type'], contains('application/json')); - - final body = jsonDecode(await request.finalize().bytesToString()) - as Map; - expect(body['auth']['tgc'], 'tgc-value'); - expect(body['auth']['cookies'], 'happyVoyage=happy; CASTGC=tgc-value'); - expect(body['sports'], ['badminton']); - expect(body['date'], '2026-05-23'); - expect(body['startSlot'], 8); - expect(body['endSlot'], 8); - return _jsonResponse({ - 'success': true, - 'data': [ - { - 'sport': 'badminton', - 'date': '2026-05-23', - 'timeSlot': 8, - 'availableCourts': [1, 3], - 'totalCourts': 6, - } - ], - }); - }); - - final service = OaGymService( - fixture.auth, - fixture.storage, - fixture.tpAuth, - client: client, - ); - final result = await service.checkAvailability( - sports: {OaSport.badminton}, - date: '2026-05-23', - startSlot: 8, - endSlot: 8, - ); - - expect(result, hasLength(1)); - expect(result.single.availableCourts, [1, 3]); - expect(requests.single.host, isNot(contains('shanghaitech.edu.cn'))); - }); - - test('loads metadata and searches courts through TechPie backend', () async { - final fixture = await _serviceFixture(); - final paths = []; - final client = _FakeClient((request) async { - paths.add(request.url.path); - expect(request.url.host, anyOf('techpie.geekpie.club', 'localhost')); - final body = jsonDecode(await request.finalize().bytesToString()) - as Map; - expect(body['auth']['tgc'], 'tgc-value'); - - if (request.url.path == '/api/oa/gym/metadata') { - return _jsonResponse({ - 'success': true, - 'data': { - 'venues': { - '所有场地': 'all', - '室内羽毛球场': 'badminton_group', - '羽毛球场地 1 号(东馆)': '13', - }, - 'allVenues': { - '羽毛球场地 1 号(东馆)': '13', - }, - 'timeSlots': { - '18:00-19:00': '8', - }, - }, - }); - } - - expect(request.url.path, '/api/oa/gym/search'); - expect(body['startDate'], '2026-05-23'); - expect(body['endDate'], '2026-05-23'); - expect(body['venueNames'], ['羽毛球场地 1 号(东馆)']); - expect(body['timeRanges'], ['18:00-19:00']); - return _jsonResponse({ - 'success': true, - 'data': [ - { - 'venue': '羽毛球场地 1 号(东馆)', - 'timeRange': '18:00-19:00', - 'rows': [ - [ - '1', - '', - '2026-05-23', - '', - '', - '', - '已通过', - 'User', - '', - '2026-05-24', - ], - ], - } - ], - }); - }); - - final service = OaGymService( - fixture.auth, - fixture.storage, - fixture.tpAuth, - client: client, - ); - final result = await service.searchCourts( - startDate: '2026-05-23', - endDate: '2026-05-23', - venueNames: {'室内羽毛球场'}, - timeRanges: const ['18:00-19:00'], - ); - - expect(result, hasLength(1)); - expect(result.single.venue, '羽毛球场地 1 号(东馆)'); - expect(result.single.rows.single[6], '已通过'); - expect(paths, ['/api/oa/gym/metadata', '/api/oa/gym/search']); - }); - - test('books courts through TechPie backend', () async { - final fixture = await _serviceFixture(); - final client = _FakeClient((request) async { - expect(request.url.path, '/api/oa/gym/book'); - final body = jsonDecode(await request.finalize().bytesToString()) - as Map; - expect(body['auth']['tgc'], 'tgc-value'); - expect(body['booking']['sport'], 'badminton'); - expect(body['booking']['studentId'], '20240001'); - expect(body['booking']['userName'], 'User'); - expect(body['booking']['phone'], '13800000000'); - return _jsonResponse({ - 'success': true, - 'data': { - 'success': true, - 'message': '羽毛球 羽毛球场地1号 18:00-19:00 预约成功', - }, - }); - }); +import 'support/fake_ids_client.dart'; +import 'support/oa_school_client.dart'; - final service = OaGymService( - fixture.auth, - fixture.storage, - fixture.tpAuth, - client: client, - ); - final result = await service.bookCourt( - sport: OaSport.badminton, - date: '2026-05-23', - timeSlot: 8, - courtNumber: 1, - playersCount: 2, - ); - - expect(result.success, isTrue); - expect(result.message, contains('预约成功')); - }); +bool _isContact(http.Request request) => request.url.path.endsWith('/HrmResourceContactEdit.jsp'); +void main() { test( 'shared courts use physical availability and never expose the unused court', () async { final fixture = await _serviceFixture(); - final slots = []; - final client = _FakeClient((request) async { - final body = jsonDecode(await request.finalize().bytesToString()) - as Map; - expect((body['sports'] as List).toSet(), {'tennis', 'pickleball'}); - expect(body['startSlot'], body['endSlot']); - final slot = body['startSlot'] as int; - slots.add(slot); - return _jsonResponse({ - 'success': true, - 'data': [ - { - 'sport': 'tennis', - 'date': '2026-10-08', - 'timeSlot': slot, - 'availableCourts': [1, 3], - }, - // Even an old backend returning the bogus OA leaf must not expose it. - { - 'sport': 'pickleball', - 'date': '2026-10-08', - 'timeSlot': slot, - 'availableCourts': [1, 2], - }, - ], - }); - }); - final service = OaGymService( - fixture.auth, - fixture.storage, - fixture.tpAuth, - client: client, - ); + final school = OaSchoolClient(); + final service = _service(fixture, school); final progress = []; final result = await service.checkAvailability( sports: {OaSport.tennis, OaSport.pickleball}, date: '2026-10-08', startSlot: 8, endSlot: 9, - onProgress: (data) => progress.add(data.length), + onProgress: (rows) => progress.add(rows.length), ); - expect(slots, [8, 9]); expect(progress, [2, 4]); expect( result.where((row) => row.sport == OaSport.tennis).first.availableCourts, - [1, 3, 4], - ); - expect( - result.where((row) => row.sport == OaSport.tennis).first.totalCourts, - 4, + [1, 2, 4], ); expect( result @@ -246,31 +49,14 @@ void main() { [1, 2], ); expect(oaCourtForSport(OaSport.pickleball, 2).label, contains('网球场1号')); - expect( - oaCourtsForSport(OaSport.pickleball).map((court) => court.physicalKey), - ['pickleball|1', 'tennis|1'], - ); + expect(school.requests.every((r) => r.url.host == 'oa.shanghaitech.edu.cn'), true); }); - test('booking shared courts submits the original OA category and number', + test('booking shared courts submits the physical OA court without repeating a submission', () async { final fixture = await _serviceFixture(); - final bookings = >[]; - final client = _FakeClient((request) async { - final body = jsonDecode(await request.finalize().bytesToString()) - as Map; - bookings.add((body['booking'] as Map).cast()); - return _jsonResponse({ - 'success': true, - 'data': {'success': true, 'message': '预约成功'}, - }); - }); - final service = OaGymService( - fixture.auth, - fixture.storage, - fixture.tpAuth, - client: client, - ); + final school = OaSchoolClient(); + final service = _service(fixture, school); await service.bookCourt( sport: OaSport.tennis, date: '2026-10-08', @@ -285,11 +71,9 @@ void main() { courtNumber: 2, playersCount: 2, ); - expect( - bookings.map((booking) => booking['sport']), - ['pickleball', 'tennis'], - ); - expect(bookings.map((booking) => booking['courtNumber']), [1, 1]); + final bookings = + school.requests.where((r) => r.url.path.endsWith('/RequestOperation.jsp')).toList(); + expect(bookings.map((r) => Uri.splitQueryString(r.body)['field31883']), ['63_43', '63_25']); await expectLater( service.bookCourt( sport: OaSport.pickleball, @@ -300,256 +84,107 @@ void main() { ), throwsA(isA()), ); - expect(bookings, hasLength(2)); + expect( + school.requests.where((r) => r.url.path.endsWith('/RequestOperation.jsp')), + hasLength(2), + ); }); - test( - 'metadata is single flight and OA cookies survive only within the same session', + test('metadata is single flight and reused until the session is cleared', () async { final fixture = await _serviceFixture(); - final metadata = Completer(); - var metadataCalls = 0; - var availabilityCalls = 0; - final client = _FakeClient((request) async { - final body = jsonDecode(await request.finalize().bytesToString()) - as Map; - if (request.url.path.endsWith('/metadata')) { - metadataCalls++; - return metadata.future; - } - availabilityCalls++; - if (availabilityCalls == 1) { - expect(body['auth']['oaCookies'], 'shkjdx_session=oa-session'); - } else { - expect(body['auth']['oaCookies'], isNull); - } - return _jsonResponse({ - 'success': true, - 'data': [ - { - 'sport': 'badminton', - 'date': '2026-10-08', - 'timeSlot': 8, - 'availableCourts': [1], - }, - ], - }); - }); - final service = OaGymService( - fixture.auth, - fixture.storage, - fixture.tpAuth, - client: client, - ); + final started = Completer(); + final release = Completer(); + var browsers = 0; + final school = OaSchoolClient() + ..intercept = (request) async { + if (request.url.path.endsWith('/CommonSingleBrowser.jsp') && ++browsers == 1) { + started.complete(); + await release.future; + } + return null; + }; + final service = _service(fixture, school); final first = service.ensureReady(); final second = service.ensureReady(); - await Future.delayed(Duration.zero); - expect(metadataCalls, 1); - metadata.complete( - _jsonResponse({ - 'success': true, - 'session': {'oaCookies': 'shkjdx_session=oa-session'}, - 'data': { - 'venues': {'羽毛球场地1号': '13'}, - 'allVenues': {'羽毛球场地1号': '13'}, - 'timeSlots': {'18:00-19:00': '8'}, - }, - }), - ); + await started.future; + expect(browsers, 1); + release.complete(); await Future.wait([first, second]); - await service.checkAvailability( - sports: {OaSport.badminton}, - date: '2026-10-08', - startSlot: 8, - endSlot: 8, - ); + expect(browsers, 2); + await service.ensureReady(); + expect(browsers, 2); service.clearSession(); - await service.checkAvailability( - sports: {OaSport.badminton}, - date: '2026-10-08', - startSlot: 8, - endSlot: 8, - ); - expect(service.loading, isFalse); - }); - - test('bulk search uses one request and filters unused pickleball metadata', - () async { - final fixture = await _serviceFixture(); - var searches = 0; - final client = _FakeClient((request) async { - final body = jsonDecode(await request.finalize().bytesToString()) - as Map; - if (request.url.path.endsWith('/metadata')) { - return _jsonResponse({ - 'success': true, - 'capabilities': {'bulkSearch': true}, - 'data': { - 'venues': { - '所有场地': 'all', - '网球场1号': '25', - '网球场2号': '26', - '网球场3号': '27', - '匹克球1号场地': '43', - '匹克球2号场地': '44', - }, - 'allVenues': {'匹克球2号场地': '44'}, - 'timeSlots': {'18:00-19:00': '8', '19:00-20:00': '9'}, - }, - }); - } - searches++; - expect( - (body['venueNames'] as List).toSet(), - {'网球场1号', '网球场2号', '网球场3号', '匹克球1号场地'}, - ); - return _jsonResponse({ - 'success': true, - 'data': [ - for (final venue in body['venueNames'] as List) - for (final time in body['timeRanges'] as List) - {'venue': venue, 'timeRange': time, 'rows': []}, - ], - }); - }); - final service = OaGymService( - fixture.auth, - fixture.storage, - fixture.tpAuth, - client: client, - ); - await service.searchCourts( - startDate: '2026-10-08', - endDate: '2026-10-08', - venueNames: {}, - timeRanges: ['18:00-19:00', '19:00-20:00'], - ); - expect(searches, 1); - expect(service.venues.keys, isNot(contains('匹克球2号场地'))); + await service.ensureReady(); + expect(browsers, 4); + expect(service.loading, false); }); - test( - 'legacy searches are bounded and failures are not reported as empty results', + test('local search bounds concurrency and reports failures instead of empty results', () async { final fixture = await _serviceFixture(); var active = 0; var peak = 0; var searches = 0; - final client = _FakeClient((request) async { - final body = jsonDecode(await request.finalize().bytesToString()) - as Map; - if (request.url.path.endsWith('/metadata')) { - return _jsonResponse({ - 'success': true, - 'data': { - 'venues': {for (var i = 1; i <= 6; i++) '羽毛球场地$i号': '${12 + i}'}, - 'timeSlots': {'18:00-19:00': '8'}, - }, - }); - } - expect(body['venueNames'], hasLength(1)); - searches++; - active++; - if (active > peak) peak = active; - await Future.delayed(const Duration(milliseconds: 5)); - active--; - return _jsonResponse({ - 'success': true, - 'data': [ - for (final venue in body['venueNames'] as List) - for (final time in body['timeRanges'] as List) - {'venue': venue, 'timeRange': time, 'rows': []}, - ], - }); - }); - final service = OaGymService( - fixture.auth, - fixture.storage, - fixture.tpAuth, - client: client, - ); - await service.searchCourts( - startDate: '2026-10-08', - endDate: '2026-10-08', - venueNames: {}, - timeRanges: ['18:00-19:00'], - ); - expect(searches, 6); - expect(peak, 3); + final school = OaSchoolClient() + ..intercept = (request) async { + if (request.url.path.endsWith('/SplitPageXmlServlet') && + Uri.splitQueryString(request.body)['tableString'] == 'BB') { + return OaSchoolClient.text( + '${List.generate(6, (i) => '${13 + i}').join()}',); + } + if (request.url.path.contains('/CustomSearch')) { + final attempt = ++searches; + active++; + if (active > peak) peak = active; + await Future.delayed(const Duration(milliseconds: 1)); + active--; + if (attempt == 3) return OaSchoolClient.text('failed', status: 503); + } + return null; + }; + final service = _service(fixture, school); await expectLater( service.searchCourts( - startDate: '2026-10-09', + startDate: '2026-10-08', endDate: '2026-10-08', venueNames: {}, - timeRanges: [], - ), - throwsA(isA()), - ); - expect(searches, 6); - }); - - test('missing availability rows are unknown rather than fully booked', - () async { - final fixture = await _serviceFixture(); - final client = _FakeClient( - (request) async => _jsonResponse({'success': true, 'data': []}), - ); - final service = OaGymService( - fixture.auth, - fixture.storage, - fixture.tpAuth, - client: client, - ); - await expectLater( - service.checkAvailability( - sports: {OaSport.tennis}, - date: '2026-10-08', - startSlot: 8, - endSlot: 8, + timeRanges: ['18:00-19:00'], ), throwsA(isA()), ); + expect(peak, lessThanOrEqualTo(3)); + expect(searches, greaterThanOrEqualTo(3)); + expect(service.loading, false); }); - test('superseded availability checks stop queued hours without overlapping', + test('superseded availability stops queued hours without overlapping checks', () async { final fixture = await _serviceFixture(); - final firstEntered = Completer(); - final releaseFirst = Completer(); + final started = Completer(); + final release = Completer(); final slots = []; + var current = true; var active = 0; var peak = 0; - var current = true; - final client = _FakeClient((request) async { - final body = jsonDecode(await request.finalize().bytesToString()) - as Map; - final slot = body['startSlot'] as int; - slots.add(slot); - active++; - if (active > peak) peak = active; - if (slots.length == 1) { - firstEntered.complete(); - await releaseFirst.future; - } - active--; - return _jsonResponse({ - 'success': true, - 'data': [ - { - 'sport': 'badminton', - 'date': body['date'], - 'timeSlot': slot, - 'availableCourts': [1], - }, - ], - }); - }); - final service = OaGymService( - fixture.auth, - fixture.storage, - fixture.tpAuth, - client: client, - ); + final school = OaSchoolClient() + ..intercept = (request) async { + if (request.url.path.contains('/CustomTreeBrowser') && + Uri.splitQueryString(request.body)['pid'] == '63_1') { + slots.add(int.parse(RegExp(r'_sfn_31902_sfv_(\d+)') + .firstMatch(request.url.queryParameters['dataconditionParam']!)! + .group(1)!,),); + active++; + if (active > peak) peak = active; + if (slots.length == 1) { + started.complete(); + await release.future; + } + active--; + } + return null; + }; + final service = _service(fixture, school); final first = service.checkAvailability( sports: {OaSport.badminton}, date: '2026-10-08', @@ -557,7 +192,7 @@ void main() { endSlot: 10, shouldContinue: () => current, ); - await firstEntered.future; + await started.future; current = false; final second = service.checkAvailability( sports: {OaSport.badminton}, @@ -567,72 +202,28 @@ void main() { ); await Future.delayed(Duration.zero); expect(slots, [8]); - releaseFirst.complete(); - final results = await Future.wait([first, second]); + release.complete(); + final result = await Future.wait([first, second]); expect(slots, [8, 9]); expect(peak, 1); - expect(results.first, hasLength(1)); - expect(results.last.single.date, '2026-10-09'); - expect(service.loading, isFalse); - }); - - test('incomplete search responses are reported instead of hiding failures', - () async { - final fixture = await _serviceFixture(); - final client = _FakeClient((request) async { - if (request.url.path.endsWith('/metadata')) { - return _jsonResponse({ - 'success': true, - 'data': { - 'venues': {'网球场1号': '25'}, - 'timeSlots': {'18:00-19:00': '8', '19:00-20:00': '9'}, - }, - }); - } - return _jsonResponse({ - 'success': true, - 'data': [ - {'venue': '网球场1号', 'timeRange': '18:00-19:00', 'rows': []}, - ], - }); - }); - final service = OaGymService( - fixture.auth, - fixture.storage, - fixture.tpAuth, - client: client, - ); - await expectLater( - service.searchCourts( - startDate: '2026-10-08', - endDate: '2026-10-08', - venueNames: {'网球场1号'}, - timeRanges: ['18:00-19:00', '19:00-20:00'], - ), - throwsA( - isA().having( - (error) => error.message, - 'message', - contains('结果不完整'), - ), - ), - ); + expect(result.first, hasLength(1)); + expect(result.last.single.date, '2026-10-09'); + expect(service.loading, false); }); - test('booking timeout warns to check records and never retries submission', + test('booking timeout tells the user to check records and never retries the POST', () async { final fixture = await _serviceFixture(); - var calls = 0; - final client = _FakeClient((request) async { - calls++; - throw TimeoutException('simulated transport timeout'); - }); - final service = OaGymService( - fixture.auth, - fixture.storage, - fixture.tpAuth, - client: client, - ); + var submits = 0; + final school = OaSchoolClient() + ..intercept = (request) async { + if (request.url.path.endsWith('/RequestOperation.jsp')) { + submits++; + throw TimeoutException('synthetic timeout'); + } + return null; + }; + final service = _service(fixture, school); await expectLater( service.bookCourt( sport: OaSport.tennis, @@ -643,110 +234,90 @@ void main() { ), throwsA( isA().having( - (error) => error.message, + (e) => e.message, 'message', contains('先查询预约记录确认结果'), ), ), ); - expect(calls, 1); + expect(submits, 1); }); group('OA personal information', () { - test('syncs immediately after binding against the legacy UUID response', - () async { - const userId = '11111111-2222-3333-4444-555555555555'; - final fixture = await _serviceFixture( - bindEgate: false, - authClient: _FakeClient((request) async { - expect(request.url.path, '/api/auth/third-party/egate'); - final body = - jsonDecode(await request.finalize().bytesToString()) as Map; - expect(body['account'], '20240001'); - return _jsonResponse({ - 'success': true, - 'data': { - 'sid': userId, - 'name': 'OA User', - 'token': 'session', - 'raw': {'tgc': 'tgc-value', 'sessionToken': 'session'}, - }, - }); - }), - ); - final paths = []; - final service = _profileService(fixture, (request) async { - paths.add(request.url.path); - final body = - jsonDecode(await request.finalize().bytesToString()) as Map; - expect(body['auth']['userId'], userId); - if (request.url.path.endsWith('/profile')) return _profileResult(); - expect(body['booking']['studentId'], '20240001'); - return _jsonResponse({ - 'success': true, - 'data': {'success': true}, - }); - }); + test('automatically syncs Passkey contacts after binding', () async { + final fixture = await _serviceFixture(bindIds: false); + final school = OaSchoolClient(); + final started = Completer(); + final release = Completer(); + school.intercept = (request) async { + if (request.url.path == '/hrm/resource/HrmResourceContactEdit.jsp') { + started.complete(); + await release.future; + } + return null; + }; + final service = _service(fixture, school); service.startProfileSync(); - await fixture.tpAuth.bind( - platform: ThirdPartyPlatform.cpdaily, + await fixture.tpAuth.bindIds( account: '20240001', password: 'fixture-password', + promptCaptcha: (_, __, {required refresh}) async => null, ); - await service.syncBookingProfile(); + await started.future; + final completed = service.syncBookingProfile(); + release.complete(); + await completed; + expect(service.profileSynced, true); expect(service.profileSyncError, isNull); - expect(service.bookingStudentId, '20240001'); - expect(service.profileOwner, 'user|20240001'); - expect(fixture.tpAuth.cpdailyNode.cookieProvider!.studentId, '20240001'); expect(service.bookingProfile().phone, '13900000000'); - await service.bookCourt( - sport: OaSport.badminton, - date: '2026-10-08', - timeSlot: 8, - courtNumber: 1, - playersCount: 2, + expect(service.bookingProfile().email, 'student@shanghaitech.edu.cn'); + expect( + school.requests.where((r) => r.url.path == '/hrm/resource/HrmResourceContactEdit.jsp'), + hasLength(1), + ); + expect( + school.requests.every((r) => r.method == 'GET' && r.url.host == 'oa.shanghaitech.edu.cn'), + true, ); - expect(paths, ['/api/oa/gym/profile', '/api/oa/gym/book']); }); - test('legacy SMS UUID bindings learn a school ID only from self OA data', + test('Passkey gym reads and submits directly to OA while keeping saved contacts', () async { - const userId = '11111111-2222-3333-4444-555555555555'; - final fixture = await _serviceFixture(bindEgate: false); - fixture.tpAuth.sessionTree.setAccount( - ThirdPartyPlatform.cpdaily, - ThirdPartyAccount( - platform: ThirdPartyPlatform.cpdaily, - account: '13800000000', - sid: userId, - token: 'session', - raw: const {'tgc': 'tgc-value'}, - boundAt: DateTime.utc(2026), - ), + final fixture = await _serviceFixture(bindIds: false); + final school = OaSchoolClient(); + final service = _service(fixture, school); + await fixture.tpAuth.bindIds( + account: '20240001', + password: 'fixture-password', + promptCaptcha: (_, __, {required refresh}) async => null, + ); + await service.saveBookingProfile( + const OaBookingProfile(name: 'OA User', phone: '13900000000', email: ''), ); - final service = _profileService(fixture, (request) async { - if (request.url.path.endsWith('/profile')) return _profileResult(); - final body = - jsonDecode(await request.finalize().bytesToString()) as Map; - expect(body['booking']['studentId'], '20240001'); - expect(body['auth']['userId'], userId); - return _jsonResponse({ - 'success': true, - 'data': {'success': true}, - }); - }); - expect(fixture.tpAuth.cpdailyStudentId, isEmpty); - expect(service.bookingStudentId, isEmpty); - expect(service.profileOwner, 'user|$userId'); await service.syncBookingProfile(); expect(service.profileSyncError, isNull); + expect(service.profileSynced, true); + expect(service.bookingProfile().email, 'student@shanghaitech.edu.cn'); expect(service.bookingStudentId, '20240001'); - // The school ID is not editable and survives manual saves and restart. - await service.saveBookingProfile( - const OaBookingProfile(name: 'Manual', phone: '13700000000', email: ''), + expect(service.profileOwner, 'user|20240001'); + expect(fixture.tpAuth.idsNode.cookieProvider!.studentId, '20240001'); + expect(service.bookingProfile().phone, '13900000000'); + await service.ensureReady(); + expect(service.timeSlots, {'18:00-19:00': '8'}); + final available = await service.checkAvailability( + sports: {OaSport.pickleball}, + date: '2026-11-03', + startSlot: 8, + endSlot: 8, ); - final restarted = _profileService(fixture, (_) async => _profileResult()); - expect(restarted.bookingStudentId, '20240001'); + expect(available.single.availableCourts, [1, 2]); + final records = await service.searchCourts( + startDate: '2026-11-03', + endDate: '2026-11-03', + venueNames: {'室内羽毛球场'}, + timeRanges: ['18:00-19:00'], + ); + expect(records.single.rows.single.last, '已通过'); await service.bookCourt( sport: OaSport.badminton, date: '2026-10-08', @@ -754,180 +325,160 @@ void main() { courtNumber: 1, playersCount: 2, ); + expect( + school.requests.every((request) => request.url.host == 'oa.shanghaitech.edu.cn'), + true, + ); + final booking = Uri.splitQueryString(school.requests.last.body); + expect(booking['field34283'], '20240001'); + expect(booking['field31879'], '13900000000'); }); - test('keeps normalized school and internal CpDaily IDs distinct', () { - const userId = '11111111-2222-3333-4444-555555555555'; - for (final raw in [ - {'studentId': '20240001', 'userId': userId}, - {'openId': '20240001', 'userId': userId}, - ]) { - final account = ThirdPartyAccount.fromJson( - ThirdPartyAccount( - platform: ThirdPartyPlatform.cpdaily, - account: '13800000000', - sid: '20240001', - token: 'session', - raw: raw, - boundAt: DateTime.utc(2026), - ).toJson(), - ); - expect(account.cpdailyStudentId, '20240001'); - expect(account.cpdailyUserId, userId); - } - expect(ThirdPartyAccount.cpdailySchoolId(userId), isEmpty); - expect(ThirdPartyAccount.cpdailySchoolId('13800000000'), isEmpty); - expect(ThirdPartyAccount.cpdailySchoolId(' 20240001 '), '20240001'); + test('Passkey OA expiry remints locally and retries without contacting the backend', + () async { + final fixture = await _serviceFixture(bindIds: false); + await fixture.tpAuth.bindIds( + account: '20240001', + password: 'fixture-password', + promptCaptcha: (_, __, {required refresh}) async => null, + ); + var expired = false; + final school = OaSchoolClient() + ..intercept = (_) async { + if (expired) return null; + expired = true; + return OaSchoolClient.text('expired', status: 401); + }; + final service = _service(fixture, school); + final epoch = fixture.tpAuth.oaNode.epoch; + await service.ensureReady(); + expect(service.sessionReady, true); + expect(fixture.tpAuth.oaNode.epoch, epoch + 2); + expect(school.requests, hasLength(5)); + expect( + school.requests.every((request) => request.url.host == 'oa.shanghaitech.edu.cn'), + true, + ); }); - test('syncs current-user contacts and uses them for booking', () async { - final fixture = await _serviceFixture(withBookingProfile: false); - final paths = []; - final service = _profileService(fixture, (request) async { - paths.add(request.url.path); - final body = - jsonDecode(await request.finalize().bytesToString()) as Map; - expect(body['auth']['tgc'], 'tgc-value'); - expect(body.containsKey('resourceId'), isFalse); - if (request.url.path.endsWith('/profile')) return _profileResult(); - expect(body['booking']['userName'], 'OA User'); - expect(body['booking']['phone'], '13900000000'); - expect(body['booking']['email'], 'student@shanghaitech.edu.cn'); - return _jsonResponse({ - 'success': true, - 'data': {'success': true, 'message': '预约成功'}, - }); - }); - - await service.syncBookingProfile(); - expect(service.profileSynced, isTrue); - expect(service.profileSyncError, isNull); - expect(service.bookingProfile().phone, '13900000000'); - await service.bookCourt( - sport: OaSport.badminton, - date: '2026-10-08', - timeSlot: 8, - courtNumber: 1, - playersCount: 2, + test('Passkey repeated OA expiry stops after one retry', () async { + final fixture = await _serviceFixture(bindIds: false); + await fixture.tpAuth.bindIds( + account: '20240001', + password: 'fixture-password', + promptCaptcha: (_, __, {required refresh}) async => null, + ); + final school = OaSchoolClient() + ..intercept = (_) async => OaSchoolClient.text('expired', status: 401); + final service = _service(fixture, school); + await expectLater( + service.ensureReady(), + throwsA( + isA().having( + (e) => e.message, + 'message', + contains('OA 登录态已失效'), + ), + ), ); - expect(paths, ['/api/oa/gym/profile', '/api/oa/gym/book']); + expect(school.requests, hasLength(2)); }); - test('syncs on binding and rebinding without repeating on token updates', + test('syncs on binding and rebinding without repeating on a session refresh', () async { - final fixture = await _serviceFixture(bindEgate: false); - var calls = 0; - final service = _profileService(fixture, (_) async { - calls++; - return _profileResult(phone: '1390000000$calls'); - }); - service.startProfileSync(); - expect(calls, 0); - fixture.tpAuth.sessionTree.setAccount( - ThirdPartyPlatform.cpdaily, - _campusAccount('20240001', DateTime.utc(2026, 10, 8)), - ); + final fixture = await _serviceFixture(bindIds: false); + var contacts = 0; + final school = OaSchoolClient() + ..intercept = (request) async { + if (_isContact(request)) return OaSchoolClient.contacts(phone: '1390000000${++contacts}'); + return null; + }; + final service = _service(fixture, school)..startProfileSync(); + expect(contacts, 0); + await _setAccount(fixture, '20240001', DateTime.utc(2026, 10, 8)); await service.syncBookingProfile(); - expect(calls, 1); - expect(service.bookingProfile().phone, '13900000001'); - - fixture.tpAuth.sessionTree.setAccount( - ThirdPartyPlatform.cpdaily, - fixture.tpAuth.cpdailyBinding!.copyWith(token: 'renewed'), + expect(contacts, 1); + await fixture.tpAuth.updateRaw( + ThirdPartyPlatform.ids, + {...fixture.tpAuth.idsAccount!.raw, 'cookies': 'CASTGC=renewed'}, ); await Future.delayed(Duration.zero); - expect(calls, 1); - fixture.tpAuth.sessionTree.setAccount( - ThirdPartyPlatform.cpdaily, - _campusAccount('20240001', DateTime.utc(2026, 10, 9)), - ); + expect(contacts, 1); + await _setAccount(fixture, '20240001', DateTime.utc(2026, 10, 9)); await service.syncBookingProfile(); - expect(calls, 2); + expect(contacts, 2); expect(service.bookingProfile().phone, '13900000002'); }); - test('shares a profile request and does not mark court queries as loading', + test('shares a pending profile request without marking court queries as loading', () async { final fixture = await _serviceFixture(withBookingProfile: false); + final started = Completer(); final response = Completer(); - var calls = 0; - final service = _profileService(fixture, (_) { - calls++; - return response.future; - }); + final school = OaSchoolClient() + ..intercept = (request) async { + if (_isContact(request)) { + started.complete(); + return response.future; + } + return null; + }; + final service = _service(fixture, school); final first = service.syncBookingProfile(); final second = service.syncBookingProfile(); - expect(identical(first, second), isTrue); - await Future.delayed(Duration.zero); - expect(calls, 1); - expect(service.profileSyncing, isTrue); - expect(service.loading, isFalse); - response.complete(_profileResult()); + expect(identical(first, second), true); + await started.future; + expect(service.profileSyncing, true); + expect(service.loading, false); + response.complete(OaSchoolClient.contacts()); await first; - expect(service.profileSyncing, isFalse); + expect(service.profileSyncing, false); }); - test('keeps contacts account-scoped and preserves the legacy record', + test('contacts stay account-scoped and ignore the old unscoped record', () async { final fixture = await _serviceFixture(withBookingProfile: false); await fixture.storage.saveOaBookingProfile( - const OaBookingProfile(name: 'Legacy', phone: '13600000000', email: ''), - ); - final service = _profileService( - fixture, - (_) async => _profileResult( - studentId: fixture.tpAuth.cpdailyStudentId, - ), + const OaBookingProfile(name: 'Old contact', phone: '13600000000', email: ''), ); + final service = _service(fixture, OaSchoolClient()); expect(service.bookingProfile().phone, isEmpty); await service.syncBookingProfile(); await service.saveBookingProfile( service.bookingProfile().copyWith(phone: '13800000000'), ); - fixture.tpAuth.sessionTree.setAccount( - ThirdPartyPlatform.cpdaily, - _campusAccount('20240002', DateTime.utc(2026, 10, 8)), - ); + await _setAccount(fixture, '20240002', DateTime.utc(2026, 10, 8)); expect(service.bookingProfile().phone, isEmpty); await service.syncBookingProfile(); expect(service.bookingProfile().phone, '13900000000'); - fixture.tpAuth.sessionTree.setAccount( - ThirdPartyPlatform.cpdaily, - _campusAccount('20240001', DateTime.utc(2026, 10, 9)), - ); + await _setAccount(fixture, '20240001', DateTime.utc(2026, 10, 9)); expect(service.bookingProfile().phone, '13800000000'); expect(fixture.storage.loadOaBookingProfile().phone, '13600000000'); }); - test('discards late contacts and leaves the new account sync running', + test('late contacts cannot overwrite a replacement account or stop its sync', () async { final fixture = await _serviceFixture(withBookingProfile: false); final responses = >[]; - final service = _profileService(fixture, (_) { - final response = Completer(); - responses.add(response); - return response.future; - }); - service.startProfileSync(); + final school = OaSchoolClient() + ..intercept = (request) async { + if (!_isContact(request)) return null; + final response = Completer(); + responses.add(response); + return response.future; + }; + final service = _service(fixture, school)..startProfileSync(); final old = service.syncBookingProfile(); await Future.delayed(Duration.zero); - fixture.tpAuth.sessionTree.setAccount( - ThirdPartyPlatform.cpdaily, - _campusAccount('20240002', DateTime.utc(2026, 10, 8)), - ); + await _setAccount(fixture, '20240002', DateTime.utc(2026, 10, 8)); final current = service.syncBookingProfile(); await Future.delayed(Duration.zero); expect(responses, hasLength(2)); - responses.first.complete(_profileResult()); + responses.first.complete(OaSchoolClient.contacts()); await old; - expect(service.profileSyncing, isTrue); + expect(service.profileSyncing, true); expect(service.bookingProfile().phone, isEmpty); - responses.last.complete( - _profileResult( - studentId: '20240002', - phone: '13700000000', - ), - ); + responses.last.complete(OaSchoolClient.contacts(phone: '13700000000')); await current; expect(service.bookingProfile().phone, '13700000000'); expect(service.profileSyncError, isNull); @@ -937,49 +488,54 @@ void main() { ); }); - test('updates OA-owned fields while preserving manual contact overrides', + test('OA updates preserve manual overrides unless overwrite was requested', () async { final fixture = await _serviceFixture(withBookingProfile: false); - var response = _profileResult(); - final service = _profileService(fixture, (_) async => response); + var response = OaSchoolClient.contacts(); + final school = OaSchoolClient() + ..intercept = (request) async => _isContact(request) ? response : null; + final service = _service(fixture, school); await service.syncBookingProfile(); await service.saveBookingProfile( service.bookingProfile().copyWith(phone: '13800000000'), ); - response = _profileResult( - name: 'Updated OA Name', + response = OaSchoolClient.contacts( phone: '13700000000', email: 'updated@shanghaitech.edu.cn', ); await service.syncBookingProfile(); - expect(service.bookingProfile().name, 'Updated OA Name'); + expect(service.bookingProfile().name, 'User'); expect(service.bookingProfile().email, 'updated@shanghaitech.edu.cn'); expect(service.bookingProfile().phone, '13800000000'); await service.syncBookingProfile(overwrite: true); expect(service.bookingProfile().phone, '13700000000'); }); - test('does not overwrite a manual save made during synchronization', + test('a manual save made during a profile request wins over its late response', () async { final fixture = await _serviceFixture(withBookingProfile: false); final response = Completer(); - final service = _profileService(fixture, (_) => response.future); + final school = OaSchoolClient() + ..intercept = (request) async => _isContact(request) ? response.future : null; + final service = _service(fixture, school); final request = service.syncBookingProfile(overwrite: true); await service.saveBookingProfile( const OaBookingProfile(name: 'Manual', phone: '13800000000', email: ''), ); - response.complete(_profileResult()); + response.complete(OaSchoolClient.contacts()); await request; expect(service.bookingProfile().name, 'Manual'); expect(service.bookingProfile().phone, '13800000000'); expect(service.bookingProfile().email, isEmpty); }); - test('rejects masked phones and contacts belonging to another identity', + test('masked phone numbers and a different user contact form are rejected', () async { final fixture = await _serviceFixture(withBookingProfile: false); - var response = _profileResult(phone: '1390000****'); - final service = _profileService(fixture, (_) async => response); + var response = OaSchoolClient.contacts(phone: '1390000****'); + final school = OaSchoolClient() + ..intercept = (request) async => _isContact(request) ? response : null; + final service = _service(fixture, school); await service.syncBookingProfile(); expect(service.bookingProfile().phone, isEmpty); expect(service.bookingProfile().email, 'student@shanghaitech.edu.cn'); @@ -993,53 +549,34 @@ void main() { ), throwsA(isA()), ); - response = _profileResult(studentId: '20240002'); + response = OaSchoolClient.contacts(id: 'different-user'); await service.syncBookingProfile(overwrite: true); - expect(service.profileSyncError, contains('账号不匹配')); + expect(service.profileSyncError, contains('当前用户')); expect(service.bookingProfile().phone, isEmpty); }); - test('old backends keep manual contacts and court queries working', + test('unavailable OA contacts still allow manual details and court queries', () async { final fixture = await _serviceFixture(withBookingProfile: false); - final service = _profileService(fixture, (request) async { - if (request.url.path.endsWith('/profile')) { - return http.Response('Not found', 404); - } - return _jsonResponse({ - 'success': true, - 'data': { - 'venues': {'网球场1号': '25'}, - 'timeSlots': {'18:00-19:00': '8'}, - }, - }); - }); + final school = OaSchoolClient() + ..intercept = (request) async => + _isContact(request) ? OaSchoolClient.text('not found', status: 404) : null; + final service = _service(fixture, school); await service.syncBookingProfile(); - expect(service.profileSyncError, contains('暂不支持自动同步')); + expect(service.profileSyncError, isNotNull); await service.saveBookingProfile( const OaBookingProfile(name: 'Manual', phone: '13800000000', email: ''), ); await service.ensureReady(); - expect(service.sessionReady, isTrue); + expect(service.sessionReady, true); expect(service.bookingProfile().phone, '13800000000'); }); }); - test('throws when eGate binding is absent', () async { - final fixture = await _serviceFixture(bindEgate: false); - final client = _FakeClient( - (request) async => _jsonResponse({ - 'success': true, - 'data': const {}, - }), - ); - final service = OaGymService( - fixture.auth, - fixture.storage, - fixture.tpAuth, - client: client, - ); - + test('court queries require a local Passkey binding', () async { + final fixture = await _serviceFixture(bindIds: false); + final school = OaSchoolClient(); + final service = _service(fixture, school); expect( () => service.checkAvailability( sports: {OaSport.badminton}, @@ -1049,20 +586,17 @@ void main() { ), throwsA(isA()), ); + expect(school.requests, isEmpty); }); } Future<_Fixture> _serviceFixture({ - bool bindEgate = true, + bool bindIds = true, bool withBookingProfile = true, - http.Client? authClient, }) async { SharedPreferences.setMockInitialValues({}); FlutterSecureStorage.setMockInitialValues({}); - final prefs = await SharedPreferences.getInstance(); - final storage = StorageService(prefs); - // Primary account is the GeekPie SSO identity session — it carries no - // CASTGC / CpDaily session at all. + final storage = StorageService(await SharedPreferences.getInstance()); await storage.saveSession( UserSession( userId: 'user', @@ -1073,113 +607,46 @@ Future<_Fixture> _serviceFixture({ createdAt: DateTime.utc(2026), ), ); - if (bindEgate) { + if (bindIds) { + await storage.saveThirdPartyAccount(FakeIdsClient.account('20240001')); if (withBookingProfile) { await storage.saveOaBookingProfile( const OaBookingProfile(name: 'User', phone: '13800000000', email: ''), owner: 'user|20240001', ); } - await storage.saveThirdPartyAccount( - ThirdPartyAccount( - platform: ThirdPartyPlatform.cpdaily, - account: '20240001', - sid: '20240001', - token: 'session', - raw: const { - 'tgc': 'tgc-value', - 'cookies': 'happyVoyage=happy', - 'sessionToken': 'session', - 'userId': 'user', - 'tenantId': 'tenant', - }, - boundAt: DateTime.utc(2026), - ), - ); } - final logger = DebugLogger(); - final httpClient = LoggingHttpClient(logger, inner: authClient); - final uniAuth = UniAuthService(); - final auth = AuthService(storage, httpClient, uniAuth); - final tpAuth = ThirdPartyAuthService(storage, httpClient); + final api = LoggingHttpClient(DebugLogger()); + final auth = AuthService(storage, api, UniAuthService()); + final tpAuth = ThirdPartyAuthService(storage, api, idsClient: FakeIdsClient()); await auth.loadSession(); await tpAuth.initialize(); return _Fixture(storage, auth, tpAuth); } -OaGymService _profileService( - _Fixture fixture, - Future Function(http.BaseRequest) handler, -) { +OaGymService _service(_Fixture fixture, OaSchoolClient school) { final service = OaGymService( fixture.auth, fixture.storage, fixture.tpAuth, - client: _FakeClient(handler), + client: school, ); addTearDown(service.dispose); return service; } -ThirdPartyAccount _campusAccount(String sid, DateTime boundAt) => - ThirdPartyAccount( - platform: ThirdPartyPlatform.cpdaily, - account: sid, - sid: sid, - token: 'session', - raw: { - 'tgc': 'tgc-$sid', - 'cookies': 'happyVoyage=happy', - 'sessionToken': 'session', - 'userId': sid, - 'tenantId': 'tenant', - }, - boundAt: boundAt, - ); - -http.Response _profileResult({ - String studentId = '20240001', - String name = 'OA User', - String phone = '13900000000', - String email = 'student@shanghaitech.edu.cn', -}) => - _jsonResponse({ - 'success': true, - 'data': { - 'studentId': studentId, - 'name': name, - 'phone': phone, - 'email': email, - }, - }); - -http.Response _jsonResponse(Map body) => http.Response( - jsonEncode(body), - 200, - headers: {'content-type': 'application/json; charset=utf-8'}, +Future _setAccount(_Fixture fixture, String username, DateTime time) => + fixture.tpAuth.applyIdsSyncBinding( + IdsSyncBinding( + credential: FakeIdsClient.key(username), + updatedAt: time, + deviceId: 'fixture', + ), ); class _Fixture { + const _Fixture(this.storage, this.auth, this.tpAuth); final StorageService storage; final AuthService auth; final ThirdPartyAuthService tpAuth; - - const _Fixture(this.storage, this.auth, this.tpAuth); -} - -class _FakeClient extends http.BaseClient { - _FakeClient(this._handler); - - final Future Function(http.BaseRequest request) _handler; - - @override - Future send(http.BaseRequest request) async { - final response = await _handler(request); - return http.StreamedResponse( - Stream>.value(response.bodyBytes), - response.statusCode, - headers: response.headers, - request: request, - ); - } } diff --git a/test/schedule_empty_week_test.dart b/test/schedule_empty_week_test.dart index d342fbaa..52ce95b5 100644 --- a/test/schedule_empty_week_test.dart +++ b/test/schedule_empty_week_test.dart @@ -2,7 +2,7 @@ import 'package:flutter_test/flutter_test.dart'; import 'package:techpie/pages/schedule_page.dart'; void main() { - // The timetable is only fetched once an eGate binding exists, and that fetch can + // The timetable is only fetched once an IDS binding exists, and that fetch can // fail — so "this week is empty" is a claim the app can only make in one of the // three cases below. Getting it wrong is what a freshly bound account saw. test('an empty week says which of the three things it is', () { diff --git a/test/schedule_fetch_coalescing_test.dart b/test/schedule_fetch_coalescing_test.dart index 2456b5ca..bf97a11e 100644 --- a/test/schedule_fetch_coalescing_test.dart +++ b/test/schedule_fetch_coalescing_test.dart @@ -13,6 +13,8 @@ import 'package:techpie/services/storage_service.dart'; import 'package:techpie/services/third_party_auth_service.dart'; import 'package:techpie/services/uni_auth_service.dart'; +import 'support/fake_ids_client.dart'; + void main() { TestWidgetsFlutterBinding.ensureInitialized(); @@ -26,14 +28,7 @@ void main() { final prefs = await SharedPreferences.getInstance(); final storage = StorageService(prefs); await storage.saveThirdPartyAccount( - ThirdPartyAccount( - platform: ThirdPartyPlatform.cpdaily, - account: '20240001', - sid: '20240001', - token: 'session', - raw: const {'tgc': 'tgc-value'}, - boundAt: DateTime.utc(2026), - ), + FakeIdsClient.account('20240001'), ); final logger = DebugLogger(); @@ -42,7 +37,7 @@ void main() { final uniAuth = UniAuthService(); final auth = AuthService(storage, http, uniAuth); await auth.loadSession(); - final tpAuth = ThirdPartyAuthService(storage, http); + final tpAuth = ThirdPartyAuthService(storage, http, idsClient: FakeIdsClient()); await tpAuth.initialize(); final schedule = ScheduleService(storage, http, auth, tpAuth); @@ -52,7 +47,7 @@ void main() { // listener, milliseconds apart. for (final marker in ['a', 'b', 'c']) { await tpAuth.updateRaw( - ThirdPartyPlatform.cpdaily, + ThirdPartyPlatform.ids, {'tgc': 'tgc-value', 'cookies': 'CASTGC=$marker'}, ); } @@ -61,9 +56,9 @@ void main() { await Future.delayed(const Duration(milliseconds: 900)); expect( - requests.length, + _pathsOf(requests).where((path) => path.startsWith('/api/schedule/')).length, 1, - reason: 'the burst is one round; the client fails on the first request, ' + reason: 'the burst is one round; the client fails on the first business request, ' 'so a second round would show up as a second request', ); }); @@ -78,14 +73,7 @@ void main() { final prefs = await SharedPreferences.getInstance(); final storage = StorageService(prefs); await storage.saveThirdPartyAccount( - ThirdPartyAccount( - platform: ThirdPartyPlatform.cpdaily, - account: '20240001', - sid: '20240001', - token: 'session', - raw: const {'tgc': 'tgc-value'}, - boundAt: DateTime.utc(2026), - ), + FakeIdsClient.account('20240001'), ); final logger = DebugLogger(); @@ -94,7 +82,7 @@ void main() { final uniAuth = UniAuthService(); final auth = AuthService(storage, http, uniAuth); await auth.loadSession(); - final tpAuth = ThirdPartyAuthService(storage, http); + final tpAuth = ThirdPartyAuthService(storage, http, idsClient: FakeIdsClient()); await tpAuth.initialize(); final schedule = ScheduleService(storage, http, auth, tpAuth); @@ -133,12 +121,6 @@ class _AnsweringClient extends http.BaseClient { Future send(http.BaseRequest request) async { requests.add(request.url); final body = switch (request.url.path) { - // The eams cookie is minted from the parent tgc before a timetable fetch - // can carry one. - '/api/auth/third-party/eams' => jsonEncode({ - 'success': true, - 'data': {'token': 'CASTGC=eams-cookie'}, - }), '/api/schedule/semesters' => jsonEncode({ 'success': true, 'data': { diff --git a/test/schedule_first_week_test.dart b/test/schedule_first_week_test.dart index cd485aeb..9ca0b814 100644 --- a/test/schedule_first_week_test.dart +++ b/test/schedule_first_week_test.dart @@ -39,7 +39,7 @@ class _Bound extends ThirdPartyAuthService { _Bound(super.storage, super.http); @override - bool get hasCpdailyBinding => true; + bool get hasIdsBinding => true; } void main() { diff --git a/test/schedule_session_refresh_test.dart b/test/schedule_session_refresh_test.dart index 5a3224db..9c7334bd 100644 --- a/test/schedule_session_refresh_test.dart +++ b/test/schedule_session_refresh_test.dart @@ -11,6 +11,8 @@ import 'package:techpie/services/storage_service.dart'; import 'package:techpie/services/third_party_auth_service.dart'; import 'package:techpie/services/uni_auth_service.dart'; +import 'support/fake_ids_client.dart'; + void main() { TestWidgetsFlutterBinding.ensureInitialized(); @@ -24,14 +26,7 @@ void main() { final prefs = await SharedPreferences.getInstance(); final storage = StorageService(prefs); await storage.saveThirdPartyAccount( - ThirdPartyAccount( - platform: ThirdPartyPlatform.cpdaily, - account: '20240001', - sid: '20240001', - token: 'session', - raw: const {'tgc': 'tgc-value'}, - boundAt: DateTime.utc(2026), - ), + FakeIdsClient.account('20240001'), ); final logger = DebugLogger(); @@ -40,7 +35,7 @@ void main() { final uniAuth = UniAuthService(); final auth = AuthService(storage, http, uniAuth); await auth.loadSession(); - final tpAuth = ThirdPartyAuthService(storage, http); + final tpAuth = ThirdPartyAuthService(storage, http, idsClient: FakeIdsClient()); await tpAuth.initialize(); final schedule = ScheduleService(storage, http, auth, tpAuth); @@ -49,14 +44,14 @@ void main() { // What a renewal or a sync merge amounts to, from a listener's point of view. await tpAuth.updateRaw( - ThirdPartyPlatform.cpdaily, + ThirdPartyPlatform.ids, const {'tgc': 'tgc-value', 'cookies': 'CASTGC=renewed'}, ); // Past the window requestFetch coalesces over. await Future.delayed(const Duration(milliseconds: 900)); expect( - requests, + requests.where((url) => url.path.startsWith('/api/schedule/')), isNotEmpty, reason: 'the table was empty, so a renew has to lead to a fetch', ); diff --git a/test/session_storm_test.dart b/test/session_storm_test.dart index a84675f9..e7cdf093 100644 --- a/test/session_storm_test.dart +++ b/test/session_storm_test.dart @@ -5,6 +5,7 @@ import 'package:http/http.dart' as http; import 'package:techpie/models/third_party_account.dart'; import 'package:techpie/services/debug_logger.dart'; import 'package:techpie/services/http_client.dart'; +import 'package:techpie/services/ids/campus_http.dart'; import 'package:techpie/services/session/session_tree.dart'; /// Verifies the anti-renew-storm guarantees of the unified SessionNode tree: @@ -14,7 +15,7 @@ import 'package:techpie/services/session/session_tree.dart'; /// 3. withCookie retries a 401 exactly once with the fresh cookie, and two /// concurrent withCookie callers share a single renew. /// 4. Child nodes (eams/elearning) mint downstream cookies from the parent -/// cpdaily tgc; parent renew cascades to clear child derived cookies. +/// ids tgc; parent renew cascades to clear child derived cookies. /// 5. Two-level retry: a child 401 caused by a stale parent tgc triggers /// parent renew → child re-mint → retry. /// 6. freshCookie — the webview pre-flight — renews a due node (parent first, @@ -28,10 +29,9 @@ void main() { late List probeDisplays; late SessionTree tree; - /// Seed a cpdaily account so the cpdaily node is available. The renew - /// endpoint (/auth/renew) is mocked to rotate tgc + cookies each call. + /// Seed a software-Passkey session. Local renewals rotate tgc and cookies. ThirdPartyAccount seedAccount({String tgc = 'tgc-v0'}) => ThirdPartyAccount( - platform: ThirdPartyPlatform.cpdaily, + platform: ThirdPartyPlatform.ids, account: 'student', sid: '2024xxxx', name: 'Test', @@ -41,10 +41,8 @@ void main() { .millisecondsSinceEpoch ~/ 1000, raw: { - 'sessionToken': 'st-v0', + 'authMethod': 'passkey', 'tgc': tgc, - 'userId': 'u1', - 'tenantId': 't1', 'cookies': 'JSESSIONID=js-v0', }, boundAt: DateTime.now(), @@ -56,61 +54,39 @@ void main() { httpClient = LoggingHttpClient(logger, inner: client); tree = SessionTree( persist: (_, {force = false}) async {}, + localAccountRenew: client.renewAccount, + localCookieMint: client.mintCookie, http: httpClient, baseUrl: () => 'https://backend.test', persistProbe: (_, result) async => probeDisplays.add(result.display), ); - tree.cpdaily.setAccount(seedAccount()); + tree.ids.setAccount(seedAccount()); }); - test('concurrent renew() calls share one in-flight POST (single-flight)', + test('concurrent renew() calls share one local renewal (single-flight)', () async { final results = await Future.wait([ - tree.cpdaily.renew(), - tree.cpdaily.renew(), - tree.cpdaily.renew(), + tree.ids.renew(), + tree.ids.renew(), + tree.ids.renew(), ]); expect(results, [true, true, true]); expect(client.renewCalls, 1); // Cookie advanced to v1. expect( - tree.cpdaily.cookieProvider!.cookies, + tree.ids.cookieProvider!.cookies, contains('CASTGC=tgc-v1'), ); }); - test('legacy CpDaily UUID remains the protocol userId during renewal', - () async { - const userId = '11111111-2222-3333-4444-555555555555'; - final legacy = ThirdPartyAccount( - platform: ThirdPartyPlatform.cpdaily, - account: '20240001', - sid: userId, - token: 'session', - raw: const { - 'sessionToken': 'session', - 'tgc': 'tgc-v0', - 'tenantId': 'tenant', - }, - boundAt: DateTime.now(), - ); - tree.cpdaily.setAccount(legacy); - expect(tree.cpdaily.rawFields['userId'], userId); - expect(tree.cpdaily.cookieProvider!.studentId, '20240001'); - expect(await tree.cpdaily.renew(), isTrue); - expect(client.lastRenewBody!['userId'], userId); - expect(tree.cpdaily.rawFields['userId'], userId); - expect(tree.cpdaily.account!.cpdailyStudentId, '20240001'); - }); - - test('cpdaily schedules renewal three days before account expiry', () async { + test('Passkey renewal schedules the next refresh ten minutes after success', () async { final before = DateTime.now(); - await tree.cpdaily.renew(); + await tree.ids.renew(); - final next = tree.cpdaily.nextRenewTimestamp; + final next = tree.ids.nextRenewTimestamp; expect(next, isNotNull); - expect(next!.isAfter(before.add(const Duration(days: 26))), true); - expect(next.isBefore(before.add(const Duration(days: 28))), true); + expect(next!.isAfter(before.add(const Duration(minutes: 9))), true); + expect(next.isBefore(before.add(const Duration(minutes: 11))), true); }); test('derived cookie schedules the next renewal ten minutes after success', @@ -126,23 +102,23 @@ void main() { test('renewIfNeeded skips when epoch already advanced by a concurrent renew', () async { - final epochBefore = tree.cpdaily.epoch; + final epochBefore = tree.ids.epoch; // Fire a renew in the background (don't await yet). - final pending = tree.cpdaily.renew(); + final pending = tree.ids.renew(); // While it's in-flight, renewIfNeeded(epochBefore) should join the same // in-flight renew rather than starting a second one. - final second = tree.cpdaily.renewIfNeeded(epochBefore); + final second = tree.ids.renewIfNeeded(epochBefore); await Future.wait([pending, second]); expect(client.renewCalls, 1); }); test('renewIfNeeded does NOT skip when epoch is still current', () async { - final epochBefore = tree.cpdaily.epoch; + final epochBefore = tree.ids.epoch; // No concurrent renew — renewIfNeeded must actually run. - final ok = await tree.cpdaily.renewIfNeeded(epochBefore); + final ok = await tree.ids.renewIfNeeded(epochBefore); expect(ok, true); expect(client.renewCalls, 1); - expect(tree.cpdaily.epoch, greaterThan(epochBefore)); + expect(tree.ids.epoch, greaterThan(epochBefore)); }); test('withCookie retries 401 once with refreshed cookie', () async { @@ -154,7 +130,7 @@ void main() { ]; final resp = await tree.withCookie( - tree.cpdaily, + tree.ids, (cp) async { final r = await httpClient.post( Uri.parse('https://backend.test/fetch'), @@ -177,7 +153,7 @@ void main() { final results = await Future.wait([ tree.withCookie( - tree.cpdaily, + tree.ids, (cp) async { final r = await httpClient.post( Uri.parse('https://backend.test/fetch'), @@ -187,7 +163,7 @@ void main() { }, ), tree.withCookie( - tree.cpdaily, + tree.ids, (cp) async { final r = await httpClient.post( Uri.parse('https://backend.test/fetch'), @@ -208,15 +184,15 @@ void main() { }); test('withCookie proactively renews when the schedule is due', () async { - await tree.cpdaily.renew(); - tree.cpdaily.seedNextRenewTimestamp( + await tree.ids.renew(); + tree.ids.seedNextRenewTimestamp( DateTime.now().subtract(const Duration(seconds: 1)), ); client.fetchStatuses = [200]; client.fetchBodies = ['{}']; final response = await tree.withCookie( - tree.cpdaily, + tree.ids, (cp) async { final r = await httpClient.post( Uri.parse('https://backend.test/fetch'), @@ -233,24 +209,24 @@ void main() { // -- Webview pre-flight (freshCookie) tests -- test('freshCookie renews a due node and hands over the new cookie', () async { - await tree.cpdaily.renew(); - tree.cpdaily.seedNextRenewTimestamp( + await tree.ids.renew(); + tree.ids.seedNextRenewTimestamp( DateTime.now().subtract(const Duration(seconds: 1)), ); - final beforeEpoch = tree.cpdaily.epoch; + final beforeEpoch = tree.ids.epoch; - final cp = await tree.freshCookie(tree.cpdaily); + final cp = await tree.freshCookie(tree.ids); expect(client.renewCalls, 2); - expect(tree.cpdaily.epoch, greaterThan(beforeEpoch)); + expect(tree.ids.epoch, greaterThan(beforeEpoch)); expect(cp?.cookies, 'JSESSIONID=js-v2; CASTGC=tgc-v2'); }); test('freshCookie leaves a node alone while its schedule is not due', () async { - await tree.cpdaily.renew(); + await tree.ids.renew(); - final cp = await tree.freshCookie(tree.cpdaily); + final cp = await tree.freshCookie(tree.ids); expect(client.renewCalls, 1); expect(cp?.cookies, 'JSESSIONID=js-v1; CASTGC=tgc-v1'); @@ -259,7 +235,7 @@ void main() { test('freshCookie renews a stale parent before re-minting the child', () async { await tree.eams.renew(); - tree.cpdaily.seedNextRenewTimestamp( + tree.ids.seedNextRenewTimestamp( DateTime.now().subtract(const Duration(seconds: 1)), ); @@ -269,7 +245,7 @@ void main() { // which is then minted again against the new tgc. expect(client.renewCalls, 1); expect(client.eamsCalls, 2); - expect(client.lastEamsBody?['tgc'], 'tgc-v1'); + expect(client.lastParentTgc, 'tgc-v1'); expect(cp?.cookies, 'JSESSIONID=eams-v2'); }); @@ -283,7 +259,7 @@ void main() { expect(tree.eams.cookieProvider, isNotNull); expect(tree.eams.cookieProvider!.cookies, 'JSESSIONID=eams-v1'); // The renew POST body used the parent's current tgc. - expect(client.lastEamsBody?['tgc'], 'tgc-v0'); + expect(client.lastParentTgc, 'tgc-v0'); }); test('eams isAvailable is false until doRenew succeeds', () { @@ -294,12 +270,12 @@ void main() { expect(tree.eams.cookieProvider, isNull); }); - test('parent cpdaily renew clears eams derived cookie (cascade)', () async { + test('parent ids renew clears eams derived cookie (cascade)', () async { // First mint the eams cookie. await tree.eams.renew(); expect(tree.eams.isAvailable, true); // Now renew the parent — the child's derived cookie must be cleared. - final ok = await tree.cpdaily.renew(); + final ok = await tree.ids.renew(); expect(ok, true); expect(tree.eams.isAvailable, false); expect(tree.eams.cookieProvider, isNull); @@ -348,7 +324,7 @@ void main() { 'two-level retry: eams renew 401 (stale parent tgc) triggers parent renew', () async { // Reset parent to a stale tgc that the eams endpoint rejects. - tree.cpdaily.setAccount(seedAccount(tgc: 'tgc-stale')); + tree.ids.setAccount(seedAccount(tgc: 'tgc-stale')); // Configure eams renew to fail on the stale tgc, then succeed after the // parent renews (rotating tgc to v1). client.eamsStatuses = [401, 200]; @@ -409,10 +385,8 @@ void main() { }); } -/// Mock HTTP client that counts /auth/renew and /auth/third-party/eams calls -/// and serves a configurable sequence of statuses/bodies for other paths. -/// The renew response rotates tgc + cookies by appending a version suffix so -/// each renew is observable. +/// Controlled local session renewals plus HTTP responses for business requests +/// and probes. Cookie suffixes make each successful renewal observable. class _CountingClient extends http.BaseClient { int renewCalls = 0; int eamsCalls = 0; @@ -421,50 +395,39 @@ class _CountingClient extends http.BaseClient { List fetchBodies = const []; List eamsStatuses = const []; List eamsTokens = const []; - Map? lastEamsBody; - Map? lastRenewBody; + String? lastParentTgc; int _renewVersion = 0; int _eamsVersion = 0; + Future renewAccount(ThirdPartyAccount current) async { + renewCalls++; + _renewVersion++; + return current.copyWith(raw: { + ...current.raw, + 'tgc': 'tgc-v$_renewVersion', + 'cookies': 'JSESSIONID=js-v$_renewVersion', + },); + } + + Future mintCookie(String nodeId, Map raw) async { + expect(nodeId, 'eams'); + eamsCalls++; + lastParentTgc = raw['tgc'] as String; + _eamsVersion++; + final index = eamsCalls - 1; + final status = index < eamsStatuses.length ? eamsStatuses[index] : 200; + if (status != 200) { + throw IdsException('synthetic mint failure', credentialRejected: status == 401); + } + final token = index < eamsTokens.length ? eamsTokens[index] : 'JSESSIONID=eams-v$_eamsVersion'; + if (token == null || token.isEmpty) throw const IdsException('synthetic missing cookie'); + return token; + } + @override Future send(http.BaseRequest request) async { final url = request.url.toString(); - if (url.endsWith('/auth/renew')) { - renewCalls++; - lastRenewBody = request is http.Request - ? jsonDecode(request.body) as Map - : {}; - _renewVersion++; - final resp = jsonEncode({ - 'success': true, - 'sessionToken': 'st-v$_renewVersion', - 'tgc': 'tgc-v$_renewVersion', - 'userId': lastRenewBody?['userId'] ?? 'u1', - 'tenantId': 't1', - 'cookies': 'JSESSIONID=js-v$_renewVersion', - }); - return _resp(resp, 200); - } - - if (url.endsWith('/auth/third-party/eams')) { - eamsCalls++; - final body = request is http.Request - ? jsonDecode(request.body) as Map - : {}; - lastEamsBody = body; - _eamsVersion++; - final idx = eamsCalls - 1; - final status = idx < eamsStatuses.length ? eamsStatuses[idx] : 200; - final token = idx < eamsTokens.length - ? eamsTokens[idx] - : 'JSESSIONID=eams-v$_eamsVersion'; - final resp = jsonEncode({ - 'success': true, - 'data': {'token': token}, - }); - return _resp(resp, status); - } if (url.contains('eams.shanghaitech.edu.cn/eams/stdDetail.action')) { return _resp('姓名:Probe User', 200); } diff --git a/test/software_passkey_test.dart b/test/software_passkey_test.dart new file mode 100644 index 00000000..67b43798 --- /dev/null +++ b/test/software_passkey_test.dart @@ -0,0 +1,74 @@ +import 'dart:convert'; +import 'dart:typed_data'; + +import 'package:cbor/cbor.dart'; +import 'package:crypto/crypto.dart'; +import 'package:flutter_test/flutter_test.dart'; +import 'package:pointycastle/asn1.dart'; +import 'package:pointycastle/export.dart'; +import 'package:techpie/models/ids_passkey.dart'; +import 'package:techpie/services/ids/software_passkey.dart'; + +void main() { + test('registration COSE key verifies DER assertions, with zero counter on every use', () { + final challenge = SoftwarePasskey.encode(List.generate(32, (i) => i)); + final registered = SoftwarePasskey.registration( + { + 'challenge': challenge, + 'rp': {'id': IdsPasskey.rpId}, + 'user': {'id': 'dXNlcg', 'name': 'student'}, + 'pubKeyCredParams': [ + {'alg': -7}, + ], + }, + 'student', + ); + final response = registered.credential['response'] as Map; + final attestation = cbor + .decode(SoftwarePasskey.decode(response['attestationObject'] as String)) + .toObject() as Map; + final auth = attestation['authData'] as List; + expect(attestation['fmt'], 'none'); + expect(auth.take(32), sha256.convert(utf8.encode(IdsPasskey.rpId)).bytes); + expect(auth[32], 0x49); + expect(auth.sublist(33, 37), [0, 0, 0, 0]); + final length = auth[53] * 256 + auth[54]; + expect(SoftwarePasskey.encode(auth.sublist(55, 55 + length)), registered.secret.credentialId); + final public = cbor.decode(auth.sublist(55 + length)).toObject() as Map; + final curve = ECDomainParameters('prime256v1'); + final point = curve.curve.decodePoint( + Uint8List.fromList([4, ...(public[-2] as List), ...(public[-3] as List)]), + ); + final key = ECPublicKey(point, curve); + final restored = IdsPasskey.fromJson( + jsonDecode(jsonEncode(registered.secret.toJson())) as Map, + ); + for (var i = 0; i < 2; i++) { + final assertion = SoftwarePasskey.authentication( + {'challenge': '$challenge$i', 'rpId': IdsPasskey.rpId}, + restored, + backedUp: i == 1, + ); + final data = assertion['response'] as Map; + final authenticator = SoftwarePasskey.decode(data['authenticatorData'] as String); + final client = SoftwarePasskey.decode(data['clientDataJSON'] as String); + expect(authenticator[32], i == 1 ? 0x19 : 0x09); + expect(authenticator.sublist(33), [0, 0, 0, 0]); + expect((jsonDecode(utf8.decode(client)) as Map)['challenge'], '$challenge$i'); + final der = ASN1Parser(SoftwarePasskey.decode(data['signature'] as String)).nextObject() + as ASN1Sequence; + final signature = ECSignature( + (der.elements![0] as ASN1Integer).integer!, + (der.elements![1] as ASN1Integer).integer!, + ); + final verifier = Signer('SHA-256/ECDSA')..init(false, PublicKeyParameter(key)); + expect( + verifier.verifySignature( + Uint8List.fromList([...authenticator, ...sha256.convert(client).bytes]), + signature, + ), + isTrue, + ); + } + }); +} diff --git a/test/support/fake_ids_client.dart b/test/support/fake_ids_client.dart new file mode 100644 index 00000000..b94a537b --- /dev/null +++ b/test/support/fake_ids_client.dart @@ -0,0 +1,51 @@ +import 'package:techpie/models/ids_passkey.dart'; +import 'package:techpie/models/third_party_account.dart'; +import 'package:techpie/services/ids/ids_client.dart'; + +/// Supplies software credentials and local OA cookies to business-service tests. +/// The real IDS wire protocol is exercised separately in ids_client_test.dart. +class FakeIdsClient extends IdsClient { + static ThirdPartyAccount account(String username, {DateTime? boundAt, String name = 'User'}) { + final account = IdsSyncBinding( + credential: key(username), + updatedAt: boundAt ?? DateTime.utc(2026), + deviceId: 'fixture', + ).toAccount(); + return account.copyWith(name: name, raw: {...account.raw, 'tgc': 'tgc-value', 'cookies': ''}); + } + + static IdsPasskey key(String username) => IdsPasskey( + credentialId: 'synthetic-$username', + privateKey: 'synthetic-private-key', + userHandle: 'synthetic-user-handle', + anonBiometricsId: 'synthetic-biometric-id', + username: username, + ); + + @override + Future login(IdsPasskey secret, {bool backedUp = false}) async => + IdsSession(secret.username, {'tgc': 'tgc-value', 'cookies': ''}, name: 'User'); + + @override + Future<({IdsPasskey credential, IdsSession session})> register( + String username, + String password, { + required IdsCaptchaPrompt promptCaptcha, + required Future Function(IdsPasskey) saveCandidate, + }) async { + final credential = key(username); + await saveCandidate(credential); + return (credential: credential, session: await login(credential)); + } + + @override + Future mintCookie(String nodeId, Map root) async { + return switch (nodeId) { + 'eams' => 'JSESSIONID=eams-mock', + 'elearning' => 'session_id=elearning-mock', + 'egateApp' => 'MOD_AUTH_CAS=egate-mock', + 'oa' => 'shkjdx_session=oa-session', + _ => throw StateError('Unexpected local cookie request: $nodeId'), + }; + } +} diff --git a/test/support/oa_school_client.dart b/test/support/oa_school_client.dart new file mode 100644 index 00000000..8759ceca --- /dev/null +++ b/test/support/oa_school_client.dart @@ -0,0 +1,112 @@ +import 'dart:convert'; + +import 'package:http/http.dart' as http; + +/// Sanitized OA protocol fixture: never connects to a school or API server. +class OaSchoolClient extends http.BaseClient { + final requests = []; + Future Function(http.Request)? intercept; + + Future respond(http.BaseRequest base) async { + final request = base as http.Request; + requests.add(request); + final overridden = await intercept?.call(request); + if (overridden != null) return overridden; + final uri = request.url; + switch (uri.path) { + case '/formmode/browser/CommonSingleBrowser.jsp': + return text( + 'var __tableStringKey__ = "${uri.queryParameters['customid'] == '7102' ? 'AA' : 'BB'}";', + ); + case '/weaver/weaver.common.util.taglib.SplitPageXmlServlet': + final fields = {...uri.queryParameters, ...Uri.splitQueryString(request.body)}; + final table = fields['tableString']; + return text( + switch (table) { + 'AA' => '8', + 'BB' => '' + '13' + '25' + '43' + '44' + '', + 'CC' => '' + '', + _ => throw StateError('Unexpected OA table'), + }, + ); + case '/formmode/tree/treebrowser/CustomTreeBrowserAjax.jsp': + final form = Uri.splitQueryString(request.body); + if (form['pid'] == '63_1') { + return text( + jsonEncode( + [ + {'id': '63_bad', 'name': '室内羽毛球场', 'isParent': 'true'}, + {'id': '63_ten', 'name': '网球场', 'isParent': 'true'}, + {'id': '63_pic', 'name': '匹克球场', 'isParent': 'true'}, + ], + ), + ); + } + final prefix = switch (form['pid']) { + '63_bad' => '羽毛球场地', + '63_ten' => '网球场', + _ => '匹克球', + }; + return text( + jsonEncode( + [ + {'name': '${prefix}1号场地'}, + {'name': '${prefix}2号场地'}, + ], + ), + ); + case '/formmode/search/CustomSearchBySimpleIframe.jsp': + return text('var __tableStringKey__ = "CC";'); + case '/workflow/request/AddRequest.jsp': + return text( + 'current user workflow form', + headers: { + 'set-cookie': 'loginidweaver=fixture-current-user; Path=/; Secure', + }, + ); + case '/workflow/request/RequestOperation.jsp': + return text( + "", + ); + case '/hrm/resource/HrmResourceContactEdit.jsp': + return contacts(); + default: + throw StateError('Unexpected request: ${uri.path}'); + } + } + + @override + Future send(http.BaseRequest request) async { + final response = await respond(request); + return http.StreamedResponse( + Stream.value(response.bodyBytes), + response.statusCode, + headers: response.headers, + request: request, + ); + } + + static http.Response text(String body, {int status = 200, Map? headers}) => + http.Response.bytes( + utf8.encode(body), + status, + headers: {'content-type': 'text/plain; charset=utf-8', ...?headers}, + ); + + static http.Response contacts({ + String id = 'fixture-current-user', + String phone = '13900000000', + String email = 'student@shanghaitech.edu.cn', + }) => + text( + '
' + '' + '
', + ); +} diff --git a/test/sync_crypto_test.dart b/test/sync_crypto_test.dart index 5979f517..9b2e7b1d 100644 --- a/test/sync_crypto_test.dart +++ b/test/sync_crypto_test.dart @@ -1,5 +1,4 @@ import 'package:flutter_test/flutter_test.dart'; -import 'package:techpie/models/third_party_account.dart'; import 'package:techpie/services/sync_crypto.dart'; void main() { @@ -9,7 +8,7 @@ void main() { test('encryptWithSalt -> decryptWithSalt recovers plaintext', () async { const password = 'correct horse battery staple'; const payload = - '[{"platform":"cpdaily","account":"13800000000","token":"tgc-secret"}]'; + '[{"platform":"ids","account":"13800000000","token":"tgc-secret"}]'; final blob = await SyncCrypto.encryptWithSalt(payload, password); expect(blob.contains('.'), isTrue); @@ -17,11 +16,6 @@ void main() { final recovered = await SyncCrypto.decryptWithSalt(blob, password); expect(recovered, payload); }); - test('ThirdPartyPlatform.fromId resolves legacy egate alias to cpdaily', - () { - expect(ThirdPartyPlatform.fromId('egate'), ThirdPartyPlatform.cpdaily); - expect(ThirdPartyPlatform.fromId('cpdaily'), ThirdPartyPlatform.cpdaily); - }); test('wrong master password fails authentication (returns null)', () async { diff --git a/test/sync_envelope_test.dart b/test/sync_envelope_test.dart index 53002e06..380814d7 100644 --- a/test/sync_envelope_test.dart +++ b/test/sync_envelope_test.dart @@ -24,7 +24,7 @@ ThirdPartyAccount _acc({ void main() { group('SyncSchema.migrate', () { - test('v0 bare array is wrapped into a v2 envelope', () { + test('v0 bare array is wrapped into the current envelope', () { final v0 = jsonEncode([ {'platform': 'gradescope', 'account': 'a', 'token': 't1'}, ]); @@ -39,7 +39,7 @@ void main() { expect(env.accounts.first.deviceId, ''); }); - test('v1 envelope (no tombstones) migrates to v2 with empty tombstones', () { + test('v1 envelope migrates to the current schema with empty tombstones', () { final v1 = jsonEncode({ 'v': 1, 'accounts': [ @@ -52,12 +52,12 @@ void main() { expect(env.tombstones, isEmpty); }); - test('v2 envelope round-trips accounts + tombstones', () { + test('current envelope round-trips accounts + tombstones', () { final original = SyncEnvelope( v: SyncSchema.current, accounts: [ _acc( - platform: ThirdPartyPlatform.cpdaily, + platform: ThirdPartyPlatform.ids, token: 'tgc', updatedAt: DateTime.utc(2026, 1, 2), deviceId: 'devA', @@ -82,10 +82,15 @@ void main() { }); test('a newer build\'s fields survive decode, merge and encode', () { - // v4 is not a version this build knows: it is read as far as it can be + // A future version is read as far as it can be // understood, and the part it cannot read is carried, not dropped. final decoded = SyncSchema.migrate( - jsonDecode('{"v":4,"futureField":{"a":1},"accounts":[],"tombstones":[]}'), + { + 'v': SyncSchema.current + 1, + 'futureField': {'a': 1}, + 'accounts': [], + 'tombstones': [], + }, )!; expect(decoded.v, SyncSchema.current); expect(decoded.unknown, { @@ -247,7 +252,7 @@ void main() { v: SyncSchema.current, accounts: [ _acc( - platform: ThirdPartyPlatform.cpdaily, + platform: ThirdPartyPlatform.ids, token: 'A', updatedAt: ts, deviceId: 'aaa', @@ -259,7 +264,7 @@ void main() { v: SyncSchema.current, accounts: [ _acc( - platform: ThirdPartyPlatform.cpdaily, + platform: ThirdPartyPlatform.ids, token: 'B', updatedAt: ts, deviceId: 'zzz', @@ -278,7 +283,7 @@ void main() { v: SyncSchema.current, accounts: [ _acc( - platform: ThirdPartyPlatform.cpdaily, + platform: ThirdPartyPlatform.ids, token: 'legacy', updatedAt: ts, deviceId: '', @@ -290,7 +295,7 @@ void main() { v: SyncSchema.current, accounts: [ _acc( - platform: ThirdPartyPlatform.cpdaily, + platform: ThirdPartyPlatform.ids, token: 'real', updatedAt: ts, deviceId: 'dev', diff --git a/test/sync_service_test.dart b/test/sync_service_test.dart index 8fcba314..eaccffbb 100644 --- a/test/sync_service_test.dart +++ b/test/sync_service_test.dart @@ -1,3 +1,4 @@ +import 'dart:async'; import 'dart:convert'; import 'package:flutter_secure_storage_ohos/flutter_secure_storage_ohos.dart'; @@ -7,6 +8,7 @@ import 'package:http/testing.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:techpie/features/campus_card/domain/models/auth_models.dart'; import 'package:techpie/models/ecard_sync_binding.dart'; +import 'package:techpie/models/ids_passkey.dart'; import 'package:techpie/models/third_party_account.dart'; import 'package:techpie/models/user_session.dart'; import 'package:techpie/services/auth_service.dart'; @@ -19,7 +21,210 @@ import 'package:techpie/services/sync_service.dart'; import 'package:techpie/services/third_party_auth_service.dart'; import 'package:techpie/services/uni_auth_service.dart'; +import 'support/fake_ids_client.dart'; + void main() { + test('a legacy cloud configuration is preserved and requests Passkey migration', () async { + final fixture = await _Fixture.withSession(); + final legacy = ThirdPartyAccount( + platform: ThirdPartyPlatform.ids, + account: '20240001', + sid: '20240001', + name: 'Legacy User', + token: 'legacy-token', + raw: const {'tgc': 'legacy-tgc'}, + boundAt: DateTime.utc(2026), + autoRenew: true, + password: 'synthetic-password', + ).toJson() + ..['platform'] = 'cpdaily'; + fixture.server.properties['techpie_sync'] = await SyncCrypto.encryptWithSalt( + jsonEncode({ + 'v': 3, + 'accounts': [legacy], + 'tombstones': [], + }), + 'synthetic-password', + ); + final restored = await _Fixture.withSession(server: fixture.server); + expect((await restored.sync.restoreWithMasterPassword('synthetic-password')).ok, true); + expect(restored.tpAuth.needsIdsRebind, true); + expect(restored.tpAuth.idsAccount!.name, 'Legacy User'); + expect(restored.tpAuth.idsAccount!.password, 'synthetic-password'); + final rewritten = jsonDecode( + (await SyncCrypto.decryptWithSalt( + fixture.server.properties['techpie_sync']!, + 'synthetic-password', + ))!, + ) as Map; + expect(rewritten['v'], 4); + expect((rewritten['accounts'] as List).single['platform'], 'ids'); + }); + + test('an old legacy upload cannot restore a configuration deleted while uploading', () async { + final fixture = await _Fixture.withSession(); + await fixture.tpAuth.replaceAll([ + ThirdPartyAccount( + platform: ThirdPartyPlatform.ids, + account: '20240001', + name: 'Legacy User', + token: 'legacy', + raw: const {'tgc': 'old'}, + boundAt: DateTime.now().subtract(const Duration(days: 1)), + ), + ]); + expect((await fixture.sync.setupWithMasterPassword('synthetic-password')).ok, true); + fixture.server.pauseNextWrite(); + final release = fixture.server.releaseNextWrite!; + final upload = fixture.sync.push(); + await fixture.server.nextWriteStarted!.future; + await fixture.tpAuth.unbind(ThirdPartyPlatform.ids); + release.complete(); + expect((await upload).ok, true); + expect(fixture.tpAuth.idsAccount, isNull); + expect(await fixture.storage.loadThirdPartyAccount(ThirdPartyPlatform.ids), isNull); + final plain = (await SyncCrypto.decryptWithSalt( + fixture.server.properties['techpie_sync']!, 'synthetic-password',))!; + expect(SyncEnvelope.decode(plain)!.accounts, isEmpty); + }); + + test('a deletion created during a queued upload is retained for the next upload', () async { + final fixture = await _Fixture.withSession(); + await fixture.tpAuth.replaceAll([ + ThirdPartyAccount( + platform: ThirdPartyPlatform.gradescope, + account: 'synthetic', + token: 'synthetic-token', + boundAt: DateTime.now(), + ), + ]); + expect((await fixture.sync.setupWithMasterPassword('synthetic-password')).ok, true); + fixture.server.pauseNextWrite(); + final release = fixture.server.releaseNextWrite!; + final pending = fixture.sync.push(); + await fixture.server.nextWriteStarted!.future; + await fixture.tpAuth.unbind(ThirdPartyPlatform.gradescope); + release.complete(); + expect((await pending).ok, true); + final plain = (await SyncCrypto.decryptWithSalt( + fixture.server.properties['techpie_sync']!, 'synthetic-password',))!; + final envelope = SyncEnvelope.decode(plain)!; + expect(envelope.accounts, isEmpty); + expect(envelope.tombstones.single.platform, ThirdPartyPlatform.gradescope); + }); + + for (final replace in [false, true]) { + test('an old push response cannot overwrite a newer IDS ${replace ? "binding" : "deletion"}', + () async { + final fixture = await _Fixture.withSession(); + await fixture.tpAuth.applyIdsSyncBinding( + IdsSyncBinding( + credential: FakeIdsClient.key('A'), + updatedAt: DateTime.now().subtract(const Duration(days: 1)), + deviceId: 'first', + ), + ); + expect((await fixture.sync.setupWithMasterPassword('synthetic-password')).ok, true); + fixture.server.pauseNextWrite(); + final release = fixture.server.releaseNextWrite!; + final firstPush = fixture.sync.push(); + await fixture.server.nextWriteStarted!.future; + if (replace) { + await fixture.tpAuth.bindIds( + account: 'B', + password: 'synthetic-password', + promptCaptcha: (_, __, {required refresh}) async => null,); + } else { + await fixture.tpAuth.unbind(ThirdPartyPlatform.ids); + } + release.complete(); + expect((await firstPush).ok, true); + final expected = replace ? 'B' : null; + expect(fixture.tpAuth.idsBinding!.credential?.username, expected); + expect( + IdsSyncBinding.fromAccount( + await fixture.storage.loadThirdPartyAccount(ThirdPartyPlatform.ids),) + ?.credential + ?.username, + expected,); + final plain = (await SyncCrypto.decryptWithSalt( + fixture.server.properties['techpie_sync']!, 'synthetic-password',))!; + expect(SyncEnvelope.decode(plain)!.ids!.credential?.username, expected); + }); + } + + test( + 'IDS sync carries the encrypted key, keeps cookies local, and merges deletions independently', + () async { + final first = await _Fixture.withSession(); + final credential = FakeIdsClient.key('20240001'); + final boundAt = DateTime.now().subtract(const Duration(days: 1)); + await first.tpAuth.applyIdsSyncBinding( + IdsSyncBinding(credential: credential, updatedAt: boundAt, deviceId: 'first'),); + await first.tpAuth.idsNode.renew(); + await first.tpAuth.updateRaw( + ThirdPartyPlatform.ids, {'tgc': 'LOCAL_ONLY_CASTGC', 'cookies': 'LOCAL_ONLY_COOKIE'},); + expect(first.tpAuth.idsBinding!.updatedAt, boundAt); + expect((await first.sync.setupWithMasterPassword('synthetic-password')).ok, true); + final blob = first.server.properties['techpie_sync']!; + expect(blob, isNot(contains(credential.privateKey))); + final plain = (await SyncCrypto.decryptWithSalt(blob, 'synthetic-password'))!; + expect(plain, contains(credential.privateKey)); + expect(plain, isNot(contains('LOCAL_ONLY'))); + final envelope = jsonDecode(plain) as Map; + expect(envelope.containsKey('ids'), false); + final account = (envelope['accounts'] as List).single as Map; + expect(account['platform'], 'ids'); + expect((account['raw'] as Map)['credential'], isNotNull); + expect(account.containsKey('password'), false); + expect(DateTime.parse(account['updatedAt'] as String), boundAt.toUtc()); + expect(account['deviceId'], 'first'); + + final second = await _Fixture.withSession(server: first.server); + expect((await second.sync.restoreWithMasterPassword('synthetic-password')).ok, true); + expect(second.tpAuth.idsBinding!.credential!.credentialId, credential.credentialId); + expect(second.tpAuth.idsNode.cookieProvider, isNull); + // A new device can obtain its own session using the restored software key. + expect(await second.tpAuth.idsNode.renew(), true); + expect(second.tpAuth.idsNode.cookieProvider!.cookies, contains('CASTGC=')); + await second.sync.pull(); + expect(second.tpAuth.idsNode.cookieProvider!.cookies, contains('CASTGC=')); + await second.tpAuth.unbind(ThirdPartyPlatform.ids); + await second.sync.push(); + // An old device's local renewal or backup cannot resurrect the Passkey. + await first.sync.push(); + await first.sync.pull(); + expect(first.tpAuth.idsBinding!.credential, isNull); + expect(first.tpAuth.idsAccount, isNull); + }); + + test('offline Passkey deletion survives a restart before an old cloud backup is read', () async { + final first = await _Fixture.withSession(); + await first.tpAuth.applyIdsSyncBinding( + IdsSyncBinding( + credential: FakeIdsClient.key('20240001'), + updatedAt: DateTime.now().subtract(const Duration(days: 1)), + deviceId: 'first', + ), + ); + expect((await first.sync.setupWithMasterPassword('synthetic-password')).ok, true); + first.tpAuth.onBindingsChanged = null; + await first.tpAuth.unbind(ThirdPartyPlatform.ids); + expect(first.storage.loadThirdPartyTombstones().single.platform, ThirdPartyPlatform.ids); + + final api = LoggingHttpClient(DebugLogger()); + final restarted = ThirdPartyAuthService(first.storage, api, idsClient: FakeIdsClient()); + await restarted.initialize(); + final sync = + SyncService(first.auth, restarted, first.storage, client: first.server.toHttpClient()); + restarted.onUnbind = sync.recordTombstone; + await sync.loadCachedKey(); + await sync.pull(); + expect(restarted.idsBinding!.credential, isNull); + expect(restarted.idsAccount, isNull); + expect(await first.storage.loadThirdPartyAccount(ThirdPartyPlatform.ids), isNull); + }); + test('encrypted cloud backup restores eCard and propagates its deletion', () async { const openId = 'SYNTHETIC_OPENID_CLOUD_123456'; final firstStore = _EcardStore(EcardSyncBinding(openId: openId, channel: EcardOpenIdChannel.alipay, @@ -84,7 +289,7 @@ void main() { final fx = await _Fixture.withSession(); await fx.tpAuth.replaceAll([ ThirdPartyAccount( - platform: ThirdPartyPlatform.cpdaily, + platform: ThirdPartyPlatform.ids, account: '13800000000', sid: '20240001', token: 'tgc-secret', @@ -98,7 +303,7 @@ void main() { final outcome = await fx2.sync.restoreWithMasterPassword('wrong'); expect(outcome.ok, isFalse); expect(outcome.message, contains('不正确')); - expect(fx2.tpAuth.account(ThirdPartyPlatform.cpdaily), isNull); + expect(fx2.tpAuth.account(ThirdPartyPlatform.ids), isNull); }); test('setup replaces an existing cloud backup only when confirmed', () async { @@ -372,6 +577,12 @@ void main() { class _FakeCasdoor { final Map properties = {}; bool enforceAuthz = true; + Completer? nextWriteStarted; + Completer? releaseNextWrite; + void pauseNextWrite() { + nextWriteStarted = Completer(); + releaseNextWrite = Completer(); + } http.Client toHttpClient() { return MockClient((request) async { @@ -405,6 +616,12 @@ class _FakeCasdoor { ); } } + final pause = releaseNextWrite; + if (pause != null) { + releaseNextWrite = null; + nextWriteStarted!.complete(); + await pause.future; + } final props = (decoded['properties'] as Map?)?.cast(); if (props != null) { @@ -456,7 +673,7 @@ class _Fixture { final httpClient = LoggingHttpClient(logger); final uniAuth = UniAuthService(); final auth = AuthService(storage, httpClient, uniAuth); - final tpAuth = ThirdPartyAuthService(storage, httpClient); + final tpAuth = ThirdPartyAuthService(storage, httpClient, idsClient: FakeIdsClient()); final sync = SyncService(auth, tpAuth, storage, client: srv.toHttpClient(), ecard: ecard); // Mirror main.dart wiring so tombstones are recorded + pushes fire. tpAuth.onBindingsChanged = ({force = false}) {