@wilm-ai/wilma-client 1.1.0 → 1.2.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/client.d.ts CHANGED
@@ -1,9 +1,10 @@
1
1
  import type { Exam, Message, MessageFolder, NewsItem, OverviewData, WilmaProfile, StudentInfo } from "./types.js";
2
+ export type MfaCallback = (formkey: string) => Promise<string>;
2
3
  export declare class WilmaClient {
3
4
  private session;
4
5
  private constructor();
5
- static login(profile: WilmaProfile): Promise<WilmaClient>;
6
- static listStudents(profile: WilmaProfile): Promise<StudentInfo[]>;
6
+ static login(profile: WilmaProfile, onMfaRequired?: MfaCallback): Promise<WilmaClient>;
7
+ static listStudents(profile: WilmaProfile, onMfaRequired?: MfaCallback): Promise<StudentInfo[]>;
7
8
  messages: {
8
9
  list: (folder?: MessageFolder) => Promise<Message[]>;
9
10
  get: (messageId: number) => Promise<Message>;
package/dist/client.js CHANGED
@@ -1,4 +1,4 @@
1
- import { WilmaSession } from "./session.js";
1
+ import { WilmaSession, MfaRequiredError } from "./session.js";
2
2
  import { parseWilmaTimestamp } from "./parsers/dates.js";
3
3
  import { parseMessagesList, parseMessageDetailHtml } from "./parsers/messages.js";
4
4
  import { parseNewsDetailHtml, parseNewsDetailJson, parseNewsList, parseNewsListHtml, } from "./parsers/news.js";
@@ -10,17 +10,39 @@ export class WilmaClient {
10
10
  constructor(session) {
11
11
  this.session = session;
12
12
  }
13
- static async login(profile) {
13
+ static async login(profile, onMfaRequired) {
14
14
  const session = new WilmaSession(profile.baseUrl, {
15
15
  studentNumber: profile.studentNumber ?? null,
16
16
  debug: profile.debug ?? false,
17
17
  });
18
- await session.login(profile.username, profile.password);
18
+ try {
19
+ await session.login(profile.username, profile.password);
20
+ }
21
+ catch (err) {
22
+ if (err instanceof MfaRequiredError && onMfaRequired) {
23
+ const otpCode = await onMfaRequired(err.formkey);
24
+ await session.submitMfaCode(err.formkey, otpCode);
25
+ }
26
+ else {
27
+ throw err;
28
+ }
29
+ }
19
30
  return new WilmaClient(session);
20
31
  }
21
- static async listStudents(profile) {
32
+ static async listStudents(profile, onMfaRequired) {
22
33
  const session = new WilmaSession(profile.baseUrl);
23
- await session.login(profile.username, profile.password);
34
+ try {
35
+ await session.login(profile.username, profile.password);
36
+ }
37
+ catch (err) {
38
+ if (err instanceof MfaRequiredError && onMfaRequired) {
39
+ const otpCode = await onMfaRequired(err.formkey);
40
+ await session.submitMfaCode(err.formkey, otpCode);
41
+ }
42
+ else {
43
+ throw err;
44
+ }
45
+ }
24
46
  const resp = await session.get("/");
25
47
  const html = await resp.text();
26
48
  return parseStudentsFromHome(html);
package/dist/index.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  export type { Exam, ExamGrade, HomeworkItem, Message, MessageFolder, Municipality, NewsItem, OverviewData, ScheduleLesson, TenantDiscoveryResponse, TenantInfo, UpcomingExam, WilmaProfile, StudentInfo, } from "./types.js";
2
2
  export { WilmaClient } from "./client.js";
3
- export { WilmaSession, AuthenticationError, APIError } from "./session.js";
3
+ export type { MfaCallback } from "./client.js";
4
+ export { WilmaSession, AuthenticationError, MfaRequiredError, APIError } from "./session.js";
4
5
  export { loadTenantDiscovery, listTenants, searchTenantsByMunicipality, findTenantByUrl, } from "./tenants.js";
5
6
  export { parseWilmaTimestamp } from "./parsers/dates.js";
6
7
  export { parseStudentsFromHome } from "./parsers/students.js";
package/dist/index.js CHANGED
@@ -1,5 +1,5 @@
1
1
  export { WilmaClient } from "./client.js";
2
- export { WilmaSession, AuthenticationError, APIError } from "./session.js";
2
+ export { WilmaSession, AuthenticationError, MfaRequiredError, APIError } from "./session.js";
3
3
  export { loadTenantDiscovery, listTenants, searchTenantsByMunicipality, findTenantByUrl, } from "./tenants.js";
4
4
  export { parseWilmaTimestamp } from "./parsers/dates.js";
5
5
  export { parseStudentsFromHome } from "./parsers/students.js";
package/dist/session.d.ts CHANGED
@@ -1,6 +1,10 @@
1
1
  import { type RequestInit, type Response } from "undici";
2
2
  export declare class AuthenticationError extends Error {
3
3
  }
4
+ export declare class MfaRequiredError extends Error {
5
+ formkey: string;
6
+ constructor(formkey: string);
7
+ }
4
8
  export declare class APIError extends Error {
5
9
  status: number;
6
10
  constructor(message: string, status: number);
@@ -20,6 +24,7 @@ export declare class WilmaSession {
20
24
  get urlPrefix(): string | null;
21
25
  getPrefixedPath(path: string): string;
22
26
  login(username: string, password: string): Promise<void>;
27
+ submitMfaCode(formkey: string, otpCode: string): Promise<void>;
23
28
  private getLoginFormFields;
24
29
  request(path: string, init?: RequestInit): Promise<Response>;
25
30
  get(path: string, init?: RequestInit): Promise<Response>;
package/dist/session.js CHANGED
@@ -2,6 +2,13 @@ import { CookieJar } from "tough-cookie";
2
2
  import { fetch } from "undici";
3
3
  export class AuthenticationError extends Error {
4
4
  }
5
+ export class MfaRequiredError extends Error {
6
+ formkey;
7
+ constructor(formkey) {
8
+ super("MFA verification required");
9
+ this.formkey = formkey;
10
+ }
11
+ }
5
12
  export class APIError extends Error {
6
13
  status;
7
14
  constructor(message, status) {
@@ -65,6 +72,24 @@ export class WilmaSession {
65
72
  .getCookiesSync(this.baseUrl)
66
73
  .some((c) => c.key === "Wilma2SID");
67
74
  const text = await resp.text();
75
+ // Check for MFA challenge by following the post-login redirect
76
+ if (resp.status >= 300 && resp.status < 400 && hasSessionCookie) {
77
+ const location = resp.headers.get("location");
78
+ if (location) {
79
+ const redirectResp = await this.rawRequest(new URL(location).pathname + new URL(location).search, { method: "GET" });
80
+ const redirectText = await redirectResp.text();
81
+ const mfaFormkeyMatch = /id="mfa-formkey"\s+value="([^"]+)"/.exec(redirectText);
82
+ if (mfaFormkeyMatch) {
83
+ if (this.debug) {
84
+ console.log(`[wilmai] MFA challenge detected`);
85
+ }
86
+ // Store credentials so we can complete login after MFA
87
+ this.username = username;
88
+ this.password = password;
89
+ throw new MfaRequiredError(mfaFormkeyMatch[1]);
90
+ }
91
+ }
92
+ }
68
93
  if (hasSessionCookie || isLoginOk(text)) {
69
94
  this.loggedIn = true;
70
95
  this.username = username;
@@ -73,6 +98,43 @@ export class WilmaSession {
73
98
  }
74
99
  throw new AuthenticationError("Wilma login failed");
75
100
  }
101
+ async submitMfaCode(formkey, otpCode) {
102
+ // Wilma's MFA endpoint: POST /api/v1/accounts/me/mfa/otp/check
103
+ // Body: formkey=<formkey>&payload={"otp":"<code>","action":"login"}
104
+ // No student prefix — MFA is account-level, not student-level
105
+ const path = `/api/v1/accounts/me/mfa/otp/check`;
106
+ const body = new URLSearchParams({
107
+ formkey,
108
+ payload: JSON.stringify({ otp: otpCode, action: "login" }),
109
+ });
110
+ if (this.debug) {
111
+ console.log(`[wilmai] POST ${path} (MFA OTP check)`);
112
+ }
113
+ const resp = await this.rawRequest(path, {
114
+ method: "POST",
115
+ body: body.toString(),
116
+ headers: {
117
+ "Content-Type": "application/x-www-form-urlencoded;charset=UTF-8",
118
+ },
119
+ });
120
+ const text = await resp.text();
121
+ let success = false;
122
+ try {
123
+ const data = JSON.parse(text);
124
+ // Response format: { statusCode, payload: { success } } or { success }
125
+ success = data?.payload?.success ?? data?.success ?? false;
126
+ }
127
+ catch {
128
+ throw new AuthenticationError("MFA verification failed: unexpected response");
129
+ }
130
+ if (!success) {
131
+ throw new AuthenticationError("MFA verification failed: invalid OTP code");
132
+ }
133
+ this.loggedIn = true;
134
+ if (this.debug) {
135
+ console.log(`[wilmai] MFA verification successful`);
136
+ }
137
+ }
76
138
  async getLoginFormFields() {
77
139
  const resp = await this.rawRequest("/login", { method: "GET" });
78
140
  if (resp.status >= 400) {
@@ -92,6 +154,9 @@ export class WilmaSession {
92
154
  await this.login(this.username, this.password);
93
155
  resp = await this.rawRequest(prefixedPath, init);
94
156
  }
157
+ if (this.debug) {
158
+ console.log(`[wilmai] ${init?.method ?? "GET"} ${prefixedPath} => ${resp.status}`);
159
+ }
95
160
  if (resp.status >= 400) {
96
161
  throw new APIError(`Wilma HTTP ${resp.status} at ${prefixedPath}`, resp.status);
97
162
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@wilm-ai/wilma-client",
3
- "version": "1.1.0",
3
+ "version": "1.2.1",
4
4
  "type": "module",
5
5
  "main": "dist/index.js",
6
6
  "types": "dist/index.d.ts",