Persist user GUI preferences and resize the shared media modal
DC CMS qualification / qualify (push) Successful in 2m22s
DC CMS qualification / qualify (push) Successful in 2m22s
This commit is contained in:
@@ -4,6 +4,7 @@ import { dirname, join, resolve, posix, relative } from "node:path";
|
||||
import { fileURLToPath } from "node:url";
|
||||
import { randomBytes } from "node:crypto";
|
||||
import { createSiteApplication } from "./site-app.mjs";
|
||||
import { UserPreferencesStore } from "./user-preferences.mjs";
|
||||
|
||||
const cmsRoot = resolve(dirname(fileURLToPath(import.meta.url)), "..");
|
||||
const projectsRoot = resolve(process.env.CMS_PROJECTS_ROOT || join(cmsRoot, "projects"));
|
||||
@@ -150,6 +151,7 @@ function json(res, status, payload) {
|
||||
}
|
||||
await mkdir(projectsRoot, { recursive: true });
|
||||
const auth = await application(defaultId);
|
||||
const userPreferences = new UserPreferencesStore(projectsRoot);
|
||||
const server = createServer(async (req, res) => {
|
||||
try {
|
||||
const url = new URL(req.url, "http://cms.local");
|
||||
@@ -160,6 +162,12 @@ const server = createServer(async (req, res) => {
|
||||
const expected = new URL(process.env.CMS_BASE_URL || `http://${req.headers.host}`).origin;
|
||||
if (req.headers["sec-fetch-site"] === "cross-site" || (origin && origin !== expected)) throw fail("Недопустимый источник запроса", 403);
|
||||
}
|
||||
if (url.pathname === "/api/user/preferences") {
|
||||
const principal = auth.authEnabled ? (req.cmsUser?.sub ? `oidc:${req.cmsUser.sub}` : null) : 'local:no-auth';
|
||||
if (req.method === 'GET') return json(res, 200, { ok: true, ...await userPreferences.read(principal) });
|
||||
if (req.method === 'PATCH') return json(res, 200, { ok: true, ...await userPreferences.patch(principal, await body(req), { ifAbsent: req.headers['if-none-match'] === '*' }) });
|
||||
throw fail('Метод не поддерживается', 405);
|
||||
}
|
||||
if (url.pathname === "/api/sites") {
|
||||
if (req.method === "GET") return json(res, 200, { ok: true, sites: await siteList() });
|
||||
if (req.method === "POST") return json(res, 201, { ok: true, project: await createSite(await body(req)) });
|
||||
|
||||
@@ -3166,6 +3166,7 @@ async function handle(req, res) {
|
||||
}
|
||||
return {
|
||||
handle, handleAuthRoute, authorizeRequest,
|
||||
authEnabled: authConfig.enabled,
|
||||
config: () => structuredClone(projectConfig),
|
||||
publicConfig: publicProjectConfig,
|
||||
root: repoRoot,
|
||||
|
||||
@@ -0,0 +1,67 @@
|
||||
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); }
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user