All files / app-dashboard/src/accounts profiles.ts

84.78% Statements 78/92
77.04% Branches 47/61
92.3% Functions 12/13
88.73% Lines 63/71

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230        7x 7x     7x 7x     7x                                                               15x 120x 15x             20x 20x 12x 12x 8x                     7x       11x 11x 10x 5x 4x               43x 43x 14x 14x 14x 14x         14x                 18x       18x 16x       16x                             3x 3x 3x 3x 3x 3x 2x 2x 1x     1x 1x 1x 1x   1x 1x 1x       1x 1x                   1x                                         4x 4x 2x 1x         12x       12x         7x         5x               5x 5x 2x                     11x 8x   3x    
import { and, eq, ne } from 'drizzle-orm';
import type { Database } from './db/client.ts';
import { handleHistory, profile } from './schema.ts';
 
const HANDLE_ALPHABET = 'abcdefghijklmnopqrstuvwxyz0123456789';
const HANDLE_ATTEMPTS = 5;
 
/** Handles: letters, digits and `_`, 3 to 15 characters, case-insensitive (stored in lower case). */
const HANDLE_PATTERN = /^[A-Za-z0-9_]{3,15}$/;
export const DISPLAY_NAME_MAX = 32;
 
/** Handles nobody can take: they name the site, its pages, or look official. */
const RESERVED_HANDLES = new Set([
  'admin',
  'administrator',
  'anonymous',
  'api',
  'be_music',
  'bemusic',
  'chart',
  'charts',
  'chartset',
  'chartsets',
  'help',
  'leaderboard',
  'me',
  'mod',
  'moderator',
  'null',
  'official',
  'player',
  'players',
  'root',
  'score',
  'scores',
  'settings',
  'staff',
  'support',
  'system',
  'undefined',
]);
 
/** A random handle (`player_` and eight lowercase letters or digits) until the player picks one. */
export function generateHandle(bytes: Uint8Array = crypto.getRandomValues(new Uint8Array(8))): string {
  let suffix = '';
  for (const byte of bytes) suffix += HANDLE_ALPHABET[byte % HANDLE_ALPHABET.length];
  return `player_${suffix}`;
}
 
export type HandleCheck = { ok: true; handle: string } | { ok: false; reason: 'format' | 'reserved' };
 
/** Checks a handle the player typed and gives its stored form (lower case). */
export function normalizeHandle(input: string): HandleCheck {
  const handle = input.trim();
  if (!HANDLE_PATTERN.test(handle)) return { ok: false, reason: 'format' };
  const lower = handle.toLowerCase();
  if (RESERVED_HANDLES.has(lower)) return { ok: false, reason: 'reserved' };
  return { ok: true, handle: lower };
}
 
export type DisplayNameCheck =
  | { ok: true; displayName: string }
  | { ok: false; reason: 'empty' | 'length' | 'characters' };
 
/**
 * Line breaks, other control characters and the bidirectional controls that can disguise a name (U+202A–U+202E,
 * U+2066–U+2069, U+200E, U+200F, U+061C).
 */
const FORBIDDEN_IN_NAME = /[\p{Cc}\p{Zl}\p{Zp}‪-‮⁦-⁩‎‏؜]/u;
 
/** Checks a display name: 1 to 32 characters (code points) after trimming, Japanese and other scripts welcome. */
export function normalizeDisplayName(input: string): DisplayNameCheck {
  const displayName = input.normalize('NFC').trim();
  if (displayName.length === 0) return { ok: false, reason: 'empty' };
  if (FORBIDDEN_IN_NAME.test(displayName)) return { ok: false, reason: 'characters' };
  if (Array.from(displayName).length > DISPLAY_NAME_MAX) return { ok: false, reason: 'length' };
  return { ok: true, displayName };
}
 
/**
 * Creates the public profile of a new account with a generated handle (retrying on the rare collision). OAuth profile
 * names are never copied in; the player names themselves later.
 */
export async function createProfile(db: Database, userId: string, isAnonymous: boolean): Promise<void> {
  const existing = await db.query.profile.findFirst({ where: eq(profile.userId, userId), columns: { userId: true } });
  if (existing !== undefined) return;
  for (let attempt = 0; attempt < HANDLE_ATTEMPTS; attempt += 1) {
    const handle = generateHandle();
    Iif (await isHandleTaken(db, handle, userId)) continue;
    const inserted = await db
      .insert(profile)
      .values({ userId, handle, displayName: isAnonymous ? 'Anonymous' : 'Player' })
      .onConflictDoNothing()
      .returning({ userId: profile.userId });
    Eif (inserted.length > 0) return;
    // Concurrent first requests may have inserted this player's profile with another generated handle.
    if (await db.query.profile.findFirst({ where: eq(profile.userId, userId), columns: { userId: true } })) return;
  }
  throw new Error('could not generate a unique handle');
}
 
/** Whether another account holds `handle`, now or as one of its former handles. */
async function isHandleTaken(db: Database, handle: string, userId: string): Promise<boolean> {
  const current = await db.query.profile.findFirst({
    where: and(eq(profile.handle, handle), ne(profile.userId, userId)),
    columns: { userId: true },
  });
  if (current !== undefined) return true;
  const former = await db.query.handleHistory.findFirst({
    where: and(eq(handleHistory.handle, handle), ne(handleHistory.userId, userId)),
    columns: { userId: true },
  });
  return former !== undefined;
}
 
export type ProfileUpdate = { handle?: string; displayName?: string };
export type ProfileUpdateResult =
  | { ok: true }
  | { ok: false; status: 400; error: 'invalid-handle' | 'invalid-display-name'; detail: string }
  | { ok: false; status: 404; error: 'not-found' }
  | { ok: false; status: 409; error: 'handle-taken' };
 
/**
 * Changes a player's handle and display name. The old handle is kept in `handle_history`: still reserved for the
 * player, and its pages redirect to the new one. Taking back a former handle of one's own removes it from the history.
 */
export async function updateProfile(db: Database, userId: string, update: ProfileUpdate): Promise<ProfileUpdateResult> {
  const current = await db.query.profile.findFirst({ where: eq(profile.userId, userId) });
  Iif (current === undefined) return { ok: false, status: 404, error: 'not-found' };
  const changes: { handle?: string; displayName?: string } = {};
  Eif (update.handle !== undefined) {
    const checked = normalizeHandle(update.handle);
    if (!checked.ok) return { ok: false, status: 400, error: 'invalid-handle', detail: checked.reason };
    Eif (checked.handle !== current.handle) {
      if (await isHandleTaken(db, checked.handle, userId)) return { ok: false, status: 409, error: 'handle-taken' };
      changes.handle = checked.handle;
    }
  }
  Eif (update.displayName !== undefined) {
    const checked = normalizeDisplayName(update.displayName);
    Iif (!checked.ok) return { ok: false, status: 400, error: 'invalid-display-name', detail: checked.reason };
    changes.displayName = checked.displayName;
  }
  Iif (changes.handle === undefined && changes.displayName === undefined) return { ok: true };
  const newHandle = changes.handle;
  Iif (newHandle === undefined) {
    await db.update(profile).set(changes).where(eq(profile.userId, userId));
    return { ok: true };
  }
  try {
    await db.batch([
      db.insert(handleHistory).values({ handle: current.handle, userId }).onConflictDoNothing(),
      db.delete(handleHistory).where(and(eq(handleHistory.handle, newHandle), eq(handleHistory.userId, userId))),
      db.update(profile).set(changes).where(eq(profile.userId, userId)),
    ]);
  } catch (error) {
    // Another account took the handle between the check and the write (the unique index refused it).
    if (String(error).includes('UNIQUE')) return { ok: false, status: 409, error: 'handle-taken' };
    throw error;
  }
  return { ok: true };
}
 
/** The current handle of whoever used `handle` before, for redirecting old player URLs. */
export async function resolveFormerHandle(db: Database, handle: string): Promise<string | undefined> {
  const [row] = await db
    .select({ handle: profile.handle })
    .from(handleHistory)
    .innerJoin(profile, eq(profile.userId, handleHistory.userId))
    .where(eq(handleHistory.handle, handle.toLowerCase()));
  return row?.handle;
}
 
export type HandleAvailability = { ok: true; handle: string } | { ok: false; reason: 'format' | 'reserved' | 'taken' };
 
/** Whether `userId` could take the handle the player is typing (the welcome checks it as they type). */
export async function checkHandleAvailability(
  db: Database,
  userId: string,
  input: string,
): Promise<HandleAvailability> {
  const checked = normalizeHandle(input);
  if (!checked.ok) return checked;
  if (await isHandleTaken(db, checked.handle, userId)) return { ok: false, reason: 'taken' };
  return checked;
}
 
/** Whether the player has yet to see the welcome: a profile made after sign-up that was never onboarded. */
export async function needsOnboarding(db: Database, userId: string): Promise<boolean> {
  const found = await db.query.profile.findFirst({
    where: eq(profile.userId, userId),
    columns: { onboardedAt: true },
  });
  return found !== undefined && found.onboardedAt === null;
}
 
/** Records that the player finished or skipped the welcome. */
export async function markOnboarded(db: Database, userId: string): Promise<void> {
  await db.update(profile).set({ onboardedAt: new Date() }).where(eq(profile.userId, userId));
}
 
/** The display name a guest's placeholder becomes when the account is kept; a name the player chose stays. */
export function keptDisplayName(displayName: string): string {
  return displayName === 'Anonymous' ? 'Player' : displayName;
}
 
/**
 * A guest kept the account (a passkey, Google or Discord): the placeholder name becomes `Player`, as the Leaderboard
 * renames it, and the welcome shows again so the player can name the account they now keep.
 */
export async function onAccountKept(db: Database, userId: string): Promise<void> {
  const found = await db.query.profile.findFirst({ where: eq(profile.userId, userId), columns: { displayName: true } });
  if (found === undefined) return;
  await db
    .update(profile)
    .set({ displayName: keptDisplayName(found.displayName), onboardedAt: null })
    .where(eq(profile.userId, userId));
}
 
/**
 * Where the welcome goes when it is done: a path on this host (`/account`, `/`), never another origin or a
 * protocol-relative URL. Anything else goes to `/account`.
 */
export function welcomeNextPath(next: string | null | undefined): string {
  if (typeof next !== 'string' || !next.startsWith('/') || next.startsWith('//') || next.startsWith('/\\')) {
    return '/account';
  }
  return next;
}