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>
868 lines
46 KiB
TypeScript
868 lines
46 KiB
TypeScript
import fs from 'node:fs';
|
|
import path from 'node:path';
|
|
import { Hono, type Context } from 'hono';
|
|
import { z } from 'zod';
|
|
import crypto from 'node:crypto';
|
|
import { getCookie, setCookie } from 'hono/cookie';
|
|
import { isHttps } from '../auth.ts';
|
|
import { safeEqual } from '../crypto.ts';
|
|
import { citedPassages, citedPassagesPrompt, EXPLAIN_SYSTEM, explainPrompt } from '../ai/explain.ts';
|
|
import { genUiPrompt } from '../ai/genui.ts';
|
|
import { officePreviewHtml, PREVIEW_CSP } from '../documents/preview.ts';
|
|
import { aiStatus, runChatWithMcp } from '../ai/service.ts';
|
|
import { startGeneration } from '../ai/generate.ts';
|
|
import { getAppSettings } from '../settings.ts';
|
|
import { AIError, type ChatMessage } from '../ai/types.ts';
|
|
import { HttpError, idParam, notFound, readBody, type AppContext } from '../http.ts';
|
|
import { listCards, listQuestions } from '../services/content.ts';
|
|
import { listChunks, searchChunks, sourceLabel, type ChunkHit } from '../services/documents.ts';
|
|
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;
|
|
type ShareKind = (typeof KINDS)[number];
|
|
|
|
interface ShareRow {
|
|
id: string;
|
|
token: string;
|
|
kind: ShareKind;
|
|
target_id: string;
|
|
enabled: number;
|
|
view_count: number;
|
|
last_viewed_at: number | null;
|
|
created_at: number;
|
|
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. */
|
|
export interface ShareAi {
|
|
/** "Explain this" on shared questions and flashcards. */
|
|
explain: boolean;
|
|
/** A chat assistant that answers from the shared material only. */
|
|
assistant: boolean;
|
|
/** Visitors of a shared class or exam can generate quizzes and flashcards from its materials. */
|
|
generate: boolean;
|
|
}
|
|
|
|
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;
|
|
/** A shared quiz is at most one exam long. */
|
|
export const SHARE_QUIZ_MAX = 50;
|
|
const SHARE_DECK_MAX = 75;
|
|
/** Medication math questions in a visitor's quiz when they ask for them. */
|
|
const SHARE_MATH_QUESTIONS = 5;
|
|
|
|
/** Today's generations on a link (since local midnight or the owner's last reset). */
|
|
function generateUsage(app: AppContext, share: Pick<ShareRow, 'id' | 'generate_reset_at'>) {
|
|
const s = getAppSettings(app.db, app.config.timezone);
|
|
const at = now();
|
|
const since = Math.max(startOfDay(at, s.timezone), share.generate_reset_at ?? 0);
|
|
const used = (kind: 'quiz' | 'deck') =>
|
|
app.db.get<{ n: number }>(`SELECT COUNT(*) AS n FROM drafts WHERE share_id = ? AND kind = ? AND status != 'failed' AND created_at >= ?`, share.id, kind, since)?.n ?? 0;
|
|
return {
|
|
quiz: { used: used('quiz'), limit: SHARE_GENERATE_LIMITS.quiz },
|
|
deck: { used: used('deck'), limit: SHARE_GENERATE_LIMITS.deck },
|
|
};
|
|
}
|
|
|
|
/**
|
|
* Sets made on a link, newest first. Finished sets are saved into the class like the owner's own
|
|
* 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, 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')${opts.visitor ? ' AND share_hidden = 0' : ''} ORDER BY created_at DESC LIMIT 30`,
|
|
shareId,
|
|
)
|
|
.flatMap((d) => {
|
|
const payload = parseJson<{ questions?: unknown[]; cards?: unknown[] }>(d.payload, {});
|
|
const saved = d.status === 'saved' && d.saved_id ? app.db.get<{ title: string }>(`SELECT title FROM ${d.saved_kind === 'deck' ? 'decks' : 'quizzes'} WHERE id = ?`, d.saved_id) : null;
|
|
// Saved, then deleted by the owner: gone from the link too.
|
|
if (d.status === 'saved' && !saved) return [];
|
|
const status = d.status === 'saved' ? ('ready' as const) : d.status === 'ready' ? ('review' as const) : (d.status as 'generating' | 'failed');
|
|
return [
|
|
{
|
|
id: d.id,
|
|
kind: d.kind,
|
|
title: saved?.title || d.title || (d.kind === 'quiz' ? 'Practice quiz' : 'Flashcards'),
|
|
status,
|
|
itemId: saved ? d.saved_id : null,
|
|
progress: d.progress,
|
|
// 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,
|
|
},
|
|
];
|
|
});
|
|
}
|
|
|
|
const TABLE: Record<ShareKind, { table: string; title: string }> = {
|
|
quiz: { table: 'quizzes', title: 'title' },
|
|
deck: { table: 'decks', title: 'title' },
|
|
note: { table: 'notes', title: 'title' },
|
|
document: { table: 'documents', title: 'title' },
|
|
folder: { table: 'folders', title: 'name' },
|
|
class: { table: 'classes', title: 'name' },
|
|
};
|
|
|
|
function mapShare(row: ShareRow) {
|
|
return {
|
|
id: row.id,
|
|
token: row.token,
|
|
kind: row.kind,
|
|
targetId: row.target_id,
|
|
enabled: Boolean(row.enabled),
|
|
viewCount: row.view_count,
|
|
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,
|
|
};
|
|
}
|
|
|
|
/** The owner's view of what visitors generated on a link. */
|
|
function ownerGenerated(app: AppContext, row: ShareRow) {
|
|
return { usage: generateUsage(app, row), sets: generatedSets(app, row.id).filter((s) => s.status !== 'failed') };
|
|
}
|
|
|
|
/** Sets made on a link belong to the class: deleting the link keeps them (and lets running ones finish). */
|
|
function releaseGenerated(app: AppContext, shareId: string): void {
|
|
app.db.run('UPDATE drafts SET share_id = NULL WHERE share_id = ?', shareId);
|
|
}
|
|
|
|
/* ------------------------------ admin ------------------------------ */
|
|
|
|
export function shareRoutes(app: AppContext): Hono {
|
|
const { db } = app;
|
|
const r = new Hono();
|
|
|
|
r.get('/shares', (c) => {
|
|
const rows = db.all<ShareRow>('SELECT * FROM shares ORDER BY created_at DESC');
|
|
const out = [];
|
|
for (const row of rows) {
|
|
const meta = TABLE[row.kind];
|
|
const target = db.get<{ title: string; class_id?: string }>(
|
|
`SELECT ${meta.title} AS title${row.kind === 'class' ? '' : ', class_id'} FROM ${meta.table} WHERE id = ?`,
|
|
row.target_id,
|
|
);
|
|
if (!target) {
|
|
releaseGenerated(app, row.id);
|
|
db.run('DELETE FROM shares WHERE id = ?', row.id);
|
|
continue;
|
|
}
|
|
const classId = row.kind === 'class' ? row.target_id : target.class_id;
|
|
const cls = classId ? db.get<{ name: string; color: string }>('SELECT name, color FROM classes WHERE id = ?', classId) : undefined;
|
|
out.push({ ...mapShare(row), title: target.title, classId: classId ?? null, className: cls?.name ?? '', classColor: cls?.color ?? 'slate', generated: row.kind === 'class' || row.kind === 'folder' ? ownerGenerated(app, row) : null });
|
|
}
|
|
return c.json({ shares: out });
|
|
});
|
|
|
|
r.post('/shares', async (c) => {
|
|
const body = await readBody(c, z.object({ kind: z.enum(KINDS), targetId: z.string() }));
|
|
const meta = TABLE[body.kind];
|
|
if (!db.get(`SELECT id FROM ${meta.table} WHERE id = ?`, body.targetId)) throw notFound('Item');
|
|
const existing = db.get<ShareRow>('SELECT * FROM shares WHERE kind = ? AND target_id = ?', body.kind, body.targetId);
|
|
const at = now();
|
|
if (existing) {
|
|
db.run('UPDATE shares SET enabled = 1, updated_at = ? WHERE id = ?', at, existing.id);
|
|
return c.json({ share: mapShare({ ...existing, enabled: 1 }) });
|
|
}
|
|
const id = newId();
|
|
db.run('INSERT INTO shares (id, token, kind, target_id, enabled, created_at, updated_at) VALUES (?, ?, ?, ?, 1, ?, ?)', id, newToken(), body.kind, body.targetId, at, at);
|
|
return c.json({ share: mapShare(db.get<ShareRow>('SELECT * FROM shares WHERE id = ?', id)!) }, 201);
|
|
});
|
|
|
|
r.patch('/shares/:id', async (c) => {
|
|
const id = idParam(c);
|
|
const body = await readBody(c, z.object({ enabled: z.boolean().optional(), ai: z.object({ explain: z.boolean(), assistant: z.boolean(), generate: z.boolean() }).partial().optional() }));
|
|
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 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);
|
|
const { changes } = db.run('UPDATE shares SET generate_reset_at = ?, updated_at = ? WHERE id = ?', now(), now(), id);
|
|
if (!changes) throw notFound('Share link');
|
|
const row = db.get<ShareRow>('SELECT * FROM shares WHERE id = ?', id)!;
|
|
return c.json({ share: mapShare(row), generated: ownerGenerated(app, row) });
|
|
});
|
|
|
|
/** Issues a new token: the old link stops working immediately. */
|
|
r.post('/shares/:id/rotate', (c) => {
|
|
const id = idParam(c);
|
|
const { changes } = db.run('UPDATE shares SET token = ?, view_count = 0, last_viewed_at = NULL, updated_at = ? WHERE id = ?', newToken(), now(), id);
|
|
if (!changes) throw notFound('Share link');
|
|
return c.json({ share: mapShare(db.get<ShareRow>('SELECT * FROM shares WHERE id = ?', id)!) });
|
|
});
|
|
|
|
r.delete('/shares/:id', (c) => {
|
|
releaseGenerated(app, idParam(c));
|
|
const { changes } = db.run('DELETE FROM shares WHERE id = ?', idParam(c));
|
|
if (!changes) throw notFound('Share link');
|
|
return c.json({ ok: true });
|
|
});
|
|
|
|
return r;
|
|
}
|
|
|
|
/* ------------------------------ public (no auth) ------------------------------ */
|
|
|
|
/**
|
|
* Visitor AI requests are limited per device (not per IP: a whole campus can share one address)
|
|
* and, as a cost backstop, per link. A device is a random id in a signed cookie; clearing cookies
|
|
* gives a fresh device allowance, which the link-wide cap still bounds.
|
|
*/
|
|
const DEVICE_LIMIT = { max: 20, windowMs: 10 * 60_000 };
|
|
const LINK_LIMIT = { max: 500, windowMs: 60 * 60_000 };
|
|
const VISITOR_COOKIE = 'sd_visitor';
|
|
const aiHits = new Map<string, number[]>();
|
|
|
|
function recentHits(key: string, windowMs: number, at: number): number[] {
|
|
const list = (aiHits.get(key) ?? []).filter((t) => at - t < windowMs);
|
|
aiHits.set(key, list);
|
|
return list;
|
|
}
|
|
|
|
function limitVisitor(shareId: string, deviceId: string): void {
|
|
const at = Date.now();
|
|
if (aiHits.size > 20_000) aiHits.clear();
|
|
const device = recentHits(`device:${shareId}:${deviceId}`, DEVICE_LIMIT.windowMs, at);
|
|
const link = recentHits(`link:${shareId}`, LINK_LIMIT.windowMs, at);
|
|
const over = device.length >= DEVICE_LIMIT.max ? { list: device, limit: DEVICE_LIMIT, who: 'from this device' } : link.length >= LINK_LIMIT.max ? { list: link, limit: LINK_LIMIT, who: 'on this link' } : null;
|
|
if (over) {
|
|
const retry = Math.max(1, Math.ceil((over.list[0] + over.limit.windowMs - at) / 60_000));
|
|
throw new HttpError(429, 'rate_limited', `Too many AI requests ${over.who}. Try again in ${retry} minute${retry === 1 ? '' : 's'}.`);
|
|
}
|
|
device.push(at);
|
|
link.push(at);
|
|
}
|
|
|
|
const signVisitor = (app: AppContext, id: string) => crypto.createHmac('sha256', app.config.secretKey).update(`visitor:${id}`).digest('base64url').slice(0, 32);
|
|
|
|
/** This browser's visitor id, from its signed cookie; a new one is issued when it is missing or forged. */
|
|
function visitorId(app: AppContext, c: Context): string {
|
|
const raw = getCookie(c, VISITOR_COOKIE) ?? '';
|
|
const [id, sig] = raw.split('.');
|
|
if (id && sig && /^[A-Za-z0-9_-]{16,64}$/.test(id) && safeEqual(sig, signVisitor(app, id))) return id;
|
|
const fresh = crypto.randomBytes(16).toString('base64url');
|
|
const secure = app.config.cookieSecure === 'auto' ? isHttps(c, app.config.trustProxy) : app.config.cookieSecure;
|
|
setCookie(c, VISITOR_COOKIE, `${fresh}.${signVisitor(app, fresh)}`, { httpOnly: true, sameSite: 'Lax', secure, path: '/api/public', maxAge: 365 * 86_400 });
|
|
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. */
|
|
function publicTool(tool: ToolActivity): ToolActivity {
|
|
return { id: tool.id, name: tool.kind === 'mcp' ? 'tool' : tool.name, label: tool.label, status: tool.status, kind: tool.kind, subject: tool.subject, sources: tool.sources };
|
|
}
|
|
|
|
const clipText = (text: string, max: number) => (text.length > max ? `${text.slice(0, max)}\n…(more not shown)` : text);
|
|
|
|
/** What the shared assistant may read: the shared item (or the one being viewed) and the documents in scope. */
|
|
function sharedMaterial(app: AppContext, share: ShareRow, viewing?: { kind: 'quiz' | 'deck' | 'note' | 'document'; id: string }): { title: string; text: string; documentIds: string[] } {
|
|
const meta = TABLE[share.kind];
|
|
const title = app.db.get<{ title: string }>(`SELECT ${meta.title} AS title FROM ${meta.table} WHERE id = ?`, share.target_id)?.title ?? 'Shared material';
|
|
const describe = (kind: 'quiz' | 'deck' | 'note' | 'document', id: string): { text: string; documentIds: string[] } => {
|
|
if (kind === 'quiz') {
|
|
const quiz = publicQuiz(app, id);
|
|
return { text: `Quiz "${quiz.title}":\n${quiz.questions.map((q, i) => `${i + 1}. ${q.stem}\n${q.options.map((o) => ` - ${o.text}${o.correct ? ' (correct)' : ''}`).join('\n')}${q.rationale ? `\n Rationale: ${q.rationale}` : ''}`).join('\n')}`, documentIds: [] };
|
|
}
|
|
if (kind === 'deck') {
|
|
const deck = publicDeck(app, id);
|
|
return { text: `Flashcards "${deck.title}":\n${deck.cards.map((c) => `- ${c.front} :: ${c.back}`).join('\n')}`, documentIds: [] };
|
|
}
|
|
if (kind === 'note') {
|
|
const note = publicNote(app, id);
|
|
return { text: `Note "${note.title}":\n${note.content}`, documentIds: [] };
|
|
}
|
|
return { text: '', documentIds: [id] };
|
|
};
|
|
if (share.kind === 'class' || share.kind === 'folder') {
|
|
const items = collectionItems(app, share);
|
|
const listing = `Materials in this shared ${share.kind}:\n${items.map((i) => `- ${i.kind}: ${i.title}`).join('\n')}`;
|
|
const current = viewing ? describe(viewing.kind, viewing.id) : { text: '', documentIds: [] };
|
|
return { title, text: clipText([current.text ? `The visitor is looking at this:\n${current.text}` : '', listing].filter(Boolean).join('\n\n'), 24_000), documentIds: items.filter((i) => i.kind === 'document').map((i) => i.id) };
|
|
}
|
|
const own = describe(share.kind, share.target_id);
|
|
return { title, text: clipText(own.text, 24_000), documentIds: own.documentIds };
|
|
}
|
|
|
|
const gone = () => new HttpError(404, 'share_not_found', 'This link is no longer available');
|
|
|
|
function publicQuiz(app: AppContext, id: string) {
|
|
const quiz = app.db.get<{ id: string; title: string; description: string; class_id: string }>('SELECT id, title, description, class_id FROM quizzes WHERE id = ?', id);
|
|
if (!quiz) throw gone();
|
|
return {
|
|
kind: 'quiz' as const,
|
|
id: quiz.id,
|
|
title: quiz.title,
|
|
description: quiz.description,
|
|
questions: listQuestions(app.db, quiz.id).map((q) => ({
|
|
id: q.id,
|
|
type: q.type,
|
|
stem: q.stem,
|
|
options: q.options,
|
|
rationale: q.rationale,
|
|
topic: q.topic,
|
|
difficulty: q.difficulty,
|
|
})),
|
|
};
|
|
}
|
|
|
|
function publicDeck(app: AppContext, id: string) {
|
|
const deck = app.db.get<{ id: string; title: string; description: string }>('SELECT id, title, description FROM decks WHERE id = ?', id);
|
|
if (!deck) throw gone();
|
|
return {
|
|
kind: 'deck' as const,
|
|
id: deck.id,
|
|
title: deck.title,
|
|
description: deck.description,
|
|
cards: listCards(app.db, deck.id).map((c) => ({ id: c.id, front: c.front, back: c.back, hint: c.hint })),
|
|
};
|
|
}
|
|
|
|
function publicNote(app: AppContext, id: string) {
|
|
const note = app.db.get<{ id: string; title: string; content: string; updated_at: number }>('SELECT id, title, content, updated_at FROM notes WHERE id = ?', id);
|
|
if (!note) throw gone();
|
|
return { kind: 'note' as const, id: note.id, title: note.title, content: note.content, updatedAt: note.updated_at };
|
|
}
|
|
|
|
function publicDocument(app: AppContext, id: string) {
|
|
const doc = app.db.get<Record<string, any>>('SELECT id, title, filename, kind, size, page_count, mime FROM documents WHERE id = ?', id);
|
|
if (!doc) throw gone();
|
|
return { kind: 'document' as const, id: doc.id as string, title: doc.title as string, filename: doc.filename as string, docKind: doc.kind as string, size: doc.size as number, pageCount: doc.page_count as number | null };
|
|
}
|
|
|
|
/** Quizzes, decks, notes and processed documents inside a class or folder. */
|
|
function collectionItems(app: AppContext, share: ShareRow) {
|
|
const { db } = app;
|
|
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, 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, 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, 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 })),
|
|
];
|
|
}
|
|
|
|
export function publicRoutes(app: AppContext): Hono {
|
|
const { db } = app;
|
|
const r = new Hono();
|
|
|
|
/** The switches visitors see: on only when the owner allowed it and a model is configured. */
|
|
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 };
|
|
};
|
|
|
|
const load = (token: string): ShareRow => {
|
|
if (!token || token.length < 16 || token.length > 64) throw gone();
|
|
const share = db.get<ShareRow>('SELECT * FROM shares WHERE token = ?', token);
|
|
if (!share || !share.enabled) throw gone();
|
|
return share;
|
|
};
|
|
|
|
r.get('/:token', (c) => {
|
|
const share = load(c.req.param('token'));
|
|
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, c);
|
|
switch (share.kind) {
|
|
case 'quiz':
|
|
return c.json({ ...publicQuiz(app, share.target_id), ai });
|
|
case 'deck':
|
|
return c.json({ ...publicDeck(app, share.target_id), ai });
|
|
case 'note':
|
|
return c.json({ ...publicNote(app, share.target_id), ai });
|
|
case 'document':
|
|
return c.json({ ...publicDocument(app, share.target_id), ai });
|
|
case 'folder': {
|
|
const folder = db.get<{ id: string; name: string; class_id: string }>('SELECT id, name, class_id FROM folders WHERE id = ?', share.target_id);
|
|
if (!folder) throw gone();
|
|
const cls = db.get<{ name: string; color: string }>('SELECT name, color FROM classes WHERE id = ?', folder.class_id);
|
|
return c.json({ kind: 'collection' as const, title: folder.name, subtitle: cls?.name ?? '', color: cls?.color ?? 'cobalt', folders: [], items: collectionItems(app, share), ai });
|
|
}
|
|
case 'class': {
|
|
const cls = db.get<{ id: string; name: string; code: string; description: string; color: string }>('SELECT * FROM classes WHERE id = ?', share.target_id);
|
|
if (!cls) throw gone();
|
|
const folders = db.all<{ id: string; name: string }>('SELECT id, name FROM folders WHERE class_id = ? ORDER BY sort_order, created_at', cls.id);
|
|
return c.json({ kind: 'collection' as const, title: cls.name, subtitle: cls.code, description: cls.description, color: cls.color, folders, items: collectionItems(app, share), ai });
|
|
}
|
|
default:
|
|
throw gone();
|
|
}
|
|
});
|
|
|
|
/** One item inside a shared class or folder. Membership is re-checked on every request. */
|
|
r.get('/:token/items/:kind/:id', (c) => {
|
|
const share = load(c.req.param('token'));
|
|
if (share.kind !== 'class' && share.kind !== 'folder') throw gone();
|
|
const kind = c.req.param('kind');
|
|
const id = c.req.param('id');
|
|
const allowed = collectionItems(app, share).some((i) => i.kind === kind && i.id === id);
|
|
if (!allowed) throw gone();
|
|
c.header('Cache-Control', 'no-store');
|
|
c.header('X-Robots-Tag', 'noindex, nofollow');
|
|
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 });
|
|
return c.json({ ...publicNote(app, id), ai });
|
|
});
|
|
|
|
const sendDocument = (documentId: string) => {
|
|
const doc = db.get<{ filename: string; mime: string; storage_name: string }>('SELECT filename, mime, storage_name FROM documents WHERE id = ?', documentId);
|
|
if (!doc) throw gone();
|
|
const file = path.join(app.config.uploadsDir, path.basename(doc.storage_name));
|
|
if (!fs.existsSync(file)) throw gone();
|
|
const inline = doc.mime === 'application/pdf' || doc.mime.startsWith('image/');
|
|
return new Response(fs.readFileSync(file), {
|
|
headers: {
|
|
'Content-Type': doc.mime || 'application/octet-stream',
|
|
'Content-Disposition': `${inline ? 'inline' : 'attachment'}; filename*=UTF-8''${encodeURIComponent(doc.filename)}`,
|
|
'X-Content-Type-Options': 'nosniff',
|
|
...(inline ? {} : { 'Content-Security-Policy': "default-src 'none'; sandbox" }),
|
|
'Cache-Control': 'private, no-store',
|
|
'X-Robots-Tag': 'noindex, nofollow',
|
|
},
|
|
});
|
|
};
|
|
|
|
/** Download for an explicitly shared document. */
|
|
r.get('/:token/file', (c) => {
|
|
const share = load(c.req.param('token'));
|
|
if (share.kind !== 'document') throw gone();
|
|
return sendDocument(share.target_id);
|
|
});
|
|
|
|
/* ------------------------------ AI for visitors ------------------------------ */
|
|
|
|
/** True when the item is the shared target or sits inside the shared class or folder. */
|
|
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 (!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.');
|
|
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. */
|
|
const sharedClassId = (share: ShareRow): string | null =>
|
|
share.kind === 'class' ? share.target_id : share.kind === 'folder' ? (db.get<{ class_id: string }>('SELECT class_id FROM folders WHERE id = ?', share.target_id)?.class_id ?? null) : null;
|
|
|
|
/** 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, 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, { visitor: true }), usage: generateUsage(app, share), limits: { quizMax: SHARE_QUIZ_MAX, deckMax: SHARE_DECK_MAX, mathQuestions: SHARE_MATH_QUESTIONS } });
|
|
});
|
|
|
|
const generateSchema = z.object({
|
|
kind: z.enum(['quiz', 'deck']),
|
|
count: z.number().int().min(1).max(SHARE_DECK_MAX).optional(),
|
|
difficulty: z.enum(['easy', 'medium', 'hard', 'mixed']).default('mixed'),
|
|
/**
|
|
* Class links: the exam the set is for (null: not in an exam). Required when the class has
|
|
* exams. The set uses only that exam's materials and is saved into it.
|
|
*/
|
|
examId: z.string().max(64).nullable().optional(),
|
|
/** Class materials to use, from the chosen exam; empty or absent: all of them. */
|
|
documentIds: z.array(z.string().max(64)).max(50).optional(),
|
|
/** Quizzes: add medication math questions, whatever the material covers. */
|
|
math: z.boolean().optional(),
|
|
});
|
|
|
|
/**
|
|
* A visitor generates a quiz or flashcard set from the link's class materials. Simplified on
|
|
* purpose: count, difficulty, materials and med math; NCLEX style with 25% select-all, checked
|
|
* with Python. Limited per link per day (and by the per-device request limit).
|
|
*/
|
|
r.post('/:token/generate', async (c) => {
|
|
const share = load(c.req.param('token'));
|
|
const body = await readBody(c, generateSchema);
|
|
if (share.kind !== 'class' && share.kind !== 'folder') throw gone();
|
|
requireAi(c, share, 'generate');
|
|
// Which exam the set is for: an exam link's own, or the visitor's choice on a class link.
|
|
let examId: string | null = share.kind === 'folder' ? share.target_id : null;
|
|
if (share.kind === 'class') {
|
|
const exams = db.all<{ id: string }>('SELECT id FROM folders WHERE class_id = ?', share.target_id);
|
|
if (body.examId === undefined && exams.length > 0) throw new HttpError(400, 'exam_required', 'Choose which exam this is for.');
|
|
if (body.examId && !exams.some((e) => e.id === body.examId)) throw gone();
|
|
examId = body.examId ?? null;
|
|
}
|
|
const docs = collectionItems(app, share).filter(
|
|
(i) => i.kind === 'document' && (share.kind === 'folder' || (examId ? i.folderId === examId : !i.folderId || !db.get('SELECT 1 FROM folders WHERE id = ?', i.folderId))),
|
|
);
|
|
if (docs.length === 0) throw new HttpError(400, 'no_materials', examId || share.kind === 'folder' ? 'This exam has no class materials to generate from.' : 'There are no class materials outside the exams to generate from.');
|
|
const chosen = body.documentIds?.length ? body.documentIds : docs.map((d) => d.id);
|
|
if (chosen.some((id) => !docs.some((d) => d.id === id))) throw gone();
|
|
const usage = generateUsage(app, share)[body.kind];
|
|
if (usage.used >= usage.limit) {
|
|
const what = body.kind === 'quiz' ? `${usage.limit} quizzes` : `${usage.limit} flashcard sets`;
|
|
throw new HttpError(429, 'generate_limit', `This link has made its ${what} for today. Try again tomorrow.`);
|
|
}
|
|
const isQuiz = body.kind === 'quiz';
|
|
if (isQuiz && (body.count ?? 0) > SHARE_QUIZ_MAX) throw new HttpError(400, 'too_many', `A quiz can have at most ${SHARE_QUIZ_MAX} questions.`);
|
|
const count = body.count ?? (isQuiz ? SHARE_QUIZ_MAX : 30);
|
|
const { draftId } = startGeneration(
|
|
app,
|
|
{
|
|
kind: body.kind,
|
|
classId: sharedClassId(share),
|
|
folderId: examId,
|
|
source: { documentIds: chosen },
|
|
count,
|
|
difficulty: body.difficulty,
|
|
...(isQuiz ? { format: count >= 40 ? 'exam' : 'practice', sataShare: 0.25, verify: true, ...(body.math ? { mathQuestions: Math.min(SHARE_MATH_QUESTIONS, count) } : {}) } : { cardStyle: 'concise' }),
|
|
},
|
|
// 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, { 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', [
|
|
z.object({ kind: z.literal('question'), quizId: z.string().max(64), questionId: z.string().max(64), selected: z.array(z.string().max(4000)).max(12).optional(), ask: z.string().max(500).optional() }),
|
|
z.object({ kind: z.literal('card'), deckId: z.string().max(64), cardId: z.string().max(64), ask: z.string().max(500).optional() }),
|
|
]);
|
|
|
|
/**
|
|
* "Explain this" for visitors. The request names a question or card; its content is loaded
|
|
* here (never taken from the request), so a link can't be used as a general-purpose model.
|
|
*/
|
|
r.post('/:token/explain', async (c) => {
|
|
const share = load(c.req.param('token'));
|
|
const body = await readBody(c, explainSchema);
|
|
requireAi(c, share, 'explain');
|
|
let prompt: string;
|
|
let sources: ReturnType<typeof citedPassages> = [];
|
|
if (body.kind === 'question') {
|
|
if (!inScope(share, 'quiz', body.quizId)) throw gone();
|
|
const q = listQuestions(db, body.quizId).find((x) => x.id === body.questionId);
|
|
if (!q) throw gone();
|
|
const texts = new Set(q.options.map((o) => o.text));
|
|
prompt = explainPrompt({ kind: 'question', stem: q.stem, options: q.options.map((o) => ({ text: o.text, correct: o.correct })), selected: body.selected?.filter((s) => texts.has(s) || q.type === 'numeric').map((s) => s.slice(0, 200)), rationale: q.rationale, ask: body.ask });
|
|
// The pages the rationale cites, read only from the quiz's own class.
|
|
const classId = db.get<{ class_id: string }>('SELECT class_id FROM quizzes WHERE id = ?', body.quizId)?.class_id;
|
|
if (classId && q.rationale) sources = citedPassages(db, q.rationale, { classIds: [classId], stem: q.stem });
|
|
prompt += citedPassagesPrompt(sources);
|
|
} else {
|
|
if (!inScope(share, 'deck', body.deckId)) throw gone();
|
|
const card = listCards(db, body.deckId).find((x) => x.id === body.cardId);
|
|
if (!card) throw gone();
|
|
prompt = explainPrompt({ kind: 'card', front: card.front, back: card.back, ask: body.ask });
|
|
}
|
|
return sse<ExplainEvent>(c, async (emit, signal) => {
|
|
try {
|
|
if (sources.length) emit({ type: 'tool', tool: sourceActivity(sources) });
|
|
// Only MCP servers the owner allowed on share links take part.
|
|
await runChatWithMcp(
|
|
app,
|
|
{ task: 'quick', purpose: 'shared explanation', system: EXPLAIN_SYSTEM + genUiPrompt('explain'), messages: [{ role: 'user', content: [{ type: 'text', text: prompt }] }], maxOutputTokens: 2500, signal, onEvent: (e) => e.type === 'text' && emit({ type: 'text', delta: e.delta }) },
|
|
'share',
|
|
{ onTool: (tool) => emit({ type: 'tool', tool: publicTool(tool) }) },
|
|
);
|
|
} catch (err) {
|
|
const ai = err instanceof AIError ? err : null;
|
|
if (ai?.code !== 'aborted') emit({ type: 'error', code: ai?.code ?? 'server', message: 'The explanation could not be generated. Try again later.' });
|
|
}
|
|
emit({ type: 'done' });
|
|
});
|
|
});
|
|
|
|
const chatSchema = z.object({
|
|
messages: z
|
|
.array(z.object({ role: z.enum(['user', 'assistant']), text: z.string().trim().min(1).max(4000) }))
|
|
.min(1)
|
|
.max(16)
|
|
.refine((m) => m[m.length - 1].role === 'user', 'The last message must be from the visitor'),
|
|
/** The item the visitor is looking at inside a shared class or folder. */
|
|
item: z.object({ kind: z.enum(['quiz', 'deck', 'note', 'document']), id: z.string().max(64) }).optional(),
|
|
});
|
|
|
|
/** A chat that answers from the shared material (plus MCP servers allowed on share links): no library access, nothing saved. */
|
|
r.post('/:token/chat', async (c) => {
|
|
const share = load(c.req.param('token'));
|
|
const body = await readBody(c, chatSchema);
|
|
requireAi(c, share, 'assistant');
|
|
const question = body.messages[body.messages.length - 1].text;
|
|
const material = sharedMaterial(app, share, body.item && inScope(share, body.item.kind, body.item.id) ? body.item : undefined);
|
|
let hits: ChunkHit[] = [];
|
|
if (material.documentIds.length) {
|
|
const scope = { documentIds: material.documentIds };
|
|
hits = await hybridSearch(app, question, scope, 6).catch(() => searchChunks(db, question, scope, 6));
|
|
}
|
|
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 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}` : '',
|
|
]
|
|
.filter(Boolean)
|
|
.join('\n\n') + genUiPrompt();
|
|
const messages: ChatMessage[] = body.messages.map((m) => ({ role: m.role, content: [{ type: 'text', text: m.text }] }));
|
|
return sse<ExplainEvent>(c, async (emit, signal) => {
|
|
try {
|
|
let wrote = false;
|
|
await runChatWithMcp(
|
|
app,
|
|
{
|
|
task: 'chat',
|
|
purpose: 'shared assistant',
|
|
system,
|
|
messages,
|
|
maxOutputTokens: 2500,
|
|
signal,
|
|
onEvent: (e) => {
|
|
if (e.type !== 'text') return;
|
|
wrote = true;
|
|
emit({ type: 'text', delta: e.delta });
|
|
},
|
|
},
|
|
'share',
|
|
{
|
|
onTool: (tool) => {
|
|
if (tool.status === 'running' && wrote) emit({ type: 'text', delta: '\n\n' });
|
|
wrote = false;
|
|
emit({ type: 'tool', tool: publicTool(tool) });
|
|
},
|
|
},
|
|
);
|
|
} catch (err) {
|
|
const ai = err instanceof AIError ? err : null;
|
|
if (ai?.code !== 'aborted') emit({ type: 'error', code: ai?.code ?? 'server', message: 'The assistant could not answer. Try again later.' });
|
|
}
|
|
emit({ type: 'done' });
|
|
});
|
|
});
|
|
|
|
/* ------------------------------ viewing documents ------------------------------ */
|
|
|
|
/** The document a link (or an item inside a shared collection) points at; membership is re-checked. */
|
|
const sharedDocument = (c: Context, nested: boolean): string => {
|
|
const share = load(c.req.param('token') ?? '');
|
|
if (!nested) {
|
|
if (share.kind !== 'document') throw gone();
|
|
return share.target_id;
|
|
}
|
|
if (share.kind !== 'class' && share.kind !== 'folder') throw gone();
|
|
const id = c.req.param('id') ?? '';
|
|
if (!collectionItems(app, share).some((i) => i.kind === 'document' && i.id === id)) throw gone();
|
|
return id;
|
|
};
|
|
|
|
/** Word and PowerPoint files as a sandboxed HTML page. */
|
|
const sendPreview = async (documentId: string) => {
|
|
const doc = db.get<{ kind: string; title: string; storage_name: string }>('SELECT kind, title, storage_name FROM documents WHERE id = ?', documentId);
|
|
if (!doc || (doc.kind !== 'docx' && doc.kind !== 'pptx')) throw gone();
|
|
const file = path.join(app.config.uploadsDir, path.basename(doc.storage_name));
|
|
if (!fs.existsSync(file)) throw gone();
|
|
let html: string;
|
|
try {
|
|
html = await officePreviewHtml(doc.kind, new Uint8Array(await fs.promises.readFile(file)), doc.title);
|
|
} catch (err) {
|
|
app.log('warn', 'Shared document preview failed', err instanceof Error ? err.message : err);
|
|
throw new HttpError(422, 'preview_failed', 'This file could not be shown. Download it to open it instead.');
|
|
}
|
|
return new Response(html, { headers: { 'Content-Type': 'text/html; charset=utf-8', 'Content-Security-Policy': PREVIEW_CSP, 'X-Content-Type-Options': 'nosniff', 'Cache-Control': 'private, no-store', 'X-Robots-Tag': 'noindex, nofollow' } });
|
|
};
|
|
|
|
/** The extracted text, page by page, for reading on any device. */
|
|
const sendText = (c: Context, documentId: string) => {
|
|
const offset = Math.max(0, Number(c.req.query('offset') ?? 0) || 0);
|
|
const limit = Math.min(60, Math.max(1, Number(c.req.query('limit') ?? 30) || 30));
|
|
const chunks = listChunks(db, documentId, offset, limit + 1);
|
|
c.header('Cache-Control', 'no-store');
|
|
c.header('X-Robots-Tag', 'noindex, nofollow');
|
|
return c.json({
|
|
chunks: chunks.slice(0, limit).map((ch) => ({ id: ch.id, seq: ch.seq, text: ch.text, heading: ch.heading, pageStart: ch.pageStart, pageEnd: ch.pageEnd })),
|
|
nextOffset: chunks.length > limit ? offset + limit : null,
|
|
});
|
|
};
|
|
|
|
r.get('/:token/preview', (c) => sendPreview(sharedDocument(c, false)));
|
|
r.get('/:token/items/document/:id/preview', (c) => sendPreview(sharedDocument(c, true)));
|
|
r.get('/:token/text', (c) => sendText(c, sharedDocument(c, false)));
|
|
r.get('/:token/items/document/:id/text', (c) => sendText(c, sharedDocument(c, true)));
|
|
|
|
/** Download for a document inside a shared class or folder. Membership is re-checked. */
|
|
r.get('/:token/items/document/:id/file', (c) => {
|
|
const share = load(c.req.param('token'));
|
|
if (share.kind !== 'class' && share.kind !== 'folder') throw gone();
|
|
const id = c.req.param('id');
|
|
if (!collectionItems(app, share).some((i) => i.kind === 'document' && i.id === id)) throw gone();
|
|
return sendDocument(id);
|
|
});
|
|
|
|
return r;
|
|
}
|