openmaic-custom/tests/api/proxy-media.test.ts
wyuc 86c8e0c543
feat: inline external assets at export for offline classrooms (#596) (#613)
* feat(export): add external-asset reference scanner for HTML inlining

* feat(export): add cached asset fetcher and data-uri encoder

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(export): recursively inline url() refs inside stylesheets

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(export): orchestrate inlining of links, scripts, images, and inline css

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor(export): drop dead escapeAttr, harden importmap skip in scanner

* feat(export): inline importmap modules incl three/addons graph closure

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* refactor(export): extract shared module to break inline-assets import cycle

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(export): inline interactive-scene assets into .maic.zip at export

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(export): inline interactive assets in Resource Pack export too

* docs: document offline export asset inlining

* style: prettier formatting

* fix(test): resolve tsc type errors in export-classroom-inline test

* fix(export): keep importmap prefix fallback on partial failure, chunk base64, preserve media attr, log pptx inline failures

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* perf(export): parallelize asset fetching, share fetcher across scenes, promise-cache

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(export): retry transient asset fetches, bound concurrency, warn user on partial inline

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* perf(export): inline only woff2 fonts, drop woff/ttf siblings to halve size

Within @font-face blocks that have a woff2 url(), rewrite sibling woff/ttf/otf/eot
refs to url(about:invalid) instead of inlining them. Falls back to full inline for
ttf-only blocks. Drops katex output from ~1.79MB to ~0.71MB (~3x fewer font fetches).

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* i18n(export): translate partial-inline warning and surface failed asset hosts

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* feat(proxy-media): follow redirects with per-hop SSRF revalidation (#398)

Replace blanket redirect rejection with a bounded 5-hop follow loop that
re-validates every Location target through validateUrlForSSRF before
fetching, preventing redirect-to-internal SSRF while allowing CDN
redirects (e.g. cdn.tailwindcss.com 302→/3.4.17).

* feat(export): route asset inlining through proxy-media to bypass CORS

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

* fix(export): keep importmap prefix fallback, forward proxy 4xx, cap proxy size, re-export FetchAsset

* style: prettier formatting for proxy-media + proxied-fetch

* fix(export): report CSS-nested asset failures in inline report

Co-Authored-By: Claude Sonnet 4.6 <noreply@anthropic.com>

---------

Co-authored-by: Claude Sonnet 4.6 <noreply@anthropic.com>
Co-authored-by: 杨慎 <117187635+cosarah@users.noreply.github.com>
2026-05-31 18:36:39 +08:00

203 lines
6.5 KiB
TypeScript

import { beforeEach, describe, expect, it, vi } from 'vitest';
import type { NextRequest } from 'next/server';
const mocks = vi.hoisted(() => ({ validateUrlForSSRF: vi.fn() }));
vi.mock('@/lib/server/ssrf-guard', () => ({ validateUrlForSSRF: mocks.validateUrlForSSRF }));
vi.mock('@/lib/logger', () => ({
createLogger: () => ({
info: vi.fn(),
warn: vi.fn(),
error: vi.fn(),
debug: vi.fn(),
}),
}));
async function postProxy(body: Record<string, unknown>) {
const { POST } = await import('@/app/api/proxy-media/route');
const req = new Request('http://localhost/api/proxy-media', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(body),
});
return POST(req as unknown as NextRequest);
}
describe('POST /api/proxy-media', () => {
beforeEach(() => {
vi.resetModules();
vi.restoreAllMocks();
mocks.validateUrlForSSRF.mockReset();
});
it('1. direct 200: returns blob with forwarded content-type', async () => {
mocks.validateUrlForSSRF.mockResolvedValue(null);
const bodyBytes = new Uint8Array([1, 2, 3, 4]);
vi.stubGlobal(
'fetch',
vi.fn().mockResolvedValue(
new Response(bodyBytes, {
status: 200,
headers: { 'Content-Type': 'image/png' },
}),
),
);
const res = await postProxy({ url: 'https://example.com/image.png' });
expect(res.status).toBe(200);
expect(res.headers.get('Content-Type')).toBe('image/png');
const buf = await res.arrayBuffer();
expect(new Uint8Array(buf)).toEqual(bodyBytes);
});
it('2. single redirect followed: validates both initial and redirect target', async () => {
mocks.validateUrlForSSRF.mockResolvedValue(null);
const finalBytes = new Uint8Array([10, 20]);
const fetchMock = vi
.fn()
.mockResolvedValueOnce(
new Response(null, {
status: 302,
headers: { location: 'https://cdn.example.com/final.png' },
}),
)
.mockResolvedValueOnce(
new Response(finalBytes, {
status: 200,
headers: { 'Content-Type': 'image/png' },
}),
);
vi.stubGlobal('fetch', fetchMock);
const res = await postProxy({ url: 'https://example.com/redirect' });
expect(res.status).toBe(200);
// validateUrlForSSRF called for both initial URL and redirect target
expect(mocks.validateUrlForSSRF).toHaveBeenCalledTimes(2);
expect(mocks.validateUrlForSSRF).toHaveBeenNthCalledWith(1, 'https://example.com/redirect');
expect(mocks.validateUrlForSSRF).toHaveBeenNthCalledWith(
2,
'https://cdn.example.com/final.png',
);
expect(fetchMock).toHaveBeenCalledTimes(2);
});
it('3. redirect to private/blocked URL is rejected (SSRF guard)', async () => {
// Initial URL passes; redirect target is blocked
mocks.validateUrlForSSRF
.mockResolvedValueOnce(null) // initial URL: ok
.mockResolvedValueOnce('Local/private network URLs are not allowed'); // redirect target: blocked
vi.stubGlobal(
'fetch',
vi.fn().mockResolvedValueOnce(
new Response(null, {
status: 302,
headers: { location: 'http://192.168.1.1/secret' },
}),
),
);
const res = await postProxy({ url: 'https://example.com/harmless' });
const json = await res.json();
expect(res.status).toBe(403);
expect(json).toMatchObject({ errorCode: 'INVALID_URL' });
});
it('4. too many redirects returns 502 TOO_MANY_REDIRECTS', async () => {
mocks.validateUrlForSSRF.mockResolvedValue(null);
// Every fetch returns 302 → infinite loop hits MAX_REDIRECTS (5)
vi.stubGlobal(
'fetch',
vi.fn().mockResolvedValue(
new Response(null, {
status: 302,
headers: { location: 'https://example.com/loop' },
}),
),
);
const res = await postProxy({ url: 'https://example.com/loop' });
const json = await res.json();
expect(res.status).toBe(502);
expect(json).toMatchObject({ errorCode: 'TOO_MANY_REDIRECTS' });
});
it('5. initial URL blocked: 403 returned, no fetch attempted', async () => {
mocks.validateUrlForSSRF.mockResolvedValue('Local/private network URLs are not allowed');
const fetchMock = vi.fn();
vi.stubGlobal('fetch', fetchMock);
const res = await postProxy({ url: 'http://169.254.169.254/metadata' });
const json = await res.json();
expect(res.status).toBe(403);
expect(json).toMatchObject({ errorCode: 'INVALID_URL' });
expect(fetchMock).not.toHaveBeenCalled();
});
it('6. redirect without Location header returns 502', async () => {
mocks.validateUrlForSSRF.mockResolvedValue(null);
vi.stubGlobal(
'fetch',
vi.fn().mockResolvedValue(
new Response(null, {
status: 302,
// no location header
}),
),
);
const res = await postProxy({ url: 'https://example.com/bad-redirect' });
const json = await res.json();
expect(res.status).toBe(502);
expect(json).toMatchObject({ errorCode: 'UPSTREAM_ERROR' });
});
it('7. upstream 404 returns 404 UPSTREAM_ERROR (forwarded, not 502)', async () => {
mocks.validateUrlForSSRF.mockResolvedValue(null);
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(null, { status: 404 })));
const res = await postProxy({ url: 'https://example.com/not-found' });
const json = await res.json();
expect(res.status).toBe(404);
expect(json).toMatchObject({ errorCode: 'UPSTREAM_ERROR' });
});
it('8. upstream 503 is collapsed to 502', async () => {
mocks.validateUrlForSSRF.mockResolvedValue(null);
vi.stubGlobal('fetch', vi.fn().mockResolvedValue(new Response(null, { status: 503 })));
const res = await postProxy({ url: 'https://example.com/server-error' });
const json = await res.json();
expect(res.status).toBe(502);
expect(json).toMatchObject({ errorCode: 'UPSTREAM_ERROR' });
});
it('9. upstream Content-Length exceeding cap returns 502', async () => {
mocks.validateUrlForSSRF.mockResolvedValue(null);
vi.stubGlobal(
'fetch',
vi.fn().mockResolvedValue(
new Response(null, {
status: 200,
headers: {
'Content-Type': 'application/octet-stream',
'Content-Length': String(26 * 1024 * 1024), // 26 MiB > 25 MiB cap
},
}),
),
);
const res = await postProxy({ url: 'https://example.com/huge-asset' });
const json = await res.json();
expect(res.status).toBe(502);
expect(json).toMatchObject({ errorCode: 'UPSTREAM_ERROR' });
});
});