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