feat(canvas-lms): Hanzo AI for Canvas LMS — OAuth + API-proxy app

@hanzo/canvas-lms: an embedded-app panel + OAuth/API-proxy service over the
Canvas REST API, built on @hanzo/ai (api.hanzo.ai /v1) and @hanzo/iam, mirroring
packages/procore.

- Canvas OAuth2 Authorization-Code (server-side secret + non-rotating refresh)
- Pure Canvas REST v1 wrappers (courses/assignments/submissions/discussions/
  pages/modules/enrollments) + RFC 5988 Link-header pagination + HTML->text
- Course-context windowing with honest truncation
- Five AI actions: summarize course, draft feedback, generate questions,
  summarize submissions, draft announcement; gated write-backs (submission
  comment via PUT, announcement via POST)
- 119 vitest tests; tsc --noEmit clean; esbuild build green
- Registered in pnpm-workspace.yaml
This commit is contained in:
Hanzo Dev
2026-07-04 01:53:47 -07:00
parent bb5528f0df
commit a2c014b777
27 changed files with 4049 additions and 0 deletions
+236
View File
@@ -0,0 +1,236 @@
# Hanzo AI for Canvas LMS
AI over your Canvas course — **summarize a course**, **draft assignment feedback**,
**generate quiz/discussion questions**, **summarize student submissions**, and
**draft an announcement**, plus a freeform "ask about the course" box. An
embedded-app **panel** you host at `canvas.hanzo.ai`, backed by a small **OAuth +
API-proxy service** that keeps the Canvas client secret and access tokens
server-side.
Built on the published Hanzo SDK:
- **[`@hanzo/ai`](https://www.npmjs.com/package/@hanzo/ai)** — the headless client.
`createAiClient({ baseUrl, token }).chat.completions.create({ model, messages })`
and `.models.list()`. All model calls go to `https://api.hanzo.ai` on `/v1/...`
(never an `/api/` prefix). We import it; we do not reimplement the transport.
- **[`@hanzo/iam`](https://www.npmjs.com/package/@hanzo/iam)** — Hanzo identity /
the `hk-…` API key the panel uses as its gateway bearer.
Canvas is the dominant higher-ed / K12 LMS: courses, syllabi, modules, assignments,
pages, discussions, and student submissions. This app reads those records through
the Canvas REST API and grounds every AI draft in them. Everything it produces —
feedback, questions, announcements, summaries — is a **draft for an educator to
review**, not an authoritative grade or decision.
> **Package name:** `@hanzo/canvas-lms` (directory `packages/canvas-lms`) — named to
> avoid colliding with the design-tool package `packages/canva`.
---
## Architecture
```
Browser panel (dist/index.html, app.js) Server service (dist/server.js)
───────────────────────────────────── ──────────────────────────────
reads Canvas via ──► /proxy/* ──────────► injects OAuth Bearer + refresh,
same-origin proxy (cookie) forwards to {canvas-host}/api/v1
(never sees a Canvas token) with the user's access token
└── calls api.hanzo.ai /v1 directly with the pasted hk-… Hanzo key
(@hanzo/ai headless client)
```
- The **panel** never holds a Canvas token or the client secret. It reaches Canvas
only through the same-origin `/proxy/*` endpoint (with an HttpOnly session
cookie). It talks to `api.hanzo.ai` directly with the user's pasted Hanzo key.
- The **service** is the only place `CANVAS_CLIENT_SECRET` and the OAuth tokens
exist. It runs the install flow, holds the session, refreshes the token
transparently, and proxies REST calls.
### Source layout (all pure logic is unit-tested)
| File | Responsibility |
| --- | --- |
| `src/config.ts` | Canvas host normalization, REST version, gateway URL, server-secret config (`readServerConfig` fails fast). |
| `src/canvas-oauth.ts` | OAuth2 Authorization-Code shaping: `authorizeUrl`, `tokenExchange`, `refreshExchange`, token parsing, non-rotating-refresh carry + expiry math. Pure. |
| `src/canvas-api.ts` | REST v1 request wrappers (`listCourses`, `getCourse`, `listAssignments`, `listSubmissions`, `postSubmissionComment`, `createAnnouncement`, …) with pagination + `Link`-header parsing, and response parsers. Pure. |
| `src/course.ts` | Course/assignment/submission/page/module JSON → windowed context text, HTML→text, honest truncation. Pure. |
| `src/hanzo.ts` | Thin over `@hanzo/ai`: prompt assembly + the single `ask` path + `listModels`. |
| `src/actions.ts` | The five AI actions (id → prompt) over `ask`. One code path to the model. |
| `src/panel.ts` | Browser proxy-client request shaping + launch-context parsing. Pure. |
| `src/app.ts` | The DOM glue for the panel (the one impure browser entry). |
| `src/server.ts` | Node http service: OAuth install/callback + `/proxy/*`. |
---
## 1. Create a Canvas Developer Key
Canvas OAuth apps authenticate with a **Developer Key** (an OAuth2
client-id/secret). An account admin creates it in **Admin → Developer Keys → +
Developer Key → API Key**:
1. **Key Name**: `Hanzo AI for Canvas` (any label).
2. **Redirect URIs** — exactly the URL your service serves the callback at:
```
https://canvas.hanzo.ai/oauth/callback
```
(For local development, add `http://localhost:8791/oauth/callback` too.)
3. **Scopes** — leave **Enforce Scopes** *off* for the simplest setup (permissions
then follow the authorizing user's Canvas role). If you enable enforcement, add
the granular URL-scopes exported as `RECOMMENDED_SCOPES` in `src/config.ts`
(the read surface plus `PUT …/submissions/:user_id` and
`POST …/discussion_topics` for the two write-backs).
4. **Save**, then **ON** the key's state, and copy the **Client ID** (the numeric
key id) and **Client Secret** (the "Key" / secret value).
5. Note your institution's **Canvas host** (e.g. `school.instructure.com` or your
custom Canvas domain) — the app builds every OAuth + API URL from it.
Because Canvas is self-hosted per institution, the host is a required deployment
value (`CANVAS_HOST`); there is no fixed host list.
---
## 2. OAuth flow
Standard **Authorization Code** grant (server-side secret):
1. `GET /oauth/install` → 302 to
`https://{canvas-host}/login/oauth2/auth?client_id=…&response_type=code&redirect_uri=…&state=…`.
2. The user consents; Canvas redirects back to `GET /oauth/callback?code=…&state=…`.
3. The service verifies `state`, then POSTs to `/login/oauth2/token` with
`grant_type=authorization_code`, the `code`, the `client_id` + `client_secret`
(**in the body, server-side only**), and the same `redirect_uri`.
4. It opens a session, sets an HttpOnly cookie, and the panel is authenticated.
5. Access tokens are short-lived (~1h). The service refreshes with
`grant_type=refresh_token` **before** each proxied call when the token has
expired. Canvas does **not** rotate the refresh token (the refresh response omits
it), so the original refresh token is carried forward.
> In-memory sessions here are for a single instance. For a multi-instance
> deployment behind `hanzoai/ingress`, persist sessions + the OAuth `state` set to
> `hanzoai/kv` (Valkey), and read `CANVAS_CLIENT_SECRET` from KMS (`kms.hanzo.ai`) —
> never from a committed env file.
---
## 3. Canvas REST API
All reads/writes go through `https://{canvas-host}/api/v1/...` with the user's
`Authorization: Bearer {token}`. Canvas's own path is `/api/v1` — this is unrelated
to the Hanzo gateway (which is always `api.hanzo.ai/v1/...`, never `/api/`).
| Resource | Endpoint (relative to `/api/v1`) |
| --- | --- |
| Courses | `GET /courses`, `GET /courses/{id}?include[]=syllabus_body` |
| Assignments | `GET /courses/{id}/assignments`, `GET /courses/{id}/assignments/{id}` |
| Submissions | `GET /courses/{id}/assignments/{aid}/submissions`, `GET …/submissions/{user_id}` |
| **Submission comment** (write) | `PUT /courses/{id}/assignments/{aid}/submissions/{user_id}` — body `{ "comment": { "text_comment": "…" } }` |
| Discussions | `GET /courses/{id}/discussion_topics` |
| **Announcement** (write) | `POST /courses/{id}/discussion_topics` — body `{ "title", "message", "is_announcement": true }` |
| Pages | `GET /courses/{id}/pages`, `GET /courses/{id}/pages/{url_or_id}` |
| Modules | `GET /courses/{id}/modules?include[]=items` |
| Enrollments | `GET /courses/{id}/enrollments` |
> Canvas models a submission comment as an **update to the submission** (a `PUT`
> with `comment[text_comment]`), not a separate comments collection — there is no
> `POST …/submissions/{id}/comments`. This app uses the correct `PUT` shape.
List endpoints paginate with `page` (1-based) + `per_page` (max 100) and return the
page relations in the **RFC 5988 `Link`** response header
(`<…?page=2…>; rel="next"`), parsed by `parseLinkHeader` / `nextPage`.
---
## 4. The summarize-course / draft-feedback flow
1. Connect the app (`/oauth/install`) so the service holds a Canvas token.
2. Open the panel and **Load** a course (the picker lists the courses the connected
user can see). The panel pulls the course's syllabus, modules, assignments,
pages, and discussions through the proxy and assembles a windowed,
truncation-honest context (Canvas HTML is stripped to plain text).
3. **Summarize course** — the model writes a course overview from the syllabus and
module structure, grounded only in the records.
4. **Draft feedback** — pick an assignment and **Load submissions**; the model
drafts specific, constructive feedback for a student submission, grounded in what
the student actually wrote and the assignment's requirements. The result lands in
the Result box.
5. Optional write-backs (gated, behind a confirm):
- **Post as submission comment** posts the Result back via
`PUT …/submissions/{user_id}` with `comment[text_comment]`, targeting the first
submitted student on the loaded assignment.
- **Post as announcement** posts the Result as a course announcement via
`POST …/discussion_topics` (`is_announcement: true`), first line as the subject.
The other actions — **Generate questions** (quiz + discussion prompts from a
page/module), **Summarize submissions** (submitted/missing/late, score spread,
common strengths and problems), and **Draft announcement** — run the same way.
---
## Build & run
```bash
pnpm install
pnpm --filter @hanzo/canvas-lms build # → dist/ (panel + server)
pnpm --filter @hanzo/canvas-lms test # vitest
pnpm --filter @hanzo/canvas-lms typecheck # tsc --noEmit
# run the service
CANVAS_HOST=school.instructure.com \
CANVAS_CLIENT_ID=… \
CANVAS_CLIENT_SECRET=… \
CANVAS_REDIRECT_URI=https://canvas.hanzo.ai/oauth/callback \
node packages/canvas-lms/dist/server.js
```
### Required environment (service)
| Var | Notes |
| --- | --- |
| `CANVAS_HOST` | Institution Canvas host, e.g. `school.instructure.com`. Normalized (scheme/path stripped). |
| `CANVAS_CLIENT_ID` | Developer Key client id (public). |
| `CANVAS_CLIENT_SECRET` | **Server only.** From KMS in production. |
| `CANVAS_REDIRECT_URI` | Must match the key's registered redirect. |
| `PORT` | Listen port (default `8791`). |
`readServerConfig` throws on a missing value — the service refuses to start rather
than pretend it can complete an OAuth exchange or reach an unknown Canvas host.
---
## Deploy over hanzoai/ingress
Host the static panel (`dist/index.html`, `app.js`, `styles.css`) with the
**hanzoai/static** plugin and run `dist/server.js` as a small service, both behind
**hanzoai/ingress** at `canvas.hanzo.ai` (no nginx, no caddy):
- `/` and the static assets → the panel.
- `/oauth/*`, `/proxy/*`, `/healthz` → the service.
Secrets come from **KMS** as `KMSSecret`-synced env; sessions from **Valkey**
(`hanzoai/kv`) for multi-instance. Image published to
`ghcr.io/hanzoai/canvas-lms:<tag>` by CI/CD (platform.hanzo.ai / Tekton) — never
built locally.
---
## Alternative embed path: LTI 1.3
This package ships the **OAuth2 + REST API** app (an external app the instructor
connects, ideal for a standalone panel at `canvas.hanzo.ai`). Canvas also supports
**LTI 1.3 / Advantage** as an in-Canvas launch: Canvas issues a signed OIDC launch
JWT and the tool calls the same REST API (or LTI Advantage services — Names & Roles,
Assignment & Grade Services). LTI is the better fit for a deep in-course placement
(course navigation, assignment menu) and passes the course context (`custom_canvas_course_id`)
in the launch — which `parseLaunchContext` already reads. The AI + context modules
(`course.ts`, `hanzo.ts`, `actions.ts`, `canvas-api.ts`) are transport-agnostic and
would be reused unchanged behind an LTI launch; only the auth front-door differs.
This build ships the OAuth+API app.
---
*Routed through `api.hanzo.ai`. Answers are grounded in your Canvas course records —
a draft for an educator to review, not an authoritative grade, decision, or the
final word to a student.*
+86
View File
@@ -0,0 +1,86 @@
// Build @hanzo/canvas-lms into dist/: bundle the web panel (app.ts) as ESM for the
// browser, copy index.html (with its entry script stamped) + styles.css, and bundle
// the OAuth + API-proxy server for Node. No framework — esbuild + Node stdlib only.
// @hanzo/ai is bundled into both outputs (it is the headless client the panel and
// server both call).
//
// node build.js → production build
// node build.js --watch → rebuild on change
// HANZO_CANVAS_BASE=https://localhost:8443 node build.js → dev base (informational)
//
// Output layout:
// dist/index.html dist/app.js dist/styles.css (panel)
// dist/server.js (service)
//
// The panel is HOSTED over hanzoai/static behind hanzoai/ingress at canvas.hanzo.ai;
// the server runs as a small service (OAuth callback + API proxy). All model calls go
// to api.hanzo.ai regardless of the host base.
import esbuild from 'esbuild';
import { rmSync, mkdirSync, copyFileSync, readFileSync, writeFileSync } from 'node:fs';
import { dirname, join } from 'node:path';
import { fileURLToPath } from 'node:url';
const __dirname = dirname(fileURLToPath(import.meta.url));
const BASE = (process.env.HANZO_CANVAS_BASE || 'https://canvas.hanzo.ai').replace(/\/+$/, '');
const watch = process.argv.includes('--watch');
const src = join(__dirname, 'src');
const dist = join(__dirname, 'dist');
async function build() {
rmSync(dist, { recursive: true, force: true });
mkdirSync(dist, { recursive: true });
// Bundle the panel as ESM for the browser.
const panelCtx = await esbuild.context({
entryPoints: { app: join(src, 'app.ts') },
outdir: dist,
bundle: true,
format: 'esm',
platform: 'browser',
target: ['chrome90', 'edge90', 'firefox90', 'safari15'],
sourcemap: true,
minify: !watch,
logLevel: 'info',
});
await panelCtx.rebuild();
// Copy index.html (stamp __ENTRY__ + base) and styles.css.
const html = readFileSync(join(src, 'index.html'), 'utf8')
.split('__ENTRY__').join('app.js')
.replace('</head>', ` <meta name="hanzo:base" content="${BASE}" />\n</head>`);
writeFileSync(join(dist, 'index.html'), html);
copyFileSync(join(src, 'styles.css'), join(dist, 'styles.css'));
// Bundle the server as a Node ESM binary — our pure stdlib code + @hanzo/ai.
const serverCtx = await esbuild.context({
entryPoints: [join(src, 'server.ts')],
outfile: join(dist, 'server.js'),
bundle: true,
format: 'esm',
platform: 'node',
target: ['node18'],
sourcemap: true,
minify: !watch,
banner: { js: "import { createRequire as __cr } from 'module'; const require = __cr(import.meta.url);" },
logLevel: 'info',
});
await serverCtx.rebuild();
console.log(`Hanzo AI for Canvas built -> dist/ (base ${BASE})`);
console.log(' Panel: dist/index.html · Service: dist/server.js');
if (watch) {
await panelCtx.watch();
await serverCtx.watch();
console.log('watching...');
} else {
await panelCtx.dispose();
await serverCtx.dispose();
}
}
build().catch((e) => {
console.error(e);
process.exit(1);
});
+43
View File
@@ -0,0 +1,43 @@
{
"name": "@hanzo/canvas-lms",
"version": "0.1.0",
"description": "Hanzo AI for Canvas LMS — AI over your course: summarize a course, draft assignment feedback, generate quiz/discussion questions, summarize student submissions, and draft an announcement. An embedded-app panel plus an OAuth + API-proxy service, built on @hanzo/ai and @hanzo/iam over the api.hanzo.ai gateway.",
"private": true,
"type": "module",
"scripts": {
"build": "node build.js",
"watch": "node build.js --watch",
"start": "node dist/server.js",
"test": "vitest run",
"typecheck": "tsc --noEmit"
},
"dependencies": {
"@hanzo/ai": "^0.2.0",
"@hanzo/iam": "^0.13.2"
},
"devDependencies": {
"@types/node": "^20.14.0",
"esbuild": "^0.25.8",
"typescript": "^5.8.3",
"vitest": "^3.2.6"
},
"engines": {
"node": ">=18.0.0"
},
"keywords": [
"hanzo",
"canvas",
"lms",
"education",
"instructure",
"ai",
"oauth"
],
"author": "Hanzo AI",
"license": "MIT",
"repository": {
"type": "git",
"url": "https://github.com/hanzoai/extension.git",
"directory": "packages/canvas-lms"
}
}
+109
View File
@@ -0,0 +1,109 @@
// The AI actions over a Canvas course — summarize the course, draft assignment
// feedback, generate quiz/discussion questions, summarize student submissions, and
// draft an announcement. Each is a prompt template applied to the windowed course
// context via the single `ask` primitive in hanzo.ts. There is exactly ONE code path
// to the model: an action is (id → prompt), and the panel and any server-side caller
// resolve an id here and call `ask`. No action speaks to the gateway directly. (A
// freeform "ask about the course" is `ask` directly, not an action — it has no fixed
// prompt.)
import { ask, type AskOptions, type CourseMeta } from './hanzo.js';
import type { CourseContext } from './course.js';
// The action catalog. `id` is the stable key the panel's chips use; `label` is the
// button text; `prompt` is the instruction handed to the model as the task, over the
// fenced course records. Prompts are specific and output-shaped (bullets, structured
// lists) so results are consistent and parseable.
export const ACTIONS = {
summarizeCourse: {
label: 'Summarize course',
prompt:
'Write a clear overview of this course for a student or a colleague, grounded ' +
'in the syllabus and module structure in these records. Cover: what the course ' +
'is about, how it is organised (the modules and their sequence), the major ' +
'assignments and how grading works if the records say, and any key policies. ' +
'Use a short headline followed by grouped bullets. Base every statement on the ' +
'records; if the syllabus or modules look incomplete, say so plainly.',
},
draftFeedback: {
label: 'Draft feedback',
prompt:
'Draft constructive, specific feedback for the student submission in these ' +
'records, addressed to the student. Ground every point in what the submission ' +
'actually contains and in the assignments stated requirements; do not invent ' +
'content the student did not write or a grade the records do not show. Lead with ' +
'what was done well, then give concrete, actionable suggestions for improvement, ' +
'and close with an encouraging next step. Keep the tone supportive and ' +
'professional. Return only the feedback text, ready to paste as a submission ' +
'comment for the instructor to review.',
},
generateQuestions: {
label: 'Generate questions',
prompt:
'From the course content in these records (a page, module, or assignment), ' +
'generate assessment questions. Produce two groups. First, "Quiz questions": 5 ' +
'to 8 questions that check understanding of the material, a mix of ' +
'multiple-choice (with options and the correct answer marked) and short-answer, ' +
'each tied to a specific idea in the records. Second, "Discussion prompts": 3 ' +
'open-ended prompts that invite analysis or application. Base every question ' +
'strictly on the provided content; do not test material that is not present.',
},
summarizeSubmissions: {
label: 'Summarize submissions',
prompt:
'Summarize the student submissions in these records for the instructor. Cover: ' +
'how many submitted vs are missing or late, the range of scores or grades if the ' +
'records show them, common strengths and common problems across the responses, ' +
'and any submissions that stand out (exemplary or struggling) — referenced by ' +
'user id, not invented names. Structure as a one-line headline followed by ' +
'grouped bullets. Do not fabricate scores or content the records do not contain.',
},
draftAnnouncement: {
label: 'Draft announcement',
prompt:
'Draft a course announcement for the students, grounded in these course records ' +
'(upcoming assignments, due dates, module content). Write a short, clear ' +
'announcement with a specific subject line on the first line, then the body: what ' +
'is happening, what students need to do, and any relevant due date drawn from the ' +
'records. Keep it warm and concise. Do not invent dates or requirements that are ' +
'not in the records. Return the subject line and body, ready for the instructor ' +
'to review and post.',
},
} as const;
// An action id from the catalog.
export type ActionId = keyof typeof ACTIONS;
// isActionId narrows an arbitrary string to a known action id. Boundary guard — the
// panel and the server validate an inbound id here before running it.
export function isActionId(id: string): id is ActionId {
return Object.prototype.hasOwnProperty.call(ACTIONS, id);
}
// actionPrompt resolves an action id to its prompt template. Throws on an unknown id
// (a boundary error, surfaced to the caller) rather than silently running a default.
// Pure.
export function actionPrompt(id: string): string {
if (!isActionId(id)) throw new Error(`Unknown action: ${id}`);
return ACTIONS[id].prompt;
}
// actionList is the ordered catalog for building the UI (chips) — id + label,
// derived from ACTIONS so the panel and the catalog can never drift. Pure.
export function actionList(): Array<{ id: ActionId; label: string }> {
return (Object.keys(ACTIONS) as ActionId[]).map((id) => ({ id, label: ACTIONS[id].label }));
}
// runAction is the single entry point every surface calls: resolve the action's
// prompt and run it over the windowed course context via `ask`. This is the one code
// path from an action id to the model. Async so an unknown id surfaces as a rejected
// promise (not a synchronous throw), giving callers ONE way to handle failure:
// `await`/`.catch`. A gateway error rejects via `ask`.
export async function runAction(
id: string,
ctx: CourseContext,
meta?: CourseMeta,
opts: AskOptions = {},
): Promise<string> {
return ask(actionPrompt(id), ctx, meta, opts);
}
+375
View File
@@ -0,0 +1,375 @@
// The Canvas panel glue: the embedded/linked-app page that opens with a course in
// context and drives the AI actions over the course's live records. All the
// logic-heavy work (action prompts, context windowing, chat shaping, proxy request
// shaping, auth) lives in its own tested modules; this file binds them to the DOM. It
// is the one impure, browser-only entry point.
//
// Data flow: the panel reads Canvas ONLY through the same-origin server proxy
// (createProxyClient), which holds the OAuth token server-side. It pulls the course's
// syllabus / modules / assignments / pages / discussions, assembles a windowed context
// (buildCourseContext), and runs an action or a freeform question against api.hanzo.ai
// with the pasted Hanzo key. The optional write-backs (submission comment, course
// announcement) post back through the same proxy, behind explicit buttons.
import { actionList, isActionId, runAction } from './actions.js';
import { ask as askHanzo, listModels, type CourseMeta } from './hanzo.js';
import {
buildCourseContext,
contextNote,
courseSection,
moduleSection,
assignmentSection,
pageSection,
discussionSection,
submissionSection,
type CourseContext,
type Section,
} from './course.js';
import { DEFAULT_MODEL } from './config.js';
import { getApiKey, setApiKey, hasApiKey, bearer, validateKey } from './auth.js';
import { createProxyClient, parseLaunchContext, type ProxyClient } from './panel.js';
import type { Course, Assignment, Submission } from './canvas-api.js';
const $ = <T extends HTMLElement = HTMLElement>(id: string) => document.getElementById(id) as T;
let controller: AbortController | null = null;
window.addEventListener('DOMContentLoaded', () => {
const launch = parseLaunchContext(window.location.search);
const courseEl = $<HTMLSelectElement>('course');
const assignmentEl = $<HTMLSelectElement>('assignment');
const loadBtn = $<HTMLButtonElement>('load');
const loadSubsBtn = $<HTMLButtonElement>('loadsubs');
const recordsEl = $('records');
const outputEl = $<HTMLTextAreaElement>('output');
const statusEl = $('status');
const modelEl = $<HTMLSelectElement>('model');
const chipRow = $('chips');
const runBtn = $<HTMLButtonElement>('run');
const stopBtn = $<HTMLButtonElement>('stop');
const promptEl = $<HTMLTextAreaElement>('prompt');
const apiKeyEl = $<HTMLInputElement>('apikey');
const saveKeyBtn = $<HTMLButtonElement>('savekey');
const authHint = $('authhint');
const commentBtn = $<HTMLButtonElement>('comment');
const announceBtn = $<HTMLButtonElement>('announce');
apiKeyEl.value = getApiKey();
reflectAuth();
void populateModels();
void populateCourses();
const client: ProxyClient = createProxyClient();
// Loaded state: the course-overview sections, the loaded submissions (a separate
// section appended on demand), and the ids the write-backs target.
let overview: Section[] = [];
let submissions: Submission[] = [];
let ctx: CourseContext | null = null;
let meta: CourseMeta = {};
let currentCourseId = '';
let currentAssignmentId = '';
let assignments: Assignment[] = [];
// Action chips — derived from the catalog so UI and logic never drift.
for (const a of actionList()) {
const b = document.createElement('button');
b.className = 'chip';
b.textContent = a.label;
b.dataset.action = a.id;
b.onclick = () => void run(a.id);
chipRow.appendChild(b);
}
loadBtn.onclick = () => void loadCourse();
loadSubsBtn.onclick = () => void loadSubmissions();
courseEl.onchange = () => {
currentCourseId = courseEl.value;
};
assignmentEl.onchange = () => {
currentAssignmentId = assignmentEl.value;
};
runBtn.onclick = () => {
const prompt = promptEl.value.trim();
if (prompt) void ask(prompt);
};
stopBtn.onclick = () => controller?.abort();
commentBtn.onclick = () => void postComment();
announceBtn.onclick = () => void postAnnouncement();
saveKeyBtn.onclick = async () => {
const key = apiKeyEl.value.trim();
setStatus('Checking key…');
try {
const models = await validateKey(key);
setApiKey(key);
fillModels(models);
reflectAuth();
setStatus('Key saved.', 'ok');
} catch (e: any) {
setStatus(e?.message || 'Key rejected.', 'error');
}
};
// If we launched already scoped to a course, load it straight away.
if (launch.courseId) {
void populateCourses().then(() => {
courseEl.value = launch.courseId;
currentCourseId = launch.courseId;
void loadCourse();
});
}
// populateCourses fills the course picker from the proxy. An auth failure leaves the
// picker empty with a status hint pointing at the connect flow.
async function populateCourses(): Promise<void> {
setStatus('Loading courses…');
try {
const { items } = await client.listCourses({ perPage: 100 });
fillCourses(items);
setStatus(
items.length ? `Loaded ${items.length} courses.` : 'No courses visible.',
items.length ? 'ok' : 'warn',
);
} catch (e: any) {
setStatus(
e?.message || 'Could not load courses — is the app connected? (Connect on canvas.hanzo.ai)',
'error',
);
}
}
// loadCourse pulls the scoped course's records and assembles the overview context
// the actions run over. The course/syllabus, modules, assignments, pages, and
// discussions are fetched in parallel; each failure is tolerated so a course missing
// one area still yields a usable context.
async function loadCourse(): Promise<void> {
const courseId = courseEl.value || currentCourseId;
if (!courseId) {
setStatus('Pick a course first.', 'warn');
return;
}
currentCourseId = courseId;
setStatus('Loading course records…');
const [course, modules, assigns, pages, discussions] = await Promise.all([
client.getCourse(courseId).catch(() => null),
client.listModules(courseId, { perPage: 100 }).then((r) => r.items).catch(() => []),
client.listAssignments(courseId, { perPage: 100 }).then((r) => r.items).catch(() => [] as Assignment[]),
client.listPages(courseId, { perPage: 100 }).then((r) => r.items).catch(() => []),
client.listDiscussions(courseId, { perPage: 100 }).then((r) => r.items).catch(() => []),
]);
assignments = assigns;
submissions = [];
fillAssignments(assigns);
overview = [
...(course ? [courseSection(course)] : []),
moduleSection(modules),
assignmentSection(assigns),
pageSection(pages),
discussionSection(discussions),
];
meta = course ? courseMetaOf(course) : {};
rebuildContext();
recordsEl.textContent =
`${modules.length} modules · ${assigns.length} assignments · ${pages.length} pages · ${discussions.length} discussions`;
announceBtn.disabled = false;
announceBtn.title = 'Post the result as a course announcement';
loadSubsBtn.disabled = assigns.length === 0;
setStatus(contextNote(ctx!));
}
// loadSubmissions pulls the selected assignment's submissions and appends them to the
// context so the feedback / summarize-submissions actions have student work. Enables
// the submission-comment write-back against the first submission.
async function loadSubmissions(): Promise<void> {
const assignmentId = assignmentEl.value || currentAssignmentId;
if (!currentCourseId || !assignmentId) {
setStatus('Load a course and pick an assignment first.', 'warn');
return;
}
currentAssignmentId = assignmentId;
setBusy(true);
setStatus('Loading submissions…');
try {
const { items } = await client.listSubmissions(currentCourseId, assignmentId, { perPage: 100 });
submissions = items;
rebuildContext();
const withWork = submissions.filter((s) => s.workflowState && s.workflowState !== 'unsubmitted');
commentBtn.disabled = withWork.length === 0;
commentBtn.title = withWork.length
? `Post the result as a comment on user ${withWork[0].userId}'s submission`
: 'No submitted work to comment on';
recordsEl.textContent += ` · ${submissions.length} submissions`;
setStatus(contextNote(ctx!));
} catch (e: any) {
setStatus(e?.message || 'Could not load submissions.', 'error');
} finally {
setBusy(false);
}
}
// rebuildContext re-windows the overview + any loaded submissions into one context.
function rebuildContext(): void {
ctx = buildCourseContext([...overview, ...(submissions.length ? [submissionSection(submissions)] : [])]);
}
// run executes one of the named actions over the loaded course context.
async function run(actionId: string): Promise<void> {
if (!isActionId(actionId)) return;
await execute((c, m, opts) => runAction(actionId, c, m, opts));
}
// ask executes a freeform question over the loaded course context.
async function ask(prompt: string): Promise<void> {
await execute((c, m, opts) => askHanzo(prompt, c, m, opts));
}
// execute is the shared runner: require a loaded context, call the model, show the
// result. Both the chips and freeform ask funnel through here (one path).
async function execute(
call: (
c: CourseContext,
m: CourseMeta,
opts: { token: string; model: string; signal: AbortSignal },
) => Promise<string>,
): Promise<void> {
if (!ctx || ctx.totalBlocks === 0) {
setStatus('Load a course first (pick one and press Load).', 'warn');
return;
}
controller?.abort();
controller = new AbortController();
setBusy(true);
setStatus(contextNote(ctx));
outputEl.value = '';
try {
const text = await call(ctx, meta, {
token: bearer(),
model: modelEl.value || DEFAULT_MODEL,
signal: controller.signal,
});
outputEl.value = text;
setStatus('Done.', 'ok');
} catch (e: any) {
if (e?.name === 'AbortError') setStatus('Stopped.');
else setStatus(e?.message || 'Request failed.', 'error');
} finally {
setBusy(false);
}
}
// postComment writes the current output back to Canvas as a comment on the first
// submitted student's submission — an explicit, documented write-back. Guarded: it
// never posts an empty body and always confirms who it targeted.
async function postComment(): Promise<void> {
const body = outputEl.value.trim();
const target = submissions.find((s) => s.workflowState && s.workflowState !== 'unsubmitted');
if (!target) return setStatus('No submitted work to comment on.', 'warn');
if (!body) return setStatus('Nothing to post — run an action or write feedback first.', 'warn');
if (!confirm(`Post this as a comment on user ${target.userId}'s submission?`)) return;
setBusy(true);
setStatus('Posting comment to Canvas…');
try {
await client.postSubmissionComment(currentCourseId, currentAssignmentId, target.userId, body);
setStatus(`Comment posted on user ${target.userId}'s submission.`, 'ok');
} catch (e: any) {
setStatus(e?.message || 'Comment failed.', 'error');
} finally {
setBusy(false);
}
}
// postAnnouncement writes the current output back as a course announcement. Canvas
// needs a title + body; we take the first line of the result as the title and the
// rest as the body, so a "subject line then body" draft posts cleanly.
async function postAnnouncement(): Promise<void> {
const text = outputEl.value.trim();
if (!currentCourseId) return setStatus('Load a course first.', 'warn');
if (!text) return setStatus('Nothing to post — draft an announcement first.', 'warn');
const nl = text.indexOf('\n');
const title = (nl === -1 ? text : text.slice(0, nl)).trim().slice(0, 200);
const message = (nl === -1 ? text : text.slice(nl + 1)).trim() || text;
if (!confirm(`Post a course announcement titled “${title}”?`)) return;
setBusy(true);
setStatus('Posting announcement to Canvas…');
try {
await client.createAnnouncement(currentCourseId, title, message);
setStatus('Announcement posted.', 'ok');
} catch (e: any) {
setStatus(e?.message || 'Announcement failed.', 'error');
} finally {
setBusy(false);
}
}
// ---- small DOM helpers ----------------------------------------------------
let courses: Course[] = [];
function courseMetaOf(course: Course): CourseMeta {
return { name: course.name || undefined, courseCode: course.courseCode || undefined, term: course.termName || undefined };
}
function fillCourses(items: Course[]): void {
courses = items;
courseEl.innerHTML = '';
for (const c of items) {
const opt = document.createElement('option');
opt.value = String(c.id);
opt.textContent = c.name || c.courseCode || `Course ${c.id}`;
courseEl.appendChild(opt);
}
if (items.length && !currentCourseId) currentCourseId = String(items[0].id);
}
function fillAssignments(items: Assignment[]): void {
assignmentEl.innerHTML = '';
for (const a of items) {
const opt = document.createElement('option');
opt.value = String(a.id);
opt.textContent = a.name || `Assignment ${a.id}`;
assignmentEl.appendChild(opt);
}
currentAssignmentId = items.length ? String(items[0].id) : '';
}
async function populateModels(): Promise<void> {
try {
fillModels(await listModels({ token: bearer() }));
} catch {
fillModels([DEFAULT_MODEL]);
}
}
function fillModels(ids: string[]): void {
const list = ids.length ? ids : [DEFAULT_MODEL];
modelEl.innerHTML = '';
for (const id of list) {
const opt = document.createElement('option');
opt.value = id;
opt.textContent = id;
modelEl.appendChild(opt);
}
if (list.includes(DEFAULT_MODEL)) modelEl.value = DEFAULT_MODEL;
}
function reflectAuth(): void {
authHint.textContent = hasApiKey()
? 'Using your saved Hanzo key.'
: 'No key saved — using public models. Paste an hk-… key for your org models.';
}
function setBusy(b: boolean): void {
runBtn.disabled = b;
stopBtn.disabled = !b;
loadBtn.disabled = b;
loadSubsBtn.disabled = b || assignments.length === 0;
for (const c of Array.from(chipRow.querySelectorAll('button'))) (c as HTMLButtonElement).disabled = b;
announceBtn.disabled = b || !currentCourseId;
commentBtn.disabled = b || submissions.length === 0;
}
function setStatus(msg: string, kind: '' | 'ok' | 'warn' | 'error' = ''): void {
statusEl.textContent = msg;
statusEl.className = `status${kind ? ' ' + kind : ''}`;
}
});
+55
View File
@@ -0,0 +1,55 @@
// Auth for the web panel: the zero-setup pasted-key path for the Hanzo gateway. The
// Canvas panel is a static web page (iframe), so the Hanzo credential lives in
// localStorage and is validated by a real /v1/models call — a key that can't list
// models is rejected before it's saved, so the user learns at paste time, not at
// first action. Mirrors @hanzo/procore exactly (one way to hold a key).
//
// The Canvas access token (for reading courses/assignments/submissions) is a SEPARATE
// credential minted server-side by the OAuth flow and held by server.ts; the panel
// reaches Canvas only through the server proxy (with its session cookie), so it never
// holds the Canvas token or secret. This module is only the Hanzo-gateway bearer.
import { APIKEY_STORAGE_KEY, pickBearer } from './config.js';
import { listModels } from './hanzo.js';
export function getApiKey(): string {
try {
return localStorage.getItem(APIKEY_STORAGE_KEY) || '';
} catch {
return '';
}
}
export function setApiKey(key: string): void {
try {
const k = key.trim();
if (k) localStorage.setItem(APIKEY_STORAGE_KEY, k);
else localStorage.removeItem(APIKEY_STORAGE_KEY);
} catch {
/* private-mode / storage disabled — the in-memory key still works this session */
}
}
export function clearApiKey(): void {
setApiKey('');
}
export function hasApiKey(): boolean {
return !!getApiKey();
}
// bearer is the credential the chat call sends: the pasted key (or empty for
// anonymous public models). When Hanzo OAuth lands it slots in as the second argument
// to pickBearer with no change to callers.
export function bearer(): string {
return pickBearer(getApiKey(), '');
}
// validateKey confirms a pasted key actually works by listing models with it. Returns
// the models on success so the caller populates the picker in one round-trip; throws
// with the gateway's message on failure.
export async function validateKey(key: string): Promise<string[]> {
const k = key.trim();
if (!k) throw new Error('Enter a Hanzo API key (hk-…).');
return listModels({ token: k });
}
+582
View File
@@ -0,0 +1,582 @@
// Canvas REST API v1 — pure request shaping + response parsing. Every function
// returns a PreparedRequest (url + headers [+ body]) or parses a response body;
// none opens a socket, so the whole API surface is unit-testable without a
// network. server.ts is the thin glue that fetches these shapes with the OAuth
// Bearer access token.
//
// The REST root is `https://{host}/api/v1` (see config.apiBaseUrl). Canvas scopes
// reads/writes by the authorizing user's Bearer token; course-scoped resources
// take the course id in the path (…/courses/{id}/…). Docs:
// canvas.instructure.com/doc/api/courses.html, assignments.html, submissions.html,
// discussion_topics.html, pages.html, modules.html, enrollments.html.
// A prepared GET: url + headers a single fetch needs (Bearer only).
export interface PreparedGet {
url: string;
headers: Record<string, string>;
}
// A prepared write (POST/PUT): adds the JSON body and Content-Type. Canvas accepts
// a JSON body (Content-Type: application/json) for these endpoints; we use it so
// nested params stay structured rather than form-bracket-encoded.
export interface PreparedWrite extends PreparedGet {
method: 'POST' | 'PUT';
body: string;
}
// headers builds the auth header set common to every request.
function headers(accessToken: string): Record<string, string> {
return { Authorization: `Bearer ${accessToken}` };
}
// jsonHeaders adds Content-Type for a write body on top of the auth header.
function jsonHeaders(accessToken: string): Record<string, string> {
return { ...headers(accessToken), 'Content-Type': 'application/json' };
}
// The scope every request carries: which REST root and which bearer. Grouping them
// keeps every wrapper's signature small.
export interface Scope {
apiBase: string;
accessToken: string;
}
// Pagination controls. Canvas paginates with page (1-based) + per_page and returns
// the page relations (next/prev/first/last) in the RFC 5988 `Link` response header
// (parsed by the caller with parseLinkHeader). We attach these as query params on
// list endpoints.
export interface Page {
page?: number;
perPage?: number;
}
// DEFAULT_PER_PAGE is Canvas's documented maximum page size; 100 minimises
// round-trips (Canvas's own default is only 10).
export const DEFAULT_PER_PAGE = 100;
// pageParams renders pagination into query pairs, clamping per_page to the
// documented maximum. Only emits params that are set, so an unpaginated call stays
// clean. Pure — unit-tested.
export function pageParams(page: Page | undefined): Record<string, string> {
const out: Record<string, string> = {};
if (!page) return out;
if (typeof page.page === 'number' && page.page > 0) out.page = String(Math.floor(page.page));
if (typeof page.perPage === 'number' && page.perPage > 0) {
out.per_page = String(Math.min(Math.floor(page.perPage), DEFAULT_PER_PAGE));
}
return out;
}
// A repeated query param, e.g. Canvas's `include[]=syllabus_body`. buildUrl expands
// an array value into one pair per element with a trailing `[]` on the key.
type Query = Record<string, string | string[] | undefined>;
// buildUrl joins the REST root + path and appends a query string, dropping
// undefined/empty values and expanding arrays into Canvas's `key[]=v` repetition.
// One place builds every URL so scoping/pagination params are applied
// consistently. Pure.
function buildUrl(apiBase: string, path: string, query: Query = {}): string {
const base = `${apiBase.replace(/\/+$/, '')}${path}`;
const q = new URLSearchParams();
for (const [k, v] of Object.entries(query)) {
if (Array.isArray(v)) {
for (const item of v) if (item !== undefined && item !== '') q.append(`${k}[]`, item);
} else if (v !== undefined && v !== '') {
q.set(k, v);
}
}
const qs = q.toString();
return qs ? `${base}?${qs}` : base;
}
// enc encodes a single path segment (ids are integers and page urls are slugs, but
// we encode defensively so a stray value can never break — or traverse — the path).
function enc(segment: number | string): string {
return encodeURIComponent(String(segment));
}
// ---- Courses --------------------------------------------------------------
// listCourses — the courses the authorizing user can see. Bearer scope only (no
// course in the path). The panel's picker uses this to choose which course to run
// against.
export function listCourses(scope: Scope, page?: Page): PreparedGet {
return {
url: buildUrl(scope.apiBase, '/courses', pageParams(page)),
headers: headers(scope.accessToken),
};
}
// getCourse — one course. `includes` maps to Canvas `include[]` associations; we
// default to `syllabus_body` (an HTML syllabus) since the summarize-course action
// grounds on it. Pass `[]` to fetch the bare course.
export function getCourse(
scope: Scope,
courseId: number | string,
includes: readonly string[] = ['syllabus_body'],
): PreparedGet {
return {
url: buildUrl(scope.apiBase, `/courses/${enc(courseId)}`, {
include: includes.length ? [...includes] : undefined,
}),
headers: headers(scope.accessToken),
};
}
// ---- Assignments ----------------------------------------------------------
// listAssignments — the assignments in a course. Course-scoped path.
export function listAssignments(scope: Scope, courseId: number | string, page?: Page): PreparedGet {
return {
url: buildUrl(scope.apiBase, `/courses/${enc(courseId)}/assignments`, pageParams(page)),
headers: headers(scope.accessToken),
};
}
// getAssignment — one assignment in full (description, due date, points, submission
// types). This is what the feedback/question actions read.
export function getAssignment(
scope: Scope,
courseId: number | string,
assignmentId: number | string,
): PreparedGet {
return {
url: buildUrl(scope.apiBase, `/courses/${enc(courseId)}/assignments/${enc(assignmentId)}`),
headers: headers(scope.accessToken),
};
}
// ---- Submissions ----------------------------------------------------------
// listSubmissions — the submissions for an assignment. Course + assignment scoped
// path; `include[]=submission_comments` so existing comments come along for the
// summarize/feedback context.
export function listSubmissions(
scope: Scope,
courseId: number | string,
assignmentId: number | string,
page?: Page,
): PreparedGet {
return {
url: buildUrl(
scope.apiBase,
`/courses/${enc(courseId)}/assignments/${enc(assignmentId)}/submissions`,
{ include: ['submission_comments'], ...pageParams(page) },
),
headers: headers(scope.accessToken),
};
}
// getSubmission — one student's submission (by user id) with its comment thread.
export function getSubmission(
scope: Scope,
courseId: number | string,
assignmentId: number | string,
userId: number | string,
): PreparedGet {
return {
url: buildUrl(
scope.apiBase,
`/courses/${enc(courseId)}/assignments/${enc(assignmentId)}/submissions/${enc(userId)}`,
{ include: ['submission_comments'] },
),
headers: headers(scope.accessToken),
};
}
// postSubmissionComment — add a text comment to a student's submission. Canvas
// models a submission comment as an UPDATE to the submission (PUT
// …/submissions/{user_id} with a `comment[text_comment]`), not a separate comments
// collection — this is the ONE feedback write path, behind an explicit action.
// Returns a PreparedWrite (PUT + JSON body).
export function postSubmissionComment(
scope: Scope,
courseId: number | string,
assignmentId: number | string,
userId: number | string,
text: string,
): PreparedWrite {
return {
method: 'PUT',
url: buildUrl(
scope.apiBase,
`/courses/${enc(courseId)}/assignments/${enc(assignmentId)}/submissions/${enc(userId)}`,
),
headers: jsonHeaders(scope.accessToken),
body: JSON.stringify({ comment: { text_comment: text } }),
};
}
// ---- Discussions ----------------------------------------------------------
// listDiscussions — the discussion topics in a course (announcements included when
// they are discussion-backed). Course-scoped path.
export function listDiscussions(scope: Scope, courseId: number | string, page?: Page): PreparedGet {
return {
url: buildUrl(scope.apiBase, `/courses/${enc(courseId)}/discussion_topics`, pageParams(page)),
headers: headers(scope.accessToken),
};
}
// createAnnouncement — post a course announcement. In Canvas an announcement is a
// discussion topic with `is_announcement: true` (POST …/discussion_topics) — the
// second gated write path. Returns a PreparedWrite (POST + JSON body).
export function createAnnouncement(
scope: Scope,
courseId: number | string,
title: string,
message: string,
): PreparedWrite {
return {
method: 'POST',
url: buildUrl(scope.apiBase, `/courses/${enc(courseId)}/discussion_topics`),
headers: jsonHeaders(scope.accessToken),
body: JSON.stringify({ title, message, is_announcement: true }),
};
}
// ---- Pages ----------------------------------------------------------------
// listPages — the wiki pages in a course. Course-scoped path.
export function listPages(scope: Scope, courseId: number | string, page?: Page): PreparedGet {
return {
url: buildUrl(scope.apiBase, `/courses/${enc(courseId)}/pages`, pageParams(page)),
headers: headers(scope.accessToken),
};
}
// getPage — one wiki page in full (its HTML body). Canvas addresses a page by its
// url slug or page id.
export function getPage(
scope: Scope,
courseId: number | string,
urlOrId: number | string,
): PreparedGet {
return {
url: buildUrl(scope.apiBase, `/courses/${enc(courseId)}/pages/${enc(urlOrId)}`),
headers: headers(scope.accessToken),
};
}
// ---- Modules --------------------------------------------------------------
// listModules — the modules in a course, with their items inlined
// (`include[]=items`) so the course-overview context sees the module structure.
export function listModules(scope: Scope, courseId: number | string, page?: Page): PreparedGet {
return {
url: buildUrl(scope.apiBase, `/courses/${enc(courseId)}/modules`, {
include: ['items'],
...pageParams(page),
}),
headers: headers(scope.accessToken),
};
}
// ---- Enrollments ----------------------------------------------------------
// listEnrollments — the enrollments in a course (who is a student / teacher / TA).
export function listEnrollments(scope: Scope, courseId: number | string, page?: Page): PreparedGet {
return {
url: buildUrl(scope.apiBase, `/courses/${enc(courseId)}/enrollments`, pageParams(page)),
headers: headers(scope.accessToken),
};
}
// ---- Pagination header (RFC 5988 Link) ------------------------------------
// The page relations Canvas returns in the `Link` header — each an absolute URL.
export interface CanvasLinks {
current?: string;
next?: string;
prev?: string;
first?: string;
last?: string;
}
// parseLinkHeader reads Canvas's RFC 5988 `Link` header into the page relations.
// Canvas returns entries like `<https://host/api/v1/courses?page=2&per_page=100>;
// rel="next"`. Accepts a Headers instance or a plain header map so it works against
// fetch Responses and test fixtures alike. Returns {} for a missing header. Pure.
export function parseLinkHeader(
h: Headers | Record<string, string | string[] | undefined>,
): CanvasLinks {
const raw =
typeof (h as Headers)?.get === 'function'
? (h as Headers).get('Link') ?? (h as Headers).get('link')
: (h as Record<string, string | string[] | undefined>).Link ??
(h as Record<string, string | string[] | undefined>).link;
const val = Array.isArray(raw) ? raw.join(', ') : raw;
const links: CanvasLinks = {};
if (!val) return links;
for (const part of String(val).split(',')) {
const m = part.match(/<([^>]+)>\s*;\s*rel="?([^"\s;]+)"?/i);
if (!m) continue;
const rel = m[2].toLowerCase();
if (rel === 'current' || rel === 'next' || rel === 'prev' || rel === 'first' || rel === 'last') {
links[rel] = m[1];
}
}
return links;
}
// pageOfUrl extracts the 1-based `page` query param from a Canvas pagination URL
// (the relations in parseLinkHeader carry absolute URLs). Returns undefined when
// absent/unparseable. Pure — lets a same-origin proxy client re-request the next
// page by number without following Canvas's absolute URL directly.
export function pageOfUrl(url: string | undefined): number | undefined {
if (!url) return undefined;
const m = url.match(/[?&]page=([^&]+)/);
if (!m) return undefined;
const n = Number.parseInt(decodeURIComponent(m[1]), 10);
return Number.isFinite(n) && n > 0 ? n : undefined;
}
// nextPage is the page number to request for the next page, or undefined when
// there is no `next` relation (the last page). Pure — the ONE way the panel decides
// whether to keep paginating.
export function nextPage(links: CanvasLinks): number | undefined {
return pageOfUrl(links.next);
}
// ---- Response parsing -----------------------------------------------------
//
// Canvas list endpoints return a bare JSON array of records; detail endpoints
// return one object. We normalize the snake_case wire fields we surface into small
// typed shapes at this boundary so nothing downstream touches the wire. Text bodies
// (syllabus, page body, assignment description, discussion message) are Canvas HTML;
// we keep them raw here and strip to plain text in course.ts (htmlToText) at render.
function arrayOf(data: any, key?: string): any[] {
if (Array.isArray(data)) return data;
if (key && Array.isArray(data?.[key])) return data[key];
return [];
}
// One course as it appears in listCourses / getCourse.
export interface Course {
id: number;
name: string;
courseCode: string;
workflowState: string;
syllabusBody: string;
termName: string;
}
export function parseCourse(data: any): Course {
return {
id: Number(data?.id ?? 0),
name: String(data?.name ?? ''),
courseCode: String(data?.course_code ?? ''),
workflowState: String(data?.workflow_state ?? ''),
syllabusBody: String(data?.syllabus_body ?? ''),
termName: String(data?.term?.name ?? data?.enrollment_term_id ?? ''),
};
}
export function parseCourses(data: any): Course[] {
return arrayOf(data, 'courses')
.map(parseCourse)
.filter((c) => c.id > 0);
}
// One assignment.
export interface Assignment {
id: number;
name: string;
description: string;
dueAt: string;
pointsPossible: number;
submissionTypes: string[];
}
export function parseAssignment(data: any): Assignment {
return {
id: Number(data?.id ?? 0),
name: String(data?.name ?? ''),
description: String(data?.description ?? ''),
dueAt: String(data?.due_at ?? ''),
pointsPossible: Number(data?.points_possible ?? 0),
submissionTypes: Array.isArray(data?.submission_types)
? data.submission_types.map((s: any) => String(s))
: [],
};
}
export function parseAssignments(data: any): Assignment[] {
return arrayOf(data, 'assignments')
.map(parseAssignment)
.filter((a) => a.id > 0);
}
// One comment within a submission's thread.
export interface SubmissionComment {
id: number;
authorName: string;
comment: string;
createdAt: string;
}
function parseSubmissionComment(c: any): SubmissionComment {
return {
id: Number(c?.id ?? 0),
authorName: String(c?.author_name ?? c?.author?.display_name ?? ''),
comment: String(c?.comment ?? ''),
createdAt: String(c?.created_at ?? ''),
};
}
// One student submission.
export interface Submission {
id: number;
userId: number;
assignmentId: number;
body: string;
submittedAt: string;
workflowState: string;
score: number | null;
grade: string;
late: boolean;
missing: boolean;
comments: SubmissionComment[];
}
export function parseSubmission(data: any): Submission {
return {
id: Number(data?.id ?? 0),
userId: Number(data?.user_id ?? 0),
assignmentId: Number(data?.assignment_id ?? 0),
body: String(data?.body ?? ''),
submittedAt: String(data?.submitted_at ?? ''),
workflowState: String(data?.workflow_state ?? ''),
score: typeof data?.score === 'number' ? data.score : null,
grade: data?.grade === null || data?.grade === undefined ? '' : String(data.grade),
late: data?.late === true,
missing: data?.missing === true,
comments: Array.isArray(data?.submission_comments)
? data.submission_comments.map(parseSubmissionComment)
: [],
};
}
export function parseSubmissions(data: any): Submission[] {
return arrayOf(data, 'submissions')
.map(parseSubmission)
.filter((s) => s.id > 0 || s.userId > 0);
}
// One discussion topic.
export interface Discussion {
id: number;
title: string;
message: string;
postedAt: string;
isAnnouncement: boolean;
}
export function parseDiscussion(data: any): Discussion {
return {
id: Number(data?.id ?? 0),
title: String(data?.title ?? ''),
message: String(data?.message ?? ''),
postedAt: String(data?.posted_at ?? ''),
isAnnouncement: data?.is_announcement === true,
};
}
export function parseDiscussions(data: any): Discussion[] {
return arrayOf(data, 'discussion_topics')
.map(parseDiscussion)
.filter((d) => d.id > 0);
}
// One wiki page. The list omits the body; the detail (getPage) carries it.
export interface Page_ {
pageId: number;
url: string;
title: string;
body: string;
updatedAt: string;
}
export function parsePage(data: any): Page_ {
return {
pageId: Number(data?.page_id ?? 0),
url: String(data?.url ?? ''),
title: String(data?.title ?? ''),
body: String(data?.body ?? ''),
updatedAt: String(data?.updated_at ?? ''),
};
}
export function parsePages(data: any): Page_[] {
return arrayOf(data, 'pages')
.map(parsePage)
.filter((p) => p.pageId > 0 || p.url.length > 0);
}
// One module item (a page, assignment, quiz, file, external link, …).
export interface ModuleItem {
id: number;
title: string;
type: string;
position: number;
}
// One course module, with its items when Canvas inlined them.
export interface Module {
id: number;
name: string;
position: number;
items: ModuleItem[];
}
function parseModuleItem(i: any): ModuleItem {
return {
id: Number(i?.id ?? 0),
title: String(i?.title ?? ''),
type: String(i?.type ?? ''),
position: Number(i?.position ?? 0),
};
}
export function parseModule(data: any): Module {
return {
id: Number(data?.id ?? 0),
name: String(data?.name ?? ''),
position: Number(data?.position ?? 0),
items: Array.isArray(data?.items) ? data.items.map(parseModuleItem) : [],
};
}
export function parseModules(data: any): Module[] {
return arrayOf(data, 'modules')
.map(parseModule)
.filter((m) => m.id > 0);
}
// One enrollment (a person's role in the course).
export interface Enrollment {
id: number;
userId: number;
userName: string;
type: string;
role: string;
state: string;
}
export function parseEnrollment(data: any): Enrollment {
return {
id: Number(data?.id ?? 0),
userId: Number(data?.user_id ?? 0),
userName: String(data?.user?.name ?? data?.user?.short_name ?? ''),
type: String(data?.type ?? ''),
role: String(data?.role ?? ''),
state: String(data?.enrollment_state ?? ''),
};
}
export function parseEnrollments(data: any): Enrollment[] {
return arrayOf(data, 'enrollments')
.map(parseEnrollment)
.filter((e) => e.id > 0);
}
+167
View File
@@ -0,0 +1,167 @@
// Canvas OAuth 2.0 (Authorization Code Grant) — pure request shaping. The client
// secret is held by the server (server.ts) and never reaches the browser; these
// functions build the exact URL/body of each OAuth call so the wire shape is
// unit-testable without a network round-trip. The token exchange and refresh are
// each one fetch in the server.
//
// Canvas uses form-encoded bodies with client_id + client_secret IN THE BODY (not
// HTTP Basic) and requires the redirect_uri on the code exchange — the standard
// OAuth2 web-server shape, documented at
// canvas.instructure.com/doc/api/file.oauth_endpoints.html. The login host is the
// institution's own Canvas host (see config.authBase): authorize at
// /login/oauth2/auth, token at /login/oauth2/token.
import { authBase } from './config.js';
// authorizeUrl is where the install flow sends the user's browser to grant the
// app. `state` is the CSRF token the server generates and re-checks on callback.
// Canvas's Authorization Code grant takes response_type=code + client_id +
// redirect_uri + state; scope is optional (only enforced when the Developer Key
// enables scope enforcement), so it is only appended when non-empty.
export function authorizeUrl(args: {
host: string;
clientId: string;
redirectUri: string;
scopes?: readonly string[];
state: string;
}): string {
const params: Record<string, string> = {
client_id: args.clientId,
response_type: 'code',
redirect_uri: args.redirectUri,
state: args.state,
};
if (args.scopes && args.scopes.length > 0) params.scope = args.scopes.join(' ');
const q = new URLSearchParams(params);
return `${authBase(args.host)}/login/oauth2/auth?${q.toString()}`;
}
// A prepared HTTP request: the pieces a single fetch needs. Pure output so a test
// asserts the form body without opening a socket. Canvas's token endpoint takes
// application/x-www-form-urlencoded.
export interface PreparedRequest {
url: string;
headers: Record<string, string>;
body: string;
}
// tokenUrl is the OAuth token endpoint for a host.
export function tokenUrl(host: string): string {
return `${authBase(host)}/login/oauth2/token`;
}
// tokenExchange builds the code→token request against the host's
// /login/oauth2/token. grant_type=authorization_code with the code, the key's
// credentials, and the SAME redirect_uri that was used on /login/oauth2/auth
// (Canvas requires it to match). The secret rides only in this server-side body.
export function tokenExchange(args: {
host: string;
clientId: string;
clientSecret: string;
code: string;
redirectUri: string;
}): PreparedRequest {
return {
url: tokenUrl(args.host),
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
grant_type: 'authorization_code',
client_id: args.clientId,
client_secret: args.clientSecret,
redirect_uri: args.redirectUri,
code: args.code,
}).toString(),
};
}
// refreshExchange builds the refresh-token→token request. Canvas access tokens are
// short-lived (~1h); a refresh returns a fresh access_token but — unlike Procore —
// Canvas does NOT rotate the refresh token (it returns none), so the server keeps
// the original refresh token. No redirect_uri on refresh.
export function refreshExchange(args: {
host: string;
clientId: string;
clientSecret: string;
refreshToken: string;
}): PreparedRequest {
return {
url: tokenUrl(args.host),
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
body: new URLSearchParams({
grant_type: 'refresh_token',
client_id: args.clientId,
client_secret: args.clientSecret,
refresh_token: args.refreshToken,
}).toString(),
};
}
// The Canvas person sub-object returned alongside a token (the authorizing user).
export interface CanvasUser {
id: number;
name: string;
}
// The token response we care about. Canvas returns access_token (+ token_type,
// user, expires_in, and refresh_token ONLY on the initial code exchange).
// parseTokenResponse validates the one field we must have and surfaces Canvas's
// own error otherwise.
export interface CanvasTokenSet {
access_token: string;
refresh_token?: string;
expires_in?: number;
token_type?: string;
user?: CanvasUser;
}
export function parseTokenResponse(data: any): CanvasTokenSet {
if (!data || typeof data !== 'object') throw new Error('empty token response');
if (data.error) {
const reason = data.error_description || data.message || data.error;
throw new Error(`Canvas OAuth error: ${reason}`);
}
if (typeof data.access_token !== 'string' || data.access_token.length === 0) {
throw new Error('Canvas OAuth response missing access_token');
}
const user =
data.user && typeof data.user === 'object'
? { id: Number(data.user.id ?? 0), name: String(data.user.name ?? '') }
: undefined;
return {
access_token: data.access_token,
refresh_token: typeof data.refresh_token === 'string' ? data.refresh_token : undefined,
expires_in: typeof data.expires_in === 'number' ? data.expires_in : undefined,
token_type: typeof data.token_type === 'string' ? data.token_type : undefined,
user,
};
}
// carryRefreshToken applies Canvas's non-rotating refresh semantics: a refresh
// response omits the refresh token, so the new token set inherits the previous
// refresh token. Pure — the server calls this after every refresh so the session
// never loses the ability to refresh again.
export function carryRefreshToken(next: CanvasTokenSet, previous: CanvasTokenSet): CanvasTokenSet {
return next.refresh_token ? next : { ...next, refresh_token: previous.refresh_token };
}
// tokenExpiresAt computes the absolute epoch-seconds expiry from a token set and
// the wall-clock second it was minted, applying a safety skew so a request is never
// sent with a token about to expire mid-flight. Canvas does not return a mint
// timestamp, so the caller supplies `mintedAt` (recorded when the token was
// stored). Pure.
export function tokenExpiresAt(token: CanvasTokenSet, mintedAt: number, skewSeconds = 60): number {
const ttl = typeof token.expires_in === 'number' ? token.expires_in : 0;
return mintedAt + ttl - skewSeconds;
}
// isExpired reports whether a token set is at/past its (skew-adjusted) expiry as of
// `now`, given when it was minted. The server checks this before each API call and
// refreshes when true. Pure.
export function isExpired(
token: CanvasTokenSet,
mintedAt: number,
now: number,
skewSeconds = 60,
): boolean {
return now >= tokenExpiresAt(token, mintedAt, skewSeconds);
}
+166
View File
@@ -0,0 +1,166 @@
// Canvas LMS config — the institution's Canvas host, the Canvas REST API version
// segment, the api.hanzo.ai model gateway, and the server-side secret set (Canvas
// OAuth). Endpoints and the bearer choice mirror @hanzo/procore and @hanzo/docusign
// so the productivity suite stays DRY; the education-specific pieces
// (course-context windowing, the AI actions) live in course.ts / hanzo.ts /
// actions.ts, not here.
// ---- Hanzo model gateway --------------------------------------------------
// Where the Hanzo model gateway lives. `@hanzo/ai` defaults here too. /v1 only,
// never an /api/ prefix (api.hanzo.ai IS the api host).
export const HANZO_API_BASE_URL = 'https://api.hanzo.ai';
// Default model. A Zen model (qwen3+). Overridable per-request via the picker;
// the gateway routes it.
export const DEFAULT_MODEL = 'zen5';
// Public IAM origin that mints Hanzo user tokens, and the OAuth client id an
// inbound Hanzo token is audienced to (owner-scoping validation via @hanzo/iam).
export const DEFAULT_IAM_SERVER_URL = 'https://hanzo.id';
export const DEFAULT_IAM_CLIENT_ID = 'hanzo-canvas';
// localStorage key for the pasted Hanzo API key (`hk-…`) in the web panel. The
// panel is a static web page (iframe), not a host with roamingSettings, so the
// zero-setup credential lives in localStorage — same as @hanzo/procore.
export const APIKEY_STORAGE_KEY = 'hanzo.canvas.apiKey';
// Course text budget. A busy course has many assignments, pages, discussions, and
// submissions; the whole corpus won't fit a model window and shouldn't be sent.
// This caps the characters of course text we attach to any one request — chosen so
// it fits comfortably inside a modern context window alongside the reply, and is
// honest rather than optimal (we truncate visibly, never drop silently).
export const COURSE_CHAR_BUDGET = 60_000;
// pickBearer chooses the credential to send to the Hanzo gateway: a pasted API key
// wins over an OAuth token (an explicit key is a deliberate override), else the
// token, else empty (anonymous — the gateway still serves public models). Pure —
// unit-tested.
export function pickBearer(apiKey: string, oauthToken: string): string {
return (apiKey && apiKey.trim()) || (oauthToken && oauthToken.trim()) || '';
}
// chatCompletionsURL / modelsURL — the model gateway endpoints.
export function chatCompletionsURL(): string {
return `${HANZO_API_BASE_URL}/v1/chat/completions`;
}
export function modelsURL(): string {
return `${HANZO_API_BASE_URL}/v1/models`;
}
// ---- Canvas host + API ----------------------------------------------------
//
// Canvas LMS is self-hosted per institution: each school runs its own Canvas at
// its own host (e.g. `school.instructure.com` or a custom domain). There is no
// fixed host list — the host is a deployment value, so every Canvas URL (OAuth
// login + REST API) is built from the configured host. We never hard-code an
// institution host inline.
//
// Docs: canvas.instructure.com/doc/api/file.oauth.html and
// canvas.instructure.com/doc/api/index.html (REST API).
// normalizeHost strips a scheme, a trailing slash, and any path/query so a raw
// value like `https://school.instructure.com/` or `school.instructure.com`
// resolves to the bare host `school.instructure.com`. Pure — the ONE place a host
// is cleaned, so every URL builder gets a canonical host. Boundary guard.
export function normalizeHost(raw: string): string {
return raw
.trim()
.replace(/^https?:\/\//i, '')
.replace(/\/.*$/, '')
.replace(/\/+$/, '');
}
// authBase turns a host into the OAuth login origin — `/login/oauth2/auth` and
// `/login/oauth2/token` live here. Pure.
export function authBase(host: string): string {
return `https://${normalizeHost(host)}`;
}
// The REST API version segment. v1 is Canvas's current (and only) REST version;
// we never bump to a speculative v2 — one version, forward only. This is Canvas's
// OWN `/api/v1` path, not a Hanzo gateway path (the /api/ ban is only for
// api.hanzo.ai, which uses /v1).
export const REST_API_VERSION = 'v1';
// apiBaseUrl turns a host into the REST root: `https://{host}/api/v1`. Every Canvas
// API call is built on top of this. Pure — the request wrappers in canvas-api.ts
// take this string.
export function apiBaseUrl(host: string): string {
return `${authBase(host)}/api/${REST_API_VERSION}`;
}
// The OAuth scopes the app requests. Canvas only enforces scopes when the
// Developer Key has "Enforce Scopes" enabled; a standard key ignores the `scope`
// parameter (permissions follow the authorizing user's Canvas role). We default to
// none so the app installs against either key type, and document the granular
// URL-scopes to add (see RECOMMENDED_SCOPES) when enforcement is on. The authorize
// URL only appends `scope` when this is non-empty.
export const OAUTH_SCOPES = [] as const;
// RECOMMENDED_SCOPES documents the exact Canvas URL-scopes to request when the
// Developer Key enforces scopes — the read surface this app uses plus the two
// gated writes. Not sent by default (see OAUTH_SCOPES); referenced by the README
// and available for a deployment that opts into scope enforcement.
export const RECOMMENDED_SCOPES = [
'url:GET|/api/v1/courses',
'url:GET|/api/v1/courses/:id',
'url:GET|/api/v1/courses/:course_id/assignments',
'url:GET|/api/v1/courses/:course_id/assignments/:id',
'url:GET|/api/v1/courses/:course_id/assignments/:assignment_id/submissions',
'url:GET|/api/v1/courses/:course_id/assignments/:assignment_id/submissions/:user_id',
'url:GET|/api/v1/courses/:course_id/discussion_topics',
'url:GET|/api/v1/courses/:course_id/pages',
'url:GET|/api/v1/courses/:course_id/pages/:url_or_id',
'url:GET|/api/v1/courses/:course_id/modules',
'url:GET|/api/v1/courses/:course_id/enrollments',
'url:PUT|/api/v1/courses/:course_id/assignments/:assignment_id/submissions/:user_id',
'url:POST|/api/v1/courses/:course_id/discussion_topics',
] as const;
// ---- Server-side configuration (Canvas OAuth) -----------------------------
//
// These are read from the environment by src/server.ts. They NEVER reach the
// browser bundle: the client id and host are public, but the client secret is
// server-only and is validated to be present before the server will start
// (readServerConfig throws on a missing secret). This is the ONLY place the secret
// exists.
export interface ServerConfig {
/** Canvas institution host, e.g. `school.instructure.com` (bare, normalized). */
canvasHost: string;
/** Canvas Developer Key client id (public). */
canvasClientId: string;
/** Canvas Developer Key client secret (SERVER ONLY — token exchange + refresh). */
canvasClientSecret: string;
/** OAuth redirect registered on the key (e.g. https://canvas.hanzo.ai/oauth/callback). */
canvasRedirectUri: string;
/** Listen port. */
port: number;
}
// readServerConfig fails fast (throws) if a required Canvas value is missing — a
// server that cannot exchange OAuth codes (or does not know which Canvas host to
// call) must not pretend to start. Pure given an env map, so it is unit-tested
// without touching process.env. The host is normalized at this one boundary.
export function readServerConfig(env: Record<string, string | undefined>): ServerConfig {
const canvasHost = env.CANVAS_HOST;
const canvasClientId = env.CANVAS_CLIENT_ID;
const canvasClientSecret = env.CANVAS_CLIENT_SECRET;
const canvasRedirectUri = env.CANVAS_REDIRECT_URI;
const missing: string[] = [];
if (!canvasHost) missing.push('CANVAS_HOST');
if (!canvasClientId) missing.push('CANVAS_CLIENT_ID');
if (!canvasClientSecret) missing.push('CANVAS_CLIENT_SECRET');
if (!canvasRedirectUri) missing.push('CANVAS_REDIRECT_URI');
if (missing.length > 0) {
throw new Error(`Missing required environment: ${missing.join(', ')}`);
}
return {
canvasHost: normalizeHost(canvasHost!),
canvasClientId: canvasClientId!,
canvasClientSecret: canvasClientSecret!,
canvasRedirectUri: canvasRedirectUri!,
port: Number(env.PORT) || 8791,
};
}
+251
View File
@@ -0,0 +1,251 @@
// Course-context assembly — PURE, host-agnostic, fully unit-testable. Turns the
// typed Canvas records (course/syllabus, modules, assignments, pages, discussions,
// submissions, enrollments) into the plain text an AI action reads, windowed to a
// character budget so a busy course never overflows the model or gets sent silently
// truncated.
//
// There is ONE windowing contract, identical in spirit to @hanzo/procore's project
// windowing: render ordered blocks, walk them in order, stop at the budget, always
// include at least the first block, and report `truncated` honestly. The only
// education-specific parts are how a record renders to a block and the HTML→text
// step (Canvas content — syllabus, page bodies, assignment descriptions, discussion
// messages — is HTML).
import type {
Assignment,
Course,
Discussion,
Enrollment,
Module,
Page_,
Submission,
} from './canvas-api.js';
import { COURSE_CHAR_BUDGET } from './config.js';
// ---- HTML → text ----------------------------------------------------------
// htmlToText reduces Canvas rich-text HTML to readable plain text: block elements
// become line breaks, tags are stripped, the common named/numeric entities are
// decoded, and whitespace is collapsed. Deliberately small and dependency-free (no
// DOM) — Canvas bodies are trusted-institution content we only need to READ, not
// render, so a full sanitizer/ parser would be over-engineering. Pure.
export function htmlToText(html: string): string {
if (!html) return '';
return html
.replace(/<\s*(br|\/p|\/div|\/li|\/h[1-6]|\/tr)\s*\/?\s*>/gi, '\n')
.replace(/<\s*li[^>]*>/gi, '• ')
.replace(/<[^>]+>/g, '')
.replace(/&nbsp;/gi, ' ')
.replace(/&amp;/gi, '&')
.replace(/&lt;/gi, '<')
.replace(/&gt;/gi, '>')
.replace(/&quot;/gi, '"')
.replace(/&#39;/gi, "'")
.replace(/&#(\d+);/g, (_, d) => String.fromCodePoint(Number(d)))
.replace(/[ \t]+/g, ' ')
.replace(/\n{3,}/g, '\n\n')
.split('\n')
.map((line) => line.trim())
.join('\n')
.trim();
}
// clamp trims a rendered body to a maximum length with an ellipsis so one giant
// page/syllabus can't dominate the budget before windowing even runs. Pure.
function clamp(text: string, max: number): string {
return text.length > max ? `${text.slice(0, max).trimEnd()}` : text;
}
// Per-body cap: a single HTML body is trimmed to this before it becomes a block, so
// the windowing budget sees comparable blocks rather than one 40k-char page.
const BODY_CAP = 4_000;
// ---- Record → text block --------------------------------------------------
// renderCourseOverview turns the course + its syllabus into the lead block: the
// course identity and the (HTML-stripped, clamped) syllabus text.
export function renderCourseOverview(course: Course): string {
const lines: string[] = [];
const head = `${course.name}${course.courseCode ? ` (${course.courseCode})` : ''}`.trim();
lines.push(head);
const meta: string[] = [];
if (course.termName) meta.push(`Term: ${course.termName}`);
if (course.workflowState) meta.push(`State: ${course.workflowState}`);
if (meta.length) lines.push(meta.join(' · '));
const syllabus = htmlToText(course.syllabusBody);
if (syllabus) lines.push(`Syllabus:\n${clamp(syllabus, BODY_CAP)}`);
return lines.join('\n');
}
// renderAssignment turns one assignment into a labelled block.
export function renderAssignment(a: Assignment): string {
const head = `Assignment: ${a.name}`.trim();
const meta: string[] = [];
if (a.dueAt) meta.push(`Due: ${a.dueAt}`);
if (a.pointsPossible) meta.push(`Points: ${a.pointsPossible}`);
if (a.submissionTypes.length) meta.push(`Submit: ${a.submissionTypes.join(', ')}`);
const lines = [meta.length ? `${head}\n${meta.join(' · ')}` : head];
const desc = htmlToText(a.description);
if (desc) lines.push(clamp(desc, BODY_CAP));
return lines.join('\n');
}
// renderSubmission turns one student submission into a labelled block, including
// the score/status and any existing comment thread (order preserved).
export function renderSubmission(s: Submission): string {
const lines: string[] = [];
const flags = [s.late ? 'late' : '', s.missing ? 'missing' : ''].filter(Boolean).join(', ');
const head = `Submission (user ${s.userId})${flags ? ` [${flags}]` : ''}`;
lines.push(head);
const meta: string[] = [];
if (s.workflowState) meta.push(`Status: ${s.workflowState}`);
if (s.score !== null) meta.push(`Score: ${s.score}`);
if (s.grade) meta.push(`Grade: ${s.grade}`);
if (s.submittedAt) meta.push(`Submitted: ${s.submittedAt}`);
if (meta.length) lines.push(meta.join(' · '));
const body = htmlToText(s.body);
if (body) lines.push(`Response: ${clamp(body, BODY_CAP)}`);
for (const c of s.comments) {
const who = c.authorName ? ` (${c.authorName})` : '';
if (c.comment) lines.push(`Comment${who}: ${c.comment.trim()}`);
}
return lines.join('\n');
}
// renderDiscussion turns one discussion topic into a labelled block.
export function renderDiscussion(d: Discussion): string {
const kind = d.isAnnouncement ? 'Announcement' : 'Discussion';
const head = `${kind}: ${d.title}`.trim();
const body = htmlToText(d.message);
return body ? `${head}\n${clamp(body, BODY_CAP)}` : head;
}
// renderPage turns one wiki page into a labelled block (title + stripped body).
export function renderPage(p: Page_): string {
const head = `Page: ${p.title || p.url}`.trim();
const body = htmlToText(p.body);
return body ? `${head}\n${clamp(body, BODY_CAP)}` : head;
}
// renderModule turns one module + its items into a labelled block.
export function renderModule(m: Module): string {
const head = `Module: ${m.name}`.trim();
const items = m.items.map((i) => ` - ${i.title}${i.type ? ` [${i.type}]` : ''}`).filter(Boolean);
return items.length ? `${head}\n${items.join('\n')}` : head;
}
// renderEnrollment turns one enrollment into a single labelled line.
export function renderEnrollment(e: Enrollment): string {
const who = e.userName || `user ${e.userId}`;
const role = e.role || e.type;
return `${who}${role ? `${role}` : ''}${e.state ? ` (${e.state})` : ''}`;
}
// ---- Windowing to a budget ------------------------------------------------
// A named group of rendered blocks — a section of the course context (e.g.
// "Assignments", "Modules"). The assembler concatenates sections in the order given
// and windows the whole thing to the budget.
export interface Section {
title: string;
blocks: string[];
}
// The windowed course context: the rendered text, how many blocks were available vs
// included, and whether anything was dropped (so the prompt and UI can say so
// honestly).
export interface CourseContext {
text: string;
totalBlocks: number;
includedBlocks: number;
truncated: boolean;
}
// buildCourseContext concatenates sections IN ORDER and caps the rendered text at
// `budget` characters. It walks blocks in order (across sections) and stops when
// adding the next block would exceed the budget — always including at least the
// first block (hard-cut to the budget if that one block alone is over). `truncated`
// is true whenever not every available block made it in. Pure and total:
// deterministic, no I/O. This is the ONE windowing algorithm for the package — the
// same "fit ordered text to a budget" contract as @hanzo/procore.
export function buildCourseContext(
sections: Section[],
budget: number = COURSE_CHAR_BUDGET,
): CourseContext {
const totalBlocks = sections.reduce((n, s) => n + s.blocks.length, 0);
if (totalBlocks === 0) {
return { text: '', totalBlocks: 0, includedBlocks: 0, truncated: false };
}
const parts: string[] = [];
let used = 0;
let included = 0;
let hardCut = false;
outer: for (const section of sections) {
if (section.blocks.length === 0) continue;
// The section header is charged to the first block that fits under it.
let headerPending = `## ${section.title}\n`;
for (const block of section.blocks) {
const prefix = parts.length === 0 ? '' : '\n\n';
const addition = prefix + headerPending + block;
if (used + addition.length > budget) {
if (parts.length === 0) {
// First block alone overflows — hard-cut it to the budget so we always
// send something rather than an empty context.
const solo = (headerPending + block).slice(0, budget);
parts.push(solo);
used = solo.length;
included = 1;
hardCut = true;
}
break outer;
}
parts.push(addition);
used += addition.length;
included += 1;
headerPending = ''; // header only precedes the first block of the section
}
}
const truncated = included < totalBlocks || hardCut;
return { text: parts.join(''), totalBlocks, includedBlocks: included, truncated };
}
// contextNote is the one honest sentence prepended to the course text so the model
// (and, echoed in the panel, the user) knows the scope of what it sees. Never claim
// the whole course was sent when it wasn't. Pure.
export function contextNote(ctx: CourseContext): string {
if (ctx.totalBlocks === 0) return 'No course records were available.';
return ctx.truncated
? `Course records: ${ctx.includedBlocks} of ${ctx.totalBlocks} items (truncated to fit — answer only from what is shown and say so if the omitted part is needed).`
: `Course records: all ${ctx.totalBlocks} item${ctx.totalBlocks === 1 ? '' : 's'}.`;
}
// ---- Convenience section builders -----------------------------------------
//
// These turn a typed record list into a Section, so a caller (server or panel)
// assembles a course context in a couple of lines. Kept here (pure) so the same
// section shapes feed both surfaces and the tests.
export function courseSection(course: Course, title = 'Course'): Section {
return { title, blocks: [renderCourseOverview(course)] };
}
export function moduleSection(modules: Module[], title = 'Modules'): Section {
return { title, blocks: modules.map(renderModule) };
}
export function assignmentSection(assignments: Assignment[], title = 'Assignments'): Section {
return { title, blocks: assignments.map(renderAssignment) };
}
export function pageSection(pages: Page_[], title = 'Pages'): Section {
return { title, blocks: pages.map(renderPage) };
}
export function discussionSection(discussions: Discussion[], title = 'Discussions'): Section {
return { title, blocks: discussions.map(renderDiscussion) };
}
export function submissionSection(submissions: Submission[], title = 'Submissions'): Section {
return { title, blocks: submissions.map(renderSubmission) };
}
export function enrollmentSection(enrollments: Enrollment[], title = 'Enrollments'): Section {
return { title, blocks: enrollments.map(renderEnrollment) };
}
+145
View File
@@ -0,0 +1,145 @@
// The Hanzo call and its request/response shaping over a COURSE — thin over the
// published `@hanzo/ai` headless client, host-agnostic, and fully unit-testable (no
// Canvas SDK, no DOM). The panel and the server are the glue that read a course's
// records and hand them here. Speaks the OpenAI-compatible /v1 wire protocol the
// whole Hanzo suite uses (identical to @hanzo/procore) so the gateway sees one shape
// from every surface.
//
// @hanzo/ai@^0.2.0 IS the headless client: createAiClient({ baseUrl, token }) →
// .chat.completions.create({ model, messages }) + .models.list(). We import it and
// do NOT reimplement the transport. This module adds only the course-aware prompt
// assembly + the single `ask` primitive the actions layer on.
import {
createAiClient,
type AiClient,
type ChatCompletion,
type ChatCompletionMessage,
} from '@hanzo/ai';
import { DEFAULT_MODEL, HANZO_API_BASE_URL } from './config.js';
import { contextNote, type CourseContext } from './course.js';
// SYSTEM_PROMPT grounds every answer in the course records. It forbids inventing
// facts nobody recorded (the failure mode that makes a teaching assistant
// untrustworthy), keeps student data handled respectfully, and stays honest about
// truncated context. It states plainly that the output is a DRAFT for an educator to
// review — not an authoritative grade, decision, or the final word to a student.
export const SYSTEM_PROMPT =
'You are Hanzo AI, an assistant that helps instructors and teaching staff work ' +
'with their Canvas course — the syllabus, modules, assignments, pages, ' +
'discussions, and student submissions. Work ONLY from the course records provided ' +
'below — never invent assignments, due dates, grades, submissions, or facts that ' +
'are not supported by the text. Be concise, precise, and constructive; when you ' +
'reference student work, be specific and fair. If the records are marked truncated ' +
'and a complete answer needs the omitted part, say so plainly rather than guessing. ' +
'Everything you produce — feedback, questions, announcements, summaries — is a ' +
'DRAFT for an educator to review and edit before it reaches a student; it is not an ' +
'authoritative grade or decision.';
// ---- Prompt assembly ------------------------------------------------------
// Optional structured context about the course (name, code, term) the Canvas API
// supplies. Attached as a short header above the records so answers can reference the
// course without the model guessing.
export interface CourseMeta {
name?: string;
courseCode?: string;
term?: string;
}
function courseHeader(meta: CourseMeta | undefined): string {
if (!meta) return '';
const parts: string[] = [];
if (meta.name) parts.push(`Course: ${meta.name}`);
if (meta.courseCode) parts.push(`Code: ${meta.courseCode}`);
if (meta.term) parts.push(`Term: ${meta.term}`);
return parts.length > 0 ? parts.join('\n') + '\n\n' : '';
}
// buildMessages turns a task (the user's question, or one of the action prompts)
// plus the windowed course context + optional metadata into the OpenAI-compatible
// message list. The records are fenced so the model treats them as data, not
// instructions, and the honest context note rides inside the user turn so it is never
// lost. Pure — unit-tested.
export function buildMessages(
task: string,
ctx: CourseContext,
meta?: CourseMeta,
): ChatCompletionMessage[] {
const system: ChatCompletionMessage = { role: 'system', content: SYSTEM_PROMPT };
const header = courseHeader(meta);
const user: ChatCompletionMessage = {
role: 'user',
content:
`${header}${contextNote(ctx)}\n\n` +
`---- course records ----\n${ctx.text}\n---- end course records ----\n\n` +
`---- task ----\n${task}`,
};
return [system, user];
}
// extractContent pulls the assistant text out of a @hanzo/ai ChatCompletion,
// tolerating the string-or-parts content shape the OpenAI schema allows. Throws on
// empty content so callers surface the real gateway state. Pure — unit-tested.
export function extractContent(res: ChatCompletion): string {
const msg = res?.choices?.[0]?.message;
const content = msg?.content;
let text = '';
if (typeof content === 'string') {
text = content;
} else if (Array.isArray(content)) {
text = content.map((part) => (part?.type === 'text' ? part.text : '')).join('');
}
if (text.length === 0) throw new Error('Hanzo API returned no content');
return text;
}
// ---- The single call path -------------------------------------------------
export interface AskOptions {
model?: string;
temperature?: number;
token?: string;
baseURL?: string;
/** Injected client (tests). Defaults to a real createAiClient. */
client?: AiClient;
signal?: AbortSignal;
}
// client resolves the @hanzo/ai client for a call: an injected one (tests) or a fresh
// createAiClient pointed at the gateway with the caller's bearer.
function client(opts: AskOptions): AiClient {
return (
opts.client ?? createAiClient({ token: opts.token, baseUrl: opts.baseURL ?? HANZO_API_BASE_URL })
);
}
// ask runs ONE non-streaming completion over a course and returns the answer. This
// is the single path from every Canvas surface to the model — the actions, a freeform
// question, and any server-side call all funnel here. token may be empty (the gateway
// serves anonymous/limited models).
export async function ask(
task: string,
ctx: CourseContext,
meta: CourseMeta | undefined,
opts: AskOptions = {},
): Promise<string> {
const res = await client(opts).chat.completions.create(
{
model: opts.model ?? DEFAULT_MODEL,
messages: buildMessages(task, ctx, meta),
stream: false,
...(opts.temperature !== undefined ? { temperature: opts.temperature } : {}),
},
{ signal: opts.signal },
);
return extractContent(res);
}
// listModels returns the model ids the caller may route to, from /v1/models via the
// headless client. The endpoint is org-scoped by the bearer; an empty token lists
// public models.
export async function listModels(opts: AskOptions = {}): Promise<string[]> {
const models = await client(opts).models.list({ signal: opts.signal });
return models.map((m) => m.id);
}
+58
View File
@@ -0,0 +1,58 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Hanzo AI for Canvas</title>
<link rel="stylesheet" href="styles.css" />
</head>
<body>
<header>
<span class="title">Hanzo AI</span>
<select id="model" aria-label="Model"></select>
<span class="host">Canvas</span>
</header>
<div class="row scope">
<select id="course" aria-label="Course"></select>
<button id="load" class="secondary">Load</button>
</div>
<div class="row scope">
<select id="assignment" aria-label="Assignment"></select>
<button id="loadsubs" class="secondary" disabled>Load submissions</button>
</div>
<div class="records" id="records"></div>
<!-- One-click actions over the loaded course. Chips are built from the catalog. -->
<div class="chips" id="chips"></div>
<label for="prompt">Ask about this course</label>
<textarea id="prompt" placeholder="e.g. Which assignments are due next week? · Summarize what module 3 covers. · What are the common themes in the discussion posts?"></textarea>
<div class="row">
<button id="run">Ask Hanzo</button>
<button id="stop" class="secondary" disabled>Stop</button>
<span class="spacer"></span>
<button id="comment" class="secondary" disabled title="Load an assignment's submissions to enable">Post as submission comment</button>
<button id="announce" class="secondary" disabled title="Load a course to enable">Post as announcement</button>
</div>
<details>
<summary>Hanzo API key</summary>
<div class="row">
<input id="apikey" type="password" placeholder="hk-…" autocomplete="off" />
<button id="savekey" class="secondary">Save</button>
</div>
<div id="authhint" class="hint"></div>
</details>
<div class="status" id="status"></div>
<label for="output">Result</label>
<textarea id="output" placeholder="Hanzo's draft appears here."></textarea>
<footer>Routed through api.hanzo.ai · grounded in your Canvas course records · a draft for an educator to review, not an authoritative grade or decision.</footer>
<script type="module" src="__ENTRY__"></script>
</body>
</html>
+11
View File
@@ -0,0 +1,11 @@
// Public surface of @hanzo/canvas-lms: the pure, host-agnostic modules. The browser
// panel (app.ts) and the Node service (server.ts) are entry points, not re-exported
// here. A consumer embedding the course-analysis pipeline in their own service imports
// from here.
export * from './config.js';
export * from './canvas-oauth.js';
export * from './canvas-api.js';
export * from './course.js';
export * from './hanzo.js';
export * from './actions.js';
+241
View File
@@ -0,0 +1,241 @@
// Browser-side panel helpers — PURE where it counts (launch-context parsing +
// proxy-request shaping), so the impure DOM wiring in app.ts stays thin and the logic
// is unit-tested. The panel reaches Canvas ONLY through the server proxy (config:
// same-origin /proxy/*), which injects the OAuth Bearer + refreshes it; the browser
// never holds a Canvas token.
import {
parseCourses,
parseCourse,
parseAssignments,
parseAssignment,
parseSubmissions,
parseSubmission,
parseDiscussions,
parsePages,
parsePage,
parseModules,
parseEnrollments,
parseLinkHeader,
nextPage,
pageParams,
type Course,
type Assignment,
type Submission,
type Discussion,
type Page_,
type Module,
type Enrollment,
type Page,
} from './canvas-api.js';
// The launch context: when Canvas embeds this app (via LTI or a course-nav link) it
// passes the course in the URL query. The panel reads it so it opens already scoped.
// Optional — without it the user picks from the course list.
export interface LaunchContext {
courseId: string;
}
// parseLaunchContext reads a course id from a location search string, accepting the
// plain `course_id` and Canvas's LTI custom-variable spellings. Pure — unit-tested
// with plain strings.
export function parseLaunchContext(search: string): LaunchContext {
const q = new URLSearchParams(search);
return {
courseId:
q.get('course_id') ??
q.get('canvas_course_id') ??
q.get('custom_canvas_course_id') ??
q.get('courseId') ??
'',
};
}
// A parsed list result: the typed items plus the page number to request next (from
// the Link header's `rel="next"`), or undefined on the last page.
export interface ListResult<T> {
items: T[];
next?: number;
}
// The panel's Canvas client: reads through the same-origin server proxy. Every call
// rides the session cookie (credentials: 'include'); the proxy injects the Bearer.
// Pure over an injected fetch + base, so request shaping is unit-testable.
export interface ProxyClient {
listCourses(page?: Page): Promise<ListResult<Course>>;
getCourse(courseId: number | string): Promise<Course>;
listAssignments(courseId: number | string, page?: Page): Promise<ListResult<Assignment>>;
getAssignment(courseId: number | string, assignmentId: number | string): Promise<Assignment>;
listSubmissions(
courseId: number | string,
assignmentId: number | string,
page?: Page,
): Promise<ListResult<Submission>>;
getSubmission(
courseId: number | string,
assignmentId: number | string,
userId: number | string,
): Promise<Submission>;
listDiscussions(courseId: number | string, page?: Page): Promise<ListResult<Discussion>>;
listPages(courseId: number | string, page?: Page): Promise<ListResult<Page_>>;
getPage(courseId: number | string, urlOrId: number | string): Promise<Page_>;
listModules(courseId: number | string, page?: Page): Promise<ListResult<Module>>;
listEnrollments(courseId: number | string, page?: Page): Promise<ListResult<Enrollment>>;
postSubmissionComment(
courseId: number | string,
assignmentId: number | string,
userId: number | string,
text: string,
): Promise<void>;
createAnnouncement(courseId: number | string, title: string, message: string): Promise<void>;
}
export interface ProxyClientOptions {
/** Proxy base (defaults to same-origin ''). The REST path is appended after /proxy. */
base?: string;
/** Injected fetch (tests). Defaults to global fetch. */
fetch?: typeof fetch;
}
// proxyUrl builds a same-origin proxy URL for a REST path + query, expanding array
// values into Canvas's `key[]=v` repetition. Normalizes the base (drops a trailing
// slash) so this is the ONE place base+path joining happens. Pure so tests assert the
// exact shape (…/proxy/courses?per_page=100).
export function proxyUrl(
base: string,
restPath: string,
query: Record<string, string | string[] | undefined> = {},
): string {
const q = new URLSearchParams();
for (const [k, v] of Object.entries(query)) {
if (Array.isArray(v)) {
for (const item of v) if (item !== undefined && item !== '') q.append(`${k}[]`, item);
} else if (v !== undefined && v !== '') {
q.set(k, v);
}
}
const qs = q.toString();
return `${base.replace(/\/+$/, '')}/proxy${restPath}${qs ? `?${qs}` : ''}`;
}
// createProxyClient returns a ProxyClient. The cookie credentials are attached once
// here so every method stays a one-liner. List methods parse the Link header into the
// next page number so a caller can page through the proxy without following Canvas's
// absolute URLs.
export function createProxyClient(opts: ProxyClientOptions = {}): ProxyClient {
const base = opts.base ?? ''; // proxyUrl normalizes the trailing slash
const doFetch = opts.fetch ?? fetch;
async function getJson(
restPath: string,
query: Record<string, string | string[] | undefined>,
): Promise<{ data: any; next?: number }> {
const resp = await doFetch(proxyUrl(base, restPath, query), { credentials: 'include' });
if (!resp.ok) throw new Error(await proxyError(resp));
return { data: await resp.json(), next: nextPage(parseLinkHeader(resp.headers)) };
}
async function write(restPath: string, method: 'POST' | 'PUT', body: unknown): Promise<void> {
const resp = await doFetch(proxyUrl(base, restPath), {
method,
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
body: JSON.stringify(body),
});
if (!resp.ok) throw new Error(await proxyError(resp));
}
return {
async listCourses(page?) {
const { data, next } = await getJson('/courses', pageParams(page));
return { items: parseCourses(data), next };
},
async getCourse(courseId) {
const { data } = await getJson(`/courses/${enc(courseId)}`, { include: ['syllabus_body'] });
return parseCourse(data);
},
async listAssignments(courseId, page?) {
const { data, next } = await getJson(`/courses/${enc(courseId)}/assignments`, pageParams(page));
return { items: parseAssignments(data), next };
},
async getAssignment(courseId, assignmentId) {
const { data } = await getJson(
`/courses/${enc(courseId)}/assignments/${enc(assignmentId)}`,
{},
);
return parseAssignment(data);
},
async listSubmissions(courseId, assignmentId, page?) {
const { data, next } = await getJson(
`/courses/${enc(courseId)}/assignments/${enc(assignmentId)}/submissions`,
{ include: ['submission_comments'], ...pageParams(page) },
);
return { items: parseSubmissions(data), next };
},
async getSubmission(courseId, assignmentId, userId) {
const { data } = await getJson(
`/courses/${enc(courseId)}/assignments/${enc(assignmentId)}/submissions/${enc(userId)}`,
{ include: ['submission_comments'] },
);
return parseSubmission(data);
},
async listDiscussions(courseId, page?) {
const { data, next } = await getJson(
`/courses/${enc(courseId)}/discussion_topics`,
pageParams(page),
);
return { items: parseDiscussions(data), next };
},
async listPages(courseId, page?) {
const { data, next } = await getJson(`/courses/${enc(courseId)}/pages`, pageParams(page));
return { items: parsePages(data), next };
},
async getPage(courseId, urlOrId) {
const { data } = await getJson(`/courses/${enc(courseId)}/pages/${enc(urlOrId)}`, {});
return parsePage(data);
},
async listModules(courseId, page?) {
const { data, next } = await getJson(`/courses/${enc(courseId)}/modules`, {
include: ['items'],
...pageParams(page),
});
return { items: parseModules(data), next };
},
async listEnrollments(courseId, page?) {
const { data, next } = await getJson(
`/courses/${enc(courseId)}/enrollments`,
pageParams(page),
);
return { items: parseEnrollments(data), next };
},
async postSubmissionComment(courseId, assignmentId, userId, text) {
await write(
`/courses/${enc(courseId)}/assignments/${enc(assignmentId)}/submissions/${enc(userId)}`,
'PUT',
{ comment: { text_comment: text } },
);
},
async createAnnouncement(courseId, title, message) {
await write(`/courses/${enc(courseId)}/discussion_topics`, 'POST', {
title,
message,
is_announcement: true,
});
},
};
}
// proxyError extracts a readable message from a non-2xx proxy response.
async function proxyError(resp: Response): Promise<string> {
const text = await resp.text().catch(() => '');
try {
const j = JSON.parse(text);
return `Canvas proxy ${resp.status}: ${j?.error || j?.message || text.slice(0, 200)}`;
} catch {
return `Canvas proxy ${resp.status}: ${text.slice(0, 200) || 'request failed'}`;
}
}
function enc(segment: number | string): string {
return encodeURIComponent(String(segment));
}
+252
View File
@@ -0,0 +1,252 @@
// The Canvas install + API-proxy service. This is the ONLY place the Canvas client
// secret and the OAuth tokens exist — the secret is read from the environment (never
// bundled, never sent to the browser); tokens are minted by the OAuth flow and kept
// server-side, refreshed transparently on expiry. It:
//
// GET /oauth/install → redirect the user to Canvas's OAuth consent
// GET /oauth/callback → exchange the code for a token, open a session, and hand
// the browser a session cookie
// ALL /proxy/* → forward a browser request to the Canvas REST API with
// the session's Bearer token, refreshing the token first
// if it has expired. The browser never sees the token or
// the secret.
// GET /healthz → readiness
//
// It is a dependency-free Node http handler built on the pure modules (config,
// canvas-oauth, canvas-api) so it is deployable behind hanzoai/ingress as a small
// service at canvas.hanzo.ai. The pure logic it wraps is what the tests cover; the
// http server is an integration concern.
//
// node dist/server.js (after build.js bundles it)
//
// Required environment (see config.readServerConfig):
// CANVAS_HOST, CANVAS_CLIENT_ID, CANVAS_CLIENT_SECRET, CANVAS_REDIRECT_URI
// PORT (default 8791)
import { createServer, type IncomingMessage, type ServerResponse } from 'node:http';
import { randomUUID } from 'node:crypto';
import { apiBaseUrl, readServerConfig, OAUTH_SCOPES, type ServerConfig } from './config.js';
import {
authorizeUrl,
tokenExchange,
refreshExchange,
parseTokenResponse,
carryRefreshToken,
isExpired,
type CanvasTokenSet,
} from './canvas-oauth.js';
// A server-side session: the tokens for one authorized user + when the token was
// minted (Canvas does not return a mint timestamp, so we record wall-clock at
// mint/refresh to compute expiry). In-memory here keyed by an opaque session id
// carried in an HttpOnly cookie; a production deployment persists this to hanzoai/kv
// (Valkey) so sessions survive a restart.
interface Session {
token: CanvasTokenSet;
/** Wall-clock epoch seconds when the token was last minted/refreshed. */
mintedAt: number;
}
const sessions = new Map<string, Session>();
const SESSION_COOKIE = 'canvas_sid';
// A pending OAuth `state` (CSRF token) minted at /oauth/install and consumed at
// /oauth/callback. A production deployment persists these (Valkey, short TTL); a Set
// is enough for a single instance.
const pendingStates = new Set<string>();
function nowSeconds(): number {
return Math.floor(Date.now() / 1000);
}
function json(res: ServerResponse, status: number, body: unknown): void {
res.writeHead(status, { 'Content-Type': 'application/json' });
res.end(JSON.stringify(body));
}
function log(fields: Record<string, unknown>): void {
console.log(JSON.stringify(fields));
}
// sessionIdFromCookie reads the session id from the Cookie header. Minimal parser — we
// only need our one cookie.
function sessionIdFromCookie(req: IncomingMessage): string | undefined {
const raw = req.headers.cookie;
if (!raw) return undefined;
for (const part of raw.split(';')) {
const [k, ...v] = part.trim().split('=');
if (k === SESSION_COOKIE) return decodeURIComponent(v.join('='));
}
return undefined;
}
// GET /oauth/install → 302 to Canvas's consent screen. `state` is a fresh CSRF token
// re-checked on callback.
function handleInstall(cfg: ServerConfig, res: ServerResponse): void {
const state = randomUUID();
pendingStates.add(state);
const url = authorizeUrl({
host: cfg.canvasHost,
clientId: cfg.canvasClientId,
redirectUri: cfg.canvasRedirectUri,
scopes: OAUTH_SCOPES,
state,
});
res.writeHead(302, { Location: url });
res.end();
}
// GET /oauth/callback?code=…&state=… → verify state, exchange the code for a token
// (secret in the server-side body), open a session, and set the cookie.
async function handleOAuthCallback(
cfg: ServerConfig,
url: URL,
res: ServerResponse,
): Promise<void> {
const code = url.searchParams.get('code');
const state = url.searchParams.get('state');
if (!code) return json(res, 400, { error: 'missing code' });
if (!state || !pendingStates.delete(state)) return json(res, 400, { error: 'invalid state' });
const exReq = tokenExchange({
host: cfg.canvasHost,
clientId: cfg.canvasClientId,
clientSecret: cfg.canvasClientSecret,
code,
redirectUri: cfg.canvasRedirectUri,
});
let token: CanvasTokenSet;
try {
const resp = await fetch(exReq.url, {
method: 'POST',
headers: exReq.headers,
body: exReq.body,
});
token = parseTokenResponse(await resp.json().catch(() => ({})));
} catch (e: any) {
return json(res, 400, { error: e?.message || 'token exchange failed' });
}
const sid = randomUUID();
sessions.set(sid, { token, mintedAt: nowSeconds() });
log({ msg: 'oauth: session opened', sid });
res.writeHead(200, {
'Content-Type': 'application/json',
'Set-Cookie': `${SESSION_COOKIE}=${sid}; HttpOnly; Secure; SameSite=Lax; Path=/`,
});
res.end(JSON.stringify({ ok: true, installed: true }));
}
// freshToken returns a session's access token, refreshing first if it has expired.
// Canvas does not rotate the refresh token (the refresh response omits it), so we
// carry the previous one forward via carryRefreshToken. Throws if the refresh fails
// (the caller returns 401 and the user re-installs).
async function freshToken(cfg: ServerConfig, sid: string, session: Session): Promise<string> {
if (!isExpired(session.token, session.mintedAt, nowSeconds())) return session.token.access_token;
const refreshToken = session.token.refresh_token;
if (!refreshToken) throw new Error('session expired and no refresh token');
const rReq = refreshExchange({
host: cfg.canvasHost,
clientId: cfg.canvasClientId,
clientSecret: cfg.canvasClientSecret,
refreshToken,
});
const resp = await fetch(rReq.url, { method: 'POST', headers: rReq.headers, body: rReq.body });
const next = carryRefreshToken(parseTokenResponse(await resp.json().catch(() => ({}))), session.token);
sessions.set(sid, { token: next, mintedAt: nowSeconds() });
log({ msg: 'oauth: token refreshed', sid });
return next.access_token;
}
// ALL /proxy/* → forward to the Canvas REST API. The browser sends the REST path
// (after /proxy); the server injects the Bearer token (never exposed to the browser)
// and forwards the method, query, and body. This is the API proxy that keeps the
// secret + tokens server-side while letting the panel read Courses/Assignments/…and
// post a comment or announcement.
async function handleProxy(
cfg: ServerConfig,
req: IncomingMessage,
res: ServerResponse,
url: URL,
): Promise<void> {
const sid = sessionIdFromCookie(req);
const session = sid ? sessions.get(sid) : undefined;
if (!sid || !session) return json(res, 401, { error: 'not authenticated' });
let accessToken: string;
try {
accessToken = await freshToken(cfg, sid, session);
} catch (e: any) {
return json(res, 401, { error: e?.message || 'token refresh failed' });
}
// The path after /proxy is the REST path relative to /api/v1, e.g.
// /proxy/courses → ${apiBase}/courses. We forbid absolute/scheme-bearing targets so
// the proxy can only ever reach the configured Canvas REST host.
const restPath = url.pathname.replace(/^\/proxy/, '') || '/';
const target = `${apiBaseUrl(cfg.canvasHost)}${restPath}${url.search}`;
const method = req.method || 'GET';
const body = method === 'GET' || method === 'HEAD' ? undefined : await readRawBody(req);
try {
const upstream = await fetch(target, {
method,
headers: {
Authorization: `Bearer ${accessToken}`,
...(body ? { 'Content-Type': 'application/json' } : {}),
},
body,
});
// Pass Canvas's Link header through so the panel can paginate.
const link = upstream.headers.get('Link');
const text = await upstream.text();
const outHeaders: Record<string, string> = { 'Content-Type': 'application/json' };
if (link) outHeaders.Link = link;
res.writeHead(upstream.status, outHeaders);
res.end(text);
} catch (e: any) {
log({ msg: 'proxy: upstream error', error: e?.message, target });
return json(res, 502, { error: 'upstream request failed' });
}
}
// readRawBody collects the raw request bytes as a utf8 string.
async function readRawBody(req: IncomingMessage): Promise<string> {
const chunks: Buffer[] = [];
for await (const c of req) chunks.push(c as Buffer);
return Buffer.concat(chunks).toString('utf8');
}
// createHandler is the request router. Everything is a small handler over the pure
// modules. Exported so a test can drive it with a mock req/res if desired.
export function createHandler(cfg: ServerConfig) {
return async (req: IncomingMessage, res: ServerResponse): Promise<void> => {
const url = new URL(req.url || '/', `http://localhost:${cfg.port}`);
try {
if (req.method === 'GET' && url.pathname === '/oauth/install') return handleInstall(cfg, res);
if (req.method === 'GET' && url.pathname === '/oauth/callback')
return await handleOAuthCallback(cfg, url, res);
if (url.pathname === '/proxy' || url.pathname.startsWith('/proxy/'))
return await handleProxy(cfg, req, res, url);
if (req.method === 'GET' && url.pathname === '/healthz') return json(res, 200, { ok: true });
return json(res, 404, { error: 'not found' });
} catch (e: any) {
log({ msg: 'unhandled error', error: e?.message });
return json(res, 500, { error: 'internal error' });
}
};
}
// main boots the server when run directly. Import-safe: only the direct entry
// listens, so tests import the handlers without opening a port.
export function main(): void {
const cfg = readServerConfig(process.env);
const server = createServer(createHandler(cfg));
server.listen(cfg.port, () => {
log({ msg: 'hanzo canvas service up', port: cfg.port, host: cfg.canvasHost });
});
}
if (process.argv[1] && process.argv[1].endsWith('server.js')) {
main();
}
+50
View File
@@ -0,0 +1,50 @@
:root {
color-scheme: light dark;
--fg: #1a1a1a; --muted: #666; --bg: #fff; --line: #e3e3e3; --accent: #111;
--ok: #1a7f37; --warn: #9a6700; --error: #cf222e;
}
@media (prefers-color-scheme: dark) {
:root {
--fg: #eaeaea; --muted: #9a9a9a; --bg: #1e1e1e; --line: #333; --accent: #fff;
--ok: #3fb950; --warn: #d29922; --error: #f85149;
}
}
* { box-sizing: border-box; }
body {
font: 14px/1.45 -apple-system, "Segoe UI", Roboto, sans-serif;
color: var(--fg); background: var(--bg); margin: 0 auto; padding: 14px;
max-width: 720px;
}
header { display: flex; align-items: center; gap: 8px; margin-bottom: 10px; }
header .title { font-weight: 600; font-size: 15px; }
header .host { color: var(--muted); font-size: 12px; margin-left: auto; }
label { display: block; font-size: 12px; color: var(--muted); margin: 10px 0 4px; }
textarea, select, input {
width: 100%; font: inherit; color: var(--fg); background: var(--bg);
border: 1px solid var(--line); border-radius: 6px; padding: 8px;
}
textarea#prompt { min-height: 56px; resize: vertical; }
textarea#output { min-height: 220px; resize: vertical; }
.row { display: flex; gap: 8px; align-items: center; margin-top: 8px; flex-wrap: wrap; }
.row.scope { margin-top: 4px; }
.row.scope select { flex: 1; min-width: 160px; }
button {
font: inherit; border: 1px solid var(--line); background: var(--accent);
color: var(--bg); border-radius: 6px; padding: 8px 14px; cursor: pointer;
}
button.secondary { background: transparent; color: var(--fg); }
button:disabled { opacity: .5; cursor: default; }
.spacer { flex: 1; }
.records { font-size: 11px; color: var(--muted); margin-top: 6px; min-height: 14px; }
.status { min-height: 18px; font-size: 12px; margin-top: 10px; color: var(--muted); }
.status.ok { color: var(--ok); } .status.warn { color: var(--warn); } .status.error { color: var(--error); }
.hint { font-size: 11px; color: var(--muted); margin-top: 4px; }
footer { margin-top: 12px; font-size: 11px; color: var(--muted); }
select#model { width: auto; max-width: 150px; padding: 4px 8px; font-size: 12px; }
.chips { display: flex; flex-wrap: wrap; gap: 6px; margin-top: 10px; }
.chip {
padding: 5px 10px; border-radius: 999px; font-size: 13px;
background: transparent; color: var(--fg); border: 1px solid var(--line);
}
.chip:hover:not(:disabled) { border-color: var(--accent); }
details summary { cursor: pointer; font-size: 12px; color: var(--muted); margin-top: 10px; }
+89
View File
@@ -0,0 +1,89 @@
import { describe, it, expect, vi } from 'vitest';
import type { AiClient, ChatCompletion, ChatCompletionCreateParams } from '@hanzo/ai';
import { ACTIONS, actionList, actionPrompt, isActionId, runAction } from '../src/actions.js';
import { buildCourseContext } from '../src/course.js';
const ctx = buildCourseContext([{ title: 'Assignments', blocks: ['Assignment: Lab Report 1'] }]);
function mockClient(text: string) {
const reply: ChatCompletion = {
id: 'c', object: 'chat.completion', created: 0, model: 'zen5',
choices: [{ index: 0, message: { role: 'assistant', content: text }, finish_reason: 'stop' }],
};
const create = vi.fn(async (_p: ChatCompletionCreateParams) => reply);
return { client: { chat: { completions: { create } }, models: { list: vi.fn() } } as unknown as AiClient, create };
}
describe('actions: catalog', () => {
it('exposes exactly the five documented actions', () => {
expect(Object.keys(ACTIONS).sort()).toEqual(
['draftAnnouncement', 'draftFeedback', 'generateQuestions', 'summarizeCourse', 'summarizeSubmissions'].sort(),
);
});
it('every action has a non-empty label and prompt', () => {
for (const [id, a] of Object.entries(ACTIONS)) {
expect(a.label.length, id).toBeGreaterThan(0);
expect(a.prompt.length, id).toBeGreaterThan(20);
}
});
it('actionList mirrors the catalog order and shape', () => {
const list = actionList();
expect(list.map((a) => a.id)).toEqual(Object.keys(ACTIONS));
expect(list[0]).toEqual({ id: 'summarizeCourse', label: ACTIONS.summarizeCourse.label });
});
});
describe('actions: prompt intent', () => {
it('summarizeCourse grounds on the syllabus and modules', () => {
const p = actionPrompt('summarizeCourse');
expect(p).toMatch(/syllabus/i);
expect(p).toMatch(/module/i);
});
it('draftFeedback stays grounded and returns paste-ready comment text', () => {
const p = actionPrompt('draftFeedback');
expect(p).toMatch(/do not invent/i);
expect(p).toMatch(/submission comment/i);
});
it('generateQuestions asks for quiz questions and discussion prompts', () => {
const p = actionPrompt('generateQuestions');
expect(p).toMatch(/quiz questions/i);
expect(p).toMatch(/discussion prompts/i);
});
it('summarizeSubmissions asks for submitted/missing/late and scores', () => {
const p = actionPrompt('summarizeSubmissions');
expect(p).toMatch(/missing or late/i);
expect(p).toMatch(/scores or grades/i);
});
it('draftAnnouncement asks for a subject line and stays grounded on dates', () => {
const p = actionPrompt('draftAnnouncement');
expect(p).toMatch(/subject line/i);
expect(p).toMatch(/do not invent dates/i);
});
});
describe('actions: isActionId / actionPrompt guards', () => {
it('narrows known ids and rejects unknown', () => {
expect(isActionId('summarizeCourse')).toBe(true);
expect(isActionId('nope')).toBe(false);
});
it('actionPrompt throws on an unknown id', () => {
expect(() => actionPrompt('nope')).toThrow(/Unknown action/);
});
});
describe('actions: runAction', () => {
it('routes the resolved prompt through ask (one code path to the model)', async () => {
const { client, create } = mockClient('overview');
const out = await runAction('summarizeCourse', ctx, { name: 'BIO-101' }, { client });
expect(out).toBe('overview');
const user = String(create.mock.calls[0][0].messages[1].content);
expect(user).toContain(ACTIONS.summarizeCourse.prompt);
expect(user).toContain('Assignment: Lab Report 1');
});
it('rejects (not synchronously throws) on an unknown id', async () => {
await expect(runAction('nope', ctx)).rejects.toThrow(/Unknown action/);
});
});
+202
View File
@@ -0,0 +1,202 @@
import { describe, it, expect } from 'vitest';
import {
DEFAULT_PER_PAGE,
pageParams,
parseLinkHeader,
pageOfUrl,
nextPage,
listCourses,
getCourse,
listAssignments,
getAssignment,
listSubmissions,
getSubmission,
postSubmissionComment,
listDiscussions,
createAnnouncement,
listPages,
getPage,
listModules,
listEnrollments,
type Scope,
} from '../src/canvas-api.js';
import { apiBaseUrl } from '../src/config.js';
const scope: Scope = {
apiBase: apiBaseUrl('school.instructure.com'),
accessToken: 'at-123',
};
function q(url: string): URLSearchParams {
return new URL(url).searchParams;
}
describe('api: pageParams', () => {
it('emits nothing for no page', () => {
expect(pageParams(undefined)).toEqual({});
});
it('emits page + per_page when set', () => {
expect(pageParams({ page: 2, perPage: 50 })).toEqual({ page: '2', per_page: '50' });
});
it('clamps per_page to the documented max', () => {
expect(pageParams({ perPage: 500 }).per_page).toBe(String(DEFAULT_PER_PAGE));
});
it('ignores non-positive values', () => {
expect(pageParams({ page: 0, perPage: -5 })).toEqual({});
});
});
describe('api: bearer scoping', () => {
it('every read carries the Bearer token and no company header', () => {
for (const req of [
listCourses(scope),
getCourse(scope, 7),
listAssignments(scope, 7),
getAssignment(scope, 7, 9),
listSubmissions(scope, 7, 9),
getSubmission(scope, 7, 9, 11),
listDiscussions(scope, 7),
listPages(scope, 7),
getPage(scope, 7, 'intro'),
listModules(scope, 7),
listEnrollments(scope, 7),
]) {
expect(req.headers.Authorization).toBe('Bearer at-123');
expect(req.headers).not.toHaveProperty('Procore-Company-Id');
}
});
});
describe('api: courses', () => {
it('lists courses with pagination and no course in the path', () => {
const req = listCourses(scope, { page: 3, perPage: 25 });
const url = new URL(req.url);
expect(url.pathname).toBe('/api/v1/courses');
expect(q(req.url).get('page')).toBe('3');
expect(q(req.url).get('per_page')).toBe('25');
});
it('gets one course defaulting to include[]=syllabus_body', () => {
const req = getCourse(scope, 100);
expect(new URL(req.url).pathname).toBe('/api/v1/courses/100');
expect(q(req.url).getAll('include[]')).toEqual(['syllabus_body']);
});
it('gets a bare course when includes are empty', () => {
const req = getCourse(scope, 100, []);
expect(q(req.url).has('include[]')).toBe(false);
});
});
describe('api: assignments + submissions', () => {
it('lists assignments on a course path', () => {
expect(new URL(listAssignments(scope, 100).url).pathname).toBe('/api/v1/courses/100/assignments');
});
it('gets one assignment by id', () => {
expect(new URL(getAssignment(scope, 100, 55).url).pathname).toBe('/api/v1/courses/100/assignments/55');
});
it('lists submissions with submission_comments included', () => {
const req = listSubmissions(scope, 100, 55, { perPage: 50 });
expect(new URL(req.url).pathname).toBe('/api/v1/courses/100/assignments/55/submissions');
expect(q(req.url).getAll('include[]')).toEqual(['submission_comments']);
expect(q(req.url).get('per_page')).toBe('50');
});
it('gets one submission by user id', () => {
const req = getSubmission(scope, 100, 55, 900);
expect(new URL(req.url).pathname).toBe('/api/v1/courses/100/assignments/55/submissions/900');
});
});
describe('api: postSubmissionComment (the feedback write path)', () => {
it('PUTs a comment[text_comment] JSON body on the submission', () => {
const req = postSubmissionComment(scope, 100, 55, 900, 'Great analysis of the data.');
expect(req.method).toBe('PUT');
expect(new URL(req.url).pathname).toBe('/api/v1/courses/100/assignments/55/submissions/900');
expect(req.headers['Content-Type']).toBe('application/json');
expect(req.headers.Authorization).toBe('Bearer at-123');
expect(JSON.parse(req.body)).toEqual({ comment: { text_comment: 'Great analysis of the data.' } });
});
});
describe('api: createAnnouncement (the announcement write path)', () => {
it('POSTs a discussion topic flagged is_announcement', () => {
const req = createAnnouncement(scope, 100, 'Midterm moved', 'The midterm is now next Friday.');
expect(req.method).toBe('POST');
expect(new URL(req.url).pathname).toBe('/api/v1/courses/100/discussion_topics');
expect(JSON.parse(req.body)).toEqual({
title: 'Midterm moved',
message: 'The midterm is now next Friday.',
is_announcement: true,
});
});
});
describe('api: discussions / pages / modules / enrollments', () => {
it('lists discussions on a course path', () => {
expect(new URL(listDiscussions(scope, 100).url).pathname).toBe('/api/v1/courses/100/discussion_topics');
});
it('lists pages and gets one page by url slug', () => {
expect(new URL(listPages(scope, 100).url).pathname).toBe('/api/v1/courses/100/pages');
expect(new URL(getPage(scope, 100, 'week-1-intro').url).pathname).toBe('/api/v1/courses/100/pages/week-1-intro');
});
it('lists modules with items included', () => {
const req = listModules(scope, 100);
expect(new URL(req.url).pathname).toBe('/api/v1/courses/100/modules');
expect(q(req.url).getAll('include[]')).toEqual(['items']);
});
it('lists enrollments on a course path', () => {
expect(new URL(listEnrollments(scope, 100).url).pathname).toBe('/api/v1/courses/100/enrollments');
});
});
describe('api: path segment encoding', () => {
it('encodes ids/slugs defensively so a stray value cannot traverse the path', () => {
const req = getPage(scope, 'a/b', 'c d');
expect(req.url).toContain('/courses/a%2Fb/pages/c%20d');
});
});
describe('api: parseLinkHeader (RFC 5988)', () => {
const header =
'<https://school.instructure.com/api/v1/courses?page=1&per_page=10>; rel="current", ' +
'<https://school.instructure.com/api/v1/courses?page=2&per_page=10>; rel="next", ' +
'<https://school.instructure.com/api/v1/courses?page=1&per_page=10>; rel="first", ' +
'<https://school.instructure.com/api/v1/courses?page=17&per_page=10>; rel="last"';
it('parses each relation URL from a Headers instance', () => {
const links = parseLinkHeader(new Headers({ Link: header }));
expect(links.current).toContain('page=1');
expect(links.next).toBe('https://school.instructure.com/api/v1/courses?page=2&per_page=10');
expect(links.first).toContain('page=1');
expect(links.last).toContain('page=17');
});
it('parses from a plain header map (either case)', () => {
expect(parseLinkHeader({ Link: header }).next).toContain('page=2');
expect(parseLinkHeader({ link: header }).last).toContain('page=17');
});
it('returns {} for a missing/blank header', () => {
expect(parseLinkHeader({})).toEqual({});
expect(parseLinkHeader(new Headers())).toEqual({});
});
it('tolerates a last-page header with no next relation', () => {
const last =
'<https://school.instructure.com/api/v1/courses?page=16&per_page=10>; rel="prev", ' +
'<https://school.instructure.com/api/v1/courses?page=17&per_page=10>; rel="current"';
const links = parseLinkHeader({ Link: last });
expect(links.next).toBeUndefined();
expect(links.prev).toContain('page=16');
});
});
describe('api: pageOfUrl + nextPage', () => {
it('extracts the page number from a pagination URL', () => {
expect(pageOfUrl('https://h/api/v1/courses?page=2&per_page=10')).toBe(2);
expect(pageOfUrl('https://h/api/v1/courses?per_page=10')).toBeUndefined();
expect(pageOfUrl(undefined)).toBeUndefined();
});
it('nextPage reads the next relation into a page number', () => {
expect(nextPage({ next: 'https://h/api/v1/courses?page=3' })).toBe(3);
expect(nextPage({})).toBeUndefined();
});
});
+108
View File
@@ -0,0 +1,108 @@
import { describe, it, expect } from 'vitest';
import {
HANZO_API_BASE_URL,
DEFAULT_MODEL,
APIKEY_STORAGE_KEY,
COURSE_CHAR_BUDGET,
pickBearer,
chatCompletionsURL,
modelsURL,
normalizeHost,
authBase,
apiBaseUrl,
readServerConfig,
OAUTH_SCOPES,
RECOMMENDED_SCOPES,
} from '../src/config.js';
describe('config: gateway constants', () => {
it('points at api.hanzo.ai with /v1 paths and never /api/', () => {
expect(HANZO_API_BASE_URL).toBe('https://api.hanzo.ai');
expect(chatCompletionsURL()).toBe('https://api.hanzo.ai/v1/chat/completions');
expect(modelsURL()).toBe('https://api.hanzo.ai/v1/models');
expect(chatCompletionsURL()).not.toContain('/api/');
});
it('defaults to a zen model and a sane budget', () => {
expect(DEFAULT_MODEL).toBe('zen5');
expect(COURSE_CHAR_BUDGET).toBeGreaterThan(10_000);
expect(APIKEY_STORAGE_KEY).toContain('canvas');
});
});
describe('config: pickBearer', () => {
it('prefers a pasted key over an oauth token', () => {
expect(pickBearer('hk-abc', 'oauth-xyz')).toBe('hk-abc');
});
it('falls back to the oauth token, trimming whitespace', () => {
expect(pickBearer(' ', ' tok ')).toBe('tok');
});
it('returns empty when both are blank (anonymous)', () => {
expect(pickBearer('', '')).toBe('');
expect(pickBearer(' ', '')).toBe('');
});
});
describe('config: normalizeHost', () => {
it('strips a scheme, path, and trailing slash to a bare host', () => {
expect(normalizeHost('https://school.instructure.com/')).toBe('school.instructure.com');
expect(normalizeHost('http://canvas.school.edu/courses/1')).toBe('canvas.school.edu');
expect(normalizeHost('school.instructure.com')).toBe('school.instructure.com');
expect(normalizeHost(' school.instructure.com ')).toBe('school.instructure.com');
});
});
describe('config: authBase + apiBaseUrl', () => {
it('builds the OAuth login origin from a host', () => {
expect(authBase('school.instructure.com')).toBe('https://school.instructure.com');
expect(authBase('https://school.instructure.com/')).toBe('https://school.instructure.com');
});
it('builds the /api/v1 REST root from a host', () => {
expect(apiBaseUrl('school.instructure.com')).toBe('https://school.instructure.com/api/v1');
expect(apiBaseUrl('canvas.school.edu')).toBe('https://canvas.school.edu/api/v1');
});
});
describe('config: scopes', () => {
it('requests no scopes by default (works with or without scope enforcement)', () => {
expect(OAUTH_SCOPES).toEqual([]);
});
it('documents the granular read + write scopes for enforcement', () => {
expect(RECOMMENDED_SCOPES.length).toBeGreaterThan(5);
expect(RECOMMENDED_SCOPES).toContain('url:GET|/api/v1/courses');
expect(RECOMMENDED_SCOPES.some((s) => s.startsWith('url:PUT|'))).toBe(true);
expect(RECOMMENDED_SCOPES.some((s) => s.startsWith('url:POST|'))).toBe(true);
});
});
describe('config: readServerConfig', () => {
const base = {
CANVAS_HOST: 'school.instructure.com',
CANVAS_CLIENT_ID: 'cid',
CANVAS_CLIENT_SECRET: 'secret',
CANVAS_REDIRECT_URI: 'https://canvas.hanzo.ai/oauth/callback',
};
it('reads a full config, normalizing the host and defaulting the port to 8791', () => {
const cfg = readServerConfig({ ...base, CANVAS_HOST: 'https://school.instructure.com/' });
expect(cfg.canvasHost).toBe('school.instructure.com');
expect(cfg.canvasClientId).toBe('cid');
expect(cfg.canvasClientSecret).toBe('secret');
expect(cfg.canvasRedirectUri).toBe('https://canvas.hanzo.ai/oauth/callback');
expect(cfg.port).toBe(8791);
});
it('honours PORT', () => {
expect(readServerConfig({ ...base, PORT: '9002' }).port).toBe(9002);
});
it('throws listing every missing required value', () => {
expect(() => readServerConfig({})).toThrow(/CANVAS_HOST/);
expect(() => readServerConfig({})).toThrow(/CANVAS_CLIENT_ID/);
expect(() => readServerConfig({})).toThrow(/CANVAS_CLIENT_SECRET/);
expect(() => readServerConfig({})).toThrow(/CANVAS_REDIRECT_URI/);
expect(() => readServerConfig({ CANVAS_HOST: 'h' })).toThrow(
/CANVAS_CLIENT_ID, CANVAS_CLIENT_SECRET, CANVAS_REDIRECT_URI/,
);
});
});
+217
View File
@@ -0,0 +1,217 @@
import { describe, it, expect } from 'vitest';
import {
htmlToText,
renderCourseOverview,
renderAssignment,
renderSubmission,
renderDiscussion,
renderPage,
renderModule,
renderEnrollment,
buildCourseContext,
contextNote,
courseSection,
moduleSection,
assignmentSection,
pageSection,
discussionSection,
submissionSection,
enrollmentSection,
} from '../src/course.js';
import type {
Course,
Assignment,
Submission,
Discussion,
Page_,
Module,
Enrollment,
} from '../src/canvas-api.js';
describe('course: htmlToText', () => {
it('strips tags, breaks blocks, and decodes entities', () => {
const html = '<h2>Syllabus</h2><p>Read &amp; annotate ch.&nbsp;1.</p><ul><li>Quiz</li><li>Lab</li></ul>';
const text = htmlToText(html);
expect(text).toContain('Syllabus');
expect(text).toContain('Read & annotate ch. 1.');
expect(text).toContain('• Quiz');
expect(text).toContain('• Lab');
expect(text).not.toContain('<');
});
it('decodes numeric entities and collapses whitespace', () => {
expect(htmlToText('a&#39;b')).toBe("a'b");
expect(htmlToText('x y')).toBe('x y');
});
it('returns empty for empty/whitespace input', () => {
expect(htmlToText('')).toBe('');
expect(htmlToText('<p> </p>')).toBe('');
});
});
const course: Course = {
id: 1,
name: 'Introduction to Biology',
courseCode: 'BIO-101',
workflowState: 'available',
syllabusBody: '<p>Welcome to <strong>BIO-101</strong>. Weekly labs.</p>',
termName: 'Fall 2026',
};
describe('course: record rendering', () => {
it('renders a course overview with the stripped syllabus', () => {
const text = renderCourseOverview(course);
expect(text).toContain('Introduction to Biology (BIO-101)');
expect(text).toContain('Term: Fall 2026');
expect(text).toContain('Syllabus:');
expect(text).toContain('Welcome to BIO-101. Weekly labs.');
expect(text).not.toContain('<strong>');
});
it('renders an assignment with meta and stripped description', () => {
const a: Assignment = {
id: 1,
name: 'Lab Report 1',
description: '<p>Write up the osmosis lab.</p>',
dueAt: '2026-09-15',
pointsPossible: 25,
submissionTypes: ['online_upload'],
};
const text = renderAssignment(a);
expect(text).toContain('Assignment: Lab Report 1');
expect(text).toContain('Due: 2026-09-15 · Points: 25 · Submit: online_upload');
expect(text).toContain('Write up the osmosis lab.');
});
it('renders a submission with score, flags, and comments', () => {
const s: Submission = {
id: 5001,
userId: 900,
assignmentId: 1,
body: '<p>Water moves across the membrane.</p>',
submittedAt: '2026-09-14',
workflowState: 'submitted',
score: 22,
grade: '22',
late: true,
missing: false,
comments: [{ id: 1, authorName: 'Prof. Ada', comment: 'Good start.', createdAt: '2026-09-15' }],
};
const text = renderSubmission(s);
expect(text).toContain('Submission (user 900) [late]');
expect(text).toContain('Status: submitted · Score: 22 · Grade: 22');
expect(text).toContain('Response: Water moves across the membrane.');
expect(text).toContain('Comment (Prof. Ada): Good start.');
});
it('renders a discussion, page, module, and enrollment compactly', () => {
const d: Discussion = { id: 10, title: 'Week 1', message: '<p>Introduce yourself.</p>', postedAt: '', isAnnouncement: false };
expect(renderDiscussion(d)).toContain('Discussion: Week 1');
expect(renderDiscussion(d)).toContain('Introduce yourself.');
const ann: Discussion = { ...d, isAnnouncement: true, title: 'Welcome' };
expect(renderDiscussion(ann)).toContain('Announcement: Welcome');
const p: Page_ = { pageId: 7, url: 'intro', title: 'Week 1 Intro', body: '<p>Read ch. 1.</p>', updatedAt: '' };
expect(renderPage(p)).toContain('Page: Week 1 Intro');
expect(renderPage(p)).toContain('Read ch. 1.');
const m: Module = {
id: 20,
name: 'Cells',
position: 1,
items: [{ id: 1, title: 'Intro page', type: 'Page', position: 1 }],
};
expect(renderModule(m)).toContain('Module: Cells');
expect(renderModule(m)).toContain('- Intro page [Page]');
const e: Enrollment = { id: 30, userId: 900, userName: 'Sam Student', type: 'StudentEnrollment', role: 'StudentEnrollment', state: 'active' };
expect(renderEnrollment(e)).toBe('Sam Student — StudentEnrollment (active)');
});
});
describe('course: buildCourseContext', () => {
it('returns empty for no blocks', () => {
const ctx = buildCourseContext([{ title: 'Assignments', blocks: [] }]);
expect(ctx).toEqual({ text: '', totalBlocks: 0, includedBlocks: 0, truncated: false });
});
it('includes all blocks under section headers when within budget', () => {
const ctx = buildCourseContext([
{ title: 'Modules', blocks: ['a', 'b'] },
{ title: 'Pages', blocks: ['c'] },
]);
expect(ctx.totalBlocks).toBe(3);
expect(ctx.includedBlocks).toBe(3);
expect(ctx.truncated).toBe(false);
expect(ctx.text).toContain('## Modules');
expect(ctx.text).toContain('## Pages');
expect(ctx.text.indexOf('## Modules')).toBeLessThan(ctx.text.indexOf('## Pages'));
});
it('windows in order and reports truncation when the budget is exceeded', () => {
const blocks = ['x'.repeat(30), 'y'.repeat(30), 'z'.repeat(30)];
const ctx = buildCourseContext([{ title: 'Pages', blocks }], 60);
expect(ctx.totalBlocks).toBe(3);
expect(ctx.includedBlocks).toBeLessThan(3);
expect(ctx.truncated).toBe(true);
expect(ctx.text).toContain('xxx');
expect(ctx.text).not.toContain('zzz');
expect(ctx.text.length).toBeLessThanOrEqual(60);
});
it('always includes at least the first block, hard-cutting it if it alone overflows', () => {
const huge = 'q'.repeat(500);
const ctx = buildCourseContext([{ title: 'Pages', blocks: [huge, 'next'] }], 50);
expect(ctx.includedBlocks).toBe(1);
expect(ctx.truncated).toBe(true);
expect(ctx.text.length).toBe(50);
expect(ctx.text.startsWith('## Pages')).toBe(true);
});
it('skips empty sections without charging a header', () => {
const ctx = buildCourseContext([
{ title: 'Empty', blocks: [] },
{ title: 'Pages', blocks: ['a'] },
]);
expect(ctx.text).not.toContain('## Empty');
expect(ctx.text).toContain('## Pages');
expect(ctx.includedBlocks).toBe(1);
});
});
describe('course: contextNote', () => {
it('is honest about no records', () => {
expect(contextNote({ text: '', totalBlocks: 0, includedBlocks: 0, truncated: false })).toMatch(/No course records/);
});
it('reports full coverage', () => {
expect(contextNote({ text: 'x', totalBlocks: 3, includedBlocks: 3, truncated: false })).toMatch(/all 3 items/);
});
it('reports truncation with the counts', () => {
expect(contextNote({ text: 'x', totalBlocks: 10, includedBlocks: 4, truncated: true })).toMatch(/4 of 10 items/);
});
});
describe('course: section builders assemble a real context', () => {
it('turns typed records into a windowed context end to end', () => {
const ctx = buildCourseContext([
courseSection(course),
moduleSection([{ id: 20, name: 'Cells', position: 1, items: [] }]),
assignmentSection([{ id: 1, name: 'Lab 1', description: '', dueAt: '', pointsPossible: 25, submissionTypes: [] }]),
pageSection([{ pageId: 7, url: 'intro', title: 'Intro', body: '', updatedAt: '' }]),
discussionSection([{ id: 10, title: 'Week 1', message: '', postedAt: '', isAnnouncement: false }]),
submissionSection([
{ id: 1, userId: 900, assignmentId: 1, body: '', submittedAt: '', workflowState: 'submitted', score: 22, grade: '22', late: false, missing: false, comments: [] },
]),
enrollmentSection([{ id: 30, userId: 900, userName: 'Sam', type: 'StudentEnrollment', role: 'StudentEnrollment', state: 'active' }]),
]);
expect(ctx.totalBlocks).toBe(7);
expect(ctx.truncated).toBe(false);
expect(ctx.text).toContain('## Course');
expect(ctx.text).toContain('Introduction to Biology');
expect(ctx.text).toContain('## Modules');
expect(ctx.text).toContain('## Assignments');
expect(ctx.text).toContain('## Pages');
expect(ctx.text).toContain('## Discussions');
expect(ctx.text).toContain('## Submissions');
expect(ctx.text).toContain('## Enrollments');
});
});
+125
View File
@@ -0,0 +1,125 @@
import { describe, it, expect, vi } from 'vitest';
import type { AiClient, ChatCompletion, ChatCompletionCreateParams, Model } from '@hanzo/ai';
import {
SYSTEM_PROMPT,
buildMessages,
extractContent,
ask,
listModels,
type CourseMeta,
} from '../src/hanzo.js';
import { buildCourseContext, type CourseContext } from '../src/course.js';
const ctx: CourseContext = buildCourseContext([{ title: 'Assignments', blocks: ['Assignment: Lab Report 1'] }]);
const meta: CourseMeta = { name: 'Intro to Biology', courseCode: 'BIO-101', term: 'Fall 2026' };
// completion builds a minimal @hanzo/ai ChatCompletion with the given content.
function completion(content: ChatCompletion['choices'][number]['message']['content']): ChatCompletion {
return {
id: 'c1',
object: 'chat.completion',
created: 0,
model: 'zen5',
choices: [{ index: 0, message: { role: 'assistant', content }, finish_reason: 'stop' }],
};
}
// mockClient captures the params the code sends and returns a canned completion.
function mockClient(reply: ChatCompletion, models: Model[] = []) {
const create = vi.fn(async (_p: ChatCompletionCreateParams, _o?: { signal?: AbortSignal }) => reply);
const list = vi.fn(async (_o?: { signal?: AbortSignal }) => models);
const client = { chat: { completions: { create } }, models: { list } } as unknown as AiClient;
return { client, create, list };
}
describe('hanzo: buildMessages', () => {
it('produces a grounded system prompt + a fenced user turn with meta + context note', () => {
const msgs = buildMessages('What is due next week?', ctx, meta);
expect(msgs).toHaveLength(2);
expect(msgs[0].role).toBe('system');
expect(msgs[0].content).toBe(SYSTEM_PROMPT);
const user = String(msgs[1].content);
expect(user).toContain('Course: Intro to Biology');
expect(user).toContain('Code: BIO-101');
expect(user).toContain('Term: Fall 2026');
expect(user).toContain('---- course records ----');
expect(user).toContain('Assignment: Lab Report 1');
expect(user).toContain('---- task ----');
expect(user).toContain('What is due next week?');
});
it('omits the header block entirely when meta is undefined', () => {
const user = String(buildMessages('q', ctx).at(1)!.content);
expect(user).not.toContain('Course:');
expect(user).toContain('---- task ----');
});
it('SYSTEM_PROMPT forbids inventing records and marks output a draft', () => {
expect(SYSTEM_PROMPT).toMatch(/never invent/i);
expect(SYSTEM_PROMPT).toMatch(/draft/i);
expect(SYSTEM_PROMPT).toMatch(/not an authoritative grade/i);
});
});
describe('hanzo: extractContent', () => {
it('reads a plain string content', () => {
expect(extractContent(completion('hello'))).toBe('hello');
});
it('concatenates text parts of an array content', () => {
const parts = [
{ type: 'text', text: 'a' },
{ type: 'image_url', image_url: { url: 'x' } },
{ type: 'text', text: 'b' },
] as any;
expect(extractContent(completion(parts))).toBe('ab');
});
it('throws on empty content', () => {
expect(() => extractContent(completion(''))).toThrow(/no content/);
expect(() => extractContent(completion(undefined))).toThrow(/no content/);
});
});
describe('hanzo: ask', () => {
it('sends model + messages non-streaming through the injected client and returns the text', async () => {
const { client, create } = mockClient(completion('due: Lab Report 1'));
const out = await ask('What is due?', ctx, meta, { client, model: 'zen5', temperature: 0.2 });
expect(out).toBe('due: Lab Report 1');
expect(create).toHaveBeenCalledOnce();
const [params, options] = create.mock.calls[0];
expect(params.model).toBe('zen5');
expect(params.stream).toBe(false);
expect(params.temperature).toBe(0.2);
expect(params.messages[0].role).toBe('system');
expect(options).toBeDefined();
});
it('omits temperature from the wire when not provided', async () => {
const { client, create } = mockClient(completion('ok'));
await ask('q', ctx, undefined, { client });
expect('temperature' in create.mock.calls[0][0]).toBe(false);
});
it('defaults the model to zen5', async () => {
const { client, create } = mockClient(completion('ok'));
await ask('q', ctx, undefined, { client });
expect(create.mock.calls[0][0].model).toBe('zen5');
});
it('propagates an abort signal to the client', async () => {
const { client, create } = mockClient(completion('ok'));
const controller = new AbortController();
await ask('q', ctx, undefined, { client, signal: controller.signal });
expect(create.mock.calls[0][1]?.signal).toBe(controller.signal);
});
});
describe('hanzo: listModels', () => {
it('maps the model catalog to ids', async () => {
const models: Model[] = [
{ id: 'zen5', object: 'model' },
{ id: 'zen5-pro', object: 'model' },
];
const { client } = mockClient(completion('x'), models);
expect(await listModels({ client })).toEqual(['zen5', 'zen5-pro']);
});
});
+166
View File
@@ -0,0 +1,166 @@
import { describe, it, expect } from 'vitest';
import {
authorizeUrl,
tokenUrl,
tokenExchange,
refreshExchange,
parseTokenResponse,
carryRefreshToken,
tokenExpiresAt,
isExpired,
} from '../src/canvas-oauth.js';
const HOST = 'school.instructure.com';
describe('oauth: authorizeUrl', () => {
it('builds the consent URL with the standard Canvas params', () => {
const url = new URL(
authorizeUrl({
host: HOST,
clientId: 'cid',
redirectUri: 'https://canvas.hanzo.ai/oauth/callback',
state: 'st-1',
}),
);
expect(url.origin).toBe('https://school.instructure.com');
expect(url.pathname).toBe('/login/oauth2/auth');
expect(url.searchParams.get('response_type')).toBe('code');
expect(url.searchParams.get('client_id')).toBe('cid');
expect(url.searchParams.get('redirect_uri')).toBe('https://canvas.hanzo.ai/oauth/callback');
expect(url.searchParams.get('state')).toBe('st-1');
});
it('omits scope when empty and normalizes a host with a scheme', () => {
const url = new URL(
authorizeUrl({ host: 'https://school.instructure.com/', clientId: 'c', redirectUri: 'https://x/cb', state: 's', scopes: [] }),
);
expect(url.origin).toBe('https://school.instructure.com');
expect(url.searchParams.has('scope')).toBe(false);
});
it('space-joins scopes when present', () => {
const url = new URL(
authorizeUrl({
host: HOST,
clientId: 'c',
redirectUri: 'https://x/cb',
state: 's',
scopes: ['url:GET|/api/v1/courses', 'url:GET|/api/v1/courses/:id'],
}),
);
expect(url.searchParams.get('scope')).toBe('url:GET|/api/v1/courses url:GET|/api/v1/courses/:id');
});
});
describe('oauth: token endpoints', () => {
it('resolves the token URL per host', () => {
expect(tokenUrl(HOST)).toBe('https://school.instructure.com/login/oauth2/token');
expect(tokenUrl('canvas.school.edu')).toBe('https://canvas.school.edu/login/oauth2/token');
});
});
describe('oauth: tokenExchange', () => {
it('form-encodes the code grant with client credentials + redirect_uri in the body', () => {
const req = tokenExchange({
host: HOST,
clientId: 'cid',
clientSecret: 'sec',
code: 'the-code',
redirectUri: 'https://canvas.hanzo.ai/oauth/callback',
});
expect(req.url).toBe('https://school.instructure.com/login/oauth2/token');
expect(req.headers['Content-Type']).toBe('application/x-www-form-urlencoded');
const body = new URLSearchParams(req.body);
expect(body.get('grant_type')).toBe('authorization_code');
expect(body.get('code')).toBe('the-code');
expect(body.get('client_id')).toBe('cid');
expect(body.get('client_secret')).toBe('sec');
expect(body.get('redirect_uri')).toBe('https://canvas.hanzo.ai/oauth/callback');
});
it('never puts the secret in the URL', () => {
const req = tokenExchange({ host: HOST, clientId: 'c', clientSecret: 'SUPER', code: 'x', redirectUri: 'https://x/cb' });
expect(req.url).not.toContain('SUPER');
});
});
describe('oauth: refreshExchange', () => {
it('form-encodes the refresh grant with client credentials and no redirect_uri', () => {
const req = refreshExchange({ host: HOST, clientId: 'cid', clientSecret: 'sec', refreshToken: 'r-1' });
expect(req.url).toBe('https://school.instructure.com/login/oauth2/token');
const body = new URLSearchParams(req.body);
expect(body.get('grant_type')).toBe('refresh_token');
expect(body.get('refresh_token')).toBe('r-1');
expect(body.get('client_id')).toBe('cid');
expect(body.get('client_secret')).toBe('sec');
expect(body.has('code')).toBe(false);
expect(body.has('redirect_uri')).toBe(false);
});
});
describe('oauth: parseTokenResponse', () => {
it('parses a full token set including the Canvas user', () => {
const t = parseTokenResponse({
access_token: 'at',
refresh_token: 'rt',
expires_in: 3600,
token_type: 'Bearer',
user: { id: 7, name: 'Prof. Ada' },
});
expect(t.access_token).toBe('at');
expect(t.refresh_token).toBe('rt');
expect(t.expires_in).toBe(3600);
expect(t.user).toEqual({ id: 7, name: 'Prof. Ada' });
});
it('throws on a Canvas error payload with the description', () => {
expect(() => parseTokenResponse({ error: 'invalid_grant', error_description: 'code used' })).toThrow(/code used/);
});
it('throws when access_token is missing or empty', () => {
expect(() => parseTokenResponse({})).toThrow(/missing access_token/);
expect(() => parseTokenResponse({ access_token: '' })).toThrow(/missing access_token/);
expect(() => parseTokenResponse(null)).toThrow(/empty token response/);
});
it('drops non-string/non-number optional fields defensively', () => {
const t = parseTokenResponse({ access_token: 'at', refresh_token: 123, expires_in: 'soon' });
expect(t.refresh_token).toBeUndefined();
expect(t.expires_in).toBeUndefined();
expect(t.user).toBeUndefined();
});
});
describe('oauth: carryRefreshToken (Canvas does not rotate)', () => {
it('keeps the previous refresh token when the refresh response omits it', () => {
const prev = { access_token: 'a0', refresh_token: 'rt-keep' };
const next = { access_token: 'a1' };
expect(carryRefreshToken(next, prev).refresh_token).toBe('rt-keep');
});
it('uses a new refresh token if one is returned', () => {
const prev = { access_token: 'a0', refresh_token: 'old' };
const next = { access_token: 'a1', refresh_token: 'new' };
expect(carryRefreshToken(next, prev).refresh_token).toBe('new');
});
});
describe('oauth: expiry math', () => {
it('computes expiry from mintedAt + expires_in minus skew', () => {
const t = { access_token: 'a', expires_in: 3600 };
expect(tokenExpiresAt(t, 1000, 60)).toBe(1000 + 3600 - 60);
});
it('treats a token with no expires_in as immediately (skew-)expired', () => {
const t = { access_token: 'a' };
expect(tokenExpiresAt(t, 5000, 0)).toBe(5000);
});
it('reports not-expired before, expired at/after the skewed boundary', () => {
const t = { access_token: 'a', expires_in: 3600 };
const minted = 1000;
const boundary = minted + 3600 - 60;
expect(isExpired(t, minted, boundary - 1, 60)).toBe(false);
expect(isExpired(t, minted, boundary, 60)).toBe(true);
expect(isExpired(t, minted, boundary + 100, 60)).toBe(true);
});
});
+111
View File
@@ -0,0 +1,111 @@
import { describe, it, expect, vi } from 'vitest';
import { parseLaunchContext, proxyUrl, createProxyClient } from '../src/panel.js';
describe('panel: parseLaunchContext', () => {
it('reads a plain course_id', () => {
expect(parseLaunchContext('?course_id=370663')).toEqual({ courseId: '370663' });
});
it('accepts Canvas LTI custom-variable spellings and defaults to empty', () => {
expect(parseLaunchContext('?custom_canvas_course_id=7')).toEqual({ courseId: '7' });
expect(parseLaunchContext('?canvas_course_id=9')).toEqual({ courseId: '9' });
expect(parseLaunchContext('')).toEqual({ courseId: '' });
});
});
describe('panel: proxyUrl', () => {
it('prefixes /proxy and appends a query, dropping empties', () => {
expect(proxyUrl('', '/courses', { page: '', per_page: '100' })).toBe('/proxy/courses?per_page=100');
});
it('expands array values into Canvas key[]=v repetition', () => {
expect(proxyUrl('', '/courses/1', { include: ['syllabus_body'] })).toBe(
'/proxy/courses/1?include%5B%5D=syllabus_body',
);
});
it('strips a trailing slash from the base', () => {
expect(proxyUrl('https://canvas.hanzo.ai/', '/x')).toBe('https://canvas.hanzo.ai/proxy/x');
});
});
// jsonResponse builds a fetch Response-like with an optional Link header.
function jsonResponse(body: unknown, link?: string): Response {
const headers = new Headers({ 'Content-Type': 'application/json' });
if (link) headers.set('Link', link);
return new Response(JSON.stringify(body), { status: 200, headers });
}
// fetchMockOf wraps a responder in a fetch-typed mock so calls[i] carries the
// (url, init) arg tuple TypeScript expects.
function fetchMockOf(responder: () => Response) {
return vi.fn((_url: RequestInfo | URL, _init?: RequestInit) => Promise.resolve(responder()));
}
describe('panel: createProxyClient — scoping + shaping', () => {
it('sends credentials and returns parsed items with the next page from the Link header', async () => {
const link = '<https://school.instructure.com/api/v1/courses?page=2&per_page=100>; rel="next"';
const fetchMock = fetchMockOf(() => jsonResponse([{ id: 1, name: 'Biology' }], link));
const client = createProxyClient({ fetch: fetchMock as any });
const { items, next } = await client.listCourses({ perPage: 100 });
expect(items).toEqual([
{ id: 1, name: 'Biology', courseCode: '', workflowState: '', syllabusBody: '', termName: '' },
]);
expect(next).toBe(2);
const [url, init] = fetchMock.mock.calls[0];
expect(String(url)).toBe('/proxy/courses?per_page=100');
expect((init as RequestInit).credentials).toBe('include');
});
it('has no next page when the Link header omits a next relation', async () => {
const fetchMock = fetchMockOf(() => jsonResponse([]));
const client = createProxyClient({ fetch: fetchMock as any });
const { next } = await client.listCourses();
expect(next).toBeUndefined();
});
it('gets a course with include[]=syllabus_body', async () => {
const fetchMock = fetchMockOf(() => jsonResponse({ id: 1, name: 'Biology', syllabus_body: '<p>Hi</p>' }));
const client = createProxyClient({ fetch: fetchMock as any });
const course = await client.getCourse(1);
expect(course.syllabusBody).toBe('<p>Hi</p>');
expect(String(fetchMock.mock.calls[0][0])).toBe('/proxy/courses/1?include%5B%5D=syllabus_body');
});
it('lists submissions on the assignment path with comments included', async () => {
const fetchMock = fetchMockOf(() => jsonResponse([]));
const client = createProxyClient({ fetch: fetchMock as any });
await client.listSubmissions(100, 55, { page: 2 });
expect(String(fetchMock.mock.calls[0][0])).toBe(
'/proxy/courses/100/assignments/55/submissions?include%5B%5D=submission_comments&page=2',
);
});
it('postSubmissionComment PUTs the comment[text_comment] JSON body', async () => {
const fetchMock = fetchMockOf(() => new Response('{}', { status: 200 }));
const client = createProxyClient({ fetch: fetchMock as any });
await client.postSubmissionComment(100, 55, 900, 'Nice work.');
const [url, init] = fetchMock.mock.calls[0];
expect(String(url)).toBe('/proxy/courses/100/assignments/55/submissions/900');
expect((init as RequestInit).method).toBe('PUT');
expect(JSON.parse(String((init as RequestInit).body))).toEqual({ comment: { text_comment: 'Nice work.' } });
});
it('createAnnouncement POSTs a discussion topic flagged is_announcement', async () => {
const fetchMock = fetchMockOf(() => new Response('{}', { status: 201 }));
const client = createProxyClient({ fetch: fetchMock as any });
await client.createAnnouncement(100, 'Heads up', 'Class is online Friday.');
const [url, init] = fetchMock.mock.calls[0];
expect(String(url)).toBe('/proxy/courses/100/discussion_topics');
expect((init as RequestInit).method).toBe('POST');
expect(JSON.parse(String((init as RequestInit).body))).toEqual({
title: 'Heads up',
message: 'Class is online Friday.',
is_announcement: true,
});
});
it('surfaces a proxy error with status + message', async () => {
const fetchMock = fetchMockOf(() => new Response(JSON.stringify({ error: 'not authenticated' }), { status: 401 }));
const client = createProxyClient({ fetch: fetchMock as any });
await expect(client.listCourses()).rejects.toThrow(/401.*not authenticated/);
});
});
+180
View File
@@ -0,0 +1,180 @@
import { describe, it, expect } from 'vitest';
import {
parseCourse,
parseCourses,
parseAssignment,
parseAssignments,
parseSubmission,
parseSubmissions,
parseDiscussions,
parsePage,
parsePages,
parseModules,
parseEnrollments,
} from '../src/canvas-api.js';
// A realistic Canvas course detail payload (trimmed to fields we surface).
const courseFixture = {
id: 370663,
name: 'Introduction to Biology',
course_code: 'BIO-101',
workflow_state: 'available',
syllabus_body: '<p>Welcome to <strong>BIO-101</strong>.</p>',
term: { id: 5, name: 'Fall 2026' },
};
describe('parse: course', () => {
it('reads name, code, state, syllabus, and term name', () => {
const c = parseCourse(courseFixture);
expect(c.id).toBe(370663);
expect(c.name).toBe('Introduction to Biology');
expect(c.courseCode).toBe('BIO-101');
expect(c.workflowState).toBe('available');
expect(c.syllabusBody).toContain('<strong>BIO-101</strong>');
expect(c.termName).toBe('Fall 2026');
});
it('normalizes a bare array and drops rows without an id', () => {
const rows = parseCourses([courseFixture, { name: 'no id' }, { id: 0, name: 'bad' }]);
expect(rows).toHaveLength(1);
expect(rows[0].courseCode).toBe('BIO-101');
});
it('reads a wrapped { courses } shape and defaults a missing term', () => {
const rows = parseCourses({ courses: [{ id: 2, name: 'Annex' }] });
expect(rows[0].termName).toBe('');
expect(rows[0].syllabusBody).toBe('');
});
});
describe('parse: assignments', () => {
it('reads name, description, due date, points, and submission types', () => {
const a = parseAssignment({
id: 1,
name: 'Lab Report 1',
description: '<p>Write up the osmosis lab.</p>',
due_at: '2026-09-15T23:59:00Z',
points_possible: 25,
submission_types: ['online_text_entry', 'online_upload'],
});
expect(a).toEqual({
id: 1,
name: 'Lab Report 1',
description: '<p>Write up the osmosis lab.</p>',
dueAt: '2026-09-15T23:59:00Z',
pointsPossible: 25,
submissionTypes: ['online_text_entry', 'online_upload'],
});
});
it('parses an array and drops idless rows', () => {
const rows = parseAssignments([{ id: 1, name: 'A' }, { name: 'no id' }]);
expect(rows).toHaveLength(1);
expect(rows[0].submissionTypes).toEqual([]);
});
});
describe('parse: submissions', () => {
const submissionFixture = {
id: 5001,
user_id: 900,
assignment_id: 1,
body: '<p>Osmosis moves water across a membrane.</p>',
submitted_at: '2026-09-14T10:00:00Z',
workflow_state: 'submitted',
score: 22,
grade: '22',
late: true,
missing: false,
submission_comments: [
{ id: 1, author_name: 'Prof. Ada', comment: 'Good start.', created_at: '2026-09-15T09:00:00Z' },
],
};
it('reads score, grade, flags, body, and the comment thread', () => {
const s = parseSubmission(submissionFixture);
expect(s.userId).toBe(900);
expect(s.workflowState).toBe('submitted');
expect(s.score).toBe(22);
expect(s.grade).toBe('22');
expect(s.late).toBe(true);
expect(s.missing).toBe(false);
expect(s.body).toContain('Osmosis');
expect(s.comments).toHaveLength(1);
expect(s.comments[0].authorName).toBe('Prof. Ada');
expect(s.comments[0].comment).toBe('Good start.');
});
it('treats a null score/grade as null/empty and no comments as []', () => {
const s = parseSubmission({ id: 1, user_id: 2, score: null, grade: null, workflow_state: 'unsubmitted' });
expect(s.score).toBeNull();
expect(s.grade).toBe('');
expect(s.comments).toEqual([]);
});
it('keeps a row that has a user id even without a submission id', () => {
const rows = parseSubmissions([{ user_id: 900, workflow_state: 'unsubmitted' }, {}]);
expect(rows).toHaveLength(1);
expect(rows[0].userId).toBe(900);
});
});
describe('parse: discussions', () => {
it('reads title, message, and the announcement flag', () => {
const rows = parseDiscussions([
{ id: 10, title: 'Week 1 discussion', message: '<p>Introduce yourself.</p>', posted_at: '2026-09-01T00:00:00Z' },
{ id: 11, title: 'Welcome', message: '<p>Hi all</p>', is_announcement: true },
]);
expect(rows).toHaveLength(2);
expect(rows[0].title).toBe('Week 1 discussion');
expect(rows[0].isAnnouncement).toBe(false);
expect(rows[1].isAnnouncement).toBe(true);
});
});
describe('parse: pages', () => {
it('reads a page detail with its body', () => {
const p = parsePage({ page_id: 7, url: 'week-1-intro', title: 'Week 1 Intro', body: '<p>Read chapter 1.</p>', updated_at: '2026-09-01T00:00:00Z' });
expect(p).toEqual({ pageId: 7, url: 'week-1-intro', title: 'Week 1 Intro', body: '<p>Read chapter 1.</p>', updatedAt: '2026-09-01T00:00:00Z' });
});
it('keeps a list row with a url even without a page_id', () => {
const rows = parsePages([{ url: 'syllabus', title: 'Syllabus' }, { title: 'no url or id' }]);
expect(rows).toHaveLength(1);
expect(rows[0].url).toBe('syllabus');
});
});
describe('parse: modules', () => {
it('reads modules with inlined items', () => {
const mods = parseModules([
{
id: 20,
name: 'Cells',
position: 1,
items: [
{ id: 1, title: 'Intro page', type: 'Page', position: 1 },
{ id: 2, title: 'Lab Report 1', type: 'Assignment', position: 2 },
],
},
]);
expect(mods[0].name).toBe('Cells');
expect(mods[0].items).toHaveLength(2);
expect(mods[0].items[1]).toEqual({ id: 2, title: 'Lab Report 1', type: 'Assignment', position: 2 });
});
it('tolerates a module with no items', () => {
expect(parseModules([{ id: 1, name: 'Empty' }])[0].items).toEqual([]);
});
});
describe('parse: enrollments', () => {
it('reads the person, role, type, and state', () => {
const rows = parseEnrollments([
{ id: 30, user_id: 900, user: { name: 'Sam Student' }, type: 'StudentEnrollment', role: 'StudentEnrollment', enrollment_state: 'active' },
]);
expect(rows[0]).toEqual({
id: 30,
userId: 900,
userName: 'Sam Student',
type: 'StudentEnrollment',
role: 'StudentEnrollment',
state: 'active',
});
});
});
+15
View File
@@ -0,0 +1,15 @@
{
"compilerOptions": {
"target": "ES2020",
"module": "ESNext",
"moduleResolution": "bundler",
"lib": ["ES2020", "DOM", "DOM.Iterable"],
"types": ["node"],
"strict": true,
"noEmit": true,
"esModuleInterop": true,
"skipLibCheck": true,
"forceConsistentCasingInFileNames": true
},
"include": ["src/**/*.ts", "test/**/*.ts"]
}
+8
View File
@@ -0,0 +1,8 @@
import { defineConfig } from 'vitest/config';
export default defineConfig({
test: {
include: ['test/**/*.test.ts'],
environment: 'node',
},
});
+1
View File
@@ -3,6 +3,7 @@ packages:
- 'packages/auth'
- 'packages/browser'
- 'packages/canva'
- 'packages/canvas-lms'
- 'packages/cards'
- 'packages/clio'
- 'packages/desktop'