import assert from 'node:assert/strict'; import { createHash, webcrypto } from 'node:crypto'; import { encryptAndUploadDmFile, decryptDmFileToBlob } from '../../shine-UI/js/services/dm-file-service.js'; import { buildDmFileTechBlock, parseDmTechBlocks } from '../../shine-UI/js/services/dm-tech-blocks.js'; import { exportPkcs8B64 } from '../../shine-UI/js/services/crypto-utils.js'; // Fake IndexedDB only for session-key lookup (no external R2 or Java server required). globalThis.crypto ??= webcrypto; globalThis.window = { location: { href: 'https://shineup.me/' } }; const keyPair = await crypto.subtle.generateKey({ name: 'Ed25519' }, true, ['sign', 'verify']); const session = { sessionId: 'test-session', sessionPrivPkcs8: await exportPkcs8B64(keyPair.privateKey) }; globalThis.indexedDB = { open() { const request = {}; const db = { objectStoreNames: { contains: () => true }, transaction() { return { objectStore() { return { get() { const result = { result: session }; queueMicrotask(() => result.onsuccess?.()); return result; } }; } }; }, close() {}, }; request.result = db; queueMicrotask(() => request.onsuccess?.()); return request; }, }; const stored = new Map(); let signedRequests = 0; let putRequests = 0; const bytesFromBody = async body => new Uint8Array(await new Response(body).arrayBuffer()); globalThis.fetch = async (url, opts = {}) => { const method = opts.method || 'GET'; const target = String(url); if (target.endsWith('/api/dm-files/prepare')) { assert.equal(method, 'POST'); const { fileId, size } = JSON.parse(opts.body); const sigBytes = Buffer.from(opts.headers['X-Shine-Signature'], 'base64'); const timeMs = opts.headers['X-Shine-Time-Ms']; const preimage = `DM_R2_PREPARE_V1:test-session:${fileId}:${size}:${timeMs}`; assert.equal(await crypto.subtle.verify('Ed25519', keyPair.publicKey, sigBytes, new TextEncoder().encode(preimage)), true); signedRequests++; return Response.json(stored.has(fileId) ? { exists: true } : { exists: false, uploadUrl: `https://r2.invalid/${fileId}`, requiredHeaders: { 'content-type': 'application/octet-stream', 'if-none-match': '*' }, }); } const id = target.split('/').at(-1); if (target.startsWith('https://r2.invalid/')) { assert.equal(method, 'PUT'); assert.equal(opts.headers['if-none-match'], '*'); const bytes = await bytesFromBody(opts.body); assert.equal(id.length >= 32, true); if (stored.has(id)) return new Response('', { status: 412 }); stored.set(id, bytes); putRequests++; return new Response('', { status: 200 }); } if (target.startsWith('https://dm-files.shineup.me/')) { const bytes = stored.get(id); if (!bytes) return new Response('', { status: 404 }); return new Response(method === 'HEAD' ? null : bytes, { status: 200, headers: { 'Content-Length': String(bytes.byteLength), 'Content-Type': 'application/octet-stream', } }); } throw new Error(`Unexpected fetch: ${method} ${target}`); }; const data = new Uint8Array(9 * 1024 * 1024 + 137); for (let i = 0; i < data.length; i++) data[i] = i % 251; const file = new File([data], 'movie.bin', { type: 'application/octet-stream' }); const upload = await encryptAndUploadDmFile({ file, login: 'alice', sessionId: 'test-session', wsUrl: 'wss://shineup.me/ws', }); assert.equal(upload.version, 3); assert.equal(upload.chunkCount, 2); assert.equal(upload.chunkSize, 8 * 1024 * 1024); assert.equal(stored.size, 3); // ciphertext chunk 0, chunk 1, encrypted manifest assert.equal(putRequests, 3); assert.equal(signedRequests, 3); assert.match(upload.url, /^https:\/\/dm-files\.shineup\.me\/[1-9A-HJ-NP-Za-km-z]+$/); const raw = buildDmFileTechBlock(upload); assert.match(raw, / id !== upload.id); const damaged = stored.get(ids[0]).slice(); damaged[0] ^= 1; stored.set(ids[0], damaged); await assert.rejects(() => decryptDmFileToBlob(parsed), /SHA-256/); console.log('DM R2 v3 end-to-end simulation OK (encrypt → signed PUT → manifest → decrypt; corruption rejected)');