create-heresay 0.2.22 → 0.2.23
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/package.json +1 -1
- package/release/VERSION +1 -1
- package/release/firebase.json +7 -0
- package/release/firestore.indexes.json +6 -0
- package/release/functions/lib/core/chat.js +220 -0
- package/release/functions/lib/core/handler.js +41 -5
- package/release/functions/lib/core/oauth.js +326 -0
- package/release/functions/lib/core/store.js +10 -0
- package/release/functions/lib/core/trail.js +16 -6
- package/release/functions/lib/core/types.js +1 -0
- package/release/functions/lib/core/version.js +1 -1
- package/release/functions/lib/providers/firebase/api.js +3 -3
- package/release/functions/lib/providers/firebase/firestore-store.js +28 -0
- package/release/functions/package.json +1 -1
- package/release/public/app/index.html +1 -0
- package/release/public/dashboard.css +15 -0
- package/release/public/dashboard.js +104 -4
- package/release/public/docs.html +8 -3
- package/release/public/guides/changes.json +1 -1
- package/release/public/guides/customize-apple.md +4 -3
- package/release/public/guides/customize-web.md +5 -3
- package/release/public/guides/index.json +1 -1
- package/release/public/guides/start.md +6 -5
- package/release/public/guides/whats-new.md +40 -18
- package/release/public/sdk.js +139 -23
|
@@ -0,0 +1,326 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* OAuth 2.1 for chat apps (ChatGPT, Claude and other MCP clients), so a team member can connect
|
|
3
|
+
* one to this Heresay with their own sign-in. Everything a chat app needs to find and use it:
|
|
4
|
+
*
|
|
5
|
+
* /.well-known/oauth-protected-resource[/v1/mcp] which server signs people in (RFC 9728)
|
|
6
|
+
* /.well-known/oauth-authorization-server[/v1] its endpoints (RFC 8414)
|
|
7
|
+
* POST /v1/oauth/register a chat app registers itself (RFC 7591)
|
|
8
|
+
* GET /v1/oauth/authorize sends the person to the dashboard to say yes
|
|
9
|
+
* POST /v1/oauth/approve the dashboard, signed in: yes or no
|
|
10
|
+
* POST /v1/oauth/token code (PKCE S256 only) or refresh -> tokens
|
|
11
|
+
*
|
|
12
|
+
* Public clients only (no client secrets), PKCE required, codes used once within ten minutes,
|
|
13
|
+
* access tokens for an hour, refresh tokens rotated on every use. A connection (grant) belongs
|
|
14
|
+
* to one member; removing them from the team, or revoking it in the dashboard, ends it.
|
|
15
|
+
*/
|
|
16
|
+
import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
|
|
17
|
+
export const SCOPE = 'heresay.requests';
|
|
18
|
+
const CODE_TTL_MS = 10 * 60_000;
|
|
19
|
+
export const ACCESS_TTL_MS = 3600_000;
|
|
20
|
+
const REFRESH_TTL_MS = 90 * 24 * 3600_000;
|
|
21
|
+
const json = (status, body, headers) => ({ status, body, headers });
|
|
22
|
+
const sha = (s) => createHash('sha256').update(s).digest('hex');
|
|
23
|
+
const secret = (bytes = 32) => randomBytes(bytes).toString('base64url');
|
|
24
|
+
/** Ids go before an underscore in a token, so they never contain one. */
|
|
25
|
+
const hexId = () => randomBytes(12).toString('hex');
|
|
26
|
+
const same = (a, b) => {
|
|
27
|
+
const x = Buffer.from(a), y = Buffer.from(b);
|
|
28
|
+
return x.length === y.length && timingSafeEqual(x, y);
|
|
29
|
+
};
|
|
30
|
+
const str = (v, max = 2000) => (typeof v === 'string' && v.trim() ? v.trim().slice(0, max) : null);
|
|
31
|
+
/** Chat apps call these from their servers, but tools like the MCP Inspector call from a page. */
|
|
32
|
+
export const OPEN_CORS = {
|
|
33
|
+
'access-control-allow-origin': '*',
|
|
34
|
+
'access-control-allow-methods': 'GET, POST, DELETE, OPTIONS',
|
|
35
|
+
'access-control-allow-headers': 'authorization, content-type, mcp-protocol-version, mcp-session-id',
|
|
36
|
+
'access-control-expose-headers': 'www-authenticate, mcp-session-id',
|
|
37
|
+
};
|
|
38
|
+
/**
|
|
39
|
+
* This Heresay's own address, as the chat app sees it. Hosting forwards the host it was asked
|
|
40
|
+
* for; only this Heresay's own origins are believed, so a forged header can't move the issuer.
|
|
41
|
+
*/
|
|
42
|
+
export function baseUrl(req, deps) {
|
|
43
|
+
const own = deps.selfOrigins ?? [];
|
|
44
|
+
const host = req.headers['x-forwarded-host'] ?? req.headers['host'];
|
|
45
|
+
const proto = req.headers['x-forwarded-proto'] ?? (host && /^(127\.0\.0\.1|localhost)(:|$)/.test(host) ? 'http' : 'https');
|
|
46
|
+
const asked = host ? `${proto.split(',')[0]}://${host.split(',')[0]}`.toLowerCase() : null;
|
|
47
|
+
if (asked && own.includes(asked))
|
|
48
|
+
return asked;
|
|
49
|
+
return own[0] ?? asked ?? '';
|
|
50
|
+
}
|
|
51
|
+
export const resourceUrl = (base) => `${base}/v1/mcp`;
|
|
52
|
+
/** Bodies arrive as JSON or as a form (the token endpoint's usual shape). */
|
|
53
|
+
function fields(b) {
|
|
54
|
+
if (b instanceof Uint8Array)
|
|
55
|
+
b = Buffer.from(b).toString('utf8');
|
|
56
|
+
if (typeof b === 'string') {
|
|
57
|
+
try {
|
|
58
|
+
return JSON.parse(b);
|
|
59
|
+
}
|
|
60
|
+
catch {
|
|
61
|
+
return Object.fromEntries(new URLSearchParams(b));
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
return b && typeof b === 'object' ? b : {};
|
|
65
|
+
}
|
|
66
|
+
/** Per network, per hour: these endpoints have no sign-in, so they're limited like /v1/reports. */
|
|
67
|
+
async function limited(what, limit, req, deps) {
|
|
68
|
+
const hour = Math.floor(deps.now() / 3600_000) * 3600_000;
|
|
69
|
+
return deps.store.hit(`oauth-${what}:${sha(req.ip)}:${hour}`, limit, hour + 3600_000);
|
|
70
|
+
}
|
|
71
|
+
// ---- discovery ---------------------------------------------------------------------------
|
|
72
|
+
export function protectedResource(req, deps) {
|
|
73
|
+
const base = baseUrl(req, deps);
|
|
74
|
+
return json(200, {
|
|
75
|
+
resource: resourceUrl(base), authorization_servers: [base], scopes_supported: [SCOPE],
|
|
76
|
+
bearer_methods_supported: ['header'], resource_name: 'Heresay',
|
|
77
|
+
}, OPEN_CORS);
|
|
78
|
+
}
|
|
79
|
+
export function authorizationServer(req, deps) {
|
|
80
|
+
const base = baseUrl(req, deps);
|
|
81
|
+
return json(200, {
|
|
82
|
+
issuer: base,
|
|
83
|
+
authorization_endpoint: `${base}/v1/oauth/authorize`,
|
|
84
|
+
token_endpoint: `${base}/v1/oauth/token`,
|
|
85
|
+
registration_endpoint: `${base}/v1/oauth/register`,
|
|
86
|
+
response_types_supported: ['code'],
|
|
87
|
+
grant_types_supported: ['authorization_code', 'refresh_token'],
|
|
88
|
+
code_challenge_methods_supported: ['S256'],
|
|
89
|
+
token_endpoint_auth_methods_supported: ['none'],
|
|
90
|
+
scopes_supported: [SCOPE],
|
|
91
|
+
}, OPEN_CORS);
|
|
92
|
+
}
|
|
93
|
+
// ---- registration ------------------------------------------------------------------------
|
|
94
|
+
/** https anywhere, or http on this computer (for local tools). Nothing else, no fragments. */
|
|
95
|
+
export function okRedirect(u) {
|
|
96
|
+
if (typeof u !== 'string' || u.length > 500)
|
|
97
|
+
return null;
|
|
98
|
+
try {
|
|
99
|
+
const x = new URL(u);
|
|
100
|
+
if (x.hash)
|
|
101
|
+
return null;
|
|
102
|
+
if (x.protocol === 'https:')
|
|
103
|
+
return x.href;
|
|
104
|
+
if (x.protocol === 'http:' && /^(localhost|127\.0\.0\.1|\[::1\])$/.test(x.hostname))
|
|
105
|
+
return x.href;
|
|
106
|
+
}
|
|
107
|
+
catch { /* not a URL */ }
|
|
108
|
+
return null;
|
|
109
|
+
}
|
|
110
|
+
export async function register(req, deps) {
|
|
111
|
+
const b = fields(req.body);
|
|
112
|
+
const now = deps.now();
|
|
113
|
+
if (!(await limited('register', 20, req, deps)))
|
|
114
|
+
return json(429, { error: 'too_many_requests' }, OPEN_CORS);
|
|
115
|
+
const uris = Array.isArray(b.redirect_uris) ? b.redirect_uris.map(okRedirect) : [];
|
|
116
|
+
if (!uris.length || uris.some((u) => !u)) {
|
|
117
|
+
return json(400, { error: 'invalid_redirect_uri', error_description: 'redirect_uris must be https URLs (or http on localhost)' }, OPEN_CORS);
|
|
118
|
+
}
|
|
119
|
+
if (b.token_endpoint_auth_method && b.token_endpoint_auth_method !== 'none') {
|
|
120
|
+
return json(400, { error: 'invalid_client_metadata', error_description: 'only public clients (token_endpoint_auth_method "none")' }, OPEN_CORS);
|
|
121
|
+
}
|
|
122
|
+
const client_id = `hc_${secret(16)}`;
|
|
123
|
+
const name = str(b.client_name, 80) ?? new URL(uris[0]).hostname;
|
|
124
|
+
await deps.store.putAuth({
|
|
125
|
+
kind: 'client', id: client_id, expires_at: null,
|
|
126
|
+
data: { name, redirect_uris: uris, created_at: new Date(now).toISOString() },
|
|
127
|
+
});
|
|
128
|
+
deps.log('oauth.client_registered', { client_id, name });
|
|
129
|
+
return json(201, {
|
|
130
|
+
client_id, client_id_issued_at: Math.floor(now / 1000), client_name: name, redirect_uris: uris,
|
|
131
|
+
token_endpoint_auth_method: 'none', grant_types: ['authorization_code', 'refresh_token'], response_types: ['code'],
|
|
132
|
+
}, OPEN_CORS);
|
|
133
|
+
}
|
|
134
|
+
/** The request is one we'd say yes to: a known client, its own redirect, PKCE S256. */
|
|
135
|
+
async function checkAsk(q, deps) {
|
|
136
|
+
const client_id = str(q.client_id, 100);
|
|
137
|
+
const client = client_id ? await deps.store.getAuth('client', client_id) : null;
|
|
138
|
+
if (!client_id || !client)
|
|
139
|
+
return { error: 'invalid_client', description: 'This chat app isn\'t registered here. Add the connector again.' };
|
|
140
|
+
const redirect_uri = okRedirect(q.redirect_uri);
|
|
141
|
+
if (!redirect_uri || !client.data.redirect_uris.includes(redirect_uri)) {
|
|
142
|
+
return { error: 'invalid_request', description: 'redirect_uri doesn\'t match the one registered' };
|
|
143
|
+
}
|
|
144
|
+
if (q.response_type !== 'code')
|
|
145
|
+
return { error: 'unsupported_response_type', description: 'response_type must be code' };
|
|
146
|
+
const code_challenge = str(q.code_challenge, 200);
|
|
147
|
+
if (!code_challenge || q.code_challenge_method !== 'S256' || !/^[A-Za-z0-9_-]{43,128}$/.test(code_challenge)) {
|
|
148
|
+
return { error: 'invalid_request', description: 'PKCE with S256 is required' };
|
|
149
|
+
}
|
|
150
|
+
return { client_id, redirect_uri, state: str(q.state, 500), code_challenge, scope: SCOPE, client };
|
|
151
|
+
}
|
|
152
|
+
const withParams = (u, p) => {
|
|
153
|
+
const x = new URL(u);
|
|
154
|
+
for (const [k, v] of Object.entries(p))
|
|
155
|
+
if (v != null)
|
|
156
|
+
x.searchParams.set(k, v);
|
|
157
|
+
return x.href;
|
|
158
|
+
};
|
|
159
|
+
/** The chat app sends the person here. They say yes on the dashboard, signed in as themselves. */
|
|
160
|
+
export async function authorize(req, deps) {
|
|
161
|
+
if (!(await limited('authorize', 120, req, deps)))
|
|
162
|
+
return json(429, { error: 'too_many_requests' });
|
|
163
|
+
const ask = await checkAsk(req.query, deps);
|
|
164
|
+
// A bad client or redirect is shown, never redirected to: that's how open redirects happen.
|
|
165
|
+
if ('error' in ask)
|
|
166
|
+
return json(400, { error: ask.error, error_description: ask.description });
|
|
167
|
+
const keep = new URLSearchParams();
|
|
168
|
+
for (const k of ['client_id', 'redirect_uri', 'state', 'code_challenge', 'code_challenge_method', 'response_type', 'scope', 'resource']) {
|
|
169
|
+
const v = req.query[k];
|
|
170
|
+
if (v)
|
|
171
|
+
keep.set(k, v);
|
|
172
|
+
}
|
|
173
|
+
return json(302, { redirect: true }, { location: `${baseUrl(req, deps)}/app/#/authorize?${keep}` });
|
|
174
|
+
}
|
|
175
|
+
/** What the dashboard shows on the "Allow?" page, before anyone says yes. */
|
|
176
|
+
export async function describeAsk(q, deps) {
|
|
177
|
+
const ask = await checkAsk(q, deps);
|
|
178
|
+
if ('error' in ask)
|
|
179
|
+
return json(400, { error: ask.description, code: ask.error });
|
|
180
|
+
return json(200, { client_name: ask.client.data.name, redirect_host: new URL(ask.redirect_uri).host });
|
|
181
|
+
}
|
|
182
|
+
/** POST /v1/oauth/approve, from the dashboard, as the signed-in member. */
|
|
183
|
+
export async function approve(member, req, deps) {
|
|
184
|
+
const b = fields(req.body);
|
|
185
|
+
const ask = await checkAsk(b, deps);
|
|
186
|
+
if ('error' in ask)
|
|
187
|
+
return json(400, { error: ask.description, code: ask.error });
|
|
188
|
+
if (b.allow !== true) {
|
|
189
|
+
deps.log('oauth.denied', { client_id: ask.client_id, by: member.email });
|
|
190
|
+
return json(200, { redirect: withParams(ask.redirect_uri, { error: 'access_denied', state: ask.state }) });
|
|
191
|
+
}
|
|
192
|
+
const code = secret();
|
|
193
|
+
await deps.store.putAuth({
|
|
194
|
+
kind: 'code', id: sha(code), expires_at: new Date(deps.now() + CODE_TTL_MS).toISOString(),
|
|
195
|
+
data: { client_id: ask.client_id, redirect_uri: ask.redirect_uri, code_challenge: ask.code_challenge, email: member.email, scope: ask.scope },
|
|
196
|
+
});
|
|
197
|
+
deps.log('oauth.approved', { client_id: ask.client_id, by: member.email });
|
|
198
|
+
return json(200, { redirect: withParams(ask.redirect_uri, { code, state: ask.state }) });
|
|
199
|
+
}
|
|
200
|
+
// ---- tokens ------------------------------------------------------------------------------
|
|
201
|
+
const tokenError = (error, error_description, status = 400) => json(status, { error, error_description }, { ...OPEN_CORS, 'cache-control': 'no-store' });
|
|
202
|
+
/** hat_<id>_<secret> for access, hrt_<grant>_<secret> for refresh: the id finds it, the hash checks it. */
|
|
203
|
+
async function issue(grant, deps) {
|
|
204
|
+
const now = deps.now();
|
|
205
|
+
const accessId = hexId(), accessSecret = secret();
|
|
206
|
+
await deps.store.putAuth({
|
|
207
|
+
kind: 'access', id: accessId, expires_at: new Date(now + ACCESS_TTL_MS).toISOString(),
|
|
208
|
+
data: { grant_id: grant.id, hash: sha(accessSecret) },
|
|
209
|
+
});
|
|
210
|
+
const refreshSecret = secret();
|
|
211
|
+
await deps.store.putAuth({
|
|
212
|
+
...grant, expires_at: new Date(now + REFRESH_TTL_MS).toISOString(),
|
|
213
|
+
data: { ...grant.data, refresh_hash: sha(refreshSecret), refreshed_at: new Date(now).toISOString() },
|
|
214
|
+
});
|
|
215
|
+
return json(200, {
|
|
216
|
+
access_token: `hat_${accessId}_${accessSecret}`, token_type: 'Bearer', expires_in: ACCESS_TTL_MS / 1000,
|
|
217
|
+
refresh_token: `hrt_${grant.id}_${refreshSecret}`, scope: SCOPE,
|
|
218
|
+
}, { ...OPEN_CORS, 'cache-control': 'no-store' });
|
|
219
|
+
}
|
|
220
|
+
/** S256: base64url(sha256(verifier)) must equal the challenge sent at the start. */
|
|
221
|
+
export const pkce = (verifier) => createHash('sha256').update(verifier).digest('base64url');
|
|
222
|
+
export async function token(req, deps) {
|
|
223
|
+
if (!(await limited('token', 240, req, deps)))
|
|
224
|
+
return tokenError('too_many_requests', 'Try again later.', 429);
|
|
225
|
+
const b = fields(req.body);
|
|
226
|
+
const instance = await deps.store.getInstance();
|
|
227
|
+
if (b.grant_type === 'authorization_code') {
|
|
228
|
+
const code = str(b.code, 200), verifier = str(b.code_verifier, 200);
|
|
229
|
+
if (!code || !verifier)
|
|
230
|
+
return tokenError('invalid_request', 'code and code_verifier are required');
|
|
231
|
+
const c = await deps.store.takeAuth('code', sha(code));
|
|
232
|
+
if (!c || Date.parse(c.expires_at ?? '') < deps.now())
|
|
233
|
+
return tokenError('invalid_grant', 'This code was used, has expired, or never existed.');
|
|
234
|
+
if (c.data.client_id !== b.client_id || c.data.redirect_uri !== okRedirect(b.redirect_uri)) {
|
|
235
|
+
return tokenError('invalid_grant', 'client_id or redirect_uri doesn\'t match the code');
|
|
236
|
+
}
|
|
237
|
+
if (!same(pkce(verifier), String(c.data.code_challenge)))
|
|
238
|
+
return tokenError('invalid_grant', 'code_verifier doesn\'t match');
|
|
239
|
+
if (!onTeam(instance, String(c.data.email)))
|
|
240
|
+
return tokenError('invalid_grant', 'That person is no longer on this Heresay\'s team.');
|
|
241
|
+
const client = await deps.store.getAuth('client', String(c.data.client_id));
|
|
242
|
+
const grant = {
|
|
243
|
+
kind: 'grant', id: hexId(), expires_at: null,
|
|
244
|
+
data: {
|
|
245
|
+
email: c.data.email, client_id: c.data.client_id, client_name: client?.data.name ?? 'A chat app',
|
|
246
|
+
created_at: new Date(deps.now()).toISOString(), last_used_at: null, revoked_at: null,
|
|
247
|
+
},
|
|
248
|
+
};
|
|
249
|
+
deps.log('oauth.connected', { grant_id: grant.id, by: c.data.email, client: grant.data.client_name });
|
|
250
|
+
return issue(grant, deps);
|
|
251
|
+
}
|
|
252
|
+
if (b.grant_type === 'refresh_token') {
|
|
253
|
+
const m = /^hrt_([a-f0-9]{24})_([A-Za-z0-9_-]{20,80})$/.exec(String(b.refresh_token ?? ''));
|
|
254
|
+
const grant = m ? await deps.store.getAuth('grant', m[1]) : null;
|
|
255
|
+
if (!m || !grant || grant.data.revoked_at || !same(sha(m[2]), String(grant.data.refresh_hash))
|
|
256
|
+
|| (grant.expires_at && Date.parse(grant.expires_at) < deps.now())) {
|
|
257
|
+
return tokenError('invalid_grant', 'This connection was revoked or has expired. Connect again.');
|
|
258
|
+
}
|
|
259
|
+
if (b.client_id && b.client_id !== grant.data.client_id)
|
|
260
|
+
return tokenError('invalid_grant', 'client_id doesn\'t match');
|
|
261
|
+
if (!onTeam(instance, String(grant.data.email)))
|
|
262
|
+
return tokenError('invalid_grant', 'That person is no longer on this Heresay\'s team.');
|
|
263
|
+
return issue(grant, deps);
|
|
264
|
+
}
|
|
265
|
+
return tokenError('unsupported_grant_type', 'grant_type must be authorization_code or refresh_token');
|
|
266
|
+
}
|
|
267
|
+
const onTeam = (i, email) => !!i?.members.some((m) => m.email.toLowerCase() === email.toLowerCase());
|
|
268
|
+
/**
|
|
269
|
+
* Who a chat app's access token is for: the member and their connection, or null. Checked on
|
|
270
|
+
* every call, so a revoked connection or a removed member stops at once, not in an hour.
|
|
271
|
+
*/
|
|
272
|
+
export async function chatCaller(req, deps) {
|
|
273
|
+
const m = /^Bearer hat_([a-f0-9]{24})_([A-Za-z0-9_-]{20,80})$/.exec(req.headers['authorization'] ?? '');
|
|
274
|
+
if (!m)
|
|
275
|
+
return null;
|
|
276
|
+
const a = await deps.store.getAuth('access', m[1]);
|
|
277
|
+
if (!a || !same(sha(m[2]), String(a.data.hash)) || Date.parse(a.expires_at ?? '') < deps.now())
|
|
278
|
+
return null;
|
|
279
|
+
const grant = await deps.store.getAuth('grant', String(a.data.grant_id));
|
|
280
|
+
if (!grant || grant.data.revoked_at)
|
|
281
|
+
return null;
|
|
282
|
+
const instance = await deps.store.getInstance();
|
|
283
|
+
const member = instance?.members.find((x) => x.email.toLowerCase() === String(grant.data.email).toLowerCase());
|
|
284
|
+
if (!member)
|
|
285
|
+
return null;
|
|
286
|
+
// At most once a minute, so the dashboard can say when it was last used.
|
|
287
|
+
const last = Date.parse(String(grant.data.last_used_at ?? '')) || 0;
|
|
288
|
+
if (deps.now() - last > 60_000) {
|
|
289
|
+
await deps.store.putAuth({ ...grant, data: { ...grant.data, last_used_at: new Date(deps.now()).toISOString() } });
|
|
290
|
+
}
|
|
291
|
+
return { member, grant };
|
|
292
|
+
}
|
|
293
|
+
/** 401 that tells a chat app where to sign in (RFC 9728 §5.1). */
|
|
294
|
+
export const signInFirst = (req, deps) => json(401, {
|
|
295
|
+
jsonrpc: '2.0', error: { code: -32001, message: 'Sign in to this Heresay first.' }, id: null,
|
|
296
|
+
}, {
|
|
297
|
+
...OPEN_CORS,
|
|
298
|
+
'www-authenticate': `Bearer realm="heresay", resource_metadata="${baseUrl(req, deps)}/.well-known/oauth-protected-resource/v1/mcp", scope="${SCOPE}"`,
|
|
299
|
+
});
|
|
300
|
+
// ---- connections, from the dashboard -------------------------------------------------------
|
|
301
|
+
/** GET /v1/chat-connections, DELETE /v1/chat-connections/:id. Yours, or anyone's for an owner. */
|
|
302
|
+
export async function connections(p, member, req, deps) {
|
|
303
|
+
const mine = (g) => String(g.data.email).toLowerCase() === member.email.toLowerCase();
|
|
304
|
+
if (p.length === 1 && req.method === 'GET') {
|
|
305
|
+
const all = (await deps.store.listAuth('grant')).filter((g) => !g.data.revoked_at && (member.role === 'owner' || mine(g)));
|
|
306
|
+
all.sort((a, b) => String(a.data.created_at).localeCompare(String(b.data.created_at)));
|
|
307
|
+
return json(200, {
|
|
308
|
+
connections: all.map((g) => ({
|
|
309
|
+
id: g.id, email: g.data.email, client_name: g.data.client_name,
|
|
310
|
+
created_at: g.data.created_at, last_used_at: g.data.last_used_at ?? null,
|
|
311
|
+
})),
|
|
312
|
+
});
|
|
313
|
+
}
|
|
314
|
+
if (p.length === 2 && req.method === 'DELETE') {
|
|
315
|
+
const g = await deps.store.getAuth('grant', p[1]);
|
|
316
|
+
if (!g || g.data.revoked_at)
|
|
317
|
+
return json(404, { error: 'no such connection' });
|
|
318
|
+
if (!mine(g) && member.role !== 'owner')
|
|
319
|
+
return json(403, { error: 'Only an owner can disconnect someone else\'s chat app.' });
|
|
320
|
+
await deps.store.putAuth({ ...g, data: { ...g.data, revoked_at: new Date(deps.now()).toISOString(), revoked_by: member.email } });
|
|
321
|
+
deps.log('oauth.revoked', { grant_id: g.id, by: member.email });
|
|
322
|
+
return json(200, { ok: true });
|
|
323
|
+
}
|
|
324
|
+
return json(404, { error: 'not found' });
|
|
325
|
+
}
|
|
326
|
+
//# sourceMappingURL=oauth.js.map
|
|
@@ -5,6 +5,7 @@ export class MemoryStore {
|
|
|
5
5
|
reports = new Map();
|
|
6
6
|
tasks = new Map();
|
|
7
7
|
tokens = new Map();
|
|
8
|
+
auth = new Map();
|
|
8
9
|
buckets = new Map();
|
|
9
10
|
async getInstance() { return this.instance ? structuredClone(this.instance) : null; }
|
|
10
11
|
async updateInstance(fn) {
|
|
@@ -92,6 +93,15 @@ export class MemoryStore {
|
|
|
92
93
|
if (t)
|
|
93
94
|
this.tokens.set(id, { ...t, ...patch, id });
|
|
94
95
|
}
|
|
96
|
+
async putAuth(r) { this.auth.set(`${r.kind}:${r.id}`, structuredClone(r)); }
|
|
97
|
+
async getAuth(kind, id) { const r = this.auth.get(`${kind}:${id}`); return r ? structuredClone(r) : null; }
|
|
98
|
+
async takeAuth(kind, id) {
|
|
99
|
+
const r = this.auth.get(`${kind}:${id}`);
|
|
100
|
+
this.auth.delete(`${kind}:${id}`);
|
|
101
|
+
return r ? structuredClone(r) : null;
|
|
102
|
+
}
|
|
103
|
+
async deleteAuth(kind, id) { this.auth.delete(`${kind}:${id}`); }
|
|
104
|
+
async listAuth(kind) { return [...this.auth.values()].filter((r) => r.kind === kind).map((r) => structuredClone(r)); }
|
|
95
105
|
async hit(bucket, limit) {
|
|
96
106
|
const n = this.buckets.get(bucket) ?? 0;
|
|
97
107
|
if (n >= limit)
|
|
@@ -51,7 +51,8 @@ export function parseTrail(v) {
|
|
|
51
51
|
if (total > TRAIL_LIMITS.totalMax)
|
|
52
52
|
break;
|
|
53
53
|
const num = (x, lo, hi) => typeof x === 'number' && Number.isFinite(x) ? Math.min(hi, Math.max(lo, Math.round(x))) : lo;
|
|
54
|
-
out.push({ kind: o.kind, ago: num(o.ago, 0, TRAIL_LIMITS.agoMax), text, detail, n: num(o.n, 1, TRAIL_LIMITS.nMax)
|
|
54
|
+
out.push({ kind: o.kind, ago: num(o.ago, 0, TRAIL_LIMITS.agoMax), text, detail, n: num(o.n, 1, TRAIL_LIMITS.nMax),
|
|
55
|
+
...(o.run === 'last' ? { run: 'last' } : {}) });
|
|
55
56
|
}
|
|
56
57
|
out.reverse();
|
|
57
58
|
return out.length ? out : null;
|
|
@@ -60,11 +61,20 @@ const LABEL = {
|
|
|
60
61
|
page: 'Page', click: 'Click', request: 'Request', error: 'Error', warn: 'Warning', state: 'Device',
|
|
61
62
|
};
|
|
62
63
|
const ago = (s) => (s >= 60 ? `-${Math.floor(s / 60)}:${String(s % 60).padStart(2, '0')}` : `-0:${String(s).padStart(2, '0')}`);
|
|
63
|
-
/**
|
|
64
|
+
/**
|
|
65
|
+
* The trail as lines of plain text, oldest first, for an agent prompt or a notification. Events
|
|
66
|
+
* from the run that crashed come first, under their own heading, timed from when it ended.
|
|
67
|
+
*/
|
|
64
68
|
export function trailLines(t) {
|
|
65
|
-
|
|
66
|
-
const
|
|
67
|
-
return e.detail ? `${
|
|
68
|
-
}
|
|
69
|
+
const line = (e) => {
|
|
70
|
+
const l = `${ago(e.ago)} ${LABEL[e.kind]}: ${e.text}${e.n > 1 ? ` (x${e.n})` : ''}`;
|
|
71
|
+
return e.detail ? `${l}\n${e.detail.split('\n').map((x) => ` ${x}`).join('\n')}` : l;
|
|
72
|
+
};
|
|
73
|
+
const last = t.filter((e) => e.run === 'last');
|
|
74
|
+
if (!last.length)
|
|
75
|
+
return t.map(line);
|
|
76
|
+
const now = t.filter((e) => e.run !== 'last');
|
|
77
|
+
return ['The run that crashed or closed, timed back from when it ended:', ...last.map(line),
|
|
78
|
+
...(now.length ? ['This run, timed back from the report:', ...now.map(line)] : [])];
|
|
69
79
|
}
|
|
70
80
|
//# sourceMappingURL=trail.js.map
|
|
@@ -33,7 +33,7 @@ function selfOrigins() {
|
|
|
33
33
|
return ['http://127.0.0.1:5055', 'http://localhost:5055'];
|
|
34
34
|
return id ? [`https://${id}.web.app`, `https://${id}.firebaseapp.com`] : [];
|
|
35
35
|
}
|
|
36
|
-
/** Hosting rewrites /v1/** here, so the SDK, the API and the dashboard share one origin. */
|
|
36
|
+
/** Hosting rewrites /v1/** and /.well-known/** here, so the SDK, the API and the dashboard share one origin. */
|
|
37
37
|
// create-heresay writes HERESAY_REGION to functions/.env; it is read when the deploy loads this file.
|
|
38
38
|
export const api = onRequest({ region: process.env.HERESAY_REGION || 'us-central1', maxInstances: 10 }, async (req, res) => {
|
|
39
39
|
const headers = {};
|
|
@@ -49,8 +49,8 @@ export const api = onRequest({ region: process.env.HERESAY_REGION || 'us-central
|
|
|
49
49
|
}, deps);
|
|
50
50
|
for (const [k, v] of Object.entries(out.headers ?? {}))
|
|
51
51
|
res.setHeader(k, v);
|
|
52
|
-
if (out.status === 204) {
|
|
53
|
-
res.status(
|
|
52
|
+
if (out.status === 204 || out.body === null) {
|
|
53
|
+
res.status(out.status).end();
|
|
54
54
|
return;
|
|
55
55
|
}
|
|
56
56
|
res.status(out.status).json(out.body);
|
|
@@ -4,6 +4,8 @@
|
|
|
4
4
|
* projects/{project_id}/reports/{report_id}
|
|
5
5
|
* projects/{project_id}/tasks/{report_id} written only by accept(), read only by the prompt
|
|
6
6
|
* agent_tokens/{id} one per connected repo; secret stored hashed
|
|
7
|
+
* auth/{kind}:{id} chat-app OAuth: clients, codes, grants, access tokens;
|
|
8
|
+
* expire_at for a TTL policy
|
|
7
9
|
* rate/{bucket} has expire_at for a Firestore TTL policy
|
|
8
10
|
*
|
|
9
11
|
* Clients never touch Firestore directly (firestore.rules denies everything); all of it goes
|
|
@@ -130,6 +132,32 @@ export class FirestoreStore {
|
|
|
130
132
|
const { id: _ignored, ...rest } = patch;
|
|
131
133
|
await this.tokens().doc(id).update(rest);
|
|
132
134
|
}
|
|
135
|
+
authRef(kind, id) { return this.db.collection('auth').doc(`${kind}:${id}`); }
|
|
136
|
+
static withExpiry(r) { return { ...r, expire_at: r.expires_at ? new Date(r.expires_at) : null }; }
|
|
137
|
+
static plain(d) {
|
|
138
|
+
const { expire_at: _, ...r } = d;
|
|
139
|
+
return r;
|
|
140
|
+
}
|
|
141
|
+
async putAuth(r) { await this.authRef(r.kind, r.id).set(FirestoreStore.withExpiry(r)); }
|
|
142
|
+
async getAuth(kind, id) {
|
|
143
|
+
const s = await this.authRef(kind, id).get();
|
|
144
|
+
return s.exists ? FirestoreStore.plain(s.data()) : null;
|
|
145
|
+
}
|
|
146
|
+
async takeAuth(kind, id) {
|
|
147
|
+
const ref = this.authRef(kind, id);
|
|
148
|
+
return this.db.runTransaction(async (tx) => {
|
|
149
|
+
const s = await tx.get(ref);
|
|
150
|
+
if (!s.exists)
|
|
151
|
+
return null;
|
|
152
|
+
tx.delete(ref);
|
|
153
|
+
return FirestoreStore.plain(s.data());
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
async deleteAuth(kind, id) { await this.authRef(kind, id).delete(); }
|
|
157
|
+
async listAuth(kind) {
|
|
158
|
+
const q = await this.db.collection('auth').where('kind', '==', kind).get();
|
|
159
|
+
return q.docs.map((d) => FirestoreStore.plain(d.data()));
|
|
160
|
+
}
|
|
133
161
|
async hit(bucket, limit, expires_at) {
|
|
134
162
|
const ref = this.db.collection('rate').doc(bucket.replaceAll('/', '_'));
|
|
135
163
|
return this.db.runTransaction(async (tx) => {
|
|
@@ -9,7 +9,7 @@
|
|
|
9
9
|
"scripts": {
|
|
10
10
|
"build": "tsc -p tsconfig.json",
|
|
11
11
|
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
12
|
-
"test": "tsc -p tsconfig.test.json && node --test 'lib-test/test/handler.test.js' 'lib-test/test/agent.test.js' 'lib-test/test/notifications.test.js' 'lib-test/test/store-memory.test.js'",
|
|
12
|
+
"test": "tsc -p tsconfig.test.json && node --test 'lib-test/test/handler.test.js' 'lib-test/test/agent.test.js' 'lib-test/test/notifications.test.js' 'lib-test/test/store-memory.test.js' 'lib-test/test/chat.test.js'",
|
|
13
13
|
"build:test": "tsc -p tsconfig.test.json"
|
|
14
14
|
},
|
|
15
15
|
"dependencies": {
|
|
@@ -45,6 +45,7 @@
|
|
|
45
45
|
<a href="#/" data-nav="apps">Apps</a>
|
|
46
46
|
<a href="#/team" data-nav="team">Team</a>
|
|
47
47
|
<a href="#/notifications" data-nav="notifications">Notifications</a>
|
|
48
|
+
<a href="#/chat" data-nav="chat">Chat apps</a>
|
|
48
49
|
</nav>
|
|
49
50
|
<span class="spacer"></span>
|
|
50
51
|
<span id="who" class="who"></span>
|
|
@@ -237,6 +237,8 @@ a.platform:hover { border-color:var(--acc); box-shadow:0 0 0 3px var(--mist); }
|
|
|
237
237
|
.trail .ago { flex:none; width:40px; font:12px var(--mono); color:var(--mute); }
|
|
238
238
|
.trail .kind { flex:none; width:62px; font-size:11px; font-weight:700; text-transform:uppercase; letter-spacing:.04em; color:var(--mute); }
|
|
239
239
|
.trail .what { min-width:0; word-break:break-word; }
|
|
240
|
+
.trail li.k-run { padding-top:8px; font-size:11px; font-weight:700; text-transform:uppercase; letter-spacing:.04em; color:var(--mute); }
|
|
241
|
+
.trail li.k-run::before { display:none; }
|
|
240
242
|
.trail pre { margin:2px 0 0; font:11.5px/1.5 var(--mono); color:var(--mute); white-space:pre-wrap; }
|
|
241
243
|
.trail .k-page::before, .trail .k-sent::before { border-color:var(--acc); }
|
|
242
244
|
.trail .k-sent::before { background:var(--acc); }
|
|
@@ -433,3 +435,16 @@ a.platform:hover { border-color:var(--acc); box-shadow:0 0 0 3px var(--mist); }
|
|
|
433
435
|
.top .tabs a { padding:6px 10px; }
|
|
434
436
|
.top .who { max-width:130px; overflow:hidden; text-overflow:ellipsis; white-space:nowrap; }
|
|
435
437
|
}
|
|
438
|
+
|
|
439
|
+
/* chat apps */
|
|
440
|
+
.pill.chat-pill { background:#eef2ff; color:#3730a3; }
|
|
441
|
+
.chat-details { margin-top:8px; font-size:14px; }
|
|
442
|
+
.chat-details summary { cursor:pointer; color:var(--mute); font-size:13px; }
|
|
443
|
+
.chat-details p { margin:6px 0 0; padding:10px 12px; border-radius:10px; background:var(--soft, #f5f6f7); white-space:pre-wrap; word-break:break-word; }
|
|
444
|
+
.howto { margin:0; padding-left:20px; line-height:1.7; }
|
|
445
|
+
.howto li + li { margin-top:4px; }
|
|
446
|
+
.howto .copy-prompt { flex-direction:row; align-items:center; flex-wrap:wrap; }
|
|
447
|
+
.howto code.url { padding:4px 8px; border-radius:6px; background:var(--soft, #f5f6f7); }
|
|
448
|
+
.authorize { max-width:520px; margin:6vh auto 0; text-align:left; }
|
|
449
|
+
.authorize h1 { margin:10px 0 6px; font-size:22px; }
|
|
450
|
+
.authorize .can { margin:6px 0 12px; padding-left:20px; line-height:1.6; }
|