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