@x-tech-laboratories/x-app 0.134.0 → 0.136.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,69 @@
1
+ // What an app's player drives: one file at a time, with the next named ahead for a gapless join. MpvEngine (mpv) plays
2
+ // it through mpv on a computer, AudioEngine (web/audio_engine) through an <audio> element in a page, and NullEngine
3
+ // plays nothing for tests. No `node:` or DOM imports.
4
+ // ── An engine for tests ──────────────────────────────────────────────────────
5
+ // Plays nothing and remembers what it was asked, for testing an app's player without mpv.
6
+ export class NullEngine {
7
+ listeners = new Set();
8
+ state = "idle";
9
+ uri = null;
10
+ position_in_milliseconds = 0;
11
+ volume = 100;
12
+ loaded = [];
13
+ preloaded = [];
14
+ emit = (event, payload) => {
15
+ for (const listener of this.listeners)
16
+ listener(event, payload);
17
+ };
18
+ set_state(state) {
19
+ this.state = state;
20
+ this.emit("state", { state });
21
+ }
22
+ async load(uri) {
23
+ this.uri = uri;
24
+ this.loaded.push(uri);
25
+ this.position_in_milliseconds = 0;
26
+ this.set_state("loading");
27
+ }
28
+ async play() {
29
+ this.set_state("playing");
30
+ }
31
+ async pause() {
32
+ this.set_state("paused");
33
+ }
34
+ async stop() {
35
+ this.uri = null;
36
+ this.set_state("idle");
37
+ }
38
+ async seek(position_in_milliseconds) {
39
+ this.position_in_milliseconds = position_in_milliseconds;
40
+ this.emit("position", { position_in_milliseconds, duration_in_milliseconds: null });
41
+ }
42
+ async set_volume(volume) {
43
+ this.volume = volume;
44
+ }
45
+ async preload(uri) {
46
+ this.preloaded.push(uri);
47
+ }
48
+ subscribe(listener) {
49
+ this.listeners.add(listener);
50
+ return () => void this.listeners.delete(listener);
51
+ }
52
+ async dispose() {
53
+ this.listeners.clear();
54
+ }
55
+ // Reports a position, as mpv does while playing.
56
+ tick(position_in_milliseconds, duration_in_milliseconds = 200_000) {
57
+ this.position_in_milliseconds = position_in_milliseconds;
58
+ this.emit("position", { position_in_milliseconds, duration_in_milliseconds });
59
+ }
60
+ // Plays the file to its end.
61
+ finish() {
62
+ this.state = "ended";
63
+ this.emit("ended", {});
64
+ }
65
+ fail(message) {
66
+ this.state = "error";
67
+ this.emit("state", { state: "error", error: message });
68
+ }
69
+ }
@@ -0,0 +1,17 @@
1
+ export type PlaylistFormat = "m3u" | "pls" | "xspf";
2
+ export declare const playlist_extensions: Readonly<Record<string, PlaylistFormat>>;
3
+ export declare function playlist_format(path: string): PlaylistFormat | null;
4
+ export declare function resolve_entry(entry: string, playlist_path: string): string;
5
+ export interface PlaylistFile {
6
+ name: string | null;
7
+ entries: string[];
8
+ }
9
+ export declare function read_playlist_file(text: string, path: string): PlaylistFile;
10
+ export declare function name_from_path(path: string): string;
11
+ export interface PlaylistEntry {
12
+ path: string;
13
+ title: string | null;
14
+ artist: string | null;
15
+ length_ms: number | null;
16
+ }
17
+ export declare function write_playlist_file(format: PlaylistFormat, name: string, entries: readonly PlaylistEntry[]): string;
@@ -0,0 +1,133 @@
1
+ // Playlist files: M3U and M3U8, PLS and XSPF read into the paths they list, and written from a playlist's entries. No
2
+ // `node:` or DOM imports, so a page, a phone and Node read them alike.
3
+ // ── Imports ──────────────────────────────────────────────────────────────────
4
+ import { XMLBuilder, XMLParser } from "fast-xml-parser";
5
+ export const playlist_extensions = { m3u: "m3u", m3u8: "m3u", pls: "pls", xspf: "xspf" };
6
+ export function playlist_format(path) {
7
+ const extension = /\.([^./\\]+)$/.exec(path)?.[1]?.toLowerCase();
8
+ return extension ? (playlist_extensions[extension] ?? null) : null;
9
+ }
10
+ // ── Paths ────────────────────────────────────────────────────────────────────
11
+ const is_absolute = (path) => path.startsWith("/") || /^[A-Za-z]:[\\/]/.test(path) || path.startsWith("\\\\");
12
+ const folder_of = (path) => path.slice(0, Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\")));
13
+ // An entry as a path on the playlist's computer: a file URL decoded, a relative path joined to the playlist's folder;
14
+ // other URLs as they are.
15
+ export function resolve_entry(entry, playlist_path) {
16
+ const trimmed = entry.trim();
17
+ if (/^file:\/\//i.test(trimmed)) {
18
+ const path = decodeURIComponent(trimmed.replace(/^file:\/\/(localhost)?/i, ""));
19
+ return /^\/[A-Za-z]:\//.test(path) ? path.slice(1) : path;
20
+ }
21
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(trimmed) || is_absolute(trimmed))
22
+ return trimmed;
23
+ const separator = playlist_path.includes("\\") && !playlist_path.includes("/") ? "\\" : "/";
24
+ const parts = `${folder_of(playlist_path)}${separator}${trimmed}`.split(/[\\/]/);
25
+ const kept = [];
26
+ for (const part of parts) {
27
+ if (part === ".." && kept.length > 1)
28
+ kept.pop();
29
+ else if (part !== ".")
30
+ kept.push(part);
31
+ }
32
+ return kept.join(separator);
33
+ }
34
+ const lines_of = (text) => text
35
+ .replace(/^/, "")
36
+ .split(/\r?\n/)
37
+ .map((line) => line.trim());
38
+ function read_m3u(text, path) {
39
+ let name = null;
40
+ const entries = [];
41
+ for (const line of lines_of(text)) {
42
+ if (line.startsWith("#PLAYLIST:"))
43
+ name = line.slice("#PLAYLIST:".length).trim() || null;
44
+ else if (line !== "" && !line.startsWith("#"))
45
+ entries.push(resolve_entry(line, path));
46
+ }
47
+ return { name, entries };
48
+ }
49
+ function read_pls(text, path) {
50
+ const files = [];
51
+ for (const line of lines_of(text)) {
52
+ const file = /^File(\d+)=(.*)$/i.exec(line);
53
+ if (file && file[2].trim() !== "")
54
+ files.push([Number(file[1]), resolve_entry(file[2], path)]);
55
+ }
56
+ return { name: null, entries: files.sort((first, second) => first[0] - second[0]).map(([, entry]) => entry) };
57
+ }
58
+ function read_xspf(text, path) {
59
+ const parser = new XMLParser({ ignoreAttributes: true, isArray: (name) => name === "track" || name === "location", parseTagValue: false });
60
+ const document = parser.parse(text);
61
+ if (!document.playlist)
62
+ throw new Error("this is not an XSPF playlist");
63
+ const tracks = document.playlist.trackList?.track ?? [];
64
+ const entries = tracks.flatMap((track) => {
65
+ const location = track.location?.[0];
66
+ return typeof location === "string" && location.trim() !== "" ? [resolve_entry(location, path)] : [];
67
+ });
68
+ const title = document.playlist.title;
69
+ return { name: typeof title === "string" && title.trim() !== "" ? title.trim() : null, entries };
70
+ }
71
+ // The entries of a playlist file, its format known by the path's extension.
72
+ export function read_playlist_file(text, path) {
73
+ const format = playlist_format(path);
74
+ if (format === "pls")
75
+ return read_pls(text, path);
76
+ if (format === "xspf")
77
+ return read_xspf(text, path);
78
+ if (format === "m3u")
79
+ return read_m3u(text, path);
80
+ throw new Error("a playlist file ends in .m3u, .m3u8, .pls or .xspf");
81
+ }
82
+ // The file's name without its folder or extension, for a playlist that names none.
83
+ export function name_from_path(path) {
84
+ return path.slice(Math.max(path.lastIndexOf("/"), path.lastIndexOf("\\")) + 1).replace(/\.[^.]+$/, "");
85
+ }
86
+ const shown_name = (entry) => [entry.artist, entry.title].filter((part) => part).join(" - ");
87
+ const seconds = (entry) => (entry.length_ms === null ? -1 : Math.round(entry.length_ms / 1000));
88
+ const one_line = (text) => text.replace(/[\r\n]+/g, " ");
89
+ function write_m3u(name, entries) {
90
+ const lines = ["#EXTM3U", `#PLAYLIST:${one_line(name)}`];
91
+ for (const entry of entries)
92
+ lines.push(`#EXTINF:${seconds(entry)},${one_line(shown_name(entry))}`, entry.path);
93
+ return `${lines.join("\n")}\n`;
94
+ }
95
+ function write_pls(entries) {
96
+ const lines = ["[playlist]"];
97
+ entries.forEach((entry, index) => {
98
+ const number = index + 1;
99
+ lines.push(`File${number}=${entry.path}`, `Title${number}=${one_line(shown_name(entry))}`, `Length${number}=${seconds(entry)}`);
100
+ });
101
+ lines.push(`NumberOfEntries=${entries.length}`, "Version=2");
102
+ return `${lines.join("\n")}\n`;
103
+ }
104
+ // A path as a file URL, each part escaped.
105
+ function file_url(path) {
106
+ if (/^[a-z][a-z0-9+.-]*:\/\//i.test(path))
107
+ return path;
108
+ const slashed = path.replace(/\\/g, "/");
109
+ return `file://${slashed.startsWith("/") ? "" : "/"}${slashed
110
+ .split("/")
111
+ .map(encodeURIComponent)
112
+ .join("/")
113
+ .replace(/^\/([A-Za-z])%3A/, "/$1:")}`;
114
+ }
115
+ function write_xspf(name, entries) {
116
+ const builder = new XMLBuilder({ ignoreAttributes: false, format: true, attributeNamePrefix: "@" });
117
+ const track = (entry) => ({
118
+ location: file_url(entry.path),
119
+ ...(entry.title ? { title: entry.title } : {}),
120
+ ...(entry.artist ? { creator: entry.artist } : {}),
121
+ ...(entry.length_ms !== null ? { duration: entry.length_ms } : {}),
122
+ });
123
+ const body = builder.build({ playlist: { "@version": "1", "@xmlns": "http://xspf.org/ns/0/", title: name, trackList: { track: entries.map(track) } } });
124
+ return `<?xml version="1.0" encoding="UTF-8"?>\n${body}`;
125
+ }
126
+ // A playlist file of the format given, naming each entry's path with its artist, title and length where the format can.
127
+ export function write_playlist_file(format, name, entries) {
128
+ if (format === "pls")
129
+ return write_pls(entries);
130
+ if (format === "xspf")
131
+ return write_xspf(name, entries);
132
+ return write_m3u(name, entries);
133
+ }
@@ -3,6 +3,7 @@ import type { PageOnlyCalls } from "../api_spec.ts";
3
3
  import { type AccountPrefsOptions } from "./account_prefs.ts";
4
4
  import { type AccountStore, type TokenKind, type TokenScopeInfo } from "./account_store.ts";
5
5
  import type { DeclaredToken } from "./declared_tokens.ts";
6
+ import type { MediaLinks } from "./media_links.ts";
6
7
  import type { OidcClient } from "./oidc.ts";
7
8
  export { is_user_or_device } from "./viewers.ts";
8
9
  export interface Viewer {
@@ -51,6 +52,7 @@ export interface AccountSignInOptions {
51
52
  address_try_window_seconds?: number;
52
53
  second_factor_from?: string | null;
53
54
  prefs?: AccountPrefsOptions | null;
55
+ media_links?: MediaLinks | null;
54
56
  }
55
57
  export declare function calls_under(...prefixes: string[]): (method: string, path: string) => string | null;
56
58
  export declare function token_refusal(viewer: Pick<Viewer, "scope">, call: string | null): string;
@@ -69,6 +69,20 @@ export async function register_accounts(app, options) {
69
69
  path: "/", httpOnly: true, sameSite: "strict", secure: is_secure(request),
70
70
  ...(remember ? { maxAge: remembered_seconds ?? longest_cookie_seconds } : {}),
71
71
  });
72
+ // A GET of a media path with a link made for it, as the user it was made for, reading only.
73
+ const media_links = options.media_links ?? null;
74
+ // Making a link only lets its path be read, so a token that only reads may make one.
75
+ if (media_links !== null)
76
+ read_only_paths.add(`${prefix}/media_link`);
77
+ const media_viewer = (request) => {
78
+ if (media_links === null || (request.method !== "GET" && request.method !== "HEAD"))
79
+ return null;
80
+ const query = request.url.indexOf("?");
81
+ const link = query < 0 ? null : new URLSearchParams(request.url.slice(query + 1)).get("link");
82
+ const name = link === null ? null : media_links.check(path_of(request), link);
83
+ const user = name === null ? null : accounts.user(name);
84
+ return user === null ? null : as_viewer(user, "token", true, null);
85
+ };
72
86
  const identify = (request) => {
73
87
  const secret = request.cookies[cookie_name];
74
88
  if (secret) {
@@ -90,6 +104,9 @@ export async function register_accounts(app, options) {
90
104
  return { name: declared.name, role: declared.role, access: declared.limited_to, via: "token", read_only: declared.read_only, credential_id: null, declared, token_kind: "program" };
91
105
  }
92
106
  }
107
+ const media = media_viewer(request);
108
+ if (media !== null)
109
+ return media;
93
110
  if (proxy !== null && proxy.trusted.has(request.ip)) {
94
111
  const header = request.headers[proxy.header.toLowerCase()];
95
112
  const user = typeof header === "string" ? accounts.user(header.trim().toLowerCase()) : null;
@@ -231,6 +248,16 @@ export async function register_accounts(app, options) {
231
248
  reply.clearCookie(cookie_name, { path: "/" });
232
249
  return reply.code(204).send();
233
250
  });
251
+ // A link to one media path for an element that cannot send the sign-in, such as <audio>.
252
+ if (media_links !== null) {
253
+ scope.post(`${prefix}/media_link`, async (request, reply) => {
254
+ const body = request.body;
255
+ const path = Array.isArray(body) ? body[0] : body?.path;
256
+ if (typeof path !== "string" || !media_links.allows(path))
257
+ return reply.code(400).send({ error: `A media link is made for a path under ${media_links.prefixes.join(" or ")}.` });
258
+ return { link: `${path}?link=${media_links.sign(path, request.viewer.name)}` };
259
+ });
260
+ }
234
261
  // Who is signed in; the page asks when it starts, which also renews a remembered cookie.
235
262
  scope.get(routes.me, async (request, reply) => {
236
263
  const viewer = request.viewer;
@@ -0,0 +1,11 @@
1
+ import type { FastifyReply, FastifyRequest } from "fastify";
2
+ export declare function media_type(path: string): string;
3
+ export declare function requested_range(header: string | undefined, size: number): {
4
+ start: number;
5
+ end: number;
6
+ } | "unsatisfiable" | null;
7
+ export interface SendFileOptions {
8
+ type?: string;
9
+ cache_control?: string;
10
+ }
11
+ export declare function send_file_ranges(request: FastifyRequest, reply: FastifyReply, path: string, options?: SendFileOptions): Promise<FastifyReply>;
@@ -0,0 +1,80 @@
1
+ // A file on the server's disk sent with HTTP ranges, so an <audio> or <video> element can start anywhere in it and seek
2
+ // without fetching the whole file first: `send_file_ranges` answers one range of bytes with 206, the whole file with 200,
3
+ // HEAD with the size alone, and a range past the end with 416. The route decides which file a request may have; this
4
+ // only sends it.
5
+ // ── Imports ──────────────────────────────────────────────────────────────────
6
+ import { createReadStream } from "node:fs";
7
+ import { stat } from "node:fs/promises";
8
+ import { extname } from "node:path";
9
+ // ── Types of media ───────────────────────────────────────────────────────────
10
+ const media_types = {
11
+ ".aac": "audio/aac",
12
+ ".aif": "audio/aiff",
13
+ ".aiff": "audio/aiff",
14
+ ".alac": "audio/mp4",
15
+ ".flac": "audio/flac",
16
+ ".m4a": "audio/mp4",
17
+ ".m4b": "audio/mp4",
18
+ ".mka": "audio/x-matroska",
19
+ ".mkv": "video/x-matroska",
20
+ ".mp3": "audio/mpeg",
21
+ ".mp4": "video/mp4",
22
+ ".oga": "audio/ogg",
23
+ ".ogg": "audio/ogg",
24
+ ".opus": "audio/ogg",
25
+ ".wav": "audio/wav",
26
+ ".weba": "audio/webm",
27
+ ".webm": "video/webm",
28
+ ".wv": "audio/x-wavpack",
29
+ };
30
+ // The media type a file's extension names, or a plain stream of bytes for one it does not.
31
+ export function media_type(path) {
32
+ return media_types[extname(path).toLowerCase()] ?? "application/octet-stream";
33
+ }
34
+ // ── Ranges ───────────────────────────────────────────────────────────────────
35
+ // The one range a Range header asks for in a file of the size given: a whole range, an open end, or the last bytes;
36
+ // null for no header or one asking for several ranges, which then gets the whole file, and "unsatisfiable" for a
37
+ // range past the end.
38
+ export function requested_range(header, size) {
39
+ const match = /^bytes=(\d*)-(\d*)$/.exec(header?.trim() ?? "");
40
+ if (!match)
41
+ return null;
42
+ const [, first, last] = match;
43
+ if (first === "" && last === "")
44
+ return null;
45
+ if (first === "") {
46
+ const length = Number(last);
47
+ if (length === 0)
48
+ return "unsatisfiable";
49
+ return { start: Math.max(0, size - length), end: size - 1 };
50
+ }
51
+ const start = Number(first);
52
+ if (start >= size)
53
+ return "unsatisfiable";
54
+ const end = last === "" ? size - 1 : Math.min(Number(last), size - 1);
55
+ return end < start ? "unsatisfiable" : { start, end };
56
+ }
57
+ // Sends the file at path, or the range of it the request asks for; a missing file is a 404.
58
+ export async function send_file_ranges(request, reply, path, options = {}) {
59
+ let size;
60
+ try {
61
+ const found = await stat(path);
62
+ if (!found.isFile())
63
+ throw new Error("not a file");
64
+ size = found.size;
65
+ }
66
+ catch {
67
+ return reply.code(404).type("text/plain").send("That file is not on the server.");
68
+ }
69
+ reply.header("accept-ranges", "bytes").header("cache-control", options.cache_control ?? "private, max-age=3600").type(options.type ?? media_type(path));
70
+ const range = requested_range(request.headers.range, size);
71
+ if (range === "unsatisfiable")
72
+ return reply.code(416).header("content-range", `bytes */${size}`).send();
73
+ const { start, end } = range ?? { start: 0, end: size - 1 };
74
+ if (range)
75
+ reply.code(206).header("content-range", `bytes ${start}-${end}/${size}`);
76
+ reply.header("content-length", String(size === 0 ? 0 : end - start + 1));
77
+ if (request.method === "HEAD" || size === 0)
78
+ return reply.send();
79
+ return reply.send(createReadStream(path, { start, end }));
80
+ }
@@ -0,0 +1,12 @@
1
+ export interface MediaLinks {
2
+ readonly prefixes: readonly string[];
3
+ allows: (path: string) => boolean;
4
+ sign: (path: string, user: string, now?: number) => string;
5
+ check: (path: string, link: string, now?: number) => string | null;
6
+ }
7
+ export interface MediaLinkOptions {
8
+ prefixes: readonly string[];
9
+ lifetime_seconds?: number;
10
+ secret?: Uint8Array;
11
+ }
12
+ export declare function create_media_links(options: MediaLinkOptions): MediaLinks;
@@ -0,0 +1,33 @@
1
+ // Links to a server's media that carry their own sign-in, for an <audio> or <video> element, which cannot send a token:
2
+ // a signed-in page asks for a link to one path, such as /api/stream/<id>, and the link lets a GET of that path alone
3
+ // in as that user, read-only, until it runs out. Each link is an HMAC over the path, the user and the moment it ends,
4
+ // keyed by a secret the server makes as it starts, so a restart ends every link.
5
+ // ── Imports ──────────────────────────────────────────────────────────────────
6
+ import { createHmac, randomBytes, timingSafeEqual } from "node:crypto";
7
+ const base64url = (bytes) => Buffer.from(bytes).toString("base64url");
8
+ export function create_media_links(options) {
9
+ const secret = options.secret ?? randomBytes(32);
10
+ const lifetime = options.lifetime_seconds ?? 12 * 60 * 60;
11
+ const signature = (path, user, ends) => createHmac("sha256", secret).update(`${ends}\n${user}\n${path}`).digest();
12
+ const allows = (path) => options.prefixes.some((prefix) => path.startsWith(prefix) && path.length > prefix.length) && !/[?#]/.test(path) && !path.split("/").includes("..");
13
+ return {
14
+ prefixes: options.prefixes,
15
+ allows,
16
+ sign: (path, user, now = Date.now()) => {
17
+ const ends = Math.floor(now / 1000) + lifetime;
18
+ return `${ends}.${base64url(Buffer.from(user))}.${base64url(signature(path, user, ends))}`;
19
+ },
20
+ check: (path, link, now = Date.now()) => {
21
+ if (!allows(path))
22
+ return null;
23
+ const [ends_text, user_text, given] = link.split(".");
24
+ const ends = Number(ends_text);
25
+ if (!Number.isInteger(ends) || user_text === undefined || given === undefined || ends < Math.floor(now / 1000))
26
+ return null;
27
+ const user = Buffer.from(user_text, "base64url").toString();
28
+ const expected = signature(path, user, ends);
29
+ const presented = Buffer.from(given, "base64url");
30
+ return presented.length === expected.length && timingSafeEqual(presented, expected) ? user : null;
31
+ },
32
+ };
33
+ }
@@ -0,0 +1,54 @@
1
+ import type { EngineListener, LoadOptions, PlaybackEngine } from "../playback.ts";
2
+ export interface AudioLike {
3
+ src: string;
4
+ currentTime: number;
5
+ readonly duration: number;
6
+ volume: number;
7
+ preload: string;
8
+ readonly error: {
9
+ code: number;
10
+ message?: string;
11
+ } | null;
12
+ play(): Promise<void>;
13
+ pause(): void;
14
+ load(): void;
15
+ removeAttribute(name: string): void;
16
+ addEventListener(type: string, listener: () => void): void;
17
+ removeEventListener(type: string, listener: () => void): void;
18
+ }
19
+ export interface AudioEngineOptions {
20
+ make_audio?: () => AudioLike;
21
+ resolve?: (uri: string) => string | Promise<string>;
22
+ position_interval_in_milliseconds?: number;
23
+ }
24
+ export declare class AudioEngine implements PlaybackEngine {
25
+ private readonly listeners;
26
+ private readonly options;
27
+ private audio;
28
+ private next;
29
+ private loaded;
30
+ private volume;
31
+ private state;
32
+ private last_report;
33
+ private detach;
34
+ constructor(options?: AudioEngineOptions);
35
+ private make;
36
+ private emit;
37
+ private set_state;
38
+ private duration_ms;
39
+ private apply_volume;
40
+ private attach;
41
+ private on_time;
42
+ private finish;
43
+ private describe;
44
+ load(uri: string, options?: LoadOptions): Promise<void>;
45
+ preload(uri: string, options?: LoadOptions): Promise<void>;
46
+ play(): Promise<void>;
47
+ pause(): Promise<void>;
48
+ stop(): Promise<void>;
49
+ seek(position_in_milliseconds: number): Promise<void>;
50
+ set_volume(volume: number): Promise<void>;
51
+ subscribe(listener: EngineListener): () => void;
52
+ private drop;
53
+ dispose(): Promise<void>;
54
+ }