@profullstack/board-saas 0.1.1 → 0.2.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.
- package/README.md +33 -4
- package/package.json +1 -1
- package/public/index.html +10 -10
- package/src/cli.js +45 -6
- package/src/client.js +86 -4
- package/src/db.js +6 -2
- package/src/mcp-stdio.js +4 -1
- package/src/mcp.js +46 -5
- package/src/meeting.js +12 -0
- package/src/oauth-pages.js +94 -0
- package/src/oauth.js +561 -0
- package/src/server.js +192 -14
- package/src/service.js +16 -9
package/src/oauth.js
ADDED
|
@@ -0,0 +1,561 @@
|
|
|
1
|
+
// OAuth 2.1 authorization server for board.saas, so any OAuth client can act for an
|
|
2
|
+
// account: Claude / ChatGPT connectors and `claude mcp add` (MCP authorization spec), our
|
|
3
|
+
// own CLI (device flow) and any other app (authorization code + PKCE).
|
|
4
|
+
//
|
|
5
|
+
// RFC 9728 protected resource metadata /.well-known/oauth-protected-resource[/mcp|/api/v1]
|
|
6
|
+
// RFC 8414 authorization server metadata /.well-known/oauth-authorization-server
|
|
7
|
+
// RFC 7591 dynamic client registration POST /oauth/register (and POST /register)
|
|
8
|
+
// OAuth 2.1 authorization code + S256 PKCE, iss on every redirect (RFC 9207)
|
|
9
|
+
// RFC 8628 device authorization grant POST /oauth/device_authorization, page /oauth/device
|
|
10
|
+
// RFC 7009 token revocation POST /oauth/revoke
|
|
11
|
+
// RFC 8707 resource indicators (accepted, must name this server)
|
|
12
|
+
//
|
|
13
|
+
// Tokens are opaque and stored as sha256: access `bso_` (1 hour), refresh `bsr_` (90 days,
|
|
14
|
+
// rotated on every use; presenting a rotated one revokes the whole family). One scope,
|
|
15
|
+
// `board`: run, read, list and clarify the account's meetings. Clients that ask for no
|
|
16
|
+
// scope (connectors never do) get `board` and always get a refresh token.
|
|
17
|
+
import { createHash, randomBytes, randomInt, timingSafeEqual } from 'node:crypto';
|
|
18
|
+
import { newId, sha256 } from './db.js';
|
|
19
|
+
import { HttpError, normalizeEmail } from './service.js';
|
|
20
|
+
|
|
21
|
+
export const SCOPE = 'board';
|
|
22
|
+
export const CLI_CLIENT_ID = 'board-saas-cli';
|
|
23
|
+
const DEVICE_GRANT = 'urn:ietf:params:oauth:grant-type:device_code';
|
|
24
|
+
const ACCESS_TTL = 3600;
|
|
25
|
+
const REFRESH_TTL = 90 * 86400;
|
|
26
|
+
const CODE_TTL = 300;
|
|
27
|
+
const DEVICE_TTL = 900;
|
|
28
|
+
const SESSION_TTL = 7 * 86400;
|
|
29
|
+
const USER_CODE_ALPHABET = 'BCDFGHJKLMNPQRSTVWXZ';
|
|
30
|
+
|
|
31
|
+
const SCHEMA = `
|
|
32
|
+
create table if not exists oauth_clients (
|
|
33
|
+
client_id text primary key,
|
|
34
|
+
secret_hash text,
|
|
35
|
+
name text not null,
|
|
36
|
+
redirect_uris text not null,
|
|
37
|
+
grant_types text not null,
|
|
38
|
+
auth_method text not null,
|
|
39
|
+
dynamic integer not null default 0,
|
|
40
|
+
created_ip text,
|
|
41
|
+
created_at integer not null
|
|
42
|
+
);
|
|
43
|
+
create table if not exists oauth_codes (
|
|
44
|
+
code_hash text primary key,
|
|
45
|
+
client_id text not null,
|
|
46
|
+
account_id text not null,
|
|
47
|
+
redirect_uri text not null,
|
|
48
|
+
challenge text not null,
|
|
49
|
+
scope text not null,
|
|
50
|
+
resource text,
|
|
51
|
+
expires_at integer not null
|
|
52
|
+
);
|
|
53
|
+
create table if not exists oauth_tokens (
|
|
54
|
+
token_hash text primary key,
|
|
55
|
+
kind text not null,
|
|
56
|
+
client_id text not null,
|
|
57
|
+
account_id text not null,
|
|
58
|
+
scope text not null,
|
|
59
|
+
family text not null,
|
|
60
|
+
expires_at integer not null,
|
|
61
|
+
used integer not null default 0,
|
|
62
|
+
revoked integer not null default 0,
|
|
63
|
+
created_at integer not null
|
|
64
|
+
);
|
|
65
|
+
create index if not exists oauth_tokens_family on oauth_tokens(family);
|
|
66
|
+
create index if not exists oauth_tokens_account on oauth_tokens(account_id, kind);
|
|
67
|
+
create table if not exists oauth_devices (
|
|
68
|
+
device_hash text primary key,
|
|
69
|
+
user_code text not null unique,
|
|
70
|
+
client_id text not null,
|
|
71
|
+
scope text not null,
|
|
72
|
+
account_id text,
|
|
73
|
+
status text not null default 'pending',
|
|
74
|
+
interval_s integer not null default 5,
|
|
75
|
+
last_poll integer not null default 0,
|
|
76
|
+
expires_at integer not null
|
|
77
|
+
);
|
|
78
|
+
create table if not exists web_sessions (
|
|
79
|
+
sid_hash text primary key,
|
|
80
|
+
account_id text not null,
|
|
81
|
+
csrf text not null,
|
|
82
|
+
expires_at integer not null
|
|
83
|
+
);
|
|
84
|
+
`;
|
|
85
|
+
|
|
86
|
+
const now = () => Date.now();
|
|
87
|
+
const sec = () => Math.floor(Date.now() / 1000);
|
|
88
|
+
const token = (prefix) => `${prefix}${randomBytes(32).toString('base64url')}`;
|
|
89
|
+
const b64url = (buf) => Buffer.from(buf).toString('base64url');
|
|
90
|
+
|
|
91
|
+
function safeEqual(a, b) {
|
|
92
|
+
const x = Buffer.from(String(a));
|
|
93
|
+
const y = Buffer.from(String(b));
|
|
94
|
+
return x.length === y.length && timingSafeEqual(x, y);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** OAuth error as JSON (token, register, revoke, device endpoints). */
|
|
98
|
+
export class OAuthError extends Error {
|
|
99
|
+
constructor(code, description, status = 400) {
|
|
100
|
+
super(description);
|
|
101
|
+
this.code = code;
|
|
102
|
+
this.status = status;
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
const isLoopback = (u) => u.protocol === 'http:' && ['127.0.0.1', 'localhost', '[::1]'].includes(u.hostname);
|
|
107
|
+
|
|
108
|
+
/** A redirect URI a client may register: https anywhere, http only on loopback, or a native app scheme. No fragments. */
|
|
109
|
+
function checkRedirect(raw) {
|
|
110
|
+
let u;
|
|
111
|
+
try {
|
|
112
|
+
u = new URL(String(raw));
|
|
113
|
+
} catch {
|
|
114
|
+
throw new OAuthError('invalid_redirect_uri', `not a URL: ${raw}`);
|
|
115
|
+
}
|
|
116
|
+
if (u.hash) throw new OAuthError('invalid_redirect_uri', 'redirect URIs may not have a fragment');
|
|
117
|
+
if (u.protocol === 'https:' || isLoopback(u)) return u.href;
|
|
118
|
+
if (/^[a-z][a-z0-9+.-]*\.[a-z0-9+.-]+:$/.test(u.protocol)) return u.href; // reverse-DNS app scheme (RFC 8252)
|
|
119
|
+
throw new OAuthError('invalid_redirect_uri', 'redirect URIs must be https, http on a loopback address, or a reverse-DNS app scheme');
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
/** Exact match, except a loopback redirect may use any port (RFC 8252 7.3). */
|
|
123
|
+
function redirectMatches(registered, given) {
|
|
124
|
+
if (registered.includes(given)) return true;
|
|
125
|
+
let g;
|
|
126
|
+
try {
|
|
127
|
+
g = new URL(given);
|
|
128
|
+
} catch {
|
|
129
|
+
return false;
|
|
130
|
+
}
|
|
131
|
+
if (!isLoopback(g)) return false;
|
|
132
|
+
return registered.some((r) => {
|
|
133
|
+
const u = new URL(r);
|
|
134
|
+
return isLoopback(u) && u.hostname === g.hostname && u.pathname === g.pathname && u.search === g.search;
|
|
135
|
+
});
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
export function createOAuth({ db, publicUrl, log = () => {} }) {
|
|
139
|
+
const raw = db.raw;
|
|
140
|
+
raw.exec(SCHEMA);
|
|
141
|
+
const get = (sql, ...a) => raw.prepare(sql).get(...a);
|
|
142
|
+
const all = (sql, ...a) => raw.prepare(sql).all(...a);
|
|
143
|
+
const run = (sql, ...a) => raw.prepare(sql).run(...a);
|
|
144
|
+
const issuer = publicUrl;
|
|
145
|
+
const mcpResource = `${publicUrl}/mcp`;
|
|
146
|
+
const apiResource = `${publicUrl}/api/v1`;
|
|
147
|
+
const secureCookie = publicUrl.startsWith('https:');
|
|
148
|
+
const limits = new Map();
|
|
149
|
+
|
|
150
|
+
// Our own CLI is a pre-registered public client: device flow plus loopback redirects.
|
|
151
|
+
run(
|
|
152
|
+
`insert into oauth_clients (client_id, secret_hash, name, redirect_uris, grant_types, auth_method, dynamic, created_at)
|
|
153
|
+
values (?, null, ?, ?, ?, 'none', 0, ?) on conflict(client_id) do update set name = excluded.name, redirect_uris = excluded.redirect_uris, grant_types = excluded.grant_types`,
|
|
154
|
+
CLI_CLIENT_ID,
|
|
155
|
+
'board-saas CLI',
|
|
156
|
+
JSON.stringify(['http://127.0.0.1/callback', 'http://localhost/callback']),
|
|
157
|
+
JSON.stringify(['authorization_code', 'refresh_token', DEVICE_GRANT]),
|
|
158
|
+
now(),
|
|
159
|
+
);
|
|
160
|
+
|
|
161
|
+
function limit(key, max, windowMs = 3_600_000) {
|
|
162
|
+
const k = `${key}:${Math.floor(now() / windowMs)}`;
|
|
163
|
+
const n = (limits.get(k) ?? 0) + 1;
|
|
164
|
+
limits.set(k, n);
|
|
165
|
+
if (limits.size > 10_000) limits.clear();
|
|
166
|
+
if (n > max) throw new OAuthError('slow_down', 'too many requests from this address; try again later', 429);
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
function sweep() {
|
|
170
|
+
if (Math.random() > 0.05) return;
|
|
171
|
+
const t = now();
|
|
172
|
+
run('delete from oauth_codes where expires_at < ?', t);
|
|
173
|
+
run('delete from oauth_devices where expires_at < ?', t - 3_600_000);
|
|
174
|
+
run('delete from oauth_tokens where expires_at < ?', t - 86_400_000);
|
|
175
|
+
run('delete from web_sessions where expires_at < ?', t);
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
// ------------------------------------------------------------- metadata
|
|
179
|
+
|
|
180
|
+
function resourceMetadata(which = 'mcp') {
|
|
181
|
+
return {
|
|
182
|
+
resource: which === 'api' ? apiResource : mcpResource,
|
|
183
|
+
authorization_servers: [issuer],
|
|
184
|
+
scopes_supported: [SCOPE],
|
|
185
|
+
bearer_methods_supported: ['header'],
|
|
186
|
+
resource_name: which === 'api' ? 'Board as a Service API' : 'Board as a Service MCP',
|
|
187
|
+
resource_documentation: `${publicUrl}/api/v1`,
|
|
188
|
+
};
|
|
189
|
+
}
|
|
190
|
+
|
|
191
|
+
function serverMetadata() {
|
|
192
|
+
return {
|
|
193
|
+
issuer,
|
|
194
|
+
authorization_endpoint: `${issuer}/oauth/authorize`,
|
|
195
|
+
token_endpoint: `${issuer}/oauth/token`,
|
|
196
|
+
registration_endpoint: `${issuer}/oauth/register`,
|
|
197
|
+
revocation_endpoint: `${issuer}/oauth/revoke`,
|
|
198
|
+
device_authorization_endpoint: `${issuer}/oauth/device_authorization`,
|
|
199
|
+
scopes_supported: [SCOPE],
|
|
200
|
+
response_types_supported: ['code'],
|
|
201
|
+
response_modes_supported: ['query'],
|
|
202
|
+
grant_types_supported: ['authorization_code', 'refresh_token', DEVICE_GRANT],
|
|
203
|
+
code_challenge_methods_supported: ['S256'],
|
|
204
|
+
token_endpoint_auth_methods_supported: ['none', 'client_secret_post', 'client_secret_basic'],
|
|
205
|
+
revocation_endpoint_auth_methods_supported: ['none', 'client_secret_post', 'client_secret_basic'],
|
|
206
|
+
authorization_response_iss_parameter_supported: true,
|
|
207
|
+
service_documentation: `${publicUrl}/api/v1`,
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
/** WWW-Authenticate for a 401 on a protected resource. */
|
|
212
|
+
function challenge(which, error) {
|
|
213
|
+
const meta = which === 'api' ? `${issuer}/.well-known/oauth-protected-resource/api/v1` : `${issuer}/.well-known/oauth-protected-resource/mcp`;
|
|
214
|
+
return `Bearer realm="board-saas", resource_metadata="${meta}", scope="${SCOPE}"${error ? `, error="${error}"` : ''}`;
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
// -------------------------------------------------------------- clients
|
|
218
|
+
|
|
219
|
+
const clientRow = (id) => (id ? get('select * from oauth_clients where client_id = ?', String(id)) : undefined);
|
|
220
|
+
const clientView = (c) => ({ ...c, redirect_uris: JSON.parse(c.redirect_uris), grant_types: JSON.parse(c.grant_types) });
|
|
221
|
+
|
|
222
|
+
function register(body, ip = '') {
|
|
223
|
+
limit(`reg:${ip}`, 30);
|
|
224
|
+
const uris = Array.isArray(body.redirect_uris) ? body.redirect_uris : [];
|
|
225
|
+
const grants = Array.isArray(body.grant_types) && body.grant_types.length ? body.grant_types.map(String) : ['authorization_code', 'refresh_token'];
|
|
226
|
+
const bad = grants.filter((g) => !['authorization_code', 'refresh_token', DEVICE_GRANT].includes(g));
|
|
227
|
+
if (bad.length) throw new OAuthError('invalid_client_metadata', `unsupported grant_types: ${bad.join(', ')}`);
|
|
228
|
+
if (grants.includes('authorization_code') && !uris.length) throw new OAuthError('invalid_redirect_uri', 'redirect_uris is required for the authorization_code grant');
|
|
229
|
+
if (uris.length > 10) throw new OAuthError('invalid_redirect_uri', 'at most 10 redirect URIs');
|
|
230
|
+
const redirectUris = uris.map(checkRedirect);
|
|
231
|
+
const method = String(body.token_endpoint_auth_method || 'none');
|
|
232
|
+
if (!['none', 'client_secret_post', 'client_secret_basic'].includes(method)) throw new OAuthError('invalid_client_metadata', `unsupported token_endpoint_auth_method: ${method}`);
|
|
233
|
+
const name = String(body.client_name || 'An OAuth app').replace(/[\u0000-\u001f]/g, '').trim().slice(0, 80) || 'An OAuth app';
|
|
234
|
+
const clientId = `bsc_${newId(16)}`;
|
|
235
|
+
const secret = method === 'none' ? null : token('bss_');
|
|
236
|
+
run(
|
|
237
|
+
'insert into oauth_clients (client_id, secret_hash, name, redirect_uris, grant_types, auth_method, dynamic, created_ip, created_at) values (?, ?, ?, ?, ?, ?, 1, ?, ?)',
|
|
238
|
+
clientId,
|
|
239
|
+
secret ? sha256(secret) : null,
|
|
240
|
+
name,
|
|
241
|
+
JSON.stringify(redirectUris),
|
|
242
|
+
JSON.stringify(grants),
|
|
243
|
+
method,
|
|
244
|
+
ip,
|
|
245
|
+
now(),
|
|
246
|
+
);
|
|
247
|
+
log(`oauth: registered client ${clientId} "${name}" (${method}) from ${ip}`);
|
|
248
|
+
return {
|
|
249
|
+
client_id: clientId,
|
|
250
|
+
...(secret ? { client_secret: secret, client_secret_expires_at: 0 } : {}),
|
|
251
|
+
client_id_issued_at: sec(),
|
|
252
|
+
client_name: name,
|
|
253
|
+
redirect_uris: redirectUris,
|
|
254
|
+
grant_types: grants,
|
|
255
|
+
response_types: ['code'],
|
|
256
|
+
token_endpoint_auth_method: method,
|
|
257
|
+
scope: SCOPE,
|
|
258
|
+
};
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
/** Authenticate the client on the token/revoke endpoints. Returns the client row. */
|
|
262
|
+
function authClient(params, authHeader) {
|
|
263
|
+
let id = params.client_id;
|
|
264
|
+
let secret = params.client_secret;
|
|
265
|
+
const m = String(authHeader ?? '').match(/^Basic\s+(.+)$/i);
|
|
266
|
+
if (m) {
|
|
267
|
+
const [u, p] = Buffer.from(m[1], 'base64').toString('utf8').split(':');
|
|
268
|
+
id = decodeURIComponent(u ?? '');
|
|
269
|
+
secret = decodeURIComponent(p ?? '');
|
|
270
|
+
}
|
|
271
|
+
const c = clientRow(id);
|
|
272
|
+
if (!c) throw new OAuthError('invalid_client', 'unknown client_id', 401);
|
|
273
|
+
if (c.auth_method !== 'none') {
|
|
274
|
+
if (!secret || !c.secret_hash || !safeEqual(sha256(secret), c.secret_hash)) throw new OAuthError('invalid_client', 'client authentication failed', 401);
|
|
275
|
+
}
|
|
276
|
+
return clientView(c);
|
|
277
|
+
}
|
|
278
|
+
|
|
279
|
+
// --------------------------------------------------------------- tokens
|
|
280
|
+
|
|
281
|
+
function issue({ clientId, accountId, scope, family = newId(12) }) {
|
|
282
|
+
const access = token('bso_');
|
|
283
|
+
const refresh = token('bsr_');
|
|
284
|
+
const t = now();
|
|
285
|
+
run('insert into oauth_tokens (token_hash, kind, client_id, account_id, scope, family, expires_at, created_at) values (?, ?, ?, ?, ?, ?, ?, ?)', sha256(access), 'access', clientId, accountId, scope, family, t + ACCESS_TTL * 1000, t);
|
|
286
|
+
run('insert into oauth_tokens (token_hash, kind, client_id, account_id, scope, family, expires_at, created_at) values (?, ?, ?, ?, ?, ?, ?, ?)', sha256(refresh), 'refresh', clientId, accountId, scope, family, t + REFRESH_TTL * 1000, t);
|
|
287
|
+
return { access_token: access, token_type: 'Bearer', expires_in: ACCESS_TTL, refresh_token: refresh, scope };
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
const revokeFamily = (family) => run('update oauth_tokens set revoked = 1 where family = ?', family);
|
|
291
|
+
|
|
292
|
+
/** Bearer access token -> account id, or null. */
|
|
293
|
+
function accountForAccessToken(bearer) {
|
|
294
|
+
if (!bearer || !bearer.startsWith('bso_')) return null;
|
|
295
|
+
const row = get("select * from oauth_tokens where token_hash = ? and kind = 'access'", sha256(bearer));
|
|
296
|
+
if (!row || row.revoked || row.expires_at < now()) return null;
|
|
297
|
+
return row.account_id;
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
function normalizeScope(s) {
|
|
301
|
+
const asked = String(s ?? '').split(/\s+/).filter(Boolean);
|
|
302
|
+
// offline_access is implied (everyone gets a refresh token); anything else unknown is refused.
|
|
303
|
+
const unknown = asked.filter((x) => x !== SCOPE && x !== 'offline_access');
|
|
304
|
+
if (unknown.length) throw new OAuthError('invalid_scope', `unknown scope: ${unknown.join(' ')}; this server has one scope, "${SCOPE}"`);
|
|
305
|
+
return SCOPE;
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
function checkResource(resource) {
|
|
309
|
+
if (!resource) return null;
|
|
310
|
+
const list = Array.isArray(resource) ? resource : [resource];
|
|
311
|
+
for (const r of list) if (!String(r).startsWith(publicUrl)) throw new OAuthError('invalid_target', `this server only issues tokens for ${publicUrl}`);
|
|
312
|
+
return list.join(' ');
|
|
313
|
+
}
|
|
314
|
+
|
|
315
|
+
async function tokenEndpoint(params, authHeader, ip = '') {
|
|
316
|
+
sweep();
|
|
317
|
+
const grant = params.grant_type;
|
|
318
|
+
if (grant === 'authorization_code') {
|
|
319
|
+
const client = authClient(params, authHeader);
|
|
320
|
+
const row = get('select * from oauth_codes where code_hash = ?', sha256(String(params.code ?? '')));
|
|
321
|
+
if (!row) throw new OAuthError('invalid_grant', 'unknown or used authorization code');
|
|
322
|
+
run('delete from oauth_codes where code_hash = ?', row.code_hash); // one use, even on failure
|
|
323
|
+
if (row.expires_at < now()) throw new OAuthError('invalid_grant', 'the authorization code expired');
|
|
324
|
+
if (row.client_id !== client.client_id) throw new OAuthError('invalid_grant', 'the code was issued to another client');
|
|
325
|
+
if (row.redirect_uri !== String(params.redirect_uri ?? '')) throw new OAuthError('invalid_grant', 'redirect_uri does not match the authorization request');
|
|
326
|
+
const verifier = String(params.code_verifier ?? '');
|
|
327
|
+
if (!/^[A-Za-z0-9._~-]{43,128}$/.test(verifier)) throw new OAuthError('invalid_grant', 'code_verifier is missing or malformed');
|
|
328
|
+
if (b64url(createHash('sha256').update(verifier).digest()) !== row.challenge) throw new OAuthError('invalid_grant', 'PKCE verification failed');
|
|
329
|
+
log(`oauth: code exchanged by ${client.client_id} for account ${row.account_id}`);
|
|
330
|
+
return issue({ clientId: client.client_id, accountId: row.account_id, scope: row.scope });
|
|
331
|
+
}
|
|
332
|
+
if (grant === 'refresh_token') {
|
|
333
|
+
const client = authClient(params, authHeader);
|
|
334
|
+
const row = get("select * from oauth_tokens where token_hash = ? and kind = 'refresh'", sha256(String(params.refresh_token ?? '')));
|
|
335
|
+
if (!row || row.client_id !== client.client_id) throw new OAuthError('invalid_grant', 'unknown refresh token');
|
|
336
|
+
if (row.revoked) throw new OAuthError('invalid_grant', 'this connection was revoked; sign in again');
|
|
337
|
+
if (row.used) {
|
|
338
|
+
revokeFamily(row.family);
|
|
339
|
+
log(`oauth: refresh token reuse on family ${row.family} (client ${row.client_id}); family revoked`);
|
|
340
|
+
throw new OAuthError('invalid_grant', 'this refresh token was already used; the connection is revoked for safety, sign in again');
|
|
341
|
+
}
|
|
342
|
+
if (row.expires_at < now()) throw new OAuthError('invalid_grant', 'the refresh token expired; sign in again');
|
|
343
|
+
if (!db.accountById(row.account_id)) throw new OAuthError('invalid_grant', 'the account no longer exists');
|
|
344
|
+
if (!run("update oauth_tokens set used = 1 where token_hash = ? and used = 0", row.token_hash).changes) {
|
|
345
|
+
revokeFamily(row.family);
|
|
346
|
+
throw new OAuthError('invalid_grant', 'this refresh token was already used; sign in again');
|
|
347
|
+
}
|
|
348
|
+
run("update oauth_tokens set revoked = 1 where family = ? and kind = 'access'", row.family);
|
|
349
|
+
return issue({ clientId: client.client_id, accountId: row.account_id, scope: row.scope, family: row.family });
|
|
350
|
+
}
|
|
351
|
+
if (grant === DEVICE_GRANT) {
|
|
352
|
+
const client = authClient(params, authHeader);
|
|
353
|
+
const row = get('select * from oauth_devices where device_hash = ?', sha256(String(params.device_code ?? '')));
|
|
354
|
+
if (!row || row.client_id !== client.client_id) throw new OAuthError('invalid_grant', 'unknown device_code');
|
|
355
|
+
if (row.expires_at < now()) throw new OAuthError('expired_token', 'the code expired; start again');
|
|
356
|
+
if (now() - row.last_poll < row.interval_s * 1000 - 250) {
|
|
357
|
+
run('update oauth_devices set interval_s = interval_s + 5, last_poll = ? where device_hash = ?', now(), row.device_hash);
|
|
358
|
+
throw new OAuthError('slow_down', `poll no faster than every ${row.interval_s + 5} seconds`);
|
|
359
|
+
}
|
|
360
|
+
run('update oauth_devices set last_poll = ? where device_hash = ?', now(), row.device_hash);
|
|
361
|
+
if (row.status === 'pending') throw new OAuthError('authorization_pending', 'waiting for you to approve in the browser');
|
|
362
|
+
if (row.status === 'denied') throw new OAuthError('access_denied', 'the request was denied');
|
|
363
|
+
if (row.status !== 'approved') throw new OAuthError('invalid_grant', 'this device code was already used');
|
|
364
|
+
if (!run("update oauth_devices set status = 'used' where device_hash = ? and status = 'approved'", row.device_hash).changes) throw new OAuthError('invalid_grant', 'this device code was already used');
|
|
365
|
+
log(`oauth: device code redeemed by ${client.client_id} for account ${row.account_id}`);
|
|
366
|
+
return issue({ clientId: client.client_id, accountId: row.account_id, scope: row.scope });
|
|
367
|
+
}
|
|
368
|
+
void ip;
|
|
369
|
+
throw new OAuthError('unsupported_grant_type', `unsupported grant_type: ${grant ?? '(none)'}`);
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
function revoke(params, authHeader) {
|
|
373
|
+
// RFC 7009: answer 200 whether or not the token existed.
|
|
374
|
+
let client = null;
|
|
375
|
+
try {
|
|
376
|
+
client = authClient(params, authHeader);
|
|
377
|
+
} catch (e) {
|
|
378
|
+
if (params.client_id || authHeader) throw e;
|
|
379
|
+
}
|
|
380
|
+
const row = get('select * from oauth_tokens where token_hash = ?', sha256(String(params.token ?? '')));
|
|
381
|
+
if (row && (!client || row.client_id === client.client_id)) {
|
|
382
|
+
if (row.kind === 'refresh') revokeFamily(row.family);
|
|
383
|
+
else run('update oauth_tokens set revoked = 1 where token_hash = ?', row.token_hash);
|
|
384
|
+
log(`oauth: revoked ${row.kind} token of family ${row.family}`);
|
|
385
|
+
}
|
|
386
|
+
return {};
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
// -------------------------------------------------------------- consent
|
|
390
|
+
|
|
391
|
+
function sessionFor(cookieHeader) {
|
|
392
|
+
const m = String(cookieHeader ?? '').match(/(?:^|;\s*)bs_sid=([A-Za-z0-9_-]+)/);
|
|
393
|
+
if (!m) return null;
|
|
394
|
+
const row = get('select * from web_sessions where sid_hash = ?', sha256(m[1]));
|
|
395
|
+
if (!row || row.expires_at < now()) return null;
|
|
396
|
+
const account = db.accountById(row.account_id);
|
|
397
|
+
return account ? { account, csrf: row.csrf } : null;
|
|
398
|
+
}
|
|
399
|
+
|
|
400
|
+
/** Email + code -> a web session for the consent and device pages. Returns the Set-Cookie value. */
|
|
401
|
+
function signIn(emailIn, code) {
|
|
402
|
+
const email = normalizeEmail(emailIn);
|
|
403
|
+
if (!db.checkLoginCode(email, code)) throw new HttpError(401, 'that code is wrong or expired; ask for a new one');
|
|
404
|
+
const account = db.ensureAccount(email);
|
|
405
|
+
const sid = randomBytes(32).toString('base64url');
|
|
406
|
+
run('insert into web_sessions (sid_hash, account_id, csrf, expires_at) values (?, ?, ?, ?)', sha256(sid), account.id, randomBytes(18).toString('base64url'), now() + SESSION_TTL * 1000);
|
|
407
|
+
return `bs_sid=${sid}; Path=/oauth; HttpOnly; SameSite=Lax; Max-Age=${SESSION_TTL}${secureCookie ? '; Secure' : ''}`;
|
|
408
|
+
}
|
|
409
|
+
|
|
410
|
+
function signOut(cookieHeader) {
|
|
411
|
+
const m = String(cookieHeader ?? '').match(/(?:^|;\s*)bs_sid=([A-Za-z0-9_-]+)/);
|
|
412
|
+
if (m) run('delete from web_sessions where sid_hash = ?', sha256(m[1]));
|
|
413
|
+
return `bs_sid=; Path=/oauth; HttpOnly; SameSite=Lax; Max-Age=0${secureCookie ? '; Secure' : ''}`;
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
/**
|
|
417
|
+
* Validate an authorization request. Returns { client, redirectUri, state, challenge, scope, resource }.
|
|
418
|
+
* Throws { redirect } once the redirect URI is trusted (errors go back to the client), or a
|
|
419
|
+
* plain error before that (shown on the page, never redirected to an unverified URI).
|
|
420
|
+
*/
|
|
421
|
+
function checkAuthorize(q) {
|
|
422
|
+
const c = clientRow(q.client_id);
|
|
423
|
+
if (!c) throw new HttpError(400, 'unknown client_id. The app must register first (POST /oauth/register).');
|
|
424
|
+
const client = clientView(c);
|
|
425
|
+
const redirectUri = String(q.redirect_uri ?? (client.redirect_uris.length === 1 ? client.redirect_uris[0] : ''));
|
|
426
|
+
if (!redirectUri || !redirectMatches(client.redirect_uris, redirectUri)) throw new HttpError(400, 'redirect_uri is not registered for this app');
|
|
427
|
+
const back = (error, description) => {
|
|
428
|
+
const u = new URL(redirectUri);
|
|
429
|
+
u.searchParams.set('error', error);
|
|
430
|
+
if (description) u.searchParams.set('error_description', description);
|
|
431
|
+
if (q.state) u.searchParams.set('state', q.state);
|
|
432
|
+
u.searchParams.set('iss', issuer);
|
|
433
|
+
return Object.assign(new Error(description), { redirect: u.href });
|
|
434
|
+
};
|
|
435
|
+
if (q.response_type !== 'code') throw back('unsupported_response_type', 'response_type must be code');
|
|
436
|
+
if (!client.grant_types.includes('authorization_code')) throw back('unauthorized_client', 'this app is not registered for the authorization_code grant');
|
|
437
|
+
if (!q.code_challenge || !/^[A-Za-z0-9_-]{43}$/.test(q.code_challenge)) throw back('invalid_request', 'PKCE is required: send code_challenge (S256)');
|
|
438
|
+
if ((q.code_challenge_method || 'plain') !== 'S256') throw back('invalid_request', 'code_challenge_method must be S256');
|
|
439
|
+
let scope;
|
|
440
|
+
let resource;
|
|
441
|
+
try {
|
|
442
|
+
scope = normalizeScope(q.scope);
|
|
443
|
+
resource = checkResource(q.resource);
|
|
444
|
+
} catch (e) {
|
|
445
|
+
throw back(e.code, e.message);
|
|
446
|
+
}
|
|
447
|
+
return { client, redirectUri, state: q.state ?? null, challenge: q.code_challenge, scope, resource };
|
|
448
|
+
}
|
|
449
|
+
|
|
450
|
+
function approve(req, accountId) {
|
|
451
|
+
const code = token('bsa_');
|
|
452
|
+
run(
|
|
453
|
+
'insert into oauth_codes (code_hash, client_id, account_id, redirect_uri, challenge, scope, resource, expires_at) values (?, ?, ?, ?, ?, ?, ?, ?)',
|
|
454
|
+
sha256(code),
|
|
455
|
+
req.client.client_id,
|
|
456
|
+
accountId,
|
|
457
|
+
req.redirectUri,
|
|
458
|
+
req.challenge,
|
|
459
|
+
req.scope,
|
|
460
|
+
req.resource,
|
|
461
|
+
now() + CODE_TTL * 1000,
|
|
462
|
+
);
|
|
463
|
+
const u = new URL(req.redirectUri);
|
|
464
|
+
u.searchParams.set('code', code);
|
|
465
|
+
if (req.state) u.searchParams.set('state', req.state);
|
|
466
|
+
u.searchParams.set('iss', issuer);
|
|
467
|
+
log(`oauth: account ${accountId} approved ${req.client.client_id} "${req.client.name}"`);
|
|
468
|
+
return u.href;
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
function deny(req) {
|
|
472
|
+
const u = new URL(req.redirectUri);
|
|
473
|
+
u.searchParams.set('error', 'access_denied');
|
|
474
|
+
u.searchParams.set('error_description', 'the account owner said no');
|
|
475
|
+
if (req.state) u.searchParams.set('state', req.state);
|
|
476
|
+
u.searchParams.set('iss', issuer);
|
|
477
|
+
return u.href;
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
// ---------------------------------------------------------- device flow
|
|
481
|
+
|
|
482
|
+
function newUserCode() {
|
|
483
|
+
let s = '';
|
|
484
|
+
for (let i = 0; i < 8; i++) s += USER_CODE_ALPHABET[randomInt(0, USER_CODE_ALPHABET.length)];
|
|
485
|
+
return `${s.slice(0, 4)}-${s.slice(4)}`;
|
|
486
|
+
}
|
|
487
|
+
const normUserCode = (v) => {
|
|
488
|
+
const s = String(v ?? '').toUpperCase().replace(/[^A-Z]/g, '');
|
|
489
|
+
return s.length === 8 ? `${s.slice(0, 4)}-${s.slice(4)}` : null;
|
|
490
|
+
};
|
|
491
|
+
|
|
492
|
+
function deviceAuthorization(params, authHeader, ip = '') {
|
|
493
|
+
limit(`dev:${ip}`, 30);
|
|
494
|
+
sweep();
|
|
495
|
+
const client = authClient(params, authHeader);
|
|
496
|
+
if (!client.grant_types.includes(DEVICE_GRANT)) throw new OAuthError('unauthorized_client', 'this app is not registered for the device grant');
|
|
497
|
+
const scope = normalizeScope(params.scope);
|
|
498
|
+
const device = token('bsd_');
|
|
499
|
+
let userCode = newUserCode();
|
|
500
|
+
for (let i = 0; i < 5 && get('select 1 from oauth_devices where user_code = ?', userCode); i++) userCode = newUserCode();
|
|
501
|
+
run('insert into oauth_devices (device_hash, user_code, client_id, scope, expires_at) values (?, ?, ?, ?, ?)', sha256(device), userCode, client.client_id, scope, now() + DEVICE_TTL * 1000);
|
|
502
|
+
// No verification_uri_complete on purpose: typing the code is what stops a phished link.
|
|
503
|
+
return { device_code: device, user_code: userCode, verification_uri: `${issuer}/oauth/device`, expires_in: DEVICE_TTL, interval: 5 };
|
|
504
|
+
}
|
|
505
|
+
|
|
506
|
+
function deviceLookup(userCodeIn) {
|
|
507
|
+
const userCode = normUserCode(userCodeIn);
|
|
508
|
+
const row = userCode && get('select * from oauth_devices where user_code = ?', userCode);
|
|
509
|
+
if (!row || row.expires_at < now() || row.status !== 'pending') throw new HttpError(404, 'that code is wrong, expired or already used; start again in your terminal');
|
|
510
|
+
const c = clientRow(row.client_id);
|
|
511
|
+
return { row, client: c ? clientView(c) : { name: row.client_id } };
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
function deviceDecide(userCodeIn, accountId, allow) {
|
|
515
|
+
const { row, client } = deviceLookup(userCodeIn);
|
|
516
|
+
const ok = run("update oauth_devices set status = ?, account_id = ? where device_hash = ? and status = 'pending'", allow ? 'approved' : 'denied', accountId, row.device_hash).changes;
|
|
517
|
+
if (!ok) throw new HttpError(409, 'that code was already used');
|
|
518
|
+
log(`oauth: account ${accountId} ${allow ? 'approved' : 'denied'} device code for ${row.client_id}`);
|
|
519
|
+
return { ok: true, approved: !!allow, client: client.name };
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
// ---------------------------------------------------------- connections
|
|
523
|
+
|
|
524
|
+
function connections(accountId) {
|
|
525
|
+
return all(
|
|
526
|
+
`select t.client_id, c.name, min(t.created_at) as first_at, max(t.created_at) as last_at
|
|
527
|
+
from oauth_tokens t left join oauth_clients c on c.client_id = t.client_id
|
|
528
|
+
where t.account_id = ? and t.kind = 'refresh' and t.revoked = 0 and t.used = 0 and t.expires_at > ?
|
|
529
|
+
group by t.client_id order by last_at desc`,
|
|
530
|
+
accountId,
|
|
531
|
+
now(),
|
|
532
|
+
).map((r) => ({ client_id: r.client_id, name: r.name ?? r.client_id, connected_at: new Date(r.first_at).toISOString(), last_refreshed_at: new Date(r.last_at).toISOString() }));
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
function disconnect(accountId, clientId) {
|
|
536
|
+
const n = run('update oauth_tokens set revoked = 1 where account_id = ? and client_id = ? and revoked = 0', accountId, String(clientId)).changes;
|
|
537
|
+
return { revoked: n > 0 };
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
return {
|
|
541
|
+
resourceMetadata,
|
|
542
|
+
serverMetadata,
|
|
543
|
+
challenge,
|
|
544
|
+
register,
|
|
545
|
+
tokenEndpoint,
|
|
546
|
+
revoke,
|
|
547
|
+
accountForAccessToken,
|
|
548
|
+
sessionFor,
|
|
549
|
+
signIn,
|
|
550
|
+
signOut,
|
|
551
|
+
checkAuthorize,
|
|
552
|
+
approve,
|
|
553
|
+
deny,
|
|
554
|
+
deviceAuthorization,
|
|
555
|
+
deviceLookup,
|
|
556
|
+
deviceDecide,
|
|
557
|
+
connections,
|
|
558
|
+
disconnect,
|
|
559
|
+
clientName: (id) => clientRow(id)?.name ?? null,
|
|
560
|
+
};
|
|
561
|
+
}
|