@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.
@@ -0,0 +1,490 @@
1
+ // The hosted mode's persistent state (L7b), one SQLite file via `node:sqlite`:
2
+ // registered OAuth clients, pending authorizations (from our `/authorize`
3
+ // through the consent page to GitHub's callback), authorization codes, our
4
+ // access and refresh tokens, and the GitHub users with their tokens.
5
+ //
6
+ // What reaches the file: our codes, tokens, the GitHub `state` and the consent
7
+ // page's browser token only as SHA-256 hashes (they are looked up, never read
8
+ // back); GitHub's tokens and a client's secret AES-256-GCM-encrypted (they
9
+ // must be read back).
10
+ //
11
+ // Every code and the tokens issued from it share a `grant_id`, kept through
12
+ // every refresh rotation. A used code and a rotated refresh token leave a
13
+ // tombstone (their hash, the grant id, the client id, the expiry they had),
14
+ // so presenting one again is recognised as a replay and revokes the whole
15
+ // grant (OAuth 2.1's code reuse rule, the Security BCP's refresh-token reuse
16
+ // detection); the operator learns of it through one `log` line naming the
17
+ // client id and the grant id, never a token or its hash. Only the hosted mode
18
+ // loads this module — `node:sqlite` needs Node >= 22.13, while the stdio
19
+ // server (`src/server.js`) stays on the package's 22.12 floor.
20
+ import { randomUUID, timingSafeEqual } from 'node:crypto'
21
+ import { chmodSync } from 'node:fs'
22
+ import { DatabaseSync } from 'node:sqlite'
23
+ import { decrypt, encrypt, hashToken, parseKey, randomToken } from './crypto.js'
24
+
25
+ /** What a replay's log line says was sent again, by tombstone kind. */
26
+ const REPLAYED = Object.freeze({
27
+ code: 'a used authorization code',
28
+ refresh: 'an already rotated refresh token',
29
+ })
30
+
31
+ /** Lifetimes in seconds; a refresh token rotates on every use, a code is single use. */
32
+ export const TTL = Object.freeze({
33
+ pending: 10 * 60,
34
+ code: 10 * 60,
35
+ access: 60 * 60,
36
+ refresh: 30 * 24 * 60 * 60,
37
+ })
38
+
39
+ const SCHEMA = `
40
+ CREATE TABLE IF NOT EXISTS clients (
41
+ client_id TEXT PRIMARY KEY,
42
+ info TEXT NOT NULL,
43
+ secret TEXT
44
+ );
45
+ CREATE TABLE IF NOT EXISTS pending (
46
+ state_hash TEXT PRIMARY KEY,
47
+ client_id TEXT NOT NULL,
48
+ params TEXT NOT NULL,
49
+ browser_hash TEXT NOT NULL,
50
+ approved INTEGER NOT NULL DEFAULT 0,
51
+ expires_at INTEGER NOT NULL
52
+ );
53
+ CREATE TABLE IF NOT EXISTS codes (
54
+ code_hash TEXT PRIMARY KEY,
55
+ grant_id TEXT NOT NULL,
56
+ client_id TEXT NOT NULL,
57
+ user_id TEXT NOT NULL,
58
+ params TEXT NOT NULL,
59
+ expires_at INTEGER NOT NULL
60
+ );
61
+ CREATE TABLE IF NOT EXISTS tokens (
62
+ token_hash TEXT PRIMARY KEY,
63
+ kind TEXT NOT NULL CHECK (kind IN ('access', 'refresh')),
64
+ grant_id TEXT NOT NULL,
65
+ client_id TEXT NOT NULL,
66
+ user_id TEXT NOT NULL,
67
+ scopes TEXT NOT NULL,
68
+ resource TEXT,
69
+ expires_at INTEGER NOT NULL
70
+ );
71
+ CREATE INDEX IF NOT EXISTS tokens_grant ON tokens (grant_id);
72
+ CREATE TABLE IF NOT EXISTS tombstones (
73
+ hash TEXT PRIMARY KEY,
74
+ kind TEXT NOT NULL CHECK (kind IN ('code', 'refresh')),
75
+ grant_id TEXT NOT NULL,
76
+ client_id TEXT NOT NULL,
77
+ expires_at INTEGER NOT NULL
78
+ );
79
+ CREATE TABLE IF NOT EXISTS github_users (
80
+ user_id TEXT PRIMARY KEY,
81
+ login TEXT NOT NULL,
82
+ access_token TEXT NOT NULL,
83
+ access_expires_at INTEGER,
84
+ refresh_token TEXT,
85
+ refresh_expires_at INTEGER,
86
+ updated_at INTEGER NOT NULL
87
+ );
88
+ `
89
+
90
+ /**
91
+ * @typedef {object} AuthorizationRecord the part of a client's `/authorize`
92
+ * request that the code exchange checks later
93
+ * @property {string} codeChallenge
94
+ * @property {string} redirectUri
95
+ * @property {string} [state] the client's own state
96
+ * @property {string[]} [scopes]
97
+ * @property {string} [resource]
98
+ */
99
+
100
+ /**
101
+ * Opens (and creates, if needed) the store.
102
+ *
103
+ * @param {object} options
104
+ * @param {string} options.file the SQLite file, or `:memory:`
105
+ * @param {string|Buffer} options.key the token key (`parseKey`)
106
+ * @param {() => number} [options.now] the clock in milliseconds, for tests
107
+ * @param {(message: string) => void} [options.log] receives one line per
108
+ * detected replay (client id and grant id, never a token); silent by default
109
+ */
110
+ export function createStore({ file, key, now = Date.now, log = () => {} }) {
111
+ const secretKey = parseKey(key)
112
+ const db = new DatabaseSync(file)
113
+ if (file !== ':memory:') {
114
+ try {
115
+ chmodSync(file, 0o600)
116
+ } catch {
117
+ // Windows has no POSIX modes; the file stays as the OS created it.
118
+ }
119
+ }
120
+ db.exec('PRAGMA journal_mode = WAL')
121
+ db.exec(SCHEMA)
122
+
123
+ const seconds = () => Math.floor(now() / 1000)
124
+ const statements = {
125
+ getClient: db.prepare('SELECT info, secret FROM clients WHERE client_id = ?'),
126
+ saveClient: db.prepare('INSERT OR REPLACE INTO clients (client_id, info, secret) VALUES (?, ?, ?)'),
127
+ savePending: db.prepare('INSERT INTO pending (state_hash, client_id, params, browser_hash, expires_at) VALUES (?, ?, ?, ?, ?)'),
128
+ getPending: db.prepare('SELECT client_id, params, browser_hash, approved, expires_at FROM pending WHERE state_hash = ?'),
129
+ approvePending: db.prepare('UPDATE pending SET approved = 1 WHERE state_hash = ? AND approved = 0'),
130
+ takePending: db.prepare('DELETE FROM pending WHERE state_hash = ? RETURNING client_id, params, browser_hash, approved, expires_at'),
131
+ saveCode: db.prepare('INSERT INTO codes (code_hash, grant_id, client_id, user_id, params, expires_at) VALUES (?, ?, ?, ?, ?, ?)'),
132
+ getCode: db.prepare('SELECT grant_id, client_id, user_id, params, expires_at FROM codes WHERE code_hash = ?'),
133
+ takeCode: db.prepare('DELETE FROM codes WHERE code_hash = ? RETURNING grant_id, client_id, user_id, params, expires_at'),
134
+ saveToken: db.prepare('INSERT INTO tokens (token_hash, kind, grant_id, client_id, user_id, scopes, resource, expires_at) VALUES (?, ?, ?, ?, ?, ?, ?, ?)'),
135
+ getToken: db.prepare('SELECT kind, grant_id, client_id, user_id, scopes, resource, expires_at FROM tokens WHERE token_hash = ?'),
136
+ deleteToken: db.prepare('DELETE FROM tokens WHERE token_hash = ?'),
137
+ revokeGrant: db.prepare('DELETE FROM tokens WHERE grant_id = ?'),
138
+ saveTombstone: db.prepare('INSERT OR REPLACE INTO tombstones (hash, kind, grant_id, client_id, expires_at) VALUES (?, ?, ?, ?, ?)'),
139
+ getTombstone: db.prepare('SELECT kind, grant_id, client_id, expires_at FROM tombstones WHERE hash = ?'),
140
+ revokeToken: db.prepare('DELETE FROM tokens WHERE token_hash = ? AND client_id = ?'),
141
+ saveGithubUser: db.prepare(`INSERT OR REPLACE INTO github_users
142
+ (user_id, login, access_token, access_expires_at, refresh_token, refresh_expires_at, updated_at)
143
+ VALUES (?, ?, ?, ?, ?, ?, ?)`),
144
+ getGithubUser: db.prepare('SELECT * FROM github_users WHERE user_id = ?'),
145
+ purge: ['pending', 'codes', 'tokens', 'tombstones'].map((table) => db.prepare(`DELETE FROM ${table} WHERE expires_at <= ?`)),
146
+ }
147
+
148
+ const live = (row) => (row && row.expires_at > seconds() ? row : null)
149
+ /** True when the browser token hashes to the one stored with the pending row. */
150
+ const sameBrowser = (row, browserToken) => typeof browserToken === 'string' && timingSafeEqual(Buffer.from(hashToken(browserToken)), Buffer.from(row.browser_hash))
151
+ /** A live pending row of this browser as a record, else null. */
152
+ const pendingRecord = (row, browserToken) => {
153
+ const own = live(row)
154
+ if (!own || !sameBrowser(own, browserToken)) return null
155
+ return { clientId: own.client_id, params: JSON.parse(own.params), approved: own.approved === 1 }
156
+ }
157
+ const codeRecord = (row) => row && {
158
+ grantId: row.grant_id,
159
+ clientId: row.client_id,
160
+ userId: row.user_id,
161
+ ...JSON.parse(row.params),
162
+ expiresAt: row.expires_at,
163
+ }
164
+ const tokenRecord = (row) => row && {
165
+ kind: row.kind,
166
+ clientId: row.client_id,
167
+ userId: row.user_id,
168
+ scopes: JSON.parse(row.scopes),
169
+ resource: row.resource ?? undefined,
170
+ expiresAt: row.expires_at,
171
+ }
172
+
173
+ /**
174
+ * Marks a used code or a rotated refresh token, so presenting it again is
175
+ * recognised as a replay until the moment it would have expired anyway.
176
+ * Only its hash is kept, as in `codes` and `tokens`.
177
+ *
178
+ * @param {string} hash
179
+ * @param {'code'|'refresh'} kind
180
+ * @param {{grant_id: string, client_id: string, expires_at: number}} row the used code's or token's row
181
+ */
182
+ function bury(hash, kind, row) {
183
+ statements.saveTombstone.run(hash, kind, row.grant_id, row.client_id, row.expires_at)
184
+ }
185
+
186
+ /**
187
+ * When `hash` is a used code or rotated refresh token of `kind` presented
188
+ * again, revokes every token of its grant: one of the two holders is not
189
+ * the legitimate client, and we cannot tell which. Logs one line after
190
+ * the revoke, naming the grant and its client — never the token or its
191
+ * hash. A failing logger never undoes the revoke (inside a transaction,
192
+ * a throw would roll it back).
193
+ *
194
+ * @param {string} hash
195
+ * @param {'code'|'refresh'} kind
196
+ */
197
+ function revokeOnReplay(hash, kind) {
198
+ const tombstone = live(statements.getTombstone.get(hash))
199
+ if (tombstone?.kind !== kind) return
200
+ const revoked = Number(statements.revokeGrant.run(tombstone.grant_id).changes)
201
+ try {
202
+ log(`replay detected: ${REPLAYED[kind]} was sent again; revoked grant ${tombstone.grant_id} of ` +
203
+ `client ${tombstone.client_id} (${revoked} tokens)`)
204
+ } catch {
205
+ // the revoke is what protects the user; a lost log line is not worth undoing it
206
+ }
207
+ }
208
+
209
+ /**
210
+ * Issues a fresh access + refresh token pair; only their hashes are stored.
211
+ *
212
+ * @param {{clientId: string, userId: string, scopes?: string[], resource?: string, grantId?: string}} grant
213
+ * `grantId` ties the pair to its code and earlier rotations; a new grant when absent
214
+ */
215
+ function issueTokens({ clientId, userId, scopes = [], resource, grantId = randomUUID() }) {
216
+ const issued = seconds()
217
+ const accessToken = randomToken()
218
+ const refreshToken = randomToken()
219
+ const accessExpiresAt = issued + TTL.access
220
+ const refreshExpiresAt = issued + TTL.refresh
221
+ const scopesJson = JSON.stringify(scopes)
222
+ statements.saveToken.run(hashToken(accessToken), 'access', grantId, clientId, String(userId), scopesJson, resource ?? null, accessExpiresAt)
223
+ statements.saveToken.run(hashToken(refreshToken), 'refresh', grantId, clientId, String(userId), scopesJson, resource ?? null, refreshExpiresAt)
224
+ return { accessToken, refreshToken, expiresIn: TTL.access, accessExpiresAt, refreshExpiresAt, scopes }
225
+ }
226
+
227
+ /** Runs `fn` in one transaction, so a rotation is all or nothing. */
228
+ function transaction(fn) {
229
+ db.exec('BEGIN IMMEDIATE')
230
+ try {
231
+ const result = fn()
232
+ db.exec('COMMIT')
233
+ return result
234
+ } catch (error) {
235
+ db.exec('ROLLBACK')
236
+ throw error
237
+ }
238
+ }
239
+
240
+ const store = {
241
+ /** @param {string} clientId */
242
+ getClient(clientId) {
243
+ const row = statements.getClient.get(String(clientId))
244
+ if (!row) return undefined
245
+ const info = JSON.parse(row.info)
246
+ if (row.secret !== null) info.client_secret = decrypt(secretKey, row.secret)
247
+ return info
248
+ },
249
+
250
+ /**
251
+ * Persists a registered client (RFC 7591); its secret, if any, encrypted.
252
+ *
253
+ * @param {object} client the full client information, `client_id` included
254
+ */
255
+ saveClient(client) {
256
+ if (!client?.client_id) throw new Error('A client needs a client_id.')
257
+ const { client_secret: secret, ...info } = client
258
+ const encrypted = secret ? encrypt(secretKey, secret) : null
259
+ statements.saveClient.run(client.client_id, JSON.stringify(info), encrypted)
260
+ return { ...client }
261
+ },
262
+
263
+ /**
264
+ * Remembers a client's authorization request while the user decides on
265
+ * the consent page and logs in at GitHub. It is bound to the browser
266
+ * that holds `browserToken` (the consent cookie).
267
+ *
268
+ * @param {{clientId: string, params: AuthorizationRecord}} pending
269
+ * @returns {{state: string, browserToken: string}} the `state` for the consent form and GitHub, the token for the cookie
270
+ */
271
+ savePending({ clientId, params }) {
272
+ const state = randomToken()
273
+ const browserToken = randomToken()
274
+ statements.savePending.run(
275
+ hashToken(state), clientId, JSON.stringify(params), hashToken(browserToken), seconds() + TTL.pending,
276
+ )
277
+ return { state, browserToken }
278
+ },
279
+
280
+ /**
281
+ * Reads a pending request without using it up.
282
+ *
283
+ * @param {string} state
284
+ * @param {string} browserToken
285
+ * @returns {{clientId: string, params: AuthorizationRecord, approved: boolean}|null} null when unknown, expired or another browser's
286
+ */
287
+ getPending(state, browserToken) {
288
+ return pendingRecord(statements.getPending.get(hashToken(state)), browserToken)
289
+ },
290
+
291
+ /**
292
+ * Records the user's Approve; once only.
293
+ *
294
+ * @param {string} state
295
+ * @param {string} browserToken
296
+ * @returns {boolean} false when unknown, expired, another browser's or already approved
297
+ */
298
+ approvePending(state, browserToken) {
299
+ return transaction(() => {
300
+ const record = pendingRecord(statements.getPending.get(hashToken(state)), browserToken)
301
+ if (!record || record.approved) return false
302
+ return statements.approvePending.run(hashToken(state)).changes > 0
303
+ })
304
+ },
305
+
306
+ /**
307
+ * Takes the pending request back (GitHub's callback, or a Deny); single
308
+ * use — the row is gone afterwards even when it belongs to another
309
+ * browser, so a wrong guess cannot be retried.
310
+ *
311
+ * @param {string} state
312
+ * @param {string} browserToken
313
+ * @returns {{clientId: string, params: AuthorizationRecord, approved: boolean}|null} null when unknown, used, expired or another browser's
314
+ */
315
+ takePending(state, browserToken) {
316
+ return pendingRecord(statements.takePending.get(hashToken(state)), browserToken)
317
+ },
318
+
319
+ /**
320
+ * Issues an authorization code for a logged-in user; it starts a new
321
+ * grant.
322
+ *
323
+ * @param {{clientId: string, userId: string, params: AuthorizationRecord}} grant
324
+ * @returns {string} the code
325
+ */
326
+ saveCode({ clientId, userId, params }) {
327
+ const code = randomToken()
328
+ statements.saveCode.run(
329
+ hashToken(code), randomUUID(), clientId, String(userId), JSON.stringify(params), seconds() + TTL.code,
330
+ )
331
+ return code
332
+ },
333
+
334
+ /**
335
+ * Reads a code without using it up (the PKCE challenge lookup, which
336
+ * the token endpoint runs first). A code that was already used revokes
337
+ * every token issued from it, here already.
338
+ *
339
+ * @param {string} code
340
+ * @returns {object|null} null when unknown, expired or used
341
+ */
342
+ getCode(code) {
343
+ const hash = hashToken(code)
344
+ const record = codeRecord(live(statements.getCode.get(hash)))
345
+ if (!record) revokeOnReplay(hash, 'code')
346
+ return record
347
+ },
348
+
349
+ /**
350
+ * Uses a code up: a second call with the same code returns null and
351
+ * revokes every token issued from the first.
352
+ *
353
+ * @param {string} code
354
+ * @returns {object|null} null when unknown, expired or used
355
+ */
356
+ takeCode(code) {
357
+ const hash = hashToken(code)
358
+ return transaction(() => {
359
+ const row = live(statements.takeCode.get(hash))
360
+ if (!row) {
361
+ revokeOnReplay(hash, 'code')
362
+ return null
363
+ }
364
+ bury(hash, 'code', row)
365
+ return codeRecord(row)
366
+ })
367
+ },
368
+
369
+ issueTokens,
370
+
371
+ /**
372
+ * Looks an access token up.
373
+ *
374
+ * @param {string} token
375
+ * @returns {object|null} null when unknown, revoked, expired or a refresh token
376
+ */
377
+ getAccessToken(token) {
378
+ const row = live(statements.getToken.get(hashToken(token)))
379
+ return row?.kind === 'access' ? tokenRecord(row) : null
380
+ },
381
+
382
+ /**
383
+ * Exchanges a refresh token for a new pair of the same grant; the old
384
+ * refresh token is gone afterwards. Presenting it again is a replay:
385
+ * it is refused and revokes the grant's current pair.
386
+ *
387
+ * @param {string} refreshToken
388
+ * @param {{clientId: string, scopes?: string[]}} request `scopes` may narrow, never widen, the grant
389
+ * @returns {object|null} the new pair, or null when the token is unknown, used, expired or another client's
390
+ */
391
+ rotateRefreshToken(refreshToken, { clientId, scopes }) {
392
+ return transaction(() => {
393
+ const hash = hashToken(refreshToken)
394
+ const row = live(statements.getToken.get(hash))
395
+ if (!row) {
396
+ revokeOnReplay(hash, 'refresh')
397
+ return null
398
+ }
399
+ const record = tokenRecord(row)
400
+ if (record.kind !== 'refresh' || record.clientId !== clientId) return null
401
+ if (scopes && !scopes.every((scope) => record.scopes.includes(scope))) return null
402
+ statements.deleteToken.run(hash)
403
+ bury(hash, 'refresh', row)
404
+ return issueTokens({
405
+ clientId,
406
+ userId: record.userId,
407
+ scopes: scopes ?? record.scopes,
408
+ resource: record.resource,
409
+ grantId: row.grant_id,
410
+ })
411
+ })
412
+ },
413
+
414
+ /**
415
+ * Revokes an access or refresh token of this client (RFC 7009 §2.1).
416
+ * A refresh token takes every token of its grant with it, so the
417
+ * access tokens issued alongside stop working too; an access token
418
+ * removes only itself, so a client dropping a stale access token keeps
419
+ * its session. An unknown token or another client's is no error and
420
+ * revokes nothing.
421
+ *
422
+ * @param {string} token
423
+ * @param {{clientId: string}} request
424
+ * @returns {boolean} whether a token was removed
425
+ */
426
+ revokeToken(token, { clientId }) {
427
+ const hash = hashToken(token)
428
+ return transaction(() => {
429
+ const row = statements.getToken.get(hash)
430
+ if (row?.client_id !== clientId) return false
431
+ if (row.kind === 'refresh') return statements.revokeGrant.run(row.grant_id).changes > 0
432
+ return statements.revokeToken.run(hash, clientId).changes > 0
433
+ })
434
+ },
435
+
436
+ /**
437
+ * Saves (or replaces) a GitHub user with their tokens, encrypted.
438
+ *
439
+ * @param {{id: string|number, login: string, accessToken: string, accessTokenExpiresAt?: number, refreshToken?: string, refreshTokenExpiresAt?: number}} user
440
+ */
441
+ saveGithubUser({ id, login, accessToken, accessTokenExpiresAt, refreshToken, refreshTokenExpiresAt }) {
442
+ statements.saveGithubUser.run(
443
+ String(id),
444
+ login,
445
+ encrypt(secretKey, accessToken),
446
+ accessTokenExpiresAt ?? null,
447
+ refreshToken ? encrypt(secretKey, refreshToken) : null,
448
+ refreshTokenExpiresAt ?? null,
449
+ seconds(),
450
+ )
451
+ },
452
+
453
+ /**
454
+ * Reads a GitHub user back, tokens decrypted. Throws when the token key
455
+ * is not the one they were written with.
456
+ *
457
+ * @param {string|number} id
458
+ */
459
+ getGithubUser(id) {
460
+ const row = statements.getGithubUser.get(String(id))
461
+ if (!row) return null
462
+ return {
463
+ id: row.user_id,
464
+ login: row.login,
465
+ accessToken: decrypt(secretKey, row.access_token),
466
+ accessTokenExpiresAt: row.access_expires_at ?? undefined,
467
+ refreshToken: row.refresh_token === null ? undefined : decrypt(secretKey, row.refresh_token),
468
+ refreshTokenExpiresAt: row.refresh_expires_at ?? undefined,
469
+ }
470
+ },
471
+
472
+ /**
473
+ * Deletes every expired pending authorization, code, token and
474
+ * tombstone.
475
+ *
476
+ * @returns {number} how many rows went
477
+ */
478
+ purgeExpired() {
479
+ const at = seconds()
480
+ return statements.purge.reduce((count, statement) => count + Number(statement.run(at).changes), 0)
481
+ },
482
+
483
+ close() {
484
+ db.close()
485
+ },
486
+ }
487
+
488
+ store.purgeExpired()
489
+ return store
490
+ }
@@ -0,0 +1,192 @@
1
+ // `publish` and `preview` of the hosted mode (L7b). The write
2
+ // tools collect their commits on the draft branch `nera-draft`; `publish`
3
+ // merges it into `main` in one push, so the site's deploy workflow
4
+ // (`.github/workflows/deploy.yml`, which triggers on pushes to `main` only)
5
+ // builds and deploys once per batch, and deletes the draft. A draft without
6
+ // unpublished commits, or no draft at all, pushes nothing, so no deploy is
7
+ // started for nothing. The build itself runs in the site's own Actions run;
8
+ // both tools only report it, with the address the site is served at.
9
+ import { setTimeout as sleepFor } from 'node:timers/promises'
10
+ import { z } from 'zod'
11
+ import { ok, ToolError } from '../../results.js'
12
+ import { GitHubError } from '../github.js'
13
+ import { BASE_BRANCH, DRAFT_BRANCH } from '../repo.js'
14
+ import { createSiteAccess, hostedSiteInput, hostedTool } from './read.js'
15
+
16
+ /**
17
+ * The deploy workflow's file name in `.github/workflows/`: the one `nera
18
+ * publish` commits (`renderDeployWorkflow` of `@nera-static/nera`).
19
+ */
20
+ export const DEPLOY_WORKFLOW = 'deploy.yml'
21
+ /** How often `publish` looks for the deploy run of its push, which GitHub starts a few seconds later. */
22
+ export const RUN_LOOKUPS = 5
23
+ /** The pause between two lookups. */
24
+ export const RUN_LOOKUP_MS = 2000
25
+
26
+ /**
27
+ * The `origin` of `config/app.yaml` when it is an http(s) address.
28
+ *
29
+ * @param {object} appConfig
30
+ * @returns {string|null}
31
+ */
32
+ function originOf(appConfig) {
33
+ if (typeof appConfig.origin !== 'string') return null
34
+ try {
35
+ const url = new URL(appConfig.origin)
36
+ return url.protocol === 'https:' || url.protocol === 'http:' ? appConfig.origin : null
37
+ } catch {
38
+ return null
39
+ }
40
+ }
41
+
42
+ /**
43
+ * Runs a lookup that only adds information (the deploy run, the address):
44
+ * GitHub refusing it (a missing permission such as Pages or Actions read, an
45
+ * outage) must not turn a publish that happened into an error, so it yields
46
+ * null instead. The site lookup itself is never wrapped, so a lost sign-in
47
+ * still fails the call before anything is pushed.
48
+ */
49
+ async function lookup(fn) {
50
+ try {
51
+ return await fn()
52
+ } catch (error) {
53
+ if (error instanceof GitHubError) return null
54
+ throw error
55
+ }
56
+ }
57
+
58
+ /** One sentence on a deploy run, for the result's text. */
59
+ function runText(run) {
60
+ if (!run) return `No run of .github/workflows/${DEPLOY_WORKFLOW} on ${BASE_BRANCH} was found.`
61
+ const state = run.status === 'completed' ? `finished: ${run.conclusion}` : run.status.replace('_', ' ')
62
+ return `The deploy run is ${state} (${run.url}).`
63
+ }
64
+
65
+ /**
66
+ * Registers `publish` and `preview`.
67
+ *
68
+ * @param {import('@modelcontextprotocol/sdk/server/mcp.js').McpServer} server
69
+ * @param {object} ctx
70
+ * @param {() => Promise<ReturnType<import('../repo.js').createRepoClient>>} ctx.repos the signed-in user's repository client
71
+ * @param {(ms: number) => Promise<void>} [ctx.sleep] the pause between run lookups (injected so tests do not wait)
72
+ */
73
+ export function registerHostedPublishTools(server, { repos, sleep = sleepFor }) {
74
+ const { openSite, appConfigAt } = createSiteAccess(repos)
75
+
76
+ /** The address the site is served at: GitHub Pages', else `origin` in config/app.yaml on main. */
77
+ async function deployedUrl(target) {
78
+ const pages = await lookup(() => target.client.pagesUrl(target.site))
79
+ if (pages) return pages
80
+ const config = await lookup(() => appConfigAt(target, BASE_BRANCH))
81
+ return config ? originOf(config.appConfig) : null
82
+ }
83
+
84
+ /** The deploy run of the push of `sha`, looked for a few times while GitHub starts it. */
85
+ async function runFor(target, sha) {
86
+ for (let attempt = 1; attempt <= RUN_LOOKUPS; attempt += 1) {
87
+ const run = await lookup(() => target.client.latestRun(target.site, DEPLOY_WORKFLOW, { sha }))
88
+ if (run) return run
89
+ if (attempt < RUN_LOOKUPS) await sleep(RUN_LOOKUP_MS)
90
+ }
91
+ return null
92
+ }
93
+
94
+ /** The draft's unpublished commits: 0 without a draft. */
95
+ async function draftAhead(target) {
96
+ if (!target.draft.exists) return 0
97
+ if (!target.mainSha) {
98
+ throw new ToolError(`The repository "${target.site}" has a draft but no ${BASE_BRANCH} branch to publish ` +
99
+ `it to. Create ${BASE_BRANCH} on GitHub first.`)
100
+ }
101
+ return target.client.aheadBy(target.site, target.mainSha, target.draft.sha)
102
+ }
103
+
104
+ /** The result of a publish that pushed nothing. */
105
+ async function nothingPublished(target, reason) {
106
+ const run = await lookup(() => target.client.latestRun(target.site, DEPLOY_WORKFLOW))
107
+ const url = await deployedUrl(target)
108
+ return ok(
109
+ { site: target.site, published: false, commits: 0, commit: null, run, url },
110
+ `${reason} Nothing was pushed to ${BASE_BRANCH}, so no deploy was started. ${runText(run)}${url ? ` The site is at ${url}.` : ''}`,
111
+ )
112
+ }
113
+
114
+ server.registerTool('publish', {
115
+ title: 'Publish the draft',
116
+ description: 'Puts a Nera site\'s unpublished changes live. Every write_page, write_file and delete_page ' +
117
+ `commits to the draft branch ${DRAFT_BRANCH} of the site's GitHub repository; publish merges that draft ` +
118
+ `into ${BASE_BRANCH} in one push and deletes it. The push starts the site's deploy workflow ` +
119
+ `(.github/workflows/${DEPLOY_WORKFLOW}, GitHub Actions), which builds the site and deploys it to GitHub ` +
120
+ 'Pages or Netlify, once for all changes since the last publish. Call validate first and fix its errors. ' +
121
+ 'Returns the merge commit, the deploy run (status and address; it takes a minute or two) and the address ' +
122
+ 'the site is served at; call preview later to see whether the run succeeded. Without unpublished changes ' +
123
+ 'nothing is pushed and only the latest run is reported.',
124
+ inputSchema: {
125
+ site: hostedSiteInput,
126
+ message: z.string().optional().describe(`The merge commit's message, used only when ${BASE_BRANCH} ` +
127
+ `changed since the draft began (otherwise the draft's own commits go onto ${BASE_BRANCH} as they ` +
128
+ `are). Defaults to "Publish the changes from ${DRAFT_BRANCH}".`),
129
+ },
130
+ }, hostedTool(async ({ site, message }) => {
131
+ const target = await openSite(site)
132
+ if (!target.draft.exists) return nothingPublished(target, `"${target.site}" has no unpublished changes.`)
133
+ const ahead = await draftAhead(target)
134
+ if (ahead === 0) {
135
+ await target.client.deleteDraft(target.site)
136
+ return nothingPublished(target, `The draft of "${target.site}" held no unpublished ` +
137
+ 'commits, so it was deleted.')
138
+ }
139
+ const merged = await target.client.mergeDraft(target.site, message?.trim() || 'Publish the ' +
140
+ `changes from ${DRAFT_BRANCH}`)
141
+ // null: the draft is gone; not pushed: main already held it. Either way another call published it in the meantime.
142
+ if (!merged || !merged.pushed) {
143
+ return nothingPublished(target, `The changes of "${target.site}" are already live on ${BASE_BRANCH}, or ` +
144
+ 'were published by another call in the meantime.')
145
+ }
146
+ const run = await runFor(target, merged.sha)
147
+ const url = await deployedUrl(target)
148
+ const runSentence = run
149
+ ? runText(run)
150
+ : 'GitHub has not started the deploy run yet; call preview in a minute to see it. If none appears, the ' +
151
+ `repository has no .github/workflows/${DEPLOY_WORKFLOW} — \`nera publish\` sets it up once.`
152
+ return ok(
153
+ {
154
+ site: target.site,
155
+ published: true,
156
+ commits: ahead,
157
+ commit: merged.sha,
158
+ fastForward: merged.fastForward,
159
+ run,
160
+ url,
161
+ },
162
+ `Published ${ahead} commit(s) of "${target.site}" to ${BASE_BRANCH} (${merged.sha.slice(0, 7)}) and deleted the draft. ${runSentence}${url ? ` Once it succeeds, the site is live at ${url}.` : ''}`,
163
+ )
164
+ }))
165
+
166
+ server.registerTool('preview', {
167
+ title: 'Show the live site',
168
+ description: 'Shows where a Nera site in a GitHub repository is live and how its last deploy went: the ' +
169
+ 'address it is served at (GitHub Pages, else `origin` in config/app.yaml), the latest run of its ' +
170
+ `deploy workflow (.github/workflows/${DEPLOY_WORKFLOW}: status, conclusion, address) and how many ` +
171
+ `changes wait unpublished on the draft branch ${DRAFT_BRANCH}. Call it after publish to see whether the ` +
172
+ 'deploy succeeded; unpublished changes are not visible at the address until publish.',
173
+ inputSchema: { site: hostedSiteInput },
174
+ annotations: { readOnlyHint: true },
175
+ }, hostedTool(async ({ site }) => {
176
+ const target = await openSite(site)
177
+ const ahead = await draftAhead(target)
178
+ const run = await lookup(() => target.client.latestRun(target.site, DEPLOY_WORKFLOW))
179
+ const url = await deployedUrl(target)
180
+ const where = url
181
+ ? `"${target.site}" is served at ${url}.`
182
+ : `No address found for "${target.site}": GitHub Pages is not set up for it and ` +
183
+ 'config/app.yaml has no origin.'
184
+ const draft = ahead
185
+ ? ` ${ahead} unpublished commit(s) wait on ${DRAFT_BRANCH}; call publish to put them live.`
186
+ : ' It has no unpublished changes.'
187
+ return ok(
188
+ { site: target.site, url, run, draft: { exists: target.draft.exists, ahead } },
189
+ `${where} ${runText(run)}${draft}`,
190
+ )
191
+ }))
192
+ }