diff --git a/.env.example b/.env.example
index 8d30954..74a5160 100644
--- a/.env.example
+++ b/.env.example
@@ -502,6 +502,12 @@ DEFAULT_MODEL=
# DATABASE_URL=postgres://openmaic:password@postgres:5432/openmaic
# PERSISTENCE_DEV_TOKEN=
+# The development authenticator above is refused when NODE_ENV=production
+# unless this explicit opt-in is set. It provides no user isolation (the
+# learner key is client-supplied), so enabling it in production is only safe
+# on a trusted-network, single-user deployment.
+# PERSISTENCE_ALLOW_INSECURE_DEV_AUTH=true
+
# Store asset bytes in S3 instead of PostgreSQL. Region, endpoint, and credentials
# are resolved through the standard AWS SDK environment / credential chain.
# ASSET_S3_BUCKET=
diff --git a/app/api/classroom/route.ts b/app/api/classroom/route.ts
index dc66047..23b426a 100644
--- a/app/api/classroom/route.ts
+++ b/app/api/classroom/route.ts
@@ -1,5 +1,6 @@
import { type NextRequest } from 'next/server';
import { randomUUID } from 'crypto';
+import { validateScene } from '@openmaic/dsl';
import { apiSuccess, apiError, API_ERROR_CODES } from '@/lib/server/api-response';
import {
buildRequestOrigin,
@@ -7,10 +8,16 @@ import {
persistClassroom,
readClassroom,
} from '@/lib/server/classroom-storage';
+import { sanitizeSceneContent } from '@/lib/server/sanitize-scene-content';
import { createLogger } from '@/lib/logger';
const log = createLogger('Classroom API');
+function describeSceneIssue(issue: { path: string; message: string }): string {
+ const at = issue.path && issue.path !== '' ? issue.path : '/';
+ return `${at}: ${issue.message}`;
+}
+
export async function POST(request: NextRequest) {
let stageId: string | undefined;
let sceneCount: number | undefined;
@@ -28,10 +35,55 @@ export async function POST(request: NextRequest) {
);
}
+ if (typeof stage !== 'object' || Array.isArray(stage)) {
+ return apiError(API_ERROR_CODES.INVALID_REQUEST, 400, 'Invalid classroom stage');
+ }
+ if (!Array.isArray(scenes)) {
+ return apiError(
+ API_ERROR_CODES.INVALID_REQUEST,
+ 400,
+ 'Invalid classroom scenes: must be an array',
+ );
+ }
+
+ // The scenes must already have the shape the slide DSL declares (id,
+ // stageId, title, order, type and a content payload bound to that type).
+ // Rejecting malformed scenes here keeps garbage out of storage instead of
+ // letting viewers choke on it later.
+ for (const [index, scene] of scenes.entries()) {
+ const result = validateScene(scene);
+ if (!result.valid) {
+ const first = result.errors[0];
+ return apiError(
+ API_ERROR_CODES.INVALID_REQUEST,
+ 400,
+ `Invalid classroom scene at index ${index}`,
+ first ? describeSceneIssue(first) : undefined,
+ );
+ }
+ }
+
const id = stage.id || randomUUID();
+
+ // An id that fails the allowlist never reaches the filesystem: the storage
+ // layer joins the id into CLASSROOMS_DIR, so a traversal-style id must be
+ // rejected here with the same contract the read side already enforces.
+ if (!isValidClassroomId(id)) {
+ return apiError(API_ERROR_CODES.INVALID_REQUEST, 400, 'Invalid classroom id');
+ }
+
const baseUrl = buildRequestOrigin(request);
- const persisted = await persistClassroom({ id, stage: { ...stage, id }, scenes }, baseUrl);
+ // Sanitize every HTML-bearing string in the payload before it reaches
+ // storage: stored slide HTML is restricted to the formatting vocabulary
+ // the renderer produces (see sanitize-scene-content.ts).
+ const safeStage = sanitizeSceneContent(stage);
+ const safeScenes = sanitizeSceneContent(scenes);
+
+ const persisted = await persistClassroom(
+ { id, stage: { ...safeStage, id }, scenes: safeScenes },
+ baseUrl,
+ );
return apiSuccess({ id: persisted.id, url: persisted.url }, 201);
} catch (error) {
@@ -69,7 +121,11 @@ export async function GET(request: NextRequest) {
return apiError(API_ERROR_CODES.INVALID_REQUEST, 404, 'Classroom not found');
}
- return apiSuccess({ classroom });
+ // Classroom files written before this change were stored unsanitized and
+ // cannot be migrated on deployments we do not control. Run the same
+ // sanitizer over the payload on the way out so already-stored content is
+ // cleaned at the single serve choke point too.
+ return apiSuccess({ classroom: sanitizeSceneContent(classroom) });
} catch (error) {
log.error(
`Classroom retrieval failed [id=${request.nextUrl.searchParams.get('id') ?? 'unknown'}]:`,
diff --git a/app/api/extract-document/route.ts b/app/api/extract-document/route.ts
index 63925f1..63f672d 100644
--- a/app/api/extract-document/route.ts
+++ b/app/api/extract-document/route.ts
@@ -255,7 +255,7 @@ async function runExtraction(
const mediaClientBaseUrl = mediaManaged ? undefined : requestConfig.baseUrl || undefined;
// Same SSRF guard the document path applies: a client-supplied endpoint
// must not let the server connect to internal/metadata hosts.
- if (mediaClientBaseUrl && process.env.NODE_ENV === 'production') {
+ if (mediaClientBaseUrl) {
const ssrfError = await validateUrlForSSRF(mediaClientBaseUrl);
if (ssrfError) {
return apiError('INVALID_URL', 403, ssrfError);
@@ -383,7 +383,7 @@ async function runExtraction(
);
}
}
- if (clientBaseUrl && process.env.NODE_ENV === 'production') {
+ if (clientBaseUrl) {
const ssrfError = await validateUrlForSSRF(clientBaseUrl);
if (ssrfError) {
return apiError('INVALID_URL', 403, ssrfError);
diff --git a/app/api/generate/image/route.ts b/app/api/generate/image/route.ts
index 8e1858d..0d106c5 100644
--- a/app/api/generate/image/route.ts
+++ b/app/api/generate/image/route.ts
@@ -67,7 +67,7 @@ export async function POST(request: NextRequest) {
const clientBaseUrl = managed ? undefined : request.headers.get('x-base-url') || undefined;
const clientModel = request.headers.get('x-image-model')?.trim() || undefined;
- if (clientBaseUrl && process.env.NODE_ENV === 'production') {
+ if (clientBaseUrl) {
const ssrfError = await validateUrlForSSRF(clientBaseUrl);
if (ssrfError) {
return apiError('INVALID_URL', 403, ssrfError);
diff --git a/app/api/generate/video/route.ts b/app/api/generate/video/route.ts
index e16201d..3a47aa8 100644
--- a/app/api/generate/video/route.ts
+++ b/app/api/generate/video/route.ts
@@ -62,7 +62,7 @@ export async function POST(request: NextRequest) {
const clientBaseUrl = managed ? undefined : request.headers.get('x-base-url') || undefined;
const clientModel = request.headers.get('x-video-model')?.trim() || undefined;
- if (clientBaseUrl && process.env.NODE_ENV === 'production') {
+ if (clientBaseUrl) {
const ssrfError = await validateUrlForSSRF(clientBaseUrl);
if (ssrfError) {
return apiError('INVALID_URL', 403, ssrfError);
diff --git a/app/api/parse-pdf/route.ts b/app/api/parse-pdf/route.ts
index bb698ed..11bdd5e 100644
--- a/app/api/parse-pdf/route.ts
+++ b/app/api/parse-pdf/route.ts
@@ -44,7 +44,7 @@ export async function POST(req: NextRequest) {
// Managed providers are admin-owned: ignore any client-sent key/baseUrl.
const managed = isServerConfiguredProvider('pdf', effectiveProviderId);
const clientBaseUrl = managed ? undefined : baseUrl || undefined;
- if (clientBaseUrl && process.env.NODE_ENV === 'production') {
+ if (clientBaseUrl) {
const ssrfError = await validateUrlForSSRF(clientBaseUrl);
if (ssrfError) {
return apiError('INVALID_URL', 403, ssrfError);
diff --git a/app/api/transcription/route.ts b/app/api/transcription/route.ts
index 92b34fd..74855fa 100644
--- a/app/api/transcription/route.ts
+++ b/app/api/transcription/route.ts
@@ -54,7 +54,7 @@ export async function POST(req: NextRequest) {
// Managed providers are admin-owned: ignore any client-sent key/baseUrl.
const managed = isServerConfiguredProvider('asr', effectiveProviderId);
const clientBaseUrl = managed ? undefined : baseUrl || undefined;
- if (clientBaseUrl && process.env.NODE_ENV === 'production') {
+ if (clientBaseUrl) {
const ssrfError = await validateUrlForSSRF(clientBaseUrl);
if (ssrfError) {
return apiError('INVALID_URL', 403, ssrfError);
diff --git a/app/api/verify-image-provider/route.ts b/app/api/verify-image-provider/route.ts
index eb16f47..92b8d4f 100644
--- a/app/api/verify-image-provider/route.ts
+++ b/app/api/verify-image-provider/route.ts
@@ -54,7 +54,7 @@ export async function POST(request: NextRequest) {
const clientApiKey = managed ? undefined : request.headers.get('x-api-key') || undefined;
const clientBaseUrl = managed ? undefined : request.headers.get('x-base-url') || undefined;
- if (clientBaseUrl && process.env.NODE_ENV === 'production') {
+ if (clientBaseUrl) {
const ssrfError = await validateUrlForSSRF(clientBaseUrl);
if (ssrfError) {
return apiError('INVALID_URL', 403, ssrfError);
diff --git a/app/api/verify-pdf-provider/route.ts b/app/api/verify-pdf-provider/route.ts
index 1da838d..55e8a32 100644
--- a/app/api/verify-pdf-provider/route.ts
+++ b/app/api/verify-pdf-provider/route.ts
@@ -55,7 +55,7 @@ export async function POST(req: NextRequest) {
);
}
// Validate a client-supplied endpoint before we sign a request to it.
- if (endpoint && process.env.NODE_ENV === 'production') {
+ if (endpoint) {
const ssrfError = await validateUrlForSSRF(
endpoint.startsWith('http') ? endpoint : `https://${endpoint}`,
);
@@ -80,7 +80,7 @@ export async function POST(req: NextRequest) {
// MinerU Cloud: verify by calling the cloud API with the token
if (providerId === 'mineru-cloud') {
const clientCloudBase = managed ? undefined : (baseUrl as string | undefined) || undefined;
- if (clientCloudBase && process.env.NODE_ENV === 'production') {
+ if (clientCloudBase) {
const ssrfError = await validateUrlForSSRF(clientCloudBase);
if (ssrfError) {
return apiError('INVALID_URL', 403, ssrfError);
@@ -129,7 +129,7 @@ export async function POST(req: NextRequest) {
// Self-hosted providers: verify by connecting to the base URL
const clientBaseUrl = managed ? undefined : (baseUrl as string | undefined) || undefined;
- if (clientBaseUrl && process.env.NODE_ENV === 'production') {
+ if (clientBaseUrl) {
const ssrfError = await validateUrlForSSRF(clientBaseUrl);
if (ssrfError) {
return apiError('INVALID_URL', 403, ssrfError);
diff --git a/app/api/verify-video-provider/route.ts b/app/api/verify-video-provider/route.ts
index 0094ac0..a836688 100644
--- a/app/api/verify-video-provider/route.ts
+++ b/app/api/verify-video-provider/route.ts
@@ -49,7 +49,7 @@ export async function POST(request: NextRequest) {
const clientApiKey = managed ? undefined : request.headers.get('x-api-key') || undefined;
const clientBaseUrl = managed ? undefined : request.headers.get('x-base-url') || undefined;
- if (clientBaseUrl && process.env.NODE_ENV === 'production') {
+ if (clientBaseUrl) {
const ssrfError = await validateUrlForSSRF(clientBaseUrl);
if (ssrfError) {
return apiError('INVALID_URL', 403, ssrfError);
diff --git a/lib/ai/providers.ts b/lib/ai/providers.ts
index 73c5fbd..b2aa575 100644
--- a/lib/ai/providers.ts
+++ b/lib/ai/providers.ts
@@ -1897,20 +1897,21 @@ function openAIStreamErrorStatus(error: Record): number {
async function fetchCustomOpenAIChat(
input: RequestInfo | URL,
init?: RequestInit,
+ fetchImpl: typeof fetch = (fetchInput, fetchInit) => globalThis.fetch(fetchInput, fetchInit),
): Promise {
const requestUrl = requestUrlString(input);
if (!requestUrl.includes('/chat/completions') || !init?.body || typeof init.body !== 'string') {
- return globalThis.fetch(input, init);
+ return fetchImpl(input, init);
}
let requestBody: Record;
try {
requestBody = JSON.parse(init.body) as Record;
} catch {
- return globalThis.fetch(input, init);
+ return fetchImpl(input, init);
}
- if (requestBody.stream === true) return globalThis.fetch(input, init);
+ if (requestBody.stream === true) return fetchImpl(input, init);
const streamOptions =
requestBody.stream_options &&
@@ -1919,7 +1920,7 @@ async function fetchCustomOpenAIChat(
? (requestBody.stream_options as Record)
: {};
- const response = await globalThis.fetch(input, {
+ const response = await fetchImpl(input, {
...init,
body: JSON.stringify({
...requestBody,
@@ -2078,14 +2079,23 @@ export function getModel(config: ModelConfig): ModelWithInfo {
config.baseUrl || provider?.defaultBaseUrl || undefined,
);
+ // The outbound transport. resolveModel installs a redirect-validating fetch
+ // here so every hop of a request to a client-supplied base URL is re-checked;
+ // without one, requests go through the global fetch exactly as before
+ // (resolved at call time, so tests that stub it keep working).
+ const transportFetch: typeof fetch =
+ config.fetchImpl ?? ((fetchInput, fetchInit) => globalThis.fetch(fetchInput, fetchInit));
+
let model: LanguageModel;
switch (providerType) {
case 'azure': {
- const azure = createAzure({
+ const azureOptions: Parameters[0] = {
apiKey: effectiveApiKey,
baseURL: normalizeAzureBaseUrl(effectiveBaseUrl),
- });
+ };
+ if (config.fetchImpl) azureOptions.fetch = config.fetchImpl;
+ const azure = createAzure(azureOptions);
model = azure(config.modelId);
break;
}
@@ -2154,8 +2164,8 @@ export function getModel(config: ModelConfig): ModelWithInfo {
}
}
const response = useStreamingChatCompat
- ? await fetchCustomOpenAIChat(url, init)
- : await globalThis.fetch(url, init);
+ ? await fetchCustomOpenAIChat(url, init, transportFetch)
+ : await transportFetch(url, init);
// Recover reasoning that @ai-sdk/openai's chat schema drops: rewrite
// streamed `reasoning_content` deltas into an inline block
@@ -2213,6 +2223,10 @@ export function getModel(config: ModelConfig): ModelWithInfo {
return response;
};
openaiOptions.fetch = compatFetch as typeof globalThis.fetch;
+ } else if (config.fetchImpl) {
+ // Native OpenAI / Responses transport with a validated fetch installed
+ // by the server: still route requests through it.
+ openaiOptions.fetch = config.fetchImpl;
}
const openai = createOpenAI(openaiOptions);
@@ -2272,8 +2286,10 @@ export function getModel(config: ModelConfig): ModelWithInfo {
}
}
- return globalThis.fetch(url, init);
+ return transportFetch(url, init);
}) as typeof globalThis.fetch;
+ } else if (config.fetchImpl) {
+ anthropicOptions.fetch = config.fetchImpl;
}
const anthropic = createAnthropic(anthropicOptions);
@@ -2317,6 +2333,8 @@ export function getModel(config: ModelConfig): ModelWithInfo {
});
return response as Response;
}) as typeof fetch;
+ } else if (config.fetchImpl) {
+ googleOptions.fetch = config.fetchImpl;
}
const google = createGoogleGenerativeAI(googleOptions);
model = google.chat(config.modelId);
diff --git a/lib/persistence/server-auth.ts b/lib/persistence/server-auth.ts
index de5eddd..3d96d4b 100644
--- a/lib/persistence/server-auth.ts
+++ b/lib/persistence/server-auth.ts
@@ -17,6 +17,10 @@ import type { IncomingMessage } from 'node:http';
import type { AssetPrincipal } from '@openmaic/storage';
import type { RuntimeHttpPrincipal } from '@openmaic/storage/server';
+import { createLogger } from '@/lib/logger';
+
+const log = createLogger('PersistenceAuth');
+
type PersistencePrincipal = RuntimeHttpPrincipal & Partial>;
/**
@@ -25,6 +29,37 @@ type PersistencePrincipal = RuntimeHttpPrincipal & Partial {
- const filePath = path.join(CLASSROOMS_DIR, `${id}.json`);
+ const filePath = resolveClassroomFilePath(id);
try {
const content = await fs.readFile(filePath, 'utf-8');
return JSON.parse(content) as PersistedClassroomData;
@@ -73,8 +89,8 @@ export async function persistClassroom(
createdAt: new Date().toISOString(),
};
+ const filePath = resolveClassroomFilePath(data.id);
await ensureClassroomsDir();
- const filePath = path.join(CLASSROOMS_DIR, `${data.id}.json`);
await writeJsonFileAtomic(filePath, classroomData);
return {
diff --git a/lib/server/fetch-with-redirect-validation.ts b/lib/server/fetch-with-redirect-validation.ts
new file mode 100644
index 0000000..2f96454
--- /dev/null
+++ b/lib/server/fetch-with-redirect-validation.ts
@@ -0,0 +1,163 @@
+/**
+ * fetch() replacement that re-validates every redirect hop.
+ *
+ * The origin of an outbound request is checked once (by the caller, through
+ * `validateUrlForSSRF`) and then handed to Node's default fetch, which follows
+ * redirects on its own without ever re-checking the `Location` target. A host
+ * that resolves publicly can therefore answer `302 Location:
+ * http:///...` and pull the request onto an internal network.
+ *
+ * This wrapper fetches with `redirect: 'manual'`, resolves each `Location`
+ * against the current URL, re-runs `validateUrlForSSRF` on the resolved
+ * target, and only then follows — mirroring the per-hop loop used by
+ * `app/api/proxy-media/route.ts` and the agent-runtime media downloads. Hops
+ * are bounded (5, matching those implementations). A rejected hop fails
+ * loudly with the guard's own message; the 3xx is never handed back as if it
+ * were a real response, and there is no unvalidated fallback.
+ */
+import { validateUrlForSSRF } from '@/lib/server/ssrf-guard';
+
+export const MAX_REDIRECT_HOPS = 5;
+
+/**
+ * Request headers that carry provider credentials and must never cross an
+ * origin boundary when a redirect is followed manually. These are the header
+ * spellings the provider layer attaches to outbound calls: `authorization`
+ * (Bearer tokens from the OpenAI/Anthropic/Azure SDKs and the verify routes),
+ * `api-key` (Azure), `x-api-key` (Anthropic) and `x-goog-api-key` (Google).
+ * Matching is case-insensitive because HTTP header names are.
+ */
+const CREDENTIAL_HEADERS = new Set(['authorization', 'api-key', 'x-api-key', 'x-goog-api-key']);
+
+function isCredentialHeader(name: string): boolean {
+ return CREDENTIAL_HEADERS.has(name.trim().toLowerCase());
+}
+
+/** Duck-typed Headers check so a Headers from any realm is recognized. */
+function isHeadersInstance(value: unknown): value is Headers {
+ return (
+ typeof value === 'object' &&
+ value !== null &&
+ typeof (value as Headers).forEach === 'function' &&
+ typeof (value as Headers).get === 'function' &&
+ typeof (value as Headers).delete === 'function'
+ );
+}
+
+function hasCredentialHeaders(headers: HeadersInit): boolean {
+ if (isHeadersInstance(headers)) {
+ for (const name of headers.keys()) {
+ if (isCredentialHeader(name)) return true;
+ }
+ return false;
+ }
+ if (Array.isArray(headers)) {
+ return headers.some(([name]) => isCredentialHeader(name));
+ }
+ return Object.keys(headers).some((name) => isCredentialHeader(name));
+}
+
+/**
+ * Return a copy of `headers` without the credential headers, preserving the
+ * original shape (`Headers` instance, string-pair array or plain object) so a
+ * same-shape header block reaches the next hop.
+ */
+function stripCredentialHeaders(headers: HeadersInit | undefined): HeadersInit | undefined {
+ if (!headers) return headers;
+ if (isHeadersInstance(headers)) {
+ const next = new Headers(headers);
+ for (const name of CREDENTIAL_HEADERS) next.delete(name);
+ return next;
+ }
+ if (Array.isArray(headers)) {
+ return headers.filter(([name]) => !isCredentialHeader(name));
+ }
+ const next: Record = {};
+ for (const [name, value] of Object.entries(headers)) {
+ if (!isCredentialHeader(name)) next[name] = value;
+ }
+ return next;
+}
+
+/**
+ * A request body that is a stream is consumed by the hop that is being sent,
+ * so it cannot be replayed onto a redirect target. Anything that is neither a
+ * string nor a static buffer-like value counts as unreplayable.
+ */
+function isStreamBody(body: unknown): boolean {
+ if (!body || typeof body !== 'object') return false;
+ const candidate = body as {
+ getReader?: unknown;
+ pipe?: unknown;
+ [Symbol.asyncIterator]?: unknown;
+ };
+ return (
+ typeof candidate.getReader === 'function' ||
+ typeof candidate.pipe === 'function' ||
+ typeof candidate[Symbol.asyncIterator] === 'function'
+ );
+}
+
+function requestUrlString(input: RequestInfo | URL): string {
+ if (typeof input === 'string') return input;
+ if (input instanceof URL) return input.toString();
+ return input.url;
+}
+
+/**
+ * Fetch `input`, following at most {@link MAX_REDIRECT_HOPS} redirects and
+ * validating every hop target with {@link validateUrlForSSRF} before the next
+ * request is made. Resolves with the first non-redirect response.
+ */
+export async function fetchWithRedirectValidation(
+ input: RequestInfo | URL,
+ init?: RequestInit,
+): Promise {
+ let currentUrl = requestUrlString(input);
+ // init of the hop about to be issued; credential headers may be removed
+ // from it before a cross-origin hop, never mutating the caller's init.
+ let hopInit: RequestInit | undefined = init;
+ for (let hop = 0; ; hop++) {
+ const response = await fetch(currentUrl, { ...hopInit, redirect: 'manual' });
+ if (response.status < 300 || response.status >= 400) return response;
+
+ const location = response.headers.get('location');
+ if (!location) throw new Error('Provider request redirected without a Location header');
+ if (hop >= MAX_REDIRECT_HOPS) {
+ throw new Error(`Provider request exceeded ${MAX_REDIRECT_HOPS} redirects`);
+ }
+
+ let nextUrl: string;
+ try {
+ nextUrl = new URL(location, currentUrl).href; // resolve relative redirects
+ } catch {
+ throw new Error('Provider request received an invalid redirect Location');
+ }
+
+ const ssrfError = await validateUrlForSSRF(nextUrl);
+ if (ssrfError) throw new Error(ssrfError);
+
+ // A streaming request body has been consumed by the request that just
+ // answered with a redirect and cannot be replayed; fail loudly instead of
+ // forwarding the next hop with an empty body.
+ if (isStreamBody(hopInit?.body)) {
+ throw new Error(
+ 'Provider request cannot follow a redirect: its streaming request body cannot be replayed',
+ );
+ }
+
+ // Credentials are scoped to the origin that issued them. The platform
+ // fetch drops Authorization itself on a cross-origin redirect; mirror that
+ // here so provider keys are not forwarded to a different origin.
+ // Same-origin hops keep their headers untouched.
+ if (
+ new URL(nextUrl).origin !== new URL(currentUrl).origin &&
+ hopInit?.headers &&
+ hasCredentialHeaders(hopInit.headers)
+ ) {
+ hopInit = { ...hopInit, headers: stripCredentialHeaders(hopInit.headers) };
+ }
+
+ currentUrl = nextUrl;
+ }
+}
diff --git a/lib/server/resolve-model.ts b/lib/server/resolve-model.ts
index e45a0ab..dfad75f 100644
--- a/lib/server/resolve-model.ts
+++ b/lib/server/resolve-model.ts
@@ -15,6 +15,7 @@ import {
resolveProxy,
} from '@/lib/server/provider-config';
import { validateUrlForSSRF } from '@/lib/server/ssrf-guard';
+import { fetchWithRedirectValidation } from '@/lib/server/fetch-with-redirect-validation';
import { getStageRoute, type LlmStage } from '@/lib/server/model-routes';
export interface ResolvedModel extends ModelWithInfo {
@@ -80,9 +81,13 @@ export async function resolveModel(params: {
const clientBaseUrlParam = routed ? undefined : params.baseUrl;
// Server-managed providers are admin-owned: the operator's key and base URL
- // are authoritative and any client-sent override is ignored. SSRF validation
- // therefore applies only to unmanaged providers, where the base URL really is
- // client-supplied. (Server-configured URLs are trusted by the operator.)
+ // are authoritative and any client-sent override is ignored. Origin URL
+ // validation therefore applies only to unmanaged providers, where the base
+ // URL really is client-supplied. (Server-configured URLs are trusted by the
+ // operator.) Every provider fetch still runs through a transport that
+ // re-validates redirect hops: no upstream can be assumed to redirect only to
+ // public targets, so the hop target is checked regardless of who chose the
+ // origin.
const managed = isServerConfiguredProvider('providers', providerId);
const registeredProviderType = getProvider(providerId)?.type;
if (
@@ -101,7 +106,7 @@ export async function resolveModel(params: {
throw new Error('Amazon Bedrock must be enabled by the server operator before it can be used.');
}
const clientBaseUrl = managed ? undefined : clientBaseUrlParam || undefined;
- if (clientBaseUrl && process.env.NODE_ENV === 'production') {
+ if (clientBaseUrl) {
const ssrfError = await validateUrlForSSRF(clientBaseUrl);
if (ssrfError) {
throw new Error(ssrfError);
@@ -118,6 +123,9 @@ export async function resolveModel(params: {
baseUrl,
proxy,
providerType: clientProviderType as ProviderType | undefined,
+ // Re-validate every redirect hop of the outbound request (see
+ // fetchWithRedirectValidation); the base URL above is checked at origin.
+ fetchImpl: fetchWithRedirectValidation,
});
// Thinking arbitration mirrors model routing — the route carries a full
diff --git a/lib/server/sanitize-scene-content.ts b/lib/server/sanitize-scene-content.ts
new file mode 100644
index 0000000..d68bff8
--- /dev/null
+++ b/lib/server/sanitize-scene-content.ts
@@ -0,0 +1,301 @@
+/**
+ * Scene-content HTML sanitization for the classroom persistence boundary.
+ *
+ * INVARIANT: stored slide HTML is restricted to the formatting vocabulary the
+ * renderer produces. Slide element content is authored as ProseMirror HTML and
+ * is later injected into the DOM verbatim (`dangerouslySetInnerHTML` on the
+ * `ProseMirror-static` containers), so anything allowed through here must be
+ * exactly the set of tags / classes / inline styles the editor schemas and the
+ * KaTeX renderer emit — nothing more. Everything executable (script tags,
+ * event-handler attributes, `javascript:` URLs, embedded-object tags) is
+ * outside that vocabulary and is removed here, once, at the boundary where
+ * classroom content enters or leaves storage, instead of at each render sink.
+ *
+ * The allowlists below were derived empirically:
+ * - the ProseMirror schemas in `lib/prosemirror/schema` and in
+ * `@openmaic/editor`'s text schema (marks/nodes → their `toDOM` output),
+ * - the renderer text/shape/table element components,
+ * - real stage/scene fixtures in `eval/`, `tests/` and the
+ * `@openmaic/editor` round-trip tests,
+ * - actual KaTeX HTML snapshots rendered with the repo's `katex`.
+ *
+ * LaTeX elements persist a `html` snapshot produced by
+ * `katex.renderToString(..., { output: 'html' })` (see
+ * `lib/edit/slide-edit-elements.ts`); that output is spans + layout SVGs and
+ * needs its own policy so formulas are not flattened.
+ */
+import sanitizeHtml, { type IOptions } from 'sanitize-html';
+
+// ---------------------------------------------------------------------------
+// Allowlist primitives
+// ---------------------------------------------------------------------------
+
+/**
+ * Inline styles are kept by *property* (colors, sizes, font families,
+ * alignment, indentation, list markers, …) rather than wholesale. Values are
+ * constrained to plain CSS tokens: no `url(...)`, no `expression(...)`, no
+ * `@`-rules, no CSS-embedded script schemes. The individual properties a
+ * renderer may emit are enumerated below — a property not in the list is
+ * dropped, so a stray `background: url(...)` or `behavior: url(...)` cannot
+ * ride in through the `style` attribute.
+ */
+const SAFE_CSS_VALUE =
+ /^(?!.*(?:url\s*\(|expression\s*\(|@|behavior\s*:|-moz-binding\s*:|vbscript:|javascript:))[^<>{};]{0,240}$/i;
+
+/**
+ * Every CSS property the ProseMirror schemas, the PPTX text importer and the
+ * KaTeX HTML snapshot emit inline. KaTeX additionally lays out spans with
+ * `position`/`top`/`left`/`bottom`/`right`; prose content never does, so those
+ * stay out of the prose policy.
+ */
+const STYLE_PROPERTIES = [
+ 'color',
+ 'background-color',
+ 'font-size',
+ 'font-family',
+ 'font-weight',
+ 'font-style',
+ 'text-align',
+ 'text-indent',
+ 'text-decoration',
+ 'text-decoration-line',
+ 'text-decoration-style',
+ 'text-transform',
+ 'letter-spacing',
+ 'word-spacing',
+ 'line-height',
+ 'vertical-align',
+ 'display',
+ 'width',
+ 'height',
+ 'min-width',
+ 'max-width',
+ 'min-height',
+ 'max-height',
+ 'margin',
+ 'margin-top',
+ 'margin-right',
+ 'margin-bottom',
+ 'margin-left',
+ 'padding',
+ 'padding-top',
+ 'padding-right',
+ 'padding-bottom',
+ 'padding-left',
+ 'white-space',
+ 'box-sizing',
+ 'list-style-type',
+ 'word-break',
+ 'word-wrap',
+ 'border',
+ 'border-top',
+ 'border-right',
+ 'border-bottom',
+ 'border-left',
+ 'border-width',
+ 'border-top-width',
+ 'border-right-width',
+ 'border-bottom-width',
+ 'border-left-width',
+ 'border-style',
+ 'border-top-style',
+ 'border-right-style',
+ 'border-bottom-style',
+ 'border-left-style',
+ 'border-color',
+ 'border-top-color',
+ 'border-right-color',
+ 'border-bottom-color',
+ 'border-left-color',
+] as const;
+
+/** Positioning geometry: used only by KaTeX layout spans, never by prose. */
+const LAYOUT_STYLE_PROPERTIES = ['top', 'bottom', 'left', 'right', 'position'] as const;
+
+const LATEX_STYLE_PROPERTIES: readonly string[] = [...STYLE_PROPERTIES, ...LAYOUT_STYLE_PROPERTIES];
+
+function styleRules(properties: readonly string[]): Record {
+ const rules: Record = {};
+ for (const property of properties) {
+ rules[property] = [SAFE_CSS_VALUE];
+ }
+ return rules;
+}
+
+/** `allowedStyles` shape: per-tag style maps; `'*'` applies the rules to every tag. */
+function allowedStylesByTag(
+ properties: readonly string[],
+): Record> {
+ return { '*': styleRules(properties) };
+}
+
+// ---------------------------------------------------------------------------
+// Prose policy — text elements, shape text and table cell text
+// ---------------------------------------------------------------------------
+
+/**
+ * HTML vocabulary of text-element content (ProseMirror serialized HTML plus
+ * the legacy/imported constructs the renderer still understands).
+ */
+export const PROSE_ALLOWED_TAGS = [
+ 'p',
+ 'br',
+ 'div',
+ 'blockquote',
+ 'ol',
+ 'ul',
+ 'li',
+ 'a',
+ 'span',
+ 'strong',
+ 'em',
+ 'b',
+ 'i',
+ 'u',
+ 's',
+ 'strike',
+ 'sub',
+ 'sup',
+ 'code',
+ 'mark',
+ // Structural table tags: keep legacy cell markup that a stored cell/body may
+ // still carry so a nested table renders instead of being flattened.
+ 'table',
+ 'thead',
+ 'tbody',
+ 'tfoot',
+ 'tr',
+ 'td',
+ 'th',
+ 'caption',
+ 'colgroup',
+ 'col',
+] as const;
+
+const PROSE_ATTRIBUTES: Record = {
+ '*': ['class', 'style'],
+ a: ['href', 'title', 'target', 'rel', 'name'],
+ p: ['align', 'data-indent'],
+ ol: ['start'],
+ mark: ['data-index'],
+ td: ['colspan', 'rowspan'],
+ th: ['colspan', 'rowspan'],
+};
+
+const PROSE_OPTIONS: IOptions = {
+ allowedTags: [...PROSE_ALLOWED_TAGS],
+ allowedAttributes: PROSE_ATTRIBUTES,
+ allowedStyles: allowedStylesByTag(STYLE_PROPERTIES),
+};
+
+/**
+ * Sanitize one prose-HTML string (a text element's `content`, a shape's
+ * `text.content`, or a table cell's `text`).
+ */
+export function sanitizeProseHtml(html: string): string {
+ return sanitizeHtml(html, PROSE_OPTIONS);
+}
+
+// ---------------------------------------------------------------------------
+// LaTeX policy — KaTeX-rendered `html` snapshots on latex elements
+// ---------------------------------------------------------------------------
+
+/**
+ * KaTeX `output: 'html'` emits nested `` nodes plus
+ * layout `'));
+ });
+
+ it('keeps real KaTeX HTML (spans + layout svg) semantically unchanged', () => {
+ const formulas = [
+ 'E = mc^2',
+ '\\frac{a}{b} + \\sqrt{x^2 + y^2}',
+ 'H_2O \\quad \\text{water}',
+ '\\sum_{i=1}^{n} i^2',
+ '\\begin{cases} 1 & x>0 \\\\ 0 & x\\le 0 \\end{cases}',
+ '\\cancel{5} + \\overrightarrow{AB}',
+ ];
+ for (const formula of formulas) {
+ const html = katex.renderToString(formula, {
+ throwOnError: false,
+ displayMode: true,
+ output: 'html',
+ });
+ expect(canon(sanitizeLatexHtml(html)), formula).toEqual(canon(html));
+ }
+ });
+
+ it('preserves the camelCase layout-svg attributes browsers need', () => {
+ const html = katex.renderToString('\\sqrt{x}', {
+ throwOnError: false,
+ displayMode: true,
+ output: 'html',
+ });
+ const output = sanitizeLatexHtml(html);
+ if (html.includes('viewBox=')) {
+ expect(output).toContain('viewBox=');
+ }
+ if (html.includes('preserveAspectRatio=')) {
+ expect(output).toContain('preserveAspectRatio=');
+ }
+ });
+});
+
+// ---------------------------------------------------------------------------
+// 2. Fidelity: realistic slide formatting survives unchanged
+// ---------------------------------------------------------------------------
+
+describe('sanitizeProseHtml — fidelity over the editor round-trip corpus', () => {
+ it('keeps nested marks, links and alignment (editor round-trip fixture)', () => {
+ // Verbatim from packages/@openmaic/editor/test/react/text/prosemirror-schema.test.ts.
+ const html =
+ 'MAIC
One
';
+ expectProseUnchanged(html);
+ });
+
+ it('keeps lists in the exact shape the renderer emits them', () => {
+ // Verbatim from packages/@openmaic/renderer/test/SlideCanvas.test.tsx.
+ expectProseUnchanged('- Number
');
+ expectProseUnchanged(
+ 'B
',
+ );
+ });
+
+ it('keeps paragraph geometry imported from PPTX (round-trip fixture)', () => {
+ // Verbatim from packages/@openmaic/editor/test/react/text/prosemirror-schema.test.ts.
+ expectProseUnchanged(
+ '',
+ );
+ });
+
+ it('keeps bullet-glyph inline-block spans (round-trip fixture)', () => {
+ // Verbatim from packages/@openmaic/editor/test/react/text/prosemirror-schema.test.ts.
+ expectProseUnchanged(
+ '■1954年清华大学首创
',
+ );
+ expectProseUnchanged(
+ '■•Text
',
+ );
+ });
+
+ it('keeps explicit line breaks and run-level spans (round-trip fixture)', () => {
+ // Verbatim from packages/@openmaic/editor/test/react/text/prosemirror-schema.test.ts.
+ expectProseUnchanged(
+ '1954年清华大学首创“先进集体”
评选制度
',
+ );
+ });
+
+ it('keeps character spacing, indentation and nowrap (round-trip fixtures)', () => {
+ // Verbatim from packages/@openmaic/editor/test/react/text/prosemirror-schema.test.ts.
+ expectProseUnchanged(
+ 'Indented text
',
+ );
+ expectProseUnchanged('在集体中成长,与集体共成长
');
+ expectProseUnchanged('Text
');
+ });
+
+ it('keeps inline marks: code, sub, sup, mark, strike variants, underline', () => {
+ expectProseUnchanged(
+ 'text const x = 1 sub sup hi del old under b i',
+ );
+ });
+
+ it('keeps structural table markup when present in a stored body', () => {
+ expectProseUnchanged(
+ '',
+ );
+ });
+});
+
+describe('real stored scene fixtures — full payload walker fidelity', () => {
+ it('leaves every HTML-bearing string of real scene fixtures unchanged', () => {
+ const strings = fixtureHtmlStrings(...evalSceneFixtures);
+ expect(strings.length).toBeGreaterThan(20);
+ for (const html of strings) {
+ expectProseUnchanged(html);
+ }
+ });
+
+ it('leaves real text-element content unchanged when sanitizing a whole scene', () => {
+ // Real scene structure: eval/orchestration/scenarios/answer-content.json,
+ // scene 0 text element "content".
+ const scene = {
+ id: 'scene-0',
+ stageId: 'eval-answer-content',
+ title: '二次函数',
+ order: 0,
+ type: 'slide',
+ content: {
+ type: 'slide',
+ canvas: {
+ id: 'slide-0',
+ viewportSize: 1000,
+ viewportRatio: 0.5625,
+ theme: {
+ backgroundColor: '#ffffff',
+ themeColors: ['#5b9bd5'],
+ fontColor: '#333333',
+ fontName: 'Microsoft YaHei',
+ },
+ elements: [
+ {
+ type: 'text',
+ id: 'title-el',
+ content: '二次函数 y = ax² + bx + c
',
+ left: 50,
+ top: 50,
+ width: 900,
+ height: 100,
+ rotate: 0,
+ defaultFontName: 'Microsoft YaHei',
+ defaultColor: '#333333',
+ },
+ ],
+ },
+ },
+ };
+
+ const sanitized = sanitizeSceneContent(scene);
+ const element = sanitized.content.canvas.elements[0];
+ expect(canon(element.content)).toEqual(
+ canon('二次函数 y = ax² + bx + c
'),
+ );
+ expect(sanitized).not.toBe(scene);
+ });
+});
+
+// ---------------------------------------------------------------------------
+// 3. Payload walker: element-kind coverage and untouched non-HTML fields
+// ---------------------------------------------------------------------------
+
+function slideSceneWithElements(elements: unknown[]): unknown {
+ return {
+ id: 'scene-1',
+ stageId: 'stage-1',
+ title: 'Scene',
+ order: 0,
+ type: 'slide',
+ content: {
+ type: 'slide',
+ canvas: {
+ id: 'slide-1',
+ viewportSize: 1000,
+ viewportRatio: 0.5625,
+ theme: {
+ backgroundColor: '#ffffff',
+ themeColors: ['#5b9bd5'],
+ fontColor: '#333333',
+ fontName: 'Microsoft YaHei',
+ },
+ elements,
+ },
+ },
+ };
+}
+
+describe('sanitizeSceneContent — payload walker', () => {
+ it('sanitizes text, shape text and table cell text and latex snapshots in one pass', () => {
+ const scene = slideSceneWithElements([
+ {
+ type: 'text',
+ id: 't1',
+ content: '
keep bold
',
+ left: 0,
+ top: 0,
+ width: 100,
+ height: 40,
+ rotate: 0,
+ defaultFontName: 'Arial',
+ defaultColor: '#333',
+ },
+ {
+ type: 'shape',
+ id: 's1',
+ left: 0,
+ top: 0,
+ width: 100,
+ height: 100,
+ rotate: 0,
+ viewBox: [100, 100],
+ path: 'M0 0',
+ fixedRatio: true,
+ fill: '#fff',
+ text: {
+ content: 'shape text
',
+ defaultFontName: 'Arial',
+ defaultColor: '#333',
+ align: 'middle',
+ },
+ },
+ {
+ type: 'table',
+ id: 'tbl1',
+ left: 0,
+ top: 0,
+ width: 100,
+ height: 60,
+ rotate: 0,
+ outline: { width: 1, color: '#000', style: 'solid' },
+ colWidths: [1],
+ cellMinHeight: 30,
+ data: [
+ [
+ {
+ id: 'c1',
+ colspan: 1,
+ rowspan: 1,
+ text: 'H2O',
+ },
+ ],
+ ],
+ },
+ {
+ type: 'latex',
+ id: 'l1',
+ left: 0,
+ top: 0,
+ width: 200,
+ height: 60,
+ rotate: 0,
+ latex: 'x',
+ html: 'x',
+ color: '#000',
+ fixedRatio: true,
+ },
+ ]);
+
+ const sanitized = sanitizeSceneContent(scene) as {
+ content: { canvas: { elements: Array> } };
+ };
+ const [textEl, shapeEl, tableEl, latexEl] = sanitized.content.canvas.elements;
+
+ expect(String(textEl.content)).not.toContain('onerror');
+ expect(String(textEl.content)).not.toContain('
keep bold
'));
+
+ const shapeText = shapeEl.text as Record;
+ expect(String(shapeText.content)).not.toContain('onclick');
+ expect(canon(String(shapeText.content))).toEqual(canon('shape text
'));
+
+ const cellText = (tableEl.data as Array>>)[0][0].text as string;
+ expect(cellText).not.toContain('