mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-12-06 10:44:23 +00:00
style: format server and shared with prettier
A mechanical prettier --write over server/src, server/tests, server/scripts and shared/src with the workspaces' .prettierrc; nothing but layout and import order changes, and every file keeps the same set of imports. shared is formatted throughout and its format baseline is empty. The server baseline keeps the 35 files that Prettier would grow past their lint:size limit (they need a split first, which is not a formatting change), and the generated entity files stay as their generator writes them.
This commit is contained in:
@@ -1,14 +1,15 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import type { PluginActionsRepository } from '../../../db/repositories/PluginActions.repository';
|
||||
import type { PluginErrorLogRepository } from '../../../db/repositories/PluginErrorLog.repository';
|
||||
import type { PluginSettingsFieldsRepository } from '../../../db/repositories/PluginSettingsFields.repository';
|
||||
import type { PluginsRepository } from '../../../db/repositories/Plugins.repository';
|
||||
import type { UnitOfWork } from '../../database/unit-of-work';
|
||||
import { devLinkEnabled } from '../dev-link';
|
||||
import { pluginsCodeRoot, pluginCodeDir } from '../paths';
|
||||
import { parseJsonText, parseManifest, type PluginManifest } from './manifest';
|
||||
import { scanForNativeBinaries } from './native-scan';
|
||||
import { devLinkEnabled } from '../dev-link';
|
||||
import type { PluginsRepository } from '../../../db/repositories/Plugins.repository';
|
||||
import type { PluginActionsRepository } from '../../../db/repositories/PluginActions.repository';
|
||||
import type { PluginSettingsFieldsRepository } from '../../../db/repositories/PluginSettingsFields.repository';
|
||||
import type { PluginErrorLogRepository } from '../../../db/repositories/PluginErrorLog.repository';
|
||||
import type { UnitOfWork } from '../../database/unit-of-work';
|
||||
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
/** `discoverPlugins`/`upsert`'s repository set — "swap the parameter type" (plan3j-inputs.md
|
||||
* §0): the raw `BetterSqlite3.Database` parameter becomes this bundle of the four
|
||||
@@ -50,7 +51,11 @@ export async function discoverPlugins(repos: DiscoveryRepos): Promise<{ discover
|
||||
// A dev-link symlink only loads in dev-link mode; a stale link left on the
|
||||
// volume must not be discovered/registered on a normal (non-dev) boot.
|
||||
if (!devLinkEnabled()) continue;
|
||||
try { isDir = fs.statSync(full).isDirectory(); } catch { isDir = false; }
|
||||
try {
|
||||
isDir = fs.statSync(full).isDirectory();
|
||||
} catch {
|
||||
isDir = false;
|
||||
}
|
||||
} else if (isDir && !devLinkEnabled()) {
|
||||
// On Windows a dev-link is a junction, which Dirent reports as a plain
|
||||
// directory (isSymbolicLink() is false). Detect it the same way: if the
|
||||
@@ -58,7 +63,9 @@ export async function discoverPlugins(repos: DiscoveryRepos): Promise<{ discover
|
||||
// unless dev-link mode is on. A normal dir realpaths back to itself.
|
||||
try {
|
||||
if (fs.realpathSync(full) !== path.join(fs.realpathSync(root), entry.name)) continue;
|
||||
} catch { /* unreadable target — leave as a normal dir and let discovery fail loudly */ }
|
||||
} catch {
|
||||
/* unreadable target — leave as a normal dir and let discovery fail loudly */
|
||||
}
|
||||
}
|
||||
if (!isDir) continue;
|
||||
const dir = pluginCodeDir(entry.name);
|
||||
@@ -116,7 +123,14 @@ async function upsert(repos: DiscoveryRepos, m: PluginManifest): Promise<void> {
|
||||
await repos.actions.deleteAllForPlugin(m.id);
|
||||
await repos.actions.insertActions(
|
||||
m.id,
|
||||
m.actions.map((a, i) => ({ action_key: a.key, label: a.label, hint: a.hint ?? null, danger: a.danger ? 1 : 0, scope: a.scope, sort_order: i })),
|
||||
m.actions.map((a, i) => ({
|
||||
action_key: a.key,
|
||||
label: a.label,
|
||||
hint: a.hint ?? null,
|
||||
danger: a.danger ? 1 : 0,
|
||||
scope: a.scope,
|
||||
sort_order: i,
|
||||
})),
|
||||
);
|
||||
|
||||
await repos.settingsFields.deleteAllForPlugin(m.id);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import semver from 'semver';
|
||||
import { readEnv, runningVersion } from '../../../app-config';
|
||||
|
||||
import semver from 'semver';
|
||||
|
||||
/**
|
||||
* Host-version compatibility for plugins (#plugins). A manifest declares the TREK
|
||||
* versions it supports as a semver RANGE (`"trek": ">=3.2.0 <4.0.0"`); this module
|
||||
@@ -46,7 +47,9 @@ export function normalizedHost(): string | null {
|
||||
const coerced = semver.coerce(raw)?.version ?? null;
|
||||
if (!coerced && !warnedUnparseable) {
|
||||
warnedUnparseable = true;
|
||||
console.warn(`[plugins] APP_VERSION "${raw}" is not a semver version — plugin TREK-compatibility checks are disabled`);
|
||||
console.warn(
|
||||
`[plugins] APP_VERSION "${raw}" is not a semver version — plugin TREK-compatibility checks are disabled`,
|
||||
);
|
||||
}
|
||||
return coerced;
|
||||
}
|
||||
|
||||
@@ -1,12 +1,6 @@
|
||||
import semver from 'semver';
|
||||
import { McpToolSchemaError, buildToolInputSchema, normaliseToolSchema, sanitiseToolText } from '../mcp-tool-schema';
|
||||
import { readPoiCategory } from '../poi-categories';
|
||||
import { isKnownPermission, PLUGIN_API_VERSION } from '../protocol/envelope';
|
||||
import { isValidTrekRange, minTrekOf, trekRangeBypassed } from './host-compat';
|
||||
import {
|
||||
McpToolSchemaError,
|
||||
buildToolInputSchema,
|
||||
normaliseToolSchema,
|
||||
sanitiseToolText,
|
||||
} from '../mcp-tool-schema';
|
||||
import {
|
||||
ACTIONS_MAX,
|
||||
ADDON_ID_RE,
|
||||
@@ -28,8 +22,10 @@ import {
|
||||
TRIP_PAGE_POSITION_MAX,
|
||||
WIDGET_SLOTS,
|
||||
} from '../protocol/manifest-rules';
|
||||
import { isValidTrekRange, minTrekOf, trekRangeBypassed } from './host-compat';
|
||||
import { PLUGIN_POI_MAX_CATEGORIES, type PluginPoiCategory } from '@trek/shared';
|
||||
import { readPoiCategory } from '../poi-categories';
|
||||
|
||||
import semver from 'semver';
|
||||
|
||||
/**
|
||||
* Parse + validate a plugin's trek-plugin.json (#plugins, M4). Kept deliberately
|
||||
@@ -262,7 +258,9 @@ export function parseManifest(raw: unknown, opts?: { requireTrek?: boolean }): P
|
||||
egress.length === 0 &&
|
||||
m.operatorEgress !== true
|
||||
) {
|
||||
throw new ManifestError('http:outbound declared but egress[] is empty (set operatorEgress: true if the hosts are admin-supplied)');
|
||||
throw new ManifestError(
|
||||
'http:outbound declared but egress[] is empty (set operatorEgress: true if the hosts are admin-supplied)',
|
||||
);
|
||||
}
|
||||
if (egress.includes('*')) throw new ManifestError('egress[] must not contain a bare "*"');
|
||||
const badEgress = egress.find((h) => !HOST_RE.test(h));
|
||||
@@ -321,7 +319,8 @@ export function parseManifest(raw: unknown, opts?: { requireTrek?: boolean }): P
|
||||
function parseRequiredAddons(raw: unknown): string[] {
|
||||
const out: string[] = [];
|
||||
for (const v of arr(raw)) {
|
||||
if (typeof v !== 'string' || !ADDON_ID_RE.test(v)) throw new ManifestError(`invalid requiredAddons entry "${String(v)}"`);
|
||||
if (typeof v !== 'string' || !ADDON_ID_RE.test(v))
|
||||
throw new ManifestError(`invalid requiredAddons entry "${String(v)}"`);
|
||||
if (!out.includes(v)) out.push(v);
|
||||
}
|
||||
return out;
|
||||
@@ -343,7 +342,8 @@ function parsePluginDependencies(raw: unknown, selfId: string): PluginDependency
|
||||
if (id === selfId) throw new ManifestError(`plugin "${selfId}" cannot depend on itself`);
|
||||
if (out.some((e) => e.id === id)) throw new ManifestError(`duplicate pluginDependencies id "${id}"`);
|
||||
const version = str(d.version, 'pluginDependencies.version');
|
||||
if (semver.validRange(version) === null) throw new ManifestError(`invalid pluginDependencies version range "${version}" for "${id}"`);
|
||||
if (semver.validRange(version) === null)
|
||||
throw new ManifestError(`invalid pluginDependencies version range "${version}" for "${id}"`);
|
||||
out.push({ id, version });
|
||||
}
|
||||
return out;
|
||||
@@ -371,15 +371,24 @@ function parseCapabilities(raw: unknown): PluginCapabilities {
|
||||
const replaces: string[] = [];
|
||||
for (const v of tp.replaces) {
|
||||
if (typeof v !== 'string' || !TABS.includes(v)) {
|
||||
throw new ManifestError(`capabilities.tripPage.replaces: "${String(v)}" is not a replaceable tab (${REPLACEABLE_TABS.join(', ')})`);
|
||||
throw new ManifestError(
|
||||
`capabilities.tripPage.replaces: "${String(v)}" is not a replaceable tab (${REPLACEABLE_TABS.join(', ')})`,
|
||||
);
|
||||
}
|
||||
if (!replaces.includes(v)) replaces.push(v);
|
||||
}
|
||||
if (replaces.length) page.replaces = replaces;
|
||||
}
|
||||
if (tp.position !== undefined) {
|
||||
if (typeof tp.position !== 'number' || !Number.isInteger(tp.position) || tp.position < 0 || tp.position > TRIP_PAGE_POSITION_MAX) {
|
||||
throw new ManifestError(`capabilities.tripPage.position must be an integer between 0 and ${TRIP_PAGE_POSITION_MAX}`);
|
||||
if (
|
||||
typeof tp.position !== 'number' ||
|
||||
!Number.isInteger(tp.position) ||
|
||||
tp.position < 0 ||
|
||||
tp.position > TRIP_PAGE_POSITION_MAX
|
||||
) {
|
||||
throw new ManifestError(
|
||||
`capabilities.tripPage.position must be an integer between 0 and ${TRIP_PAGE_POSITION_MAX}`,
|
||||
);
|
||||
}
|
||||
page.position = tp.position;
|
||||
}
|
||||
@@ -395,7 +404,8 @@ function parseCapabilities(raw: unknown): PluginCapabilities {
|
||||
const title = optStr(nc.title);
|
||||
if (title) channel.title = title;
|
||||
if (nc.events !== undefined) {
|
||||
if (!Array.isArray(nc.events)) throw new ManifestError('capabilities.notificationChannel.events must be an array');
|
||||
if (!Array.isArray(nc.events))
|
||||
throw new ManifestError('capabilities.notificationChannel.events must be an array');
|
||||
const events: string[] = [];
|
||||
for (const v of nc.events) {
|
||||
if (typeof v !== 'string' || !CHANNEL_EVENTS.includes(v)) {
|
||||
@@ -422,9 +432,11 @@ function parseCapabilities(raw: unknown): PluginCapabilities {
|
||||
if (!ROUTE_PROFILE_ID_RE.test(id)) {
|
||||
throw new ManifestError('capabilities.routeProfiles: id must be lowercase [a-z][a-z0-9-], max 24 chars');
|
||||
}
|
||||
if (profiles.some((x) => x.id === id)) throw new ManifestError(`capabilities.routeProfiles: duplicate id "${id}"`);
|
||||
if (profiles.some((x) => x.id === id))
|
||||
throw new ManifestError(`capabilities.routeProfiles: duplicate id "${id}"`);
|
||||
const label = typeof p.label === 'string' ? p.label.trim() : '';
|
||||
if (!label || label.length > 40) throw new ManifestError('capabilities.routeProfiles: label is required (max 40 chars)');
|
||||
if (!label || label.length > 40)
|
||||
throw new ManifestError('capabilities.routeProfiles: label is required (max 40 chars)');
|
||||
const icon = optStr(p.icon);
|
||||
profiles.push({ id, label, ...(icon ? { icon: icon.slice(0, 40) } : {}) });
|
||||
}
|
||||
@@ -525,7 +537,8 @@ function parseCapabilityNames(raw: unknown, field: string): string[] {
|
||||
if (!Array.isArray(raw)) throw new ManifestError(`capabilities.${field} must be an array of names`);
|
||||
const out: string[] = [];
|
||||
for (const v of raw) {
|
||||
if (typeof v !== 'string' || !CAPABILITY_NAME_RE.test(v)) throw new ManifestError(`invalid capabilities.${field} entry "${String(v)}"`);
|
||||
if (typeof v !== 'string' || !CAPABILITY_NAME_RE.test(v))
|
||||
throw new ManifestError(`invalid capabilities.${field} entry "${String(v)}"`);
|
||||
if (!out.includes(v)) out.push(v);
|
||||
}
|
||||
return out;
|
||||
@@ -550,7 +563,10 @@ function parseSettings(raw: unknown): ManifestSettingField[] {
|
||||
default: parseSettingDefault(s.default, { secret, input_type, options }),
|
||||
scope: s.scope === 'user' ? 'user' : 'instance',
|
||||
options,
|
||||
oauth: s.oauth && typeof s.oauth === 'object' ? (s.oauth as { initPath?: string; callbackPath?: string }) : undefined,
|
||||
oauth:
|
||||
s.oauth && typeof s.oauth === 'object'
|
||||
? (s.oauth as { initPath?: string; callbackPath?: string })
|
||||
: undefined,
|
||||
};
|
||||
})
|
||||
.filter((s) => s.key);
|
||||
@@ -573,7 +589,8 @@ function parseSettingDefault(
|
||||
if (raw === undefined || raw === null || field.secret) return undefined;
|
||||
if (typeof raw !== 'string' && typeof raw !== 'number' && typeof raw !== 'boolean') return undefined;
|
||||
if (field.input_type === 'checkbox' && typeof raw !== 'boolean') return undefined;
|
||||
if (field.options && field.options.length > 0 && !field.options.some((o) => o.value === String(raw))) return undefined;
|
||||
if (field.options && field.options.length > 0 && !field.options.some((o) => o.value === String(raw)))
|
||||
return undefined;
|
||||
return raw;
|
||||
}
|
||||
|
||||
@@ -636,7 +653,9 @@ function assertSettingKey(key: string): string {
|
||||
// would leave the plugin expecting a setting the host will never store.
|
||||
if (!key) return key;
|
||||
if (!SETTING_KEY_RE.test(key) || RESERVED_SETTING_KEYS.has(key)) {
|
||||
throw new ManifestError(`invalid settings key "${key}" (letters, digits, . _ - ; must start with a letter; 1–64 chars)`);
|
||||
throw new ManifestError(
|
||||
`invalid settings key "${key}" (letters, digits, . _ - ; must start with a letter; 1–64 chars)`,
|
||||
);
|
||||
}
|
||||
return key;
|
||||
}
|
||||
|
||||
@@ -33,7 +33,8 @@ export function safeJoin(dest: string, name: string): string {
|
||||
if (norm.split('/').some((seg) => seg === '..')) throw new ExtractError(`path traversal rejected: ${name}`);
|
||||
const resolved = path.resolve(dest, norm);
|
||||
const root = path.resolve(dest);
|
||||
if (resolved !== root && !resolved.startsWith(root + path.sep)) throw new ExtractError(`escapes destination: ${name}`);
|
||||
if (resolved !== root && !resolved.startsWith(root + path.sep))
|
||||
throw new ExtractError(`escapes destination: ${name}`);
|
||||
return resolved;
|
||||
}
|
||||
|
||||
@@ -90,7 +91,9 @@ function readTarGz(buf: Buffer, lim: Required<ExtractLimits>): Member[] {
|
||||
// memory. The entry budgets in extractArchive never get a say; they run on
|
||||
// the list this function has to finish building first.
|
||||
if (!Number.isSafeInteger(size) || size < 0) {
|
||||
throw new ExtractError(`invalid entry size in tar header: ${block.subarray(124, 136).toString('utf8').replace(/\0.*$/, '').trim()}`);
|
||||
throw new ExtractError(
|
||||
`invalid entry size in tar header: ${block.subarray(124, 136).toString('utf8').replace(/\0.*$/, '').trim()}`,
|
||||
);
|
||||
}
|
||||
const typeflag = String.fromCodePoint(block[156]);
|
||||
off += 512;
|
||||
@@ -98,7 +101,8 @@ function readTarGz(buf: Buffer, lim: Required<ExtractLimits>): Member[] {
|
||||
off += Math.ceil(size / 512) * 512;
|
||||
if (!name || name.endsWith('/PaxHeader/') || typeflag === 'x' || typeflag === 'g') continue;
|
||||
if (typeflag === '5') members.push({ name, type: 'dir' });
|
||||
else if (typeflag === '0' || typeflag === '\0' || typeflag === '') members.push({ name, type: 'file', data: Buffer.from(data) });
|
||||
else if (typeflag === '0' || typeflag === '\0' || typeflag === '')
|
||||
members.push({ name, type: 'file', data: Buffer.from(data) });
|
||||
else members.push({ name, type: 'other' }); // links (1,2), devices, fifo
|
||||
}
|
||||
return members;
|
||||
@@ -109,7 +113,10 @@ function readZip(buf: Buffer, lim: Required<ExtractLimits>): Member[] {
|
||||
// Find End Of Central Directory.
|
||||
let eocd = -1;
|
||||
for (let i = buf.length - 22; i >= 0 && i > buf.length - 22 - 65536; i--) {
|
||||
if (buf.readUInt32LE(i) === 0x06054b50) { eocd = i; break; }
|
||||
if (buf.readUInt32LE(i) === 0x06054b50) {
|
||||
eocd = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if (eocd < 0) throw new ExtractError('invalid zip (no EOCD)');
|
||||
const count = buf.readUInt16LE(eocd + 10);
|
||||
@@ -140,8 +147,14 @@ function readZip(buf: Buffer, lim: Required<ExtractLimits>): Member[] {
|
||||
const comp = buf.subarray(dataStart, dataStart + compSize);
|
||||
p += 46 + nameLen + extraLen + commentLen;
|
||||
|
||||
if (isSymlink) { members.push({ name, type: 'other' }); continue; }
|
||||
if (name.endsWith('/')) { members.push({ name, type: 'dir' }); continue; }
|
||||
if (isSymlink) {
|
||||
members.push({ name, type: 'other' });
|
||||
continue;
|
||||
}
|
||||
if (name.endsWith('/')) {
|
||||
members.push({ name, type: 'dir' });
|
||||
continue;
|
||||
}
|
||||
let data: Buffer;
|
||||
if (method === 0) {
|
||||
if (compSize > lim.maxFileBytes) throw new ExtractError(`file too large: ${name}`);
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import { isBlockedIp } from '../runtime/egress-policy';
|
||||
|
||||
import { createHash } from 'node:crypto';
|
||||
import dns from 'node:dns/promises';
|
||||
import { isBlockedIp } from '../runtime/egress-policy';
|
||||
|
||||
/**
|
||||
* SSRF-hardened download for the plugin installer (#plugins, M4). The primary
|
||||
|
||||
@@ -34,7 +34,12 @@ function ed25519KeyFromRaw(raw: Buffer): crypto.KeyObject {
|
||||
* A bare 32-byte base64 key (44 chars) is also accepted for simple deployments.
|
||||
*/
|
||||
function parseMinisignPubKey(pub: string): { key: crypto.KeyObject; keyId: Buffer | null } {
|
||||
const line = pub.trim().split(/\r?\n/).map((l) => l.trim()).filter((l) => l && !l.startsWith('untrusted comment')).pop();
|
||||
const line = pub
|
||||
.trim()
|
||||
.split(/\r?\n/)
|
||||
.map((l) => l.trim())
|
||||
.filter((l) => l && !l.startsWith('untrusted comment'))
|
||||
.pop();
|
||||
if (!line) throw new SignatureError('empty public key');
|
||||
const buf = Buffer.from(line, 'base64');
|
||||
if (buf.length === 32) return { key: ed25519KeyFromRaw(buf), keyId: null };
|
||||
@@ -51,7 +56,12 @@ function parseMinisignPubKey(pub: string): { key: crypto.KeyObject; keyId: Buffe
|
||||
* raw bytes) is also accepted.
|
||||
*/
|
||||
function parseMinisignSignature(sig: string): { algo: 'Ed' | 'ED' | 'raw'; keyId: Buffer | null; signature: Buffer } {
|
||||
const line = sig.trim().split(/\r?\n/).map((l) => l.trim()).filter((l) => l && !l.startsWith('untrusted comment')).shift();
|
||||
const line = sig
|
||||
.trim()
|
||||
.split(/\r?\n/)
|
||||
.map((l) => l.trim())
|
||||
.filter((l) => l && !l.startsWith('untrusted comment'))
|
||||
.shift();
|
||||
if (!line) throw new SignatureError('empty signature');
|
||||
const buf = Buffer.from(line, 'base64');
|
||||
if (buf.length === 64) return { algo: 'raw', keyId: null, signature: buf };
|
||||
@@ -77,8 +87,7 @@ export function verifyAuthorSignature(bytes: Buffer, signatureB64: string, publi
|
||||
// If both carry a key id, they must match the same key (catches a wrong-key mixup).
|
||||
if (keyId && sigKeyId && !keyId.equals(sigKeyId)) return false;
|
||||
|
||||
const message =
|
||||
algo === 'ED' ? crypto.createHash('blake2b512').update(bytes).digest() : bytes;
|
||||
const message = algo === 'ED' ? crypto.createHash('blake2b512').update(bytes).digest() : bytes;
|
||||
try {
|
||||
return crypto.verify(null, message, key, signature);
|
||||
} catch {
|
||||
|
||||
Reference in New Issue
Block a user