@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.
@@ -0,0 +1,141 @@
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.
8
+ //
9
+ // The page is bound to the browser that opened it: a random token sits both in
10
+ // an HttpOnly cookie and in the form, and the store keeps only its hash. A
11
+ // forged POST from another site cannot know this browser's token, so its form
12
+ // field never matches the cookie, whatever SameSite does; and a state an
13
+ // attacker approved in their own browser is refused at the GitHub callback,
14
+ // which checks the same cookie.
15
+ import { createHash } from 'node:crypto'
16
+
17
+ /** Where the consent form posts to; step 3 mounts the route here. */
18
+ export const CONSENT_PATH = '/oauth/consent'
19
+
20
+ /** The browser-binding cookie. `__Host-`: Secure, Path=/, no Domain, so no subdomain can set it. */
21
+ export const CONSENT_COOKIE = '__Host-nera-consent'
22
+
23
+ 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; }
25
+ h1 { font-size: 1.4rem; }
26
+ .client { font-weight: 600; overflow-wrap: anywhere; }
27
+ .host { font-family: ui-monospace, monospace; overflow-wrap: anywhere; }
28
+ .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; }
30
+ 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; } }
32
+ `
33
+
34
+ /** The page allows its own inline style block and nothing else; no framing. */
35
+ const CONTENT_SECURITY_POLICY = [
36
+ 'default-src \'none\'',
37
+ `style-src 'sha256-${createHash('sha256').update(STYLE).digest('base64')}'`,
38
+ 'frame-ancestors \'none\'',
39
+ 'base-uri \'none\'',
40
+ // No `form-action`: browsers apply it to the redirect that follows the
41
+ // POST too, and that goes to GitHub or to the client's redirect URI.
42
+ ].join('; ')
43
+
44
+ /** Headers for every response of the consent flow: never cached, never framed. */
45
+ export const CONSENT_HEADERS = Object.freeze({
46
+ 'Cache-Control': 'no-store',
47
+ 'Content-Security-Policy': CONTENT_SECURITY_POLICY,
48
+ 'X-Frame-Options': 'DENY',
49
+ 'Referrer-Policy': 'no-referrer',
50
+ 'X-Content-Type-Options': 'nosniff',
51
+ })
52
+
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
+ * What the page shows as the place the client sends the user back to: the
65
+ * host of a web redirect URI, the whole URI for a custom scheme or loopback
66
+ * app without one.
67
+ *
68
+ * @param {string} redirectUri
69
+ * @returns {string}
70
+ */
71
+ export function redirectTarget(redirectUri) {
72
+ const url = new URL(redirectUri)
73
+ return url.host || url.href
74
+ }
75
+
76
+ /**
77
+ * The consent page.
78
+ *
79
+ * @param {object} page
80
+ * @param {string} [page.clientName] the client's self-declared `client_name`
81
+ * @param {string} page.clientId
82
+ * @param {string} page.redirectUri
83
+ * @param {string} page.state our pending state
84
+ * @param {string} page.csrfToken the browser-binding token, also in the cookie
85
+ * @param {string} [page.action] where the form posts
86
+ * @returns {string} the HTML
87
+ */
88
+ export function renderConsentPage({ clientName, clientId, redirectUri, state, csrfToken, action = CONSENT_PATH }) {
89
+ const name = clientName?.trim() ? clientName.trim() : `An application without a name (${clientId})`
90
+ return `<!doctype html>
91
+ <html lang="en">
92
+ <head>
93
+ <meta charset="utf-8">
94
+ <meta name="viewport" content="width=device-width, initial-scale=1">
95
+ <title>Connect to Nera</title>
96
+ <style>${STYLE}</style>
97
+ </head>
98
+ <body>
99
+ <h1>Connect an application to Nera?</h1>
100
+ <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>
103
+ <form method="post" action="${escapeHtml(action)}">
104
+ <input type="hidden" name="state" value="${escapeHtml(state)}">
105
+ <input type="hidden" name="csrf_token" value="${escapeHtml(csrfToken)}">
106
+ <div class="actions">
107
+ <button type="submit" name="decision" value="approve">Approve</button>
108
+ <button type="submit" name="decision" value="deny">Deny</button>
109
+ </div>
110
+ </form>
111
+ </body>
112
+ </html>
113
+ `
114
+ }
115
+
116
+ /**
117
+ * The `Set-Cookie` value for the browser-binding token. `SameSite=Lax`, not
118
+ * `Strict`: the cookie must come along on GitHub's top-level redirect back to
119
+ * our callback. The protection does not rest on SameSite, though — see above.
120
+ *
121
+ * @param {string} token
122
+ * @param {number} maxAge seconds; 0 deletes the cookie
123
+ */
124
+ export function consentCookie(token, maxAge) {
125
+ return `${CONSENT_COOKIE}=${token}; Max-Age=${maxAge}; Path=/; Secure; HttpOnly; SameSite=Lax`
126
+ }
127
+
128
+ /**
129
+ * Reads the browser-binding token from a `Cookie` request header.
130
+ *
131
+ * @param {string|undefined} header
132
+ * @returns {string|undefined}
133
+ */
134
+ export function readConsentCookie(header) {
135
+ if (typeof header !== 'string') return undefined
136
+ for (const part of header.split(';')) {
137
+ const separator = part.indexOf('=')
138
+ if (separator !== -1 && part.slice(0, separator).trim() === CONSENT_COOKIE) return part.slice(separator + 1).trim() || undefined
139
+ }
140
+ return undefined
141
+ }
@@ -0,0 +1,90 @@
1
+ // The hosted mode's secrets (L7b): our own tokens are random and stored only as
2
+ // SHA-256 hashes, so a leaked database cannot be replayed; GitHub's user tokens
3
+ // must be read back to call the API, so they are encrypted with AES-256-GCM
4
+ // under the operator's key (`NERA_MCP_TOKEN_KEY`). Nothing here logs a value.
5
+ import { createCipheriv, createDecipheriv, createHash, randomBytes } from 'node:crypto'
6
+
7
+ const ALGORITHM = 'aes-256-gcm'
8
+ const KEY_BYTES = 32
9
+ const IV_BYTES = 12
10
+ const TAG_BYTES = 16
11
+ /** The prefix of every encrypted value, so a later format can be told apart. */
12
+ const VERSION = 'v1'
13
+
14
+ /**
15
+ * Turns the operator's key into the 32 bytes AES-256 needs. Accepted: 64 hex
16
+ * characters or the base64 of 32 bytes (`openssl rand -base64 32`).
17
+ *
18
+ * @param {string|Buffer} input
19
+ * @returns {Buffer}
20
+ */
21
+ export function parseKey(input) {
22
+ if (Buffer.isBuffer(input)) {
23
+ if (input.length === KEY_BYTES) return Buffer.from(input)
24
+ } else if (typeof input === 'string') {
25
+ const text = input.trim()
26
+ if (/^[0-9a-fA-F]{64}$/.test(text)) return Buffer.from(text, 'hex')
27
+ if (/^[A-Za-z0-9+/_-]{43}=?$/.test(text)) {
28
+ const bytes = Buffer.from(text, 'base64')
29
+ if (bytes.length === KEY_BYTES) return bytes
30
+ }
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\`).`)
33
+ }
34
+
35
+ /**
36
+ * Encrypts a string with a fresh random IV per call.
37
+ *
38
+ * @param {Buffer} key 32 bytes, from `parseKey`
39
+ * @param {string} plaintext
40
+ * @returns {string} `v1.<iv>.<tag>.<ciphertext>`, each part base64url
41
+ */
42
+ export function encrypt(key, plaintext) {
43
+ const iv = randomBytes(IV_BYTES)
44
+ const cipher = createCipheriv(ALGORITHM, key, iv)
45
+ const ciphertext = Buffer.concat([cipher.update(plaintext, 'utf8'), cipher.final()])
46
+ const tag = cipher.getAuthTag()
47
+ return [VERSION, iv, tag, ciphertext].map((part) => (typeof part === 'string' ? part : part.toString('base64url'))).join('.')
48
+ }
49
+
50
+ /**
51
+ * Decrypts what `encrypt` wrote. Throws when the key is wrong or the value was
52
+ * altered (the GCM auth tag does not match), never returns garbage.
53
+ *
54
+ * @param {Buffer} key
55
+ * @param {string} blob
56
+ * @returns {string}
57
+ */
58
+ export function decrypt(key, blob) {
59
+ const parts = String(blob).split('.')
60
+ if (parts.length !== 4 || parts[0] !== VERSION) throw new Error('Not an encrypted value of a known format.')
61
+ const [iv, tag, ciphertext] = parts.slice(1).map((part) => Buffer.from(part, 'base64url'))
62
+ if (iv.length !== IV_BYTES || tag.length !== TAG_BYTES) throw new Error('Not an encrypted value of a known format.')
63
+ const decipher = createDecipheriv(ALGORITHM, key, iv, { authTagLength: TAG_BYTES })
64
+ decipher.setAuthTag(tag)
65
+ try {
66
+ return Buffer.concat([decipher.update(ciphertext), decipher.final()]).toString('utf8')
67
+ } catch {
68
+ throw new Error('Cannot decrypt a stored token: the token key differs from the one it was written with, or the value was altered.')
69
+ }
70
+ }
71
+
72
+ /**
73
+ * The SHA-256 of a token, hex: how our tokens are stored and looked up.
74
+ *
75
+ * @param {string} token
76
+ * @returns {string}
77
+ */
78
+ export function hashToken(token) {
79
+ return createHash('sha256').update(String(token), 'utf8').digest('hex')
80
+ }
81
+
82
+ /**
83
+ * A random, URL-safe token.
84
+ *
85
+ * @param {number} [bytes] entropy in bytes (default 32 = 256 bits)
86
+ * @returns {string}
87
+ */
88
+ export function randomToken(bytes = 32) {
89
+ return randomBytes(bytes).toString('base64url')
90
+ }
@@ -0,0 +1,157 @@
1
+ // The GitHub side of the hosted mode's login (L7b, plan D4): the web flow of
2
+ // the GitHub App "Nera Static". Our `/authorize` sends the user to GitHub,
3
+ // GitHub sends them back to our callback with a code, and this client turns
4
+ // that code into a user token and reads who the user is. GitHub App user tokens
5
+ // expire (8 h) and come with a refresh token (6 months) that GitHub rotates on
6
+ // every use. Every call goes through the injected `fetch`, so tests never touch
7
+ // the network; no token ever appears in an error message.
8
+
9
+ const USER_AGENT = 'nera-mcp'
10
+ const API_VERSION = '2022-11-28'
11
+
12
+ /** A failed call to GitHub; `code` is GitHub's own error code when it sent one. */
13
+ export class GitHubError extends Error {
14
+ /**
15
+ * @param {string} message
16
+ * @param {{code?: string, status?: number}} [details]
17
+ */
18
+ constructor(message, { code, status } = {}) {
19
+ super(message)
20
+ this.name = 'GitHubError'
21
+ this.code = code
22
+ this.status = status
23
+ }
24
+ }
25
+
26
+ /**
27
+ * @typedef {object} GitHubTokens a user token as we keep it; times in seconds since the epoch
28
+ * @property {string} accessToken
29
+ * @property {number} [accessTokenExpiresAt] absent when the App issues non-expiring tokens
30
+ * @property {string} [refreshToken]
31
+ * @property {number} [refreshTokenExpiresAt]
32
+ */
33
+
34
+ /**
35
+ * Creates the GitHub web-flow client.
36
+ *
37
+ * @param {object} options
38
+ * @param {string} options.clientId the GitHub App's client ID
39
+ * @param {string} options.clientSecret the GitHub App's client secret
40
+ * @param {string} options.redirectUri our callback, as registered in the App
41
+ * @param {typeof fetch} [options.fetch]
42
+ * @param {string} [options.webUrl] `https://github.com`, overridable for tests
43
+ * @param {string} [options.apiUrl] `https://api.github.com`, overridable for tests
44
+ * @param {() => number} [options.now] the clock in milliseconds
45
+ */
46
+ export function createGitHubClient({
47
+ clientId,
48
+ clientSecret,
49
+ redirectUri,
50
+ fetch = globalThis.fetch,
51
+ webUrl = 'https://github.com',
52
+ apiUrl = 'https://api.github.com',
53
+ now = Date.now,
54
+ }) {
55
+ if (!clientId || !clientSecret || !redirectUri) {
56
+ throw new Error('The GitHub client needs the App\'s client ID, its client secret and our callback URL.')
57
+ }
58
+
59
+ const seconds = () => Math.floor(now() / 1000)
60
+
61
+ /**
62
+ * POSTs to GitHub's token endpoint. GitHub answers errors there with
63
+ * HTTP 200 and an `error` field, so both cases are checked.
64
+ *
65
+ * @param {Record<string, string>} fields
66
+ * @returns {Promise<GitHubTokens>}
67
+ */
68
+ async function tokenRequest(fields) {
69
+ const issuedAt = seconds()
70
+ let response
71
+ try {
72
+ response = await fetch(new URL('/login/oauth/access_token', webUrl), {
73
+ method: 'POST',
74
+ headers: { Accept: 'application/json', 'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': USER_AGENT },
75
+ body: new URLSearchParams({ client_id: clientId, client_secret: clientSecret, ...fields }),
76
+ })
77
+ } catch (error) {
78
+ throw new GitHubError(`Cannot reach GitHub: ${error.message}`)
79
+ }
80
+ const body = await response.json().catch(() => ({}))
81
+ if (!response.ok || body.error || !body.access_token) {
82
+ const code = body.error || undefined
83
+ const reason = body.error_description || code || `HTTP ${response.status}`
84
+ throw new GitHubError(`GitHub refused the token request: ${reason}`, { code, status: response.status })
85
+ }
86
+ return {
87
+ accessToken: body.access_token,
88
+ accessTokenExpiresAt: body.expires_in ? issuedAt + Number(body.expires_in) : undefined,
89
+ refreshToken: body.refresh_token || undefined,
90
+ refreshTokenExpiresAt: body.refresh_token_expires_in ? issuedAt + Number(body.refresh_token_expires_in) : undefined,
91
+ }
92
+ }
93
+
94
+ return {
95
+ /**
96
+ * Where to send the user to sign in.
97
+ *
98
+ * @param {string} state our own state, which GitHub hands back to the callback
99
+ * @returns {string}
100
+ */
101
+ authorizeUrl(state) {
102
+ const url = new URL('/login/oauth/authorize', webUrl)
103
+ url.searchParams.set('client_id', clientId)
104
+ url.searchParams.set('redirect_uri', redirectUri)
105
+ url.searchParams.set('state', state)
106
+ return url.href
107
+ },
108
+
109
+ /**
110
+ * Exchanges the code GitHub sent to our callback for a user token.
111
+ *
112
+ * @param {string} code
113
+ * @returns {Promise<GitHubTokens>}
114
+ */
115
+ exchangeCode(code) {
116
+ return tokenRequest({ code, redirect_uri: redirectUri })
117
+ },
118
+
119
+ /**
120
+ * Trades a refresh token for a new user token (and a new refresh token:
121
+ * GitHub invalidates the old one).
122
+ *
123
+ * @param {string} refreshToken
124
+ * @returns {Promise<GitHubTokens>}
125
+ */
126
+ refresh(refreshToken) {
127
+ return tokenRequest({ grant_type: 'refresh_token', refresh_token: refreshToken })
128
+ },
129
+
130
+ /**
131
+ * Reads the signed-in user.
132
+ *
133
+ * @param {string} accessToken
134
+ * @returns {Promise<{id: string, login: string}>}
135
+ */
136
+ async getUser(accessToken) {
137
+ let response
138
+ try {
139
+ response = await fetch(new URL('/user', apiUrl), {
140
+ headers: {
141
+ Accept: 'application/vnd.github+json',
142
+ Authorization: `Bearer ${accessToken}`,
143
+ 'User-Agent': USER_AGENT,
144
+ 'X-GitHub-Api-Version': API_VERSION,
145
+ },
146
+ })
147
+ } catch (error) {
148
+ throw new GitHubError(`Cannot reach GitHub: ${error.message}`)
149
+ }
150
+ const body = await response.json().catch(() => ({}))
151
+ 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 })
153
+ }
154
+ return { id: String(body.id), login: body.login }
155
+ },
156
+ }
157
+ }
@@ -0,0 +1,62 @@
1
+ // The MCP server of the hosted mode (L7b, plan D3/D5). It has no folder to
2
+ // work in: the catalogs of starters, themes and plugins and the docs
3
+ // resource need none, and the site tools work on the signed-in user's GitHub
4
+ // repositories through the repository client (src/hosted/repo.js). The app
5
+ // (src/hosted/app.js) builds one per `/mcp` request, bound to the user its
6
+ // bearer token belongs to.
7
+ import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js'
8
+ import pkg from '../../package.json' with { type: 'json' }
9
+ import { registerCatalogTools } from '../catalog.js'
10
+ import { registerHostedPrompts } from '../prompts.js'
11
+ import { registerDocsResources } from '../resources.js'
12
+ import { sharedCheckouts } from './checkout.js'
13
+ import { createRepoClient } from './repo.js'
14
+ import { registerHostedPublishTools } from './tools/publish.js'
15
+ import { registerHostedReadTools } from './tools/read.js'
16
+ import { registerHostedValidateTool } from './tools/validate.js'
17
+ import { registerHostedWriteTools } from './tools/write.js'
18
+
19
+ /**
20
+ * Builds the hosted MCP server, with no transport attached. Without a user
21
+ * (`userId` and `githubToken`) it offers the catalog tools and the docs and
22
+ * catalog resources only; with one also the site tools and the hosted prompts.
23
+ *
24
+ * @param {object} [options]
25
+ * @param {typeof fetch} [options.fetch] fetches the npm registry catalogs (injected so tests stay offline)
26
+ * @param {string} [options.userId] the signed-in user, from the bearer token's `extra`
27
+ * @param {(userId: string) => Promise<string>} [options.githubToken] the user's GitHub token (`provider.githubToken`); throws `SignInRequiredError` when the sign-in is gone
28
+ * @param {(token: string) => ReturnType<typeof createRepoClient>} [options.createRepo] builds the repository client (injected so tests talk to a fake GitHub)
29
+ * @param {ReturnType<typeof import('./checkout.js').createCheckouts>} [options.checkouts] the temporary checkouts of `validate`; the process-wide ones by default, since this server lives for one request only
30
+ * @param {(ms: number) => Promise<void>} [options.sleep] the pause between `publish`'s lookups of the deploy run (injected so tests do not wait)
31
+ * @param {string} [options.docsFile] the docs the `nera://docs/llms-full.txt` resource serves; the bundled file by default
32
+ * @returns {McpServer}
33
+ */
34
+ export function createHostedServer({
35
+ fetch = globalThis.fetch,
36
+ userId,
37
+ githubToken,
38
+ createRepo = (token) => createRepoClient({ token }),
39
+ checkouts = sharedCheckouts,
40
+ sleep,
41
+ docsFile,
42
+ } = {}) {
43
+ const server = new McpServer(
44
+ { name: pkg.name, version: pkg.version },
45
+ {
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
+ },
48
+ )
49
+ registerCatalogTools(server, { fetch })
50
+ registerDocsResources(server, { fetch, docsFile })
51
+ if (userId && githubToken) {
52
+ // The token is fetched per tool call, so a refreshed one is used and a
53
+ // lost sign-in becomes that call's error, not the request's.
54
+ const repos = async () => createRepo(await githubToken(userId))
55
+ registerHostedReadTools(server, { repos })
56
+ registerHostedWriteTools(server, { repos })
57
+ registerHostedValidateTool(server, { repos, userId, checkouts })
58
+ registerHostedPublishTools(server, { repos, sleep })
59
+ registerHostedPrompts(server)
60
+ }
61
+ return server
62
+ }