atagen

malice

public
Star0
Watch0
9ad1d568a721b95f4c11c07b836f1ee0be6a81ae
2
ssh://brewery@pls.lobotomise.me:33/atagen/malice.git
web/src/sw.tsTypescript486 lines17.0 KB
1
import { statusForKind } from './lib/wire-status';
2
import { decodeAttachmentIv, importAttachmentKey, RangeDecryptor } from './lib/media-decrypt';
3
import { attachmentContentType } from './lib/media-sniff';
4
import { createAvatarLoader } from './lib/avatar-cache';
5
6
// Prepended by vite.config.ts's precacheManifestPlugin: every emitted chunk,
7
// asset, and the wasm, as root-relative URLs.
8
const sw = self as unknown as ServiceWorkerGlobalScope & { __MALICE_PRECACHE__: string[] };
9
10
const CACHE_NAME = 'malice-shell-v1';
11
const AVATAR_CACHE = 'malice-avatars-v3';
12
13
sw.addEventListener('install', (event) => {
14
  event.waitUntil(
15
    (async () => {
16
      const cache = await caches.open(CACHE_NAME);
17
      await cache.addAll(['/', '/index.html', ...sw.__MALICE_PRECACHE__]);
18
    })()
19
  );
20
  void sw.skipWaiting();
21
});
22
23
sw.addEventListener('activate', (event) => {
24
  event.waitUntil(
25
    (async () => {
26
      const keys = await caches.keys();
27
      await Promise.all(keys.filter((key) => key !== CACHE_NAME && key !== AVATAR_CACHE).map((key) => caches.delete(key)));
28
      await sw.clients.claim();
29
    })()
30
  );
31
});
32
33
interface MediaReply {
34
  bytes?: Uint8Array<ArrayBuffer>;
35
  content_type?: string | null;
36
  error?: { kind: string; message: string };
37
}
38
39
interface AttachmentEncryptionWire {
40
  key: string;
41
  iv: string;
42
  sha256: string;
43
}
44
45
interface MediaFileWire {
46
  url: string;
47
  mimetype: string | null;
48
  declared_size: number | null;
49
  encryption: AttachmentEncryptionWire | null;
50
}
51
52
type MediaLocationWire = { File: MediaFileWire } | { ServerThumbnail: { url: string; fallback: MediaFileWire } } | 'Local';
53
54
interface LocateReply {
55
  location?: MediaLocationWire;
56
  token?: string | null;
57
  error?: { kind: string; message: string };
58
}
59
60
const MEDIA_TIMEOUT_MS = 30000;
61
const mediaChannel = new BroadcastChannel('malice-media');
62
const pendingMedia = new Map<string, (reply: MediaReply & LocateReply) => void>();
63
let nextMediaRequestId = 0;
64
65
mediaChannel.onmessage = (ev: MessageEvent) => {
66
  const msg = ev.data as MediaReply & LocateReply & { id: string };
67
  const resolve = pendingMedia.get(msg.id);
68
  if (!resolve) return;
69
  pendingMedia.delete(msg.id);
70
  resolve(msg);
71
};
72
73
function requestMedia(kind: 'avatar' | 'media', fields: Record<string, string>): Promise<MediaReply | null> {
74
  const id = `${Date.now()}-${nextMediaRequestId++}`;
75
  return new Promise((resolve) => {
76
    const timer = setTimeout(() => {
77
      pendingMedia.delete(id);
78
      resolve(null);
79
    }, MEDIA_TIMEOUT_MS);
80
    pendingMedia.set(id, (reply) => {
81
      clearTimeout(timer);
82
      resolve(reply);
83
    });
84
    mediaChannel.postMessage({ id, kind, ...fields });
85
  });
86
}
87
88
interface LocateEntry {
89
  location: MediaLocationWire;
90
  token: string | null;
91
  expiresAt: number;
92
}
93
94
const LOCATE_TTL_MS = 5 * 60 * 1000;
95
const locateCache = new Map<string, LocateEntry>();
96
const sniffCache = new Map<string, { contentType: string | null; expiresAt: number }>();
97
98
function requestLocate(mediaId: string, size: string): Promise<{ location: MediaLocationWire; token: string | null } | null> {
99
  const id = `${Date.now()}-${nextMediaRequestId++}`;
100
  return new Promise((resolve) => {
101
    const timer = setTimeout(() => {
102
      pendingMedia.delete(id);
103
      resolve(null);
104
    }, MEDIA_TIMEOUT_MS);
105
    pendingMedia.set(id, (reply) => {
106
      clearTimeout(timer);
107
      resolve(reply.error || !reply.location ? null : { location: reply.location, token: reply.token ?? null });
108
    });
109
    mediaChannel.postMessage({ id, kind: 'locate', media_id: mediaId, size });
110
  });
111
}
112
113
/** In-memory only: the access token never touches Cache Storage or IndexedDB, and expires with the entry. */
114
async function locate(mediaId: string, size: string, force: boolean): Promise<LocateEntry | null> {
115
  if (!force) {
116
    const cached = locateCache.get(mediaId);
117
    if (cached && cached.expiresAt > Date.now()) return cached;
118
  }
119
  const reply = await requestLocate(mediaId, size);
120
  if (!reply) return null;
121
  const entry: LocateEntry = { ...reply, expiresAt: Date.now() + LOCATE_TTL_MS };
122
  locateCache.set(mediaId, entry);
123
  return entry;
124
}
125
126
interface RangeSlice {
127
  body: Uint8Array<ArrayBuffer>;
128
  status: number;
129
  contentRange?: string;
130
}
131
132
/** The engine hands back the whole attachment at once, so seeking in <video>/<audio> needs this SW to slice it. */
133
function sliceForRange(bytes: Uint8Array<ArrayBuffer>, rangeHeader: string | null): RangeSlice {
134
  const match = rangeHeader ? /^bytes=(\d*)-(\d*)$/.exec(rangeHeader) : null;
135
  if (!match) return { body: bytes, status: 200 };
136
  const total = bytes.byteLength;
137
  let start = match[1] ? parseInt(match[1], 10) : undefined;
138
  let end = match[2] ? parseInt(match[2], 10) : undefined;
139
  if (start === undefined && end !== undefined) {
140
    start = Math.max(total - end, 0);
141
    end = total - 1;
142
  } else if (end === undefined) {
143
    end = total - 1;
144
  }
145
  if (start === undefined || start > end || start >= total) return { body: bytes, status: 200 };
146
  end = Math.min(end, total - 1);
147
  return { body: bytes.subarray(start, end + 1), status: 206, contentRange: `bytes ${start}-${end}/${total}` };
148
}
149
150
function mediaResponse(reply: MediaReply | null, rangeHeader: string | null, attachment: boolean): Response {
151
  if (!reply) return new Response(null, { status: 504 });
152
  if (reply.error) return new Response(reply.error.message, { status: statusForKind(reply.error.kind) });
153
  const bytes = reply.bytes ?? new Uint8Array();
154
  const { body, status, contentRange } = sliceForRange(bytes, rangeHeader);
155
  const headers = new Headers({
156
    'Content-Type': reply.content_type ?? 'application/octet-stream',
157
    'Cache-Control': attachment ? 'private, max-age=3600' : 'private, max-age=31536000, immutable',
158
    'X-Content-Type-Options': 'nosniff'
159
  });
160
  if (attachment) {
161
    headers.set('Content-Disposition', reply.content_type ? 'inline' : 'attachment');
162
    headers.set('Content-Security-Policy', 'sandbox');
163
  }
164
  if (contentRange) {
165
    headers.set('Content-Range', contentRange);
166
    headers.set('Accept-Ranges', 'bytes');
167
  }
168
  return new Response(body, { status, headers });
169
}
170
171
interface ByteRange {
172
  start: number;
173
  end: number;
174
}
175
176
/** Unlike sliceForRange, the total comes from the server's declared_size, not a buffer already in hand. */
177
function parseByteRange(rangeHeader: string | null, total: number): ByteRange | null {
178
  const match = rangeHeader ? /^bytes=(\d*)-(\d*)$/.exec(rangeHeader) : null;
179
  if (!match) return null;
180
  let start = match[1] ? parseInt(match[1], 10) : undefined;
181
  let end = match[2] ? parseInt(match[2], 10) : undefined;
182
  if (start === undefined && end !== undefined) {
183
    start = Math.max(total - end, 0);
184
    end = total - 1;
185
  } else if (end === undefined) {
186
    start = start ?? 0;
187
    end = total - 1;
188
  }
189
  if (start === undefined || start > end || start >= total) return null;
190
  return { start, end: Math.min(end, total - 1) };
191
}
192
193
function attachmentHeaders(contentType: string | null): Headers {
194
  return new Headers({
195
    'Content-Type': contentType ?? 'application/octet-stream',
196
    'Cache-Control': 'private, max-age=3600',
197
    'X-Content-Type-Options': 'nosniff',
198
    'Content-Disposition': contentType ? 'inline' : 'attachment',
199
    'Content-Security-Policy': 'sandbox'
200
  });
201
}
202
203
/**
204
 * The Authorization header carries the account's access token, so it's only worth the risk on the
205
 * exact authenticated media endpoints, and only when the URL being fetched is the one `locate` named
206
 * (never a redirect target, should a future caller pass one through).
207
 */
208
function shouldAuthorize(fetchUrl: string, locatedUrl: string): boolean {
209
  try {
210
    const target = new URL(fetchUrl);
211
    const located = new URL(locatedUrl);
212
    if (target.origin !== located.origin) return false;
213
    return target.pathname.startsWith('/_matrix/client/v1/media/') || target.pathname.startsWith('/_matrix/media/');
214
  } catch {
215
    return false;
216
  }
217
}
218
219
function concatChunks(parts: Uint8Array[]): Uint8Array<ArrayBuffer> {
220
  const total = parts.reduce((sum, part) => sum + part.byteLength, 0);
221
  const out = new Uint8Array(total);
222
  let offset = 0;
223
  for (const part of parts) {
224
    out.set(part, offset);
225
    offset += part.byteLength;
226
  }
227
  return out;
228
}
229
230
async function readUpTo(
231
  reader: ReadableStreamDefaultReader<Uint8Array<ArrayBuffer>>,
232
  limit: number
233
): Promise<Uint8Array<ArrayBuffer>> {
234
  const chunks: Uint8Array[] = [];
235
  let total = 0;
236
  while (total < limit) {
237
    const { value, done } = await reader.read();
238
    if (done) break;
239
    chunks.push(value);
240
    total += value.byteLength;
241
  }
242
  reader.cancel().catch(() => undefined);
243
  return concatChunks(chunks).subarray(0, Math.min(limit, total));
244
}
245
246
/**
247
 * Ciphertext in, plaintext out: skips the bytes the upstream sent but the caller didn't ask for
248
 * (only nonzero when the upstream ignored the Range request), decrypts, drops the sub-16-byte
249
 * alignment prefix from the very first output, and stops once `limit` bytes have been produced.
250
 */
251
async function* decryptedChunks(
252
  reader: ReadableStreamDefaultReader<Uint8Array<ArrayBuffer>>,
253
  decryptor: RangeDecryptor | null,
254
  skipBytes: number,
255
  dropPrefix: number,
256
  limit: number
257
): AsyncGenerator<Uint8Array> {
258
  let toSkip = skipBytes;
259
  let toDrop = dropPrefix;
260
  let remaining = limit;
261
  while (remaining > 0) {
262
    const { value, done } = await reader.read();
263
    if (done) break;
264
    let chunk = value;
265
    if (toSkip > 0) {
266
      if (chunk.byteLength <= toSkip) {
267
        toSkip -= chunk.byteLength;
268
        continue;
269
      }
270
      chunk = chunk.subarray(toSkip);
271
      toSkip = 0;
272
    }
273
    const plain = decryptor ? await decryptor.push(chunk) : chunk;
274
    if (plain.byteLength === 0) continue;
275
    const emitted = emit(plain);
276
    if (emitted) yield emitted;
277
  }
278
  if (remaining > 0 && decryptor) {
279
    const emitted = emit(await decryptor.finish());
280
    if (emitted) yield emitted;
281
  }
282
  reader.cancel().catch(() => undefined);
283
284
  function emit(chunk: Uint8Array): Uint8Array | null {
285
    let out = chunk;
286
    if (toDrop > 0) {
287
      if (out.byteLength <= toDrop) {
288
        toDrop -= out.byteLength;
289
        return null;
290
      }
291
      out = out.subarray(toDrop);
292
      toDrop = 0;
293
    }
294
    if (out.byteLength > remaining) out = out.subarray(0, remaining);
295
    remaining -= out.byteLength;
296
    return out.byteLength > 0 ? out : null;
297
  }
298
}
299
300
async function headSniff(mediaId: string, file: MediaFileWire, token: string | null, retried: boolean): Promise<string | null> {
301
  const cached = sniffCache.get(mediaId);
302
  if (cached && cached.expiresAt > Date.now()) return cached.contentType;
303
  const headers = new Headers({ Range: 'bytes=0-79' });
304
  if (shouldAuthorize(file.url, file.url) && token) headers.set('Authorization', `Bearer ${token}`);
305
  let upstream: Response;
306
  try {
307
    upstream = await fetch(file.url, { headers });
308
  } catch {
309
    return null;
310
  }
311
  if (upstream.status === 401 && !retried) {
312
    const fresh = await locate(mediaId, 'Full', true);
313
    if (fresh && typeof fresh.location === 'object' && 'File' in fresh.location) {
314
      return headSniff(mediaId, fresh.location.File, fresh.token, true);
315
    }
316
  }
317
  if (!upstream.body || (!upstream.ok && upstream.status !== 206)) return null;
318
  const head = await readUpTo(upstream.body.getReader(), 80);
319
  let contentType: string | null;
320
  if (file.encryption) {
321
    const key = await importAttachmentKey(file.encryption.key);
322
    const iv = decodeAttachmentIv(file.encryption.iv);
323
    const decryptor = new RangeDecryptor(key, iv, 0);
324
    contentType = attachmentContentType(concatChunks([await decryptor.push(head), await decryptor.finish()]).subarray(0, 64));
325
  } else {
326
    contentType = attachmentContentType(head.subarray(0, 64));
327
  }
328
  sniffCache.set(mediaId, { contentType, expiresAt: Date.now() + LOCATE_TTL_MS });
329
  return contentType;
330
}
331
332
function wholeFileFallback(mediaId: string, rangeHeader: string | null): Promise<Response> {
333
  return requestMedia('media', { media_id: mediaId, size: 'Full' }).then((reply) => mediaResponse(reply, rangeHeader, true));
334
}
335
336
async function streamFullMedia(mediaId: string, rangeHeader: string | null, entry?: LocateEntry, retried = false): Promise<Response> {
337
  const located = entry ?? (await locate(mediaId, 'Full', false));
338
  if (!located) return wholeFileFallback(mediaId, rangeHeader);
339
  if (typeof located.location !== 'object' || !('File' in located.location)) return wholeFileFallback(mediaId, rangeHeader);
340
  const file = located.location.File;
341
  const total = file.declared_size;
342
  if (total == null) return wholeFileFallback(mediaId, rangeHeader);
343
344
  const requested = parseByteRange(rangeHeader, total);
345
  const start = requested?.start ?? 0;
346
  const end = requested?.end ?? total - 1;
347
  const alignedStart = start - (start % 16);
348
349
  const headers = new Headers({ Range: `bytes=${alignedStart}-${end}` });
350
  if (shouldAuthorize(file.url, file.url) && located.token) headers.set('Authorization', `Bearer ${located.token}`);
351
352
  let upstream: Response;
353
  try {
354
    upstream = await fetch(file.url, { headers });
355
  } catch {
356
    return new Response('media upstream unreachable', { status: 502 });
357
  }
358
  if (upstream.status === 401 && !retried) {
359
    const fresh = await locate(mediaId, 'Full', true);
360
    if (fresh) return streamFullMedia(mediaId, rangeHeader, fresh, true);
361
  }
362
  if (!upstream.body || (!upstream.ok && upstream.status !== 206)) {
363
    return new Response('media upstream error', { status: 502 });
364
  }
365
366
  const decryptor = file.encryption
367
    ? new RangeDecryptor(await importAttachmentKey(file.encryption.key), decodeAttachmentIv(file.encryption.iv), alignedStart / 16)
368
    : null;
369
  const skipBytes = upstream.status === 206 ? 0 : alignedStart;
370
  const dropPrefix = start - alignedStart;
371
  const limit = end - start + 1;
372
373
  const reader = upstream.body.getReader();
374
  const chunks = decryptedChunks(reader, decryptor, skipBytes, dropPrefix, limit);
375
376
  const prefetched: Uint8Array[] = [];
377
  let prefetchedLen = 0;
378
  let chunksDone = false;
379
  let contentType: string | null;
380
381
  if (alignedStart === 0) {
382
    while (prefetchedLen < 64) {
383
      const step = await chunks.next();
384
      if (step.done) {
385
        chunksDone = true;
386
        break;
387
      }
388
      prefetched.push(step.value);
389
      prefetchedLen += step.value.byteLength;
390
    }
391
    contentType = attachmentContentType(concatChunks(prefetched).subarray(0, Math.min(64, prefetchedLen)));
392
    sniffCache.set(mediaId, { contentType, expiresAt: Date.now() + LOCATE_TTL_MS });
393
  } else {
394
    contentType = await headSniff(mediaId, file, located.token, retried);
395
  }
396
397
  const body = new ReadableStream<Uint8Array>({
398
    async pull(controller) {
399
      const next = prefetched.shift();
400
      if (next) {
401
        controller.enqueue(next);
402
        return;
403
      }
404
      if (chunksDone) {
405
        controller.close();
406
        return;
407
      }
408
      const step = await chunks.next();
409
      if (step.done) controller.close();
410
      else controller.enqueue(step.value);
411
    },
412
    cancel() {
413
      reader.cancel().catch(() => undefined);
414
    }
415
  });
416
417
  const responseHeaders = attachmentHeaders(contentType);
418
  responseHeaders.set('Accept-Ranges', 'bytes');
419
  if (requested) {
420
    responseHeaders.set('Content-Range', `bytes ${start}-${end}/${total}`);
421
    return new Response(body, { status: 206, headers: responseHeaders });
422
  }
423
  return new Response(body, { status: 200, headers: responseHeaders });
424
}
425
426
async function cacheFirst(request: Request): Promise<Response> {
427
  const cached = await caches.match(request);
428
  if (cached) return cached;
429
  const response = await fetch(request);
430
  if (response.ok) {
431
    const cache = await caches.open(CACHE_NAME);
432
    void cache.put(request, response.clone());
433
  }
434
  return response;
435
}
436
437
/** Keyed by the request URL, which names image and size, so cached bytes outlive the access token and survive restarts. */
438
const cachedAvatar = createAvatarLoader(
439
  async () => caches.open(AVATAR_CACHE),
440
  async (query) => mediaResponse(await requestMedia('avatar', Object.fromEntries(new URLSearchParams(query))), null, false)
441
);
442
443
async function networkFirstNavigation(request: Request): Promise<Response> {
444
  try {
445
    return await fetch(request);
446
  } catch {
447
    const cached = await caches.match('/index.html');
448
    if (cached) return cached;
449
    throw new Error('offline and no cached shell');
450
  }
451
}
452
453
sw.addEventListener('fetch', (event) => {
454
  const url = new URL(event.request.url);
455
  const range = event.request.headers.get('Range');
456
457
  if (url.pathname === '/api/media') {
458
    const mxc = url.searchParams.get('mxc');
459
    if (mxc) {
460
      const size = url.searchParams.get('size') ?? '256';
461
      event.respondWith(cachedAvatar(event.request.url, new URLSearchParams({ mxc, size }).toString()));
462
      return;
463
    }
464
  }
465
  if (url.pathname === '/api/message-media') {
466
    const mediaId = url.searchParams.get('media_id');
467
    const size = url.searchParams.get('size');
468
    if (mediaId && size === 'Full') {
469
      event.respondWith(streamFullMedia(mediaId, range));
470
      return;
471
    }
472
    if (mediaId && size) {
473
      event.respondWith(
474
        requestMedia('media', { media_id: mediaId, size }).then((reply) => mediaResponse(reply, range, true))
475
      );
476
      return;
477
    }
478
  }
479
  if (url.pathname.startsWith('/assets/') || url.pathname.startsWith('/twemoji/')) {
480
    event.respondWith(cacheFirst(event.request));
481
    return;
482
  }
483
  if (event.request.mode === 'navigate') {
484
    event.respondWith(networkFirstNavigation(event.request));
485
  }
486
});