@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/server.js
CHANGED
|
@@ -10,6 +10,8 @@ import { allFooters, startFooterRefresh } from './footers.js';
|
|
|
10
10
|
import { createModel } from './llm.js';
|
|
11
11
|
import { createMailer } from './mail.js';
|
|
12
12
|
import { createMcpHandler, TOOLS } from './mcp.js';
|
|
13
|
+
import { createOAuth, OAuthError } from './oauth.js';
|
|
14
|
+
import { consentPage, devicePage, errorPage, newNonce, pageHeaders } from './oauth-pages.js';
|
|
13
15
|
import { reportDownload, reportPage, statusPage } from './pages.js';
|
|
14
16
|
import { createService, HttpError, PRICE_USD } from './service.js';
|
|
15
17
|
|
|
@@ -22,22 +24,35 @@ export const API_DOCS = {
|
|
|
22
24
|
name: 'Board as a Service API',
|
|
23
25
|
version: VERSION,
|
|
24
26
|
base: 'https://board.saas.pit.world/api/v1',
|
|
25
|
-
auth: 'Authorization: Bearer <
|
|
27
|
+
auth: 'Authorization: Bearer <token>. Either an OAuth 2.1 access token (any app: discovery at /.well-known/oauth-authorization-server, dynamic client registration, authorization code + S256 PKCE, device flow, refresh, revoke) or an API key from POST /auth/code {email} then POST /auth/verify {email, code}. Keys are full access to your account; a new verify replaces the old key.',
|
|
28
|
+
oauth: {
|
|
29
|
+
metadata: 'https://board.saas.pit.world/.well-known/oauth-authorization-server',
|
|
30
|
+
protected_resources: ['https://board.saas.pit.world/.well-known/oauth-protected-resource/mcp', 'https://board.saas.pit.world/.well-known/oauth-protected-resource/api/v1'],
|
|
31
|
+
register: 'POST /oauth/register (RFC 7591, open; public clients use PKCE, confidential ones get a secret)',
|
|
32
|
+
authorize: 'GET /oauth/authorize?response_type=code&client_id=..&redirect_uri=..&code_challenge=..&code_challenge_method=S256&state=..',
|
|
33
|
+
token: 'POST /oauth/token (authorization_code, refresh_token, urn:ietf:params:oauth:grant-type:device_code)',
|
|
34
|
+
device: 'POST /oauth/device_authorization, then the person enters the code at /oauth/device',
|
|
35
|
+
revoke: 'POST /oauth/revoke',
|
|
36
|
+
scope: 'board',
|
|
37
|
+
cli_client_id: 'board-saas-cli',
|
|
38
|
+
},
|
|
26
39
|
pricing: `First meeting free per email, then $${PRICE_USD} per meeting via CoinPay (crypto). A meeting the network cannot finish is refunded.`,
|
|
27
40
|
honesty: 'The advisors are AI models on the c0mpute network, not real directors.',
|
|
28
41
|
endpoints: [
|
|
29
42
|
{ method: 'POST', path: '/auth/code', body: { email: 'you@example.com' }, does: 'Email a 6-digit sign-in code.' },
|
|
30
43
|
{ method: 'POST', path: '/auth/verify', body: { email: 'you@example.com', code: '123456' }, does: 'Exchange the code for an API key.' },
|
|
31
44
|
{ method: 'GET', path: '/account', auth: true, does: 'Free meeting left, paid credits.' },
|
|
32
|
-
{ method: 'POST', path: '/meetings', auth: true, body: { brief: 'Decision ... Options ... Constraints ...' }, does: 'Start a meeting. 201 with status queued, or awaiting_payment with checkout_url.' },
|
|
45
|
+
{ method: 'POST', path: '/meetings', auth: true, body: { brief: 'Decision ... Options ... Constraints ...', company_data: 'optional: P&L, cash, runway, MRR, churn (max 12000 chars, text or JSON); every advisor reads it, the shareable report does not show it' }, does: 'Start a meeting. 201 with status queued, or awaiting_payment with checkout_url.' },
|
|
33
46
|
{ method: 'GET', path: '/meetings', auth: true, does: 'Your meetings, newest first.' },
|
|
34
47
|
{ method: 'GET', path: '/meetings/:id', does: 'Status, progress, and the full meeting when done. The id is the capability; share it like a link.' },
|
|
35
48
|
{ method: 'POST', path: '/meetings/:id/clarify', body: { answers: '...' }, does: 'Answer the chair\'s one round of questions (status needs_clarification).' },
|
|
36
49
|
{ method: 'GET', path: '/meetings/:id/report.html', does: 'The interactive report as a downloadable file.' },
|
|
37
50
|
{ method: 'GET', path: '/meetings/:id/meeting.json', does: 'The meeting data (boardroom meeting.json shape).' },
|
|
51
|
+
{ method: 'GET', path: '/connections', auth: true, does: 'Apps connected to your account over OAuth.' },
|
|
52
|
+
{ method: 'DELETE', path: '/connections/:client_id', auth: true, does: 'Disconnect an app; its tokens stop working at once.' },
|
|
38
53
|
],
|
|
39
|
-
mcp: { endpoint: 'https://board.saas.pit.world/mcp', transport: 'streamable HTTP (JSON responses)', auth: 'Authorization: Bearer <key>', tools: TOOLS.map((t) => t.name), stdio: 'npx -y @profullstack/board-saas mcp' },
|
|
40
|
-
cli: 'npm i -g @profullstack/board-saas (board-saas login | meet | get | list | tui | mcp)',
|
|
54
|
+
mcp: { endpoint: 'https://board.saas.pit.world/mcp', transport: 'streamable HTTP (JSON responses)', auth: 'OAuth 2.1 (add the URL as a connector; the client discovers and registers itself) or Authorization: Bearer <key>', tools: TOOLS.map((t) => t.name), stdio: 'npx -y @profullstack/board-saas mcp' },
|
|
55
|
+
cli: 'npm i -g @profullstack/board-saas (board-saas login | meet | get | list | connections | tui | mcp)',
|
|
41
56
|
};
|
|
42
57
|
|
|
43
58
|
function bearer(req) {
|
|
@@ -72,11 +87,35 @@ async function jsonBody(req) {
|
|
|
72
87
|
}
|
|
73
88
|
}
|
|
74
89
|
|
|
90
|
+
/** OAuth endpoints take application/x-www-form-urlencoded (the spec) or JSON. */
|
|
91
|
+
async function formBody(req) {
|
|
92
|
+
const raw = await readBody(req, 32 * 1024);
|
|
93
|
+
if (!raw) return {};
|
|
94
|
+
if (String(req.headers['content-type'] ?? '').includes('application/json')) {
|
|
95
|
+
try {
|
|
96
|
+
const v = JSON.parse(raw);
|
|
97
|
+
return v && typeof v === 'object' && !Array.isArray(v) ? v : {};
|
|
98
|
+
} catch {
|
|
99
|
+
throw new OAuthError('invalid_request', 'body must be form-encoded or JSON');
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
const out = {};
|
|
103
|
+
for (const [k, v] of new URLSearchParams(raw)) {
|
|
104
|
+
if (k === 'resource' && out.resource) out.resource = [].concat(out.resource, v);
|
|
105
|
+
else out[k] = v;
|
|
106
|
+
}
|
|
107
|
+
return out;
|
|
108
|
+
}
|
|
109
|
+
|
|
110
|
+
const clientIp = (req) => String(req.headers['x-forwarded-for'] ?? req.socket.remoteAddress ?? '').split(',')[0].trim();
|
|
111
|
+
|
|
75
112
|
const CORS = {
|
|
76
113
|
'access-control-allow-origin': '*',
|
|
77
114
|
'access-control-allow-headers': 'authorization, content-type, mcp-protocol-version, mcp-session-id',
|
|
78
|
-
'access-control-allow-methods': 'GET, POST, OPTIONS',
|
|
115
|
+
'access-control-allow-methods': 'GET, POST, DELETE, OPTIONS',
|
|
116
|
+
'access-control-expose-headers': 'www-authenticate, mcp-session-id',
|
|
79
117
|
};
|
|
118
|
+
const NO_STORE = { ...CORS, 'cache-control': 'no-store', pragma: 'no-cache' };
|
|
80
119
|
|
|
81
120
|
function send(res, status, body, headers = {}) {
|
|
82
121
|
const isStr = typeof body === 'string';
|
|
@@ -93,17 +132,132 @@ export function createApp({ env = process.env, db, model, mailer, fetchImpl = fe
|
|
|
93
132
|
db ??= openDb(env.BOARD_DB || join(env.HOME || '.', '.local/share/board-saas/board.db'));
|
|
94
133
|
model ??= createModel(env);
|
|
95
134
|
mailer ??= createMailer(env, fetchImpl);
|
|
96
|
-
const
|
|
135
|
+
const oauth = createOAuth({ db, publicUrl, log });
|
|
136
|
+
const service = createService({ db, env, model, mailer, log, publicUrl, accountForToken: oauth.accountForAccessToken });
|
|
137
|
+
const origin = new URL(publicUrl).origin;
|
|
97
138
|
|
|
98
139
|
const mcp = (key) =>
|
|
99
140
|
createMcpHandler(
|
|
100
141
|
{
|
|
101
|
-
runMeeting: (brief) => service.createMeeting(key, brief),
|
|
142
|
+
runMeeting: (brief, companyData) => service.createMeeting(key, brief, companyData),
|
|
102
143
|
getMeeting: async (id) => service.getMeeting(id),
|
|
144
|
+
listMeetings: async () => service.listMeetings(key),
|
|
145
|
+
clarify: async (id, answers) => service.clarify(key, id, answers),
|
|
146
|
+
account: async () => service.account(key),
|
|
103
147
|
},
|
|
104
148
|
{ version: VERSION },
|
|
105
149
|
);
|
|
106
150
|
|
|
151
|
+
/**
|
|
152
|
+
* Browser POSTs to /oauth/* must come from our own pages. The pit.world edge forwards with
|
|
153
|
+
* the Moshpit name (Host and Origin both `board.saas`), so an Origin whose host is the
|
|
154
|
+
* request's Host is ours too; a cross-site page cannot make those two match.
|
|
155
|
+
*/
|
|
156
|
+
function sameOrigin(req) {
|
|
157
|
+
const o = req.headers.origin;
|
|
158
|
+
if (!o || o === origin) return;
|
|
159
|
+
let host = null;
|
|
160
|
+
try {
|
|
161
|
+
host = new URL(o).host;
|
|
162
|
+
} catch {
|
|
163
|
+
/* "null" or garbage */
|
|
164
|
+
}
|
|
165
|
+
if (host && host === req.headers.host) return;
|
|
166
|
+
throw new HttpError(403, `cross-site request refused (Origin ${String(o).slice(0, 80)})`);
|
|
167
|
+
}
|
|
168
|
+
function sessionOrThrow(req, csrf) {
|
|
169
|
+
const s = oauth.sessionFor(req.headers.cookie);
|
|
170
|
+
if (!s) throw new HttpError(401, 'your sign-in expired; reload the page and sign in again');
|
|
171
|
+
if (csrf !== undefined && csrf !== s.csrf) throw new HttpError(403, 'stale page; reload and try again');
|
|
172
|
+
return s;
|
|
173
|
+
}
|
|
174
|
+
const sendOAuthError = (res, e) => send(res, e.status || 400, { error: e.code, error_description: e.message }, NO_STORE);
|
|
175
|
+
|
|
176
|
+
async function oauthRoute(req, res, path, method, url) {
|
|
177
|
+
if (path === '/oauth/register' || path === '/register') {
|
|
178
|
+
if (method !== 'POST') return send(res, 405, { error: 'POST client metadata (RFC 7591)' }, CORS);
|
|
179
|
+
try {
|
|
180
|
+
return send(res, 201, oauth.register(await jsonBody(req).catch(() => ({})), clientIp(req)), NO_STORE);
|
|
181
|
+
} catch (e) {
|
|
182
|
+
if (e instanceof OAuthError) return sendOAuthError(res, e);
|
|
183
|
+
throw e;
|
|
184
|
+
}
|
|
185
|
+
}
|
|
186
|
+
if (path === '/oauth/token' && method === 'POST') {
|
|
187
|
+
try {
|
|
188
|
+
return send(res, 200, await oauth.tokenEndpoint(await formBody(req), req.headers.authorization, clientIp(req)), NO_STORE);
|
|
189
|
+
} catch (e) {
|
|
190
|
+
if (e instanceof OAuthError) return sendOAuthError(res, e);
|
|
191
|
+
throw e;
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
if (path === '/oauth/device_authorization' && method === 'POST') {
|
|
195
|
+
try {
|
|
196
|
+
return send(res, 200, oauth.deviceAuthorization(await formBody(req), req.headers.authorization, clientIp(req)), NO_STORE);
|
|
197
|
+
} catch (e) {
|
|
198
|
+
if (e instanceof OAuthError) return sendOAuthError(res, e);
|
|
199
|
+
throw e;
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
if (path === '/oauth/revoke' && method === 'POST') {
|
|
203
|
+
try {
|
|
204
|
+
return send(res, 200, oauth.revoke(await formBody(req), req.headers.authorization), NO_STORE);
|
|
205
|
+
} catch (e) {
|
|
206
|
+
if (e instanceof OAuthError) return sendOAuthError(res, e);
|
|
207
|
+
throw e;
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
if (path === '/oauth/authorize' && method === 'GET') {
|
|
211
|
+
const nonce = newNonce();
|
|
212
|
+
let ar;
|
|
213
|
+
try {
|
|
214
|
+
ar = oauth.checkAuthorize(Object.fromEntries(url.searchParams));
|
|
215
|
+
} catch (e) {
|
|
216
|
+
if (e.redirect) return send(res, 302, '', { location: e.redirect, 'cache-control': 'no-store' });
|
|
217
|
+
return send(res, 400, errorPage(e.message, nonce), pageHeaders(nonce));
|
|
218
|
+
}
|
|
219
|
+
const session = oauth.sessionFor(req.headers.cookie);
|
|
220
|
+
return send(res, 200, consentPage({ client: ar.client, redirectUri: ar.redirectUri, session, query: url.search, nonce }), pageHeaders(nonce));
|
|
221
|
+
}
|
|
222
|
+
if (path === '/oauth/authorize' && method === 'POST') {
|
|
223
|
+
sameOrigin(req);
|
|
224
|
+
const b = await jsonBody(req);
|
|
225
|
+
const s = sessionOrThrow(req, b.csrf);
|
|
226
|
+
let ar;
|
|
227
|
+
try {
|
|
228
|
+
ar = oauth.checkAuthorize(Object.fromEntries(new URLSearchParams(String(b.query ?? ''))));
|
|
229
|
+
} catch (e) {
|
|
230
|
+
if (e.redirect) return send(res, 200, { redirect: e.redirect }, { 'cache-control': 'no-store' });
|
|
231
|
+
throw new HttpError(400, e.message);
|
|
232
|
+
}
|
|
233
|
+
const redirect = b.action === 'approve' ? oauth.approve(ar, s.account.id) : oauth.deny(ar);
|
|
234
|
+
return send(res, 200, { redirect }, { 'cache-control': 'no-store' });
|
|
235
|
+
}
|
|
236
|
+
if (path === '/oauth/device' && method === 'GET') {
|
|
237
|
+
const nonce = newNonce();
|
|
238
|
+
return send(res, 200, devicePage({ session: oauth.sessionFor(req.headers.cookie), nonce }), pageHeaders(nonce));
|
|
239
|
+
}
|
|
240
|
+
if (path === '/oauth/device' && method === 'POST') {
|
|
241
|
+
sameOrigin(req);
|
|
242
|
+
const b = await jsonBody(req);
|
|
243
|
+
const s = sessionOrThrow(req, b.csrf);
|
|
244
|
+
if (b.action === 'lookup') return send(res, 200, { client: oauth.deviceLookup(b.user_code).client.name }, { 'cache-control': 'no-store' });
|
|
245
|
+
if (b.action !== 'approve' && b.action !== 'deny') throw new HttpError(400, 'action must be lookup, approve or deny');
|
|
246
|
+
return send(res, 200, oauth.deviceDecide(b.user_code, s.account.id, b.action === 'approve'), { 'cache-control': 'no-store' });
|
|
247
|
+
}
|
|
248
|
+
if (path === '/oauth/session' && method === 'POST') {
|
|
249
|
+
sameOrigin(req);
|
|
250
|
+
const b = await jsonBody(req);
|
|
251
|
+
const cookie = oauth.signIn(b.email, b.code);
|
|
252
|
+
return send(res, 200, { ok: true }, { 'set-cookie': cookie, 'cache-control': 'no-store' });
|
|
253
|
+
}
|
|
254
|
+
if (path === '/oauth/logout' && method === 'POST') {
|
|
255
|
+
sameOrigin(req);
|
|
256
|
+
return send(res, 200, { ok: true }, { 'set-cookie': oauth.signOut(req.headers.cookie), 'cache-control': 'no-store' });
|
|
257
|
+
}
|
|
258
|
+
return send(res, 404, { error: 'no such OAuth endpoint; see /.well-known/oauth-authorization-server' }, CORS);
|
|
259
|
+
}
|
|
260
|
+
|
|
107
261
|
// ------------------------------------------------------------ static site
|
|
108
262
|
const builtDir = join(ROOT, 'site');
|
|
109
263
|
const localDir = existsSync(join(builtDir, 'index.html')) ? builtDir : join(ROOT, 'public');
|
|
@@ -142,7 +296,7 @@ export function createApp({ env = process.env, db, model, mailer, fetchImpl = fe
|
|
|
142
296
|
async function route(req, res) {
|
|
143
297
|
const url = new URL(req.url, publicUrl);
|
|
144
298
|
const path = url.pathname;
|
|
145
|
-
const method = req.method;
|
|
299
|
+
const method = req.method === 'HEAD' ? 'GET' : req.method; // node drops the body for HEAD
|
|
146
300
|
|
|
147
301
|
if (method === 'OPTIONS') return send(res, 204, '', CORS);
|
|
148
302
|
|
|
@@ -152,13 +306,26 @@ export function createApp({ env = process.env, db, model, mailer, fetchImpl = fe
|
|
|
152
306
|
return send(res, 200, `#!/bin/sh\n# Board as a Service CLI: board-saas\nset -e\ncommand -v npm >/dev/null 2>&1 || { echo "board-saas needs Node 22+ and npm: https://nodejs.org" >&2; exit 1; }\nnpm install -g @profullstack/board-saas\necho "installed: run 'board-saas login you@example.com' then 'board-saas meet \\"<brief>\\"'"\n`, { 'content-type': 'text/x-shellscript; charset=utf-8' });
|
|
153
307
|
}
|
|
154
308
|
|
|
155
|
-
if (path === '/robots.txt') return send(res, 200, 'User-agent: *\nAllow: /\nDisallow: /m/\nDisallow: /api/\n', { 'content-type': 'text/plain' });
|
|
309
|
+
if (path === '/robots.txt') return send(res, 200, 'User-agent: *\nAllow: /\nDisallow: /m/\nDisallow: /api/\nDisallow: /oauth/\n', { 'content-type': 'text/plain' });
|
|
310
|
+
|
|
311
|
+
// OAuth discovery: RFC 9728 (resource) at the root and path forms, RFC 8414 (server).
|
|
312
|
+
if (method === 'GET' && (path === '/.well-known/oauth-protected-resource' || path === '/.well-known/oauth-protected-resource/mcp')) return send(res, 200, oauth.resourceMetadata('mcp'), { ...CORS, 'cache-control': 'public, max-age=3600' });
|
|
313
|
+
if (method === 'GET' && path === '/.well-known/oauth-protected-resource/api/v1') return send(res, 200, oauth.resourceMetadata('api'), { ...CORS, 'cache-control': 'public, max-age=3600' });
|
|
314
|
+
if (method === 'GET' && (path === '/.well-known/oauth-authorization-server' || path === '/.well-known/oauth-authorization-server/mcp' || path === '/.well-known/openid-configuration')) return send(res, 200, oauth.serverMetadata(), { ...CORS, 'cache-control': 'public, max-age=3600' });
|
|
315
|
+
if (path.startsWith('/oauth/') || path === '/register') return oauthRoute(req, res, path, method, url);
|
|
156
316
|
|
|
157
317
|
if (path === '/mcp') {
|
|
158
318
|
if (method === 'GET') return send(res, 405, { error: 'POST JSON-RPC messages to this endpoint' }, { ...CORS, allow: 'POST' });
|
|
159
319
|
if (method !== 'POST') return send(res, 405, { error: 'method not allowed' }, CORS);
|
|
320
|
+
// Every MCP call needs a bearer: an OAuth access token or an API key. The 401 points the
|
|
321
|
+
// client at the resource metadata, which is how connectors find the OAuth server.
|
|
322
|
+
const key = bearer(req);
|
|
323
|
+
if (!service.actorFor(key)) {
|
|
324
|
+
await readBody(req).catch(() => '');
|
|
325
|
+
return send(res, 401, { error: key ? 'invalid_token' : 'unauthorized', error_description: key ? 'the token is expired, revoked or unknown' : 'sign in with OAuth or send Authorization: Bearer <key>' }, { ...CORS, 'www-authenticate': oauth.challenge('mcp', key ? 'invalid_token' : undefined) });
|
|
326
|
+
}
|
|
160
327
|
const msg = await jsonBody(req);
|
|
161
|
-
const handle = mcp(
|
|
328
|
+
const handle = mcp(key);
|
|
162
329
|
if (Array.isArray(msg)) {
|
|
163
330
|
const out = (await Promise.all(msg.map(handle))).filter(Boolean);
|
|
164
331
|
return out.length ? send(res, 200, out, CORS) : send(res, 202, '', CORS);
|
|
@@ -179,8 +346,7 @@ export function createApp({ env = process.env, db, model, mailer, fetchImpl = fe
|
|
|
179
346
|
if (path === '/api/v1' || path === '/api/v1/' || path === '/api') return send(res, 200, API_DOCS, CORS);
|
|
180
347
|
if (path === '/api/v1/auth/code' && method === 'POST') {
|
|
181
348
|
const b = await jsonBody(req);
|
|
182
|
-
|
|
183
|
-
return send(res, 200, await service.startLogin(b.email, ip), CORS);
|
|
349
|
+
return send(res, 200, await service.startLogin(b.email, clientIp(req)), CORS);
|
|
184
350
|
}
|
|
185
351
|
if (path === '/api/v1/auth/verify' && method === 'POST') {
|
|
186
352
|
const b = await jsonBody(req);
|
|
@@ -189,10 +355,20 @@ export function createApp({ env = process.env, db, model, mailer, fetchImpl = fe
|
|
|
189
355
|
if (path === '/api/v1/account' && method === 'GET') return send(res, 200, service.account(key), CORS);
|
|
190
356
|
if (path === '/api/v1/meetings' && method === 'POST') {
|
|
191
357
|
const b = await jsonBody(req);
|
|
192
|
-
const v = await service.createMeeting(key, b.brief);
|
|
358
|
+
const v = await service.createMeeting(key, b.brief, b.company_data ?? b.context ?? null);
|
|
193
359
|
return send(res, v.status === 'awaiting_payment' ? 402 : 201, v, CORS);
|
|
194
360
|
}
|
|
195
361
|
if (path === '/api/v1/meetings' && method === 'GET') return send(res, 200, { meetings: service.listMeetings(key) }, CORS);
|
|
362
|
+
if (path === '/api/v1/connections' && method === 'GET') {
|
|
363
|
+
const a = service.actorFor(key);
|
|
364
|
+
if (!a?.account) throw new HttpError(401, 'sign in first', { auth: true });
|
|
365
|
+
return send(res, 200, { connections: oauth.connections(a.account.id) }, NO_STORE);
|
|
366
|
+
}
|
|
367
|
+
if ((m = path.match(/^\/api\/v1\/connections\/([\w-]{3,80})$/)) && method === 'DELETE') {
|
|
368
|
+
const a = service.actorFor(key);
|
|
369
|
+
if (!a?.account) throw new HttpError(401, 'sign in first', { auth: true });
|
|
370
|
+
return send(res, 200, oauth.disconnect(a.account.id, m[1]), NO_STORE);
|
|
371
|
+
}
|
|
196
372
|
if ((m = path.match(/^\/api\/v1\/meetings\/([\w-]{8,40})$/)) && method === 'GET') return send(res, 200, service.getMeeting(m[1]), CORS);
|
|
197
373
|
if ((m = path.match(/^\/api\/v1\/meetings\/([\w-]{8,40})\/clarify$/)) && method === 'POST') {
|
|
198
374
|
const b = await jsonBody(req);
|
|
@@ -235,7 +411,9 @@ export function createApp({ env = process.env, db, model, mailer, fetchImpl = fe
|
|
|
235
411
|
} catch (e) {
|
|
236
412
|
const status = e instanceof HttpError ? e.status : e?.status && e.status < 600 ? e.status : 500;
|
|
237
413
|
if (status >= 500) log(`error ${req.method} ${req.url}: ${e?.stack ?? e}`);
|
|
238
|
-
|
|
414
|
+
const { auth, ...extra } = e.extra ?? {};
|
|
415
|
+
const headers = auth && status === 401 ? { ...CORS, 'www-authenticate': oauth.challenge('api', bearer(req) ? 'invalid_token' : undefined) } : CORS;
|
|
416
|
+
if (!res.headersSent) send(res, status, { error: status >= 500 && !(e instanceof HttpError) ? `server error: ${e.message}` : e.message, ...extra }, headers);
|
|
239
417
|
}
|
|
240
418
|
}
|
|
241
419
|
|
package/src/service.js
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
// awaiting_payment -> queued -> checking -> (needs_clarification -> queued -> checking) -> running -> done | failed
|
|
4
4
|
import { CoinPay, readWebhook, verifyWebhook } from '@profullstack/coinpay-onboard';
|
|
5
5
|
import { timingSafeEqual } from 'node:crypto';
|
|
6
|
-
import { assumptionsFor, checkBrief, clarifyingQuestions, MAX_BRIEF, runMeeting } from './meeting.js';
|
|
6
|
+
import { assumptionsFor, checkBrief, clarifyingQuestions, MAX_BRIEF, MAX_CONTEXT, runMeeting } from './meeting.js';
|
|
7
7
|
import { codeEmail, meetingDoneEmail } from './mail.js';
|
|
8
8
|
|
|
9
9
|
export const PRICE_USD = 9;
|
|
@@ -29,7 +29,7 @@ function safeEqual(a, b) {
|
|
|
29
29
|
return x.length === y.length && timingSafeEqual(x, y);
|
|
30
30
|
}
|
|
31
31
|
|
|
32
|
-
export function createService({ db, env = process.env, model, mailer, log = console.log, publicUrl = 'https://board.saas.pit.world' }) {
|
|
32
|
+
export function createService({ db, env = process.env, model, mailer, log = console.log, publicUrl = 'https://board.saas.pit.world', accountForToken = () => null }) {
|
|
33
33
|
const coinpay = env.COINPAY_API_KEY ? new CoinPay({ token: env.COINPAY_API_KEY, base: env.COINPAY_API_URL || undefined }) : null;
|
|
34
34
|
const running = new Set();
|
|
35
35
|
const maxRunning = Number(env.BOARD_MAX_MEETINGS) || 2;
|
|
@@ -41,13 +41,15 @@ export function createService({ db, env = process.env, model, mailer, log = cons
|
|
|
41
41
|
function actorFor(key) {
|
|
42
42
|
if (!key) return null;
|
|
43
43
|
if (env.BOARD_SAAS_ADMIN_KEY && safeEqual(key, env.BOARD_SAAS_ADMIN_KEY)) return { admin: true, account: null };
|
|
44
|
-
|
|
45
|
-
|
|
44
|
+
// An OAuth access token (bso_) from any connected app, or the account's own API key.
|
|
45
|
+
const viaOAuth = accountForToken(key);
|
|
46
|
+
const account = viaOAuth ? db.accountById(viaOAuth) : db.accountByKey(key);
|
|
47
|
+
return account ? { admin: false, account, oauth: !!viaOAuth } : null;
|
|
46
48
|
}
|
|
47
49
|
|
|
48
50
|
function requireActor(key) {
|
|
49
51
|
const a = actorFor(key);
|
|
50
|
-
if (!a) throw new HttpError(401, 'sign in first: POST /api/v1/auth/code with your email
|
|
52
|
+
if (!a) throw new HttpError(401, key ? 'that key or token is not valid (expired, revoked or replaced); sign in again' : 'sign in first: use OAuth (see /.well-known/oauth-authorization-server), or POST /api/v1/auth/code with your email then /api/v1/auth/verify with the code, and send "Authorization: Bearer <key>"', { auth: true });
|
|
51
53
|
return a;
|
|
52
54
|
}
|
|
53
55
|
|
|
@@ -89,6 +91,7 @@ export function createService({ db, env = process.env, model, mailer, log = cons
|
|
|
89
91
|
finished_at: row.finished_at ? new Date(row.finished_at).toISOString() : null,
|
|
90
92
|
progress: row.progress ? JSON.parse(row.progress) : null,
|
|
91
93
|
brief_text: row.brief_text,
|
|
94
|
+
has_company_data: !!row.context_text,
|
|
92
95
|
};
|
|
93
96
|
if (row.status === 'needs_clarification') {
|
|
94
97
|
const b = row.brief_json ? JSON.parse(row.brief_json) : { missing: [] };
|
|
@@ -108,24 +111,27 @@ export function createService({ db, env = process.env, model, mailer, log = cons
|
|
|
108
111
|
return v;
|
|
109
112
|
}
|
|
110
113
|
|
|
111
|
-
async function createMeeting(key, briefIn) {
|
|
114
|
+
async function createMeeting(key, briefIn, contextIn = null) {
|
|
112
115
|
const actor = requireActor(key);
|
|
113
116
|
const briefText = String(briefIn ?? '').trim();
|
|
114
117
|
if (briefText.length < 20) throw new HttpError(400, 'the brief is too short: give the decision, the options and the constraints');
|
|
115
118
|
if (briefText.length > MAX_BRIEF) throw new HttpError(400, `the brief is too long (max ${MAX_BRIEF} characters)`);
|
|
119
|
+
const ctx = contextIn && typeof contextIn === 'object' ? JSON.stringify(contextIn, null, 1) : String(contextIn ?? '');
|
|
120
|
+
const contextText = ctx.trim() || null;
|
|
121
|
+
if (contextText && contextText.length > MAX_CONTEXT) throw new HttpError(400, `the company data is too long (max ${MAX_CONTEXT} characters): send the summary figures (P&L totals, cash, runway, MRR, churn), not raw ledgers`);
|
|
116
122
|
if (actor.admin) {
|
|
117
|
-
const row = db.createMeeting({ accountId: null, briefText, status: 'queued', paidWith: 'admin' });
|
|
123
|
+
const row = db.createMeeting({ accountId: null, briefText, contextText, status: 'queued', paidWith: 'admin' });
|
|
118
124
|
kick();
|
|
119
125
|
return meetingView(row);
|
|
120
126
|
}
|
|
121
127
|
const spent = db.spend(actor.account.id);
|
|
122
128
|
if (spent) {
|
|
123
|
-
const row = db.createMeeting({ accountId: actor.account.id, briefText, status: 'queued', paidWith: spent });
|
|
129
|
+
const row = db.createMeeting({ accountId: actor.account.id, briefText, contextText, status: 'queued', paidWith: spent });
|
|
124
130
|
kick();
|
|
125
131
|
return meetingView(row);
|
|
126
132
|
}
|
|
127
133
|
if (!coinpay) throw new HttpError(503, 'payments are not configured on this server');
|
|
128
|
-
const row = db.createMeeting({ accountId: actor.account.id, briefText, status: 'awaiting_payment' });
|
|
134
|
+
const row = db.createMeeting({ accountId: actor.account.id, briefText, contextText, status: 'awaiting_payment' });
|
|
129
135
|
const session = await coinpay.createCheckoutSession({
|
|
130
136
|
amount: PRICE_USD,
|
|
131
137
|
description: 'Board as a Service: one board meeting',
|
|
@@ -250,6 +256,7 @@ export function createService({ db, env = process.env, model, mailer, log = cons
|
|
|
250
256
|
: [check.options[0] || 'Go ahead with what the brief describes', 'Do nothing for now'],
|
|
251
257
|
constraints: check.constraints,
|
|
252
258
|
assumptions: assumptionsFor(check.missing),
|
|
259
|
+
context: row.context_text || null,
|
|
253
260
|
};
|
|
254
261
|
db.transition(id, 'checking', 'running', { brief_json: JSON.stringify(brief), progress: JSON.stringify({ stage: 'round1', done: 0, of: 5 }) });
|
|
255
262
|
const meeting = await runMeeting(model, brief, {
|