Branchwell

Skillfarm / website · skillfarm.ai / src / lib / tokens.ts

Raw 3.0 KB on c724bfa127f7a93b48788385cedf1e60cb4e7943
1import type { Env, User } from '../env';
2import { newId, now, randomToken, sha256Hex } from './util';
3
4export const SCOPES = ['skills:read', 'skills:write'] as const;
5export type Scope = (typeof SCOPES)[number];
6export const SCOPE_TEXT: Record<Scope, string> = {
7 'skills:read': 'See your Skillfarm account: handle, Seeds, tier and your own submissions',
8 'skills:write': 'Share skills, like skills and write reviews as you. Submissions still go through review',
9};
10
11const PREFIX: Record<string, string> = { pat: 'sf_pat_', access: 'sf_at_', refresh: 'sf_rt_' };
12
13export function cleanScopes(input: string | string[] | undefined | null): Scope[] {
14 const list = Array.isArray(input) ? input : (input ?? '').split(/[\s,]+/);
15 return SCOPES.filter((s) => list.includes(s));
16}
17
18export async function createToken(
19 env: Env,
20 o: { userId: string; kind: 'pat' | 'access' | 'refresh'; name?: string; scopes: Scope[]; clientId?: string | null; grantId?: string | null; ttl?: number | null },
21): Promise<{ token: string; id: string; expiresAt: number | null }> {
22 const token = PREFIX[o.kind] + randomToken(32);
23 const id = newId();
24 const expiresAt = o.ttl ? now() + o.ttl : null;
25 await env.DB.prepare('INSERT INTO api_tokens (id, user_id, kind, name, token_hash, scopes, client_id, grant_id, expires_at, created_at) VALUES (?,?,?,?,?,?,?,?,?,?)')
26 .bind(id, o.userId, o.kind, o.name ?? '', await sha256Hex(token), o.scopes.join(' '), o.clientId ?? null, o.grantId ?? null, expiresAt, now())
27 .run();
28 return { token, id, expiresAt };
29}
30
31export type TokenAuth = { user: User; scopes: Scope[]; tokenId: string; kind: string; grantId: string | null; clientId: string | null };
32
33/** Resolve a bearer token to its owner. Refresh tokens are not accepted as bearer credentials. */
34export async function authenticateBearer(env: Env, header: string | undefined, kinds: string[] = ['pat', 'access']): Promise<TokenAuth | null> {
35 const m = /^Bearer\s+(\S+)$/i.exec(header ?? '');
36 if (!m || !m[1].startsWith('sf_')) return null;
37 const row = await env.DB.prepare(
38 `SELECT t.id AS token_id, t.kind, t.scopes, t.expires_at, t.revoked_at, t.last_used_at, t.grant_id, t.client_id, u.* FROM api_tokens t JOIN users u ON u.id = t.user_id WHERE t.token_hash = ?`,
39 ).bind(await sha256Hex(m[1])).first<User & { token_id: string; kind: string; scopes: string; expires_at: number | null; revoked_at: number | null; last_used_at: number | null; grant_id: string | null; client_id: string | null }>();
40 const ts = now();
41 if (!row || row.revoked_at || (row.expires_at && row.expires_at < ts) || row.status !== 'active' || !kinds.includes(row.kind)) return null;
42 if (!row.last_used_at || ts - row.last_used_at > 300) await env.DB.prepare('UPDATE api_tokens SET last_used_at = ? WHERE id = ?').bind(ts, row.token_id).run();
43 const { token_id, kind, scopes, expires_at: _e, revoked_at: _r, last_used_at: _l, grant_id, client_id, ...user } = row;
44 return { user: user as User, scopes: cleanScopes(scopes), tokenId: token_id, kind, grantId: grant_id, clientId: client_id };
45}