All files / worker-play/src player-settings.ts

94.94% Statements 94/99
92.3% Branches 84/91
100% Functions 17/17
97.53% Lines 79/81

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                1x 1x 1x 1x 1x           1x                   26x 26x 26x 2x 24x 24x 7x 17x                                                         20x 20x 7x 5x   15x     15x 15x 15x 14x 14x   13x 13x             13x 13x 12x 12x 12x 12x 11x                   17x       25x   29x 29x   13x 13x       13x           25x   29x                             12x 12x 20x 22x 20x 3x                 17x 20x   20x 20x 22x 18x 16x       18x 9x 9x     20x   9x         16x 16x       13x   13x 13x 8x       17x       4x               20x 20x 20x 20x 6x 6x 96x       20x 20x 20x       20x    
// The Options dialog document for one browser, and for the signed-in account when there is one.
//
// `__Host-be-music.device` is set with `Set-Cookie`, so it is not script-writable storage. Safari's seven-day cap
// deletes `localStorage` and IndexedDB after seven days of Safari use without a visit; this cookie stays, and the
// next visit reads the document back from R2. New objects are gzip-compressed JSON; a plain JSON object written
// earlier still reads. The bytes share the play bucket with the ffmpeg core, under `player-settings/`, which
// `/ffmpeg-core/` refuses because that route rejects nested keys.
 
export const PLAYER_SETTINGS_PATH = '/api/player-settings';
const DEVICE_COOKIE = '__Host-be-music.device';
const COOKIE_MAX_AGE_SECONDS = 60 * 60 * 24 * 400;
const MAX_BODY_BYTES = 64 * 1024;
const KEY_PREFIX = 'player-settings';
 
/**
 * The document the player stores. Field checks happen when the browser reads it back. `0` while the shape is still
 * being defined: any other stamp is unreadable. The browser copy uses the same number.
 */
const DOCUMENT_VERSION = 0;
 
interface OptionSettingsDocument {
  version: 0;
  updatedAt: number;
  settings: Record<string, unknown>;
  deleted?: true;
}
 
function optionSettingsDocument(value: unknown): OptionSettingsDocument | undefined {
  Iif (typeof value !== 'object' || value === null) return undefined;
  const { version, updatedAt, settings } = value as { version?: unknown; updatedAt?: unknown; settings?: unknown };
  if (version !== DOCUMENT_VERSION || typeof updatedAt !== 'number' || !Number.isFinite(updatedAt) || updatedAt < 0)
    return undefined;
  Iif (typeof settings !== 'object' || settings === null || Array.isArray(settings)) return undefined;
  if ((value as { deleted?: unknown }).deleted === true)
    return { version: DOCUMENT_VERSION, updatedAt, settings: {}, deleted: true };
  return { version: DOCUMENT_VERSION, updatedAt, settings: settings as Record<string, unknown> };
}
 
export interface PlayerSettingsObject {
  etag: string;
  arrayBuffer(): Promise<ArrayBuffer>;
  httpMetadata?: { contentEncoding?: string };
}
 
export interface PlayerSettingsBucket {
  get(key: string): Promise<PlayerSettingsObject | null>;
  put(
    key: string,
    value: ArrayBuffer | string,
    options?: {
      onlyIf: { etagMatches?: string; etagDoesNotMatch?: string };
      httpMetadata?: { contentType?: string; contentEncoding?: string };
    },
  ): Promise<{ etag: string } | null>;
  delete(key: string): Promise<unknown>;
}
 
/** Reads, writes, or deletes the document. `subject` is the signed-in account, when the session has one. */
export async function handlePlayerSettings(
  request: Request,
  bucket: PlayerSettingsBucket,
  subject: string | undefined,
  now = Date.now(),
): Promise<Response> {
  const device = deviceId(request);
  if (request.method === 'GET') {
    const chosen = latest((await snapshots(bucket, keys(device.id, subject))).map((entry) => entry.document));
    return json(chosen ?? null, chosen ? 200 : 204, device.id);
  }
  Iif (request.method !== 'PUT' && request.method !== 'DELETE') {
    return json({ error: 'method' }, 405, device.id);
  }
  const origin = request.headers.get('origin');
  const target = new URL(request.url).origin;
  if (origin !== target) return json({ error: 'origin' }, 403, device.id);
  const text = await request.text();
  if (new TextEncoder().encode(text).byteLength > MAX_BODY_BYTES) return json({ error: 'too-large' }, 413, device.id);
  let body: unknown;
  try {
    body =
      text === '' && request.method === 'DELETE'
        ? { version: DOCUMENT_VERSION, updatedAt: now, settings: {}, deleted: true }
        : JSON.parse(text);
  } catch {
    return json({ error: 'json' }, 400, device.id);
  }
  const incoming = optionSettingsDocument(body);
  if (!incoming) return json({ error: 'document' }, 400, device.id);
  const deletion = request.method === 'DELETE';
  Iif (!deletion && incoming.deleted) return json({ error: 'document' }, 400, device.id);
  const stored = await storeNewer(bucket, keys(device.id, subject), incoming, deletion);
  if (!stored) return json({ error: 'conflict' }, 409, device.id);
  return json(stored, 200, device.id);
}
 
interface Snapshot {
  key: string;
  etag?: string;
  document?: OptionSettingsDocument;
}
 
function keys(id: string, subject: string | undefined): string[] {
  return [deviceKey(id), ...(subject ? [accountKey(subject)] : [])];
}
 
async function snapshots(bucket: PlayerSettingsBucket, paths: string[]): Promise<Snapshot[]> {
  return Promise.all(
    paths.map(async (key) => {
      const object = await bucket.get(key);
      if (!object) return { key };
      let document: OptionSettingsDocument | undefined;
      try {
        document = optionSettingsDocument(JSON.parse(await storedText(object)));
      } catch {
        /* Replace invalid data conditionally. */
      }
      return { key, etag: object.etag, document };
    }),
  );
}
 
function latest(documents: Array<OptionSettingsDocument | undefined>): OptionSettingsDocument | undefined {
  return documents.reduce<OptionSettingsDocument | undefined>(
    (best, item) =>
      item && (!best || item.updatedAt > best.updatedAt || (item.updatedAt === best.updatedAt && item.deleted))
        ? item
        : best,
    undefined,
  );
}
 
/** Conditional writes retry against the observed version; no GET performs a repair write. */
async function storeNewer(
  bucket: PlayerSettingsBucket,
  paths: string[],
  incoming: OptionSettingsDocument,
  deletion: boolean,
): Promise<OptionSettingsDocument | undefined> {
  // A reset retains its revision only, so delayed pre-reset writes cannot recreate deleted values.
  let candidate = incoming;
  for (let attempt = 0; attempt < 8; attempt++) {
    const entries = await snapshots(bucket, paths);
    const current = latest(entries.map((entry) => entry.document));
    if (deletion) {
      candidate =
        current?.deleted && current.updatedAt >= candidate.updatedAt
          ? current
          : {
              version: DOCUMENT_VERSION,
              updatedAt: Math.max(candidate.updatedAt, (current?.updatedAt ?? -1) + 1),
              settings: {},
              deleted: true,
            };
    } else if (current && current.updatedAt >= candidate.updatedAt) candidate = current;
    const body = JSON.stringify(candidate);
    let compressed: ArrayBuffer | undefined;
    let conflict = false;
    for (const entry of entries) {
      if (JSON.stringify(entry.document) === body) continue;
      compressed ??= await gzipText(body);
      const written = await bucket.put(entry.key, compressed, {
        onlyIf: entry.etag === undefined ? { etagDoesNotMatch: '*' } : { etagMatches: entry.etag },
        httpMetadata: { contentType: 'application/json', contentEncoding: 'gzip' },
      });
      if (!written) {
        conflict = true;
        break;
      }
    }
    if (!conflict) return candidate;
  }
  return undefined;
}
 
/** gzip of the JSON stored in R2. Objects written as plain JSON still read. */
async function gzipText(text: string): Promise<ArrayBuffer> {
  const stream = new Blob([text]).stream().pipeThrough(new CompressionStream('gzip'));
  return await new Response(stream).arrayBuffer();
}
 
async function storedText(object: PlayerSettingsObject): Promise<string> {
  const bytes = new Uint8Array(await object.arrayBuffer());
  const gzip =
    object.httpMetadata?.contentEncoding === 'gzip' || (bytes.length >= 2 && bytes[0] === 0x1f && bytes[1] === 0x8b);
  if (!gzip) return new TextDecoder().decode(bytes);
  return await new Response(new Blob([bytes]).stream().pipeThrough(new DecompressionStream('gzip'))).text();
}
 
function deviceKey(id: string): string {
  return `${KEY_PREFIX}/device/${id}`;
}
 
function accountKey(subject: string): string {
  return `${KEY_PREFIX}/account/${encodeURIComponent(subject)}`;
}
 
interface Device {
  readonly id: string;
}
 
function deviceId(request: Request): Device {
  const cookie = request.headers.get('cookie') ?? '';
  const match = new RegExp(`(?:^|;\\s*)${DEVICE_COOKIE}=([^;]+)`).exec(cookie);
  const current = match?.[1];
  if (current && /^[a-f0-9]{32}$/.test(current)) return { id: current };
  const bytes = new Uint8Array(16);
  crypto.getRandomValues(bytes);
  return { id: [...bytes].map((byte) => byte.toString(16).padStart(2, '0')).join('') };
}
 
function json(body: unknown, status: number, device: string): Response {
  const headers = new Headers({ 'cache-control': 'no-store' });
  if (status !== 204) headers.set('content-type', 'application/json; charset=utf-8');
  headers.append(
    'set-cookie',
    `${DEVICE_COOKIE}=${device}; HttpOnly; Secure; Path=/; Max-Age=${COOKIE_MAX_AGE_SECONDS}; SameSite=Lax`,
  );
  return new Response(status === 204 ? null : JSON.stringify(body), { status, headers });
}