Skillfarm / website · skillfarm.ai / src / lib / users.ts
| 1 | import type { Env, User } from '../env'; |
| 2 | import { newId, slugify } from './util'; |
| 3 | |
| 4 | const 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 | |
| 10 | export const HANDLE_RE = /^[a-z0-9](?:[a-z0-9-]{0,28}[a-z0-9])$/; |
| 11 | |
| 12 | export 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 | |
| 19 | export 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 | |
| 31 | export 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 | |
| 35 | export 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 | } |