Fifth revision: share-link AI safety, sturdier generation, cleaner UI
All checks were successful
Verify and publish V2 container / build-and-push (push) Successful in 1m0s

- Malformed model JSON is sent back for repair, then retried; a failed job
  starts over once before it fails. Visitors can dismiss failed sets.
- Generated sets get a short distinct name and description; flashcards are
  atomic and have no hints; standard study shows known/learning counts.
- Share links: "In progress" list, finished sets join the normal lists with a
  "New" tag, plain progress steps, newest exam first.
- Share-link AI expires after a week, can be limited to the US or Arizona
  (DB-IP Lite or Cloudflare headers) and is locked by abuse protection
  (migration 8).
- The assistant never answers from general knowledge; MCP and web search
  tools load without a manual test.
- Plain-text copy, no question count in exam mode, filler text removed.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
Elijah 2026-11-16 09:17:50 -07:00
parent d8df5edf30
commit 85d5c9186d
46 changed files with 1242 additions and 283 deletions

View file

@ -34,6 +34,7 @@ import {
testMcpServer,
WEB_SEARCH_ID,
webSearchPatchSchema,
warmMcpServers,
} from '../ai/mcp.ts';
import type { ToolActivity } from '../ai/activity.ts';
import { genUiPrompt } from '../ai/genui.ts';
@ -160,8 +161,17 @@ export function aiRoutes(app: AppContext): Hono {
// MCP servers the assistant can call as tools.
r.get('/ai/mcp', (c) => c.json({ servers: listMcpServers(app) }));
r.post('/ai/mcp', async (c) => c.json({ server: saveMcpServer(app, null, await readBody(c, mcpServerInputSchema)) }, 201));
r.patch('/ai/mcp/:id', async (c) => c.json({ server: saveMcpServer(app, idParam(c), await readBody(c, mcpServerPatchSchema)) }));
// Saving (or signing in) connects in the background, so the tools are ready without a manual test.
r.post('/ai/mcp', async (c) => {
const server = saveMcpServer(app, null, await readBody(c, mcpServerInputSchema));
warmMcpServers(app);
return c.json({ server }, 201);
});
r.patch('/ai/mcp/:id', async (c) => {
const server = saveMcpServer(app, idParam(c), await readBody(c, mcpServerPatchSchema));
warmMcpServers(app);
return c.json({ server });
});
r.delete('/ai/mcp/:id', (c) => {
deleteMcpServer(app, idParam(c));
return c.json({ ok: true });
@ -188,6 +198,7 @@ export function aiRoutes(app: AppContext): Hono {
if (c.req.query('error')) return back('/settings/ai', 'error', c.req.query('error_description') || 'The sign-in was cancelled.');
try {
const done = await finishMcpOAuth(app, state, code);
warmMcpServers(app);
return back(done.returnTo, 'ok', `Signed in to ${done.name}.`);
} catch (err) {
app.log('warn', 'MCP sign-in failed', err instanceof Error ? err.message : err);
@ -198,7 +209,11 @@ export function aiRoutes(app: AppContext): Hono {
// The built-in web search.
r.get('/ai/web-search', (c) => c.json({ webSearch: getWebSearch(app) }));
r.patch('/ai/web-search', async (c) => c.json({ webSearch: saveWebSearch(app, await readBody(c, webSearchPatchSchema)) }));
r.patch('/ai/web-search', async (c) => {
const webSearch = saveWebSearch(app, await readBody(c, webSearchPatchSchema));
warmMcpServers(app);
return c.json({ webSearch });
});
r.post('/ai/web-search/test', async (c) => c.json({ result: await testMcpServer(app, WEB_SEARCH_ID), webSearch: getWebSearch(app) }));
/** Tool sources the chat may use, for the per-conversation switches. */

View file

@ -19,6 +19,7 @@ import { listChunks, searchChunks, sourceLabel, type ChunkHit } from '../service
import { hybridSearch } from '../services/semantic.ts';
import { newId, newToken, now, parseJson, startOfDay } from '../util.ts';
import type { ToolActivity } from '../ai/activity.ts';
import { checkVisitorRegion, geoRegionSchema, geoStatus, setGeoRegion } from '../services/geo.ts';
import { sourceActivity, sse, type ExplainEvent } from './ai.ts';
const KINDS = ['quiz', 'deck', 'folder', 'class', 'note', 'document'] as const;
@ -36,6 +37,10 @@ interface ShareRow {
updated_at: number;
ai: string;
generate_reset_at: number | null;
/** AI features switch themselves off at this time (a week after they were turned on). */
ai_expires_at: number | null;
/** Set when abuse protection turned AI off: JSON {at, reason}. */
ai_blocked: string | null;
}
/** AI features a share's visitors may use. Both are off until the owner turns them on. */
@ -48,7 +53,24 @@ export interface ShareAi {
generate: boolean;
}
const shareAi = (row: Pick<ShareRow, 'ai'>): ShareAi => ({ explain: false, assistant: false, generate: false, ...parseJson<Partial<ShareAi>>(row.ai, {}) });
const NO_AI: ShareAi = { explain: false, assistant: false, generate: false };
/** The AI switches as the owner set them. */
const shareAi = (row: Pick<ShareRow, 'ai'>): ShareAi => ({ ...NO_AI, ...parseJson<Partial<ShareAi>>(row.ai, {}) });
const anyAi = (ai: ShareAi) => ai.explain || ai.assistant || ai.generate;
/** AI on a link lasts a week from when it was turned on; the owner can give it another week. */
export const SHARE_AI_DAYS = 7;
const SHARE_AI_MS = SHARE_AI_DAYS * 86_400_000;
/** Whether the link's AI is running: switched on, within its week, and not locked by abuse protection. */
function aiState(row: Pick<ShareRow, 'ai' | 'ai_expires_at' | 'ai_blocked'>) {
const blocked = row.ai_blocked ? parseJson<{ at: number; reason: string } | null>(row.ai_blocked, null) : null;
const expired = row.ai_expires_at !== null && row.ai_expires_at <= now();
return { expiresAt: row.ai_expires_at, expired, blocked, active: anyAi(shareAi(row)) && !expired && !blocked };
}
/** The AI features that work on the link right now. */
const liveAi = (row: Pick<ShareRow, 'ai' | 'ai_expires_at' | 'ai_blocked'>): ShareAi => (aiState(row).active ? shareAi(row) : NO_AI);
/** Sets a share link may generate per day (the app's time zone), until the owner resets it. */
export const SHARE_GENERATE_LIMITS = { quiz: 4, deck: 2 } as const;
@ -76,10 +98,10 @@ function generateUsage(app: AppContext, share: Pick<ShareRow, 'id' | 'generate_r
* material: `itemId` is the quiz or deck, which the link shows with everything else. A set whose
* automatic save failed waits in the owner's drafts (`review`).
*/
function generatedSets(app: AppContext, shareId: string) {
function generatedSets(app: AppContext, shareId: string, opts: { visitor?: boolean } = {}) {
return app.db
.all<{ id: string; kind: 'quiz' | 'deck'; title: string; status: string; progress: number; progress_label: string; payload: string; saved_kind: string | null; saved_id: string | null; created_at: number }>(
`SELECT id, kind, title, status, progress, progress_label, payload, saved_kind, saved_id, created_at FROM drafts WHERE share_id = ? AND status IN ('generating', 'ready', 'failed', 'saved') ORDER BY created_at DESC LIMIT 30`,
`SELECT id, kind, title, status, progress, progress_label, payload, saved_kind, saved_id, created_at FROM drafts WHERE share_id = ? AND status IN ('generating', 'ready', 'failed', 'saved')${opts.visitor ? ' AND share_hidden = 0' : ''} ORDER BY created_at DESC LIMIT 30`,
shareId,
)
.flatMap((d) => {
@ -96,7 +118,8 @@ function generatedSets(app: AppContext, shareId: string) {
status,
itemId: saved ? d.saved_id : null,
progress: d.progress,
progressLabel: d.progress_label,
// Visitors see plain steps; the owner's drafts keep the detail.
progressLabel: opts.visitor && /python|checking/i.test(d.progress_label) ? 'Verifying questions' : d.progress_label,
error: status === 'failed' ? 'This set could not be made. Try again later.' : status === 'review' ? 'Made, and waiting for the owner to check it.' : '',
count: (d.kind === 'quiz' ? payload.questions?.length : payload.cards?.length) ?? 0,
createdAt: d.created_at,
@ -125,6 +148,9 @@ function mapShare(row: ShareRow) {
lastViewedAt: row.last_viewed_at,
createdAt: row.created_at,
ai: shareAi(row),
aiExpiresAt: row.ai_expires_at,
aiBlocked: aiState(row).blocked,
aiActive: aiState(row).active,
};
}
@ -186,11 +212,39 @@ export function shareRoutes(app: AppContext): Hono {
const row = db.get<ShareRow>('SELECT * FROM shares WHERE id = ?', id);
if (!row) throw notFound('Share link');
const enabled = body.enabled ?? Boolean(row.enabled);
const ai = { ...shareAi(row), ...body.ai };
db.run('UPDATE shares SET enabled = ?, ai = ?, updated_at = ? WHERE id = ?', enabled ? 1 : 0, JSON.stringify(ai), now(), id);
const state = aiState(row);
// Switching AI on after it lapsed (or was locked) starts from scratch: only what is turned on now.
const ai = { ...(state.active ? shareAi(row) : NO_AI), ...body.ai };
let expiresAt = row.ai_expires_at;
let blocked = row.ai_blocked;
if (!anyAi(ai)) {
expiresAt = null;
} else if (!state.active) {
expiresAt = now() + SHARE_AI_MS;
blocked = null;
}
db.run('UPDATE shares SET enabled = ?, ai = ?, ai_expires_at = ?, ai_blocked = ?, updated_at = ? WHERE id = ?', enabled ? 1 : 0, JSON.stringify(ai), expiresAt, blocked, now(), id);
return c.json({ share: mapShare(db.get<ShareRow>('SELECT * FROM shares WHERE id = ?', id)!) });
});
/** Another week of AI on the link, with the features it had (also lifts an abuse lock). */
r.post('/shares/:id/ai/renew', (c) => {
const id = idParam(c);
const row = db.get<ShareRow>('SELECT * FROM shares WHERE id = ?', id);
if (!row) throw notFound('Share link');
if (!anyAi(shareAi(row))) throw new HttpError(400, 'ai_off', 'Turn on an AI feature first.');
db.run('UPDATE shares SET ai_expires_at = ?, ai_blocked = NULL, updated_at = ? WHERE id = ?', now() + SHARE_AI_MS, now(), id);
return c.json({ share: mapShare(db.get<ShareRow>('SELECT * FROM shares WHERE id = ?', id)!) });
});
/** Where visitors may use AI from, and how the location check is doing. */
r.get('/share-settings/ai', (c) => c.json({ geo: geoStatus(app), abuse: ABUSE }));
r.put('/share-settings/ai', async (c) => {
const body = await readBody(c, geoRegionSchema);
setGeoRegion(app, body.region);
return c.json({ geo: geoStatus(app), abuse: ABUSE });
});
/** Gives the link a fresh daily allowance of generated quizzes and flashcards. */
r.post('/shares/:id/generate/reset', (c) => {
const id = idParam(c);
@ -263,8 +317,51 @@ function visitorId(app: AppContext, c: Context): string {
return fresh;
}
/**
* Abuse protection: signs that a link has leaked or is being scripted turn its AI off until the
* owner turns it back on. Counted over the last hour per link (in memory).
*/
export const ABUSE = {
windowMs: 60 * 60_000,
/** Different networks (IP addresses) using AI. A class shares a handful; dozens is a leak. */
addresses: 25,
/** Different browsers (visitor cookies), which clearing cookies inflates. */
devices: 40,
/** A flood: this many AI requests within five minutes. */
burst: 60,
burstMs: 5 * 60_000,
/** Requests from outside the allowed region (the page hides AI there, so these are scripted). */
outside: 10,
/** Requests refused by the per-device limit. */
limited: 30,
} as const;
type GuardEvent = { at: number; ip: string; device: string; kind: 'ok' | 'outside' | 'limited' };
const guardEvents = new Map<string, GuardEvent[]>();
/** Records one AI request on a link; returns why AI should be turned off, if it should. */
function guard(shareId: string, event: Omit<GuardEvent, 'at'>): string | null {
const at = Date.now();
if (guardEvents.size > 5000) guardEvents.clear();
const list = (guardEvents.get(shareId) ?? []).filter((e) => at - e.at < ABUSE.windowMs);
list.push({ ...event, at });
guardEvents.set(shareId, list);
const addresses = new Set(list.map((e) => e.ip)).size;
const devices = new Set(list.map((e) => e.device)).size;
const burst = list.filter((e) => at - e.at < ABUSE.burstMs).length;
const outside = list.filter((e) => e.kind === 'outside').length;
const limited = list.filter((e) => e.kind === 'limited').length;
if (addresses >= ABUSE.addresses) return `AI was used from ${addresses} different networks within an hour.`;
if (devices >= ABUSE.devices) return `AI was used from ${devices} different browsers within an hour.`;
if (burst >= ABUSE.burst) return `${burst} AI requests arrived within five minutes.`;
if (outside >= ABUSE.outside) return `${outside} AI requests came from outside the allowed region within an hour.`;
if (limited >= ABUSE.limited) return `${limited} AI requests went over the rate limit within an hour.`;
return null;
}
export function resetShareAiLimits(): void {
aiHits.clear();
guardEvents.clear();
}
/** What a visitor sees of a tool step: the step itself and its pages, not its raw input and output. */
@ -355,19 +452,19 @@ function collectionItems(app: AppContext, share: ShareRow) {
const byFolder = share.kind === 'folder';
const where = byFolder ? 'folder_id = ?' : 'class_id = ?';
const quizzes = db.all<Record<string, any>>(
`SELECT z.id, z.title, z.description, z.folder_id, (SELECT COUNT(*) FROM questions q WHERE q.quiz_id = z.id) AS n FROM quizzes z WHERE z.${where} ORDER BY z.sort_order, z.created_at`,
`SELECT z.id, z.title, z.description, z.folder_id, z.created_at, (SELECT COUNT(*) FROM questions q WHERE q.quiz_id = z.id) AS n FROM quizzes z WHERE z.${where} ORDER BY z.sort_order, z.created_at`,
share.target_id,
);
const decks = db.all<Record<string, any>>(
`SELECT d.id, d.title, d.description, d.folder_id, (SELECT COUNT(*) FROM cards c WHERE c.deck_id = d.id) AS n FROM decks d WHERE d.${where} ORDER BY d.sort_order, d.created_at`,
`SELECT d.id, d.title, d.description, d.folder_id, d.created_at, (SELECT COUNT(*) FROM cards c WHERE c.deck_id = d.id) AS n FROM decks d WHERE d.${where} ORDER BY d.sort_order, d.created_at`,
share.target_id,
);
const notes = db.all<Record<string, any>>(`SELECT id, title, folder_id FROM notes WHERE ${where} ORDER BY sort_order, created_at`, share.target_id);
// Documents are shared once they have been processed (a failed or half-read upload stays private).
const documents = db.all<Record<string, any>>(`SELECT id, title, folder_id, page_count, kind FROM documents WHERE ${where} AND status = 'ready' ORDER BY sort_order, created_at`, share.target_id);
return [
...quizzes.filter((q) => q.n > 0).map((q) => ({ kind: 'quiz' as const, id: q.id as string, title: q.title as string, description: q.description as string, folderId: q.folder_id as string | null, count: q.n as number })),
...decks.filter((d) => d.n > 0).map((d) => ({ kind: 'deck' as const, id: d.id as string, title: d.title as string, description: d.description as string, folderId: d.folder_id as string | null, count: d.n as number })),
...quizzes.filter((q) => q.n > 0).map((q) => ({ kind: 'quiz' as const, id: q.id as string, title: q.title as string, description: q.description as string, folderId: q.folder_id as string | null, count: q.n as number, createdAt: q.created_at as number })),
...decks.filter((d) => d.n > 0).map((d) => ({ kind: 'deck' as const, id: d.id as string, title: d.title as string, description: d.description as string, folderId: d.folder_id as string | null, count: d.n as number, createdAt: d.created_at as number })),
...notes.map((n) => ({ kind: 'note' as const, id: n.id as string, title: n.title as string, description: '', folderId: n.folder_id as string | null, count: 0 })),
...documents.map((d) => ({ kind: 'document' as const, id: d.id as string, title: d.title as string, description: String(d.kind ?? ''), folderId: d.folder_id as string | null, count: (d.page_count as number | null) ?? 0 })),
];
@ -378,11 +475,13 @@ export function publicRoutes(app: AppContext): Hono {
const r = new Hono();
/** The switches visitors see: on only when the owner allowed it and a model is configured. */
const publicAi = (share: ShareRow): ShareAi => {
const flags = { ...shareAi(share) };
const publicAi = (share: ShareRow, c: Context): ShareAi => {
const flags = { ...liveAi(share) };
// Generating needs class materials, which only class and exam links have.
if (share.kind !== 'class' && share.kind !== 'folder') flags.generate = false;
if (!flags.explain && !flags.assistant && !flags.generate) return flags;
// Outside the allowed region the page works, without AI.
if (!checkVisitorRegion(app, c).allowed) return NO_AI;
const ready = aiStatus(app).ready;
return { explain: flags.explain && ready, assistant: flags.assistant && ready, generate: flags.generate && ready };
};
@ -399,7 +498,7 @@ export function publicRoutes(app: AppContext): Hono {
db.run('UPDATE shares SET view_count = view_count + 1, last_viewed_at = ? WHERE id = ?', now(), share.id);
c.header('Cache-Control', 'no-store');
c.header('X-Robots-Tag', 'noindex, nofollow');
const ai = publicAi(share);
const ai = publicAi(share, c);
switch (share.kind) {
case 'quiz':
return c.json({ ...publicQuiz(app, share.target_id), ai });
@ -436,7 +535,7 @@ export function publicRoutes(app: AppContext): Hono {
if (!allowed) throw gone();
c.header('Cache-Control', 'no-store');
c.header('X-Robots-Tag', 'noindex, nofollow');
const ai = publicAi(share);
const ai = publicAi(share, c);
if (kind === 'quiz') return c.json({ ...publicQuiz(app, id), ai });
if (kind === 'deck') return c.json({ ...publicDeck(app, id), ai });
if (kind === 'document') return c.json({ ...publicDocument(app, id), ai });
@ -474,10 +573,36 @@ export function publicRoutes(app: AppContext): Hono {
const inScope = (share: ShareRow, kind: 'quiz' | 'deck' | 'note' | 'document', id: string): boolean =>
share.kind === kind ? share.target_id === id : (share.kind === 'class' || share.kind === 'folder') && collectionItems(app, share).some((i) => i.kind === kind && i.id === id);
/** Turns a link's AI off (abuse protection); the owner sees why and can turn it back on. */
const lockAi = (share: ShareRow, reason: string) => {
db.run('UPDATE shares SET ai_blocked = ?, updated_at = ? WHERE id = ?', JSON.stringify({ at: now(), reason }), now(), share.id);
guardEvents.delete(share.id);
app.log('warn', `AI turned off on a share link by abuse protection: ${reason}`);
};
const requireAi = (c: Context, share: ShareRow, feature: keyof ShareAi) => {
if (!shareAi(share)[feature]) throw new HttpError(403, 'ai_disabled', 'The owner has not turned this on for this link.');
if (!liveAi(share)[feature]) throw new HttpError(403, 'ai_disabled', 'AI is not turned on for this link.');
if (!aiStatus(app).ready) throw new HttpError(503, 'ai_unavailable', 'AI is not available right now.');
limitVisitor(share.id, visitorId(app, c));
const device = visitorId(app, c);
const geo = checkVisitorRegion(app, c);
const trip = (kind: GuardEvent['kind']) => {
const reason = guard(share.id, { ip: geo.ip, device, kind });
if (reason) {
lockAi(share, reason);
throw new HttpError(403, 'ai_disabled', 'AI is not turned on for this link.');
}
};
if (!geo.allowed) {
trip('outside');
throw new HttpError(403, 'ai_region', "AI features aren't available from your location.");
}
try {
limitVisitor(share.id, device);
} catch (err) {
trip('limited');
throw err;
}
trip('ok');
};
/** The class a class or exam link belongs to. */
@ -487,9 +612,9 @@ export function publicRoutes(app: AppContext): Hono {
/** What visitors can generate on this link, and what was made on it. */
r.get('/:token/generated', (c) => {
const share = load(c.req.param('token'));
if (!publicAi(share).generate) throw new HttpError(403, 'ai_disabled', 'The owner has not turned this on for this link.');
if (!publicAi(share, c).generate) throw new HttpError(403, 'ai_disabled', 'AI is not turned on for this link.');
c.header('Cache-Control', 'no-store');
return c.json({ sets: generatedSets(app, share.id), usage: generateUsage(app, share), limits: { quizMax: SHARE_QUIZ_MAX, deckMax: SHARE_DECK_MAX, mathQuestions: SHARE_MATH_QUESTIONS } });
return c.json({ sets: generatedSets(app, share.id, { visitor: true }), usage: generateUsage(app, share), limits: { quizMax: SHARE_QUIZ_MAX, deckMax: SHARE_DECK_MAX, mathQuestions: SHARE_MATH_QUESTIONS } });
});
const generateSchema = z.object({
@ -553,7 +678,15 @@ export function publicRoutes(app: AppContext): Hono {
// Saved into the class (and exam) as if the owner had approved it; in Drafts while it is written.
{ origin: 'share', shareId: share.id, autoSave: { description: 'Made with AI on a share link.' } },
);
return c.json({ set: generatedSets(app, share.id).find((s) => s.id === draftId), usage: generateUsage(app, share) }, 202);
return c.json({ set: generatedSets(app, share.id, { visitor: true }).find((s) => s.id === draftId), usage: generateUsage(app, share) }, 202);
});
/** A visitor clears a failed set from the link; the owner still finds it in Drafts. */
r.post('/:token/generated/:id/dismiss', (c) => {
const share = load(c.req.param('token'));
const { changes } = db.run(`UPDATE drafts SET share_hidden = 1 WHERE id = ? AND share_id = ? AND status = 'failed'`, c.req.param('id'), share.id);
if (!changes) throw gone();
return c.json({ ok: true });
});
const explainSchema = z.discriminatedUnion('kind', [
@ -630,7 +763,7 @@ export function publicRoutes(app: AppContext): Hono {
const excerpts = hits.map((h) => `[${sourceLabel(h)}]\n${h.text}`).join('\n\n---\n\n');
const system = [
`You are a study assistant on a page someone shared: "${material.title}". Help the visitor understand and remember this material.`,
'Answer from the shared material below and from general nursing knowledge. You cannot see anything else of the owner\'s, and you cannot change anything. If a question has nothing to do with studying this material, politely say you can only help with it.',
'Answer only from the shared material and excerpts below (and web search results, when that tool is offered). Never answer factual questions from your own general knowledge: if the material does not cover something, say you do not have information on it in these materials. You cannot see anything else of the owner\'s, and you cannot change anything. If a question has nothing to do with studying this material, politely say you can only help with it.',
'When you use a document excerpt, name its source in parentheses, e.g. (Lecture 3, p. 4). Be concise and use Markdown.',
material.text ? `SHARED MATERIAL:\n${material.text}` : '',
excerpts ? `RELEVANT DOCUMENT EXCERPTS:\n${excerpts}` : '',