68 lines
3.9 KiB
JavaScript
68 lines
3.9 KiB
JavaScript
import { createHash, randomBytes } from 'node:crypto';
|
|
import { mkdir, readFile, rename, rm, writeFile } from 'node:fs/promises';
|
|
import { join } from 'node:path';
|
|
|
|
const fail = () => Object.assign(new Error('Некорректные настройки интерфейса'), { status: 400 });
|
|
const object = value => value && typeof value === 'object' && !Array.isArray(value);
|
|
const defaults = () => ({ schemaVersion: 1, appearance: { theme: 'dark', accent: null }, gui: { modals: {} } });
|
|
export function validatePreferencesPatch(patch) {
|
|
if (!object(patch) || Object.keys(patch).some(k => !['appearance', 'gui'].includes(k))) throw fail();
|
|
if (patch.appearance !== undefined) {
|
|
const a = patch.appearance;
|
|
if (!object(a) || Object.keys(a).some(k => !['theme', 'accent'].includes(k))) throw fail();
|
|
if (a.theme !== undefined && !['dark', 'light'].includes(a.theme)) throw fail();
|
|
if (a.accent !== undefined && a.accent !== null && (typeof a.accent !== 'string' || !/^#[a-f\d]{6}$/i.test(a.accent))) throw fail();
|
|
}
|
|
if (patch.gui !== undefined) {
|
|
if (!object(patch.gui) || Object.keys(patch.gui).some(k => k !== 'modals') || !object(patch.gui.modals)) throw fail();
|
|
for (const [key, size] of Object.entries(patch.gui.modals)) {
|
|
if (!/^[a-z][a-z0-9-]{0,63}$/.test(key) || ['constructor', 'prototype'].includes(key)) throw fail();
|
|
if (size === null) continue;
|
|
if (!object(size) || Object.keys(size).length !== 2 || !Number.isInteger(size.width) || !Number.isInteger(size.height) || size.width < 100 || size.height < 100 || size.width > 10000 || size.height > 10000) throw fail();
|
|
}
|
|
}
|
|
return patch;
|
|
}
|
|
|
|
/** Private per-principal metadata, outside all sites, exports and publish roots. */
|
|
export class UserPreferencesStore {
|
|
#root; #queues = new Map();
|
|
constructor(projectsRoot) { this.#root = join(projectsRoot, '.user-meta'); }
|
|
#key(principal) {
|
|
if (typeof principal !== 'string' || !principal) throw Object.assign(new Error('Требуется вход'), { status: 401 });
|
|
return createHash('sha256').update(principal).digest('hex');
|
|
}
|
|
async read(principal) {
|
|
const key = this.#key(principal);
|
|
try {
|
|
const document = JSON.parse(await readFile(join(this.#root, `${key}.json`), 'utf8'));
|
|
if (document.schemaVersion !== 1) throw new Error('Unsupported GUI metadata version');
|
|
validatePreferencesPatch({ appearance: document.appearance, gui: document.gui });
|
|
return { preferences: document, exists: true };
|
|
} catch (error) { if (error.code === 'ENOENT') return { preferences: defaults(), exists: false }; throw error; }
|
|
}
|
|
async patch(principal, patch, { ifAbsent = false } = {}) {
|
|
validatePreferencesPatch(patch);
|
|
const key = this.#key(principal);
|
|
const pending = (this.#queues.get(key) || Promise.resolve()).then(async () => {
|
|
const current = await this.read(principal);
|
|
if (ifAbsent && current.exists) return current;
|
|
const next = current.preferences;
|
|
Object.assign(next.appearance, patch.appearance);
|
|
if (next.appearance.accent) next.appearance.accent = next.appearance.accent.toLowerCase();
|
|
for (const [id, size] of Object.entries(patch.gui?.modals || {})) {
|
|
if (size === null) delete next.gui.modals[id]; else next.gui.modals[id] = size;
|
|
}
|
|
if (Object.keys(next.gui.modals).length > 64) throw fail();
|
|
await mkdir(this.#root, { recursive: true, mode: 0o700 });
|
|
const path = join(this.#root, `${key}.json`), temporary = `${path}.${randomBytes(8).toString('hex')}.tmp`;
|
|
try { await writeFile(temporary, JSON.stringify(next, null, 2) + '\n', { flag: 'wx', mode: 0o600 }); await rename(temporary, path); }
|
|
finally { await rm(temporary, { force: true }); }
|
|
return { preferences: next, exists: true };
|
|
});
|
|
const settled = pending.catch(() => {});
|
|
this.#queues.set(key, settled);
|
|
try { return await pending; } finally { if (this.#queues.get(key) === settled) this.#queues.delete(key); }
|
|
}
|
|
}
|