clone

a self-hosted multitenant nostr relay with sites, file storage, git hosting, and inbox and outbox delivery

feat/ui-updates
tinyrelay / scripts / file-media-preview.test.mjs
file-media-preview.test.mjs 7.0K
1import test from "node:test";2import assert from "node:assert/strict";3import fs from "node:fs";4import vm from "node:vm";56class Node {7 constructor(tag = "") { this.tagName = tag.toUpperCase(); this.children = []; this.attributes = {}; this.listeners = {}; this.textContent = ""; this.dataset = {}; }8 append(...nodes) { for (const node of nodes) if (node && typeof node !== "string") { this.children.push(node); node.parentNode = this; } }9 remove() { this.parentNode?.children.splice(this.parentNode.children.indexOf(this), 1); }10 setAttribute(name, value) { this.attributes[name] = String(value); }11 getAttribute(name) { return this.attributes[name] ?? null; }12 hasAttribute(name) { return Object.hasOwn(this.attributes, name); }13 addEventListener(name, fn) { (this.listeners[name] ||= []).push(fn); }14 click() {}15 replaceChildren(...nodes) { this.children = []; this.append(...nodes); }16 querySelector(selector) { return this.querySelectorAll(selector)[0] || null; }17 querySelectorAll(selector) {18 const selectors = selector.split(",").map(value => value.trim());19 const match = node => selectors.some(value => {20 const attr = value.match(/^([^[]+)?\[([^=\]]+)(?:="([^"]+)")?\]$/);21 if (attr) return (!attr[1] || node.tagName === attr[1].toUpperCase()) && node.hasAttribute(attr[2]) && (attr[3] === undefined || node.getAttribute(attr[2]) === attr[3]);22 return node.tagName === value.toUpperCase();23 });24 const found = [];25 const walk = node => { for (const child of node.children) { if (match(child)) found.push(child); walk(child); } };26 walk(this); return found;27 }28 set innerHTML(value) {29 this.children = [];30 const stack = [this];31 for (const token of value.match(/<[^>]+>|[^<]+/g) || []) {32 if (!token.startsWith("<")) continue;33 if (/^<\//.test(token)) { stack.pop(); continue; }34 const match = token.match(/^<([\w-]+)([^>]*)>/); if (!match) continue;35 const child = new Node(match[1]);36 for (const [, name, quote, attrValue] of match[2].matchAll(/([\w-]+)(?:=(['"])(.*?)\2)?/g)) child.setAttribute(name, attrValue ?? "");37 stack.at(-1).append(child);38 if (!/^(input|br|meta|img)$/.test(match[1])) stack.push(child);39 }40 }41}4243const setup = () => {44 const document = new Node("document");45 document.readyState = "complete";46 document.documentElement = new Node("html");47 document.body = new Node("body");48 document.createElement = name => new Node(name);49 document.addEventListener = () => {};50 document.dispatchEvent = () => {};51 document.querySelectorAll = () => [];52 const customElements = {registry: {}, define(name, ctor) { this.registry[name] = ctor; }};53 const location = {href: "https://relay.test/r/test/file/cipher", origin: "https://relay.test", pathname: "/r/test/file/cipher", hash: ""};54 const window = {document, customElements, location, addEventListener: () => {}, tiny: {util: {}, blossom: {encryption: {}}}};55 class HTMLElement extends Node {}56 Object.assign(globalThis, {window, document, customElements, HTMLElement, location, Blob, URL, CustomEvent: class {}});57 globalThis.tiny = window.tiny;58 vm.runInThisContext(fs.readFileSync("tinyclient/tiny.js", "utf8"));59 window.tiny.localPath = path => "/r/test" + path;60 window.tiny.require = async () => {};61 window.tiny.sha256hex = async () => "cipher";62 window.tiny.blossom.encryption.decryptCHK = async () => new TextEncoder().encode("video bytes");63 vm.runInThisContext(fs.readFileSync("tinyclient/components.js", "utf8"));64 return {FileTools: customElements.registry["file-tools"], window};65};6667const makeTool = (FileTools, window, type = "video/mp4") => {68 window.location.hash = "#enc=chk-v1&key=secret&name=clip.mp4&type=" + encodeURIComponent(type);69 const tool = new FileTools();70 tool.setAttribute("hash", "cipher");71 tool.setAttribute("type", "application/octet-stream");72 return tool;73};7475test("encrypted MP4 renders a local video preview and replaces it on retry", async () => {76 const {FileTools, window} = setup();77 const revoked = [];78 const originalCreate = URL.createObjectURL, originalRevoke = URL.revokeObjectURL;79 URL.createObjectURL = blob => "blob:preview-" + blob.type + "-" + Math.random();80 URL.revokeObjectURL = url => revoked.push(url);81 const originalFetch = globalThis.fetch;82 globalThis.fetch = async () => new Response(new Uint8Array([1, 2, 3]));83 try {84 const tool = makeTool(FileTools, window); tool.connectedCallback();85 await new Promise(resolve => setTimeout(resolve, 0));86 const first = tool.querySelector("[data-decrypted-preview]");87 assert.ok(first);88 assert.equal(first.querySelector("video").controls, true);89 assert.equal(first.querySelector("video").preload, "metadata");90 assert.equal(first.querySelector("video").src.startsWith("blob:preview-video/mp4-"), true);91 await tool.decryptFromFragment();92 assert.equal(tool.querySelectorAll("[data-decrypted-preview]").length, 1);93 assert.equal(revoked.length, 1, "retry releases the previous object URL");94 tool.disconnectedCallback();95 assert.equal(revoked.length, 2, "disconnect releases the current object URL");96 } finally {97 globalThis.fetch = originalFetch;98 URL.createObjectURL = originalCreate;99 URL.revokeObjectURL = originalRevoke;100 }101});102103test("HTML and SVG render as inert bounded source text", async () => {104 for (const type of ["image/svg+xml", "text/html"]) {105 const {FileTools, window} = setup();106 const originalFetch = globalThis.fetch;107 globalThis.fetch = async () => new Response(new Uint8Array([1, 2, 3]));108 try {109 const tool = makeTool(FileTools, window, type); tool.connectedCallback();110 await tool.decryptFromFragment();111 const preview = tool.querySelector("[data-decrypted-preview]");112 assert.ok(preview, type + " should have a source preview");113 assert.equal(preview.querySelector("pre").textContent, "video bytes");114 assert.equal(preview.querySelector("img"), null);115 assert.equal(preview.querySelector("iframe"), null);116 assert.ok(tool.querySelector("a[download]") || tool.querySelector("a"));117 } finally { globalThis.fetch = originalFetch; }118 }119});120121test("plain text preview is bounded while download remains complete", async () => {122 const {FileTools, window} = setup();123 const originalFetch = globalThis.fetch;124 const originalDecrypt = window.tiny.blossom.encryption.decryptCHK;125 const source = "A".repeat(256 * 1024 + 20);126 window.tiny.blossom.encryption.decryptCHK = async () => new TextEncoder().encode(source);127 globalThis.fetch = async () => new Response(new Uint8Array([1, 2, 3]));128 try {129 const tool = makeTool(FileTools, window, "text/plain"); tool.connectedCallback();130 await new Promise(resolve => setTimeout(resolve, 0));131 const pre = tool.querySelector("pre");132 assert.ok(pre);133 assert.equal(pre.textContent.startsWith("A".repeat(256 * 1024)), true);134 assert.match(pre.textContent, /Preview truncated/);135 const downloaded = await (await originalFetch(tool.downloadURL)).text();136 assert.equal(downloaded, source);137 } finally {138 window.tiny.blossom.encryption.decryptCHK = originalDecrypt;139 globalThis.fetch = originalFetch;140 }141});