Skip to content
refs
52 lines · 2.3 KBRaw
1import { createAccessToken, now, sha256 } from "../auth.ts";
2import type { Person } from "../contract/actor.ts";
3import type { Me } from "../contract/handles.ts";
4import * as mail from "../mail.ts";
5import { captureAccountEvent } from "../analytics.ts";
6import { conflict, invalid, ok, problem } from "../outcomes.ts";
7import { activateUser } from "../repos.ts";
8import { agentGrants, revokeAgentGrant } from "../oauth.ts";
9
10export function openMe(env: Env, person: Person): Me {
11 const db = env.DB;
12 return {
13 person,
14
15 async tokens() {
16 const { results } = await db
17 .prepare("SELECT id, name, created_at AS createdAt, last_used_at AS lastUsedAt FROM access_tokens WHERE user_id = ? ORDER BY created_at DESC")
18 .bind(person.id)
19 .all<{ id: string; name: string; createdAt: number; lastUsedAt: number | null }>();
20 return results;
21 },
22
23 async createToken(name) {
24 const text = name.trim();
25 if (!text || text.length > 64) return invalid("Token name must be 1–64 characters.", "name");
26 const secret = await createAccessToken(db, person.id, text);
27 const token = (await db.prepare("SELECT id, name, created_at AS createdAt, last_used_at AS lastUsedAt FROM access_tokens WHERE token_hash = ?").bind(await sha256(secret)).first<{ id: string; name: string; createdAt: number; lastUsedAt: number | null }>())!;
28 return ok({ token, secret });
29 },
30
31 async revokeToken(id) {
32 await db.prepare("DELETE FROM access_tokens WHERE id = ? AND user_id = ?").bind(id, person.id).run();
33 return ok();
34 },
35
36 agentGrants: () => agentGrants(env, person.id),
37
38 async revokeAgentGrant(id) {
39 await revokeAgentGrant(env, person.id, id);
40 await endGrantSessions(env.DB, person.id, id, now());
41 return ok();
42 },
43 };
44}
45
46/**
47 * Ends the live sessions an OAuth grant started, once the human revokes it, so their git tokens stop working too.
48 * Sessions from before grants were recorded have no grant, and end with any revocation.
49 */
50export async function endGrantSessions(db: D1Database, userId: string, grantId: string, at: number): Promise<void> {
51 await db.prepare("UPDATE agent_sessions SET status = 'finished', ended_at = ? WHERE user_id = ? AND (grant_id = ? OR grant_id IS NULL) AND ended_at IS NULL").bind(at, userId, grantId).run();
52}