flutter_chaoxing 0.4.2
flutter_chaoxing: ^0.4.2 copied to clipboard
Typed Chaoxing (学习通) protocol clients for Dart: request signing, device registration, passport2 login, classroom sign-in across all nine sign flavours, and a solver for the captcha.chaoxing.com slider captcha.
flutter_chaoxing #
Typed Chaoxing (学习通) protocol clients, request signing, and classroom sign-in
for Dart and Flutter. Every routine is a byte-exact port of the official
Android client 7.0.2, recovered from that client's decompiled sources; the
inline citations in the source give the exact file:line each constant and
algorithm came from.
This package is an independent community project and is not affiliated with Chaoxing, 超星, or any 学习通 operator.
Features #
- Three request-signing schemes, ported exactly and never interchanged:
inf_encquery signing (both the declared-orderjui.V/Wvariant and the sorted-key OkHttp interceptor variant).cxsign/signTokenheader signing (sortedkey + valueconcatenation plus a per-installation secret).webRequestSign— the RSA-SHA256 half of theCLIENT_FORM_SIGNJS bridge, with the obfuscated private key extracted fromlibsecuritylib.so.
- Device registration:
CxDevice.getDeviceInfo/decryptDeviceInfo(chunked RSA, jsoncppFastWriteralignment, millisecond timestamps). - Login: passport2 password and SMS flows, AES-ECB
logininfo, manual SSO redirect walking, andclientIdharvest. - Classroom sign-in: the activity/mission surface, the native Fanya
usersign/addsignendpoint, a fullCLIENT_FORM_SIGNimplementation, and apptSign/stuSignajaxsubmit covering every sign flavour — plain, anti-cheat, photo, location, location+face, gesture, sign-code, and the three QR variants. - CXCaptcha solver: 超星's in-house
captcha.chaoxing.comslider, reversed from the obfuscated web bundle — protocol, MD5 parameter derivation, and a four-cue gap detector. Anti-cheat (防作弊/验证码) signs pass with no WebView. - Student data API: notices, grades, homework feed, live classes, course content, timetable, messages, and discussions.
- Typed domain models mirroring the official
StudentMission,Course, andClazzschemas, plus theactiveTypedispatch table and theactiveSortsign-flavour table.
The load-bearing finding #
The official Android client has no native sign-submit endpoint.
StudentMissionFragment.H9 dispatches a handful of activeTypes natively and
sends everything else — all sign flavours — to a WebView pointed at the
server-supplied mission.url. The words otherId, ifphoto,
ifopenAddress, ifrefreshewm, and signCode appear nowhere in the 69,685
recovered classes: they belong to the H5 page's own protocol, not to the app.
What the app does contribute to a sign is two JS bridges — CLIENT_FORM_SIGN
(RSA-signs the page's form fields) and CLIENT_USER_LOCATION (supplies GPS).
An implementation that wants official parity therefore drives the H5 page and
answers those bridges rather than inventing a submit URL.
ChaoxingSignService.handleFormSign is that bridge.
The one exception is the scanned Fanya code, which the client submits natively
via usersign/addsign — see submitFanyaSign.
…but the H5 contract is fully recovered #
"No native submit" is a fact about the client, not a limit on a headless one.
Every flavour's page terminates in the same cookie-authenticated
pptSign/stuSignajax call, and that contract — verbs, per-flavour parameters,
response tokens, and the anti-cheat captcha — is mapped in doc/protocol.md §6–7
and implemented here. Measured live against a course with every flavour published
at once:
| flavour | submit | input it needs |
|---|---|---|
| 纯普通, 防作弊(验证码), 拍照, 位置, 手势, 签到码 | headless | nothing a person must supply at sign time |
| 位置+人脸识别 | headless | one enrolled still photo + the device identity — submitFaceSign; no live capture |
| 二维码, 二维码指定地点 | scanned enc |
decode the teacher's QR (parseScannedQr), then submit |
| 二维码自动更新(~30 s) | scanned enc, timed |
re-decode and submit inside one refresh window |
"Headless" here means no camera, no live QR, no human face at sign time
(ChaoxingSignKind.isHeadlessCapable). Face signs qualify because enrolment
accepts any still photo containing a face and the per-sign "liveness" token is a
plain MD5 over the device secret — there is no live capture to reproduce. The QR
flavours are the only ones that need a person: not to sign, but to point a camera
at the teacher's code so the enc can be read. Once you have the enc,
submitClassroomSign records the sign like any other. Nothing here is a gap in
the package; the only server-side gate left standing is the rotating QR's refresh
window.
Installation #
dart pub add flutter_chaoxing
For Flutter applications:
flutter pub add flutter_chaoxing
The package is pure Dart (no Flutter SDK dependency) and uses dio for HTTP,
so it runs on Android, iOS, Linux, macOS, Windows, and the web (subject to
CORS for the web).
Usage #
Log in #
import 'package:flutter_chaoxing/flutter_chaoxing.dart';
final auth = ChaoxingAuthService();
final session = await auth.login(
const ChaoxingCredentials(account: 'student', password: 'secret'),
);
// session.cookieHeader is replayed on every later call.
SMS login reuses the same call after auth.sendSmsCode(phone), with the code
in the password field and mode: ChaoxingLoginMode.sms.
Two failures mean "a human has to intervene", and they are distinct:
ChaoxingCaptchaRequired— the password itself was refused pending an interactive page.ChaoxingSecondaryVerificationRequired— the password was accepted (status:true) but passport2 wants a second factor before issuing an SSO url. In practice this is new-device SMS verification; it needs a code only the account owner can read.
ChaoxingUserAgent.build now emits the real cryptUserAgent header, so one
UA works for both passport2 and mobilelearn. cryptUserAgent turned out to be
"(schild:" + MD5(suffix + salt) + ")" + suffix; the salt is a 32-byte constant
in libsecuritylib.so. A plaintext official UA (no schild) is still rejected by
passport2 and a browser UA is still rejected by mobilelearn, but neither case
comes up if you use build. The older split, for reference:
// passport2 — browser UA
final auth = ChaoxingAuthService(userAgent: mobileBrowserUa);
final session = await auth.login(credentials, deviceInfo: payload);
// mobilelearn — official UA
final sign = ChaoxingSignService(
userAgent: ChaoxingUserAgent.build(uniqueId: uniqueId),
);
Repeated login attempts provoke the challenge, and it clears on its own; back off
rather than retrying in a tight loop. See doc/protocol.md §1.
Device identity #
The cxsign secret is not a constant in the APK — it is issued per
installation. To obtain it, post a deviceInfo payload with the SSO follow so
the server returns a clientId, then resolve it:
final uniqueId = ChaoxingSignCrypto.newUniqueId(); // persist this!
final payload = ChaoxingSignService.buildDeviceInfoPayload(
ChaoxingDeviceProfile(deviceId: uniqueId, /* …hardware fields… */),
);
final session = await auth.login(credentials, deviceInfo: payload);
if (session.hasDeviceIdentity) {
final identity =
ChaoxingSignService.resolveDeviceIdentity(session.clientId);
// identity.cxcid / identity.sc feed cxsign and CLIENT_FORM_SIGN.
}
uniqueId is a dashless UUID v4 that the official client generates once and
reuses forever. Persist it (secure storage) and never rotate it — changing it
makes the server see a "new device".
List courses and sign-in activities #
final sign = ChaoxingSignService();
final courses = await sign.listCourses(session);
final missions = await sign.listMissions(
session,
courseId: courses.first.courseId,
classId: courses.first.classId,
);
final signIns = missions.where((m) => m.isWebViewDriven);
activeType is 2 for every sign flavour, so it cannot tell them apart. The
stable discriminator is getPPTActiveInfo's otherId plus its modifier flags,
which ChaoxingActiveInfo.parse folds into info.kind (activeSort is not it
— that is a per-plan sequence number that differs between batches):
final info = await sign.fetchActiveInfo(session, mission.id);
switch (info?.kind) {
case ChaoxingSignKind.plain: // no extra input
case ChaoxingSignKind.antiCheat: // needs a CXCaptcha validate token
case ChaoxingSignKind.photo: // needs objectId + photoResult
case ChaoxingSignKind.location: // needs address + coordinates
case ChaoxingSignKind.gesture: // a keypad-digit stroke, same field as signCode
case ChaoxingSignKind.signCode: // needs the code the teacher displays
case ChaoxingSignKind.locationWithFace: // submitFaceSign: enrolled photo + device identity
case ChaoxingSignKind.qrCode: // submitClassroomSign(enc:) from a scanned QR
case ChaoxingSignKind.qrCodeAtLocation: // scanned enc + the sign location
case ChaoxingSignKind.qrCodeRotating: // scanned enc, submitted within one ~30 s window
case ChaoxingSignKind.unknown:
case null:
break; // info == null, or a flavour this build does not recognise
}
info.kind.isHeadlessCapable is the short answer for "can I sign with no camera
and no live QR": true for every flavour except the three QR ones, which need a
scanned enc first (their submit is still submitClassroomSign).
Sign in headlessly #
// 纯普通
var r = await sign.submitClassroomSign(
session,
activeId: mission.id,
courseId: course.courseId,
fid: session.fid,
);
// 防作弊(验证码)— probe, solve the slider, resubmit
r = await sign.submitClassroomSign(/* … */);
if (r.needsValidate) {
final validate = await ChaoxingCaptchaService()
.solveSlide(ChaoxingCaptchaService.signCaptchaId);
r = await sign.submitClassroomSign(/* … */, validate: validate);
}
The remaining flavours add their own arguments — objectId/photoResult
(from uploadPhoto), address/latitude/longitude/ifTiJiao, or
signCode — and submitClassroomSign picks the HTTP verb the matching page
uses. Check the result:
if (r.isSigned) { /* success, success2, or 您已签到过了 */ }
位置+人脸 is headless once a face is enrolled. Enrol any still photo that
contains a face (uploadPhoto, then passport2-api…/api/changefaceid?objectid=),
resolve the device identity from the login clientId, and let submitFaceSign
build the per-sign token, exchange it for an enc, and submit:
final identity = ChaoxingSignService.resolveDeviceIdentity(session.clientId);
r = await sign.submitFaceSign(
session,
activeId: mission.id,
courseId: course.courseId,
fid: session.fid,
faceObjectId: enrolledObjectId, // from changefaceid
identity: identity, // cxcid/sc
latitude: lat, longitude: lng, // BD-09, jittered
);
There is no liveness check to defeat: enrolment runs face detection only, and the per-sign "liveness" token is a plain MD5 over the device secret.
二维码 flavours submit through the same submitClassroomSign, with the enc
read off the teacher's QR. Decode the scan, then sign — the rotating variant has
to land inside one ~30 s refresh:
final target = ChaoxingSignService.parseScannedQr(scannedRaw);
if (target != null && target.enc != null) {
r = await sign.submitClassroomSign(
session,
activeId: target.activeId,
courseId: course.courseId,
fid: session.fid,
kind: ChaoxingSignKind.qrCode,
enc: target.enc!,
// qrCodeAtLocation also needs address + latitude/longitude + the location JSON
);
}
Three gotchas worth knowing:
- Location coordinates are BD-09. The H5 pages use Baidu Maps. The server
names the target in
info.locationTextbut returns its coordinates empty — geocode the address yourself, and run it throughjitterLocationso repeated signs do not all land on one identical point. - 签到码 must not be brute-forced. Validate once with
sign.checkSignCode(...);ChaoxingSignCodeCheck.isBannedmeans the server has already blocked further attempts for that activity. A 手势 sign uses the same field: the 3×3 keypad stroke as digits (middle column =258). namemust be passed raw. The pagesencodeURIComponentit and then hand-build a query string; a form/Uribody encodes again, and the server stores the percent-encoded bytes in the teacher's roster.
Solving the captcha on its own #
ChaoxingCaptchaService talks to captcha.chaoxing.com directly and needs no
session:
final captcha = ChaoxingCaptchaService(logger: debugPrint);
final validate = await captcha.solveSlide(
ChaoxingCaptchaService.signCaptchaId, // classroom signs
// ChaoxingCaptchaService.passportCaptchaId for the login 安全验证 page
);
Each step is also exposed separately (fetchServerTime, fetchChallenge,
check) and the detector is usable on its own
(ChaoxingCaptchaDetector.detectOffset). Note that a token accepts exactly
one answer — solveSlide's attempts buys fresh challenges, not retries.
Only the slide flavour is solved; see doc/protocol.md §7.5 for why the
others are harder.
Answer the CLIENT_FORM_SIGN bridge #
When driving the H5 sign page in a WebView, intercept the bridge and return
handleFormSignJson verbatim:
final tokens = sign.handleFormSignJson(
rawJsonFromPage,
identity, // ChaoxingDeviceIdentity from resolveDeviceIdentity
);
// hand `tokens` back to the page's JS callback
Student data API #
final api = ChaoxingApiService();
final notices = await api.fetchNotices(session, pageSize: 20);
final unread = await api.fetchUnreadNoticeCount(session);
final tasks = await api.fetchTaskFeed(session, userid: session.puid);
final live = await api.fetchOngoingLive(session);
See lib/src/chaoxing_api_service.dart for the full surface: grades
(fetchSelfScoreDetail, fetchExamList, fetchWorkList), homework
(fetchUnfinishedJobs), live classes (fetchLiveDetail), course content
(fetchChapterTree, fetchKnowledgeCards), timetable (fetchLesson),
messages, and discussions.
API Overview #
| Type | Purpose |
|---|---|
ChaoxingAuthService |
passport2 login, SMS, SSO cookie harvest |
ChaoxingSignService |
Classroom activities, sign-in, CLIENT_FORM_SIGN, Fanya submit |
ChaoxingCaptchaService |
captcha.chaoxing.com client — challenge, answer, solveSlide |
ChaoxingCaptchaDetector |
Slide gap detection over the two challenge images |
ChaoxingApiService |
Notices, grades, homework, live, courses, timetable, messages |
ChaoxingSignCrypto |
The three signing schemes, device RSA, jsoncpp alignment |
ChaoxingUserAgent |
Official 7.0.2 User-Agent construction |
ChaoxingSession |
Cookie jar + parsed identity + clientId |
ChaoxingCredentials |
Account/password or phone/SMS pair |
ChaoxingCourse / ChaoxingMission |
Official course and activity schemas |
ChaoxingActiveInfo / ChaoxingSignKind |
Activity config and the activeSort flavour table |
ChaoxingClassroomSignResult / ChaoxingSignCodeCheck |
Submit and 签到码 verdicts |
ChaoxingCaptchaChallenge / ChaoxingCaptchaVerdict |
Captcha round-trip types |
ChaoxingDeviceProfile / ChaoxingDeviceIdentity |
Device registration in, cxcid/sc out |
ChaoxingFormSignRequest / ChaoxingFormSignTokens |
The CLIENT_FORM_SIGN bridge contract |
ChaoxingFanyaSignResult / ChaoxingFanyaSignCode |
Native Fanya submit outcome |
ChaoxingLogger |
Injectable diagnostics sink (replaces debugPrint) |
Integration boundary #
The package owns the protocol: HTTP, signing, parsing, and typed models. The host application owns everything stateful:
- Credential/session persistence — store
ChaoxingSessionin secure storage; the package never touches disk. uniqueIdpersistence — generate once viaChaoxingSignCrypto .newUniqueId(), persist, and pass it into device registration and Fanya signs.- Dependency injection — construct the services yourself (or wire them into Riverpod/Bloc/providers as you see fit).
- Logging — inject a
ChaoxingLogger(e.g.debugPrint) intoChaoxingAuthServiceandChaoxingSignService. - WebView driving — the H5 sign page and the
CLIENT_FORM_SIGN/CLIENT_USER_LOCATIONbridges are the host's responsibility.
Security And Compatibility #
- Do not commit passwords, cookies,
clientId, or thecxcid/scpair. - The
cxsignsecret is per-installation; never hardcode a captured one. - Endpoints and constants are pinned to client 7.0.2. Chaoxing rotates these periodically — re-verify against a current capture before relying on them.
- Several device-fingerprint fields (
mediaDrmId,cdtype,cdid,platform/os_name) are built inside JNI and were not recoverable; they are modelled as caller-supplied and omitted when unset, never faked. - Test against a disposable account before enabling any write path.
Development #
dart format lib test example
dart analyze
dart test
dart pub publish --dry-run
Publishing #
Releases are published manually with an authenticated dart pub login session:
dart pub publish --force # after bumping version in pubspec.yaml + CHANGELOG.md
Run dart pub publish --dry-run first; it is the only way to see exactly which
files end up in the archive.
License #
Apache-2.0. See LICENSE.
Versions 0.1.0–0.1.2 were released under MIT; the switch to Apache-2.0 took effect with 0.1.3 and adds an explicit patent grant. Code already taken under MIT may continue to be used under those terms.