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
14 changes: 7 additions & 7 deletions docs/CLI_REFERENCE.md
Original file line number Diff line number Diff line change
Expand Up @@ -86,7 +86,7 @@ uit grades 'https://courses.uit.edu.vn/course/view.php?id=19207'

### `uit login`

Sign in to UIT Moodle. **UIT SSO is the default**; `--legacy` restores the v1.0/v1.1 Student ID/password flow for the old Moodle portal.
Sign in to UIT Moodle. **UIT SSO is the default**; `--legacy` opens the selected legacy Moodle portal in bundled Chromium.

```bash
# Recommended: Sign in via UIT SSO in browser (default)
Expand All @@ -95,16 +95,16 @@ uit login
# Explicit SSO:
uit login --sso

# Legacy Moodle: prompts for Student ID and password, then stores the returned token:
# Undergraduate legacy Moodle:
uit login --legacy

# Non-interactive legacy token setup:
uit login --legacy --username YOUR_STUDENT_ID --password YOUR_PASSWORD
# Graduate legacy Moodle:
uit login --legacy --graduate
```

Prefer the interactive browser login (`uit login`) or `uit login --legacy` for normal use. Passwords passed as command-line arguments can be saved in shell history. The CLI does not save your password; it stores only the session/token.
Both flows open the official portal in bundled Chromium. Sign in there; UIT stores the Moodle session cookies and `sesskey`, never the password. Web-service-token authentication is not supported.

SSO and token sessions are saved to `~/.uit/sessions.json` (mode `0600` on Unix) and shared with UIT Studio. The user ID is discovered during login and stored with the session. Re-run `uit login` at any time to refresh or rotate it.
Sessions are saved to `~/.uit/sessions.json` (mode `0600` on Unix) and shared with UIT Studio. The user ID is discovered during login and stored with the session. Re-run the relevant `uit login` command to refresh it.

---

Expand Down Expand Up @@ -372,7 +372,7 @@ uit grades 19207

### `uit functions [keyword]`

List the 420+ Moodle web service functions available to your token. Grouped by module.
List the Moodle API functions exposed to your signed-in account, grouped by module.

```bash
uit functions # list all
Expand Down
2 changes: 1 addition & 1 deletion packages/uit-runtime/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
"LICENSE"
],
"scripts": {
"postinstall": "node dist/studio-sso.js --install-browser",
"postinstall": "node dist/moodle-browser-login.js --install-browser",
"prepack": "npm --prefix ../.. run build && node ../../scripts/prepare-runtime-package.mjs"
},
"dependencies": {
Expand Down
2 changes: 1 addition & 1 deletion scripts/check-studio-package.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ for (const required of [
"dist/session-health.js",
"dist/studio-core.js",
"dist/studio-thread-store.js",
"dist/studio-sso.js",
"dist/moodle-browser-login.js",
"dist/studio-web-server.js",
"dist/studio-web-launcher.js",
"dist/uit-tools.js",
Expand Down
2 changes: 1 addition & 1 deletion scripts/package-studio-standalone.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -195,7 +195,7 @@ async function main() {
const browserRoot = join(runtimeRoot, "browsers");
const browserEnvironment = { ...process.env, PLAYWRIGHT_BROWSERS_PATH: browserRoot, UIT_STUDIO_CHROMIUM_DIR: browserRoot };
delete browserEnvironment.PLAYWRIGHT_SKIP_BROWSER_DOWNLOAD;
const installScript = `import { installBundledChromium } from ${JSON.stringify(pathToFileURL(join(runtimeRoot, "dist", "studio-sso.js")).href)}; installBundledChromium();`;
const installScript = `import { installBundledChromium } from ${JSON.stringify(pathToFileURL(join(runtimeRoot, "dist", "moodle-browser-login.js")).href)}; installBundledChromium();`;
run(nodePath, ["--input-type=module", "-e", installScript], { cwd: appRoot, env: browserEnvironment });
const executablePath = chromiumManifest(runtimeRoot, platform, architecture);
console.log(`Bundled Chromium: ${executablePath}`);
Expand Down
2 changes: 1 addition & 1 deletion scripts/prepare-runtime-package.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ const sharedModules = [
"studio-core",
"notifications",
"studio-thread-store",
"studio-sso",
"moodle-browser-login",
"studio-web-server",
"studio-web-launcher",
"moodle-session-client",
Expand Down
149 changes: 53 additions & 96 deletions src/api.ts

Large diffs are not rendered by default.

35 changes: 13 additions & 22 deletions src/cli.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,6 @@ import {
cmdEvents,
cmdFunctions,
cmdGrades,
cmdInit,
cmdOpen,
cmdRaw,
cmdReply,
Expand All @@ -25,17 +24,19 @@ import {
createContext
} from "./commands.js";
import { runMcpServer, installMcpServer } from "./mcp-server.js";
import { cmdLoginSso, type SsoLoginLauncher } from "./sso-login.js";
import { cmdLoginLegacy, cmdLoginSso, type LegacyLoginLauncher, type SsoLoginLauncher } from "./sso-login.js";
import { VERSION } from "./version.js";
import { registerNotificationCommands } from "./notification-commands.js";

const CURRENT_SITE_BASE_URL = "https://courses.uit.edu.vn";
const LEGACY_SITE_BASE_URL = "https://coursesold.uit.edu.vn";
const GRADUATE_SITE_BASE_URL = `${LEGACY_SITE_BASE_URL}/sdh`;

export const WORKFLOW = `
workflow:
uit login -> sign in via UIT SSO (default)
uit login --legacy -> sign in to legacy Moodle with Student ID/password
uit login --legacy -> sign in to undergraduate legacy Moodle in Chromium
uit login --legacy --graduate -> sign in to graduate legacy Moodle in Chromium
uit courses --current -> get course IDs
uit contents <course_id> -> browse modules (shows module IDs)
uit view <id> -> inspect any module (accepts module_id or assign_id)
Expand All @@ -53,7 +54,7 @@ export const WORKFLOW = `
uit view-discussion <discussion_id> -> read forum thread (shows post IDs)
uit reply <post_id> <message> -> reply to a forum post
uit open <id> -> open in browser (module, course, or URL)
uit functions [keyword] -> discover 420+ raw API functions
uit functions [keyword] -> discover available Moodle API functions
uit raw <function> key=value -> call any Moodle API function

ID chain: courses -> course_id -> contents / download / announcements / deadlines / grades
Expand Down Expand Up @@ -122,7 +123,7 @@ function printLanding(): void {

export function createProgram(
api: ApiClient = defaultApiClient,
options: { openBrowser?: boolean; ssoLauncher?: SsoLoginLauncher } = {}
options: { openBrowser?: boolean; ssoLauncher?: SsoLoginLauncher; legacyLauncher?: LegacyLoginLauncher } = {}
): Command {
const ctx = createContext(api);
const program = new Command();
Expand All @@ -142,23 +143,13 @@ export function createProgram(
.command("login")
.description("Sign in via UIT SSO (default) or legacy Moodle")
.option("--sso", "Sign in via UIT SSO in browser window")
.option("--legacy", "Sign in to legacy Moodle with Student ID/password")
.option("-u, --username <username>", "Student ID for legacy token setup")
.option("-p, --password <password>", "Password for non-interactive legacy token setup")
.option("--legacy", "Sign in to legacy Moodle in a browser window")
.option("--graduate", "Use the graduate legacy portal (/sdh); requires --legacy")
.action(async (opts) => {
const hasLegacyCredentials = Boolean(opts.username || opts.password);
if (opts.legacy && opts.sso) {
throw new CliError("Choose one login method: --sso or --legacy.");
}
if (opts.sso && hasLegacyCredentials) {
throw new CliError("--sso cannot be combined with --username or --password.");
}
if (opts.legacy || hasLegacyCredentials) {
await cmdInit({
url: LEGACY_SITE_BASE_URL,
username: opts.username,
password: opts.password
});
if (opts.legacy && opts.sso) throw new CliError("Choose one login method: --sso or --legacy.");
if (opts.graduate && !opts.legacy) throw new CliError("--graduate requires --legacy.");
if (opts.legacy) {
await cmdLoginLegacy({ url: opts.graduate ? GRADUATE_SITE_BASE_URL : LEGACY_SITE_BASE_URL }, options.legacyLauncher);
return;
}
await cmdLoginSso({ url: CURRENT_SITE_BASE_URL }, options.ssoLauncher);
Expand Down Expand Up @@ -265,7 +256,7 @@ export function createProgram(

program
.command("functions")
.description("List/search available Moodle API functions (420+)")
.description("List/search Moodle API functions exposed to your account")
.argument("[query]", "Filter by keyword, e.g. 'assign', 'quiz', 'forum'", "")
.action((query) => cmdFunctions({ query }, ctx));

Expand Down
92 changes: 2 additions & 90 deletions src/commands.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,8 @@ import { existsSync } from "node:fs";
import { basename, join, resolve, sep } from "node:path";
import { execFile } from "node:child_process";
import { promisify } from "node:util";
import { createInterface } from "node:readline/promises";
import { Writable } from "node:stream";
import { defaultApiClient } from "./api.js";
import { get, save } from "./config.js";
import { get } from "./config.js";
import { listH5pActivities, readH5pActivity } from "./h5p.js";
import type { ApiClient, MoodleRecord } from "./types.js";
import { extractH5pPackage } from "./unzip.js";
Expand Down Expand Up @@ -56,90 +54,6 @@ function formatSize(size: number): string {
return size < 1_048_576 ? `${(size / 1024).toFixed(0)}KB` : `${(size / 1_048_576).toFixed(1)}MB`;
}

async function initSiteInfo(token: string, baseUrl: string): Promise<MoodleRecord> {
const url = new URL(`${baseUrl}/webservice/rest/server.php`);
url.searchParams.set("wstoken", token);
url.searchParams.set("wsfunction", "core_webservice_get_site_info");
url.searchParams.set("moodlewsrestformat", "json");
const response = await fetch(url, { signal: AbortSignal.timeout(15_000) });
if (!response.ok) throw new Error(`HTTP ${response.status}: ${response.statusText}`);
return response.json() as Promise<MoodleRecord>;
}

export async function requestMobileToken(baseUrl: string, username: string, password: string): Promise<string> {
const response = await fetch(`${baseUrl}/login/token.php`, {
method: "POST",
headers: { "Content-Type": "application/x-www-form-urlencoded" },
body: new URLSearchParams({
username,
password,
service: "moodle_mobile_app"
}),
signal: AbortSignal.timeout(15_000)
});
if (!response.ok) throw new Error(`HTTP ${response.status}: ${response.statusText}`);
const data = (await response.json()) as MoodleRecord;
if (data.error) die(String(data.error));
if (!data.token) die("Moodle did not return a token", "Check your username/password and whether Moodle Mobile services are enabled.");
return String(data.token);
}

async function promptText(label: string): Promise<string> {
if (!process.stdin.isTTY) die("Cannot prompt for credentials without an interactive terminal.");
const rl = createInterface({ input: process.stdin, output: process.stderr });
try {
return (await rl.question(label)).trim();
} finally {
rl.close();
}
}

async function promptPassword(label: string): Promise<string> {
if (!process.stdin.isTTY) die("Cannot prompt for credentials without an interactive terminal.");
process.stderr.write(label);
const mutedOutput = new Writable({
write(_chunk, _encoding, callback) {
callback();
}
}) as Writable & { isTTY?: boolean; columns?: number };
mutedOutput.isTTY = true;
mutedOutput.columns = process.stderr.columns || 80;

const rl = createInterface({
input: process.stdin,
output: mutedOutput,
terminal: true
});
try {
return await rl.question("");
} finally {
rl.close();
process.stderr.write("\n");
}
}

async function resolveInitToken(args: { token?: string; username?: string; password?: string }, baseUrl: string): Promise<string> {
if (args.token) return args.token;

const username = args.username || (await promptText("Student ID: "));
const password = args.password || (await promptPassword("Password: "));
if (!username) die("Student ID is required.");
if (!password) die("Password is required.");

loading("Requesting Moodle token...");
return requestMobileToken(baseUrl, username, password);
}

export async function cmdInit(args: { token?: string; url: string; username?: string; password?: string }): Promise<void> {
const baseUrl = args.url.replace(/\/+$/, "");
const token = await resolveInitToken(args, baseUrl);
const data = await initSiteInfo(token, baseUrl);
if (data.exception) die(data.message || "invalid token");
const userId = data.userid;
save(token, userId, baseUrl);
out({ status: "ok", user: data.fullname, user_id: userId, site: data.sitename });
}

export async function cmdCourses(args: { current?: boolean }, ctx = createContext()): Promise<void> {
loading("Loading courses...");
let courses = await ctx.api.call<MoodleRecord[]>("core_enrol_get_users_courses", { userid: get("userId") });
Expand Down Expand Up @@ -775,9 +689,7 @@ export async function cmdDownload(
if (isH5p && args.extract) extractPackage(record, dest);
results.push(record);
} catch (error) {
let message = error instanceof Error ? error.message : String(error);
const token = get("token");
if (token && message.includes(token)) message = message.replaceAll(token, "***");
const message = error instanceof Error ? error.message : String(error);
results.push({ file: file.filename, status: "error", error: message });
if (!isJsonMode()) console.log(` FAIL: ${message}`);
}
Expand Down
Loading
Loading