import type { Env, User } from '../env'; import { newId, now, randomToken, sha256Hex } from './util'; export const SCOPES = ['skills:read', 'skills:write'] as const; export type Scope = (typeof SCOPES)[number]; export const SCOPE_TEXT: Record = { 'skills:read': 'See your Skillfarm account: handle, Seeds, tier and your own submissions', 'skills:write': 'Share skills, like skills and write reviews as you. Submissions still go through review', }; const PREFIX: Record = { pat: 'sf_pat_', access: 'sf_at_', refresh: 'sf_rt_' }; export function cleanScopes(input: string | string[] | undefined | null): Scope[] { const list = Array.isArray(input) ? input : (input ?? '').split(/[\s,]+/); return SCOPES.filter((s) => list.includes(s)); } export async function createToken( env: Env, o: { userId: string; kind: 'pat' | 'access' | 'refresh'; name?: string; scopes: Scope[]; clientId?: string | null; grantId?: string | null; ttl?: number | null }, ): Promise<{ token: string; id: string; expiresAt: number | null }> { const token = PREFIX[o.kind] + randomToken(32); const id = newId(); const expiresAt = o.ttl ? now() + o.ttl : null; 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 (?,?,?,?,?,?,?,?,?,?)') .bind(id, o.userId, o.kind, o.name ?? '', await sha256Hex(token), o.scopes.join(' '), o.clientId ?? null, o.grantId ?? null, expiresAt, now()) .run(); return { token, id, expiresAt }; } export type TokenAuth = { user: User; scopes: Scope[]; tokenId: string; kind: string; grantId: string | null; clientId: string | null }; /** Resolve a bearer token to its owner. Refresh tokens are not accepted as bearer credentials. */ export async function authenticateBearer(env: Env, header: string | undefined, kinds: string[] = ['pat', 'access']): Promise { const m = /^Bearer\s+(\S+)$/i.exec(header ?? ''); if (!m || !m[1].startsWith('sf_')) return null; const row = await env.DB.prepare( `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 = ?`, ).bind(await sha256Hex(m[1])).first(); const ts = now(); if (!row || row.revoked_at || (row.expires_at && row.expires_at < ts) || row.status !== 'active' || !kinds.includes(row.kind)) return null; 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(); const { token_id, kind, scopes, expires_at: _e, revoked_at: _r, last_used_at: _l, grant_id, client_id, ...user } = row; return { user: user as User, scopes: cleanScopes(scopes), tokenId: token_id, kind, grantId: grant_id, clientId: client_id }; }