import { ApiError, request } from './client'; export type User = { id: string; username: string; created_at: string; }; export type Credentials = { username: string; password: string; }; type AuthResponse = { user: User }; export async function register(creds: Credentials): Promise { const r = await request('/v1/auth/register', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(creds) }); return r.user; } export async function login(creds: Credentials): Promise { const r = await request('/v1/auth/login', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(creds) }); return r.user; } export async function logout(): Promise { await request('/v1/auth/logout', { method: 'POST' }); } export type ChangePassword = { current_password: string; new_password: string; }; /** * Rotates the password. Backend signs out every other session for this * user and mints a fresh cookie for the caller (returned as Set-Cookie, * applied automatically by the browser). Bot tokens are left alone. * * Throws ApiError with `status=401, code='unauthenticated'` for wrong * `current_password`; `status=400, code='invalid_input'` for a weak new * password. */ export async function changePassword(input: ChangePassword): Promise { await request('/v1/auth/me/password', { method: 'PATCH', headers: { 'content-type': 'application/json' }, body: JSON.stringify(input) }); } /** * Returns the current user, or `null` if no valid session. * Re-throws any non-401 error. */ export async function me(): Promise { try { const r = await request('/v1/auth/me'); return r.user; } catch (e) { if (e instanceof ApiError && e.status === 401) return null; throw e; } } export type ApiToken = { id: string; user_id: string; name: string; created_at: string; last_used_at: string | null; }; export type CreatedToken = ApiToken & { bearer: string }; export async function createToken(name: string): Promise { return request('/v1/auth/tokens', { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify({ name }) }); } export async function deleteToken(id: string): Promise { await request(`/v1/auth/tokens/${encodeURIComponent(id)}`, { method: 'DELETE' }); }