amicooked 0.0.0-stage → 0.1.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +23 -0
- package/README.md +88 -2
- package/dist/auth.js +171 -0
- package/dist/browser.js +141 -0
- package/dist/cdp.js +62 -0
- package/dist/cli/manage.js +97 -0
- package/dist/cli/serve.js +84 -0
- package/dist/cli/setup.js +231 -0
- package/dist/cli.js +78 -0
- package/dist/client.js +129 -0
- package/dist/clients/chatgpt.js +30 -0
- package/dist/clients/claudeCode.js +43 -0
- package/dist/clients/claudeDesktop.js +118 -0
- package/dist/clients/codex.js +117 -0
- package/dist/clients/self.js +26 -0
- package/dist/config.js +76 -0
- package/dist/courseResolver.js +80 -0
- package/dist/extract.js +60 -0
- package/dist/instructions.js +6 -0
- package/dist/library.js +186 -0
- package/dist/remote/http.js +150 -0
- package/dist/remote/oauth.js +159 -0
- package/dist/remote/service.js +119 -0
- package/dist/remote/tunnel.js +99 -0
- package/dist/schools.js +82 -0
- package/dist/server.js +40 -0
- package/dist/skill.js +2 -0
- package/dist/tools/content.js +24 -0
- package/dist/tools/cooked.js +287 -0
- package/dist/tools/courses.js +28 -0
- package/dist/tools/deadlines.js +59 -0
- package/dist/tools/files.js +143 -0
- package/dist/tools/types.js +1 -0
- package/dist/utils/dateEvent.js +239 -0
- package/dist/utils/marshal.js +247 -0
- package/dist/version.js +2 -0
- package/package.json +54 -4
- package/skill/SKILL.md +58 -0
|
@@ -0,0 +1,150 @@
|
|
|
1
|
+
import * as http from "http";
|
|
2
|
+
import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js";
|
|
3
|
+
import { serverInstructions } from "../instructions.js";
|
|
4
|
+
import { createServer } from "../server.js";
|
|
5
|
+
import { OAuthError, OAuthStore } from "./oauth.js";
|
|
6
|
+
export const DEFAULT_PORT = 8787;
|
|
7
|
+
const MAX_BODY = 1024 * 1024;
|
|
8
|
+
const escapeHtml = (s) => s.replace(/[&<>"']/g, (c) => `&#${c.charCodeAt(0)};`);
|
|
9
|
+
function send(res, status, body, headers = {}) {
|
|
10
|
+
const text = typeof body === "string" ? body : JSON.stringify(body);
|
|
11
|
+
res.writeHead(status, {
|
|
12
|
+
"Content-Type": typeof body === "string" ? "text/html; charset=utf-8" : "application/json",
|
|
13
|
+
"Cache-Control": "no-store",
|
|
14
|
+
...headers,
|
|
15
|
+
});
|
|
16
|
+
res.end(text);
|
|
17
|
+
}
|
|
18
|
+
async function readBody(req) {
|
|
19
|
+
const chunks = [];
|
|
20
|
+
let size = 0;
|
|
21
|
+
for await (const chunk of req) {
|
|
22
|
+
size += chunk.length;
|
|
23
|
+
if (size > MAX_BODY)
|
|
24
|
+
throw new OAuthError("invalid_request", "Request too large", 413);
|
|
25
|
+
chunks.push(chunk);
|
|
26
|
+
}
|
|
27
|
+
const raw = Buffer.concat(chunks).toString("utf8");
|
|
28
|
+
if (!raw)
|
|
29
|
+
return {};
|
|
30
|
+
if ((req.headers["content-type"] ?? "").includes("application/json"))
|
|
31
|
+
return JSON.parse(raw);
|
|
32
|
+
return Object.fromEntries(new URLSearchParams(raw));
|
|
33
|
+
}
|
|
34
|
+
function consentPage(params, clientName, error) {
|
|
35
|
+
const hidden = ["client_id", "redirect_uri", "state", "code_challenge", "code_challenge_method"]
|
|
36
|
+
.map((k) => `<input type="hidden" name="${k}" value="${escapeHtml(params[k] ?? "")}">`)
|
|
37
|
+
.join("");
|
|
38
|
+
return `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
|
|
39
|
+
<title>Connect Am I Cooked</title>
|
|
40
|
+
<style>
|
|
41
|
+
body{margin:0;min-height:100vh;display:grid;place-items:center;background:#F7F3EC;color:#1A1714;font:16px/1.5 system-ui,sans-serif;padding:16px}
|
|
42
|
+
main{max-width:380px;width:100%}h1{font-size:28px;margin:0 0 8px}p{color:#6B645C;margin:0 0 20px}
|
|
43
|
+
input[name=pairing_code]{width:100%;box-sizing:border-box;font:600 28px ui-monospace,monospace;letter-spacing:.3em;text-align:center;padding:12px;border:1px solid #E4DDD2;border-radius:10px;background:#fff}
|
|
44
|
+
button{margin-top:12px;width:100%;padding:12px;border:0;border-radius:10px;background:#1A1714;color:#F7F3EC;font:600 16px system-ui}
|
|
45
|
+
.error{color:#B42318;margin:0 0 12px}code{background:#EFE8DC;padding:1px 5px;border-radius:5px}
|
|
46
|
+
</style></head><body><main>
|
|
47
|
+
<h1>Connect ${escapeHtml(clientName)}</h1>
|
|
48
|
+
<p>Enter the 6-digit code from <code>amicooked pair</code> on your computer. It lets ${escapeHtml(clientName)} read your courses through Am I Cooked.</p>
|
|
49
|
+
${error ? `<p class="error">${escapeHtml(error)}</p>` : ""}
|
|
50
|
+
<form method="post" action="/authorize">${hidden}
|
|
51
|
+
<input name="pairing_code" inputmode="numeric" autocomplete="one-time-code" maxlength="7" required autofocus aria-label="Pairing code">
|
|
52
|
+
<button type="submit">Connect</button></form></main></body></html>`;
|
|
53
|
+
}
|
|
54
|
+
/** HTTP MCP server with OAuth, for ChatGPT and other remote clients. Listens on loopback only. */
|
|
55
|
+
export function createRemoteServer({ publicUrl, store = new OAuthStore() }) {
|
|
56
|
+
const base = publicUrl.replace(/\/+$/, "");
|
|
57
|
+
const resourceMetadata = `${base}/.well-known/oauth-protected-resource`;
|
|
58
|
+
return http.createServer(async (req, res) => {
|
|
59
|
+
const url = new URL(req.url ?? "/", base);
|
|
60
|
+
const route = `${req.method} ${url.pathname}`;
|
|
61
|
+
try {
|
|
62
|
+
if (req.method === "GET" && url.pathname.startsWith("/.well-known/oauth-protected-resource")) {
|
|
63
|
+
return send(res, 200, { resource: `${base}/mcp`, authorization_servers: [base], bearer_methods_supported: ["header"] });
|
|
64
|
+
}
|
|
65
|
+
if (req.method === "GET" && url.pathname.startsWith("/.well-known/oauth-authorization-server")) {
|
|
66
|
+
return send(res, 200, {
|
|
67
|
+
issuer: base,
|
|
68
|
+
authorization_endpoint: `${base}/authorize`,
|
|
69
|
+
token_endpoint: `${base}/token`,
|
|
70
|
+
registration_endpoint: `${base}/register`,
|
|
71
|
+
response_types_supported: ["code"],
|
|
72
|
+
grant_types_supported: ["authorization_code", "refresh_token"],
|
|
73
|
+
code_challenge_methods_supported: ["S256"],
|
|
74
|
+
token_endpoint_auth_methods_supported: ["none"],
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
if (route === "POST /register") {
|
|
78
|
+
return send(res, 201, { ...store.register(await readBody(req)), token_endpoint_auth_method: "none" });
|
|
79
|
+
}
|
|
80
|
+
if (route === "GET /authorize") {
|
|
81
|
+
const params = Object.fromEntries(url.searchParams);
|
|
82
|
+
if (params.response_type !== "code")
|
|
83
|
+
throw new OAuthError("unsupported_response_type", "Only response_type=code is supported");
|
|
84
|
+
return send(res, 200, consentPage(params, store.clientName(params.client_id, params.redirect_uri)));
|
|
85
|
+
}
|
|
86
|
+
if (route === "POST /authorize") {
|
|
87
|
+
const params = await readBody(req);
|
|
88
|
+
const clientName = store.clientName(params.client_id, params.redirect_uri);
|
|
89
|
+
try {
|
|
90
|
+
const code = store.authorize({
|
|
91
|
+
clientId: params.client_id,
|
|
92
|
+
redirectUri: params.redirect_uri,
|
|
93
|
+
challenge: params.code_challenge,
|
|
94
|
+
method: params.code_challenge_method,
|
|
95
|
+
pairingCode: String(params.pairing_code ?? ""),
|
|
96
|
+
});
|
|
97
|
+
const target = new URL(params.redirect_uri);
|
|
98
|
+
target.searchParams.set("code", code);
|
|
99
|
+
if (params.state)
|
|
100
|
+
target.searchParams.set("state", params.state);
|
|
101
|
+
res.writeHead(302, { Location: target.toString(), "Cache-Control": "no-store" });
|
|
102
|
+
return res.end();
|
|
103
|
+
}
|
|
104
|
+
catch (error) {
|
|
105
|
+
if (!(error instanceof OAuthError) || error.status !== 403)
|
|
106
|
+
throw error;
|
|
107
|
+
return send(res, 403, consentPage(params, clientName, error.message));
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
if (route === "POST /token") {
|
|
111
|
+
const body = await readBody(req);
|
|
112
|
+
if (body.grant_type === "authorization_code") {
|
|
113
|
+
return send(res, 200, store.exchangeCode({ code: body.code, clientId: body.client_id, redirectUri: body.redirect_uri, verifier: body.code_verifier }));
|
|
114
|
+
}
|
|
115
|
+
if (body.grant_type === "refresh_token") {
|
|
116
|
+
return send(res, 200, store.refresh({ refreshToken: body.refresh_token, clientId: body.client_id }));
|
|
117
|
+
}
|
|
118
|
+
throw new OAuthError("unsupported_grant_type", "Use authorization_code or refresh_token");
|
|
119
|
+
}
|
|
120
|
+
if (url.pathname === "/mcp") {
|
|
121
|
+
const auth = req.headers.authorization ?? "";
|
|
122
|
+
if (!auth.startsWith("Bearer ") || !store.verifyAccessToken(auth.slice(7))) {
|
|
123
|
+
return send(res, 401, { error: "invalid_token" }, { "WWW-Authenticate": `Bearer resource_metadata="${resourceMetadata}"` });
|
|
124
|
+
}
|
|
125
|
+
if (req.method !== "POST")
|
|
126
|
+
return send(res, 405, { error: "method_not_allowed" }, { Allow: "POST" });
|
|
127
|
+
// Stateless: a fresh server per request, JSON responses (no SSE, which quick tunnels drop)
|
|
128
|
+
const server = createServer({ instructions: serverInstructions() });
|
|
129
|
+
const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true });
|
|
130
|
+
res.on("close", () => {
|
|
131
|
+
transport.close().catch(() => { });
|
|
132
|
+
server.close().catch(() => { });
|
|
133
|
+
});
|
|
134
|
+
await server.connect(transport);
|
|
135
|
+
return await transport.handleRequest(req, res, await readBody(req));
|
|
136
|
+
}
|
|
137
|
+
return send(res, 404, { error: "not_found" });
|
|
138
|
+
}
|
|
139
|
+
catch (error) {
|
|
140
|
+
if (res.headersSent)
|
|
141
|
+
return;
|
|
142
|
+
if (error instanceof OAuthError)
|
|
143
|
+
return send(res, error.status, { error: error.code, error_description: error.message });
|
|
144
|
+
if (error instanceof SyntaxError)
|
|
145
|
+
return send(res, 400, { error: "invalid_request", error_description: "Malformed body" });
|
|
146
|
+
console.error(`[http] ${route} failed: ${error instanceof Error ? error.message : error}`);
|
|
147
|
+
return send(res, 500, { error: "server_error" });
|
|
148
|
+
}
|
|
149
|
+
});
|
|
150
|
+
}
|
|
@@ -0,0 +1,159 @@
|
|
|
1
|
+
import { createHash, randomBytes, randomInt, timingSafeEqual } from "crypto";
|
|
2
|
+
import * as fs from "fs";
|
|
3
|
+
import { paths, writePrivateFile } from "../config.js";
|
|
4
|
+
/**
|
|
5
|
+
* A tiny OAuth 2.1 authorization server for remote MCP clients like ChatGPT:
|
|
6
|
+
* dynamic client registration, authorization code + PKCE (S256), refresh tokens.
|
|
7
|
+
* Consent needs a short pairing code shown on the student's own computer, so
|
|
8
|
+
* someone who finds the public URL can't connect themselves.
|
|
9
|
+
*/
|
|
10
|
+
const ACCESS_TTL_MS = 60 * 60 * 1000;
|
|
11
|
+
const REFRESH_TTL_MS = 90 * 24 * 60 * 60 * 1000;
|
|
12
|
+
const CODE_TTL_MS = 5 * 60 * 1000;
|
|
13
|
+
const PAIRING_TTL_MS = 10 * 60 * 1000;
|
|
14
|
+
const PAIRING_MAX_ATTEMPTS = 5;
|
|
15
|
+
export class OAuthError extends Error {
|
|
16
|
+
code;
|
|
17
|
+
status;
|
|
18
|
+
constructor(code, message, status = 400) {
|
|
19
|
+
super(message);
|
|
20
|
+
this.code = code;
|
|
21
|
+
this.status = status;
|
|
22
|
+
}
|
|
23
|
+
}
|
|
24
|
+
const sha256 = (s) => createHash("sha256").update(s).digest("hex");
|
|
25
|
+
const b64url = (buf) => buf.toString("base64url");
|
|
26
|
+
const secret = () => b64url(randomBytes(32));
|
|
27
|
+
function sameHash(a, b) {
|
|
28
|
+
const x = Buffer.from(a, "hex");
|
|
29
|
+
const y = Buffer.from(b, "hex");
|
|
30
|
+
return x.length === y.length && timingSafeEqual(x, y);
|
|
31
|
+
}
|
|
32
|
+
/** Redirects must go to an https URL (or loopback during development). */
|
|
33
|
+
function validRedirect(uri) {
|
|
34
|
+
try {
|
|
35
|
+
const u = new URL(uri);
|
|
36
|
+
return u.protocol === "https:" || (u.protocol === "http:" && ["127.0.0.1", "localhost", "[::1]"].includes(u.hostname));
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
return false;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
export class OAuthStore {
|
|
43
|
+
file;
|
|
44
|
+
now;
|
|
45
|
+
constructor(file = paths().oauth, now = () => Date.now()) {
|
|
46
|
+
this.file = file;
|
|
47
|
+
this.now = now;
|
|
48
|
+
}
|
|
49
|
+
load() {
|
|
50
|
+
try {
|
|
51
|
+
return JSON.parse(fs.readFileSync(this.file, "utf8"));
|
|
52
|
+
}
|
|
53
|
+
catch {
|
|
54
|
+
return { clients: {}, codes: {}, tokens: {} };
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
save(state) {
|
|
58
|
+
const t = this.now();
|
|
59
|
+
// Drop anything expired so the file doesn't grow forever
|
|
60
|
+
for (const [k, v] of Object.entries(state.codes))
|
|
61
|
+
if (v.expiresAt < t)
|
|
62
|
+
delete state.codes[k];
|
|
63
|
+
for (const [k, v] of Object.entries(state.tokens))
|
|
64
|
+
if (v.expiresAt < t)
|
|
65
|
+
delete state.tokens[k];
|
|
66
|
+
writePrivateFile(this.file, JSON.stringify(state));
|
|
67
|
+
}
|
|
68
|
+
/** A fresh 6-digit pairing code for the student to type into ChatGPT's consent page. */
|
|
69
|
+
newPairingCode() {
|
|
70
|
+
const code = String(randomInt(0, 1_000_000)).padStart(6, "0");
|
|
71
|
+
const state = this.load();
|
|
72
|
+
state.pairing = { hash: sha256(code), expiresAt: this.now() + PAIRING_TTL_MS, attempts: 0 };
|
|
73
|
+
this.save(state);
|
|
74
|
+
return code;
|
|
75
|
+
}
|
|
76
|
+
register(body) {
|
|
77
|
+
const uris = Array.isArray(body.redirect_uris) ? body.redirect_uris.filter((u) => typeof u === "string") : [];
|
|
78
|
+
if (!uris.length || !uris.every(validRedirect))
|
|
79
|
+
throw new OAuthError("invalid_redirect_uri", "redirect_uris must be https URLs");
|
|
80
|
+
const state = this.load();
|
|
81
|
+
if (Object.keys(state.clients).length >= 50)
|
|
82
|
+
throw new OAuthError("invalid_client_metadata", "Too many registered clients");
|
|
83
|
+
const id = secret();
|
|
84
|
+
const name = (body.client_name ?? "AI app").slice(0, 80);
|
|
85
|
+
state.clients[id] = { name, redirectUris: uris, createdAt: this.now() };
|
|
86
|
+
this.save(state);
|
|
87
|
+
return { client_id: id, client_name: name, redirect_uris: uris };
|
|
88
|
+
}
|
|
89
|
+
clientName(clientId, redirectUri) {
|
|
90
|
+
const client = this.load().clients[clientId];
|
|
91
|
+
if (!client)
|
|
92
|
+
throw new OAuthError("invalid_client", "Unknown client");
|
|
93
|
+
if (!client.redirectUris.includes(redirectUri))
|
|
94
|
+
throw new OAuthError("invalid_request", "redirect_uri doesn't match the registration");
|
|
95
|
+
return client.name;
|
|
96
|
+
}
|
|
97
|
+
/** Check the pairing code and issue an authorization code bound to the PKCE challenge. */
|
|
98
|
+
authorize(params) {
|
|
99
|
+
this.clientName(params.clientId, params.redirectUri);
|
|
100
|
+
if (params.method !== "S256" || !/^[A-Za-z0-9_-]{43}$/.test(params.challenge)) {
|
|
101
|
+
throw new OAuthError("invalid_request", "PKCE with S256 is required");
|
|
102
|
+
}
|
|
103
|
+
const state = this.load();
|
|
104
|
+
const pairing = state.pairing;
|
|
105
|
+
if (!pairing || pairing.expiresAt < this.now() || pairing.attempts >= PAIRING_MAX_ATTEMPTS) {
|
|
106
|
+
throw new OAuthError("access_denied", "That pairing code expired. Run `amicooked pair` for a new one.", 403);
|
|
107
|
+
}
|
|
108
|
+
if (!sameHash(sha256(params.pairingCode.replace(/\D/g, "")), pairing.hash)) {
|
|
109
|
+
pairing.attempts++;
|
|
110
|
+
this.save(state);
|
|
111
|
+
throw new OAuthError("access_denied", "Wrong pairing code. Check the code from `amicooked pair`.", 403);
|
|
112
|
+
}
|
|
113
|
+
delete state.pairing; // one use
|
|
114
|
+
const code = secret();
|
|
115
|
+
state.codes[sha256(code)] = { clientId: params.clientId, redirectUri: params.redirectUri, challenge: params.challenge, expiresAt: this.now() + CODE_TTL_MS };
|
|
116
|
+
this.save(state);
|
|
117
|
+
return code;
|
|
118
|
+
}
|
|
119
|
+
issue(state, clientId) {
|
|
120
|
+
const access = secret();
|
|
121
|
+
const refresh = secret();
|
|
122
|
+
state.tokens[sha256(access)] = { clientId, kind: "access", expiresAt: this.now() + ACCESS_TTL_MS };
|
|
123
|
+
state.tokens[sha256(refresh)] = { clientId, kind: "refresh", expiresAt: this.now() + REFRESH_TTL_MS };
|
|
124
|
+
this.save(state);
|
|
125
|
+
return { access_token: access, token_type: "Bearer", expires_in: ACCESS_TTL_MS / 1000, refresh_token: refresh };
|
|
126
|
+
}
|
|
127
|
+
exchangeCode(params) {
|
|
128
|
+
const state = this.load();
|
|
129
|
+
const key = sha256(params.code);
|
|
130
|
+
const grant = state.codes[key];
|
|
131
|
+
delete state.codes[key]; // codes are single-use even when the exchange fails
|
|
132
|
+
this.save(state);
|
|
133
|
+
if (!grant || grant.expiresAt < this.now())
|
|
134
|
+
throw new OAuthError("invalid_grant", "Authorization code is invalid or expired");
|
|
135
|
+
if (grant.clientId !== params.clientId || grant.redirectUri !== params.redirectUri)
|
|
136
|
+
throw new OAuthError("invalid_grant", "Code was issued to another client");
|
|
137
|
+
if (b64url(createHash("sha256").update(params.verifier).digest()) !== grant.challenge)
|
|
138
|
+
throw new OAuthError("invalid_grant", "PKCE verification failed");
|
|
139
|
+
return this.issue(this.load(), grant.clientId);
|
|
140
|
+
}
|
|
141
|
+
refresh(params) {
|
|
142
|
+
const state = this.load();
|
|
143
|
+
const key = sha256(params.refreshToken);
|
|
144
|
+
const token = state.tokens[key];
|
|
145
|
+
if (!token || token.kind !== "refresh" || token.expiresAt < this.now() || token.clientId !== params.clientId) {
|
|
146
|
+
throw new OAuthError("invalid_grant", "Refresh token is invalid or expired");
|
|
147
|
+
}
|
|
148
|
+
delete state.tokens[key]; // rotate
|
|
149
|
+
return this.issue(state, token.clientId);
|
|
150
|
+
}
|
|
151
|
+
verifyAccessToken(token) {
|
|
152
|
+
const entry = this.load().tokens[sha256(token)];
|
|
153
|
+
return Boolean(entry && entry.kind === "access" && entry.expiresAt > this.now());
|
|
154
|
+
}
|
|
155
|
+
/** Disconnect every remote app, e.g. when the student turns ChatGPT off. */
|
|
156
|
+
revokeAll() {
|
|
157
|
+
this.save({ clients: {}, codes: {}, tokens: {} });
|
|
158
|
+
}
|
|
159
|
+
}
|
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import { spawnSync } from "child_process";
|
|
2
|
+
import * as fs from "fs";
|
|
3
|
+
import * as os from "os";
|
|
4
|
+
import * as path from "path";
|
|
5
|
+
import { paths } from "../config.js";
|
|
6
|
+
/**
|
|
7
|
+
* Keeps `amicooked serve` running in the student's login session, so ChatGPT can reach
|
|
8
|
+
* it whenever the computer is on: a LaunchAgent on macOS, a logon task on Windows,
|
|
9
|
+
* a systemd user unit on Linux.
|
|
10
|
+
*/
|
|
11
|
+
const LABEL = "app.amicooked.serve";
|
|
12
|
+
const TASK = "Am I Cooked";
|
|
13
|
+
const xml = (s) => s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
14
|
+
export function launchAgentPlist(launch, logFile) {
|
|
15
|
+
const args = [launch.command, ...launch.args].map((a) => ` <string>${xml(a)}</string>`).join("\n");
|
|
16
|
+
const env = Object.entries(launch.env ?? {})
|
|
17
|
+
.map(([k, v]) => ` <key>${xml(k)}</key>\n <string>${xml(v)}</string>`)
|
|
18
|
+
.join("\n");
|
|
19
|
+
return `<?xml version="1.0" encoding="UTF-8"?>
|
|
20
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
21
|
+
<plist version="1.0">
|
|
22
|
+
<dict>
|
|
23
|
+
<key>Label</key>
|
|
24
|
+
<string>${LABEL}</string>
|
|
25
|
+
<key>ProgramArguments</key>
|
|
26
|
+
<array>
|
|
27
|
+
${args}
|
|
28
|
+
</array>
|
|
29
|
+
${env ? ` <key>EnvironmentVariables</key>\n <dict>\n${env}\n </dict>\n` : ""} <key>RunAtLoad</key>
|
|
30
|
+
<true/>
|
|
31
|
+
<key>KeepAlive</key>
|
|
32
|
+
<true/>
|
|
33
|
+
<key>StandardOutPath</key>
|
|
34
|
+
<string>${xml(logFile)}</string>
|
|
35
|
+
<key>StandardErrorPath</key>
|
|
36
|
+
<string>${xml(logFile)}</string>
|
|
37
|
+
</dict>
|
|
38
|
+
</plist>
|
|
39
|
+
`;
|
|
40
|
+
}
|
|
41
|
+
export function systemdUnit(launch) {
|
|
42
|
+
const quote = (a) => (/[\s"\\]/.test(a) ? `"${a.replace(/(["\\])/g, "\\$1")}"` : a);
|
|
43
|
+
const env = Object.entries(launch.env ?? {}).map(([k, v]) => `Environment=${quote(`${k}=${v}`)}\n`).join("");
|
|
44
|
+
return `[Unit]
|
|
45
|
+
Description=Am I Cooked (ChatGPT connection)
|
|
46
|
+
After=network-online.target
|
|
47
|
+
|
|
48
|
+
[Service]
|
|
49
|
+
ExecStart=${[launch.command, ...launch.args].map(quote).join(" ")}
|
|
50
|
+
${env}Restart=always
|
|
51
|
+
RestartSec=10
|
|
52
|
+
|
|
53
|
+
[Install]
|
|
54
|
+
WantedBy=default.target
|
|
55
|
+
`;
|
|
56
|
+
}
|
|
57
|
+
/** Windows runs console programs in a visible window; a VBScript wrapper starts it hidden. */
|
|
58
|
+
export function hiddenLauncherVbs(launch) {
|
|
59
|
+
const cmd = [launch.command, ...launch.args].map((a) => `""${a}""`).join(" ");
|
|
60
|
+
return `CreateObject("Wscript.Shell").Run "${cmd}", 0, False\r\n`;
|
|
61
|
+
}
|
|
62
|
+
function run(cmd, args) {
|
|
63
|
+
const result = spawnSync(cmd, args, { encoding: "utf8" });
|
|
64
|
+
if (result.error || result.status !== 0) {
|
|
65
|
+
throw new Error(`${cmd} ${args[0]} failed: ${(result.stderr || result.error?.message || "").trim()}`);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
const plistPath = () => path.join(os.homedir(), "Library", "LaunchAgents", `${LABEL}.plist`);
|
|
69
|
+
const unitPath = () => path.join(os.homedir(), ".config", "systemd", "user", "amicooked.service");
|
|
70
|
+
const vbsPath = () => path.join(paths().bin, "amicooked-serve.vbs");
|
|
71
|
+
/** Install (or replace) the background service running `launch`, and start it now. */
|
|
72
|
+
export function installService(launch) {
|
|
73
|
+
fs.mkdirSync(paths().logs, { recursive: true });
|
|
74
|
+
if (process.platform === "darwin") {
|
|
75
|
+
const uid = String(os.userInfo().uid);
|
|
76
|
+
fs.mkdirSync(path.dirname(plistPath()), { recursive: true });
|
|
77
|
+
spawnSync("launchctl", ["bootout", `gui/${uid}`, plistPath()]);
|
|
78
|
+
fs.writeFileSync(plistPath(), launchAgentPlist(launch, path.join(paths().logs, "serve.log")));
|
|
79
|
+
run("launchctl", ["bootstrap", `gui/${uid}`, plistPath()]);
|
|
80
|
+
}
|
|
81
|
+
else if (process.platform === "win32") {
|
|
82
|
+
fs.mkdirSync(paths().bin, { recursive: true });
|
|
83
|
+
fs.writeFileSync(vbsPath(), hiddenLauncherVbs(launch));
|
|
84
|
+
run("schtasks", ["/Create", "/F", "/TN", TASK, "/SC", "ONLOGON", "/RL", "LIMITED", "/TR", `wscript.exe "${vbsPath()}"`]);
|
|
85
|
+
run("schtasks", ["/Run", "/TN", TASK]);
|
|
86
|
+
}
|
|
87
|
+
else {
|
|
88
|
+
fs.mkdirSync(path.dirname(unitPath()), { recursive: true });
|
|
89
|
+
fs.writeFileSync(unitPath(), systemdUnit(launch));
|
|
90
|
+
run("systemctl", ["--user", "daemon-reload"]);
|
|
91
|
+
run("systemctl", ["--user", "enable", "--now", "amicooked.service"]);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
export function uninstallService() {
|
|
95
|
+
if (process.platform === "darwin") {
|
|
96
|
+
if (!fs.existsSync(plistPath()))
|
|
97
|
+
return false;
|
|
98
|
+
spawnSync("launchctl", ["bootout", `gui/${os.userInfo().uid}`, plistPath()]);
|
|
99
|
+
fs.rmSync(plistPath());
|
|
100
|
+
return true;
|
|
101
|
+
}
|
|
102
|
+
if (process.platform === "win32") {
|
|
103
|
+
const result = spawnSync("schtasks", ["/Delete", "/F", "/TN", TASK]);
|
|
104
|
+
fs.rmSync(vbsPath(), { force: true });
|
|
105
|
+
return result.status === 0;
|
|
106
|
+
}
|
|
107
|
+
if (!fs.existsSync(unitPath()))
|
|
108
|
+
return false;
|
|
109
|
+
spawnSync("systemctl", ["--user", "disable", "--now", "amicooked.service"]);
|
|
110
|
+
fs.rmSync(unitPath());
|
|
111
|
+
return true;
|
|
112
|
+
}
|
|
113
|
+
export function serviceInstalled() {
|
|
114
|
+
if (process.platform === "darwin")
|
|
115
|
+
return fs.existsSync(plistPath());
|
|
116
|
+
if (process.platform === "win32")
|
|
117
|
+
return spawnSync("schtasks", ["/Query", "/TN", TASK]).status === 0;
|
|
118
|
+
return fs.existsSync(unitPath());
|
|
119
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { execFileSync, spawn, spawnSync } from "child_process";
|
|
2
|
+
import { createHash } from "crypto";
|
|
3
|
+
import * as fs from "fs";
|
|
4
|
+
import * as os from "os";
|
|
5
|
+
import * as path from "path";
|
|
6
|
+
import { paths, writePrivateFile } from "../config.js";
|
|
7
|
+
import { VERSION } from "../version.js";
|
|
8
|
+
/** Hands out a permanent <id>.amicooked.app tunnel; holds the Cloudflare API token so we never ship it. */
|
|
9
|
+
const TUNNEL_API = process.env.AMICOOKED_TUNNEL_API || "https://tunnels.amicooked.app";
|
|
10
|
+
const USER_AGENT = `amicooked/${VERSION}`;
|
|
11
|
+
export function readTunnel() {
|
|
12
|
+
try {
|
|
13
|
+
return JSON.parse(fs.readFileSync(paths().tunnel, "utf8"));
|
|
14
|
+
}
|
|
15
|
+
catch {
|
|
16
|
+
return null;
|
|
17
|
+
}
|
|
18
|
+
}
|
|
19
|
+
/** Reuse this computer's tunnel, or ask the provisioning API for one. */
|
|
20
|
+
export async function ensureTunnel() {
|
|
21
|
+
const existing = readTunnel();
|
|
22
|
+
if (existing)
|
|
23
|
+
return existing;
|
|
24
|
+
const res = await fetch(`${TUNNEL_API}/tunnels`, { method: "POST", headers: { "User-Agent": USER_AGENT }, signal: AbortSignal.timeout(30000) });
|
|
25
|
+
if (res.status === 429)
|
|
26
|
+
throw new Error("Too many ChatGPT connections were set up from this network today. Try again tomorrow.");
|
|
27
|
+
if (!res.ok)
|
|
28
|
+
throw new Error(`Couldn't set up the ChatGPT connection (error ${res.status}). Try again later.`);
|
|
29
|
+
const body = (await res.json());
|
|
30
|
+
const tunnel = { url: body.url, tunnelId: body.tunnelId, tunnelToken: body.tunnelToken, heartbeatSecret: body.heartbeatSecret };
|
|
31
|
+
writePrivateFile(paths().tunnel, JSON.stringify(tunnel));
|
|
32
|
+
return tunnel;
|
|
33
|
+
}
|
|
34
|
+
/** Tell the API this tunnel is still in use, so it isn't cleaned up after 30 quiet days. */
|
|
35
|
+
export async function heartbeat(tunnel) {
|
|
36
|
+
await fetch(`${TUNNEL_API}/tunnels/heartbeat`, {
|
|
37
|
+
method: "POST",
|
|
38
|
+
headers: { "User-Agent": USER_AGENT, Authorization: `Bearer ${tunnel.heartbeatSecret}`, "Content-Type": "application/json" },
|
|
39
|
+
body: JSON.stringify({ tunnelId: tunnel.tunnelId }),
|
|
40
|
+
signal: AbortSignal.timeout(15000),
|
|
41
|
+
}).catch(() => { });
|
|
42
|
+
}
|
|
43
|
+
// ---- cloudflared ----
|
|
44
|
+
const CLOUDFLARED_VERSION = "2026.10.3";
|
|
45
|
+
// SHA-256 of each release asset as downloaded (GitHub's asset digest; the release notes hash the binary inside the .tgz)
|
|
46
|
+
const CLOUDFLARED_ASSETS = {
|
|
47
|
+
"darwin-arm64": { asset: "cloudflared-darwin-arm64.tgz", sha256: "1165d14b6f6360a3b8c283d7d1100024d6ec7cd9bc9e32519e96150645f3ec55" },
|
|
48
|
+
"darwin-x64": { asset: "cloudflared-darwin-amd64.tgz", sha256: "81b7b85f2376815c4f59b1aa323887b62e16ce8b67555c2e1577dc23f2a82000" },
|
|
49
|
+
"linux-x64": { asset: "cloudflared-linux-amd64", sha256: "053b80b0a23031a038fdbf3c073f59f82b8f1f152aa67971d7383ffafc0dbab0" },
|
|
50
|
+
"win32-x64": { asset: "cloudflared-windows-amd64.exe", sha256: "76b2805253d0d6ffacb092a7acfbee99e7af6917835c0c5410e23f3ef5052da2" },
|
|
51
|
+
};
|
|
52
|
+
const exe = process.platform === "win32" ? "cloudflared.exe" : "cloudflared";
|
|
53
|
+
/** A cloudflared to run: one already on PATH, or our own pinned, checksum-verified copy. */
|
|
54
|
+
export async function ensureCloudflared() {
|
|
55
|
+
const onPath = spawnSync("cloudflared", ["--version"], { encoding: "utf8", shell: process.platform === "win32" });
|
|
56
|
+
if (!onPath.error && onPath.status === 0)
|
|
57
|
+
return "cloudflared";
|
|
58
|
+
const target = path.join(paths().bin, exe);
|
|
59
|
+
if (fs.existsSync(target))
|
|
60
|
+
return target;
|
|
61
|
+
const key = `${process.platform}-${os.arch()}`;
|
|
62
|
+
const spec = CLOUDFLARED_ASSETS[key];
|
|
63
|
+
if (!spec)
|
|
64
|
+
throw new Error(`ChatGPT support isn't available on ${key} yet.`);
|
|
65
|
+
const url = `https://github.com/cloudflare/cloudflared/releases/download/${CLOUDFLARED_VERSION}/${spec.asset}`;
|
|
66
|
+
// GitHub's download CDN sometimes answers 5xx; retry a couple of times before giving up
|
|
67
|
+
let res = null;
|
|
68
|
+
for (let attempt = 1; attempt <= 3; attempt++) {
|
|
69
|
+
res = await fetch(url, { signal: AbortSignal.timeout(120000) }).catch(() => null);
|
|
70
|
+
if (res?.ok)
|
|
71
|
+
break;
|
|
72
|
+
await new Promise((resolve) => setTimeout(resolve, attempt * 2000));
|
|
73
|
+
}
|
|
74
|
+
if (!res?.ok)
|
|
75
|
+
throw new Error(`Couldn't download cloudflared (${res?.status ?? "network error"}). Check your connection and try again.`);
|
|
76
|
+
const data = Buffer.from(await res.arrayBuffer());
|
|
77
|
+
if (createHash("sha256").update(data).digest("hex") !== spec.sha256)
|
|
78
|
+
throw new Error("cloudflared download failed its checksum; not using it.");
|
|
79
|
+
fs.mkdirSync(paths().bin, { recursive: true });
|
|
80
|
+
if (spec.asset.endsWith(".tgz")) {
|
|
81
|
+
const archive = path.join(paths().bin, spec.asset);
|
|
82
|
+
fs.writeFileSync(archive, data);
|
|
83
|
+
execFileSync("tar", ["-xzf", archive, "-C", paths().bin]);
|
|
84
|
+
fs.rmSync(archive);
|
|
85
|
+
}
|
|
86
|
+
else {
|
|
87
|
+
fs.writeFileSync(target, data);
|
|
88
|
+
}
|
|
89
|
+
fs.chmodSync(target, 0o755);
|
|
90
|
+
return target;
|
|
91
|
+
}
|
|
92
|
+
/** Run the tunnel. The token goes through the environment so it isn't visible in `ps`. */
|
|
93
|
+
export function startCloudflared(binary, tunnel) {
|
|
94
|
+
return spawn(binary, ["tunnel", "--no-autoupdate", "run"], {
|
|
95
|
+
env: { ...process.env, TUNNEL_TOKEN: tunnel.tunnelToken },
|
|
96
|
+
stdio: ["ignore", "ignore", "pipe"],
|
|
97
|
+
windowsHide: true,
|
|
98
|
+
});
|
|
99
|
+
}
|
package/dist/schools.js
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
/** API versions the tools are written against. Setup checks the school supports them. */
|
|
2
|
+
export const API_VERSIONS = { le: "1.57", lp: "1.43" };
|
|
3
|
+
/** Ontario Brightspace schools, hosts checked against /d2l/api/versions/. Only McMaster is login-tested. */
|
|
4
|
+
export const PRESETS = [
|
|
5
|
+
{ id: "mcmaster", name: "McMaster University", lmsName: "Avenue to Learn", host: "avenue.cllmcmaster.ca", loginUrl: "https://avenue.mcmaster.ca/login.php" },
|
|
6
|
+
{ id: "waterloo", name: "University of Waterloo", lmsName: "LEARN", host: "learn.uwaterloo.ca" },
|
|
7
|
+
{ id: "western", name: "Western University", lmsName: "OWL Brightspace", host: "westernu.brightspace.com" },
|
|
8
|
+
{ id: "queens", name: "Queen's University", lmsName: "onQ", host: "onq.queensu.ca" },
|
|
9
|
+
{ id: "guelph", name: "University of Guelph", lmsName: "CourseLink", host: "courselink.uoguelph.ca" },
|
|
10
|
+
{ id: "laurier", name: "Wilfrid Laurier University", lmsName: "MyLearningSpace", host: "mylearningspace.wlu.ca" },
|
|
11
|
+
{ id: "tmu", name: "Toronto Metropolitan University", lmsName: "D2L Brightspace", host: "courses.torontomu.ca" },
|
|
12
|
+
{ id: "uottawa", name: "University of Ottawa", lmsName: "Brightspace", host: "uottawa.brightspace.com" },
|
|
13
|
+
{ id: "carleton", name: "Carleton University", lmsName: "Brightspace", host: "brightspace.carleton.ca" },
|
|
14
|
+
{ id: "brock", name: "Brock University", lmsName: "Brightspace", host: "brightspace.brocku.ca" },
|
|
15
|
+
{ id: "windsor", name: "University of Windsor", lmsName: "Brightspace", host: "brightspace.uwindsor.ca" },
|
|
16
|
+
{ id: "laurentian", name: "Laurentian University", lmsName: "D2L", host: "d2l.laurentian.ca" },
|
|
17
|
+
{ id: "lakehead", name: "Lakehead University", lmsName: "myCourseLink", host: "mycourselink.lakeheadu.ca" },
|
|
18
|
+
];
|
|
19
|
+
export function findPreset(id) {
|
|
20
|
+
const key = id.trim().toLowerCase();
|
|
21
|
+
return PRESETS.find((s) => s.id === key || s.host === key);
|
|
22
|
+
}
|
|
23
|
+
/** True if `host` serves the Brightspace versions API with the versions we need. */
|
|
24
|
+
export async function checkBrightspaceHost(host, fetchImpl = fetch) {
|
|
25
|
+
try {
|
|
26
|
+
const res = await fetchImpl(`https://${host}/d2l/api/versions/`, { signal: AbortSignal.timeout(10000) });
|
|
27
|
+
if (!res.ok)
|
|
28
|
+
return false;
|
|
29
|
+
const products = (await res.json());
|
|
30
|
+
const supports = (code) => products.some((p) => p.ProductCode === code && p.SupportedVersions.includes(API_VERSIONS[code]));
|
|
31
|
+
return supports("le") && supports("lp");
|
|
32
|
+
}
|
|
33
|
+
catch {
|
|
34
|
+
return false;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
function normalizeUrl(input) {
|
|
38
|
+
const trimmed = input.trim();
|
|
39
|
+
return new URL(/^https?:\/\//i.test(trimmed) ? trimmed : `https://${trimmed}`);
|
|
40
|
+
}
|
|
41
|
+
/** Hosts of absolute links into /d2l/ found in a page, e.g. an SSO portal linking to the real D2L host. */
|
|
42
|
+
function d2lHostsIn(html) {
|
|
43
|
+
const hosts = [...html.matchAll(/https:\/\/([a-z0-9.-]+)\/d2l\//gi)].map((m) => m[1].toLowerCase());
|
|
44
|
+
return [...new Set(hosts)];
|
|
45
|
+
}
|
|
46
|
+
async function fetchPage(url, fetchImpl) {
|
|
47
|
+
try {
|
|
48
|
+
const res = await fetchImpl(url, { redirect: "follow", signal: AbortSignal.timeout(10000) });
|
|
49
|
+
return { finalHost: new URL(res.url || url).host, html: await res.text() };
|
|
50
|
+
}
|
|
51
|
+
catch {
|
|
52
|
+
return null;
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
/**
|
|
56
|
+
* Work out the school from whatever URL a student logs in through: the D2L host itself,
|
|
57
|
+
* a page that redirects there, or a portal that links to it.
|
|
58
|
+
*/
|
|
59
|
+
export async function detectSchool(input, fetchImpl = fetch) {
|
|
60
|
+
const url = normalizeUrl(input);
|
|
61
|
+
const preset = PRESETS.find((s) => s.host === url.host || (s.loginUrl && new URL(s.loginUrl).host === url.host));
|
|
62
|
+
if (preset)
|
|
63
|
+
return preset;
|
|
64
|
+
const candidates = [url.host];
|
|
65
|
+
for (const pageUrl of [url.href, url.origin + "/"]) {
|
|
66
|
+
const page = await fetchPage(pageUrl, fetchImpl);
|
|
67
|
+
if (page)
|
|
68
|
+
candidates.push(page.finalHost, ...d2lHostsIn(page.html));
|
|
69
|
+
}
|
|
70
|
+
for (const host of [...new Set(candidates)]) {
|
|
71
|
+
if (await checkBrightspaceHost(host, fetchImpl)) {
|
|
72
|
+
return {
|
|
73
|
+
id: "custom",
|
|
74
|
+
name: host,
|
|
75
|
+
lmsName: "D2L",
|
|
76
|
+
host,
|
|
77
|
+
...(host !== url.host ? { loginUrl: url.href } : {}),
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
throw new Error(`Couldn't find D2L Brightspace at ${url.host}. Log in to your school's D2L in a browser and paste the address of your course homepage (it contains /d2l/home).`);
|
|
82
|
+
}
|
package/dist/server.js
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
|
|
2
|
+
import { LoginPendingError } from "./auth.js";
|
|
3
|
+
import { amICookedTool } from "./tools/cooked.js";
|
|
4
|
+
import { getAnnouncements, getMyCourses, getMyGrades } from "./tools/courses.js";
|
|
5
|
+
import { getCourseContent } from "./tools/content.js";
|
|
6
|
+
import { getAssignments, getUpcomingDueDates } from "./tools/deadlines.js";
|
|
7
|
+
import { downloadFileTool, readFileTool } from "./tools/files.js";
|
|
8
|
+
import { VERSION } from "./version.js";
|
|
9
|
+
export const TOOLS = [
|
|
10
|
+
amICookedTool,
|
|
11
|
+
getMyCourses,
|
|
12
|
+
getMyGrades,
|
|
13
|
+
getUpcomingDueDates,
|
|
14
|
+
getAnnouncements,
|
|
15
|
+
getAssignments,
|
|
16
|
+
getCourseContent,
|
|
17
|
+
downloadFileTool,
|
|
18
|
+
readFileTool,
|
|
19
|
+
];
|
|
20
|
+
export function createServer(options = {}) {
|
|
21
|
+
const server = new McpServer({ name: "amicooked", version: VERSION }, { instructions: options.instructions });
|
|
22
|
+
for (const tool of TOOLS) {
|
|
23
|
+
server.registerTool(tool.name, { description: tool.description, inputSchema: tool.schema, annotations: { readOnlyHint: true, openWorldHint: false } }, async (args) => {
|
|
24
|
+
const started = Date.now();
|
|
25
|
+
try {
|
|
26
|
+
const text = await tool.handler(args ?? {});
|
|
27
|
+
console.error(`[tool] ${tool.name} ok (${Date.now() - started}ms)`);
|
|
28
|
+
return { content: [{ type: "text", text }] };
|
|
29
|
+
}
|
|
30
|
+
catch (error) {
|
|
31
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
32
|
+
console.error(`[tool] ${tool.name} failed (${Date.now() - started}ms): ${message}`);
|
|
33
|
+
// Report errors as results so the AI can relay them, e.g. "sign in, then ask again"
|
|
34
|
+
const text = error instanceof LoginPendingError ? message : `Error: ${message}`;
|
|
35
|
+
return { content: [{ type: "text", text }], isError: true };
|
|
36
|
+
}
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
return server;
|
|
40
|
+
}
|