Press n or j to go to the next uncovered block, b, p or k for the previous block.
| 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 | 29x 29x 29x 29x 29x 29x 29x 29x 29x 29x 5x 3x 29x 29x 2x 2x | import { API_DOCS, ERROR_CODE, SYSTEM_API } from '@chattra/shared'
import { Hono } from 'hono'
import { NONCE, secureHeaders } from 'hono/secure-headers'
import { buildOpenApi, isDocsEnabled } from '../server/docs/openapi'
import { ApiHttpError, type AppEnv } from '../server/http'
// Swagger UI on local and dev (owner's decision, 2026-11-13); staging and production answer 404.
export const docsRoutes = new Hono<AppEnv>()
// Pinned with SRI: the page runs only these two files from outside the Worker.
const SWAGGER_UI = 'https://cdn.jsdelivr.net/npm/swagger-ui-dist@5.17.14'
const SWAGGER_JS_SRI = 'sha384-wmyclcVGX/WhUkdkATwhaK1X1JtiNrr2EoYJ+diV3vj4v6OC5yCeSu+yW13SYJep'
const SWAGGER_CSS_SRI = 'sha384-wxLW6kwyHktdDGr6Pv1zgm/VGJh99lfUbzSn6HNHBENZlCN7W602k9VkGdxuFvPn'
// The web's own Firebase version (apps/web/package.json), as its compat (global) builds, so the
// page reads the session /signin left in this origin's IndexedDB. Hashes match node_modules.
const FIREBASE = 'https://cdn.jsdelivr.net/npm/firebase@13.2.0'
const FIREBASE_APP_SRI = 'sha384-cLbh0Cu4dx/85kRPmEgNAXMBIChYFkojdl+72mu8+CktIaQ1u3yBrkyiKnDRkZ2q'
const FIREBASE_AUTH_SRI = 'sha384-4nmyawBuPA7UcE167bEqFiWjWvbYi/4+pPVJIglWre5cWJrdcMmq1BQJejMsZjFb'
// The local Auth emulator (`pnpm emulators`), on the page's own host name (apps/web/src/lib/firebase.ts).
const AUTH_EMULATOR = ['http://localhost:9099', 'http://127.0.0.1:9099']
// Signed in → every Swagger request gets a fresh ID token (getIdToken refreshes an expired one);
// signed out → /signin, which comes back here. The token never goes in a URL or in storage of ours.
const INIT_SCRIPT = `
(async () => {
const config = await (await fetch(${JSON.stringify(SYSTEM_API.config.path)})).json()
const { projectId, apiKey, authDomain, appId } = config.firebase
firebase.initializeApp({ projectId, apiKey, authDomain, appId })
const auth = firebase.auth()
if (config.environment === 'local') {
auth.useEmulator('http://' + location.hostname + ':9099', { disableWarnings: true })
}
// The compat build has no authStateReady(); the first auth state event is the restored user.
const user = await new Promise((resolve) => {
const stop = auth.onAuthStateChanged((current) => {
stop()
resolve(current)
})
})
if (!user) {
location.assign('/signin?redirect=' + encodeURIComponent(${JSON.stringify(API_DOCS.page)}))
return
}
window.ui = SwaggerUIBundle({
url: ${JSON.stringify(API_DOCS.openApi)},
dom_id: '#swagger-ui',
requestInterceptor: async (request) => {
const token = await auth.currentUser?.getIdToken()
if (token) request.headers.Authorization = 'Bearer ' + token
return request
},
})
})()`
docsRoutes.use(`${API_DOCS.page}/*`, async (c, next) => {
if (!isDocsEnabled(c.env)) throw new ApiHttpError(ERROR_CODE.notFound, 'Not found')
await next()
})
docsRoutes.get(API_DOCS.openApi, (c) => c.json(buildOpenApi()))
docsRoutes.get(
API_DOCS.page,
// The one HTML page the Worker builds: routes.ts leaves it out of the JSON-only headers.
secureHeaders({
xFrameOptions: 'DENY',
contentSecurityPolicy: {
defaultSrc: ["'none'"],
// The trailing slash matters: a CSP source path without one matches that exact URL only.
// apis.google.com: the gapi loader Firebase Auth fetches for its /__/auth/iframe (as the SPA).
scriptSrc: [`${SWAGGER_UI}/`, `${FIREBASE}/`, 'https://apis.google.com', NONCE],
styleSrc: [`${SWAGGER_UI}/`, "'unsafe-inline'"],
imgSrc: ["'self'", 'data:'],
connectSrc: [
"'self'",
'https://identitytoolkit.googleapis.com',
'https://securetoken.googleapis.com',
...AUTH_EMULATOR,
],
frameSrc: ["'self'", ...AUTH_EMULATOR],
frameAncestors: ["'none'"],
},
}),
(c) => {
// Set by NONCE in the middleware above before this handler runs.
const nonce = String(c.get('secureHeadersNonce'))
return c.html(`<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<title>Chattra API</title>
<link rel="stylesheet" href="${SWAGGER_UI}/swagger-ui.css" integrity="${SWAGGER_CSS_SRI}" crossorigin="anonymous" />
</head>
<body>
<div id="swagger-ui"></div>
<script src="${SWAGGER_UI}/swagger-ui-bundle.js" integrity="${SWAGGER_JS_SRI}" crossorigin="anonymous"></script>
<script src="${FIREBASE}/firebase-app-compat.js" integrity="${FIREBASE_APP_SRI}" crossorigin="anonymous"></script>
<script src="${FIREBASE}/firebase-auth-compat.js" integrity="${FIREBASE_AUTH_SRI}" crossorigin="anonymous"></script>
<script nonce="${nonce}">${INIT_SCRIPT}
</script>
</body>
</html>`)
},
)
|