@nera-static/mcp 1.2.1 → 1.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@nera-static/mcp",
3
- "version": "1.2.1",
3
+ "version": "1.4.0",
4
4
  "description": "A local MCP server for Nera: lets an AI assistant create, edit, build, validate, preview and publish Nera static sites under one folder",
5
5
  "type": "module",
6
6
  "files": [
@@ -47,7 +47,9 @@
47
47
  "dependencies": {
48
48
  "@modelcontextprotocol/sdk": "^1.32.2",
49
49
  "@nera-static/core": "^4.18.3",
50
- "@nera-static/nera": "^1.26.0",
50
+ "@nera-static/nera": "^1.27.0",
51
+ "express": "^5.3.0",
52
+ "semver": "^7.8.6",
51
53
  "yaml": "^2.9.1",
52
54
  "zod": "^4.6.7"
53
55
  },
@@ -0,0 +1,129 @@
1
+ // The HTTP app of the hosted mode (L7b, plan D1/D4/D5): one Express app that
2
+ // is both the OAuth 2.1 authorization server and the protected MCP resource.
3
+ //
4
+ // /.well-known/oauth-protected-resource/mcp RFC 9728, names our issuer
5
+ // /.well-known/oauth-authorization-server RFC 8414 (S256 only, DCR)
6
+ // /register /authorize /token /revoke the SDK's `mcpAuthRouter`
7
+ // POST /oauth/consent our consent page's form
8
+ // GET /oauth/github/callback GitHub's redirect back to us
9
+ // /mcp Streamable HTTP, bearer-guarded
10
+ //
11
+ // The issuer is configured, never taken from the request: behind a TLS proxy
12
+ // the request says `http://127.0.0.1:…`, while every URL we publish must be the
13
+ // public `https://` one. `/mcp` is stateless — each POST gets a fresh server
14
+ // and transport, bound to the caller's token through `req.auth`, whose
15
+ // `extra.userId` picks the GitHub sign-in the site tools act as.
16
+ import express from 'express'
17
+ import { requireBearerAuth } from '@modelcontextprotocol/sdk/server/auth/middleware/bearerAuth.js'
18
+ import { getOAuthProtectedResourceMetadataUrl, mcpAuthRouter } from '@modelcontextprotocol/sdk/server/auth/router.js'
19
+ import { StreamableHTTPServerTransport } from '@modelcontextprotocol/sdk/server/streamableHttp.js'
20
+ import { CONSENT_PATH } from './consent.js'
21
+ import { createHostedServer } from './mcp.js'
22
+ import { createProvider } from './provider.js'
23
+
24
+ /** Where the MCP endpoint lives; the protected resource is `<issuer>/mcp`. */
25
+ export const MCP_PATH = '/mcp'
26
+
27
+ /** GitHub's redirect back to us; the GitHub App's callback URL is `<issuer>` + this. */
28
+ export const GITHUB_CALLBACK_PATH = '/oauth/github/callback'
29
+
30
+ /** The largest JSON-RPC request body `/mcp` accepts. */
31
+ const MCP_BODY_LIMIT = '1mb'
32
+
33
+ /** A JSON-RPC error without a request id, for requests the transport never sees. */
34
+ function jsonRpcError(res, status, code, message) {
35
+ res.status(status).json({ jsonrpc: '2.0', error: { code, message }, id: null })
36
+ }
37
+
38
+ /**
39
+ * Checks the configured issuer: an origin only, since the SDK publishes the
40
+ * endpoints and the authorization-server metadata at the root of it. The SDK
41
+ * itself refuses a non-https issuer other than localhost.
42
+ *
43
+ * @param {string|URL} issuer
44
+ * @returns {URL}
45
+ */
46
+ function issuerUrl(issuer) {
47
+ const url = new URL(issuer)
48
+ if (url.pathname !== '/' || url.search || url.hash) {
49
+ throw new Error(`The issuer must be an origin such as https://mcp.nera-pro.app, without a path, query or fragment (got ${url.href}).`)
50
+ }
51
+ return url
52
+ }
53
+
54
+ /**
55
+ * Builds the hosted app. It does not listen: the bin (or a test) hands it to
56
+ * an HTTP server.
57
+ *
58
+ * @param {object} options
59
+ * @param {string|URL} options.issuer our public origin, e.g. `https://mcp.nera-pro.app`
60
+ * @param {ReturnType<import('./store.js').createStore>} options.store
61
+ * @param {ReturnType<import('./github.js').createGitHubClient>} options.github with `<issuer>/oauth/github/callback` as its redirect URI
62
+ * @param {typeof fetch} [options.fetch] fetches the npm registry catalogs for the tools
63
+ * @param {(token: string) => ReturnType<import('./repo.js').createRepoClient>} [options.createRepo] builds the site tools' repository client for a user's GitHub token
64
+ * @param {() => number} [options.now] the clock in milliseconds
65
+ * @param {(message: string) => void} [options.log] where failures are reported (never with a token in them)
66
+ * @param {boolean|number|string} [options.trustProxy] Express's `trust proxy`, so the rate limits see the client's address behind a proxy
67
+ * @returns {{ app: import('express').Express, provider: ReturnType<typeof createProvider> }}
68
+ */
69
+ export function createHostedApp({ issuer, store, github, fetch = globalThis.fetch, createRepo, now, log = () => {}, trustProxy = false }) {
70
+ const base = issuerUrl(issuer)
71
+ const resource = new URL(MCP_PATH, base)
72
+ const provider = createProvider({ store, github, resource, now, log })
73
+
74
+ const app = express()
75
+ app.disable('x-powered-by')
76
+ app.set('trust proxy', trustProxy)
77
+
78
+ app.use(mcpAuthRouter({ provider, issuerUrl: base, resourceServerUrl: resource, resourceName: 'Nera' }))
79
+ app.post(CONSENT_PATH, express.urlencoded({ extended: false }), (req, res) => provider.handleConsent(req, res))
80
+ app.get(GITHUB_CALLBACK_PATH, (req, res) => provider.handleGitHubCallback(req, res))
81
+
82
+ // Every method on /mcp passes the guard first; a token is accepted only
83
+ // when it was issued for exactly this resource.
84
+ app.use(MCP_PATH, requireBearerAuth({
85
+ verifier: provider,
86
+ resourceMetadataUrl: getOAuthProtectedResourceMetadataUrl(resource),
87
+ expectedResource: resource,
88
+ }))
89
+ app.post(MCP_PATH, express.json({ limit: MCP_BODY_LIMIT }), async (req, res) => {
90
+ const server = createHostedServer({
91
+ fetch,
92
+ userId: req.auth.extra?.userId,
93
+ githubToken: (userId) => provider.githubToken(userId),
94
+ createRepo,
95
+ })
96
+ const transport = new StreamableHTTPServerTransport({ sessionIdGenerator: undefined, enableJsonResponse: true })
97
+ // Both close calls are async; allSettled keeps a failed close from becoming an unhandled rejection.
98
+ res.on('close', () => void Promise.allSettled([transport.close(), server.close()]))
99
+ await server.connect(transport)
100
+ await transport.handleRequest(req, res, req.body)
101
+ })
102
+ // Stateless: there is no session to stream to (GET) or to end (DELETE).
103
+ app.all(MCP_PATH, (req, res) => {
104
+ res.setHeader('Allow', 'POST')
105
+ jsonRpcError(res, 405, -32000, 'Method not allowed: this server is stateless, send every request as a POST.')
106
+ })
107
+
108
+ // Last: a body a parser refused keeps its 4xx; anything else is a 500
109
+ // without a stack trace in the response. `/mcp` answers in JSON-RPC, the
110
+ // browser routes (consent, callback) in plain text.
111
+ app.use((error, req, res, next) => {
112
+ if (res.headersSent) {
113
+ next(error)
114
+ return
115
+ }
116
+ const clientError = error.expose && error.status >= 400 && error.status < 500
117
+ if (!clientError) log(`${req.method} ${req.path} failed: ${error.message}`)
118
+ const status = clientError ? error.status : 500
119
+ const message = clientError ? error.message : 'Internal server error.'
120
+ if (req.path === MCP_PATH) {
121
+ const code = !clientError ? -32603 : error.type === 'entity.parse.failed' ? -32700 : -32600
122
+ jsonRpcError(res, status, code, message)
123
+ return
124
+ }
125
+ res.status(status).type('text/plain').send(message)
126
+ })
127
+
128
+ return { app, provider }
129
+ }
@@ -0,0 +1,427 @@
1
+ // The temporary checkout of the hosted `validate` (L7b, plan D1/D6). The
2
+ // hosted server builds nothing and runs no npm: it downloads a site's tarball
3
+ // from GitHub, unpacks it with the system `tar` into a fresh folder, deletes
4
+ // every symbolic link (and anything else that is not a plain file or folder),
5
+ // refuses a config that points the validator outside the checkout, downloads
6
+ // the one theme package `config/app.yaml` names from the npm registry (nothing
7
+ // else: the validator needs node_modules only to find the theme), refuses a
8
+ // layout or Pug include/extends that leaves the checkout, hands the folder to
9
+ // the caller and removes it again, whatever happened. Each user runs one
10
+ // checkout at a time. No code of the site or the theme runs: nothing is
11
+ // installed, and the validator reads files, it imports none.
12
+ import fssync from 'node:fs'
13
+ import fs from 'node:fs/promises'
14
+ import os from 'node:os'
15
+ import path from 'node:path'
16
+ import { promisify } from 'node:util'
17
+ import { gunzip as gunzipCallback } from 'node:zlib'
18
+ import { computeFolders, defaultSettings, makeLayeredResolver, resolveEntry, resolveSiteModel } from '@nera-static/core'
19
+ import semver from 'semver'
20
+ import yaml from 'yaml'
21
+ import { ToolError } from '../results.js'
22
+ import { createRunner } from '../runner.js'
23
+ import { failureText } from '../tools/cli.js'
24
+ import { readLimited } from './repo.js'
25
+
26
+ const gunzip = promisify(gunzipCallback)
27
+
28
+ /** The default cap on each unpacked archive; the site's download has its own (`downloadTarball`). */
29
+ export const MAX_UNPACKED_BYTES = 200 * 1024 * 1024
30
+ /** The default cap on the theme package's download. */
31
+ export const MAX_THEME_BYTES = 20 * 1024 * 1024
32
+ /** The cap on the theme's registry metadata (a theme's is a few kilobytes). */
33
+ const MAX_PACKUMENT_BYTES = 5 * 1024 * 1024
34
+ /** A theme package as `theme:` names it: a bare name (`blog`) or an npm package (`@scope/name`). */
35
+ const THEME_PACKAGE = /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/
36
+ /** The lockfiles that may pin the theme's version. */
37
+ const LOCKFILES = ['package-lock.json', 'npm-shrinkwrap.json']
38
+ /** The only host the checkout downloads a package from. */
39
+ export const NPM_REGISTRY = 'https://registry.npmjs.org/'
40
+ /** The package.json fields that name the site's theme package, in the order they are searched. */
41
+ const DEPENDENCY_FIELDS = ['dependencies', 'devDependencies', 'optionalDependencies']
42
+ /** The frontmatter fence exactly as `@nera-static/validate` (src/frontmatter.js) reads it. */
43
+ const FRONTMATTER = /^---\r?\n([\s\S]*?)\r?\n---/
44
+ /** A Pug `include`/`include:filter`/`extends` line exactly as `@nera-static/validate` (src/pug-refs.js) reads it. */
45
+ const PUG_REFERENCE = /^\s*(?:include(?::[^\s]+)?|extends)\s+(.+?)\s*$/
46
+
47
+ /**
48
+ * The environment of every child of a checkout: the PATH of this process (to
49
+ * find `tar`), nothing else — no token, no `NERA_MCP_*` setting reaches tar.
50
+ *
51
+ * @param {Record<string, string|undefined>} [env]
52
+ * @returns {Record<string, string>}
53
+ */
54
+ export function checkoutEnv(env = process.env) {
55
+ const stripped = { NO_COLOR: '1' }
56
+ if (env.PATH !== undefined) stripped.PATH = env.PATH
57
+ return stripped
58
+ }
59
+
60
+ /**
61
+ * Deletes, below `dir`, every entry that is neither a plain file nor a folder:
62
+ * symbolic links first of all (one could point the validator at a file of the
63
+ * server), but also FIFOs, sockets and devices.
64
+ *
65
+ * @param {string} dir
66
+ * @returns {Promise<number>} how many entries were deleted
67
+ */
68
+ export async function removeLinks(dir) {
69
+ let removed = 0
70
+ for (const entry of await fs.readdir(dir, { withFileTypes: true })) {
71
+ const full = path.join(dir, entry.name)
72
+ if (entry.isDirectory()) {
73
+ removed += await removeLinks(full)
74
+ } else if (!entry.isFile()) {
75
+ await fs.rm(full, { force: true })
76
+ removed += 1
77
+ }
78
+ }
79
+ return removed
80
+ }
81
+
82
+ /** Whether `target` is `dir` or inside it, both resolved. */
83
+ function isInside(dir, target) {
84
+ const relative = path.relative(dir, target)
85
+ return relative === '' || (!relative.startsWith('..') && !path.isAbsolute(relative))
86
+ }
87
+
88
+ /**
89
+ * The npm package of a `theme:` that names one, the way core resolves it: a
90
+ * bare name is `@nera-static/theme-<name>`, a scoped name is used verbatim.
91
+ * Mirrors core's `packageName` (src/theme.js), which core does not export;
92
+ * core's unscoped `a/b` case is left out because `THEME_PACKAGE` refuses it.
93
+ */
94
+ function themePackageName(spec) {
95
+ return spec.startsWith('@') ? spec : `@nera-static/theme-${spec}`
96
+ }
97
+
98
+ /**
99
+ * Refuses a site whose `config/app.yaml` sends the validator outside the
100
+ * checkout: a `folders.<key>` that resolves outside it, a local `theme:` path
101
+ * that does, or a theme package name that is none. An app.yaml that does not
102
+ * parse is left to the validator, which reports it (and then uses the default
103
+ * folders, all inside).
104
+ *
105
+ * @param {string} dir the checkout
106
+ * @returns {Promise<string|null>} the theme's npm package when `theme:` names one, else null
107
+ * @throws {ToolError}
108
+ */
109
+ export async function refuseEscapes(dir) {
110
+ let appConfig
111
+ try {
112
+ const text = await fs.readFile(path.join(dir, defaultSettings.folders.config, 'app.yaml'), 'utf8')
113
+ appConfig = yaml.parse(text)
114
+ } catch {
115
+ return null
116
+ }
117
+ if (!appConfig || typeof appConfig !== 'object' || Array.isArray(appConfig)) return null
118
+ for (const [key, folder] of Object.entries(computeFolders(appConfig, { cwd: dir }))) {
119
+ if (typeof folder !== 'string' || !isInside(dir, path.resolve(dir, folder))) {
120
+ throw new ToolError(`folders.${key} in config/app.yaml ("${folder}") points outside the repository. The hosted validate reads only files inside the repository; give the folder relative to it, e.g. ./${key}.`)
121
+ }
122
+ }
123
+ const theme = appConfig.theme
124
+ if (theme === undefined || theme === null || theme === '') return null
125
+ const spec = String(theme)
126
+ if (spec.startsWith('.')) {
127
+ if (isInside(dir, path.resolve(dir, spec))) return null
128
+ } else if (THEME_PACKAGE.test(spec)) {
129
+ return themePackageName(spec)
130
+ }
131
+ throw new ToolError(`theme in config/app.yaml ("${spec}") is neither a theme package (e.g. blog or @nera-static/theme-blog) nor a folder inside the repository (e.g. ./themes/mine).`)
132
+ }
133
+
134
+ /** Reads a JSON file of the checkout; a file that does not parse is a tool error. */
135
+ async function readJson(dir, name) {
136
+ const text = await fs.readFile(path.join(dir, name), 'utf8')
137
+ try {
138
+ return JSON.parse(text)
139
+ } catch {
140
+ throw new ToolError(`${name} is not valid JSON, so the hosted validate cannot find the version of the site's theme. Fix ${name} and call validate again.`)
141
+ }
142
+ }
143
+
144
+ /**
145
+ * Which version of the theme package `name` the site installs: the one its
146
+ * lockfile pins (`packages["node_modules/<name>"]`, which must come from
147
+ * `NPM_REGISTRY`), else the range or tag its package.json names. A site that
148
+ * depends on no such package gets none: the validator then reports the theme
149
+ * as not installed, as the build would fail on it.
150
+ *
151
+ * @param {string} dir the checkout
152
+ * @param {string} name the theme's npm package
153
+ * @returns {Promise<{ version: string } | { spec: string } | null>}
154
+ * @throws {ToolError} for a pin outside the registry or a spec that is no range or tag
155
+ */
156
+ export async function themeRequest(dir, name) {
157
+ const files = await fs.readdir(dir)
158
+ for (const lockfile of LOCKFILES.filter((file) => files.includes(file))) {
159
+ const entry = (await readJson(dir, lockfile))?.packages?.[`node_modules/${name}`]
160
+ if (!entry || typeof entry !== 'object') continue
161
+ if (!String(entry.resolved ?? '').startsWith(NPM_REGISTRY)) {
162
+ throw new ToolError(`The theme ${name} in ${lockfile} comes from "${entry.resolved ?? 'nowhere'}", not from the npm registry. The hosted validate downloads themes from ${NPM_REGISTRY} only; install the theme from npm (npm install ${name}) and commit ${lockfile}.`)
163
+ }
164
+ if (!semver.valid(entry.version)) {
165
+ throw new ToolError(`The theme ${name} in ${lockfile} has the version "${entry.version}", which is none. Regenerate ${lockfile} with npm install and call validate again.`)
166
+ }
167
+ return { version: entry.version }
168
+ }
169
+ if (!files.includes('package.json')) return null
170
+ const manifest = await readJson(dir, 'package.json')
171
+ for (const field of DEPENDENCY_FIELDS) {
172
+ const spec = manifest?.[field]?.[name]
173
+ if (spec === undefined) continue
174
+ if (typeof spec !== 'string' || (!semver.validRange(spec) && !/^[\w.-]+$/.test(spec))) {
175
+ throw new ToolError(`The theme ${name} in package.json (${field}) is "${spec}", which is not a version range or tag of the npm registry. The hosted validate downloads themes from ${NPM_REGISTRY} only: give a range such as ^1.2.0, or validate this site locally with nera validate.`)
176
+ }
177
+ return { spec }
178
+ }
179
+ return null
180
+ }
181
+
182
+ /**
183
+ * The version a registry `packument` has for `request`: the pinned version,
184
+ * the highest version in the range, or the version of the dist-tag.
185
+ *
186
+ * @returns {string|null}
187
+ */
188
+ function pickVersion(packument, request) {
189
+ const versions = Object.keys(packument?.versions ?? {})
190
+ if ('version' in request) return versions.includes(request.version) ? request.version : null
191
+ // npm reads a spec as a range when it is one, else as a dist-tag
192
+ const range = semver.validRange(request.spec)
193
+ if (range) return semver.maxSatisfying(versions, range)
194
+ const tagged = packument?.['dist-tags']?.[request.spec]
195
+ return typeof tagged === 'string' && versions.includes(tagged) ? tagged : null
196
+ }
197
+
198
+ /** The tool error for a view path that leaves the checkout; it never says whether the target exists. */
199
+ function viewEscape(where, value) {
200
+ return new ToolError(`${where} ("${value}") points outside the repository. The hosted validate reads only files inside the repository; give the path relative to the views folder (a layout) or to the including file (an include).`)
201
+ }
202
+
203
+ /** Every `.md` file below `dir`, like the validator's walk (a missing folder has none). */
204
+ async function markdownFiles(dir) {
205
+ let entries
206
+ try {
207
+ entries = await fs.readdir(dir, { withFileTypes: true })
208
+ } catch {
209
+ return []
210
+ }
211
+ const found = []
212
+ for (const entry of entries) {
213
+ const full = path.join(dir, entry.name)
214
+ if (entry.isDirectory()) found.push(...await markdownFiles(full))
215
+ else if (entry.name.endsWith('.md')) found.push(full)
216
+ }
217
+ return found
218
+ }
219
+
220
+ /**
221
+ * Follows the include/extends graph of `file` the way the validator does
222
+ * (`collectIncludeFindings`) and refuses the first target that resolves
223
+ * outside `dir`, before the validator would test whether it exists or read it.
224
+ */
225
+ async function refuseIncludeEscapes(file, roots, dir, visited) {
226
+ if (visited.has(file)) return
227
+ visited.add(file)
228
+ let source
229
+ try {
230
+ source = await fs.readFile(file, 'utf8')
231
+ } catch {
232
+ return
233
+ }
234
+ const resolve = makeLayeredResolver(roots)
235
+ const lines = source.split(/\r?\n/)
236
+ for (const [index, line] of lines.entries()) {
237
+ const match = line.match(PUG_REFERENCE)
238
+ if (!match) continue
239
+ const target = match[1]
240
+ // Pug appends .pug to an extensionless target before resolving it.
241
+ const resolved = resolve(path.extname(target) ? target : `${target}.pug`, file, { basedir: roots[0] })
242
+ if (!isInside(dir, resolved)) {
243
+ throw viewEscape(`The include/extends target on line ${index + 1} of ${path.relative(dir, file)}`, target)
244
+ }
245
+ if (path.extname(resolved) === '.pug' && fssync.existsSync(resolved)) {
246
+ await refuseIncludeEscapes(resolved, roots, dir, visited)
247
+ }
248
+ }
249
+ }
250
+
251
+ /**
252
+ * Refuses, before the validator runs, every path it would look up outside the
253
+ * checkout: a view root (the theme) found outside it, e.g. in a node_modules
254
+ * folder above it; a page's `layout:` that leaves it below any view root; and
255
+ * a Pug include/extends, in any template the validator reaches from a layout,
256
+ * that leaves it. Without this the validator's verdict on such a path tells
257
+ * whether a file of the server exists, and the include lines of a server
258
+ * template appear in its messages. The lasting fix is a root jail in
259
+ * `validateSite` (the `[nera-validate]` issue 01a2050a-60cb-7274-84dc-ce7f845ffca8);
260
+ * until then this mirrors the validator's own lookups through core's resolver.
261
+ *
262
+ * @param {string} dir the checkout, after the install
263
+ * @throws {ToolError}
264
+ */
265
+ export async function refuseViewEscapes(dir) {
266
+ const model = resolveSiteModel({ cwd: dir })
267
+ if (!model.roots.every((root) => isInside(dir, root))) {
268
+ throw new ToolError('The theme in config/app.yaml resolves to a folder outside the repository. The hosted validate reads only the themes the site installs itself; add the theme to the dependencies in package.json.')
269
+ }
270
+ const visited = new Set()
271
+ for (const page of await markdownFiles(path.resolve(dir, model.folders.pages))) {
272
+ const fence = (await fs.readFile(page, 'utf8')).match(FRONTMATTER)
273
+ if (!fence) continue
274
+ let meta
275
+ try {
276
+ meta = yaml.parse(fence[1])
277
+ } catch {
278
+ continue // the validator reports it and skips the page
279
+ }
280
+ if (!meta || typeof meta !== 'object' || !meta.layout) continue
281
+ const layout = String(meta.layout)
282
+ if (!model.roots.every((root) => isInside(dir, path.join(root, layout)))) {
283
+ throw viewEscape(`The layout of ${path.relative(dir, page)}`, layout)
284
+ }
285
+ const entry = resolveEntry(layout, model.roots)
286
+ if (fssync.existsSync(entry)) await refuseIncludeEscapes(entry, model.roots, dir, visited)
287
+ }
288
+ }
289
+
290
+ /**
291
+ * Creates the checkouts of one server process. The hosted server is built per
292
+ * request, so the instance that keeps "one checkout per user" must outlive it:
293
+ * `createHostedServer` uses `sharedCheckouts` unless a test passes its own.
294
+ *
295
+ * @param {object} [options]
296
+ * @param {ReturnType<typeof createRunner>} [options.runner] runs `tar` (injected so tests stay offline)
297
+ * @param {typeof fetch} [options.fetch] downloads the theme package from the npm registry (injected so tests stay offline)
298
+ * @param {string} [options.tmpdir] where checkouts are made
299
+ * @param {number} [options.maxTarballBytes] the cap on the site's download (`downloadTarball`'s default when absent)
300
+ * @param {number} [options.maxThemeBytes] the cap on the theme package's download
301
+ * @param {number} [options.maxUnpackedBytes] the cap on each unpacked archive
302
+ */
303
+ export function createCheckouts({
304
+ runner = createRunner(),
305
+ fetch = globalThis.fetch,
306
+ tmpdir = os.tmpdir(),
307
+ maxTarballBytes,
308
+ maxThemeBytes = MAX_THEME_BYTES,
309
+ maxUnpackedBytes = MAX_UNPACKED_BYTES,
310
+ } = {}) {
311
+ /** The users with a checkout in progress. */
312
+ const busy = new Set()
313
+
314
+ /** Unpacks the gzipped `tarball` into `target`, without its top folder (GitHub's `owner-name-sha/`, npm's `package/`). */
315
+ async function unpack(tarball, dir, target, what, signal) {
316
+ let tar
317
+ try {
318
+ tar = await gunzip(tarball, { maxOutputLength: maxUnpackedBytes })
319
+ } catch (error) {
320
+ if (error.code === 'ERR_BUFFER_TOO_LARGE') {
321
+ throw new ToolError(`${what} unpacks to more than the ${maxUnpackedBytes} bytes a checkout may have, so the hosted validate cannot check it.`)
322
+ }
323
+ throw new ToolError(`${what} came as no readable archive (${error.message}). Try validate again.`)
324
+ }
325
+ const archive = path.join(dir, 'archive.tar')
326
+ await fs.writeFile(archive, tar)
327
+ const result = await runner('tar', ['-xf', archive, '-C', target, '--strip-components=1'], { cwd: dir, signal, env: checkoutEnv() })
328
+ if (result.code !== 0) throw new ToolError(`Unpacking ${what} failed: ${failureText(result)}`)
329
+ await fs.rm(archive)
330
+ }
331
+
332
+ /**
333
+ * GETs `url` from the npm registry, never following a redirect to another
334
+ * host, and returns at most `maxBytes` of its body; null for a 404.
335
+ */
336
+ async function fromRegistry(url, { maxBytes, accept, what, signal }) {
337
+ let response
338
+ try {
339
+ response = await fetch(url, { headers: { accept }, redirect: 'error', signal })
340
+ } catch (error) {
341
+ throw new ToolError(`Downloading ${what} from the npm registry failed (${error.message}). Try validate again.`)
342
+ }
343
+ if (response.status === 404) return null
344
+ if (!response.ok) throw new ToolError(`The npm registry answered ${response.status} for ${what}. Try validate again.`)
345
+ return readLimited(response, maxBytes, () => new ToolError(`${what} is larger than the ${maxBytes} bytes a checkout may download, so the hosted validate cannot check this site.`))
346
+ }
347
+
348
+ /**
349
+ * Downloads the theme package `name` from the registry into the
350
+ * checkout's `node_modules/<name>`: the version `themeRequest` names, no
351
+ * dependency of it, nothing from another host.
352
+ */
353
+ async function addTheme(dir, siteDir, name, signal) {
354
+ const request = await themeRequest(siteDir, name)
355
+ if (!request) return
356
+ const what = `The theme package ${name}`
357
+ const metadata = await fromRegistry(`${NPM_REGISTRY}${name.replace('/', '%2f')}`, {
358
+ maxBytes: MAX_PACKUMENT_BYTES, accept: 'application/vnd.npm.install-v1+json', what: `the registry entry of ${name}`, signal,
359
+ })
360
+ if (!metadata) throw new ToolError(`${what} is not on the npm registry. Publish it, or keep the theme in the repository (theme: ./themes/<name> in config/app.yaml).`)
361
+ let packument
362
+ try {
363
+ packument = JSON.parse(metadata.toString('utf8'))
364
+ } catch {
365
+ throw new ToolError(`The npm registry sent no readable entry for ${name}. Try validate again.`)
366
+ }
367
+ const version = pickVersion(packument, request)
368
+ const wanted = 'version' in request ? request.version : request.spec
369
+ if (!version) throw new ToolError(`${what} has no version "${wanted}" on the npm registry. Install an existing version (npm install ${name}) and commit package.json and the lockfile.`)
370
+ const tarballUrl = packument.versions[version]?.dist?.tarball
371
+ if (typeof tarballUrl !== 'string' || !tarballUrl.startsWith(NPM_REGISTRY)) {
372
+ throw new ToolError(`The npm registry names no download of ${name}@${version} on ${NPM_REGISTRY}, so the hosted validate cannot fetch it.`)
373
+ }
374
+ const tarball = await fromRegistry(tarballUrl, { maxBytes: maxThemeBytes, accept: 'application/octet-stream', what: `${what} (${version})`, signal })
375
+ if (!tarball) throw new ToolError(`The npm registry has no download of ${name}@${version}. Try validate again.`)
376
+ const target = path.join(siteDir, 'node_modules', ...name.split('/'))
377
+ await fs.rm(target, { recursive: true, force: true })
378
+ await fs.mkdir(target, { recursive: true })
379
+ await unpack(tarball, dir, target, `${what} (${version})`, signal)
380
+ }
381
+
382
+ return {
383
+ /**
384
+ * Checks out `ref` of `site` into a temporary folder, calls `use` with
385
+ * it and deletes the folder afterwards, also when anything failed.
386
+ *
387
+ * @template T
388
+ * @param {string} userId the signed-in user; one checkout each at a time
389
+ * @param {object} source
390
+ * @param {ReturnType<typeof import('./repo.js').createRepoClient>} source.client the user's repository client
391
+ * @param {string} source.site `owner/name`
392
+ * @param {string} source.ref the commit to check out
393
+ * @param {AbortSignal} [source.signal] stops the downloads and `tar` when the client cancels
394
+ * @param {(dir: string) => T|Promise<T>} use gets the checkout's folder
395
+ * @returns {Promise<T>}
396
+ */
397
+ async withCheckout(userId, { client, site, ref, signal }, use) {
398
+ if (busy.has(userId)) {
399
+ throw new ToolError('Another validate of yours is still running. Wait for its result, then call validate again.')
400
+ }
401
+ busy.add(userId)
402
+ let dir = null
403
+ try {
404
+ // undefined keeps downloadTarball's own default cap
405
+ const tarball = await client.downloadTarball(site, ref, { maxBytes: maxTarballBytes })
406
+ dir = await fs.mkdtemp(path.join(tmpdir, 'nera-mcp-checkout-'))
407
+ const siteDir = path.join(dir, 'site')
408
+ await fs.mkdir(siteDir)
409
+ await unpack(tarball, dir, siteDir, `The repository ${site}`, signal)
410
+ await removeLinks(siteDir)
411
+ const theme = await refuseEscapes(siteDir)
412
+ if (theme) {
413
+ await addTheme(dir, siteDir, theme, signal)
414
+ await removeLinks(siteDir)
415
+ }
416
+ await refuseViewEscapes(siteDir)
417
+ return await use(siteDir)
418
+ } finally {
419
+ if (dir) await fs.rm(dir, { recursive: true, force: true })
420
+ busy.delete(userId)
421
+ }
422
+ },
423
+ }
424
+ }
425
+
426
+ /** The checkouts of this server process. */
427
+ export const sharedCheckouts = createCheckouts()
@@ -0,0 +1,89 @@
1
+ // The hosted mode's configuration (L7b), read by the bin before anything else
2
+ // of `src/hosted/` loads. It has no imports on purpose: the bin calls it before
3
+ // it knows whether this Node has `node:sqlite`, which `store.js` needs.
4
+ // Values come from the environment, never from the command line, so no secret
5
+ // shows up in `ps`; no error message ever quotes a value.
6
+
7
+ /** The environment variables the hosted mode needs, with what each one is. */
8
+ export const HOSTED_ENV = Object.freeze({
9
+ NERA_MCP_ISSUER: 'our public origin, e.g. https://mcp.nera-pro.app',
10
+ NERA_MCP_DB: 'the SQLite file for clients and tokens',
11
+ NERA_MCP_TOKEN_KEY: 'the key that encrypts GitHub tokens (openssl rand -base64 32)',
12
+ NERA_MCP_GITHUB_CLIENT_ID: 'the GitHub App\'s client ID',
13
+ NERA_MCP_GITHUB_CLIENT_SECRET: 'the GitHub App\'s client secret',
14
+ })
15
+
16
+ /** The first Node releases with an unflagged `node:sqlite`, per major line. */
17
+ const SQLITE_SINCE = Object.freeze({ 22: 13, 23: 4 })
18
+
19
+ /** A configuration the hosted mode cannot start with; the message is safe to print. */
20
+ export class HostedConfigError extends Error {
21
+ constructor(message) {
22
+ super(message)
23
+ this.name = 'HostedConfigError'
24
+ }
25
+ }
26
+
27
+ /**
28
+ * Whether a Node version has `node:sqlite` without a flag: 22.13+, 23.4+, 24+.
29
+ *
30
+ * @param {string} version `process.versions.node`, e.g. `22.12.0`
31
+ * @returns {boolean}
32
+ */
33
+ export function hasNodeSqlite(version) {
34
+ const [major, minor] = version.split('.').map(Number)
35
+ if (major in SQLITE_SINCE) return minor >= SQLITE_SINCE[major]
36
+ return major > 23
37
+ }
38
+
39
+ /**
40
+ * Reads the hosted mode's settings from `env`. Every missing variable is named
41
+ * in one error, so the operator fixes them in one go.
42
+ *
43
+ * @param {Record<string, string|undefined>} env usually `process.env`
44
+ * @returns {{ issuer: string, db: string, tokenKey: string, githubClientId: string, githubClientSecret: string }}
45
+ * @throws {HostedConfigError} when a variable is missing or empty
46
+ */
47
+ export function readHostedConfig(env) {
48
+ const missing = Object.keys(HOSTED_ENV).filter((name) => !env[name]?.trim())
49
+ if (missing.length > 0) {
50
+ const lines = missing.map((name) => ` ${name} ${HOSTED_ENV[name]}`)
51
+ throw new HostedConfigError(`the hosted mode (--http) needs these environment variables:\n${lines.join('\n')}`)
52
+ }
53
+ return {
54
+ issuer: env.NERA_MCP_ISSUER.trim(),
55
+ db: env.NERA_MCP_DB.trim(),
56
+ tokenKey: env.NERA_MCP_TOKEN_KEY.trim(),
57
+ githubClientId: env.NERA_MCP_GITHUB_CLIENT_ID.trim(),
58
+ githubClientSecret: env.NERA_MCP_GITHUB_CLIENT_SECRET.trim(),
59
+ }
60
+ }
61
+
62
+ /**
63
+ * Turns `--trust-proxy` into Express's `trust proxy` setting: a number of
64
+ * hops (`1`), or the addresses/subnets to trust (`loopback`, `10.0.0.0/8`).
65
+ * Absent means no proxy is trusted.
66
+ *
67
+ * @param {string|undefined} value
68
+ * @returns {false|number|string}
69
+ */
70
+ export function parseTrustProxy(value) {
71
+ if (value === undefined) return false
72
+ const text = value.trim()
73
+ if (text === '') throw new HostedConfigError('--trust-proxy needs a value: a number of proxies (e.g. 1) or the addresses to trust (e.g. loopback).')
74
+ return /^\d+$/.test(text) ? Number(text) : text
75
+ }
76
+
77
+ /**
78
+ * Turns `--port` into a TCP port; `0` picks a free one.
79
+ *
80
+ * @param {string|undefined} value
81
+ * @param {number} fallback
82
+ * @returns {number}
83
+ */
84
+ export function parsePort(value, fallback) {
85
+ if (value === undefined) return fallback
86
+ const port = /^\d+$/.test(value.trim()) ? Number(value) : NaN
87
+ if (!(port >= 0 && port <= 65535)) throw new HostedConfigError(`--port must be a number from 0 to 65535 (got ${value}).`)
88
+ return port
89
+ }