infinitecampus-mcp 3.1.2 → 3.1.3

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.js CHANGED
@@ -1,7 +1,9 @@
1
- import { writeFile, stat } from 'fs/promises';
2
- import { dirname } from 'path';
1
+ import { open, lstat, realpath } from 'fs/promises';
2
+ import { constants as fsConstants } from 'fs';
3
+ import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'path';
3
4
  import { parseCookieJar } from '@chrischall/mcp-utils';
4
5
  import { createCookieSessionManager } from '@chrischall/mcp-utils/session';
6
+ import { resolveDownloadDir } from './config.js';
5
7
  import { createSessionCache, reportCacheWriteFailure } from './session-cache.js';
6
8
  const SESSION_TTL_MS = 5 * 60 * 60 * 1000; // 5h, slightly under IC's typical 6h
7
9
  export class ICClient {
@@ -226,20 +228,29 @@ export class ICClient {
226
228
  return data;
227
229
  }
228
230
  async request(district, path, opts = {}) {
231
+ const account = await this.resolveAccount(district);
232
+ await this.managers.get(account.name).ensure();
233
+ return this.doRequest(account, path, opts);
234
+ }
235
+ /**
236
+ * The account for `district`, running CUPS discovery once on a miss.
237
+ *
238
+ * Cold-start: linked districts are only added to the accounts map after
239
+ * primary login + CUPS discovery. If the caller asks for a linked district
240
+ * before any other request triggered login, we'd otherwise throw
241
+ * UnknownDistrictError despite the district being valid. Shared by request()
242
+ * and download() — download() once looked the map up directly, so a linked
243
+ * district's document failed on a cold start (fleet-audit#142).
244
+ */
245
+ async resolveAccount(district) {
229
246
  let account = this.accounts.get(district);
230
247
  if (!account) {
231
- // Cold-start: linked districts are only added to the accounts map after
232
- // primary login + CUPS discovery. If the caller asks for a linked
233
- // district before any other request triggered login, we'd otherwise
234
- // throw UnknownDistrictError despite the district being valid. Run
235
- // discovery once before giving up.
236
248
  await this.ensureDiscovery();
237
249
  account = this.accounts.get(district);
238
250
  if (!account)
239
251
  throw new UnknownDistrictError(district, [...this.accounts.keys()]);
240
252
  }
241
- await this.managers.get(account.name).ensure();
242
- return this.doRequest(account, path, opts);
253
+ return account;
243
254
  }
244
255
  async login(account) {
245
256
  // Linked districts have no real credentials of their own — they hold
@@ -489,42 +500,43 @@ export class ICClient {
489
500
  }
490
501
  }
491
502
  async download(district, path, destinationPath, opts = {}) {
492
- // Pre-flight checks before authenticating, so we fail fast on bad paths
503
+ // Pre-flight checks before authenticating, so we fail fast on bad paths —
504
+ // and, for the confinement checks, before anything is fetched at all.
505
+ const target = await confinedDestination(destinationPath);
493
506
  let destStat = null;
494
507
  try {
495
- destStat = await stat(destinationPath);
508
+ destStat = await lstat(target.real);
496
509
  }
497
510
  catch { /* not present, ok */ }
511
+ // lstat, not stat: a symlink here would redirect the write anywhere. This
512
+ // is the fail-fast check; writeConfined() re-enforces it atomically at
513
+ // open time, since a link can be planted while the document is fetched.
514
+ if (destStat?.isSymbolicLink())
515
+ throw new InvalidPathError(destinationPath, 'is a symlink');
498
516
  if (destStat?.isDirectory())
499
517
  throw new InvalidPathError(destinationPath);
500
518
  if (destStat && !opts.overwrite)
501
519
  throw new FileExistsError(destinationPath);
502
- const parent = dirname(destinationPath);
503
- try {
504
- await stat(parent);
505
- }
506
- catch {
507
- throw new ParentDirectoryMissingError(parent);
508
- }
509
- const account = this.accounts.get(district);
510
- if (!account)
511
- throw new UnknownDistrictError(district, [...this.accounts.keys()]);
512
- const session = await this.managers.get(account.name).ensure();
513
- // Support both relative paths (/campus/...) and absolute URLs
514
- // (e.g. report-card URLs from ic_list_documents come fully-qualified).
515
- const url = /^https?:\/\//i.test(path) ? path : `${account.baseUrl}${path}`;
516
- const res = await fetch(url, {
520
+ const account = await this.resolveAccount(district);
521
+ const url = documentUrl(account, path);
522
+ // Same session contract as doRequest(): withSession invalidates a 401'd
523
+ // session (one restored from disk, or idled out server-side), re-logs in
524
+ // and replays exactly once. A bare ensure()+fetch left a stale session in
525
+ // place, so every retry 401'd until some unrelated call refreshed it.
526
+ const res = await this.managers.get(account.name).withSession(async (session) => fetch(url, {
517
527
  headers: {
518
528
  Cookie: session.cookieHeader,
519
529
  ...(session.xsrfToken ? { 'X-XSRF-TOKEN': session.xsrfToken } : {}),
520
530
  },
521
- });
531
+ }));
532
+ if (res.status === 401)
533
+ throw new SessionExpiredError(account.name);
522
534
  if (!res.ok)
523
535
  throw new Error(`IC download ${res.status} for ${path}`);
524
536
  const buf = new Uint8Array(await res.arrayBuffer());
525
- await writeFile(destinationPath, buf);
537
+ await writeConfined(target.real, destinationPath, buf, !!opts.overwrite);
526
538
  return {
527
- path: destinationPath,
539
+ path: target.requested,
528
540
  bytes: buf.byteLength,
529
541
  contentType: res.headers.get('content-type') ?? 'application/octet-stream',
530
542
  };
@@ -566,6 +578,99 @@ export class ICClient {
566
578
  return (text ? JSON.parse(text) : null);
567
579
  }
568
580
  }
581
+ /**
582
+ * Write a download to its (already confined) destination without ever
583
+ * following a symlink at the final path component. The pre-flight lstat in
584
+ * download() is separated from this write by a network fetch, so a link can
585
+ * be planted in between; O_NOFOLLOW makes the open itself refuse it (ELOOP),
586
+ * and O_EXCL (without overwrite) refuses anything that appeared at all.
587
+ */
588
+ async function writeConfined(real, requested, buf, overwrite) {
589
+ // O_NOFOLLOW is POSIX-only: on Windows it is undefined, which `|` coerces to
590
+ // 0 (and creating a symlink there needs elevated rights anyway).
591
+ const { O_WRONLY, O_CREAT, O_TRUNC, O_EXCL, O_NOFOLLOW } = fsConstants;
592
+ const flags = O_WRONLY | O_CREAT | O_NOFOLLOW | (overwrite ? O_TRUNC : O_EXCL);
593
+ let handle;
594
+ try {
595
+ handle = await open(real, flags, 0o666);
596
+ }
597
+ catch (e) {
598
+ const code = e.code;
599
+ if (code === 'ELOOP')
600
+ throw new InvalidPathError(requested, 'is a symlink');
601
+ if (code === 'EEXIST')
602
+ throw new FileExistsError(requested);
603
+ throw e;
604
+ }
605
+ try {
606
+ await handle.writeFile(buf);
607
+ }
608
+ finally {
609
+ await handle.close();
610
+ }
611
+ }
612
+ /**
613
+ * Resolve a model-supplied destinationPath inside the download directory, or
614
+ * refuse it (fleet-audit#145).
615
+ *
616
+ * Relative paths resolve against the download dir. The containment check runs
617
+ * on REAL paths: the parent directory is realpath'd, so a symlinked directory
618
+ * inside the download dir that points elsewhere is caught, and a download dir
619
+ * that is itself reached through a symlink (macOS /var → /private/var) still
620
+ * matches. `requested` is the path as the caller named it, for the receipt.
621
+ */
622
+ async function confinedDestination(destinationPath) {
623
+ const root = resolveDownloadDir();
624
+ let rootReal;
625
+ try {
626
+ rootReal = await realpath(root);
627
+ }
628
+ catch {
629
+ throw new DownloadDirMissingError(root);
630
+ }
631
+ const requested = resolve(root, destinationPath);
632
+ const parent = dirname(requested);
633
+ let parentReal;
634
+ try {
635
+ parentReal = await realpath(parent);
636
+ }
637
+ catch {
638
+ throw new ParentDirectoryMissingError(parent);
639
+ }
640
+ const real = join(parentReal, basename(requested));
641
+ const rel = relative(rootReal, real);
642
+ if (isAbsolute(rel) || rel.split(sep)[0] === '..') {
643
+ throw new PathOutsideDownloadDirError(destinationPath, root);
644
+ }
645
+ return { requested, real };
646
+ }
647
+ /**
648
+ * Resolve a documentId to the URL download() may fetch WITH the district's
649
+ * session cookies — or refuse it.
650
+ *
651
+ * Both relative paths (/campus/...) and absolute URLs are accepted, because
652
+ * report-card URLs from ic_list_documents come fully-qualified. But documentId
653
+ * is model-controlled, and the text the model reads (teacher messages, district
654
+ * announcements) is not ours: honouring any absolute URL handed the parent's
655
+ * live IC session to whatever host a prompt injection named, and made the
656
+ * server a credentialed SSRF primitive when hosted. So the result must be https
657
+ * on the district's own origin, checked on the PARSED URL — a string prefix
658
+ * test would pass `https://<district-host>.evil.example` and, via the
659
+ * concatenation below, `@evil.example/x` (userinfo) too.
660
+ */
661
+ function documentUrl(account, path) {
662
+ const raw = /^[a-z][a-z0-9+.-]*:/i.test(path) ? path : `${account.baseUrl}${path}`;
663
+ let parsed = null;
664
+ try {
665
+ parsed = new URL(raw);
666
+ }
667
+ catch { /* unparseable — refused below */ }
668
+ const allowed = new URL(account.baseUrl).origin;
669
+ if (!parsed || parsed.protocol !== 'https:' || parsed.origin !== allowed) {
670
+ throw new DocumentOriginNotAllowedError(path, allowed);
671
+ }
672
+ return parsed.href;
673
+ }
569
674
  /**
570
675
  * Parse Set-Cookie headers into a deduplicated Cookie header + XSRF token via
571
676
  * `parseCookieJar` (see inline comment for the splitter/jar details).
@@ -641,14 +746,46 @@ export class SessionExpiredError extends Error {
641
746
  this.name = 'SessionExpiredError';
642
747
  }
643
748
  }
749
+ export class DocumentOriginNotAllowedError extends Error {
750
+ documentId;
751
+ allowedOrigin;
752
+ constructor(documentId, allowedOrigin) {
753
+ super(`DocumentOriginNotAllowed: refusing to send the IC session to '${documentId}'. ` +
754
+ `Documents are only downloaded over https from ${allowedOrigin} — pass the url ` +
755
+ 'field from ic_list_documents for this district.');
756
+ this.documentId = documentId;
757
+ this.allowedOrigin = allowedOrigin;
758
+ this.name = 'DocumentOriginNotAllowedError';
759
+ }
760
+ }
644
761
  export class InvalidPathError extends Error {
645
762
  path;
646
- constructor(path) {
647
- super(`InvalidPath: destinationPath must be a filename, not a directory: ${path}`);
763
+ constructor(path, reason = 'is a directory') {
764
+ super(`InvalidPath: destinationPath must be a regular filename, but ${path} ${reason}`);
648
765
  this.path = path;
649
766
  this.name = 'InvalidPathError';
650
767
  }
651
768
  }
769
+ export class PathOutsideDownloadDirError extends Error {
770
+ path;
771
+ downloadDir;
772
+ constructor(path, downloadDir) {
773
+ super(`PathOutsideDownloadDir: ${path} is outside the download directory ${downloadDir}. ` +
774
+ 'Documents are only written inside it — pass a path under it (or a relative one), ' +
775
+ 'or set IC_DOWNLOAD_DIR to change it.');
776
+ this.path = path;
777
+ this.downloadDir = downloadDir;
778
+ this.name = 'PathOutsideDownloadDirError';
779
+ }
780
+ }
781
+ export class DownloadDirMissingError extends Error {
782
+ path;
783
+ constructor(path) {
784
+ super(`DownloadDirMissing: the download directory ${path} does not exist. Create it or set IC_DOWNLOAD_DIR.`);
785
+ this.path = path;
786
+ this.name = 'DownloadDirMissingError';
787
+ }
788
+ }
652
789
  export class ParentDirectoryMissingError extends Error {
653
790
  path;
654
791
  constructor(path) {
package/dist/config.js CHANGED
@@ -1,3 +1,5 @@
1
+ import { homedir } from 'node:os';
2
+ import { isAbsolute, join } from 'node:path';
1
3
  import { readEnvVar } from '@chrischall/mcp-utils';
2
4
  /**
3
5
  * Read an env var, trim whitespace, and treat as unset if blank or if the value
@@ -60,3 +62,17 @@ export function loadAccount(env = process.env) {
60
62
  password: password ?? '',
61
63
  };
62
64
  }
65
+ /**
66
+ * The one directory ic_download_document may write into: IC_DOWNLOAD_DIR, or
67
+ * ~/Downloads. destinationPath is model-controlled, so without a fence a
68
+ * prompt injection could write downloaded bytes over ~/.zshrc or into
69
+ * ~/.ssh/authorized_keys (fleet-audit#145). Must be absolute — a relative one
70
+ * would move with the process's cwd.
71
+ */
72
+ export function resolveDownloadDir(env = process.env) {
73
+ const dir = readVar(env, 'IC_DOWNLOAD_DIR') ?? join(homedir(), 'Downloads');
74
+ if (!isAbsolute(dir)) {
75
+ throw new Error(`IC_DOWNLOAD_DIR must be an absolute path, got: '${dir}'`);
76
+ }
77
+ return dir;
78
+ }
package/dist/index.js CHANGED
@@ -56,7 +56,7 @@ catch (e) {
56
56
  // avoids — see `unconfiguredClient`.
57
57
  const COMMON = {
58
58
  name: 'infinitecampus',
59
- version: '3.1.2', // x-release-please-version
59
+ version: '3.1.3', // x-release-please-version
60
60
  };
61
61
  // Shared with the healthcheck so it can report the SAME state the tools see,
62
62
  // including on the unconfigured path where there are no tools at all.
@@ -9,7 +9,7 @@ const listArgs = z.object({
9
9
  const downloadArgs = z.object({
10
10
  district: z.string(),
11
11
  documentId: z.string().describe('The url field returned by ic_list_documents'),
12
- destinationPath: z.string().describe('Absolute path where the PDF should be written'),
12
+ destinationPath: z.string().describe('Where to write the PDF. Must be inside the download directory (IC_DOWNLOAD_DIR, default ~/Downloads); a relative path resolves against it.'),
13
13
  overwrite: z.boolean().optional(),
14
14
  });
15
15
  export function registerDocumentTools(server, client) {
@@ -50,7 +50,7 @@ export function registerDocumentTools(server, client) {
50
50
  }
51
51
  });
52
52
  server.registerTool('ic_download_document', {
53
- description: "Download a student's document (PDF) to disk. documentId is the url field returned by ic_list_documents. Returns FeatureDisabled if the district has the module turned off.",
53
+ description: "Download a student's document (PDF) to disk, inside the download directory (IC_DOWNLOAD_DIR, default ~/Downloads). documentId is the url field returned by ic_list_documents. Will not overwrite an existing file unless overwrite is true. Returns FeatureDisabled if the district has the module turned off.",
54
54
  annotations: { destructiveHint: true },
55
55
  inputSchema: downloadArgs,
56
56
  }, async (rawArgs) => {
@@ -3,12 +3,15 @@ import { z } from 'zod';
3
3
  const argsSchema = z.object({
4
4
  district: z.string().describe('District name from ic_list_districts'),
5
5
  studentId: z.string().describe('Student personID from ic_list_students'),
6
- date: z.string().describe('YYYY-MM-DD; defaults to today').optional(),
7
- termFilter: z.string().describe('Term name or ID; optional').optional(),
8
6
  });
7
+ // No date/term arguments: the roster endpoint honours only personID, and no
8
+ // captured payload documents which fields carry the term window, so a
9
+ // client-side filter would be guesswork. Advertising `date`/`termFilter` while
10
+ // ignoring them let the model present the all-terms roster as the answer for
11
+ // the date or term it asked about (fleet-audit#143).
9
12
  export function registerScheduleTools(server, client) {
10
13
  server.registerTool('ic_get_schedule', {
11
- description: "Get a student's class schedule for a given date (default: today).",
14
+ description: "Get a student's class roster: every course with its section placements, across every term of the current enrollment. Not filtered by date or term — each placement carries its own term, so narrow the result yourself.",
12
15
  annotations: { readOnlyHint: true },
13
16
  inputSchema: z.object({ ...argsSchema.shape, view: viewArg() }),
14
17
  }, async (rawArgs) => {
package/mint.yaml CHANGED
@@ -51,6 +51,11 @@ env:
51
51
  help: >-
52
52
  Absolute path for the session cache file. Defaults to
53
53
  $MCP_DATA_DIR/.infinitecampus-mcp/session-<district>.json.
54
+ - name: IC_DOWNLOAD_DIR
55
+ required: false
56
+ help: >-
57
+ Absolute path of the only directory ic_download_document may write into.
58
+ Defaults to ~/Downloads, which must exist.
54
59
  state:
55
60
  dataDir: true
56
61
  reason: >-
@@ -89,7 +94,7 @@ egress:
89
94
  # - each CUPS-linked district's own host, taken from the
90
95
  # `districtLoginUrl` the primary district's API returns (the CUPS
91
96
  # verify.jsp POST and every call to that district go straight there)
92
- # - fully-qualified document URLs the API returns (report cards from
93
- # ic_list_documents are downloaded from wherever they point)
97
+ # (fully-qualified document URLs from ic_list_documents are NOT among
98
+ # them: download() only fetches https URLs on the district's own origin)
94
99
  # Confirm the concrete host(s) against a live run and add them, or the
95
100
  # fence will block those calls while the primary district keeps working.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "infinitecampus-mcp",
3
- "version": "3.1.2",
3
+ "version": "3.1.3",
4
4
  "mcpName": "io.github.chrischall/infinitecampus-mcp",
5
5
  "description": "Infinite Campus (Campus Parent) MCP server — multi-district read + message/document write",
6
6
  "author": "Claude Code (AI) <https://www.anthropic.com/claude>",
package/server.json CHANGED
@@ -6,12 +6,12 @@
6
6
  "url": "https://github.com/chrischall/infinitecampus-mcp",
7
7
  "source": "github"
8
8
  },
9
- "version": "3.1.2",
9
+ "version": "3.1.3",
10
10
  "packages": [
11
11
  {
12
12
  "registryType": "npm",
13
13
  "identifier": "infinitecampus-mcp",
14
- "version": "3.1.2",
14
+ "version": "3.1.3",
15
15
  "transport": {
16
16
  "type": "stdio"
17
17
  },
@@ -64,6 +64,12 @@
64
64
  "description": "Absolute path for the session cache file. Defaults to $MCP_DATA_DIR/.infinitecampus-mcp/session-<district>.json.",
65
65
  "isRequired": false,
66
66
  "format": "string"
67
+ },
68
+ {
69
+ "name": "IC_DOWNLOAD_DIR",
70
+ "description": "Absolute path of the only directory ic_download_document may write into. Defaults to ~/Downloads.",
71
+ "isRequired": false,
72
+ "format": "string"
67
73
  }
68
74
  ]
69
75
  }
@@ -109,7 +109,7 @@ inexplicably. Most student-scoped tools also take `studentId` (the personID from
109
109
  ### Academics
110
110
  | Tool | Notes |
111
111
  |------|-------|
112
- | `ic_get_schedule(district, studentId, view?)` | Today's class schedule by default, with section placements. |
112
+ | `ic_get_schedule(district, studentId, view?)` | Full class roster with section placements, across every term — not filtered by date or term. |
113
113
  | `ic_list_assignments(district, studentId, courseId?, since?, until?, missingOnly?, view?)` | `sectionID` is the only server-side filter; `since`/`until`/`missingOnly` are applied client-side. Pass `missingOnly=true` to see only missing/late work across all courses. |
114
114
  | `ic_list_grades(district, studentId, termId?, view?)` | Term + in-progress grade summary. Omit `termId` for all terms. |
115
115
  | `ic_list_recent_grades(district, studentId, since?, view?)` | Recently-scored assignments. Defaults to a 14-day window; pass `since` (YYYY-MM-DD) to widen. |
@@ -130,7 +130,7 @@ inexplicably. Most student-scoped tools also take `studentId` (the personID from
130
130
  | Tool | Notes |
131
131
  |------|-------|
132
132
  | `ic_list_documents(district, studentId, view?)` | Metadata only (report cards, schedules, transcripts). Each item has a `url` to pass to `ic_download_document`. Returns `FeatureDisabled` if the documents module is off. |
133
- | `ic_download_document(district, url, destinationPath)` | Writes the document to `destinationPath` on disk. **`destinationPath` is required** — confirm the path with the user before calling. |
133
+ | `ic_download_document(district, url, destinationPath, overwrite?)` | Writes the document to `destinationPath`, which must be inside the download directory (`IC_DOWNLOAD_DIR`, default `~/Downloads`; relative paths resolve against it). **`destinationPath` is required** — confirm the path with the user before calling. |
134
134
 
135
135
  ### Messaging
136
136
  | Tool | Notes |
@@ -207,7 +207,7 @@ Two tools take no `view`, both because there is nothing to project:
207
207
  - Or `ic_list_assignments(district, studentId, since=..., until=...)` for a date window
208
208
 
209
209
  **Today's schedule:**
210
- - `ic_get_schedule(district, studentId)` — returns today's classes by default
210
+ - `ic_get_schedule(district, studentId)` — returns every term's roster; pick out the current term's placements
211
211
 
212
212
  **Weather closure or priority announcement?**
213
213
  - `ic_list_messages(district)` — scan the Messenger 2.0 inbox entries for priority subjects
@@ -216,10 +216,10 @@ Two tools take no `view`, both because there is nothing to project:
216
216
  **Download a report card:**
217
217
  1. `ic_list_documents(district, studentId)` → find the report card's `url`
218
218
  2. Confirm destination path with the user
219
- 3. `ic_download_document(district, url, destinationPath="/Users/.../report-card.pdf")`
219
+ 3. `ic_download_document(district, url, destinationPath="report-card.pdf")` — a relative path lands in the download directory
220
220
 
221
221
  ## Caution
222
222
 
223
- - `ic_download_document` writes to disk at `destinationPath` — confirm the path with the user; overwrites silently.
223
+ - `ic_download_document` writes to disk at `destinationPath`, only inside the download directory, and refuses to replace an existing file unless `overwrite: true` — confirm the path with the user.
224
224
  - `ic_list_messages` / `ic_get_message` are nominally read-only, but on some district configurations fetching an inbox message or enumerating the list may mark entries as read. Behavior was not confirmable against an empty test inbox.
225
225
  - Endpoint behavior varies by district. If `ic_list_behavior`, `ic_list_food_service`, `ic_list_documents`, `ic_list_assessments`, or `ic_list_fees` returns a `FeatureDisabled` warning, that module is simply turned off for the district — it's not an error. `ic_list_fees` may also return `PartialSuccess` when only one of its two sub-endpoints works.
@@ -33,8 +33,8 @@ Each `enrollments[]` entry carries `enrollmentID`, `calendarID`,
33
33
  ic_get "/campus/resources/portal/roster?personID=$PID" | jq .
34
34
  ```
35
35
 
36
- (Only `personID` is honored server-side — no working date/term filter, even
37
- though the MCP tool's schema accepts `date`/`termFilter` args.)
36
+ (Only `personID` is honored server-side — there is no date/term filter, so
37
+ the MCP tool takes none.)
38
38
 
39
39
  ## Assignments
40
40