@nera-static/mcp 1.3.0 → 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.
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nera",
3
- "version": "1.3.0",
3
+ "version": "1.4.0",
4
4
  "description": "Create, edit, build, validate, preview and publish websites made with Nera, a static site generator: the Nera skill plus the Nera MCP server, which works only inside the sites folder you pick on enable.",
5
5
  "author": {
6
6
  "name": "Michael Becker"
@@ -29,7 +29,7 @@
29
29
  "command": "npx",
30
30
  "args": [
31
31
  "-y",
32
- "@nera-static/mcp@1.3.0",
32
+ "@nera-static/mcp@1.4.0",
33
33
  "--root",
34
34
  "${user_config.root}"
35
35
  ]
package/CHANGELOG.md CHANGED
@@ -5,6 +5,34 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [1.4.0] - 2026-11-23
9
+
10
+ ### Added
11
+
12
+ - A hosted mode, `nera-mcp --http [--port] [--host] [--trust-proxy]`, for MCP clients that cannot start a local process (claude.ai, ChatGPT). It is an OAuth 2.1 authorization server with protected-resource metadata (RFC 9728), authorization-server metadata (RFC 8414, S256 PKCE only), dynamic client registration (RFC 7591) and rotating refresh tokens (an authorization code or refresh token sent a second time revokes every token of that sign-in and logs one line naming the client id and grant id, never a token), and token revocation (RFC 7009: revoking a refresh token revokes every token of its sign-in, revoking an access token only that token), in front of a stateless Streamable HTTP endpoint at `/mcp` that requires a bearer token issued for it (an `/authorize` request without `resource` is bound to `/mcp`, one naming another resource is refused with `invalid_target`). The sign-in is delegated to a GitHub App, after a consent page that shows the user which client asks. Besides the catalog tools (`list_starters`, `list_themes`, `list_plugins`), the hosted server offers the site tools below, acting as the signed-in GitHub user.
13
+ - Hosted site tools that work on the user's GitHub repositories, the repository being the working copy: `list_sites` (the repositories the GitHub App reaches with the user's token whose `package.json` depends on `@nera-static/nera`; a site is `owner/name`, and every tool refuses a repository outside that list), `get_site`, `read_page` and `read_file`. Reads come from the draft branch `nera-draft` while it exists, else from `main`. Paths are relative to the repository, and `..`, absolute paths, backslashes, symbolic links, `.git` and files that can hold secrets (`.env*`, `.npmrc`) are refused.
14
+ - Hosted `write_page`, `write_file` and `delete_page`: each call makes exactly one commit, with the message the model passes (a required `message` input), on the draft branch `nera-draft`, which the first write creates from `main`. `write_page` keeps the local rules (frontmatter must contain `layout`, comments of unchanged keys are kept); `write_file` refuses `node_modules` and the output folder, and sends pages to `write_page`. A commit that loses a race against another push is made once more on the new head, then reported as an error.
15
+ - Hosted `validate` on a temporary checkout of the draft (or of `main`): the repository's tarball (at most 50 MB, at most 200 MB unpacked) is unpacked with the system `tar`, every symbolic link is deleted, a configuration, a page `layout` or a Pug `include`/`extends` that leaves the checkout is refused, and the records come back exactly as `validate()` of `@nera-static/nera` returns them. No npm runs and no code of the site or its theme is executed: when `config/app.yaml` names a theme package, only that package is downloaded from `https://registry.npmjs.org/` (the version pinned in the lockfile, else the highest match of the `package.json` range or tag; no dependencies, no redirects, at most 20 MB). The checkout is deleted afterwards, whatever happened, and each user runs one at a time. There is no hosted `build`: it would run the site's local plugins on the server; the site's own GitHub Actions run builds it.
16
+ - Hosted `publish`: merges `nera-draft` into `main` in one push (a fast-forward, or a merge commit with an optional `message` when `main` moved) and deletes the draft, so the site's deploy workflow (`.github/workflows/deploy.yml`, run on pushes to `main` only) builds and deploys once per batch of changes, which spares Netlify's build credits. It returns the merge commit, the deploy run of that push (status, conclusion, address) and the address the site is served at (GitHub Pages, else `origin` in `config/app.yaml`). A merge conflict is an error that says to merge the draft on GitHub. Without unpublished commits nothing is pushed, so no deploy is started, and the latest run is reported.
17
+ - Hosted `preview`: the address the site is served at, the latest deploy run and the number of unpublished commits on `nera-draft`.
18
+ - A `publish` whose changes another call put live first (it finds `main` already at the draft, or nothing left to merge) reports `published: false` and says so, instead of a push it did not make.
19
+ - A hosted write keeps an existing file's git mode (an executable script stays executable); a new file is a regular file.
20
+ - The hosted server offers the resources `nera://docs/llms-full.txt` and `nera://catalog/{starters,themes,plugins}`, the same as the stdio mode, and with a signed-in user the prompts `add_page` and `put_site_online`, worded for write_page → validate → publish. A site's `AGENTS.md` is read with `read_file` there.
21
+ - No tool result, error message or log line carries the user's GitHub token.
22
+ - The hosted mode is configured by `NERA_MCP_ISSUER`, `NERA_MCP_DB`, `NERA_MCP_TOKEN_KEY`, `NERA_MCP_GITHUB_CLIENT_ID` and `NERA_MCP_GITHUB_CLIENT_SECRET`, and stops with exit code 1 and a message naming what is missing or wrong (never a value). It keeps its state in one SQLite file (`node:sqlite`, so it needs Node 22.13 or later; the stdio mode stays on 22.12): our tokens only as SHA-256 hashes, GitHub's tokens AES-256-GCM-encrypted. Its logs go to stderr and never carry a token, the key or the client secret; `SIGTERM` lets running requests finish, closes the database and exits 0.
23
+ - `express` as a dependency, for the SDK's OAuth router the hosted mode is built on; the stdio mode does not load it.
24
+ - `semver` as a dependency, to pick the theme version the hosted `validate` downloads.
25
+
26
+ ### Changed
27
+
28
+ - The stdio mode refuses `--port`, `--host` and `--trust-proxy` without `--http`, and the hosted mode refuses `--root`, each with a message saying which mode the option belongs to. `--root` stays required for the stdio mode, which is otherwise unchanged.
29
+
30
+ ## [1.3.1] - 2026-11-21
31
+
32
+ ### Changed
33
+
34
+ - `preview` no longer promises that the page in the browser updates by itself: its description and its result text say the site rebuilds after every change and that the user may need to reload the page to see it. Its inputs and result shape are unchanged.
35
+
8
36
  ## [1.3.0] - 2026-11-19
9
37
 
10
38
  ### Changed
package/README.md CHANGED
@@ -140,9 +140,66 @@ A **site** is a folder under the root (or the root itself) whose `package.json`
140
140
 
141
141
  ## Compatibility
142
142
 
143
- - Node.js 22.12 or later
143
+ - Node.js 22.12 or later (22.13 or later for the hosted mode, `--http`)
144
144
  - Brings `@nera-static/nera` 1.27.0 for sites that have none installed. A site with its own CLI installed runs that one: `build` needs 1.9.0 or later (`--json`), `publish` 1.27.0 or later for GitHub Pages and Netlify alike (its sign-in events), and refuses an older one. `npm update` in the site brings it up to date.
145
145
 
146
+ ## Hosted mode (for operators)
147
+
148
+ `nera-mcp --http` runs the server for MCP clients that cannot start a local process, such as claude.ai and ChatGPT. This section is for whoever runs such a server; there is no public Nera service to connect to yet. The hosted server has no folder to work in, so `--root` is refused together with `--http`: the signed-in user's GitHub repository is the working copy.
149
+
150
+ ### Hosted tools
151
+
152
+ Besides the catalog tools (`list_starters`, `list_themes`, `list_plugins`), a signed-in user gets the site tools, acting as that GitHub user. A **site** is a repository as `owner/name` that the GitHub App reaches with the user's token and whose `package.json` depends on `@nera-static/nera`; any other repository is refused. Paths are relative to the repository root; `..`, absolute paths, backslashes, symbolic links, `.git` and files that can hold secrets (`.env*`, `.npmrc`) are refused.
153
+
154
+ | Tool | Does |
155
+ | --- | --- |
156
+ | `list_sites`, `get_site` | The user's Nera sites; one site's configuration, folders, theme, plugins, pages and unpublished draft commits |
157
+ | `read_page`, `read_file` | A page with its frontmatter, or a text file, from `nera-draft` while it exists, else from `main` |
158
+ | `write_page`, `write_file`, `delete_page` | One commit per call, with the `message` the model passes, on the draft branch `nera-draft` (created from `main` by the first write) |
159
+ | `validate` | The validator of `nera validate` on a temporary checkout of the draft, as `{ file, line, severity, rule, message }` records |
160
+ | `publish` | Merges `nera-draft` into `main` in one push and deletes it; returns the merge commit, the deploy run and the site's address |
161
+ | `preview` | The site's address, its latest deploy run and the number of unpublished draft commits |
162
+
163
+ Changes collect on `nera-draft` and deploy only with `publish`. The site's deploy workflow (`.github/workflows/deploy.yml`, as `nera publish` sets it up) runs on pushes to `main` only, so a batch of changes is built and deployed once, which matters for Netlify's build credits. `publish` without unpublished commits pushes nothing, and one whose changes another call put live first reports `published: false`. A merge conflict (someone changed `main` in the meantime) is reported with the hint to merge the draft on GitHub. The site's address comes from GitHub Pages, else from `origin` in `config/app.yaml`. A write keeps an existing file's git mode, so an executable script stays executable.
164
+
165
+ The hosted server also offers the resources `nera://docs/llms-full.txt` and `nera://catalog/{starters,themes,plugins}`, and the prompts `add_page` and `put_site_online`, worded for write_page → validate → publish. A site's `AGENTS.md` is read with `read_file`; the `new_*` prompts need `create_site`, which the hosted mode does not have.
166
+
167
+ There is no hosted `build`: it would run the site's local plugins, which is user code, on the server. The site's own GitHub Actions run builds it. `validate` runs no code of the site either: it downloads the repository's tarball (at most 50 MB, at most 200 MB unpacked), unpacks it with the system `tar` into a temporary folder, deletes every symbolic link, refuses a configuration (`folders.*`, `theme`), a page `layout` or a Pug `include`/`extends` that leaves the checkout, and runs no npm. When `config/app.yaml` names a theme package, only that package is downloaded from `https://registry.npmjs.org/` (the version the lockfile pins, else the highest match of the `package.json` range or tag; no dependencies, no redirects, at most 20 MB). The checkout is deleted afterwards, whatever happened, and each user runs one checkout at a time (per server process). Needs `tar` on the server's PATH.
168
+
169
+ ### Running it
170
+
171
+ It is an OAuth 2.1 authorization server in front of a Streamable HTTP endpoint at `/mcp`. Clients register themselves (dynamic client registration) and sign in with PKCE; the sign-in itself is delegated to a GitHub App, so a user only ever logs in at GitHub.
172
+
173
+ | Path | What |
174
+ |---|---|
175
+ | `/.well-known/oauth-protected-resource/mcp` | protected-resource metadata (RFC 9728) |
176
+ | `/.well-known/oauth-authorization-server` | authorization-server metadata (RFC 8414), S256 only |
177
+ | `/register`, `/authorize`, `/token`, `/revoke` | registration (RFC 7591) and the OAuth endpoints |
178
+ | `/oauth/consent` | where the consent page posts: `/authorize` first shows the user which client asks, and only an approval goes on to GitHub |
179
+ | `/oauth/github/callback` | GitHub's redirect back to the server |
180
+ | `/mcp` | the MCP endpoint; requires a bearer token, answers `401` with a `WWW-Authenticate` pointing at the metadata otherwise |
181
+
182
+ Requirements: Node.js **22.13 or later** (for `node:sqlite`; the stdio mode stays on 22.12), a TLS proxy in front (nginx, Caddy) that serves the issuer over HTTPS, and a GitHub App with a client secret, its callback URL set to `<issuer>/oauth/github/callback` (expiring user tokens are recommended; the server refreshes them).
183
+
184
+ The configuration comes from the environment, so no secret shows up in the process list:
185
+
186
+ | Variable | What |
187
+ |---|---|
188
+ | `NERA_MCP_ISSUER` | the public origin, e.g. `https://mcp.example.org` (HTTPS; plain HTTP only for `localhost`) |
189
+ | `NERA_MCP_DB` | the SQLite file for clients and tokens, created with mode `0600`; back it up |
190
+ | `NERA_MCP_TOKEN_KEY` | 32 bytes as base64 or hex that encrypt the GitHub tokens: `openssl rand -base64 32`. Losing it means every user signs in again |
191
+ | `NERA_MCP_GITHUB_CLIENT_ID` | the GitHub App's client ID |
192
+ | `NERA_MCP_GITHUB_CLIENT_SECRET` | the GitHub App's client secret |
193
+
194
+ ```bash
195
+ nera-mcp --http --port 8080 --host 127.0.0.1 --trust-proxy loopback
196
+ ```
197
+
198
+ - `--port` (default `8080`, `0` picks a free one) and `--host` (default `127.0.0.1`, so only the proxy on the same machine reaches it).
199
+ - `--trust-proxy` tells the server which proxies to believe for the client's address, which the rate limits on the OAuth endpoints count by: a number of hops (`1`) or addresses (`loopback`, `10.0.0.0/8`). Without it no proxy is trusted, and behind a proxy every client shares one limit.
200
+ - A missing variable, a key of the wrong size or a taken port stop the server with exit code 1 and a message on stderr. `SIGTERM` lets running requests finish (up to 10 seconds), closes the database and exits 0.
201
+ - Logs go to stderr and never contain a token, the key or the client secret. Our own access and refresh tokens are stored only as SHA-256 hashes (access tokens live 1 hour, refresh tokens 30 days and rotate on every use). An authorization code or refresh token sent a second time is refused and revokes every token of that sign-in, so the client has to connect again; the log gets one line naming the client id and the sign-in's grant id, never a token. A client revoking its refresh token at `/revoke` signs out that sign-in entirely (its access tokens stop working too); revoking an access token removes only that token. GitHub's tokens are stored AES-256-GCM-encrypted.
202
+
146
203
  ## License
147
204
 
148
205
  MIT
package/bin/nera-mcp.js CHANGED
@@ -1,24 +1,48 @@
1
1
  #!/usr/bin/env node
2
- // The stdio entry of @nera-static/mcp: `npx -y @nera-static/mcp --root <folder>`.
3
- // stdout carries the MCP protocol (JSON-RPC) and nothing else, so every
4
- // console method that would write there is routed to stderr before any other
5
- // module loads, and the server is imported only after that.
2
+ // The entry of @nera-static/mcp, in one of two modes:
3
+ //
4
+ // nera-mcp --root <folder> stdio, started by a local MCP client (L7a)
5
+ // nera-mcp --http the hosted server, behind a TLS proxy (L7b)
6
+ //
7
+ // In stdio mode stdout carries the MCP protocol (JSON-RPC) and nothing else,
8
+ // so every console method that would write there is routed to stderr before
9
+ // any other module loads, and the server is imported only after that. The
10
+ // hosted mode logs to stderr the same way.
6
11
  import { parseArgs } from 'node:util'
7
12
 
8
13
  for (const method of ['log', 'info', 'debug', 'dir', 'dirxml', 'table']) {
9
14
  console[method] = console.error
10
15
  }
11
16
 
17
+ /** Where the hosted mode listens unless told otherwise: only this machine, for the proxy in front. */
18
+ const DEFAULT_HOST = '127.0.0.1'
19
+ const DEFAULT_PORT = 8080
20
+
21
+ /** How long the hosted mode lets running requests finish after SIGTERM before it cuts them off. */
22
+ const SHUTDOWN_GRACE_MS = 10000
23
+
12
24
  const USAGE = `Usage: nera-mcp --root <folder>
25
+ nera-mcp --http [--port <port>] [--host <address>] [--trust-proxy <value>]
26
+
27
+ With --root, runs the Nera MCP server over stdio. An MCP client (Claude Code,
28
+ Claude Desktop, Cursor, Codex, …) starts it; it lets the assistant create, edit,
29
+ build, validate, preview and publish Nera sites inside <folder> and nowhere else.
13
30
 
14
- Runs the Nera MCP server over stdio. An MCP client (Claude Code, Claude Desktop,
15
- Cursor, Codex, …) starts it; it lets the assistant create, edit, build, validate,
16
- preview and publish Nera sites inside <folder> and nowhere else.
31
+ With --http, runs the hosted server: an OAuth 2.1 authorization server that
32
+ signs users in through a GitHub App, in front of a Streamable HTTP endpoint at
33
+ /mcp. It is meant to run behind a TLS proxy and is configured by environment
34
+ variables (NERA_MCP_ISSUER, NERA_MCP_DB, NERA_MCP_TOKEN_KEY,
35
+ NERA_MCP_GITHUB_CLIENT_ID, NERA_MCP_GITHUB_CLIENT_SECRET). Needs Node 22.13+.
17
36
 
18
37
  Options:
19
- --root <folder> the folder the server may work in (required, must exist)
20
- --help show this help
21
- --version show the version`
38
+ --root <folder> stdio: the folder the server may work in (required, must exist)
39
+ --http run the hosted server instead of stdio
40
+ --port <port> hosted: the port to listen on (default ${DEFAULT_PORT}, 0 picks a free one)
41
+ --host <address> hosted: the address to listen on (default ${DEFAULT_HOST})
42
+ --trust-proxy <value> hosted: the proxies to trust for the client's address, a number
43
+ of hops (1) or addresses (loopback); default none
44
+ --help show this help
45
+ --version show the version`
22
46
 
23
47
  /**
24
48
  * Prints `message` to stderr and exits with code 1.
@@ -36,6 +60,10 @@ try {
36
60
  ({ values: options } = parseArgs({
37
61
  options: {
38
62
  root: { type: 'string' },
63
+ http: { type: 'boolean' },
64
+ port: { type: 'string' },
65
+ host: { type: 'string' },
66
+ 'trust-proxy': { type: 'string' },
39
67
  help: { type: 'boolean' },
40
68
  version: { type: 'boolean' },
41
69
  },
@@ -59,66 +87,180 @@ if (options.version) {
59
87
  process.exit(0)
60
88
  }
61
89
 
62
- if (!options.root) {
63
- fail(`--root <folder> is required: the folder the server may work in.\n\n${USAGE}`)
64
- }
90
+ const HTTP_ONLY = ['port', 'host', 'trust-proxy']
65
91
 
66
- // the server and the Nera packages it loads come last: only the server needs them
67
- const [{ StdioServerTransport }, { createServer }, { createProcesses }, { PathError }, { setupRuntime }] = await Promise.all([
68
- import('@modelcontextprotocol/sdk/server/stdio.js'),
69
- import('../src/server.js'),
70
- import('../src/processes.js'),
71
- import('../src/paths.js'),
72
- import('../src/runtime.js'),
73
- ])
74
-
75
- // the Desktop extension sets NERA_MCP_RUNTIME=bundled: its Node has no npm and
76
- // nothing on the PATH, so children get a shim folder for node, npm and npx;
77
- // the folder goes when this process exits, however it exits
78
- const runtime = setupRuntime()
79
- if (runtime) {
80
- process.on('exit', runtime.remove)
81
- console.error(`nera-mcp: bundled runtime, node${runtime.npm ? ', npm and npx' : ' (no npm found)'} for children in ${runtime.dir}`)
92
+ if (options.http) {
93
+ if (options.root !== undefined) {
94
+ fail(`--root is for the stdio mode only: the hosted mode (--http) has no folder to work in.\n\n${USAGE}`)
95
+ }
96
+ await serveHttp()
97
+ } else {
98
+ const stray = HTTP_ONLY.filter((name) => options[name] !== undefined)
99
+ if (stray.length > 0) {
100
+ fail(`${stray.map((name) => `--${name}`).join(', ')} only work together with --http.\n\n${USAGE}`)
101
+ }
102
+ if (!options.root) {
103
+ fail(`--root <folder> is required: the folder the server may work in.\n\n${USAGE}`)
104
+ }
105
+ await serveStdio()
82
106
  }
83
107
 
84
- const processes = createProcesses()
85
- let server
86
- try {
87
- server = await createServer({ root: options.root, processes })
88
- } catch (error) {
89
- if (error instanceof PathError) fail(error.message)
90
- throw error
91
- }
108
+ /** The local mode: one server for one client, over stdin and stdout. */
109
+ async function serveStdio() {
110
+ // the server and the Nera packages it loads come last: only the server needs them
111
+ const [{ StdioServerTransport }, { createServer }, { createProcesses }, { PathError }, { setupRuntime }] = await Promise.all([
112
+ import('@modelcontextprotocol/sdk/server/stdio.js'),
113
+ import('../src/server.js'),
114
+ import('../src/processes.js'),
115
+ import('../src/paths.js'),
116
+ import('../src/runtime.js'),
117
+ ])
118
+
119
+ // the Desktop extension sets NERA_MCP_RUNTIME=bundled: its Node has no npm and
120
+ // nothing on the PATH, so children get a shim folder for node, npm and npx;
121
+ // the folder goes when this process exits, however it exits
122
+ const runtime = setupRuntime()
123
+ if (runtime) {
124
+ process.on('exit', runtime.remove)
125
+ console.error(`nera-mcp: bundled runtime, node${runtime.npm ? ', npm and npx' : ' (no npm found)'} for children in ${runtime.dir}`)
126
+ }
127
+
128
+ const processes = createProcesses()
129
+ let server
130
+ try {
131
+ server = await createServer({ root: options.root, processes })
132
+ } catch (error) {
133
+ if (error instanceof PathError) fail(error.message)
134
+ throw error
135
+ }
136
+
137
+ let closing = false
138
+
139
+ /**
140
+ * Stops the preview and publish children (they run in their own process
141
+ * group, so they would outlive this process otherwise), closes the server
142
+ * and exits. A second signal while that runs exits at once.
143
+ *
144
+ * @param {number} code
145
+ */
146
+ async function shutdown(code) {
147
+ if (closing) process.exit(code)
148
+ closing = true
149
+ try {
150
+ // before server.close(): its onclose handler would start the same stop
151
+ // without anyone waiting for it
152
+ await processes.stopAll()
153
+ await server.close()
154
+ } catch (error) {
155
+ console.error(`nera-mcp: shutting down failed: ${error.message}`)
156
+ code = 1
157
+ }
158
+ process.exit(code)
159
+ }
160
+
161
+ process.on('SIGINT', () => shutdown(0))
162
+ process.on('SIGTERM', () => shutdown(0))
163
+ // the client hung up: stdin ends, or stdout can no longer be written
164
+ process.stdin.on('end', () => shutdown(0))
165
+ process.stdout.on('error', () => shutdown(0))
92
166
 
93
- let closing = false
167
+ await server.connect(new StdioServerTransport())
168
+ console.error(`nera-mcp ${pkg.version}: serving Nera sites under ${options.root} over stdio`)
169
+ }
94
170
 
95
171
  /**
96
- * Stops the preview and publish children (they run in their own process
97
- * group, so they would outlive this process otherwise), closes the server
98
- * and exits. A second signal while that runs exits at once.
99
- *
100
- * @param {number} code
172
+ * The hosted mode: the OAuth server and `/mcp` on one HTTP port. Everything
173
+ * secret comes from the environment; nothing logged here or by the app ever
174
+ * carries a token, a key or the client secret.
101
175
  */
102
- async function shutdown(code) {
103
- if (closing) process.exit(code)
104
- closing = true
176
+ async function serveHttp() {
177
+ const { HostedConfigError, hasNodeSqlite, parsePort, parseTrustProxy, readHostedConfig } = await import('../src/hosted/config.js')
178
+
179
+ // before anything imports the store: on an older Node, `node:sqlite` would
180
+ // fail with an error that does not say what to do
181
+ if (!hasNodeSqlite(process.versions.node)) {
182
+ fail(`the hosted mode (--http) needs Node 22.13 or later (for node:sqlite); this is Node ${process.versions.node}.`)
183
+ }
184
+
185
+ let config
186
+ let port
187
+ let trustProxy
105
188
  try {
106
- // before server.close(): its onclose handler would start the same stop
107
- // without anyone waiting for it
108
- await processes.stopAll()
109
- await server.close()
189
+ config = readHostedConfig(process.env)
190
+ port = parsePort(options.port, DEFAULT_PORT)
191
+ trustProxy = parseTrustProxy(options['trust-proxy'])
110
192
  } catch (error) {
111
- console.error(`nera-mcp: shutting down failed: ${error.message}`)
112
- code = 1
193
+ if (error instanceof HostedConfigError) fail(error.message)
194
+ throw error
113
195
  }
114
- process.exit(code)
115
- }
196
+ const host = options.host ?? DEFAULT_HOST
197
+
198
+ const [{ createServer }, { createHostedApp, GITHUB_CALLBACK_PATH }, { createGitHubClient }, { createStore }] = await Promise.all([
199
+ import('node:http'),
200
+ import('../src/hosted/app.js'),
201
+ import('../src/hosted/github.js'),
202
+ import('../src/hosted/store.js'),
203
+ ])
204
+
205
+ const log = (message) => console.error(`nera-mcp: ${message}`)
206
+
207
+ // the messages of these errors name a setting, never its value (the
208
+ // issuer, a path or an address at most, none of them secret)
209
+ let store
210
+ let app
211
+ try {
212
+ const github = createGitHubClient({
213
+ clientId: config.githubClientId,
214
+ clientSecret: config.githubClientSecret,
215
+ redirectUri: new URL(GITHUB_CALLBACK_PATH, config.issuer).href,
216
+ })
217
+ store = createStore({ file: config.db, key: config.tokenKey, log })
218
+ app = createHostedApp({ issuer: config.issuer, store, github, log, trustProxy }).app
219
+ } catch (error) {
220
+ store?.close()
221
+ fail(`cannot start the hosted mode: ${error.message}`)
222
+ }
223
+
224
+ const server = createServer(app)
225
+ try {
226
+ await new Promise((resolve, reject) => {
227
+ server.once('error', reject)
228
+ server.listen(port, host, resolve)
229
+ })
230
+ } catch (error) {
231
+ store.close()
232
+ fail(`cannot listen on ${host}:${port}: ${error.message}`)
233
+ }
234
+
235
+ let closing = false
116
236
 
117
- process.on('SIGINT', () => shutdown(0))
118
- process.on('SIGTERM', () => shutdown(0))
119
- // the client hung up: stdin ends, or stdout can no longer be written
120
- process.stdin.on('end', () => shutdown(0))
121
- process.stdout.on('error', () => shutdown(0))
237
+ /**
238
+ * Stops taking connections, lets running requests finish (for at most
239
+ * SHUTDOWN_GRACE_MS), then closes the database and exits. A second signal
240
+ * while that runs exits at once.
241
+ */
242
+ function shutdown() {
243
+ if (closing) process.exit(0)
244
+ closing = true
245
+ const cutOff = setTimeout(() => server.closeAllConnections(), SHUTDOWN_GRACE_MS)
246
+ cutOff.unref()
247
+ server.close(() => {
248
+ clearTimeout(cutOff)
249
+ let code = 0
250
+ try {
251
+ store.close()
252
+ } catch (error) {
253
+ log(`closing the database failed: ${error.message}`)
254
+ code = 1
255
+ }
256
+ process.exit(code)
257
+ })
258
+ server.closeIdleConnections()
259
+ }
122
260
 
123
- await server.connect(new StdioServerTransport())
124
- console.error(`nera-mcp ${pkg.version}: serving Nera sites under ${options.root} over stdio`)
261
+ process.on('SIGINT', shutdown)
262
+ process.on('SIGTERM', shutdown)
263
+
264
+ const address = server.address()
265
+ console.error(`nera-mcp ${pkg.version}: hosted mode for ${new URL(config.issuer).origin}, listening on ${address.address}:${address.port}`)
266
+ }