Branchwell

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

Raw 2.0 KB on 9a071bd1de362520c199c643265ba6c57566da6f
1import type { Env, User } from '../env';
2import { newId, slugify } from './util';
3
4const RESERVED = new Set([
5 'admin', 'administrator', 'skillfarm', 'sprout', 'api', 'www', 'mcp', 'oauth', 'auth', 'signin', 'signout', 'login', 'logout', 'settings', 'skills', 'skill', 'share',
6 'growers', 'leaderboard', 'seeds', 'connect', 'privacy', 'guidelines', 'terms', 'support', 'help', 'about', 'root', 'system', 'moderator', 'mod', 'staff', 'official',
7 'anthropic', 'claude', 'protomota', 'projectatom', 'me', 'new', 'edit', 'u', 'null', 'undefined', 'deleted',
8]);
9
10export const HANDLE_RE = /^[a-z0-9](?:[a-z0-9-]{0,28}[a-z0-9])$/;
11
12export function handleProblem(handle: string): string | null {
13 if (!HANDLE_RE.test(handle)) return 'Handles are 2 to 30 characters: lowercase letters, numbers and hyphens, with no hyphen at either end.';
14 if (handle.includes('--')) return 'Handles cannot contain two hyphens in a row.';
15 if (RESERVED.has(handle) || handle.startsWith('deleted-')) return 'That handle is reserved. Pick another.';
16 return null;
17}
18
19export async function uniqueHandle(env: Env, wanted: string): Promise<string> {
20 let base = slugify(wanted, 24);
21 if (base.length < 2 || handleProblem(base)) base = 'grower';
22 let candidate = base;
23 for (let i = 0; i < 6; i++) {
24 const taken = await env.DB.prepare('SELECT 1 AS x FROM users WHERE handle = ?').bind(candidate).first();
25 if (!taken && !handleProblem(candidate)) return candidate;
26 candidate = `${base}-${newId(4)}`;
27 }
28 return `grower-${newId(8)}`;
29}
30
31export async function getUserByHandle(env: Env, handle: string): Promise<User | null> {
32 return env.DB.prepare('SELECT * FROM users WHERE handle = ?').bind(handle).first<User>();
33}
34
35export async function getUserById(env: Env, id: string): Promise<User | null> {
36 return env.DB.prepare('SELECT * FROM users WHERE id = ?').bind(id).first<User>();
37}
38
39export function isAdminGithubId(env: Env, githubId: string): boolean {
40 return (env.ADMIN_GITHUB_IDS || '').split(',').map((s) => s.trim()).filter(Boolean).includes(githubId);
41}