TagSpaces is an offline, open source, document manager with tagging support
fix: playing media files
Ilian Sapundshievc66b30e951ae
diff --git a/release/app/package-lock.json b/release/app/package-lock.jsonindex 466a26b3a..b5389483a 100644--- a/release/app/package-lock.json+++ b/release/app/package-lock.json@@ -10,7 +10,7 @@"hasInstallScript": true,"license": "AGPL-3.0","dependencies": {- "@tagspaces/extensions": "1.0.248",+ "@tagspaces/extensions": "1.0.249","@tagspaces/tagspaces-common-node": "4.8.6","@tagspaces/tagspaces-ws": "4.8.6","wasm-vips": "0.0.17",@@ -286,9 +286,9 @@}},"node_modules/@tagspaces/extensions": {- "version": "1.0.248",- "resolved": "https://registry.npmjs.org/@tagspaces/extensions/-/extensions-1.0.248.tgz",- "integrity": "sha512-/ShtkSWazNoBl8PsHhzBLgbGOAXIIGH5hZSQj9IUuMneZhXpZRMoBUBk9x7/ty1QMF8Nag/1mG0zc/QzUCCHqw==",+ "version": "1.0.249",+ "resolved": "https://registry.npmjs.org/@tagspaces/extensions/-/extensions-1.0.249.tgz",+ "integrity": "sha512-2piPuPNFl5Q4NbMzW4cvULUaG1C95ebsmNcnWKBQdyglI6Vom5nXvUeWEkDguE2Ws0fDgnmv7FKO9fa05NwoBQ==","license": "MIT","engines": {"npm": ">= 6.14.15",@@ -881,9 +881,9 @@"optional": true},"@tagspaces/extensions": {- "version": "1.0.248",- "resolved": "https://registry.npmjs.org/@tagspaces/extensions/-/extensions-1.0.248.tgz",- "integrity": "sha512-/ShtkSWazNoBl8PsHhzBLgbGOAXIIGH5hZSQj9IUuMneZhXpZRMoBUBk9x7/ty1QMF8Nag/1mG0zc/QzUCCHqw=="+ "version": "1.0.249",+ "resolved": "https://registry.npmjs.org/@tagspaces/extensions/-/extensions-1.0.249.tgz",+ "integrity": "sha512-2piPuPNFl5Q4NbMzW4cvULUaG1C95ebsmNcnWKBQdyglI6Vom5nXvUeWEkDguE2Ws0fDgnmv7FKO9fa05NwoBQ=="},"@tagspaces/tagspaces-common": {"version": "4.8.6",diff --git a/release/app/package.json b/release/app/package.jsonindex 5a7887542..82d163b34 100644--- a/release/app/package.json+++ b/release/app/package.json@@ -17,7 +17,7 @@"link-modules": "node -r ts-node/register ../../.erb/scripts/link-modules.ts"},"dependencies": {- "@tagspaces/extensions": "1.0.248",+ "@tagspaces/extensions": "1.0.249","@tagspaces/tagspaces-common-node": "4.8.6","@tagspaces/tagspaces-ws": "4.8.6","wasm-vips": "0.0.17",diff --git a/src/main/protocol-utils.ts b/src/main/protocol-utils.tsnew file mode 100644index 000000000..bee13edc6--- /dev/null+++ b/src/main/protocol-utils.ts@@ -0,0 +1,53 @@+// Pure helpers extracted from protocol.ts so they can be unit-tested without+// pulling in electron. Keep this file electron-free.++import { normalize } from 'path';+import { fileURLToPath } from 'url';++/**+ * Convert a tsfile:// request URL to a native filesystem path.+ *+ * Two quirks to handle:+ *+ * 1. The media-player extension preserves Windows backslashes when building+ * the tsfile:// URL (e.g. tsfile:///E:\test\video.mp4). Node's+ * fileURLToPath only accepts forward slashes in the URL path component,+ * so we normalize before handing it off. fileURLToPath then re-produces+ * the native Windows path with backslashes on its own.+ *+ * 2. Do NOT decodeURIComponent the path before constructing the file:// URL.+ * fileURLToPath does its own %xx decoding. Pre-decoding turns escapes+ * like `%5B`/`%5D`/`%20`/`%23` (which appear in filenames such as+ * `Album [2020] (mix).webm`) into literal `[`/`]`/space/`#` — characters+ * that are reserved or unsafe in URL paths and make fileURLToPath either+ * throw or silently lose part of the path (e.g. `#` is treated as the+ * start of a fragment and the rest of the filename is dropped).+ */+export const requestUrlToFilesystemPath = (+ url: string,+ scheme: string,+): string => {+ let filepath = url.slice(`${scheme}://`.length).replace(/\/$/, '');+ filepath = filepath.replace(/\\/g, '/');+ return normalize(fileURLToPath(`file://${filepath}`));+};++/**+ * Set CORS headers on a Response so tsfile:// resources can be consumed by+ * <video crossOrigin> / fetch() from extension iframes. Echoes the caller's+ * Origin back rather than using `*` so only origins that actually reached the+ * scheme inside this Electron process are served.+ */+export const withCors = (+ response: Response,+ request: { headers: { get: (name: string) => string | null } },+): Response => {+ const origin = request.headers.get('Origin');+ if (origin) {+ response.headers.set('Access-Control-Allow-Origin', origin);+ response.headers.append('Vary', 'Origin');+ }+ response.headers.set('Access-Control-Allow-Headers', '*');+ response.headers.set('Access-Control-Allow-Methods', 'GET, HEAD, OPTIONS');+ return response;+};diff --git a/src/main/protocol.ts b/src/main/protocol.tsindex 72a59db0f..bbc70664a 100644--- a/src/main/protocol.ts+++ b/src/main/protocol.ts@@ -6,8 +6,9 @@ import { mediaProtocol } from '@tagspaces/tagspaces-common/AppConfig';import { net, protocol } from 'electron';import { createReadStream } from 'fs';import * as fs from 'fs-extra';-import { extname, normalize } from 'path';-import { fileURLToPath, pathToFileURL } from 'url';+import { extname } from 'path';+import { pathToFileURL } from 'url';+import { requestUrlToFilesystemPath, withCors } from './protocol-utils';const register = () => {//Logger.status(`Registering file protocol: ${mediaProtocol}`);@@ -26,7 +27,13 @@ const register = () => {// Allows loading <video>/<audio> streaming elementsstream: true,- // corsEnabled: true,+ // Required so fetch() from extension iframes (file:// origin) can+ // target tsfile:// resources. Without this Chromium rejects the+ // request at the network layer with "Cross origin requests are only+ // supported for protocol schemes: chrome, chrome-extension,+ // chrome-untrusted, data, http, https." — before our protocol handler+ // ever runs. Affects fetch() only; <video>/<img> never needed it.+ corsEnabled: true,// codeCache: true, Code cache can only be enabled when the custom scheme is registered as standard scheme.// allowServiceWorkers: true,// bypassCSP: true,@@ -44,14 +51,7 @@ const initialize = () => {}protocol.handle(mediaProtocol, async (request: any) => {- // Get the file path from the URL without the trailing slash- let filepath = request.url- .slice(`${mediaProtocol}://`.length)- .replace(/\/$/, '');- filepath = decodeURIComponent(filepath);- // Re-encode '#' characters to preserve them in the file URL- filepath = filepath.replace(/#/g, '%23');- const pathname = normalize(fileURLToPath(`file://${filepath}`)); //pathToFileURL(filepath).toString();+ const pathname = requestUrlToFilesystemPath(request.url, mediaProtocol);const asFileUrl = pathToFileURL(pathname).toString();// Pre-check existence: net.fetch on a missing file yields ERR_UNEXPECTED@@ -61,7 +61,7 @@ const initialize = () => {try {await fs.promises.access(pathname);} catch {- return new Response('', { status: 404 });+ return withCors(new Response('', { status: 404 }), request);}// console.log(@@ -75,9 +75,9 @@ const initialize = () => {const rangeHeader = request.headers.get('Range');if (!rangeHeader) {- return net.fetch(asFileUrl);+ return withCors(await net.fetch(asFileUrl), request);} else {- return handleRangeRequest(request, pathname);+ return withCors(await handleRangeRequest(request, pathname), request);}});};diff --git a/tests/unit/protocol.test.js b/tests/unit/protocol.test.jsnew file mode 100644index 000000000..acc81276f--- /dev/null+++ b/tests/unit/protocol.test.js@@ -0,0 +1,203 @@+import { describe, expect, test } from '@playwright/test';++import {+ requestUrlToFilesystemPath,+ withCors,+} from '../../src/main/protocol-utils';++// Duck-typed Request-like stub. Avoids Node's undici Request being picky about+// the forbidden Origin header in some Node versions.+const fakeRequest = (origin) => ({+ headers: {+ get: (name) =>+ name.toLowerCase() === 'origin' && origin !== undefined ? origin : null,+ },+});++const isWindows = process.platform === 'win32';++describe('requestUrlToFilesystemPath', () => {+ const scheme = 'tsfile';++ test('Windows path with literal backslashes is accepted (TST regression for the CORS/video bug)', () => {+ // Repro of the user-reported URL shape:+ // tsfile:///E:\test\video_2026-05-24_03-26-06.mp4+ // The media-player extension preserves backslashes when building the URL,+ // and the handler must accept that — fileURLToPath itself only takes+ // forward slashes, so a missing normalization step throws.+ expect(() =>+ requestUrlToFilesystemPath(+ 'tsfile:///E:\\test\\video_2026-05-24_03-26-06.mp4',+ scheme,+ ),+ ).not.toThrow();+ const out = requestUrlToFilesystemPath(+ 'tsfile:///E:\\test\\video_2026-05-24_03-26-06.mp4',+ scheme,+ );+ if (isWindows) {+ expect(out).toBe('E:\\test\\video_2026-05-24_03-26-06.mp4');+ } else {+ // On POSIX we still need a non-empty deterministic string; the exact+ // shape is platform-dependent but the call must not blow up.+ expect(typeof out).toBe('string');+ expect(out.length).toBeGreaterThan(0);+ }+ });++ test('square brackets in filename are accepted (regression for ERR_FAILED on fetch)', () => {+ // Repro: user has files like `Skinshape - Filoxiny [Full Album].webm`.+ // Chromium delivers the URL with brackets percent-encoded as %5B / %5D.+ // Pre-decoding to literal `[`/`]` made fileURLToPath fail because those+ // chars are reserved in URL paths (IPv6 literal syntax in the authority).+ if (isWindows) return;+ expect(+ requestUrlToFilesystemPath(+ 'tsfile:///Users/na/Music/Skinshape%20-%20Filoxiny%20%5BFull%20Album%5D-fdCupyYt_BA.webm',+ scheme,+ ),+ ).toBe(+ '/Users/na/Music/Skinshape - Filoxiny [Full Album]-fdCupyYt_BA.webm',+ );+ });++ test('parentheses and spaces in filename round-trip', () => {+ if (isWindows) return;+ expect(+ requestUrlToFilesystemPath(+ 'tsfile:///tmp/Album%20(2020)%20-%20mix.mp4',+ scheme,+ ),+ ).toBe('/tmp/Album (2020) - mix.mp4');+ });++ test('Windows path with forward slashes round-trips identically', () => {+ const out = requestUrlToFilesystemPath(+ 'tsfile:///E:/test/video.mp4',+ scheme,+ );+ if (isWindows) {+ expect(out).toBe('E:\\test\\video.mp4');+ } else {+ expect(typeof out).toBe('string');+ }+ });++ test('POSIX absolute path round-trips', () => {+ if (isWindows) return; // skip — file:// without drive is ambiguous on Win+ expect(+ requestUrlToFilesystemPath(+ 'tsfile:///Users/me/Documents/video.mp4',+ scheme,+ ),+ ).toBe('/Users/me/Documents/video.mp4');+ });++ test('decodes percent-encoded characters (spaces)', () => {+ if (isWindows) return;+ expect(+ requestUrlToFilesystemPath(+ 'tsfile:///tmp/file%20with%20spaces.mp4',+ scheme,+ ),+ ).toBe('/tmp/file with spaces.mp4');+ });++ test('preserves # in filenames (not treated as URL fragment delimiter)', () => {+ if (isWindows) return;+ // The media-player extension percent-encodes `#` to `%23` before building+ // the URL, so it arrives as `%23` and fileURLToPath decodes it back. If+ // a `#` ever arrived literal it would be treated as a fragment by+ // fileURLToPath and the rest of the filename would be dropped — pre-+ // decoding the URL is what caused that regression and is why we leave+ // percent-encoded bytes alone now.+ expect(+ requestUrlToFilesystemPath('tsfile:///tmp/foo%23bar.txt', scheme),+ ).toBe('/tmp/foo#bar.txt');+ });++ test('strips trailing slash from URL', () => {+ if (isWindows) return;+ expect(requestUrlToFilesystemPath('tsfile:///tmp/foo/', scheme)).toBe(+ '/tmp/foo',+ );+ });+});++describe('withCors', () => {+ test('echoes Origin header back when present', () => {+ const res = withCors(new Response('x'), fakeRequest('file://'));+ expect(res.headers.get('Access-Control-Allow-Origin')).toBe('file://');+ expect(res.headers.get('Vary')).toContain('Origin');+ });++ test('omits Allow-Origin when Origin header is absent (no-CORS request)', () => {+ const res = withCors(new Response('x'), fakeRequest(undefined));+ expect(res.headers.get('Access-Control-Allow-Origin')).toBe(null);+ });++ test('does not fall back to wildcard when Origin is missing (security)', () => {+ // Important: tsfile:// must NOT return Access-Control-Allow-Origin: * —+ // that would allow any caller to read arbitrary local files via fetch.+ const res = withCors(new Response('x'), fakeRequest(undefined));+ expect(res.headers.get('Access-Control-Allow-Origin')).not.toBe('*');+ });++ test('sets Allow-Headers and Allow-Methods on every response', () => {+ const res = withCors(+ new Response('x'),+ fakeRequest('http://localhost:1212'),+ );+ expect(res.headers.get('Access-Control-Allow-Headers')).toBe('*');+ expect(res.headers.get('Access-Control-Allow-Methods')).toBe(+ 'GET, HEAD, OPTIONS',+ );+ });++ test('preserves response status code (404 path used by missing thumbnails)', () => {+ const res = withCors(+ new Response('', { status: 404 }),+ fakeRequest('file://'),+ );+ expect(res.status).toBe(404);+ expect(res.headers.get('Access-Control-Allow-Origin')).toBe('file://');+ });++ test('preserves response status code (206 partial used by range requests)', () => {+ const res = withCors(+ new Response('chunk', { status: 206 }),+ fakeRequest('file://'),+ );+ expect(res.status).toBe(206);+ });++ test('preserves pre-existing response headers (Content-Type, Content-Range)', () => {+ const res = withCors(+ new Response('', {+ headers: {+ 'Content-Type': 'video/mp4',+ 'Content-Range': 'bytes 0-1023/2048',+ },+ }),+ fakeRequest('file://'),+ );+ expect(res.headers.get('Content-Type')).toBe('video/mp4');+ expect(res.headers.get('Content-Range')).toBe('bytes 0-1023/2048');+ });++ test('echoes the dev-server origin (http://localhost:1212)', () => {+ const res = withCors(+ new Response('x'),+ fakeRequest('http://localhost:1212'),+ );+ expect(res.headers.get('Access-Control-Allow-Origin')).toBe(+ 'http://localhost:1212',+ );+ });++ test('echoes a sandboxed null origin without falling back to *', () => {+ // Sandboxed iframes without allow-same-origin report Origin: null.+ const res = withCors(new Response('x'), fakeRequest('null'));+ expect(res.headers.get('Access-Control-Allow-Origin')).toBe('null');+ });+});