193 lines
8.3 KiB
JavaScript
193 lines
8.3 KiB
JavaScript
'use strict';
|
|
|
|
// Persistent Remote Apps configuration (official config blob `remoteApps`, installed client main.js@1292478:
|
|
// {enabled:true, port:5899, allowLanAccess:false, apps:{}}) plus the per-app authorization the original keeps
|
|
// natively. Only a SHA-256 verifier of each issued API key is stored; the key itself exists only in the reply
|
|
// sent to the approved application. Nothing in this file is ever sent to the renderer.
|
|
const fs = require('node:fs');
|
|
const path = require('node:path');
|
|
const crypto = require('node:crypto');
|
|
|
|
const FILE_VERSION = 1;
|
|
const DEFAULT_PORT = 5899;
|
|
// Official TSInputNumber#websocket-port bounds (render@4957240: minimum 1025, maximum 65535).
|
|
const PORT_MIN = 1025;
|
|
const PORT_MAX = 65535;
|
|
const MAX_APPS = 128;
|
|
// docs/Remote Apps.md: "Only letters a-z and the dot are valid in the identifier."
|
|
const IDENTIFIER = /^[a-z.]{1,128}$/;
|
|
const CONTROL = /[\u0000-\u001f\u007f]/;
|
|
const LIMITS = Object.freeze({ name: 128, version: 64, description: 1024, apiKey: 256, origin: 256 });
|
|
|
|
const validPort = (v) => Number.isInteger(v) && v >= PORT_MIN && v <= PORT_MAX;
|
|
const validIdentifier = (v) => typeof v === 'string' && IDENTIFIER.test(v);
|
|
const validText = (v, max, { allowEmpty = true } = {}) => typeof v === 'string' && v.length <= max && (allowEmpty || v.length > 0) && !CONTROL.test(v);
|
|
const validHash = (v) => typeof v === 'string' && /^[0-9a-f]{64}$/.test(v);
|
|
|
|
function hashKey(key) {
|
|
return crypto.createHash('sha256').update(key, 'utf8').digest('hex');
|
|
}
|
|
|
|
/** Metadata an application announces in its auth payload; returns null when any field is invalid. */
|
|
function cleanMetadata(payload) {
|
|
if (!payload || typeof payload !== 'object' || Array.isArray(payload)) return null;
|
|
const { identifier, name, version, description } = payload;
|
|
if (!validIdentifier(identifier)) return null;
|
|
if (!validText(name, LIMITS.name, { allowEmpty: false }) || name.trim() === '') return null;
|
|
if (!validText(version, LIMITS.version) || !validText(description, LIMITS.description)) return null;
|
|
return { identifier, name, version, description };
|
|
}
|
|
|
|
/** null = a native client (no Origin header); a string = the exact browser Origin the app was approved for. */
|
|
const validOrigin = (v) => v === null || validText(v, LIMITS.origin, { allowEmpty: false });
|
|
|
|
function validApp(identifier, app) {
|
|
return app && typeof app === 'object' && app.identifier === identifier && cleanMetadata(app)
|
|
&& typeof app.allowed === 'boolean' && (app.keyHash === null || validHash(app.keyHash))
|
|
&& (app.origin === undefined || validOrigin(app.origin));
|
|
}
|
|
|
|
class RemoteAppStore {
|
|
constructor(file) {
|
|
this.file = file;
|
|
this.enabled = true;
|
|
this.port = DEFAULT_PORT;
|
|
this.apps = new Map();
|
|
this.loadError = null;
|
|
let raw;
|
|
try {
|
|
raw = fs.readFileSync(file, 'utf8');
|
|
} catch (err) {
|
|
if (err.code !== 'ENOENT') this.loadError = err.code ?? 'read_failed';
|
|
return;
|
|
}
|
|
let data;
|
|
try {
|
|
data = JSON.parse(raw);
|
|
} catch {
|
|
data = null;
|
|
}
|
|
if (!data || typeof data !== 'object' || data.version !== FILE_VERSION) {
|
|
// Fail closed: an unreadable file never grants anything; keep it aside instead of overwriting it.
|
|
this.loadError = 'corrupt';
|
|
try { fs.renameSync(file, `${file}.corrupt`); } catch { /* best effort */ }
|
|
return;
|
|
}
|
|
if (typeof data.enabled === 'boolean') this.enabled = data.enabled;
|
|
if (validPort(data.port)) this.port = data.port;
|
|
if (data.apps && typeof data.apps === 'object' && !Array.isArray(data.apps)) {
|
|
for (const [identifier, app] of Object.entries(data.apps).slice(0, MAX_APPS)) {
|
|
if (!validApp(identifier, app)) continue;
|
|
// Records written before origin binding were approved for native clients; they never trust a web page.
|
|
this.apps.set(identifier, { identifier, name: app.name, version: app.version, description: app.description, allowed: app.allowed, keyHash: app.keyHash, origin: app.origin ?? null });
|
|
}
|
|
}
|
|
}
|
|
|
|
/** Atomic owner-only write; on failure neither the file nor memory changes (callers pass the next state). */
|
|
write(next) {
|
|
const apps = {};
|
|
for (const [identifier, app] of next.apps) apps[identifier] = { ...app };
|
|
const body = JSON.stringify({ version: FILE_VERSION, enabled: next.enabled, port: next.port, allowLanAccess: false, apps }, null, 2);
|
|
fs.mkdirSync(path.dirname(this.file), { recursive: true });
|
|
const tmp = `${this.file}.tmp`;
|
|
fs.writeFileSync(tmp, body, { mode: 0o600 });
|
|
fs.renameSync(tmp, this.file);
|
|
this.enabled = next.enabled;
|
|
this.port = next.port;
|
|
this.apps = next.apps;
|
|
}
|
|
|
|
snapshotState() {
|
|
return { enabled: this.enabled, port: this.port, apps: new Map(Array.from(this.apps, ([k, v]) => [k, { ...v }])) };
|
|
}
|
|
|
|
setEnabled(enabled) {
|
|
if (typeof enabled !== 'boolean') throw new TypeError('enabled must be a boolean');
|
|
this.write({ ...this.snapshotState(), enabled });
|
|
}
|
|
|
|
setPort(port) {
|
|
if (!validPort(port)) throw new RangeError(`port must be an integer ${PORT_MIN}-${PORT_MAX}`);
|
|
this.write({ ...this.snapshotState(), port });
|
|
}
|
|
|
|
app(identifier) {
|
|
const app = this.apps.get(identifier);
|
|
return app ? { ...app } : null;
|
|
}
|
|
|
|
/** Public view without verifiers. */
|
|
list() {
|
|
return Array.from(this.apps.values(), ({ identifier, name, version, description, allowed, origin }) => ({ identifier, name, version, description, allowed, origin }));
|
|
}
|
|
|
|
/**
|
|
* Constant-time comparison of SHA-256 digests. The key is valid only from the exact origin it was issued to
|
|
* (null = native); a missing verifier, malformed key or other origin never matches.
|
|
*/
|
|
verifyKey(identifier, apiKey, origin) {
|
|
const app = this.apps.get(identifier);
|
|
if (!app || !app.allowed || !app.keyHash || !validText(apiKey, LIMITS.apiKey, { allowEmpty: false }) || !validOrigin(origin)) return false;
|
|
const match = crypto.timingSafeEqual(Buffer.from(hashKey(apiKey), 'hex'), Buffer.from(app.keyHash, 'hex'));
|
|
return match && app.origin === origin;
|
|
}
|
|
|
|
/** User approved `metadata` from `origin`: issues a fresh crypto-random key bound to that origin, revoking any earlier one. */
|
|
approve(metadata, origin) {
|
|
const meta = cleanMetadata(metadata);
|
|
if (!meta) throw new TypeError('invalid application metadata');
|
|
if (!validOrigin(origin)) throw new TypeError('invalid origin');
|
|
const next = this.snapshotState();
|
|
if (!next.apps.has(meta.identifier) && next.apps.size >= MAX_APPS) throw new RangeError('too many registered applications');
|
|
const apiKey = crypto.randomUUID();
|
|
next.apps.set(meta.identifier, { ...meta, allowed: true, keyHash: hashKey(apiKey), origin });
|
|
this.write(next);
|
|
return apiKey;
|
|
}
|
|
|
|
/** User denied `metadata`: the app is listed as not allowed and any earlier key is discarded. */
|
|
deny(metadata, origin) {
|
|
const meta = cleanMetadata(metadata);
|
|
if (!meta) throw new TypeError('invalid application metadata');
|
|
if (!validOrigin(origin)) throw new TypeError('invalid origin');
|
|
const next = this.snapshotState();
|
|
if (!next.apps.has(meta.identifier) && next.apps.size >= MAX_APPS) throw new RangeError('too many registered applications');
|
|
next.apps.set(meta.identifier, { ...meta, allowed: false, keyHash: null, origin });
|
|
this.write(next);
|
|
}
|
|
|
|
/** Metadata refresh after a successful key authentication (the key holder may update name/version/description). */
|
|
updateMetadata(metadata) {
|
|
const meta = cleanMetadata(metadata);
|
|
const app = meta && this.apps.get(meta.identifier);
|
|
if (!app || (app.name === meta.name && app.version === meta.version && app.description === meta.description)) return;
|
|
const next = this.snapshotState();
|
|
next.apps.set(meta.identifier, { ...app, ...meta });
|
|
this.write(next);
|
|
}
|
|
|
|
setAllowed(identifier, allowed) {
|
|
if (typeof allowed !== 'boolean') throw new TypeError('allowed must be a boolean');
|
|
const app = this.apps.get(identifier);
|
|
if (!app) return false;
|
|
const next = this.snapshotState();
|
|
next.apps.set(identifier, { ...app, allowed });
|
|
this.write(next);
|
|
return true;
|
|
}
|
|
|
|
remove(identifier) {
|
|
if (!this.apps.has(identifier)) return false;
|
|
const next = this.snapshotState();
|
|
next.apps.delete(identifier);
|
|
this.write(next);
|
|
return true;
|
|
}
|
|
}
|
|
|
|
module.exports = {
|
|
RemoteAppStore, cleanMetadata, validIdentifier, validPort, validText, validOrigin, hashKey,
|
|
DEFAULT_PORT, PORT_MIN, PORT_MAX, LIMITS,
|
|
};
|