atagen

malice

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