@nera-static/mcp 1.4.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/package.json CHANGED
@@ -1,8 +1,21 @@
1
1
  {
2
2
  "name": "@nera-static/mcp",
3
- "version": "1.4.0",
3
+ "version": "1.4.1",
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
+ "bin": {
7
+ "nera-mcp": "bin/nera-mcp.js"
8
+ },
9
+ "scripts": {
10
+ "lint": "nera-stan",
11
+ "test": "vitest run",
12
+ "test:watch": "vitest",
13
+ "prepack": "node scripts/fetch-docs.js && node scripts/sync-skill.js",
14
+ "mcpb": "node scripts/fetch-docs.js && node scripts/build-mcpb.js",
15
+ "skill": "node scripts/sync-skill.js",
16
+ "version": "node scripts/sync-version.js && git add .claude-plugin/plugin.json",
17
+ "prepare": "husky"
18
+ },
6
19
  "files": [
7
20
  ".claude-plugin/icon.png",
8
21
  ".claude-plugin/plugin.json",
@@ -12,14 +25,6 @@
12
25
  "src",
13
26
  "CHANGELOG.md"
14
27
  ],
15
- "scripts": {
16
- "lint": "eslint .",
17
- "test": "vitest",
18
- "prepack": "node scripts/fetch-docs.js && node scripts/sync-skill.js",
19
- "mcpb": "node scripts/fetch-docs.js && node scripts/build-mcpb.js",
20
- "skill": "node scripts/sync-skill.js",
21
- "version": "node scripts/sync-version.js && git add .claude-plugin/plugin.json"
22
- },
23
28
  "keywords": [
24
29
  "nera",
25
30
  "mcp",
@@ -38,16 +43,17 @@
38
43
  "url": "https://github.com/seebaermichi/nera-mcp/issues"
39
44
  },
40
45
  "homepage": "https://github.com/seebaermichi/nera-mcp#readme",
41
- "engines": {
42
- "node": ">=22.12.0"
43
- },
44
46
  "publishConfig": {
45
47
  "access": "public"
46
48
  },
49
+ "engines": {
50
+ "node": ">=22.12.0"
51
+ },
47
52
  "dependencies": {
48
53
  "@modelcontextprotocol/sdk": "^1.32.2",
49
54
  "@nera-static/core": "^4.18.3",
50
- "@nera-static/nera": "^1.27.0",
55
+ "@nera-static/nera": "^1.31.0",
56
+ "@nera-static/plugin-utils": "^1.9.0",
51
57
  "express": "^5.3.0",
52
58
  "semver": "^7.8.6",
53
59
  "yaml": "^2.9.1",
@@ -55,11 +61,16 @@
55
61
  },
56
62
  "devDependencies": {
57
63
  "@anthropic-ai/mcpb": "^2.1.2",
58
- "eslint": "^10.15.0",
64
+ "@nera-static/stan": "^1.1.0",
65
+ "@nera-static/test-utils": "^1.1.0",
66
+ "husky": "^9.1.7",
59
67
  "vitest": "^5.1.1"
60
68
  },
61
- "bin": {
62
- "nera-mcp": "bin/nera-mcp.js"
63
- },
64
- "mcpName": "io.github.seebaermichi/nera-mcp"
69
+ "mcpName": "io.github.seebaermichi/nera-mcp",
70
+ "nera-stan": {
71
+ "variants": {
72
+ ".github/workflows/test.yml": "windows-smoke",
73
+ ".github/workflows/publish.yml": "desktop-release"
74
+ }
75
+ }
65
76
  }
@@ -25,6 +25,9 @@ Eleventy, Hugo, Astro or Jekyll; do not apply their conventions.
25
25
  Start from an official starter when one fits, with `--starter <name>`:
26
26
  - `blank`: a home page, imprint and privacy placeholders, one layout
27
27
  - `blog`: sample posts, tags, archive, prev/next, feed, sitemap
28
+ - `stack`: a blog for developers with highlighted code, series and search
29
+ - `ansitz`: a photo blog with large photographs, series and search
30
+ - `umwege`: a travel blog with trip facts, places, photographs and search
28
31
  - `business`: home, about, services, opening hours, contact form
29
32
  - `portfolio`: project pages with image galleries, about, contact form
30
33
 
@@ -5,11 +5,15 @@ links and a sitemap.
5
5
 
6
6
  ## Fast path
7
7
 
8
- `npx @nera-static/nera new my-blog --starter blog` creates a blog on
9
- `@nera-static/theme-blog`: sample posts, tags, an archive by year,
10
- previous/next, an Atom feed, a sitemap and navigation. The theme's own
11
- templates list the posts; it does not use simple-page-list. Read its
12
- `AGENTS.md`, then replace the sample posts and the placeholder
8
+ `npx @nera-static/nera new my-blog --starter blog` creates a plain blog on
9
+ `@nera-static/theme-blog` 2.x: sample posts with a series, tags, an archive
10
+ by year, previous/next, an Atom feed, a sitemap and navigation. With `--yes`
11
+ or without a terminal it is always this plain blog; on a terminal without
12
+ `--yes` it first asks which blog. `--starter stack` (a blog for developers,
13
+ highlighted code), `--starter ansitz` (a photo blog) and `--starter umwege`
14
+ (a travel blog) pick another one directly, each on its own theme with the
15
+ same post fields. The theme's own templates list the posts; it does not use
16
+ simple-page-list. Read the new site's `AGENTS.md`, then replace the sample posts and the placeholder
13
17
  `origin: https://example.com` in `config/app.yaml` with the live URL; step 9
14
18
  below still applies. The steps below build the blog by hand instead, with
15
19
  different files.
package/src/catalog.js CHANGED
@@ -4,7 +4,7 @@ import { ok, tool, ToolError } from './results.js'
4
4
 
5
5
  /**
6
6
  * The three catalogs, as the tools and resources present them. The registry
7
- * search itself is the CLI's `listCatalog` (ROADMAP principle 4).
7
+ * search itself is the CLI's `listCatalog`: one logic, many front ends.
8
8
  */
9
9
  export const KINDS = {
10
10
  starters: {
package/src/hosted/app.js CHANGED
@@ -1,4 +1,4 @@
1
- // The HTTP app of the hosted mode (L7b, plan D1/D4/D5): one Express app that
1
+ // The HTTP app of the hosted mode (L7b): one Express app that
2
2
  // is both the OAuth 2.1 authorization server and the protected MCP resource.
3
3
  //
4
4
  // /.well-known/oauth-protected-resource/mcp RFC 9728, names our issuer
@@ -66,7 +66,9 @@ function issuerUrl(issuer) {
66
66
  * @param {boolean|number|string} [options.trustProxy] Express's `trust proxy`, so the rate limits see the client's address behind a proxy
67
67
  * @returns {{ app: import('express').Express, provider: ReturnType<typeof createProvider> }}
68
68
  */
69
- export function createHostedApp({ issuer, store, github, fetch = globalThis.fetch, createRepo, now, log = () => {}, trustProxy = false }) {
69
+ export function createHostedApp({
70
+ issuer, store, github, fetch = globalThis.fetch, createRepo, now, log = () => {}, trustProxy = false,
71
+ }) {
70
72
  const base = issuerUrl(issuer)
71
73
  const resource = new URL(MCP_PATH, base)
72
74
  const provider = createProvider({ store, github, resource, now, log })
@@ -1,4 +1,4 @@
1
- // The temporary checkout of the hosted `validate` (L7b, plan D1/D6). The
1
+ // The temporary checkout of the hosted `validate` (L7b). The
2
2
  // hosted server builds nothing and runs no npm: it downloads a site's tarball
3
3
  // from GitHub, unpacks it with the system `tar` into a fresh folder, deletes
4
4
  // every symbolic link (and anything else that is not a plain file or folder),
@@ -16,8 +16,14 @@ import path from 'node:path'
16
16
  import { promisify } from 'node:util'
17
17
  import { gunzip as gunzipCallback } from 'node:zlib'
18
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'
19
24
  import semver from 'semver'
20
25
  import yaml from 'yaml'
26
+ import { PAGE_YAML_OPTIONS } from '../pages.js'
21
27
  import { ToolError } from '../results.js'
22
28
  import { createRunner } from '../runner.js'
23
29
  import { failureText } from '../tools/cli.js'
@@ -39,8 +45,6 @@ const LOCKFILES = ['package-lock.json', 'npm-shrinkwrap.json']
39
45
  export const NPM_REGISTRY = 'https://registry.npmjs.org/'
40
46
  /** The package.json fields that name the site's theme package, in the order they are searched. */
41
47
  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
48
  /** A Pug `include`/`include:filter`/`extends` line exactly as `@nera-static/validate` (src/pug-refs.js) reads it. */
45
49
  const PUG_REFERENCE = /^\s*(?:include(?::[^\s]+)?|extends)\s+(.+?)\s*$/
46
50
 
@@ -79,22 +83,6 @@ export async function removeLinks(dir) {
79
83
  return removed
80
84
  }
81
85
 
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
86
  /**
99
87
  * Refuses a site whose `config/app.yaml` sends the validator outside the
100
88
  * checkout: a `folders.<key>` that resolves outside it, a local `theme:` path
@@ -114,10 +102,12 @@ export async function refuseEscapes(dir) {
114
102
  } catch {
115
103
  return null
116
104
  }
117
- if (!appConfig || typeof appConfig !== 'object' || Array.isArray(appConfig)) return null
105
+ if (!isPlainObject(appConfig)) return null
118
106
  for (const [key, folder] of Object.entries(computeFolders(appConfig, { cwd: dir }))) {
119
107
  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}.`)
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}.`)
121
111
  }
122
112
  }
123
113
  const theme = appConfig.theme
@@ -126,9 +116,11 @@ export async function refuseEscapes(dir) {
126
116
  if (spec.startsWith('.')) {
127
117
  if (isInside(dir, path.resolve(dir, spec))) return null
128
118
  } else if (THEME_PACKAGE.test(spec)) {
129
- return themePackageName(spec)
119
+ // THEME_PACKAGE has refused an unscoped `a/b`, which themePackage would keep
120
+ return themePackage(spec)
130
121
  }
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).`)
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).')
132
124
  }
133
125
 
134
126
  /** Reads a JSON file of the checkout; a file that does not parse is a tool error. */
@@ -137,7 +129,8 @@ async function readJson(dir, name) {
137
129
  try {
138
130
  return JSON.parse(text)
139
131
  } 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.`)
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.`)
141
134
  }
142
135
  }
143
136
 
@@ -157,12 +150,13 @@ export async function themeRequest(dir, name) {
157
150
  const files = await fs.readdir(dir)
158
151
  for (const lockfile of LOCKFILES.filter((file) => files.includes(file))) {
159
152
  const entry = (await readJson(dir, lockfile))?.packages?.[`node_modules/${name}`]
160
- if (!entry || typeof entry !== 'object') continue
153
+ if (!isPlainObject(entry)) continue
161
154
  if (!String(entry.resolved ?? '').startsWith(NPM_REGISTRY)) {
162
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}.`)
163
156
  }
164
157
  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.`)
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.`)
166
160
  }
167
161
  return { version: entry.version }
168
162
  }
@@ -172,7 +166,9 @@ export async function themeRequest(dir, name) {
172
166
  const spec = manifest?.[field]?.[name]
173
167
  if (spec === undefined) continue
174
168
  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.`)
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.')
176
172
  }
177
173
  return { spec }
178
174
  }
@@ -197,24 +193,9 @@ function pickVersion(packument, request) {
197
193
 
198
194
  /** The tool error for a view path that leaves the checkout; it never says whether the target exists. */
199
195
  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
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).')
218
199
  }
219
200
 
220
201
  /**
@@ -268,16 +249,18 @@ export async function refuseViewEscapes(dir) {
268
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.')
269
250
  }
270
251
  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)
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'))
273
256
  if (!fence) continue
274
257
  let meta
275
258
  try {
276
- meta = yaml.parse(fence[1])
259
+ meta = yaml.parse(fence.yamlText, PAGE_YAML_OPTIONS)
277
260
  } catch {
278
261
  continue // the validator reports it and skips the page
279
262
  }
280
- if (!meta || typeof meta !== 'object' || !meta.layout) continue
263
+ if (!isPlainObject(meta) || !meta.layout) continue
281
264
  const layout = String(meta.layout)
282
265
  if (!model.roots.every((root) => isInside(dir, path.join(root, layout)))) {
283
266
  throw viewEscape(`The layout of ${path.relative(dir, page)}`, layout)
@@ -318,7 +301,8 @@ export function createCheckouts({
318
301
  tar = await gunzip(tarball, { maxOutputLength: maxUnpackedBytes })
319
302
  } catch (error) {
320
303
  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.`)
304
+ throw new ToolError(`${what} unpacks to more than the ${maxUnpackedBytes} bytes a checkout may have, ` +
305
+ 'so the hosted validate cannot check it.')
322
306
  }
323
307
  throw new ToolError(`${what} came as no readable archive (${error.message}). Try validate again.`)
324
308
  }
@@ -338,11 +322,14 @@ export function createCheckouts({
338
322
  try {
339
323
  response = await fetch(url, { headers: { accept }, redirect: 'error', signal })
340
324
  } catch (error) {
341
- throw new ToolError(`Downloading ${what} from the npm registry failed (${error.message}). Try validate again.`)
325
+ throw new ToolError(`Downloading ${what} from the npm registry failed (${error.message}). ` +
326
+ 'Try validate again.')
342
327
  }
343
328
  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.`))
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.'))
346
333
  }
347
334
 
348
335
  /**
@@ -357,7 +344,8 @@ export function createCheckouts({
357
344
  const metadata = await fromRegistry(`${NPM_REGISTRY}${name.replace('/', '%2f')}`, {
358
345
  maxBytes: MAX_PACKUMENT_BYTES, accept: 'application/vnd.npm.install-v1+json', what: `the registry entry of ${name}`, signal,
359
346
  })
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).`)
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).')
361
349
  let packument
362
350
  try {
363
351
  packument = JSON.parse(metadata.toString('utf8'))
@@ -366,10 +354,12 @@ export function createCheckouts({
366
354
  }
367
355
  const version = pickVersion(packument, request)
368
356
  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.`)
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.`)
370
359
  const tarballUrl = packument.versions[version]?.dist?.tarball
371
360
  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.`)
361
+ throw new ToolError(`The npm registry names no download of ${name}@${version} on ${NPM_REGISTRY}, so the ` +
362
+ 'hosted validate cannot fetch it.')
373
363
  }
374
364
  const tarball = await fromRegistry(tarballUrl, { maxBytes: maxThemeBytes, accept: 'application/octet-stream', what: `${what} (${version})`, signal })
375
365
  if (!tarball) throw new ToolError(`The npm registry has no download of ${name}@${version}. Try validate again.`)
@@ -1,8 +1,10 @@
1
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.
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.
4
5
  // Values come from the environment, never from the command line, so no secret
5
6
  // shows up in `ps`; no error message ever quotes a value.
7
+ import { satisfiesFloor } from '@nera-static/plugin-utils/guard'
6
8
 
7
9
  /** The environment variables the hosted mode needs, with what each one is. */
8
10
  export const HOSTED_ENV = Object.freeze({
@@ -13,8 +15,10 @@ export const HOSTED_ENV = Object.freeze({
13
15
  NERA_MCP_GITHUB_CLIENT_SECRET: 'the GitHub App\'s client secret',
14
16
  })
15
17
 
16
- /** The first Node releases with an unflagged `node:sqlite`, per major line. */
17
- const SQLITE_SINCE = Object.freeze({ 22: 13, 23: 4 })
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'
18
22
 
19
23
  /** A configuration the hosted mode cannot start with; the message is safe to print. */
20
24
  export class HostedConfigError extends Error {
@@ -31,9 +35,8 @@ export class HostedConfigError extends Error {
31
35
  * @returns {boolean}
32
36
  */
33
37
  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
38
+ const major = Number.parseInt(version, 10)
39
+ return satisfiesFloor(version, SQLITE_SINCE[major] ?? SQLITE_OTHER_LINES)
37
40
  }
38
41
 
39
42
  /**
@@ -84,6 +87,7 @@ export function parseTrustProxy(value) {
84
87
  export function parsePort(value, fallback) {
85
88
  if (value === undefined) return fallback
86
89
  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}).`)
90
+ if (!(port >= 0 && port <= 65535)) throw new HostedConfigError('--port must be a number from 0 ' +
91
+ `to 65535 (got ${value}).`)
88
92
  return port
89
93
  }
@@ -1,10 +1,11 @@
1
- // The hosted mode's consent page (L7b, plan step 2b, decision D6). Any client
2
- // can register itself via DCR, and GitHub does not ask again once a user has
3
- // authorized the "Nera Static" App — so without a page of our own, a link to
4
- // our `/authorize` with an attacker's client would sign a victim in silently
5
- // and hand the code to the attacker's redirect URI (the "confused deputy" of
6
- // the MCP authorization spec). This page names the client and where it sends
7
- // the user, and only its Approve button goes on to GitHub.
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.
8
9
  //
9
10
  // The page is bound to the browser that opened it: a random token sits both in
10
11
  // an HttpOnly cookie and in the form, and the store keeps only its hash. A
@@ -13,6 +14,7 @@
13
14
  // attacker approved in their own browser is refused at the GitHub callback,
14
15
  // which checks the same cookie.
15
16
  import { createHash } from 'node:crypto'
17
+ import { escapeHtml } from '@nera-static/plugin-utils/html'
16
18
 
17
19
  /** Where the consent form posts to; step 3 mounts the route here. */
18
20
  export const CONSENT_PATH = '/oauth/consent'
@@ -21,14 +23,23 @@ export const CONSENT_PATH = '/oauth/consent'
21
23
  export const CONSENT_COOKIE = '__Host-nera-consent'
22
24
 
23
25
  const STYLE = `
24
- body { font: 16px/1.5 system-ui, sans-serif; max-width: 32rem; margin: 3rem auto; padding: 0 1rem; color: #1f2328; background: #fff; }
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
+ }
25
30
  h1 { font-size: 1.4rem; }
26
31
  .client { font-weight: 600; overflow-wrap: anywhere; }
27
32
  .host { font-family: ui-monospace, monospace; overflow-wrap: anywhere; }
28
33
  .actions { display: flex; gap: 0.75rem; margin-top: 2rem; }
29
- button { font: inherit; padding: 0.5rem 1.25rem; border-radius: 6px; border: 1px solid #d0d7de; background: #f6f8fa; cursor: pointer; }
34
+ button {
35
+ font: inherit; padding: 0.5rem 1.25rem; border-radius: 6px; border: 1px solid #d0d7de;
36
+ background: #f6f8fa; cursor: pointer;
37
+ }
30
38
  button[value="approve"] { background: #1f883d; border-color: #1f883d; color: #fff; }
31
- @media (prefers-color-scheme: dark) { body { color: #e6edf3; background: #0d1117; } button { background: #21262d; border-color: #30363d; color: #e6edf3; } }
39
+ @media (prefers-color-scheme: dark) {
40
+ body { color: #e6edf3; background: #0d1117; }
41
+ button { background: #21262d; border-color: #30363d; color: #e6edf3; }
42
+ }
32
43
  `
33
44
 
34
45
  /** The page allows its own inline style block and nothing else; no framing. */
@@ -50,16 +61,6 @@ export const CONSENT_HEADERS = Object.freeze({
50
61
  'X-Content-Type-Options': 'nosniff',
51
62
  })
52
63
 
53
- /**
54
- * Escapes text for HTML element content and double-quoted attributes.
55
- *
56
- * @param {unknown} value
57
- * @returns {string}
58
- */
59
- export function escapeHtml(value) {
60
- return String(value).replace(/[&<>"']/g, (char) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', '\'': '&#39;' })[char])
61
- }
62
-
63
64
  /**
64
65
  * What the page shows as the place the client sends the user back to: the
65
66
  * host of a web redirect URI, the whole URI for a custom scheme or loopback
@@ -98,8 +99,10 @@ export function renderConsentPage({ clientName, clientId, redirectUri, state, cs
98
99
  <body>
99
100
  <h1>Connect an application to Nera?</h1>
100
101
  <p><span class="client">${escapeHtml(name)}</span> wants to work on your Nera sites with your GitHub account.</p>
101
- <p>After you approve and sign in with GitHub, you are sent back to <span class="host">${escapeHtml(redirectTarget(redirectUri))}</span>.</p>
102
- <p>The name is chosen by the application itself. Approve only if you started this connection from your AI assistant just now and you recognise that address.</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>
103
106
  <form method="post" action="${escapeHtml(action)}">
104
107
  <input type="hidden" name="state" value="${escapeHtml(state)}">
105
108
  <input type="hidden" name="csrf_token" value="${escapeHtml(csrfToken)}">
@@ -135,7 +138,9 @@ export function readConsentCookie(header) {
135
138
  if (typeof header !== 'string') return undefined
136
139
  for (const part of header.split(';')) {
137
140
  const separator = part.indexOf('=')
138
- if (separator !== -1 && part.slice(0, separator).trim() === CONSENT_COOKIE) return part.slice(separator + 1).trim() || undefined
141
+ if (separator !== -1 && part.slice(0, separator).trim() === CONSENT_COOKIE) {
142
+ return part.slice(separator + 1).trim() || undefined
143
+ }
139
144
  }
140
145
  return undefined
141
146
  }
@@ -29,7 +29,8 @@ export function parseKey(input) {
29
29
  if (bytes.length === KEY_BYTES) return bytes
30
30
  }
31
31
  }
32
- throw new Error(`The token key must be ${KEY_BYTES} bytes, written as 64 hex characters or base64 (create one with \`openssl rand -base64 32\`).`)
32
+ throw new Error(`The token key must be ${KEY_BYTES} bytes, written as 64 hex characters or base64 (create one ` +
33
+ 'with `openssl rand -base64 32`).')
33
34
  }
34
35
 
35
36
  /**
@@ -1,4 +1,4 @@
1
- // The GitHub side of the hosted mode's login (L7b, plan D4): the web flow of
1
+ // The GitHub side of the hosted mode's login (L7b): the web flow of
2
2
  // the GitHub App "Nera Static". Our `/authorize` sends the user to GitHub,
3
3
  // GitHub sends them back to our callback with a code, and this client turns
4
4
  // that code into a user token and reads who the user is. GitHub App user tokens
@@ -87,7 +87,9 @@ export function createGitHubClient({
87
87
  accessToken: body.access_token,
88
88
  accessTokenExpiresAt: body.expires_in ? issuedAt + Number(body.expires_in) : undefined,
89
89
  refreshToken: body.refresh_token || undefined,
90
- refreshTokenExpiresAt: body.refresh_token_expires_in ? issuedAt + Number(body.refresh_token_expires_in) : undefined,
90
+ refreshTokenExpiresAt: body.refresh_token_expires_in
91
+ ? issuedAt + Number(body.refresh_token_expires_in)
92
+ : undefined,
91
93
  }
92
94
  }
93
95
 
@@ -149,7 +151,8 @@ export function createGitHubClient({
149
151
  }
150
152
  const body = await response.json().catch(() => ({}))
151
153
  if (!response.ok || body.id === undefined || !body.login) {
152
- throw new GitHubError(`GitHub did not return the signed-in user (HTTP ${response.status}).`, { status: response.status })
154
+ throw new GitHubError('GitHub did not return the signed-in user ' +
155
+ `(HTTP ${response.status}).`, { status: response.status })
153
156
  }
154
157
  return { id: String(body.id), login: body.login }
155
158
  },
package/src/hosted/mcp.js CHANGED
@@ -1,14 +1,14 @@
1
- // The MCP server of the hosted mode (L7b, plan D3/D5). It has no folder to
1
+ // The MCP server of the hosted mode (L7b). It has no folder to
2
2
  // work in: the catalogs of starters, themes and plugins and the docs
3
3
  // resource need none, and the site tools work on the signed-in user's GitHub
4
4
  // repositories through the repository client (src/hosted/repo.js). The app
5
5
  // (src/hosted/app.js) builds one per `/mcp` request, bound to the user its
6
6
  // bearer token belongs to.
7
7
  import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
8
- import pkg from '../../package.json' with { type: 'json' }
9
8
  import { registerCatalogTools } from '../catalog.js'
10
9
  import { registerHostedPrompts } from '../prompts.js'
11
10
  import { registerDocsResources } from '../resources.js'
11
+ import { SERVER_INFO } from '../server-info.js'
12
12
  import { sharedCheckouts } from './checkout.js'
13
13
  import { createRepoClient } from './repo.js'
14
14
  import { registerHostedPublishTools } from './tools/publish.js'
@@ -41,7 +41,7 @@ export function createHostedServer({
41
41
  docsFile,
42
42
  } = {}) {
43
43
  const server = new McpServer(
44
- { name: pkg.name, version: pkg.version },
44
+ { ...SERVER_INFO },
45
45
  {
46
46
  instructions: 'Tools for Nera, a static site generator: a site is Markdown pages rendered through Pug layouts into plain HTML. This hosted server works on your Nera sites in GitHub repositories: list_sites finds them, get_site describes one, read_page and read_file read its files, write_page, write_file and delete_page change them as one commit each on the draft branch nera-draft, which goes live only with publish, validate checks the draft, publish merges the draft into main so the site\'s GitHub Actions workflow builds and deploys it once, and preview shows the live address and how the last deploy went. It also lists the Nera starter kits, themes and plugins. The full documentation is the resource nera://docs/llms-full.txt (online at https://nera.js.org/llms-full.txt).',
47
47
  },
@@ -1,4 +1,4 @@
1
- // The hosted mode's OAuth 2.1 authorization server logic (L7b, plan D1/D4):
1
+ // The hosted mode's OAuth 2.1 authorization server logic (L7b):
2
2
  // the `OAuthServerProvider` the SDK's `mcpAuthRouter` drives, over the token
3
3
  // store. We are the authorization server for claude.ai and ChatGPT (they
4
4
  // register via DCR), and delegate the login itself to GitHub:
@@ -127,7 +127,8 @@ export function createProvider({ store, github, resource, now = Date.now, log =
127
127
  }
128
128
 
129
129
  /** True when a requested resource names a different one than the grant's. */
130
- const otherResource = (requested, granted) => requested !== undefined && granted !== undefined && comparableResource(requested) !== comparableResource(granted)
130
+ const otherResource = (requested, granted) => requested !== undefined && granted !== undefined
131
+ && comparableResource(requested) !== comparableResource(granted)
131
132
 
132
133
  /**
133
134
  * The code's record when it belongs to this client and is still valid.
@@ -168,7 +169,8 @@ export function createProvider({ store, github, resource, now = Date.now, log =
168
169
  */
169
170
  async authorize(client, params, res) {
170
171
  if (params.resource && comparableResource(params.resource) !== comparableResource(hostedResource)) {
171
- throw new InvalidTargetError(`This server issues tokens only for ${hostedResource.href}; the requested resource is another one.`)
172
+ throw new InvalidTargetError(`This server issues tokens only for ${hostedResource.href}; the ` +
173
+ 'requested resource is another one.')
172
174
  }
173
175
  const { state, browserToken } = store.savePending({
174
176
  clientId: client.client_id,
@@ -253,7 +255,9 @@ export function createProvider({ store, github, resource, now = Date.now, log =
253
255
  return
254
256
  }
255
257
  const { clientId, params } = pending
256
- const fail = (error, description) => redirectToClient(res, params.redirectUri, { error, error_description: description, state: params.state })
258
+ const fail = (error, description) => redirectToClient(res, params.redirectUri, {
259
+ error, error_description: description, state: params.state,
260
+ })
257
261
 
258
262
  if (text('error')) {
259
263
  if (text('error') === 'access_denied') fail('access_denied', 'The GitHub sign-in was cancelled.')
@@ -356,8 +360,11 @@ export function createProvider({ store, github, resource, now = Date.now, log =
356
360
  async githubToken(userId) {
357
361
  const user = store.getGithubUser(userId)
358
362
  if (!user) throw new SignInRequiredError('No GitHub sign-in is saved for this user. Sign in again by reconnecting the Nera connector.')
359
- if (user.accessTokenExpiresAt === undefined || user.accessTokenExpiresAt > seconds() + GITHUB_REFRESH_MARGIN) return user.accessToken
360
- if (!user.refreshToken || (user.refreshTokenExpiresAt !== undefined && user.refreshTokenExpiresAt <= seconds())) {
363
+ const fresh = user.accessTokenExpiresAt === undefined
364
+ || user.accessTokenExpiresAt > seconds() + GITHUB_REFRESH_MARGIN
365
+ if (fresh) return user.accessToken
366
+ const refreshExpired = user.refreshTokenExpiresAt !== undefined && user.refreshTokenExpiresAt <= seconds()
367
+ if (!user.refreshToken || refreshExpired) {
361
368
  throw new SignInRequiredError('The GitHub sign-in has expired. Sign in again: remove the Nera connector in your AI assistant and connect it once more.')
362
369
  }
363
370
  if (!refreshing.has(user.id)) {