@nera-static/mcp 1.3.0 → 1.4.1
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/.claude-plugin/plugin.json +2 -2
- package/CHANGELOG.md +42 -0
- package/README.md +58 -1
- package/bin/nera-mcp.js +211 -63
- package/docs/llms-full.txt +2336 -179
- package/package.json +31 -18
- package/skills/nera/SKILL.md +3 -0
- package/skills/nera/recipes/blog.md +9 -5
- package/src/catalog.js +1 -1
- package/src/hosted/app.js +131 -0
- package/src/hosted/checkout.js +417 -0
- package/src/hosted/config.js +93 -0
- package/src/hosted/consent.js +146 -0
- package/src/hosted/crypto.js +91 -0
- package/src/hosted/github.js +160 -0
- package/src/hosted/mcp.js +62 -0
- package/src/hosted/provider.js +376 -0
- package/src/hosted/repo.js +489 -0
- package/src/hosted/store.js +490 -0
- package/src/hosted/tools/publish.js +192 -0
- package/src/hosted/tools/read.js +351 -0
- package/src/hosted/tools/validate.js +51 -0
- package/src/hosted/tools/write.js +201 -0
- package/src/pages.js +171 -0
- package/src/paths.js +11 -18
- package/src/prompts.js +80 -10
- package/src/resources.js +22 -6
- package/src/runner.js +27 -17
- package/src/server-info.js +11 -0
- package/src/server.js +14 -4
- package/src/tools/cli.js +47 -23
- package/src/tools/files.js +19 -111
- package/src/tools/long-running.js +14 -33
- package/src/tools/sites.js +39 -13
|
@@ -0,0 +1,417 @@
|
|
|
1
|
+
// The temporary checkout of the hosted `validate` (L7b). 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 { walkFiles } from '@nera-static/plugin-utils/files'
|
|
20
|
+
import { splitFrontmatter } from '@nera-static/plugin-utils/frontmatter'
|
|
21
|
+
import { themePackage } from '@nera-static/plugin-utils/packages'
|
|
22
|
+
import { isInside } from '@nera-static/plugin-utils/urls'
|
|
23
|
+
import { isPlainObject } from '@nera-static/plugin-utils/values'
|
|
24
|
+
import semver from 'semver'
|
|
25
|
+
import yaml from 'yaml'
|
|
26
|
+
import { PAGE_YAML_OPTIONS } from '../pages.js'
|
|
27
|
+
import { ToolError } from '../results.js'
|
|
28
|
+
import { createRunner } from '../runner.js'
|
|
29
|
+
import { failureText } from '../tools/cli.js'
|
|
30
|
+
import { readLimited } from './repo.js'
|
|
31
|
+
|
|
32
|
+
const gunzip = promisify(gunzipCallback)
|
|
33
|
+
|
|
34
|
+
/** The default cap on each unpacked archive; the site's download has its own (`downloadTarball`). */
|
|
35
|
+
export const MAX_UNPACKED_BYTES = 200 * 1024 * 1024
|
|
36
|
+
/** The default cap on the theme package's download. */
|
|
37
|
+
export const MAX_THEME_BYTES = 20 * 1024 * 1024
|
|
38
|
+
/** The cap on the theme's registry metadata (a theme's is a few kilobytes). */
|
|
39
|
+
const MAX_PACKUMENT_BYTES = 5 * 1024 * 1024
|
|
40
|
+
/** A theme package as `theme:` names it: a bare name (`blog`) or an npm package (`@scope/name`). */
|
|
41
|
+
const THEME_PACKAGE = /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/
|
|
42
|
+
/** The lockfiles that may pin the theme's version. */
|
|
43
|
+
const LOCKFILES = ['package-lock.json', 'npm-shrinkwrap.json']
|
|
44
|
+
/** The only host the checkout downloads a package from. */
|
|
45
|
+
export const NPM_REGISTRY = 'https://registry.npmjs.org/'
|
|
46
|
+
/** The package.json fields that name the site's theme package, in the order they are searched. */
|
|
47
|
+
const DEPENDENCY_FIELDS = ['dependencies', 'devDependencies', 'optionalDependencies']
|
|
48
|
+
/** A Pug `include`/`include:filter`/`extends` line exactly as `@nera-static/validate` (src/pug-refs.js) reads it. */
|
|
49
|
+
const PUG_REFERENCE = /^\s*(?:include(?::[^\s]+)?|extends)\s+(.+?)\s*$/
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* The environment of every child of a checkout: the PATH of this process (to
|
|
53
|
+
* find `tar`), nothing else — no token, no `NERA_MCP_*` setting reaches tar.
|
|
54
|
+
*
|
|
55
|
+
* @param {Record<string, string|undefined>} [env]
|
|
56
|
+
* @returns {Record<string, string>}
|
|
57
|
+
*/
|
|
58
|
+
export function checkoutEnv(env = process.env) {
|
|
59
|
+
const stripped = { NO_COLOR: '1' }
|
|
60
|
+
if (env.PATH !== undefined) stripped.PATH = env.PATH
|
|
61
|
+
return stripped
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* Deletes, below `dir`, every entry that is neither a plain file nor a folder:
|
|
66
|
+
* symbolic links first of all (one could point the validator at a file of the
|
|
67
|
+
* server), but also FIFOs, sockets and devices.
|
|
68
|
+
*
|
|
69
|
+
* @param {string} dir
|
|
70
|
+
* @returns {Promise<number>} how many entries were deleted
|
|
71
|
+
*/
|
|
72
|
+
export async function removeLinks(dir) {
|
|
73
|
+
let removed = 0
|
|
74
|
+
for (const entry of await fs.readdir(dir, { withFileTypes: true })) {
|
|
75
|
+
const full = path.join(dir, entry.name)
|
|
76
|
+
if (entry.isDirectory()) {
|
|
77
|
+
removed += await removeLinks(full)
|
|
78
|
+
} else if (!entry.isFile()) {
|
|
79
|
+
await fs.rm(full, { force: true })
|
|
80
|
+
removed += 1
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
return removed
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/**
|
|
87
|
+
* Refuses a site whose `config/app.yaml` sends the validator outside the
|
|
88
|
+
* checkout: a `folders.<key>` that resolves outside it, a local `theme:` path
|
|
89
|
+
* that does, or a theme package name that is none. An app.yaml that does not
|
|
90
|
+
* parse is left to the validator, which reports it (and then uses the default
|
|
91
|
+
* folders, all inside).
|
|
92
|
+
*
|
|
93
|
+
* @param {string} dir the checkout
|
|
94
|
+
* @returns {Promise<string|null>} the theme's npm package when `theme:` names one, else null
|
|
95
|
+
* @throws {ToolError}
|
|
96
|
+
*/
|
|
97
|
+
export async function refuseEscapes(dir) {
|
|
98
|
+
let appConfig
|
|
99
|
+
try {
|
|
100
|
+
const text = await fs.readFile(path.join(dir, defaultSettings.folders.config, 'app.yaml'), 'utf8')
|
|
101
|
+
appConfig = yaml.parse(text)
|
|
102
|
+
} catch {
|
|
103
|
+
return null
|
|
104
|
+
}
|
|
105
|
+
if (!isPlainObject(appConfig)) return null
|
|
106
|
+
for (const [key, folder] of Object.entries(computeFolders(appConfig, { cwd: dir }))) {
|
|
107
|
+
if (typeof folder !== 'string' || !isInside(dir, path.resolve(dir, folder))) {
|
|
108
|
+
throw new ToolError(`folders.${key} in config/app.yaml ("${folder}") points outside the repository. The ` +
|
|
109
|
+
'hosted validate reads only files inside the repository; give the folder ' +
|
|
110
|
+
`relative to it, e.g. ./${key}.`)
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
const theme = appConfig.theme
|
|
114
|
+
if (theme === undefined || theme === null || theme === '') return null
|
|
115
|
+
const spec = String(theme)
|
|
116
|
+
if (spec.startsWith('.')) {
|
|
117
|
+
if (isInside(dir, path.resolve(dir, spec))) return null
|
|
118
|
+
} else if (THEME_PACKAGE.test(spec)) {
|
|
119
|
+
// THEME_PACKAGE has refused an unscoped `a/b`, which themePackage would keep
|
|
120
|
+
return themePackage(spec)
|
|
121
|
+
}
|
|
122
|
+
throw new ToolError(`theme in config/app.yaml ("${spec}") is neither a theme package (e.g. blog or ` +
|
|
123
|
+
'@nera-static/theme-blog) nor a folder inside the repository (e.g. ./themes/mine).')
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/** Reads a JSON file of the checkout; a file that does not parse is a tool error. */
|
|
127
|
+
async function readJson(dir, name) {
|
|
128
|
+
const text = await fs.readFile(path.join(dir, name), 'utf8')
|
|
129
|
+
try {
|
|
130
|
+
return JSON.parse(text)
|
|
131
|
+
} catch {
|
|
132
|
+
throw new ToolError(`${name} is not valid JSON, so the hosted validate cannot find the version of the site's ` +
|
|
133
|
+
`theme. Fix ${name} and call validate again.`)
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
/**
|
|
138
|
+
* Which version of the theme package `name` the site installs: the one its
|
|
139
|
+
* lockfile pins (`packages["node_modules/<name>"]`, which must come from
|
|
140
|
+
* `NPM_REGISTRY`), else the range or tag its package.json names. A site that
|
|
141
|
+
* depends on no such package gets none: the validator then reports the theme
|
|
142
|
+
* as not installed, as the build would fail on it.
|
|
143
|
+
*
|
|
144
|
+
* @param {string} dir the checkout
|
|
145
|
+
* @param {string} name the theme's npm package
|
|
146
|
+
* @returns {Promise<{ version: string } | { spec: string } | null>}
|
|
147
|
+
* @throws {ToolError} for a pin outside the registry or a spec that is no range or tag
|
|
148
|
+
*/
|
|
149
|
+
export async function themeRequest(dir, name) {
|
|
150
|
+
const files = await fs.readdir(dir)
|
|
151
|
+
for (const lockfile of LOCKFILES.filter((file) => files.includes(file))) {
|
|
152
|
+
const entry = (await readJson(dir, lockfile))?.packages?.[`node_modules/${name}`]
|
|
153
|
+
if (!isPlainObject(entry)) continue
|
|
154
|
+
if (!String(entry.resolved ?? '').startsWith(NPM_REGISTRY)) {
|
|
155
|
+
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}.`)
|
|
156
|
+
}
|
|
157
|
+
if (!semver.valid(entry.version)) {
|
|
158
|
+
throw new ToolError(`The theme ${name} in ${lockfile} has the version "${entry.version}", which is none. ` +
|
|
159
|
+
`Regenerate ${lockfile} with npm install and call validate again.`)
|
|
160
|
+
}
|
|
161
|
+
return { version: entry.version }
|
|
162
|
+
}
|
|
163
|
+
if (!files.includes('package.json')) return null
|
|
164
|
+
const manifest = await readJson(dir, 'package.json')
|
|
165
|
+
for (const field of DEPENDENCY_FIELDS) {
|
|
166
|
+
const spec = manifest?.[field]?.[name]
|
|
167
|
+
if (spec === undefined) continue
|
|
168
|
+
if (typeof spec !== 'string' || (!semver.validRange(spec) && !/^[\w.-]+$/.test(spec))) {
|
|
169
|
+
throw new ToolError(`The theme ${name} in package.json (${field}) is "${spec}", which is not a version ` +
|
|
170
|
+
`range or tag of the npm registry. The hosted validate downloads themes from ${NPM_REGISTRY} only: ` +
|
|
171
|
+
'give a range such as ^1.2.0, or validate this site locally with nera validate.')
|
|
172
|
+
}
|
|
173
|
+
return { spec }
|
|
174
|
+
}
|
|
175
|
+
return null
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* The version a registry `packument` has for `request`: the pinned version,
|
|
180
|
+
* the highest version in the range, or the version of the dist-tag.
|
|
181
|
+
*
|
|
182
|
+
* @returns {string|null}
|
|
183
|
+
*/
|
|
184
|
+
function pickVersion(packument, request) {
|
|
185
|
+
const versions = Object.keys(packument?.versions ?? {})
|
|
186
|
+
if ('version' in request) return versions.includes(request.version) ? request.version : null
|
|
187
|
+
// npm reads a spec as a range when it is one, else as a dist-tag
|
|
188
|
+
const range = semver.validRange(request.spec)
|
|
189
|
+
if (range) return semver.maxSatisfying(versions, range)
|
|
190
|
+
const tagged = packument?.['dist-tags']?.[request.spec]
|
|
191
|
+
return typeof tagged === 'string' && versions.includes(tagged) ? tagged : null
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
/** The tool error for a view path that leaves the checkout; it never says whether the target exists. */
|
|
195
|
+
function viewEscape(where, value) {
|
|
196
|
+
return new ToolError(`${where} ("${value}") points outside the repository. The hosted validate reads only files ` +
|
|
197
|
+
'inside the repository; give the path relative to the views folder (a layout) or to the ' +
|
|
198
|
+
'including file (an include).')
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* Follows the include/extends graph of `file` the way the validator does
|
|
203
|
+
* (`collectIncludeFindings`) and refuses the first target that resolves
|
|
204
|
+
* outside `dir`, before the validator would test whether it exists or read it.
|
|
205
|
+
*/
|
|
206
|
+
async function refuseIncludeEscapes(file, roots, dir, visited) {
|
|
207
|
+
if (visited.has(file)) return
|
|
208
|
+
visited.add(file)
|
|
209
|
+
let source
|
|
210
|
+
try {
|
|
211
|
+
source = await fs.readFile(file, 'utf8')
|
|
212
|
+
} catch {
|
|
213
|
+
return
|
|
214
|
+
}
|
|
215
|
+
const resolve = makeLayeredResolver(roots)
|
|
216
|
+
const lines = source.split(/\r?\n/)
|
|
217
|
+
for (const [index, line] of lines.entries()) {
|
|
218
|
+
const match = line.match(PUG_REFERENCE)
|
|
219
|
+
if (!match) continue
|
|
220
|
+
const target = match[1]
|
|
221
|
+
// Pug appends .pug to an extensionless target before resolving it.
|
|
222
|
+
const resolved = resolve(path.extname(target) ? target : `${target}.pug`, file, { basedir: roots[0] })
|
|
223
|
+
if (!isInside(dir, resolved)) {
|
|
224
|
+
throw viewEscape(`The include/extends target on line ${index + 1} of ${path.relative(dir, file)}`, target)
|
|
225
|
+
}
|
|
226
|
+
if (path.extname(resolved) === '.pug' && fssync.existsSync(resolved)) {
|
|
227
|
+
await refuseIncludeEscapes(resolved, roots, dir, visited)
|
|
228
|
+
}
|
|
229
|
+
}
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
/**
|
|
233
|
+
* Refuses, before the validator runs, every path it would look up outside the
|
|
234
|
+
* checkout: a view root (the theme) found outside it, e.g. in a node_modules
|
|
235
|
+
* folder above it; a page's `layout:` that leaves it below any view root; and
|
|
236
|
+
* a Pug include/extends, in any template the validator reaches from a layout,
|
|
237
|
+
* that leaves it. Without this the validator's verdict on such a path tells
|
|
238
|
+
* whether a file of the server exists, and the include lines of a server
|
|
239
|
+
* template appear in its messages. The lasting fix is a root jail in
|
|
240
|
+
* `validateSite` (the `[nera-validate]` issue 01a2050a-60cb-7274-84dc-ce7f845ffca8);
|
|
241
|
+
* until then this mirrors the validator's own lookups through core's resolver.
|
|
242
|
+
*
|
|
243
|
+
* @param {string} dir the checkout, after the install
|
|
244
|
+
* @throws {ToolError}
|
|
245
|
+
*/
|
|
246
|
+
export async function refuseViewEscapes(dir) {
|
|
247
|
+
const model = resolveSiteModel({ cwd: dir })
|
|
248
|
+
if (!model.roots.every((root) => isInside(dir, root))) {
|
|
249
|
+
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.')
|
|
250
|
+
}
|
|
251
|
+
const visited = new Set()
|
|
252
|
+
// The validator's walk and split: dot folders such as pages/.drafts/ are
|
|
253
|
+
// skipped, and a fence without its closing line makes the rest YAML.
|
|
254
|
+
for (const page of walkFiles(path.resolve(dir, model.folders.pages), { ext: '.md' })) {
|
|
255
|
+
const fence = splitFrontmatter(await fs.readFile(page, 'utf8'))
|
|
256
|
+
if (!fence) continue
|
|
257
|
+
let meta
|
|
258
|
+
try {
|
|
259
|
+
meta = yaml.parse(fence.yamlText, PAGE_YAML_OPTIONS)
|
|
260
|
+
} catch {
|
|
261
|
+
continue // the validator reports it and skips the page
|
|
262
|
+
}
|
|
263
|
+
if (!isPlainObject(meta) || !meta.layout) continue
|
|
264
|
+
const layout = String(meta.layout)
|
|
265
|
+
if (!model.roots.every((root) => isInside(dir, path.join(root, layout)))) {
|
|
266
|
+
throw viewEscape(`The layout of ${path.relative(dir, page)}`, layout)
|
|
267
|
+
}
|
|
268
|
+
const entry = resolveEntry(layout, model.roots)
|
|
269
|
+
if (fssync.existsSync(entry)) await refuseIncludeEscapes(entry, model.roots, dir, visited)
|
|
270
|
+
}
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
/**
|
|
274
|
+
* Creates the checkouts of one server process. The hosted server is built per
|
|
275
|
+
* request, so the instance that keeps "one checkout per user" must outlive it:
|
|
276
|
+
* `createHostedServer` uses `sharedCheckouts` unless a test passes its own.
|
|
277
|
+
*
|
|
278
|
+
* @param {object} [options]
|
|
279
|
+
* @param {ReturnType<typeof createRunner>} [options.runner] runs `tar` (injected so tests stay offline)
|
|
280
|
+
* @param {typeof fetch} [options.fetch] downloads the theme package from the npm registry (injected so tests stay offline)
|
|
281
|
+
* @param {string} [options.tmpdir] where checkouts are made
|
|
282
|
+
* @param {number} [options.maxTarballBytes] the cap on the site's download (`downloadTarball`'s default when absent)
|
|
283
|
+
* @param {number} [options.maxThemeBytes] the cap on the theme package's download
|
|
284
|
+
* @param {number} [options.maxUnpackedBytes] the cap on each unpacked archive
|
|
285
|
+
*/
|
|
286
|
+
export function createCheckouts({
|
|
287
|
+
runner = createRunner(),
|
|
288
|
+
fetch = globalThis.fetch,
|
|
289
|
+
tmpdir = os.tmpdir(),
|
|
290
|
+
maxTarballBytes,
|
|
291
|
+
maxThemeBytes = MAX_THEME_BYTES,
|
|
292
|
+
maxUnpackedBytes = MAX_UNPACKED_BYTES,
|
|
293
|
+
} = {}) {
|
|
294
|
+
/** The users with a checkout in progress. */
|
|
295
|
+
const busy = new Set()
|
|
296
|
+
|
|
297
|
+
/** Unpacks the gzipped `tarball` into `target`, without its top folder (GitHub's `owner-name-sha/`, npm's `package/`). */
|
|
298
|
+
async function unpack(tarball, dir, target, what, signal) {
|
|
299
|
+
let tar
|
|
300
|
+
try {
|
|
301
|
+
tar = await gunzip(tarball, { maxOutputLength: maxUnpackedBytes })
|
|
302
|
+
} catch (error) {
|
|
303
|
+
if (error.code === 'ERR_BUFFER_TOO_LARGE') {
|
|
304
|
+
throw new ToolError(`${what} unpacks to more than the ${maxUnpackedBytes} bytes a checkout may have, ` +
|
|
305
|
+
'so the hosted validate cannot check it.')
|
|
306
|
+
}
|
|
307
|
+
throw new ToolError(`${what} came as no readable archive (${error.message}). Try validate again.`)
|
|
308
|
+
}
|
|
309
|
+
const archive = path.join(dir, 'archive.tar')
|
|
310
|
+
await fs.writeFile(archive, tar)
|
|
311
|
+
const result = await runner('tar', ['-xf', archive, '-C', target, '--strip-components=1'], { cwd: dir, signal, env: checkoutEnv() })
|
|
312
|
+
if (result.code !== 0) throw new ToolError(`Unpacking ${what} failed: ${failureText(result)}`)
|
|
313
|
+
await fs.rm(archive)
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
/**
|
|
317
|
+
* GETs `url` from the npm registry, never following a redirect to another
|
|
318
|
+
* host, and returns at most `maxBytes` of its body; null for a 404.
|
|
319
|
+
*/
|
|
320
|
+
async function fromRegistry(url, { maxBytes, accept, what, signal }) {
|
|
321
|
+
let response
|
|
322
|
+
try {
|
|
323
|
+
response = await fetch(url, { headers: { accept }, redirect: 'error', signal })
|
|
324
|
+
} catch (error) {
|
|
325
|
+
throw new ToolError(`Downloading ${what} from the npm registry failed (${error.message}). ` +
|
|
326
|
+
'Try validate again.')
|
|
327
|
+
}
|
|
328
|
+
if (response.status === 404) return null
|
|
329
|
+
if (!response.ok) throw new ToolError(`The npm registry answered ${response.status} for ${what}. ` +
|
|
330
|
+
'Try validate again.')
|
|
331
|
+
return readLimited(response, maxBytes, () => new ToolError(`${what} is larger than the ${maxBytes} bytes a ` +
|
|
332
|
+
'checkout may download, so the hosted validate cannot check this site.'))
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/**
|
|
336
|
+
* Downloads the theme package `name` from the registry into the
|
|
337
|
+
* checkout's `node_modules/<name>`: the version `themeRequest` names, no
|
|
338
|
+
* dependency of it, nothing from another host.
|
|
339
|
+
*/
|
|
340
|
+
async function addTheme(dir, siteDir, name, signal) {
|
|
341
|
+
const request = await themeRequest(siteDir, name)
|
|
342
|
+
if (!request) return
|
|
343
|
+
const what = `The theme package ${name}`
|
|
344
|
+
const metadata = await fromRegistry(`${NPM_REGISTRY}${name.replace('/', '%2f')}`, {
|
|
345
|
+
maxBytes: MAX_PACKUMENT_BYTES, accept: 'application/vnd.npm.install-v1+json', what: `the registry entry of ${name}`, signal,
|
|
346
|
+
})
|
|
347
|
+
if (!metadata) throw new ToolError(`${what} is not on the npm registry. Publish it, or keep the theme in the ` +
|
|
348
|
+
'repository (theme: ./themes/<name> in config/app.yaml).')
|
|
349
|
+
let packument
|
|
350
|
+
try {
|
|
351
|
+
packument = JSON.parse(metadata.toString('utf8'))
|
|
352
|
+
} catch {
|
|
353
|
+
throw new ToolError(`The npm registry sent no readable entry for ${name}. Try validate again.`)
|
|
354
|
+
}
|
|
355
|
+
const version = pickVersion(packument, request)
|
|
356
|
+
const wanted = 'version' in request ? request.version : request.spec
|
|
357
|
+
if (!version) throw new ToolError(`${what} has no version "${wanted}" on the npm registry. Install an ` +
|
|
358
|
+
`existing version (npm install ${name}) and commit package.json and the lockfile.`)
|
|
359
|
+
const tarballUrl = packument.versions[version]?.dist?.tarball
|
|
360
|
+
if (typeof tarballUrl !== 'string' || !tarballUrl.startsWith(NPM_REGISTRY)) {
|
|
361
|
+
throw new ToolError(`The npm registry names no download of ${name}@${version} on ${NPM_REGISTRY}, so the ` +
|
|
362
|
+
'hosted validate cannot fetch it.')
|
|
363
|
+
}
|
|
364
|
+
const tarball = await fromRegistry(tarballUrl, { maxBytes: maxThemeBytes, accept: 'application/octet-stream', what: `${what} (${version})`, signal })
|
|
365
|
+
if (!tarball) throw new ToolError(`The npm registry has no download of ${name}@${version}. Try validate again.`)
|
|
366
|
+
const target = path.join(siteDir, 'node_modules', ...name.split('/'))
|
|
367
|
+
await fs.rm(target, { recursive: true, force: true })
|
|
368
|
+
await fs.mkdir(target, { recursive: true })
|
|
369
|
+
await unpack(tarball, dir, target, `${what} (${version})`, signal)
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
return {
|
|
373
|
+
/**
|
|
374
|
+
* Checks out `ref` of `site` into a temporary folder, calls `use` with
|
|
375
|
+
* it and deletes the folder afterwards, also when anything failed.
|
|
376
|
+
*
|
|
377
|
+
* @template T
|
|
378
|
+
* @param {string} userId the signed-in user; one checkout each at a time
|
|
379
|
+
* @param {object} source
|
|
380
|
+
* @param {ReturnType<typeof import('./repo.js').createRepoClient>} source.client the user's repository client
|
|
381
|
+
* @param {string} source.site `owner/name`
|
|
382
|
+
* @param {string} source.ref the commit to check out
|
|
383
|
+
* @param {AbortSignal} [source.signal] stops the downloads and `tar` when the client cancels
|
|
384
|
+
* @param {(dir: string) => T|Promise<T>} use gets the checkout's folder
|
|
385
|
+
* @returns {Promise<T>}
|
|
386
|
+
*/
|
|
387
|
+
async withCheckout(userId, { client, site, ref, signal }, use) {
|
|
388
|
+
if (busy.has(userId)) {
|
|
389
|
+
throw new ToolError('Another validate of yours is still running. Wait for its result, then call validate again.')
|
|
390
|
+
}
|
|
391
|
+
busy.add(userId)
|
|
392
|
+
let dir = null
|
|
393
|
+
try {
|
|
394
|
+
// undefined keeps downloadTarball's own default cap
|
|
395
|
+
const tarball = await client.downloadTarball(site, ref, { maxBytes: maxTarballBytes })
|
|
396
|
+
dir = await fs.mkdtemp(path.join(tmpdir, 'nera-mcp-checkout-'))
|
|
397
|
+
const siteDir = path.join(dir, 'site')
|
|
398
|
+
await fs.mkdir(siteDir)
|
|
399
|
+
await unpack(tarball, dir, siteDir, `The repository ${site}`, signal)
|
|
400
|
+
await removeLinks(siteDir)
|
|
401
|
+
const theme = await refuseEscapes(siteDir)
|
|
402
|
+
if (theme) {
|
|
403
|
+
await addTheme(dir, siteDir, theme, signal)
|
|
404
|
+
await removeLinks(siteDir)
|
|
405
|
+
}
|
|
406
|
+
await refuseViewEscapes(siteDir)
|
|
407
|
+
return await use(siteDir)
|
|
408
|
+
} finally {
|
|
409
|
+
if (dir) await fs.rm(dir, { recursive: true, force: true })
|
|
410
|
+
busy.delete(userId)
|
|
411
|
+
}
|
|
412
|
+
},
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
/** The checkouts of this server process. */
|
|
417
|
+
export const sharedCheckouts = createCheckouts()
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
// The hosted mode's configuration (L7b), read by the bin before anything else
|
|
2
|
+
// of `src/hosted/` loads. It imports nothing of `src/hosted/` on purpose: the
|
|
3
|
+
// bin calls it before it knows whether this Node has `node:sqlite`, which
|
|
4
|
+
// `store.js` needs.
|
|
5
|
+
// Values come from the environment, never from the command line, so no secret
|
|
6
|
+
// shows up in `ps`; no error message ever quotes a value.
|
|
7
|
+
import { satisfiesFloor } from '@nera-static/plugin-utils/guard'
|
|
8
|
+
|
|
9
|
+
/** The environment variables the hosted mode needs, with what each one is. */
|
|
10
|
+
export const HOSTED_ENV = Object.freeze({
|
|
11
|
+
NERA_MCP_ISSUER: 'our public origin, e.g. https://mcp.nera-pro.app',
|
|
12
|
+
NERA_MCP_DB: 'the SQLite file for clients and tokens',
|
|
13
|
+
NERA_MCP_TOKEN_KEY: 'the key that encrypts GitHub tokens (openssl rand -base64 32)',
|
|
14
|
+
NERA_MCP_GITHUB_CLIENT_ID: 'the GitHub App\'s client ID',
|
|
15
|
+
NERA_MCP_GITHUB_CLIENT_SECRET: 'the GitHub App\'s client secret',
|
|
16
|
+
})
|
|
17
|
+
|
|
18
|
+
/** The first Node releases with an unflagged `node:sqlite` on the 22 and 23 lines. */
|
|
19
|
+
const SQLITE_SINCE = Object.freeze({ 22: '22.13.0', 23: '23.4.0' })
|
|
20
|
+
/** The floor for every other line: 24 and later have it from their first release, older lines never. */
|
|
21
|
+
const SQLITE_OTHER_LINES = '24.0.0'
|
|
22
|
+
|
|
23
|
+
/** A configuration the hosted mode cannot start with; the message is safe to print. */
|
|
24
|
+
export class HostedConfigError extends Error {
|
|
25
|
+
constructor(message) {
|
|
26
|
+
super(message)
|
|
27
|
+
this.name = 'HostedConfigError'
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Whether a Node version has `node:sqlite` without a flag: 22.13+, 23.4+, 24+.
|
|
33
|
+
*
|
|
34
|
+
* @param {string} version `process.versions.node`, e.g. `22.12.0`
|
|
35
|
+
* @returns {boolean}
|
|
36
|
+
*/
|
|
37
|
+
export function hasNodeSqlite(version) {
|
|
38
|
+
const major = Number.parseInt(version, 10)
|
|
39
|
+
return satisfiesFloor(version, SQLITE_SINCE[major] ?? SQLITE_OTHER_LINES)
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Reads the hosted mode's settings from `env`. Every missing variable is named
|
|
44
|
+
* in one error, so the operator fixes them in one go.
|
|
45
|
+
*
|
|
46
|
+
* @param {Record<string, string|undefined>} env usually `process.env`
|
|
47
|
+
* @returns {{ issuer: string, db: string, tokenKey: string, githubClientId: string, githubClientSecret: string }}
|
|
48
|
+
* @throws {HostedConfigError} when a variable is missing or empty
|
|
49
|
+
*/
|
|
50
|
+
export function readHostedConfig(env) {
|
|
51
|
+
const missing = Object.keys(HOSTED_ENV).filter((name) => !env[name]?.trim())
|
|
52
|
+
if (missing.length > 0) {
|
|
53
|
+
const lines = missing.map((name) => ` ${name} ${HOSTED_ENV[name]}`)
|
|
54
|
+
throw new HostedConfigError(`the hosted mode (--http) needs these environment variables:\n${lines.join('\n')}`)
|
|
55
|
+
}
|
|
56
|
+
return {
|
|
57
|
+
issuer: env.NERA_MCP_ISSUER.trim(),
|
|
58
|
+
db: env.NERA_MCP_DB.trim(),
|
|
59
|
+
tokenKey: env.NERA_MCP_TOKEN_KEY.trim(),
|
|
60
|
+
githubClientId: env.NERA_MCP_GITHUB_CLIENT_ID.trim(),
|
|
61
|
+
githubClientSecret: env.NERA_MCP_GITHUB_CLIENT_SECRET.trim(),
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
/**
|
|
66
|
+
* Turns `--trust-proxy` into Express's `trust proxy` setting: a number of
|
|
67
|
+
* hops (`1`), or the addresses/subnets to trust (`loopback`, `10.0.0.0/8`).
|
|
68
|
+
* Absent means no proxy is trusted.
|
|
69
|
+
*
|
|
70
|
+
* @param {string|undefined} value
|
|
71
|
+
* @returns {false|number|string}
|
|
72
|
+
*/
|
|
73
|
+
export function parseTrustProxy(value) {
|
|
74
|
+
if (value === undefined) return false
|
|
75
|
+
const text = value.trim()
|
|
76
|
+
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).')
|
|
77
|
+
return /^\d+$/.test(text) ? Number(text) : text
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
/**
|
|
81
|
+
* Turns `--port` into a TCP port; `0` picks a free one.
|
|
82
|
+
*
|
|
83
|
+
* @param {string|undefined} value
|
|
84
|
+
* @param {number} fallback
|
|
85
|
+
* @returns {number}
|
|
86
|
+
*/
|
|
87
|
+
export function parsePort(value, fallback) {
|
|
88
|
+
if (value === undefined) return fallback
|
|
89
|
+
const port = /^\d+$/.test(value.trim()) ? Number(value) : NaN
|
|
90
|
+
if (!(port >= 0 && port <= 65535)) throw new HostedConfigError('--port must be a number from 0 ' +
|
|
91
|
+
`to 65535 (got ${value}).`)
|
|
92
|
+
return port
|
|
93
|
+
}
|
|
@@ -0,0 +1,146 @@
|
|
|
1
|
+
// The hosted mode's consent page (L7b; it asks on every sign-in and remembers
|
|
2
|
+
// no approval). Any client can register itself via DCR, and GitHub does not
|
|
3
|
+
// ask again once a user has authorized the "Nera Static" App — so without a
|
|
4
|
+
// page of our own, a link to our `/authorize` with an attacker's client would
|
|
5
|
+
// sign a victim in silently and hand the code to the attacker's redirect URI
|
|
6
|
+
// (the "confused deputy" of the MCP authorization spec). This page names the
|
|
7
|
+
// client and where it sends the user, and only its Approve button goes on to
|
|
8
|
+
// GitHub.
|
|
9
|
+
//
|
|
10
|
+
// The page is bound to the browser that opened it: a random token sits both in
|
|
11
|
+
// an HttpOnly cookie and in the form, and the store keeps only its hash. A
|
|
12
|
+
// forged POST from another site cannot know this browser's token, so its form
|
|
13
|
+
// field never matches the cookie, whatever SameSite does; and a state an
|
|
14
|
+
// attacker approved in their own browser is refused at the GitHub callback,
|
|
15
|
+
// which checks the same cookie.
|
|
16
|
+
import { createHash } from 'node:crypto'
|
|
17
|
+
import { escapeHtml } from '@nera-static/plugin-utils/html'
|
|
18
|
+
|
|
19
|
+
/** Where the consent form posts to; step 3 mounts the route here. */
|
|
20
|
+
export const CONSENT_PATH = '/oauth/consent'
|
|
21
|
+
|
|
22
|
+
/** The browser-binding cookie. `__Host-`: Secure, Path=/, no Domain, so no subdomain can set it. */
|
|
23
|
+
export const CONSENT_COOKIE = '__Host-nera-consent'
|
|
24
|
+
|
|
25
|
+
const STYLE = `
|
|
26
|
+
body {
|
|
27
|
+
font: 16px/1.5 system-ui, sans-serif; max-width: 32rem; margin: 3rem auto; padding: 0 1rem;
|
|
28
|
+
color: #1f2328; background: #fff;
|
|
29
|
+
}
|
|
30
|
+
h1 { font-size: 1.4rem; }
|
|
31
|
+
.client { font-weight: 600; overflow-wrap: anywhere; }
|
|
32
|
+
.host { font-family: ui-monospace, monospace; overflow-wrap: anywhere; }
|
|
33
|
+
.actions { display: flex; gap: 0.75rem; margin-top: 2rem; }
|
|
34
|
+
button {
|
|
35
|
+
font: inherit; padding: 0.5rem 1.25rem; border-radius: 6px; border: 1px solid #d0d7de;
|
|
36
|
+
background: #f6f8fa; cursor: pointer;
|
|
37
|
+
}
|
|
38
|
+
button[value="approve"] { background: #1f883d; border-color: #1f883d; color: #fff; }
|
|
39
|
+
@media (prefers-color-scheme: dark) {
|
|
40
|
+
body { color: #e6edf3; background: #0d1117; }
|
|
41
|
+
button { background: #21262d; border-color: #30363d; color: #e6edf3; }
|
|
42
|
+
}
|
|
43
|
+
`
|
|
44
|
+
|
|
45
|
+
/** The page allows its own inline style block and nothing else; no framing. */
|
|
46
|
+
const CONTENT_SECURITY_POLICY = [
|
|
47
|
+
'default-src \'none\'',
|
|
48
|
+
`style-src 'sha256-${createHash('sha256').update(STYLE).digest('base64')}'`,
|
|
49
|
+
'frame-ancestors \'none\'',
|
|
50
|
+
'base-uri \'none\'',
|
|
51
|
+
// No `form-action`: browsers apply it to the redirect that follows the
|
|
52
|
+
// POST too, and that goes to GitHub or to the client's redirect URI.
|
|
53
|
+
].join('; ')
|
|
54
|
+
|
|
55
|
+
/** Headers for every response of the consent flow: never cached, never framed. */
|
|
56
|
+
export const CONSENT_HEADERS = Object.freeze({
|
|
57
|
+
'Cache-Control': 'no-store',
|
|
58
|
+
'Content-Security-Policy': CONTENT_SECURITY_POLICY,
|
|
59
|
+
'X-Frame-Options': 'DENY',
|
|
60
|
+
'Referrer-Policy': 'no-referrer',
|
|
61
|
+
'X-Content-Type-Options': 'nosniff',
|
|
62
|
+
})
|
|
63
|
+
|
|
64
|
+
/**
|
|
65
|
+
* What the page shows as the place the client sends the user back to: the
|
|
66
|
+
* host of a web redirect URI, the whole URI for a custom scheme or loopback
|
|
67
|
+
* app without one.
|
|
68
|
+
*
|
|
69
|
+
* @param {string} redirectUri
|
|
70
|
+
* @returns {string}
|
|
71
|
+
*/
|
|
72
|
+
export function redirectTarget(redirectUri) {
|
|
73
|
+
const url = new URL(redirectUri)
|
|
74
|
+
return url.host || url.href
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* The consent page.
|
|
79
|
+
*
|
|
80
|
+
* @param {object} page
|
|
81
|
+
* @param {string} [page.clientName] the client's self-declared `client_name`
|
|
82
|
+
* @param {string} page.clientId
|
|
83
|
+
* @param {string} page.redirectUri
|
|
84
|
+
* @param {string} page.state our pending state
|
|
85
|
+
* @param {string} page.csrfToken the browser-binding token, also in the cookie
|
|
86
|
+
* @param {string} [page.action] where the form posts
|
|
87
|
+
* @returns {string} the HTML
|
|
88
|
+
*/
|
|
89
|
+
export function renderConsentPage({ clientName, clientId, redirectUri, state, csrfToken, action = CONSENT_PATH }) {
|
|
90
|
+
const name = clientName?.trim() ? clientName.trim() : `An application without a name (${clientId})`
|
|
91
|
+
return `<!doctype html>
|
|
92
|
+
<html lang="en">
|
|
93
|
+
<head>
|
|
94
|
+
<meta charset="utf-8">
|
|
95
|
+
<meta name="viewport" content="width=device-width, initial-scale=1">
|
|
96
|
+
<title>Connect to Nera</title>
|
|
97
|
+
<style>${STYLE}</style>
|
|
98
|
+
</head>
|
|
99
|
+
<body>
|
|
100
|
+
<h1>Connect an application to Nera?</h1>
|
|
101
|
+
<p><span class="client">${escapeHtml(name)}</span> wants to work on your Nera sites with your GitHub account.</p>
|
|
102
|
+
<p>After you approve and sign in with GitHub, you are sent back to \
|
|
103
|
+
<span class="host">${escapeHtml(redirectTarget(redirectUri))}</span>.</p>
|
|
104
|
+
<p>The name is chosen by the application itself. Approve only if you started this connection from your AI assistant \
|
|
105
|
+
just now and you recognise that address.</p>
|
|
106
|
+
<form method="post" action="${escapeHtml(action)}">
|
|
107
|
+
<input type="hidden" name="state" value="${escapeHtml(state)}">
|
|
108
|
+
<input type="hidden" name="csrf_token" value="${escapeHtml(csrfToken)}">
|
|
109
|
+
<div class="actions">
|
|
110
|
+
<button type="submit" name="decision" value="approve">Approve</button>
|
|
111
|
+
<button type="submit" name="decision" value="deny">Deny</button>
|
|
112
|
+
</div>
|
|
113
|
+
</form>
|
|
114
|
+
</body>
|
|
115
|
+
</html>
|
|
116
|
+
`
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
/**
|
|
120
|
+
* The `Set-Cookie` value for the browser-binding token. `SameSite=Lax`, not
|
|
121
|
+
* `Strict`: the cookie must come along on GitHub's top-level redirect back to
|
|
122
|
+
* our callback. The protection does not rest on SameSite, though — see above.
|
|
123
|
+
*
|
|
124
|
+
* @param {string} token
|
|
125
|
+
* @param {number} maxAge seconds; 0 deletes the cookie
|
|
126
|
+
*/
|
|
127
|
+
export function consentCookie(token, maxAge) {
|
|
128
|
+
return `${CONSENT_COOKIE}=${token}; Max-Age=${maxAge}; Path=/; Secure; HttpOnly; SameSite=Lax`
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
/**
|
|
132
|
+
* Reads the browser-binding token from a `Cookie` request header.
|
|
133
|
+
*
|
|
134
|
+
* @param {string|undefined} header
|
|
135
|
+
* @returns {string|undefined}
|
|
136
|
+
*/
|
|
137
|
+
export function readConsentCookie(header) {
|
|
138
|
+
if (typeof header !== 'string') return undefined
|
|
139
|
+
for (const part of header.split(';')) {
|
|
140
|
+
const separator = part.indexOf('=')
|
|
141
|
+
if (separator !== -1 && part.slice(0, separator).trim() === CONSENT_COOKIE) {
|
|
142
|
+
return part.slice(separator + 1).trim() || undefined
|
|
143
|
+
}
|
|
144
|
+
}
|
|
145
|
+
return undefined
|
|
146
|
+
}
|