Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
Binary file added assets/help/ids_passkey.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
18 changes: 18 additions & 0 deletions ios/Runner/AppDelegate.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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?
Expand Down Expand Up @@ -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()
Expand Down
7 changes: 5 additions & 2 deletions lib/main.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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';
Expand All @@ -42,6 +43,7 @@ void main(List<String> 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: '启动中…'));
Expand Down Expand Up @@ -77,6 +79,7 @@ Future<void> _realMain(SharedPreferences prefs) async {
final thirdPartyAuthService = ThirdPartyAuthService(
storageService,
httpClient,
idsClient: IdsClient(logger: debugLogger),
);
final scheduleService = ScheduleService(
storageService,
Expand Down Expand Up @@ -127,7 +130,7 @@ Future<void> _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
Expand Down Expand Up @@ -247,7 +250,7 @@ Future<void> _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);
Expand Down
102 changes: 102 additions & 0 deletions lib/models/ids_passkey.dart
Original file line number Diff line number Diff line change
@@ -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<String, dynamic> toJson() => {
'credentialId': credentialId,
'privateKey': privateKey,
'userHandle': userHandle,
'anonBiometricsId': anonBiometricsId,
'username': username,
'rpId': rpId,
'alg': -7,
};

factory IdsPasskey.fromJson(Map<String, dynamic> 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<String, dynamic> 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<String, dynamic>()),
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;
}
}
2 changes: 1 addition & 1 deletion lib/models/renew_status.dart
Original file line number Diff line number Diff line change
@@ -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 {
Expand Down
42 changes: 11 additions & 31 deletions lib/models/third_party_account.dart
Original file line number Diff line number Diff line change
@@ -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,
};
}
Expand Down Expand Up @@ -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) &&
Expand All @@ -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
Expand Down
2 changes: 1 addition & 1 deletion lib/pages/campus_card_page.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
4 changes: 2 additions & 2 deletions lib/pages/campus_session_handle.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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;

Expand Down Expand Up @@ -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,
};
Expand Down
14 changes: 7 additions & 7 deletions lib/pages/egate_app_page.dart
Original file line number Diff line number Diff line change
Expand Up @@ -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});
Expand Down Expand Up @@ -176,7 +176,7 @@ class _EgateAppPageState extends State<EgateAppPage> {
listenable: Listenable.merge([auth, tpAuth]),
builder: (context, _) => PageRefreshButton(
onRefresh: () => _refresh(service),
enabled: auth.isLoggedIn && tpAuth.hasCpdailyBinding,
enabled: auth.isLoggedIn && tpAuth.hasIdsBinding,
refreshing: _loading,
),
),
Expand All @@ -185,7 +185,7 @@ class _EgateAppPageState extends State<EgateAppPage> {
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),
Expand All @@ -203,21 +203,21 @@ class _EgateAppPageState extends State<EgateAppPage> {
),
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' : '去登录'),
),
],
),
Expand Down
6 changes: 3 additions & 3 deletions lib/pages/elrc_recordings_page.dart
Original file line number Diff line number Diff line change
Expand Up @@ -117,13 +117,13 @@ class _ElrcRecordingsPageState extends State<ElrcRecordingsPage> {
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<void> _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();
Expand Down Expand Up @@ -170,7 +170,7 @@ class _ElrcRecordingsPageState extends State<ElrcRecordingsPage> {
}
if (_isLogin(uri) &&
!_campusAttempted &&
_tpAuth!.hasCpdailyBinding) {
_tpAuth!.hasIdsBinding) {
_expectedMainFrameCancellations++;
unawaited(_openLogin());
return NavigationDecision.prevent;
Expand Down
Loading
Loading