mirror of
https://github.com/shumaiOne/shumai.git
synced 2026-11-23 11:46:53 +00:00
fix(auth,web): gracefully degrade MCP on remote HTTP and cache production static assets (#519)
* fix: gracefully handle remote HTTP URLs for MCP and cache production static assets * test(mcp): add remote http mcp integration test and fix static etag normalization and fallback error
This commit is contained in:
+22
-13
@@ -21,6 +21,7 @@ import { embeddingService } from '@shumai/core/src/search/embedding-service'
|
||||
import { sandboxService } from '@shumai/core'
|
||||
import { notificationJobService } from '@shumai/core/src/notification/notification-job'
|
||||
import { autoArchiveJobService } from '@shumai/core/src/asset/auto-archive-job'
|
||||
import { createHtmlHandler, createStaticFileHandler } from './static'
|
||||
|
||||
if (process.argv.includes('--check')) {
|
||||
console.log('✅ Web app evaluated successfully!')
|
||||
@@ -151,7 +152,8 @@ async function run() {
|
||||
for (const file of bundle.files) {
|
||||
const routePath = file.path.startsWith('.') ? file.path.slice(1) : file.path
|
||||
const filePath = join(import.meta.dir, file.path)
|
||||
routes[routePath] = () => new Response(Bun.file(filePath), { headers: file.headers })
|
||||
const isHtml = file.loader === 'html' || file.path.endsWith('.html')
|
||||
routes[routePath] = createStaticFileHandler(filePath, file.headers, !isHtml)
|
||||
}
|
||||
|
||||
const sampleFile = bundle.files[0]?.path || bundle.index || ''
|
||||
@@ -163,13 +165,14 @@ async function run() {
|
||||
const routePath = '/' + pdfWorkerFile
|
||||
const filePath = join(bundleDir, pdfWorkerFile)
|
||||
const bunFile = Bun.file(filePath)
|
||||
routes[routePath] = () =>
|
||||
new Response(bunFile, {
|
||||
headers: {
|
||||
'content-type': 'text/javascript;charset=utf-8',
|
||||
etag: `"${bunFile.size}-${bunFile.lastModified}"`,
|
||||
},
|
||||
})
|
||||
routes[routePath] = createStaticFileHandler(
|
||||
filePath,
|
||||
{
|
||||
'content-type': 'text/javascript;charset=utf-8',
|
||||
etag: `"${bunFile.size}-${bunFile.lastModified}"`,
|
||||
},
|
||||
true,
|
||||
)
|
||||
}
|
||||
} catch (err) {
|
||||
console.warn('Failed to register pdf.worker route:', err)
|
||||
@@ -185,16 +188,22 @@ async function run() {
|
||||
.replaceAll('href="./', 'href="/')
|
||||
.replaceAll('src="./', 'src="/')
|
||||
.replaceAll('content="./', 'content="/')
|
||||
const serveMainHtml = () => new Response(mainHtmlText, { headers: mainHtmlHeaders })
|
||||
const serveMainHtml = createHtmlHandler(mainHtmlText, mainHtmlHeaders)
|
||||
|
||||
routes['/'] = serveMainHtml
|
||||
routes['/*'] = serveMainHtml
|
||||
} else {
|
||||
const fallbackHtmlPath = join(import.meta.dir, 'shumai-app.html')
|
||||
const serveFallbackHtml = () =>
|
||||
new Response(Bun.file(fallbackHtmlPath), {
|
||||
headers: { 'content-type': 'text/html;charset=utf-8' },
|
||||
})
|
||||
const fallbackHtmlFile = Bun.file(fallbackHtmlPath)
|
||||
if (!(await fallbackHtmlFile.exists())) {
|
||||
throw new Error(
|
||||
`Production HTML bundle is missing: neither bundle.files nor ${fallbackHtmlPath} exists.`,
|
||||
)
|
||||
}
|
||||
const fallbackRaw = await fallbackHtmlFile.text()
|
||||
const serveFallbackHtml = createHtmlHandler(fallbackRaw, {
|
||||
'content-type': 'text/html;charset=utf-8',
|
||||
})
|
||||
routes['/'] = serveFallbackHtml
|
||||
routes['/*'] = serveFallbackHtml
|
||||
}
|
||||
|
||||
@@ -0,0 +1,175 @@
|
||||
import { afterAll, beforeAll, describe, expect, it } from 'vitest'
|
||||
import { writeFileSync, unlinkSync } from 'node:fs'
|
||||
import { join } from 'node:path'
|
||||
import { tmpdir } from 'node:os'
|
||||
import { createHtmlHandler, createStaticFileHandler, isEtagMatching, normalizeEtag } from './static'
|
||||
|
||||
describe('Static Asset Serving & Caching', () => {
|
||||
const tempChunkPath = join(tmpdir(), `test-chunk-${Date.now()}.js`)
|
||||
const chunkContent = 'console.log("chunk loaded");'
|
||||
|
||||
beforeAll(() => {
|
||||
writeFileSync(tempChunkPath, chunkContent, 'utf8')
|
||||
})
|
||||
|
||||
afterAll(() => {
|
||||
try {
|
||||
unlinkSync(tempChunkPath)
|
||||
} catch {
|
||||
// Ignore cleanup error if already deleted
|
||||
}
|
||||
})
|
||||
|
||||
describe('normalizeEtag', () => {
|
||||
it('quotes unquoted ETags according to RFC 9110', () => {
|
||||
expect(normalizeEtag('hHRmXFeFVSk')).toBe('"hHRmXFeFVSk"')
|
||||
expect(normalizeEtag('ACJrxcts9Iw')).toBe('"ACJrxcts9Iw"')
|
||||
})
|
||||
|
||||
it('preserves already-quoted strong and weak ETags', () => {
|
||||
expect(normalizeEtag('"hHRmXFeFVSk"')).toBe('"hHRmXFeFVSk"')
|
||||
expect(normalizeEtag('W/"hHRmXFeFVSk"')).toBe('W/"hHRmXFeFVSk"')
|
||||
})
|
||||
|
||||
it('returns undefined for empty or missing ETags', () => {
|
||||
expect(normalizeEtag(undefined)).toBeUndefined()
|
||||
expect(normalizeEtag('')).toBeUndefined()
|
||||
expect(normalizeEtag(' ')).toBeUndefined()
|
||||
})
|
||||
})
|
||||
|
||||
describe('isEtagMatching', () => {
|
||||
it('matches exact etag string', () => {
|
||||
expect(isEtagMatching('"12345"', '"12345"')).toBe(true)
|
||||
})
|
||||
|
||||
it('matches weak etag to strong or weak candidates', () => {
|
||||
expect(isEtagMatching('W/"12345"', '"12345"')).toBe(true)
|
||||
expect(isEtagMatching('"12345"', 'W/"12345"')).toBe(true)
|
||||
expect(isEtagMatching('W/"12345"', 'W/"12345"')).toBe(true)
|
||||
})
|
||||
|
||||
it('matches wildcard *', () => {
|
||||
expect(isEtagMatching('"12345"', '*')).toBe(true)
|
||||
})
|
||||
|
||||
it('matches comma-separated candidate lists', () => {
|
||||
expect(isEtagMatching('"12345"', '"old-etag", "12345", "other"')).toBe(true)
|
||||
expect(isEtagMatching('"12345"', '"old-etag", "mismatch"')).toBe(false)
|
||||
})
|
||||
|
||||
it('returns false when etag or ifNoneMatch is missing or empty', () => {
|
||||
expect(isEtagMatching(undefined, '"12345"')).toBe(false)
|
||||
expect(isEtagMatching('"12345"', null)).toBe(false)
|
||||
expect(isEtagMatching('', '"12345"')).toBe(false)
|
||||
expect(isEtagMatching('"12345"', '')).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('createStaticFileHandler', () => {
|
||||
it('sets immutable Cache-Control for immutable content-hashed assets', async () => {
|
||||
const handler = createStaticFileHandler(
|
||||
tempChunkPath,
|
||||
{ 'content-type': 'text/javascript;charset=utf-8', etag: '"chunk-hash-1"' },
|
||||
true,
|
||||
)
|
||||
|
||||
const req = new Request('http://localhost/chunk-123.js')
|
||||
const res = handler(req)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(res.headers.get('content-type')).toBe('text/javascript;charset=utf-8')
|
||||
expect(res.headers.get('cache-control')).toBe('public, max-age=31536000, immutable')
|
||||
expect(res.headers.get('etag')).toBe('"chunk-hash-1"')
|
||||
expect(await res.text()).toBe(chunkContent)
|
||||
})
|
||||
|
||||
it('returns 304 Not Modified when If-None-Match matches the file etag', async () => {
|
||||
const handler = createStaticFileHandler(
|
||||
tempChunkPath,
|
||||
{ 'content-type': 'text/javascript;charset=utf-8', etag: '"chunk-hash-1"' },
|
||||
true,
|
||||
)
|
||||
|
||||
const req = new Request('http://localhost/chunk-123.js', {
|
||||
headers: { 'if-none-match': '"chunk-hash-1"' },
|
||||
})
|
||||
const res = handler(req)
|
||||
|
||||
expect(res.status).toBe(304)
|
||||
expect(res.headers.get('cache-control')).toBe('public, max-age=31536000, immutable')
|
||||
expect(res.headers.get('etag')).toBe('"chunk-hash-1"')
|
||||
expect(await res.text()).toBe('')
|
||||
})
|
||||
|
||||
it('sets no-cache Cache-Control for non-immutable static assets', async () => {
|
||||
const handler = createStaticFileHandler(
|
||||
tempChunkPath,
|
||||
{ 'content-type': 'text/plain', etag: '"plain-1"' },
|
||||
false,
|
||||
)
|
||||
|
||||
const req = new Request('http://localhost/robots.txt')
|
||||
const res = handler(req)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(res.headers.get('cache-control')).toBe('no-cache')
|
||||
})
|
||||
|
||||
it('normalizes unquoted manifest ETags to quoted RFC 9110 strings', async () => {
|
||||
const handler = createStaticFileHandler(
|
||||
tempChunkPath,
|
||||
{ 'content-type': 'text/javascript;charset=utf-8', etag: 'hHRmXFeFVSk' },
|
||||
true,
|
||||
)
|
||||
|
||||
const req = new Request('http://localhost/chunk-123.js')
|
||||
const res = handler(req)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(res.headers.get('etag')).toBe('"hHRmXFeFVSk"')
|
||||
|
||||
const revalidateRes = handler(
|
||||
new Request('http://localhost/chunk-123.js', {
|
||||
headers: { 'if-none-match': '"hHRmXFeFVSk"' },
|
||||
}),
|
||||
)
|
||||
expect(revalidateRes.status).toBe(304)
|
||||
expect(revalidateRes.headers.get('etag')).toBe('"hHRmXFeFVSk"')
|
||||
})
|
||||
})
|
||||
|
||||
describe('createHtmlHandler', () => {
|
||||
const htmlText = '<!DOCTYPE html><html><head><title>Shumai</title></head><body></body></html>'
|
||||
|
||||
it('sets no-cache and generates deterministic ETag for HTML', async () => {
|
||||
const handler = createHtmlHandler(htmlText, { 'content-type': 'text/html;charset=utf-8' })
|
||||
|
||||
const req = new Request('http://localhost/')
|
||||
const res = handler(req)
|
||||
|
||||
expect(res.status).toBe(200)
|
||||
expect(res.headers.get('content-type')).toBe('text/html;charset=utf-8')
|
||||
expect(res.headers.get('cache-control')).toBe('no-cache')
|
||||
const etag = res.headers.get('etag')
|
||||
expect(etag).toBeTruthy()
|
||||
expect(await res.text()).toBe(htmlText)
|
||||
})
|
||||
|
||||
it('returns 304 Not Modified when HTML If-None-Match matches', async () => {
|
||||
const handler = createHtmlHandler(htmlText, { 'content-type': 'text/html;charset=utf-8' })
|
||||
|
||||
const initialRes = handler(new Request('http://localhost/'))
|
||||
const etag = initialRes.headers.get('etag')!
|
||||
|
||||
const revalidateReq = new Request('http://localhost/', {
|
||||
headers: { 'if-none-match': etag },
|
||||
})
|
||||
const revalidateRes = handler(revalidateReq)
|
||||
|
||||
expect(revalidateRes.status).toBe(304)
|
||||
expect(revalidateRes.headers.get('cache-control')).toBe('no-cache')
|
||||
expect(await revalidateRes.text()).toBe('')
|
||||
})
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,106 @@
|
||||
/**
|
||||
* Helpers for serving static production assets with caching headers and ETag revalidation.
|
||||
*/
|
||||
|
||||
/**
|
||||
* Checks whether an incoming `If-None-Match` header matches the asset's ETag.
|
||||
* Supports weak ETags (`W/"..."`), exact matches, and comma-separated lists.
|
||||
*/
|
||||
export function isEtagMatching(etag: string | undefined, ifNoneMatch: string | null): boolean {
|
||||
if (!etag || !ifNoneMatch) {
|
||||
return false
|
||||
}
|
||||
|
||||
const cleanTarget = etag.trim().replace(/^W\//, '').replace(/^"|"$/g, '')
|
||||
if (!cleanTarget) {
|
||||
return false
|
||||
}
|
||||
|
||||
const candidates = ifNoneMatch
|
||||
.split(',')
|
||||
.map((candidate) => candidate.trim().replace(/^W\//, '').replace(/^"|"$/g, ''))
|
||||
|
||||
return candidates.includes(cleanTarget) || candidates.includes('*')
|
||||
}
|
||||
|
||||
/**
|
||||
* Normalizes an ETag to ensure it is enclosed in quotes according to RFC 9110.
|
||||
* Preserves weak validators (`W/"..."`).
|
||||
*/
|
||||
export function normalizeEtag(etag: string | undefined): string | undefined {
|
||||
if (!etag) {
|
||||
return undefined
|
||||
}
|
||||
const trimmed = etag.trim()
|
||||
if (!trimmed) {
|
||||
return undefined
|
||||
}
|
||||
if (trimmed.startsWith('W/"') && trimmed.endsWith('"')) {
|
||||
return trimmed
|
||||
}
|
||||
if (trimmed.startsWith('"') && trimmed.endsWith('"')) {
|
||||
return trimmed
|
||||
}
|
||||
return `"${trimmed.replace(/^"|"$/g, '')}"`
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a route handler for a static file on disk.
|
||||
* Content-hashed assets (e.g. `chunk-*.js`, `chunk-*.css`) should be marked `isImmutable: true`
|
||||
* to be aggressively cached locally by browsers across page reloads.
|
||||
*/
|
||||
export function createStaticFileHandler(
|
||||
filePath: string,
|
||||
baseHeaders: Record<string, string>,
|
||||
isImmutable: boolean,
|
||||
): (req: Request) => Response {
|
||||
const bunFile = Bun.file(filePath)
|
||||
const rawEtag = baseHeaders.etag || baseHeaders.ETag
|
||||
const normalizedEtag = normalizeEtag(rawEtag)
|
||||
const headers: Record<string, string> = {
|
||||
...baseHeaders,
|
||||
...(normalizedEtag ? { etag: normalizedEtag } : {}),
|
||||
'cache-control': isImmutable ? 'public, max-age=31536000, immutable' : 'no-cache',
|
||||
}
|
||||
const etag = headers.etag
|
||||
|
||||
return (req: Request): Response => {
|
||||
const ifNoneMatch = req.headers.get('if-none-match')
|
||||
if (etag && isEtagMatching(etag, ifNoneMatch)) {
|
||||
return new Response(null, {
|
||||
status: 304,
|
||||
headers,
|
||||
})
|
||||
}
|
||||
return new Response(bunFile, { headers })
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Creates a route handler for in-memory transformed HTML entry points.
|
||||
* Sets `cache-control: no-cache` with a deterministic ETag, allowing browsers to cache locally
|
||||
* while always revalidating to ensure new chunk hashes are picked up immediately after deployment.
|
||||
*/
|
||||
export function createHtmlHandler(
|
||||
htmlText: string,
|
||||
baseHeaders: Record<string, string>,
|
||||
): (req: Request) => Response {
|
||||
const rawEtag = baseHeaders.etag || baseHeaders.ETag
|
||||
const etag = normalizeEtag(rawEtag) || `"${Bun.hash(htmlText).toString(16)}"`
|
||||
const headers: Record<string, string> = {
|
||||
...baseHeaders,
|
||||
etag,
|
||||
'cache-control': 'no-cache',
|
||||
}
|
||||
|
||||
return (req: Request): Response => {
|
||||
const ifNoneMatch = req.headers.get('if-none-match')
|
||||
if (isEtagMatching(etag, ifNoneMatch)) {
|
||||
return new Response(null, {
|
||||
status: 304,
|
||||
headers,
|
||||
})
|
||||
}
|
||||
return new Response(htmlText, { headers })
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user