All files / app-play/src account.ts

81.52% Statements 75/92
86.3% Branches 63/73
66.66% Functions 14/21
81.01% Lines 64/79

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 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342                                      3x                   9x 9x 7x 4x 4x       2x                                         3x 3x 3x 3x 3x         3x 2x 1x                                                                   2x           2x 1x 1x 2x         9x 9x   2x   3x 2x 1x   2x   1x   1x                     5x 5x   4x   3x 2x                           3x 3x 1x             2x 2x 1x             1x                                                                                                                           3x 3x 1x           2x 1x           1x               10x 10x 5x               5x 5x 3x               2x                                 6x       3x       5x 5x 5x       5x               2x 2x                       3x     3x    
import { playerText } from './player-copy.ts';
 
/** The player's Leaderboard account as `GET /api/v0/me` reports it. */
export interface LeaderboardAccount {
  handle: string;
  displayName: string;
  anonymous: boolean;
  passkeys: number;
  /** The player's avatar: a Leaderboard path (`/players/<handle>/avatar?v=…`) or an absolute URL. */
  avatarUrl?: string;
}
 
export type AccountActionResult = { ok: true } | { ok: false; error: string; code?: string };
 
/**
 * The signed-in account, or `undefined` without a session (or when the Leaderboard cannot be reached). The session is
 * checked first (`null` when signed out), so a signed-out player never triggers a 401 the browser would log.
 */
export async function loadLeaderboardAccount(doFetch: typeof fetch = fetch): Promise<LeaderboardAccount | undefined> {
  return (await readLeaderboardAccount(doFetch)).account;
}
 
/**
 * {@link loadLeaderboardAccount}, saying whether the Leaderboard answered: `reached` is false when a request failed (no
 * network, the page unloading), so the account is unknown rather than signed out.
 */
export async function readLeaderboardAccount(
  doFetch: typeof fetch = fetch,
): Promise<{ account: LeaderboardAccount | undefined; reached: boolean }> {
  try {
    const session = await doFetch('/api/auth/get-session', { credentials: 'same-origin' });
    if (!session.ok || (await session.json()) === null) return { account: undefined, reached: session.ok };
    const response = await doFetch('/api/v0/me', { credentials: 'same-origin' });
    return response.ok
      ? { account: (await response.json()) as LeaderboardAccount, reached: true }
      : { account: undefined, reached: response.status === 401 };
  } catch {
    return { account: undefined, reached: false };
  }
}
 
/**
 * Open Accounts to manage the shared account: keep a guest account there with a passkey (on the correct relying-party
 * origin), Google or Discord.
 */
export async function keepLeaderboardAccount(): Promise<AccountActionResult> {
  location.assign('/api/auth/manage');
  return { ok: true };
}
 
/** Google or Discord. A passkey stays a separate click because WebAuthn needs the Accounts origin. */
export type AccountProvider = 'google' | 'discord';
 
/**
 * Accounts sign-in for this page. `method` asks Accounts to start Google or Discord; omitted, the
 * login page offers a passkey, as {@link signInToLeaderboard} does.
 */
export function accountSignInPath(returnTo: string, method?: AccountProvider): string {
  const params = new URLSearchParams();
  Eif (returnTo !== '') params.set('returnTo', returnTo);
  if (method !== undefined) params.set('method', method);
  const query = params.toString();
  return query === '' ? '/api/auth/sign-in' : `/api/auth/sign-in?${query}`;
}
 
/** The provider a sign-in or sign-up button names, if it is Google or Discord. */
export function accountProviderFromAction(action: string | undefined): AccountProvider | undefined {
  if (action === 'sign-in-google' || action === 'sign-up-google') return 'google';
  if (action === 'sign-in-discord' || action === 'sign-up-discord') return 'discord';
  return undefined;
}
 
/** Open Accounts to sign in with any method it offers; the OIDC callback returns to this player. */
export async function signInToLeaderboard(): Promise<AccountActionResult> {
  location.assign(accountSignInPath(`${location.pathname}${location.search}`));
  return { ok: true };
}
 
/** Open Accounts and start Google or Discord. The session and return path match a passkey sign-in. */
export async function signInWithAccountProvider(method: AccountProvider): Promise<AccountActionResult> {
  location.assign(accountSignInPath(`${location.pathname}${location.search}`, method));
  return { ok: true };
}
 
/** The handle and name a new account is made with. */
export interface SignUpDetails {
  handle: string;
  displayName: string;
}
 
/** Save a signed-in player's profile when possible, then open the central Accounts sign-in. */
export async function signUpForLeaderboard(
  details: SignUpDetails,
  doFetch: typeof fetch = fetch,
): Promise<AccountActionResult> {
  const saved = await saveProfile(details, doFetch);
  if (!saved.ok && saved.code !== 'sign-in-required') return saved;
  location.assign('/api/auth/sign-in');
  return { ok: true };
}
 
/** Saves the handle and name of the signed-in account (`PATCH /api/v0/me`). */
export async function saveProfile(details: SignUpDetails, doFetch: typeof fetch = fetch): Promise<AccountActionResult> {
  const response = await doFetch('/api/v0/me', {
    method: 'PATCH',
    credentials: 'same-origin',
    headers: { 'content-type': 'application/json' },
    body: JSON.stringify(details),
  });
  if (response.ok) return { ok: true };
  const body = (await response.json().catch(() => ({}))) as { error?: string; detail?: string };
  const code = body.error ?? `http-${response.status}`;
  return { ok: false, error: describeProfileError(code, body.detail), code };
}
 
/** A message for an error the account API answered when saving a handle and name (`{ error, detail? }`). */
export function describeProfileError(error: string, detail?: string): string {
  const copy = playerText().account;
  switch (error) {
    case 'invalid-handle':
      return detail === 'reserved' ? copy.handleReserved : copy.handleFormat;
    case 'invalid-display-name':
      if (detail === 'empty') return copy.nameEmpty;
      if (detail === 'length') return copy.nameLength;
      return copy.nameCharacters;
    case 'handle-taken':
      return copy.handleTaken;
    case 'sign-in-required':
      return copy.signInFirst;
    default:
      return copy.somethingWrong(error);
  }
}
 
export async function signOutOfLeaderboard(): Promise<AccountActionResult> {
  const response = await fetch('/api/auth/sign-out', { method: 'POST', credentials: 'same-origin' });
  return response.ok ? { ok: true } : { ok: false, error: playerText().account.couldNotSignOut };
}
 
/** One status-line summary of the account. */
export function describeLeaderboardAccount(account: LeaderboardAccount | undefined): string {
  const copy = playerText().account;
  if (account === undefined) return copy.notSignedIn;
  // Short enough for the Options dialog row; the "Keep this account" button carries the hint.
  if (account.anonymous) return `${account.handle} (${copy.anonymous})`;
  // An account kept with Google or Discord alone has no passkey to count.
  if (account.passkeys === 0) return `${account.displayName} @${account.handle}`;
  return `${account.displayName} @${account.handle} · ${copy.passkey(account.passkeys)}`;
}
 
/** What the account chip on the select screens shows: the sign-in state at a glance. */
export interface AccountChip {
  state: 'signed-in' | 'anonymous' | 'signed-out';
  label: string;
  /** Longer explanation for the tooltip. */
  title: string;
  /** The player's Leaderboard page, when there is an account. */
  href: string | undefined;
}
 
export function describeAccountChip(account: LeaderboardAccount | undefined): AccountChip {
  const copy = playerText().account;
  if (account === undefined) {
    return {
      state: 'signed-out',
      label: copy.notSignedIn,
      title: copy.chipSignedOutTitle,
      href: undefined,
    };
  }
  const href = `/players/${encodeURIComponent(account.handle)}`;
  if (account.anonymous) {
    return {
      state: 'anonymous',
      label: `@${account.handle} · ${copy.anonymous}`,
      title: copy.chipAnonymousTitle,
      href,
    };
  }
  return {
    state: 'signed-in',
    label: `@${account.handle}`,
    title: copy.chipSignedInTitle(account.displayName, account.handle),
    href,
  };
}
 
/** An action the start card offers for the account. */
export type StartAccountAction = 'sign-in' | 'sign-up' | 'keep' | 'sign-out';
 
/** What the start card's Leaderboard row shows: who the plays go to, and what the player can do about it. */
export interface StartAccountView {
  state: AccountChip['state'];
  label: string;
  /** The player's Leaderboard page, when there is an account. */
  href: string | undefined;
  actions: StartAccountAction[];
  /**
   * What the player needs to know about where plays go: signed out, that submitting needs an account (a guest one is
   * enough); as a guest, that the rankings leave its plays out until it is kept. Undefined when signed in.
   */
  hint: string | undefined;
}
 
/** The button text of each start card action, in the player's language. */
export function startAccountActionLabels(): Readonly<Record<StartAccountAction, string>> {
  const copy = playerText().account;
  const shell = playerText().shell;
  return {
    'sign-in': shell.signIn,
    'sign-up': copy.signUp,
    keep: copy.keep,
    'sign-out': copy.signOut,
  };
}
 
/** What the Options dialog's Leaderboard account form offers. */
export type LeaderboardAccountFormAction =
  | 'keep'
  | 'sign-in-passkey'
  | 'sign-in-google'
  | 'sign-in-discord'
  | 'sign-up'
  | 'sign-out';
 
/** The Options dialog's Leaderboard account form, as a sign-in form reads. */
export interface LeaderboardAccountFormView {
  readonly state: AccountChip['state'];
  /** The heading when no one is signed in; an account shows its identity instead. */
  readonly title: string | undefined;
  readonly lead: string;
  /** The actions, in the order the form shows them. */
  readonly actions: readonly LeaderboardAccountFormAction[];
}
 
/**
 * The Leaderboard account form. Signed out: a sign-in form, a passkey first and Google and Discord after, with signing up
 * below. Guest: the account, keeping it first, then signing in to another, and signing out. Signed in: the account
 * and signing out.
 */
export function describeLeaderboardAccountForm(account: LeaderboardAccount | undefined): LeaderboardAccountFormView {
  const copy = playerText().account;
  if (account === undefined)
    return {
      state: 'signed-out',
      title: copy.signIn,
      lead: copy.signInLead,
      actions: ['sign-in-passkey', 'sign-in-google', 'sign-in-discord', 'sign-up'],
    };
  if (account.anonymous)
    return {
      state: 'anonymous',
      title: undefined,
      lead: copy.anonymousLead,
      actions: ['keep', 'sign-in-passkey', 'sign-in-google', 'sign-in-discord', 'sign-out'],
    };
  return { state: 'signed-in', title: undefined, lead: copy.signedInLead, actions: ['sign-out'] };
}
 
/**
 * The start card's account row. Signed out: sign in, or sign up. Guest: keep it with a passkey, Google or Discord, or
 * sign in to another account, which takes this browser's plays along. Signed in: the player's page and signing out.
 */
export function describeStartAccount(account: LeaderboardAccount | undefined): StartAccountView {
  const copy = playerText().account;
  if (account === undefined) {
    return {
      state: 'signed-out',
      label: copy.notSignedIn,
      href: undefined,
      actions: ['sign-in', 'sign-up'],
      hint: copy.startSignedOutHint,
    };
  }
  const href = `/players/${encodeURIComponent(account.handle)}`;
  if (account.anonymous) {
    return {
      state: 'anonymous',
      label: `@${account.handle} · ${copy.anonymous}`,
      href,
      actions: ['keep', 'sign-in', 'sign-out'],
      hint: copy.startAnonymousHint,
    };
  }
  return {
    state: 'signed-in',
    label: `${account.displayName} @${account.handle}`,
    href,
    actions: ['sign-out'],
    hint: undefined,
  };
}
 
/**
 * Whether submitting should turn on: when the player arrives signed in, or signs in, to a kept account — not on every
 * re-read of an account already shown as signed in, so unticking it during a session sticks.
 */
export function shouldTurnOnSubmitting(
  previous: AccountChip['state'] | undefined,
  next: AccountChip['state'],
): boolean {
  return next === 'signed-in' && previous !== 'signed-in';
}
 
/** Where the start card remembers the account state it last showed, to shape its placeholder on the next visit. */
export const START_ACCOUNT_STATE_KEY = 'be-music.start-account-state';
 
/** The account state the start card last showed in this browser; signed out on a first visit or blocked storage. */
export function readStartAccountState(storage: Pick<Storage, 'getItem'> | undefined): AccountChip['state'] {
  let value: string | null = null;
  try {
    value = storage?.getItem(START_ACCOUNT_STATE_KEY) ?? null;
  } catch {
    // Blocked storage: a first visit.
  }
  return value === 'signed-in' || value === 'anonymous' ? value : 'signed-out';
}
 
/** Remembers the account state the start card shows (see {@link readStartAccountState}). */
export function rememberStartAccountState(
  state: AccountChip['state'],
  storage: Pick<Storage, 'setItem'> | undefined,
): void {
  try {
    storage?.setItem(START_ACCOUNT_STATE_KEY, state);
  } catch {
    // Blocked storage: the next visit shapes the placeholder as a first one.
  }
}
 
/**
 * What the start card's placeholder stands in for while the account is read: the actions and the hint the card showed
 * last time ({@link describeStartAccount} for that state), so a returning player's card keeps its size when the
 * account arrives.
 */
export function startAccountPlaceholder(state: AccountChip['state']): Pick<StartAccountView, 'actions' | 'hint'> {
  const view = describeStartAccount(
    state === 'signed-out' ? undefined : { handle: '', displayName: '', anonymous: state === 'anonymous', passkeys: 0 },
  );
  return { actions: view.actions, hint: view.hint };
}