@aisocialautomate/mcp 0.0.0-stage → 0.2.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/dist/oauth.js ADDED
@@ -0,0 +1,339 @@
1
+ /**
2
+ * OAuth 2.1 for the hosted MCP server, so Claude, ChatGPT and other directory clients can connect with a normal
3
+ * "sign in and allow" flow instead of a pasted key.
4
+ *
5
+ * Stateless by design: client ids, authorization codes and tokens are AES-256-GCM sealed blobs that only this server can
6
+ * open, so nothing is stored except the short-lived pending sign-in requests in memory. The token carries the user's own
7
+ * API key (created by the dashboard when the user clicks Allow), so every call is still charged and scoped by that key
8
+ * and revoking the key in the dashboard cuts the connection off.
9
+ *
10
+ * client ─ /oauth/register ─▶ client_id (sealed)
11
+ * client ─ /oauth/authorize ─▶ redirect to the dashboard consent page (user signs in, clicks Allow)
12
+ * dashboard ─ POST /oauth/complete {request, key} ─▶ redirect back to the client with ?code=
13
+ * client ─ /oauth/token (PKCE) ─▶ access + refresh token
14
+ */
15
+ import { createCipheriv, createDecipheriv, createHash, createHmac, hkdfSync, randomBytes, timingSafeEqual } from 'node:crypto';
16
+ const ACCESS_TTL_S = 3600;
17
+ const REFRESH_TTL_S = 90 * 24 * 3600;
18
+ const CODE_TTL_S = 300;
19
+ const PENDING_TTL_MS = 10 * 60_000;
20
+ const MAX_FORM = 16_384;
21
+ const b64 = (b) => b.toString('base64url');
22
+ const nowS = () => Math.floor(Date.now() / 1000);
23
+ class Sealer {
24
+ enc;
25
+ mac;
26
+ constructor(secret) {
27
+ this.enc = Buffer.from(hkdfSync('sha256', secret, 'aisocialautomate-mcp', 'enc', 32));
28
+ this.mac = Buffer.from(hkdfSync('sha256', secret, 'aisocialautomate-mcp', 'mac', 32));
29
+ }
30
+ seal(obj) {
31
+ const iv = randomBytes(12);
32
+ const c = createCipheriv('aes-256-gcm', this.enc, iv);
33
+ const ct = Buffer.concat([c.update(JSON.stringify(obj), 'utf8'), c.final()]);
34
+ return b64(Buffer.concat([iv, c.getAuthTag(), ct]));
35
+ }
36
+ open(blob) {
37
+ try {
38
+ const raw = Buffer.from(blob, 'base64url');
39
+ if (raw.length < 29)
40
+ return null;
41
+ const d = createDecipheriv('aes-256-gcm', this.enc, raw.subarray(0, 12));
42
+ d.setAuthTag(raw.subarray(12, 28));
43
+ return JSON.parse(Buffer.concat([d.update(raw.subarray(28)), d.final()]).toString('utf8'));
44
+ }
45
+ catch {
46
+ return null;
47
+ }
48
+ }
49
+ /** Client ids are public, so they are signed rather than sealed. */
50
+ sign(obj) {
51
+ const body = b64(Buffer.from(JSON.stringify(obj)));
52
+ return `${body}.${b64(createHmac('sha256', this.mac).update(body).digest())}`;
53
+ }
54
+ verify(s) {
55
+ const [body, sig] = s.split('.');
56
+ if (!body || !sig)
57
+ return null;
58
+ const want = createHmac('sha256', this.mac).update(body).digest();
59
+ let got;
60
+ try {
61
+ got = Buffer.from(sig, 'base64url');
62
+ }
63
+ catch {
64
+ return null;
65
+ }
66
+ if (got.length !== want.length || !timingSafeEqual(got, want))
67
+ return null;
68
+ try {
69
+ return JSON.parse(Buffer.from(body, 'base64url').toString('utf8'));
70
+ }
71
+ catch {
72
+ return null;
73
+ }
74
+ }
75
+ }
76
+ const json = (res, status, body, headers = {}) => {
77
+ res.writeHead(status, { 'content-type': 'application/json', 'cache-control': 'no-store', ...headers });
78
+ res.end(JSON.stringify(body));
79
+ };
80
+ const oauthErr = (res, status, error, description, headers = {}) => json(res, status, { error, error_description: description }, headers);
81
+ async function readBody(req) {
82
+ const chunks = [];
83
+ let size = 0;
84
+ for await (const c of req) {
85
+ size += c.length;
86
+ if (size > MAX_FORM)
87
+ throw new Error('too large');
88
+ chunks.push(c);
89
+ }
90
+ return Buffer.concat(chunks).toString('utf8');
91
+ }
92
+ /** https, or http on a loopback address (local tools such as Claude Code). No fragments. */
93
+ export function validRedirect(u) {
94
+ try {
95
+ const url = new URL(u);
96
+ if (url.hash)
97
+ return false;
98
+ if (url.protocol === 'https:')
99
+ return true;
100
+ return url.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(url.hostname);
101
+ }
102
+ catch {
103
+ return false;
104
+ }
105
+ }
106
+ /** Loopback redirects may use any port. */
107
+ const sameRedirect = (registered, given) => {
108
+ if (registered === given)
109
+ return true;
110
+ try {
111
+ const a = new URL(registered), b = new URL(given);
112
+ return a.protocol === 'http:' && ['localhost', '127.0.0.1', '[::1]'].includes(a.hostname) && a.hostname === b.hostname && a.protocol === b.protocol && a.pathname === b.pathname && a.search === b.search;
113
+ }
114
+ catch {
115
+ return false;
116
+ }
117
+ };
118
+ export function createOAuth(env, fetchImpl = fetch) {
119
+ const secret = env.MCP_OAUTH_SECRET ?? '';
120
+ const publicUrl = (env.MCP_PUBLIC_URL ?? '').replace(/\/+$/, '');
121
+ const consentOrigin = (env.MCP_CONSENT_ORIGIN ?? 'https://aisocialautomate.com').replace(/\/+$/, '');
122
+ const apiBase = (env.SOCIAL_AUTOMATE_API_URL || 'https://aisocialautomate.com/api/v1').replace(/\/+$/, '');
123
+ const enabled = secret.length >= 32 && /^https:\/\//.test(publicUrl);
124
+ const metadataUrl = `${publicUrl}/.well-known/oauth-protected-resource`;
125
+ if (!enabled)
126
+ return { enabled: false, metadataUrl, handle: async () => false, resolveToken: () => null };
127
+ const sealer = new Sealer(secret);
128
+ const pending = new Map();
129
+ const usedCodes = new Map();
130
+ const prune = () => {
131
+ const t = Date.now();
132
+ for (const [k, v] of pending)
133
+ if (v.exp < t)
134
+ pending.delete(k);
135
+ for (const [k, v] of usedCodes)
136
+ if (v < t)
137
+ usedCodes.delete(k);
138
+ };
139
+ const protectedResource = { resource: `${publicUrl}/mcp`, authorization_servers: [publicUrl], bearer_methods_supported: ['header'], scopes_supported: ['mcp'], resource_name: 'AI Social Automate' };
140
+ const authServer = {
141
+ issuer: publicUrl, authorization_endpoint: `${publicUrl}/oauth/authorize`, token_endpoint: `${publicUrl}/oauth/token`, registration_endpoint: `${publicUrl}/oauth/register`,
142
+ response_types_supported: ['code'], grant_types_supported: ['authorization_code', 'refresh_token'], code_challenge_methods_supported: ['S256'],
143
+ token_endpoint_auth_methods_supported: ['none'], scopes_supported: ['mcp'],
144
+ };
145
+ const cors = (req) => req.headers.origin === consentOrigin
146
+ ? { 'access-control-allow-origin': consentOrigin, 'access-control-allow-headers': 'content-type', 'access-control-allow-methods': 'GET, POST, OPTIONS', vary: 'Origin' }
147
+ : {};
148
+ const client = (cid) => { const c = sealer.verify(cid); return c && Array.isArray(c.r) ? c : null; };
149
+ const issue = (key, cid) => {
150
+ const access = 'mcp_at_' + sealer.seal({ k: key, t: 'a', exp: nowS() + ACCESS_TTL_S });
151
+ const refresh = 'mcp_rt_' + sealer.seal({ k: key, t: 'r', cid, exp: nowS() + REFRESH_TTL_S });
152
+ return { access_token: access, token_type: 'Bearer', expires_in: ACCESS_TTL_S, refresh_token: refresh, scope: 'mcp' };
153
+ };
154
+ async function keyIsValid(key) {
155
+ try {
156
+ const r = await fetchImpl(`${apiBase}/api-keys/self`, { headers: { Authorization: `ApiKey ${key}`, Accept: 'application/json' }, signal: AbortSignal.timeout(10_000) });
157
+ return r.ok;
158
+ }
159
+ catch {
160
+ return false;
161
+ }
162
+ }
163
+ return {
164
+ enabled, metadataUrl,
165
+ resolveToken(token) {
166
+ if (!token.startsWith('mcp_at_'))
167
+ return null;
168
+ const t = sealer.open(token.slice(7));
169
+ return t && t.t === 'a' && t.exp > nowS() && typeof t.k === 'string' ? t.k : null;
170
+ },
171
+ async handle(req, res, path, ip) {
172
+ void ip;
173
+ if (path === '/.well-known/oauth-protected-resource' || path === '/.well-known/oauth-protected-resource/mcp') {
174
+ json(res, 200, protectedResource, { 'cache-control': 'public, max-age=300' });
175
+ return true;
176
+ }
177
+ if (path === '/.well-known/oauth-authorization-server' || path === '/.well-known/openid-configuration') {
178
+ json(res, 200, authServer, { 'cache-control': 'public, max-age=300' });
179
+ return true;
180
+ }
181
+ if (!path.startsWith('/oauth/'))
182
+ return false;
183
+ prune();
184
+ const url = new URL(req.url ?? '', publicUrl);
185
+ if (req.method === 'OPTIONS') {
186
+ res.writeHead(204, cors(req)).end();
187
+ return true;
188
+ }
189
+ if (path === '/oauth/register' && req.method === 'POST') {
190
+ let body;
191
+ try {
192
+ body = JSON.parse(await readBody(req));
193
+ }
194
+ catch {
195
+ oauthErr(res, 400, 'invalid_client_metadata', 'Send JSON.');
196
+ return true;
197
+ }
198
+ const uris = Array.isArray(body?.redirect_uris) ? body.redirect_uris.map(String) : [];
199
+ if (!uris.length || uris.length > 10 || !uris.every(validRedirect)) {
200
+ oauthErr(res, 400, 'invalid_redirect_uri', 'redirect_uris must be 1 to 10 https links (or http on localhost).');
201
+ return true;
202
+ }
203
+ const name = String(body?.client_name ?? 'MCP client').replace(/[\u0000-\u001f<>]/g, '').slice(0, 80) || 'MCP client';
204
+ const cid = sealer.sign({ n: name, r: uris, iat: nowS() });
205
+ json(res, 201, { client_id: cid, client_name: name, redirect_uris: uris, grant_types: ['authorization_code', 'refresh_token'], response_types: ['code'], token_endpoint_auth_method: 'none', client_id_issued_at: nowS() });
206
+ return true;
207
+ }
208
+ if (path === '/oauth/authorize' && req.method === 'GET') {
209
+ const q = url.searchParams;
210
+ const c = client(q.get('client_id') ?? '');
211
+ const ru = q.get('redirect_uri') ?? '';
212
+ // Without a known client and an exact redirect we cannot safely redirect anywhere, so show the error here.
213
+ if (!c) {
214
+ oauthErr(res, 400, 'invalid_client', 'Unknown client_id.');
215
+ return true;
216
+ }
217
+ const reg = c.r.find(r => sameRedirect(r, ru));
218
+ if (!reg) {
219
+ oauthErr(res, 400, 'invalid_request', 'redirect_uri does not match the registered one.');
220
+ return true;
221
+ }
222
+ const back = (error, desc) => { const u = new URL(ru); u.searchParams.set('error', error); u.searchParams.set('error_description', desc); if (q.get('state'))
223
+ u.searchParams.set('state', q.get('state')); res.writeHead(302, { location: u.toString() }).end(); };
224
+ if (q.get('response_type') !== 'code')
225
+ return back('unsupported_response_type', 'Only response_type=code is supported.'), true;
226
+ const ch = q.get('code_challenge') ?? '';
227
+ if (q.get('code_challenge_method') !== 'S256' || !/^[A-Za-z0-9_-]{43,128}$/.test(ch))
228
+ return back('invalid_request', 'PKCE with code_challenge_method=S256 is required.'), true;
229
+ if (pending.size > 5000)
230
+ return back('temporarily_unavailable', 'Too many sign-ins in progress. Try again shortly.'), true;
231
+ const id = b64(randomBytes(24));
232
+ pending.set(id, { cid: q.get('client_id'), name: c.n, ru, state: q.get('state') ?? '', ch, exp: Date.now() + PENDING_TTL_MS });
233
+ res.writeHead(302, { location: `${consentOrigin}/authorize-assistant?request=${encodeURIComponent(id)}`, 'cache-control': 'no-store' }).end();
234
+ return true;
235
+ }
236
+ // What the consent page shows: who is asking and where they will be sent back.
237
+ if (path === '/oauth/request' && req.method === 'GET') {
238
+ const p = pending.get(url.searchParams.get('id') ?? '');
239
+ if (!p) {
240
+ json(res, 404, { error: 'expired' }, cors(req));
241
+ return true;
242
+ }
243
+ let host = '';
244
+ try {
245
+ host = new URL(p.ru).host;
246
+ }
247
+ catch { /* ignore */ }
248
+ json(res, 200, { client_name: p.name, redirect_host: host }, cors(req));
249
+ return true;
250
+ }
251
+ if (path === '/oauth/complete' && req.method === 'POST') {
252
+ const h = cors(req);
253
+ if (!h['access-control-allow-origin']) {
254
+ json(res, 403, { error: 'forbidden' });
255
+ return true;
256
+ }
257
+ let body;
258
+ try {
259
+ body = JSON.parse(await readBody(req));
260
+ }
261
+ catch {
262
+ json(res, 400, { error: 'invalid_request' }, h);
263
+ return true;
264
+ }
265
+ const p = pending.get(String(body?.request ?? ''));
266
+ if (!p) {
267
+ json(res, 404, { error: 'expired', message: 'This sign-in link expired. Start again from your assistant.' }, h);
268
+ return true;
269
+ }
270
+ pending.delete(String(body.request));
271
+ const u = new URL(p.ru);
272
+ if (p.state)
273
+ u.searchParams.set('state', p.state);
274
+ if (body?.deny) {
275
+ u.searchParams.set('error', 'access_denied');
276
+ json(res, 200, { redirect: u.toString() }, h);
277
+ return true;
278
+ }
279
+ const key = String(body?.key ?? '');
280
+ if (!key.startsWith('sk_') || !(await keyIsValid(key))) {
281
+ json(res, 400, { error: 'invalid_key', message: 'The access key was not accepted.' }, h);
282
+ return true;
283
+ }
284
+ const jti = b64(randomBytes(12));
285
+ u.searchParams.set('code', sealer.seal({ k: key, cid: p.cid, ru: p.ru, ch: p.ch, jti, exp: nowS() + CODE_TTL_S }));
286
+ json(res, 200, { redirect: u.toString() }, h);
287
+ return true;
288
+ }
289
+ if (path === '/oauth/token' && req.method === 'POST') {
290
+ let f;
291
+ try {
292
+ f = new URLSearchParams(await readBody(req));
293
+ }
294
+ catch {
295
+ oauthErr(res, 400, 'invalid_request', 'Body too large.');
296
+ return true;
297
+ }
298
+ const grant = f.get('grant_type');
299
+ if (grant === 'authorization_code') {
300
+ const c = sealer.open(f.get('code') ?? '');
301
+ if (!c || c.exp < nowS() || usedCodes.has(c.jti)) {
302
+ oauthErr(res, 400, 'invalid_grant', 'The code is invalid, expired or already used.');
303
+ return true;
304
+ }
305
+ usedCodes.set(c.jti, Date.now() + CODE_TTL_S * 1000);
306
+ if (f.get('client_id') !== c.cid || !sameRedirect(c.ru, f.get('redirect_uri') ?? '')) {
307
+ oauthErr(res, 400, 'invalid_grant', 'client_id or redirect_uri does not match.');
308
+ return true;
309
+ }
310
+ const ver = f.get('code_verifier') ?? '';
311
+ const calc = createHash('sha256').update(ver).digest('base64url');
312
+ if (!/^[A-Za-z0-9._~-]{43,128}$/.test(ver) || calc !== c.ch) {
313
+ oauthErr(res, 400, 'invalid_grant', 'PKCE verification failed.');
314
+ return true;
315
+ }
316
+ json(res, 200, issue(c.k, c.cid));
317
+ return true;
318
+ }
319
+ if (grant === 'refresh_token') {
320
+ const t = (f.get('refresh_token') ?? '').startsWith('mcp_rt_') ? sealer.open(f.get('refresh_token').slice(7)) : null;
321
+ if (!t || t.t !== 'r' || t.exp < nowS() || (f.get('client_id') && f.get('client_id') !== t.cid)) {
322
+ oauthErr(res, 400, 'invalid_grant', 'The refresh token is invalid or expired. Sign in again.');
323
+ return true;
324
+ }
325
+ if (!(await keyIsValid(t.k))) {
326
+ oauthErr(res, 400, 'invalid_grant', 'Access was revoked. Sign in again.');
327
+ return true;
328
+ }
329
+ json(res, 200, issue(t.k, t.cid));
330
+ return true;
331
+ }
332
+ oauthErr(res, 400, 'unsupported_grant_type', 'Use authorization_code or refresh_token.');
333
+ return true;
334
+ }
335
+ json(res, 404, { error: 'not_found' });
336
+ return true;
337
+ },
338
+ };
339
+ }