visual-living-plan 2.32.1 → 2.33.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,403 @@
1
+ import { createHash, randomBytes } from 'node:crypto';
2
+ import { isLoopbackHost } from '../localName';
3
+ import { MCP_SCOPE } from './oauthStore';
4
+ /** Where the MCP endpoint lives on the plan service. */
5
+ export const MCP_PATH = '/mcp';
6
+ export const PROTECTED_RESOURCE_PATH = '/.well-known/oauth-protected-resource';
7
+ export const AUTHORIZATION_SERVER_PATH = '/.well-known/oauth-authorization-server';
8
+ export const AUTHORIZE_PATH = '/oauth/authorize';
9
+ export const TOKEN_PATH = '/oauth/token';
10
+ export const REGISTER_PATH = '/oauth/register';
11
+ export const REVOKE_PATH = '/oauth/revoke';
12
+ /** A consent page and the code it hands out are each good for this long. */
13
+ const PENDING_MS = 10 * 60 * 1000;
14
+ const CODE_MS = 5 * 60 * 1000;
15
+ const MAX_PENDING = 100;
16
+ const MAX_BODY_BYTES = 16_384;
17
+ const BLOCKED_SCHEMES = new Set(['javascript', 'data', 'file', 'vbscript', 'about', 'blob', 'filesystem']);
18
+ export function originOf(request) {
19
+ return new URL(request.url).origin;
20
+ }
21
+ function json(body, status = 200, headers = {}) {
22
+ return new Response(JSON.stringify(body), {
23
+ status,
24
+ headers: { 'content-type': 'application/json', 'cache-control': 'no-store', ...headers },
25
+ });
26
+ }
27
+ function oauthError(error, description, status = 400) {
28
+ return json({ error, error_description: description }, status);
29
+ }
30
+ function token(size = 32) {
31
+ return randomBytes(size).toString('base64url');
32
+ }
33
+ function prune(map, now) {
34
+ for (const [key, value] of map)
35
+ if (value.expiresAt <= now)
36
+ map.delete(key);
37
+ }
38
+ async function readBody(request) {
39
+ const text = await request.text();
40
+ if (text.length > MAX_BODY_BYTES)
41
+ throw new Error('Request body is too large');
42
+ const type = request.headers.get('content-type') ?? '';
43
+ if (type.includes('application/json')) {
44
+ const parsed = JSON.parse(text || '{}');
45
+ return Object.fromEntries(Object.entries(parsed).flatMap(([key, value]) => (typeof value === 'string' ? [[key, value]] : [])));
46
+ }
47
+ return Object.fromEntries(new URLSearchParams(text));
48
+ }
49
+ /**
50
+ * A redirect URI an agent may register: https anywhere, http only back to this computer, or an app's
51
+ * own scheme (RFC 8252). Never a fragment, and never a scheme a browser runs as code.
52
+ */
53
+ export function allowedRedirectUri(value) {
54
+ if (typeof value !== 'string' || value.length > 2000)
55
+ return false;
56
+ let url;
57
+ try {
58
+ url = new URL(value);
59
+ }
60
+ catch {
61
+ return false;
62
+ }
63
+ if (url.hash)
64
+ return false;
65
+ const scheme = url.protocol.slice(0, -1).toLowerCase();
66
+ if (scheme === 'https')
67
+ return true;
68
+ if (scheme === 'http')
69
+ return isLoopbackHost(url.hostname);
70
+ return /^[a-z][a-z0-9+.-]*$/.test(scheme) && !BLOCKED_SCHEMES.has(scheme);
71
+ }
72
+ /** Exact match, except a loopback http redirect may use any port (RFC 8252 section 7.3). */
73
+ export function redirectMatches(registered, presented) {
74
+ if (registered === presented)
75
+ return true;
76
+ try {
77
+ const left = new URL(registered);
78
+ const right = new URL(presented);
79
+ if (left.protocol !== 'http:' || right.protocol !== 'http:')
80
+ return false;
81
+ if (!isLoopbackHost(left.hostname) || left.hostname !== right.hostname)
82
+ return false;
83
+ return left.pathname === right.pathname && left.search === right.search;
84
+ }
85
+ catch {
86
+ return false;
87
+ }
88
+ }
89
+ /** The redirect the person's browser follows with the outcome of the consent page. */
90
+ function redirectWith(redirectUri, params) {
91
+ const url = new URL(redirectUri);
92
+ for (const [key, value] of Object.entries(params))
93
+ if (value !== null)
94
+ url.searchParams.set(key, value);
95
+ return new Response(null, { status: 303, headers: { location: url.toString(), 'cache-control': 'no-store' } });
96
+ }
97
+ function escapeHtml(value) {
98
+ return value.replace(/[&<>"']/g, (char) => `&#${char.charCodeAt(0)};`);
99
+ }
100
+ const PAGE_HEADERS = {
101
+ 'content-type': 'text/html; charset=utf-8',
102
+ 'cache-control': 'no-store',
103
+ 'x-frame-options': 'DENY',
104
+ 'content-security-policy': "default-src 'none'; style-src 'unsafe-inline'; frame-ancestors 'none'; base-uri 'none'",
105
+ // Not no-referrer: browsers then send `Origin: null` on the form post, and the service refuses it as
106
+ // cross-site. same-origin keeps the real Origin on Allow and still sends no referrer to the agent.
107
+ 'referrer-policy': 'same-origin',
108
+ };
109
+ function page(title, body, status = 200) {
110
+ const html = `<!doctype html>
111
+ <html lang="en">
112
+ <head>
113
+ <meta charset="utf-8">
114
+ <meta name="viewport" content="width=device-width, initial-scale=1">
115
+ <title>${escapeHtml(title)}</title>
116
+ <style>
117
+ :root { color-scheme: light dark; --bg: #ffffff; --fg: #0a0a0a; --muted: #52525b; --line: #e4e4e7; --primary: #0a0a0a; --on-primary: #ffffff; }
118
+ @media (prefers-color-scheme: dark) { :root { --bg: #0a0a0a; --fg: #fafafa; --muted: #a1a1aa; --line: #27272a; --primary: #fafafa; --on-primary: #0a0a0a; } }
119
+ * { box-sizing: border-box; }
120
+ body { margin: 0; min-height: 100vh; display: grid; place-items: center; padding: 24px 16px; background: var(--bg); color: var(--fg); font: 15px/1.5 "DM Sans", Inter, system-ui, sans-serif; }
121
+ main { width: 100%; max-width: 440px; }
122
+ .eyebrow { font-size: 12px; font-weight: 600; letter-spacing: .06em; text-transform: uppercase; color: var(--muted); margin: 0 0 8px; }
123
+ h1 { font-size: 24px; line-height: 1.2; letter-spacing: -.01em; margin: 0 0 12px; }
124
+ p { margin: 0 0 12px; color: var(--muted); }
125
+ strong { color: var(--fg); }
126
+ code { font: 13px/1.4 ui-monospace, SFMono-Regular, Menlo, monospace; overflow-wrap: anywhere; }
127
+ ul { margin: 0 0 20px; padding: 16px 0 0 20px; border-top: 1px solid var(--line); color: var(--muted); }
128
+ li { margin-bottom: 4px; }
129
+ .actions { display: flex; gap: 8px; flex-wrap: wrap; }
130
+ button { font: inherit; font-weight: 600; border-radius: 999px; padding: 10px 20px; cursor: pointer; border: 1px solid var(--line); background: transparent; color: var(--fg); }
131
+ button.primary { background: var(--primary); color: var(--on-primary); border-color: var(--primary); }
132
+ </style>
133
+ </head>
134
+ <body><main>${body}</main></body>
135
+ </html>`;
136
+ return new Response(html, { status, headers: PAGE_HEADERS });
137
+ }
138
+ function errorPage(message, status = 400) {
139
+ return page('Living Plan sign-in', `<p class="eyebrow">Living Plan</p><h1>This sign-in cannot continue</h1><p>${escapeHtml(message)}</p>`, status);
140
+ }
141
+ function consentPage(client, redirectUri, requestId) {
142
+ let target = redirectUri;
143
+ try {
144
+ const url = new URL(redirectUri);
145
+ target = url.protocol === 'http:' || url.protocol === 'https:' ? url.host : url.protocol;
146
+ }
147
+ catch {
148
+ // Shown as registered.
149
+ }
150
+ return page('Allow agent access', `<p class="eyebrow">Living Plan · Agent access</p>
151
+ <h1>Allow ${escapeHtml(client.clientName)} to use your plans?</h1>
152
+ <p>It is asking to connect to Living Plan on this computer. Allow it only if you just added Living Plan to an agent.</p>
153
+ <ul>
154
+ <li>Open plan files on this computer and show them as pages</li>
155
+ <li>Read what you answer, approve, and comment on those pages</li>
156
+ <li>Change a plan's mode, reply to comments, and close plans</li>
157
+ </ul>
158
+ <p>The sign-in returns to <code>${escapeHtml(target)}</code>.</p>
159
+ <form method="post" action="${AUTHORIZE_PATH}" class="actions">
160
+ <input type="hidden" name="request" value="${escapeHtml(requestId)}">
161
+ <button class="primary" type="submit" name="decision" value="allow">Allow</button>
162
+ <button type="submit" name="decision" value="deny">Deny</button>
163
+ </form>`);
164
+ }
165
+ function pkceMatches(verifier, challenge) {
166
+ if (!/^[A-Za-z0-9\-._~]{43,128}$/.test(verifier))
167
+ return false;
168
+ return createHash('sha256').update(verifier).digest('base64url') === challenge;
169
+ }
170
+ /** A `resource` parameter names this service's MCP endpoint, on whichever host name the agent used. */
171
+ function resourceIsOurs(value) {
172
+ if (!value)
173
+ return true;
174
+ try {
175
+ return new URL(value).pathname.replace(/\/$/, '') === MCP_PATH;
176
+ }
177
+ catch {
178
+ return false;
179
+ }
180
+ }
181
+ function scopeIsOurs(value) {
182
+ if (!value)
183
+ return true;
184
+ return value.split(/\s+/).filter(Boolean).every((scope) => scope === MCP_SCOPE);
185
+ }
186
+ /**
187
+ * The OAuth 2.1 authorization server for the MCP endpoint, built into the plan service.
188
+ *
189
+ * Agents register themselves (RFC 7591), send the person to the consent page, and trade the code for
190
+ * tokens with PKCE. Only a browser on this computer can allow access, so a page reached over the LAN
191
+ * or through `--host` cannot grant it.
192
+ */
193
+ export function createOAuthServer(store, options = {}) {
194
+ const now = options.now ?? Date.now;
195
+ const pending = new Map();
196
+ const codes = new Map();
197
+ function authorizationServerMetadata(origin) {
198
+ return {
199
+ issuer: origin,
200
+ authorization_endpoint: `${origin}${AUTHORIZE_PATH}`,
201
+ token_endpoint: `${origin}${TOKEN_PATH}`,
202
+ registration_endpoint: `${origin}${REGISTER_PATH}`,
203
+ revocation_endpoint: `${origin}${REVOKE_PATH}`,
204
+ response_types_supported: ['code'],
205
+ grant_types_supported: ['authorization_code', 'refresh_token'],
206
+ code_challenge_methods_supported: ['S256'],
207
+ token_endpoint_auth_methods_supported: ['none'],
208
+ revocation_endpoint_auth_methods_supported: ['none'],
209
+ scopes_supported: [MCP_SCOPE],
210
+ authorization_response_iss_parameter_supported: true,
211
+ client_id_metadata_document_supported: false,
212
+ };
213
+ }
214
+ function protectedResourceMetadata(origin) {
215
+ return {
216
+ resource: `${origin}${MCP_PATH}`,
217
+ authorization_servers: [origin],
218
+ scopes_supported: [MCP_SCOPE],
219
+ bearer_methods_supported: ['header'],
220
+ resource_name: 'Living Plan',
221
+ };
222
+ }
223
+ async function register(request) {
224
+ let body;
225
+ try {
226
+ const text = await request.text();
227
+ if (text.length > MAX_BODY_BYTES)
228
+ return oauthError('invalid_client_metadata', 'Registration is too large');
229
+ body = JSON.parse(text || '{}');
230
+ }
231
+ catch {
232
+ return oauthError('invalid_client_metadata', 'Send the registration as a JSON object');
233
+ }
234
+ const uris = body.redirect_uris;
235
+ if (!Array.isArray(uris) || uris.length === 0 || uris.length > 10) {
236
+ return oauthError('invalid_redirect_uri', 'redirect_uris needs one to ten URIs');
237
+ }
238
+ if (!uris.every(allowedRedirectUri)) {
239
+ return oauthError('invalid_redirect_uri', 'Each redirect URI must be https, http on this computer, or an app scheme');
240
+ }
241
+ const name = typeof body.client_name === 'string' && body.client_name.trim() ? body.client_name.trim().slice(0, 100) : 'An MCP client';
242
+ const client = store.registerClient({ clientName: name, redirectUris: uris }, now());
243
+ return json({
244
+ client_id: client.clientId,
245
+ client_id_issued_at: Math.floor(client.createdAt / 1000),
246
+ client_name: client.clientName,
247
+ redirect_uris: client.redirectUris,
248
+ grant_types: ['authorization_code', 'refresh_token'],
249
+ response_types: ['code'],
250
+ token_endpoint_auth_method: 'none',
251
+ scope: MCP_SCOPE,
252
+ }, 201);
253
+ }
254
+ function authorizeGet(request, peer) {
255
+ const params = new URL(request.url).searchParams;
256
+ const client = store.getClient(params.get('client_id') ?? '');
257
+ if (!client)
258
+ return errorPage('The agent is not registered with this Living Plan service. Remove Living Plan from the agent and add it again.');
259
+ const presented = params.get('redirect_uri');
260
+ const redirectUri = presented ?? (client.redirectUris.length === 1 ? client.redirectUris[0] : null);
261
+ if (!redirectUri || !client.redirectUris.some((registered) => redirectMatches(registered, redirectUri))) {
262
+ return errorPage('The agent asked to return to an address it did not register.');
263
+ }
264
+ const state = params.get('state');
265
+ const fail = (error, description) => redirectWith(redirectUri, { error, error_description: description, state, iss: originOf(request) });
266
+ if (params.get('response_type') !== 'code')
267
+ return fail('unsupported_response_type', 'Only the code flow is supported');
268
+ const challenge = params.get('code_challenge');
269
+ if (!challenge || params.get('code_challenge_method') !== 'S256') {
270
+ return fail('invalid_request', 'PKCE with S256 is required');
271
+ }
272
+ if (!scopeIsOurs(params.get('scope')))
273
+ return fail('invalid_scope', `The only scope is ${MCP_SCOPE}`);
274
+ if (!resourceIsOurs(params.get('resource')))
275
+ return fail('invalid_target', 'The resource is not this MCP server');
276
+ if (!isLoopbackHost(peer)) {
277
+ return errorPage('Open this page in a browser on the computer that runs Living Plan to allow an agent.', 403);
278
+ }
279
+ const at = now();
280
+ prune(pending, at);
281
+ if (pending.size >= MAX_PENDING)
282
+ return errorPage('Too many sign-ins are waiting. Try again in a few minutes.', 429);
283
+ const requestId = token(24);
284
+ pending.set(requestId, { clientId: client.clientId, redirectUri, codeChallenge: challenge, state, expiresAt: at + PENDING_MS });
285
+ return consentPage(client, redirectUri, requestId);
286
+ }
287
+ async function authorizePost(request, peer) {
288
+ if (!isLoopbackHost(peer))
289
+ return errorPage('Allow agents from a browser on the computer that runs Living Plan.', 403);
290
+ let body;
291
+ try {
292
+ body = await readBody(request);
293
+ }
294
+ catch {
295
+ return errorPage('The answer could not be read.');
296
+ }
297
+ const at = now();
298
+ prune(pending, at);
299
+ const waiting = pending.get(body.request ?? '');
300
+ if (!waiting)
301
+ return errorPage('This page expired. Start the sign-in from the agent again.');
302
+ pending.delete(body.request ?? '');
303
+ const iss = originOf(request);
304
+ if (body.decision !== 'allow') {
305
+ return redirectWith(waiting.redirectUri, { error: 'access_denied', error_description: 'The person denied access', state: waiting.state, iss });
306
+ }
307
+ prune(codes, at);
308
+ const code = token(32);
309
+ codes.set(code, {
310
+ clientId: waiting.clientId,
311
+ redirectUri: waiting.redirectUri,
312
+ codeChallenge: waiting.codeChallenge,
313
+ expiresAt: at + CODE_MS,
314
+ });
315
+ return redirectWith(waiting.redirectUri, { code, state: waiting.state, iss });
316
+ }
317
+ async function tokenRequest(request) {
318
+ let body;
319
+ try {
320
+ body = await readBody(request);
321
+ }
322
+ catch {
323
+ return oauthError('invalid_request', 'The request body could not be read');
324
+ }
325
+ const clientId = body.client_id ?? '';
326
+ const client = store.getClient(clientId);
327
+ if (!client)
328
+ return oauthError('invalid_client', 'Unknown client', 401);
329
+ const tokens = (() => {
330
+ if (body.grant_type === 'authorization_code') {
331
+ const at = now();
332
+ prune(codes, at);
333
+ const issued = codes.get(body.code ?? '');
334
+ // A code works once, even when the exchange fails.
335
+ if (issued)
336
+ codes.delete(body.code ?? '');
337
+ if (!issued || issued.clientId !== clientId)
338
+ return oauthError('invalid_grant', 'The code is not valid');
339
+ if (body.redirect_uri !== undefined && body.redirect_uri !== issued.redirectUri) {
340
+ return oauthError('invalid_grant', 'redirect_uri does not match the authorization request');
341
+ }
342
+ if (!pkceMatches(body.code_verifier ?? '', issued.codeChallenge)) {
343
+ return oauthError('invalid_grant', 'The code verifier does not match');
344
+ }
345
+ if (!resourceIsOurs(body.resource ?? null))
346
+ return oauthError('invalid_target', 'The resource is not this MCP server');
347
+ return store.issueTokens(clientId, at);
348
+ }
349
+ if (body.grant_type === 'refresh_token') {
350
+ const refreshed = store.refreshTokens(clientId, body.refresh_token ?? '', now());
351
+ return refreshed ?? oauthError('invalid_grant', 'The refresh token is not valid');
352
+ }
353
+ return oauthError('unsupported_grant_type', 'Use authorization_code or refresh_token');
354
+ })();
355
+ if (tokens instanceof Response)
356
+ return tokens;
357
+ return json({
358
+ access_token: tokens.accessToken,
359
+ token_type: 'Bearer',
360
+ expires_in: tokens.expiresIn,
361
+ refresh_token: tokens.refreshToken,
362
+ scope: MCP_SCOPE,
363
+ }, 200, { pragma: 'no-cache' });
364
+ }
365
+ async function revoke(request) {
366
+ try {
367
+ const body = await readBody(request);
368
+ if (body.token)
369
+ store.revokeToken(body.token);
370
+ }
371
+ catch {
372
+ return oauthError('invalid_request', 'The request body could not be read');
373
+ }
374
+ return new Response(null, { status: 200, headers: { 'cache-control': 'no-store' } });
375
+ }
376
+ return {
377
+ async handle(request, peer) {
378
+ const { pathname } = new URL(request.url);
379
+ const method = request.method.toUpperCase();
380
+ const origin = originOf(request);
381
+ if (pathname === PROTECTED_RESOURCE_PATH || pathname === `${PROTECTED_RESOURCE_PATH}${MCP_PATH}`) {
382
+ return method === 'GET' ? json(protectedResourceMetadata(origin)) : undefined;
383
+ }
384
+ if (pathname === AUTHORIZATION_SERVER_PATH) {
385
+ return method === 'GET' ? json(authorizationServerMetadata(origin)) : undefined;
386
+ }
387
+ if (pathname === REGISTER_PATH && method === 'POST')
388
+ return register(request);
389
+ if (pathname === AUTHORIZE_PATH && method === 'GET')
390
+ return authorizeGet(request, peer);
391
+ if (pathname === AUTHORIZE_PATH && method === 'POST')
392
+ return authorizePost(request, peer);
393
+ if (pathname === TOKEN_PATH && method === 'POST')
394
+ return tokenRequest(request);
395
+ if (pathname === REVOKE_PATH && method === 'POST')
396
+ return revoke(request);
397
+ return undefined;
398
+ },
399
+ resourceMetadataUrl(request) {
400
+ return `${originOf(request)}${PROTECTED_RESOURCE_PATH}${MCP_PATH}`;
401
+ },
402
+ };
403
+ }
@@ -0,0 +1,42 @@
1
+ /** The one scope a token carries: drive the plans this service hosts. */
2
+ export declare const MCP_SCOPE = "plans";
3
+ export declare const ACCESS_TOKEN_SECONDS: number;
4
+ export declare const REFRESH_TOKEN_SECONDS: number;
5
+ export type OAuthClient = {
6
+ clientId: string;
7
+ clientName: string;
8
+ redirectUris: string[];
9
+ createdAt: number;
10
+ };
11
+ export type IssuedTokens = {
12
+ accessToken: string;
13
+ refreshToken: string;
14
+ expiresIn: number;
15
+ };
16
+ export type AccessGrant = {
17
+ clientId: string;
18
+ expiresAt: number;
19
+ };
20
+ export type GrantSummary = OAuthClient & {
21
+ lastIssuedAt: number | null;
22
+ live: boolean;
23
+ };
24
+ export type OAuthStore = {
25
+ registerClient(input: {
26
+ clientName: string;
27
+ redirectUris: string[];
28
+ }, now?: number): OAuthClient;
29
+ getClient(clientId: string): OAuthClient | null;
30
+ issueTokens(clientId: string, now?: number): IssuedTokens;
31
+ /** Trade a refresh token for new tokens. The old refresh token stops working. */
32
+ refreshTokens(clientId: string, refreshToken: string, now?: number): IssuedTokens | null;
33
+ verifyAccessToken(token: string, now?: number): AccessGrant | null;
34
+ revokeToken(token: string): void;
35
+ /** Agents that were allowed, newest first. */
36
+ listGrants(now?: number): GrantSummary[];
37
+ /** Drop every token, or one agent's tokens and its registration. Returns how many agents lost access. */
38
+ revoke(clientId?: string): number;
39
+ close(): void;
40
+ };
41
+ export declare function oauthDatabasePath(home: string): string;
42
+ export declare function openOAuthStore(path: string): OAuthStore;
@@ -0,0 +1,138 @@
1
+ import { createHash, randomBytes } from 'node:crypto';
2
+ import { join } from 'node:path';
3
+ import { openSqliteStore } from '../store/sqlite';
4
+ /** The one scope a token carries: drive the plans this service hosts. */
5
+ export const MCP_SCOPE = 'plans';
6
+ export const ACCESS_TOKEN_SECONDS = 60 * 60;
7
+ export const REFRESH_TOKEN_SECONDS = 30 * 24 * 60 * 60;
8
+ /** Registered agents kept at most. The oldest one with no live token goes first. */
9
+ const MAX_CLIENTS = 200;
10
+ export function oauthDatabasePath(home) {
11
+ return join(home, 'mcp-oauth.sqlite');
12
+ }
13
+ /** Tokens are stored as their SHA-256, so a copy of the database cannot be replayed. */
14
+ function digest(token) {
15
+ return createHash('sha256').update(token).digest('hex');
16
+ }
17
+ function secret(prefix) {
18
+ return `${prefix}${randomBytes(32).toString('base64url')}`;
19
+ }
20
+ function toClient(row) {
21
+ let redirectUris = [];
22
+ try {
23
+ const parsed = JSON.parse(row.redirect_uris);
24
+ if (Array.isArray(parsed))
25
+ redirectUris = parsed.filter((uri) => typeof uri === 'string');
26
+ }
27
+ catch {
28
+ redirectUris = [];
29
+ }
30
+ return { clientId: row.client_id, clientName: row.client_name, redirectUris, createdAt: row.created_at };
31
+ }
32
+ export function openOAuthStore(path) {
33
+ const db = openSqliteStore(path);
34
+ db.exec(`
35
+ CREATE TABLE IF NOT EXISTS oauth_clients (
36
+ client_id TEXT PRIMARY KEY,
37
+ client_name TEXT NOT NULL,
38
+ redirect_uris TEXT NOT NULL,
39
+ created_at INTEGER NOT NULL
40
+ );
41
+ CREATE TABLE IF NOT EXISTS oauth_tokens (
42
+ token_hash TEXT PRIMARY KEY,
43
+ kind TEXT NOT NULL CHECK (kind IN ('access', 'refresh')),
44
+ client_id TEXT NOT NULL,
45
+ expires_at INTEGER NOT NULL,
46
+ created_at INTEGER NOT NULL
47
+ );
48
+ CREATE INDEX IF NOT EXISTS oauth_tokens_client ON oauth_tokens (client_id);
49
+ `);
50
+ function pruneExpired(now) {
51
+ db.prepare('DELETE FROM oauth_tokens WHERE expires_at <= ?').run(now);
52
+ }
53
+ function pruneClients() {
54
+ const count = db.prepare('SELECT COUNT(*) AS n FROM oauth_clients').get()?.n ?? 0;
55
+ if (count < MAX_CLIENTS)
56
+ return;
57
+ db.prepare(`DELETE FROM oauth_clients WHERE client_id IN (
58
+ SELECT client_id FROM oauth_clients
59
+ WHERE client_id NOT IN (SELECT client_id FROM oauth_tokens)
60
+ ORDER BY created_at ASC LIMIT ?
61
+ )`).run(count - MAX_CLIENTS + 1);
62
+ }
63
+ function issueTokens(clientId, now = Date.now()) {
64
+ const accessToken = secret('lpa_');
65
+ const refreshToken = secret('lpr_');
66
+ const insert = db.prepare('INSERT INTO oauth_tokens (token_hash, kind, client_id, expires_at, created_at) VALUES (?, ?, ?, ?, ?)');
67
+ db.transaction(() => {
68
+ insert.run(digest(accessToken), 'access', clientId, now + ACCESS_TOKEN_SECONDS * 1000, now);
69
+ insert.run(digest(refreshToken), 'refresh', clientId, now + REFRESH_TOKEN_SECONDS * 1000, now);
70
+ });
71
+ return { accessToken, refreshToken, expiresIn: ACCESS_TOKEN_SECONDS };
72
+ }
73
+ return {
74
+ registerClient(input, now = Date.now()) {
75
+ pruneClients();
76
+ const client = {
77
+ clientId: `lpc_${randomBytes(16).toString('hex')}`,
78
+ clientName: input.clientName,
79
+ redirectUris: input.redirectUris,
80
+ createdAt: now,
81
+ };
82
+ db.prepare('INSERT INTO oauth_clients (client_id, client_name, redirect_uris, created_at) VALUES (?, ?, ?, ?)').run(client.clientId, client.clientName, JSON.stringify(client.redirectUris), client.createdAt);
83
+ return client;
84
+ },
85
+ getClient(clientId) {
86
+ const row = db.prepare('SELECT * FROM oauth_clients WHERE client_id = ?').get(clientId);
87
+ return row ? toClient(row) : null;
88
+ },
89
+ issueTokens,
90
+ refreshTokens(clientId, refreshToken, now = Date.now()) {
91
+ pruneExpired(now);
92
+ const hash = digest(refreshToken);
93
+ const row = db
94
+ .prepare("SELECT client_id FROM oauth_tokens WHERE token_hash = ? AND kind = 'refresh' AND expires_at > ?")
95
+ .get(hash, now);
96
+ if (!row || row.client_id !== clientId)
97
+ return null;
98
+ db.prepare('DELETE FROM oauth_tokens WHERE token_hash = ?').run(hash);
99
+ return issueTokens(clientId, now);
100
+ },
101
+ verifyAccessToken(token, now = Date.now()) {
102
+ const row = db
103
+ .prepare("SELECT client_id, expires_at FROM oauth_tokens WHERE token_hash = ? AND kind = 'access'")
104
+ .get(digest(token));
105
+ if (!row || row.expires_at <= now)
106
+ return null;
107
+ return { clientId: row.client_id, expiresAt: row.expires_at };
108
+ },
109
+ revokeToken(token) {
110
+ db.prepare('DELETE FROM oauth_tokens WHERE token_hash = ?').run(digest(token));
111
+ },
112
+ listGrants(now = Date.now()) {
113
+ pruneExpired(now);
114
+ const rows = db
115
+ .prepare(`SELECT c.*, MAX(t.created_at) AS last_issued_at, COUNT(t.token_hash) AS live
116
+ FROM oauth_clients c JOIN oauth_tokens t ON t.client_id = c.client_id
117
+ GROUP BY c.client_id ORDER BY last_issued_at DESC`)
118
+ .all();
119
+ return rows.map((row) => ({ ...toClient(row), lastIssuedAt: row.last_issued_at, live: row.live > 0 }));
120
+ },
121
+ revoke(clientId) {
122
+ if (clientId) {
123
+ const known = db.prepare('SELECT client_id FROM oauth_clients WHERE client_id = ?').get(clientId);
124
+ db.transaction(() => {
125
+ db.prepare('DELETE FROM oauth_tokens WHERE client_id = ?').run(clientId);
126
+ db.prepare('DELETE FROM oauth_clients WHERE client_id = ?').run(clientId);
127
+ });
128
+ return known ? 1 : 0;
129
+ }
130
+ const count = db.prepare('SELECT COUNT(DISTINCT client_id) AS n FROM oauth_tokens').get()?.n ?? 0;
131
+ db.prepare('DELETE FROM oauth_tokens').run();
132
+ return count;
133
+ },
134
+ close() {
135
+ db.close();
136
+ },
137
+ };
138
+ }
@@ -0,0 +1,27 @@
1
+ import { McpServer } from '@modelcontextprotocol/server';
2
+ import type { PlanHost } from '../planHost';
3
+ import type { PlanSession } from '../planSession';
4
+ import type { PlanSubmissionEvent } from '../types';
5
+ /** How long `wait_for_events` waits by default, and at most. */
6
+ export declare const DEFAULT_WAIT_SECONDS = 300;
7
+ export declare const MAX_WAIT_SECONDS = 3600;
8
+ export declare const SERVER_INSTRUCTIONS = "Living Plan shows a plan file you write as a page a person reads and answers.\n\n1. Write the plan as a .plan.md file (the live-plan skill has the format) and call check_plan.\n2. Call serve_plan. The page opens for the person.\n3. Call wait_for_events, again and again. Each call returns what the person submitted: answers (interaction), comments (comment), and verdicts (review). An empty list means nothing came in yet; call it again.\n4. Answer each comment with reply_to_comment. Edit the plan file to show progress; the page updates by itself.\n5. Call set_mode with review when you need the person to approve, deny, or ask for another iteration.\n6. Call close_plan when the work is done.\n\nEvery tool takes the plan file's absolute path.";
9
+ export type PlanToolOptions = {
10
+ planHost: PlanHost;
11
+ /** The page URL of a hosted plan. */
12
+ planUrl: (id: string) => string;
13
+ /** Open a newly served page for the person. */
14
+ openPage: (url: string) => Promise<void>;
15
+ version: string;
16
+ };
17
+ /**
18
+ * Wait until the person submits something, the timeout passes, or the call is cancelled. While it
19
+ * waits, the page shows an agent connected. Submissions that reach a call still open are marked
20
+ * delivered; a cancelled call leaves them queued for the next one.
21
+ */
22
+ export declare function waitForSubmissions(session: PlanSession, timeoutMs: number, signal: AbortSignal, onTick?: (elapsedMs: number) => void): Promise<{
23
+ events: PlanSubmissionEvent[];
24
+ closed: boolean;
25
+ }>;
26
+ /** One MCP server instance with the six plan tools. The handler builds one per request. */
27
+ export declare function createPlanToolServer(options: PlanToolOptions): McpServer;