feat(webui): EULA/PRIVACY consent gate — backend
Server-side consent gate: GET /api/agreements (texts + content-hash version + consentRequired) and POST /api/agreements/record-consent, persisted to config/consent.json. Enforced in the auth middleware (CONSENT_ALLOWLIST, ordered before the must-change-password gate) so the gate is real, not just a frontend convention. The version is content-derived, so consent is stable across app upgrades and re-prompts only when the agreement text changes. The EULA/PRIVACY docs are bundled into dist/ (build fails if they are missing).
This commit is contained in:
4 files changed
+382
No files matched your search
@@ -0,0 +1,184 @@
|
||||
import { createLogger } from '@snowluma/common/logger';
|
||||
import { createHash } from 'crypto';
|
||||
import fs from 'fs';
|
||||
import path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
|
||||
const log = createLogger('WebUI.Consent');
|
||||
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
||||
|
||||
const CONFIG_DIR = 'config';
|
||||
const CONSENT_CONFIG_PATH = path.join(CONFIG_DIR, 'consent.json');
|
||||
|
||||
// The two legal documents shown at the consent gate. Source of truth is the
|
||||
// repo-root markdown; the build copies them next to the bundle (dist/) so the
|
||||
// same lookup works in a packaged deploy. See vite.config.ts cp targets.
|
||||
const AGREEMENT_FILES = [
|
||||
{ id: 'eula' as const, file: 'EULA.md' },
|
||||
{ id: 'privacy' as const, file: 'PRIVACY.md' },
|
||||
];
|
||||
|
||||
export interface AgreementDoc {
|
||||
id: 'eula' | 'privacy';
|
||||
/** First markdown `# ` heading, for the tab/section title. */
|
||||
title: string;
|
||||
/** Declared "Version: x" from the doc — display only, NOT the consent key. */
|
||||
declaredVersion: string;
|
||||
/** Declared effective date (YYYY-MM-DD) — display only. */
|
||||
effectiveDate: string;
|
||||
/** Full markdown body the frontend renders. */
|
||||
text: string;
|
||||
}
|
||||
|
||||
export interface ConsentRecord {
|
||||
/** The content-hash agreements version that was accepted. */
|
||||
version: string;
|
||||
/** ISO timestamp of acceptance. */
|
||||
acceptedAt: string;
|
||||
}
|
||||
|
||||
export interface AgreementsPayload {
|
||||
/** Content-hash version of the current agreement set. */
|
||||
version: string;
|
||||
/**
|
||||
* True when the operator must (re-)accept: the agreements carry real text
|
||||
* AND the stored consent version differs from the current one. A missing or
|
||||
* unreadable agreement set fails OPEN (no gate) so a broken bundle can never
|
||||
* lock the admin out of their own panel.
|
||||
*/
|
||||
consentRequired: boolean;
|
||||
documents: AgreementDoc[];
|
||||
}
|
||||
|
||||
// ── Agreement loading (pure-ish; file read + parse, cached) ─────────────────
|
||||
|
||||
/**
|
||||
* Resolve an agreement file across the dev and packaged layouts. In dev the
|
||||
* server runs from source (`__dirname` = packages/core/src/webui); in a build
|
||||
* it is the single bundled dist/index.mjs (`__dirname` = dist/) with the docs
|
||||
* copied alongside. cwd is not reliable (dev cwd = packages/core, prod = repo
|
||||
* root or dist/), so we probe a handful of candidates and take the first hit.
|
||||
*/
|
||||
function resolveAgreementFile(file: string): string | null {
|
||||
const candidates = [
|
||||
path.join(__dirname, file), // packaged: dist/<file>
|
||||
path.resolve(__dirname, '..', '..', '..', '..', file), // dev tsx: repoRoot/<file>
|
||||
path.resolve(process.cwd(), file), // started from repo root
|
||||
path.resolve(process.cwd(), '..', '..', file), // dev cwd = packages/core
|
||||
];
|
||||
for (const candidate of candidates) {
|
||||
try {
|
||||
if (fs.existsSync(candidate)) return candidate;
|
||||
} catch {
|
||||
/* unreadable candidate, try next */
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
/** Extract title / declared version / effective date from a doc body. */
|
||||
export function parseAgreementMeta(text: string): {
|
||||
title: string;
|
||||
declaredVersion: string;
|
||||
effectiveDate: string;
|
||||
} {
|
||||
const title = text.match(/^#\s+(.+?)\s*$/m)?.[1]?.trim() ?? '';
|
||||
// Matches both "Version: 1.0" / "版本 / Version:** 1.0" style lines.
|
||||
const declaredVersion =
|
||||
text.match(/(?:Version|版本)[^\n0-9]*([0-9][0-9A-Za-z.\-]*)/)?.[1]?.trim() ?? '';
|
||||
const effectiveDate =
|
||||
text.match(/(?:Effective date|生效日期)[^\n0-9]*(\d{4}-\d{2}-\d{2})/)?.[1] ?? '';
|
||||
return { title, declaredVersion, effectiveDate };
|
||||
}
|
||||
|
||||
/**
|
||||
* Canonical agreements version = short sha256 over each doc's id + body.
|
||||
* Deliberately content-derived, NOT app-version-derived: it stays stable when
|
||||
* only the app is upgraded (so a one-time consent survives across versions),
|
||||
* and changes the moment any agreement's TEXT changes (forcing re-consent).
|
||||
*/
|
||||
export function computeAgreementsVersion(docs: { id: string; text: string }[]): string {
|
||||
const hash = createHash('sha256');
|
||||
for (const doc of docs) {
|
||||
hash.update(doc.id);
|
||||
hash.update('\0');
|
||||
hash.update(doc.text);
|
||||
hash.update('\0');
|
||||
}
|
||||
return hash.digest('hex').slice(0, 16);
|
||||
}
|
||||
|
||||
let cache: { docs: AgreementDoc[]; version: string } | null = null;
|
||||
|
||||
/** Load + parse both agreements and compute the version. Cached per process. */
|
||||
export function loadAgreements(): { docs: AgreementDoc[]; version: string } {
|
||||
if (cache) return cache;
|
||||
const docs: AgreementDoc[] = AGREEMENT_FILES.map(({ id, file }) => {
|
||||
const resolved = resolveAgreementFile(file);
|
||||
let text = '';
|
||||
if (resolved) {
|
||||
try {
|
||||
text = fs.readFileSync(resolved, 'utf8');
|
||||
} catch (err) {
|
||||
log.warn('failed to read %s: %s', file, err instanceof Error ? err.message : String(err));
|
||||
}
|
||||
} else {
|
||||
log.warn('agreement file not found (looked for %s near the bundle and repo root)', file);
|
||||
}
|
||||
const meta = parseAgreementMeta(text);
|
||||
return { id, title: meta.title, declaredVersion: meta.declaredVersion, effectiveDate: meta.effectiveDate, text };
|
||||
});
|
||||
cache = { docs, version: computeAgreementsVersion(docs) };
|
||||
return cache;
|
||||
}
|
||||
|
||||
// ── Consent persistence (config/consent.json, atomic) ───────────────────────
|
||||
|
||||
function ensureConfigDir(): void {
|
||||
fs.mkdirSync(CONFIG_DIR, { recursive: true });
|
||||
}
|
||||
|
||||
function isConsentRecord(value: unknown): value is ConsentRecord {
|
||||
if (!value || typeof value !== 'object') return false;
|
||||
const v = value as Record<string, unknown>;
|
||||
return typeof v.version === 'string' && v.version.length > 0 && typeof v.acceptedAt === 'string';
|
||||
}
|
||||
|
||||
export function loadConsentRecord(): ConsentRecord | null {
|
||||
try {
|
||||
if (!fs.existsSync(CONSENT_CONFIG_PATH)) return null;
|
||||
const parsed = JSON.parse(fs.readFileSync(CONSENT_CONFIG_PATH, 'utf8')) as unknown;
|
||||
return isConsentRecord(parsed) ? parsed : null;
|
||||
} catch (err) {
|
||||
log.warn('consent.json unreadable, treating as no consent: %s', err instanceof Error ? err.message : String(err));
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
function atomicWrite(record: ConsentRecord): void {
|
||||
ensureConfigDir();
|
||||
const tmp = CONSENT_CONFIG_PATH + '.tmp';
|
||||
fs.writeFileSync(tmp, JSON.stringify(record, null, 2), { encoding: 'utf8' });
|
||||
fs.renameSync(tmp, CONSENT_CONFIG_PATH);
|
||||
}
|
||||
|
||||
/** Persist that the operator accepted `version`. Returns the stored record. */
|
||||
export function recordConsent(version: string): ConsentRecord {
|
||||
const record: ConsentRecord = { version, acceptedAt: new Date().toISOString() };
|
||||
atomicWrite(record);
|
||||
return record;
|
||||
}
|
||||
|
||||
/** True when the agreements carry real text and the stored consent is stale. */
|
||||
export function isConsentRequired(): boolean {
|
||||
const { docs, version } = loadAgreements();
|
||||
const hasContent = docs.some((d) => d.text.trim().length > 0);
|
||||
if (!hasContent) return false; // fail open: never brick the panel on a broken bundle
|
||||
return loadConsentRecord()?.version !== version;
|
||||
}
|
||||
|
||||
/** Public payload for GET /api/agreements (texts + version + consentRequired). */
|
||||
export function getAgreementsPayload(): AgreementsPayload {
|
||||
const { docs, version } = loadAgreements();
|
||||
return { version, consentRequired: isConsentRequired(), documents: docs };
|
||||
}
|
||||
@@ -14,6 +14,7 @@ import os from 'os';
|
||||
import path from 'path';
|
||||
import { fileURLToPath } from 'url';
|
||||
import { evaluatePasswordRules, isStrongPassword, WebuiAuth } from './auth';
|
||||
import { getAgreementsPayload, isConsentRequired, loadAgreements, recordConsent } from './consent';
|
||||
import { resolveTlsContext, validateTlsPair } from './tls';
|
||||
import { coerceSettingsPatch } from './system-settings';
|
||||
import { buildBackup, planRestore, validateBackup } from './backup';
|
||||
@@ -58,6 +59,23 @@ const MUST_CHANGE_ALLOWLIST = new Set([
|
||||
'/api/auth/state',
|
||||
'/api/auth/check-strength',
|
||||
'/api/auth/change-password',
|
||||
// Consent is collected AFTER login but BEFORE the forced password change, so
|
||||
// reading + recording it must be reachable while the session mustChangePassword.
|
||||
'/api/agreements',
|
||||
'/api/agreements/record-consent',
|
||||
'/api/logout',
|
||||
]);
|
||||
|
||||
// Endpoints reachable while consent is still pending. Everything else is 403'd
|
||||
// with consentRequired:true until the operator accepts — the same server-side
|
||||
// enforcement pattern as MUST_CHANGE_ALLOWLIST, so the consent gate is real and
|
||||
// not merely a frontend convention. Ordered BEFORE the must-change gate so a
|
||||
// fresh install must consent first, then set its password.
|
||||
const CONSENT_ALLOWLIST = new Set([
|
||||
'/api/status',
|
||||
'/api/auth/state',
|
||||
'/api/agreements',
|
||||
'/api/agreements/record-consent',
|
||||
'/api/logout',
|
||||
]);
|
||||
|
||||
@@ -140,6 +158,12 @@ export async function initWebUI(
|
||||
log.warn('SNOWLUMA_WEBUI_TRUST_PROXY=1 — only safe behind a reverse proxy that strips client-set X-Real-IP / X-Forwarded-For');
|
||||
}
|
||||
|
||||
// Memoized once at startup (agreements version is fixed per process; a text
|
||||
// change ships with a redeploy that restarts us). Flipped to false the moment
|
||||
// consent is recorded, so the middleware never touches disk per request.
|
||||
let consentGatePending = isConsentRequired();
|
||||
if (consentGatePending) log.info('awaiting EULA/PRIVACY consent before the panel unlocks');
|
||||
|
||||
const app = new Hono();
|
||||
|
||||
// ─── Anti-indexing ───────────────────────────────────────────────────────
|
||||
@@ -181,6 +205,17 @@ export async function initWebUI(
|
||||
return c.json({ status: 'failed', message: 'Token expired or invalid' }, 401);
|
||||
}
|
||||
|
||||
// Consent gate (before the password gate): block everything outside the
|
||||
// consent allowlist until the operator has accepted the current agreements.
|
||||
// `consentGatePending` is memoized (see below) so this is a Set lookup, not
|
||||
// a disk read, on the hot path.
|
||||
if (consentGatePending && !CONSENT_ALLOWLIST.has(reqPath)) {
|
||||
return c.json(
|
||||
{ status: 'failed', message: '请先阅读并同意用户协议与隐私政策', consentRequired: true },
|
||||
403,
|
||||
);
|
||||
}
|
||||
|
||||
if (info.mustChangePassword && !MUST_CHANGE_ALLOWLIST.has(reqPath)) {
|
||||
return c.json({ status: 'failed', message: '请先修改密码', mustChangePassword: true }, 403);
|
||||
}
|
||||
@@ -286,6 +321,41 @@ export async function initWebUI(
|
||||
return c.json({ success: true, requireRelogin: true });
|
||||
});
|
||||
|
||||
// ─── EULA / PRIVACY consent ──────────────────────────────────────────────
|
||||
// Both are bearer-gated (consent is collected AFTER login) and live in the
|
||||
// consent + must-change allowlists so they're reachable during onboarding.
|
||||
// The version is content-derived, so consent is stable across app upgrades
|
||||
// and re-prompted only when the agreement text itself changes.
|
||||
app.get('/api/agreements', (c) => c.json(getAgreementsPayload()));
|
||||
|
||||
app.post('/api/agreements/record-consent', async (c) => {
|
||||
let body: { version?: unknown };
|
||||
try {
|
||||
body = await c.req.json();
|
||||
} catch {
|
||||
return c.json({ success: false, message: '请求格式错误' }, 400);
|
||||
}
|
||||
const version = typeof body.version === 'string' ? body.version : '';
|
||||
const current = loadAgreements().version;
|
||||
// Reject a stale/blank version so a client that read an older agreement set
|
||||
// can't record consent that the server would then treat as current.
|
||||
if (!version || version !== current) {
|
||||
return c.json(
|
||||
{ success: false, message: '协议版本已更新,请刷新后重新确认', currentVersion: current },
|
||||
409,
|
||||
);
|
||||
}
|
||||
try {
|
||||
recordConsent(version);
|
||||
} catch (err) {
|
||||
log.warn('record consent failed: %s', err instanceof Error ? err.message : String(err));
|
||||
return c.json({ success: false, message: '保存失败,请检查服务器日志' }, 500);
|
||||
}
|
||||
consentGatePending = false; // unlock the rest of the API for this process
|
||||
log.info('agreements consent recorded (version=%s)', version);
|
||||
return c.json({ success: true, version });
|
||||
});
|
||||
|
||||
// ─── Avatar proxy (uin validated) ────────────────────────────────────────
|
||||
app.get('/avatar/:uin', async (c) => {
|
||||
const uin = c.req.param('uin');
|
||||
|
||||
@@ -0,0 +1,108 @@
|
||||
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
|
||||
import fs from 'fs';
|
||||
import os from 'os';
|
||||
import path from 'path';
|
||||
import {
|
||||
computeAgreementsVersion,
|
||||
parseAgreementMeta,
|
||||
recordConsent,
|
||||
loadConsentRecord,
|
||||
} from '@/webui/consent';
|
||||
|
||||
describe('computeAgreementsVersion', () => {
|
||||
it('is deterministic for identical input', () => {
|
||||
const docs = [
|
||||
{ id: 'eula', text: 'A' },
|
||||
{ id: 'privacy', text: 'B' },
|
||||
];
|
||||
expect(computeAgreementsVersion(docs)).toBe(computeAgreementsVersion(docs));
|
||||
});
|
||||
|
||||
it('changes when any agreement TEXT changes (forces re-consent)', () => {
|
||||
const before = computeAgreementsVersion([
|
||||
{ id: 'eula', text: 'terms v1' },
|
||||
{ id: 'privacy', text: 'privacy v1' },
|
||||
]);
|
||||
const after = computeAgreementsVersion([
|
||||
{ id: 'eula', text: 'terms v2' }, // edited
|
||||
{ id: 'privacy', text: 'privacy v1' },
|
||||
]);
|
||||
expect(after).not.toBe(before);
|
||||
});
|
||||
|
||||
it('is independent of app version — same text => same version', () => {
|
||||
// The function takes only doc id+text, never an app version, so an app
|
||||
// upgrade with unchanged docs yields an identical version (stable consent).
|
||||
const v1 = computeAgreementsVersion([{ id: 'eula', text: 'same' }]);
|
||||
const v2 = computeAgreementsVersion([{ id: 'eula', text: 'same' }]);
|
||||
expect(v1).toBe(v2);
|
||||
});
|
||||
|
||||
it('is not fooled by id/text boundary shifting', () => {
|
||||
const a = computeAgreementsVersion([{ id: 'eula', text: 'x' }]);
|
||||
const b = computeAgreementsVersion([{ id: 'eu', text: 'lax' }]);
|
||||
expect(a).not.toBe(b);
|
||||
});
|
||||
});
|
||||
|
||||
describe('parseAgreementMeta', () => {
|
||||
it('pulls title / declared version / effective date from a bilingual doc', () => {
|
||||
const text = [
|
||||
'# SnowLuma 最终用户许可协议(EULA)/ End-User License Agreement',
|
||||
'',
|
||||
'- **生效日期 / Effective date:** 2026-06-19',
|
||||
'- **版本 / Version:** 1.0',
|
||||
'',
|
||||
'正文…',
|
||||
].join('\n');
|
||||
const meta = parseAgreementMeta(text);
|
||||
expect(meta.title).toBe('SnowLuma 最终用户许可协议(EULA)/ End-User License Agreement');
|
||||
expect(meta.declaredVersion).toBe('1.0');
|
||||
expect(meta.effectiveDate).toBe('2026-06-19');
|
||||
});
|
||||
|
||||
it('degrades gracefully on empty text', () => {
|
||||
expect(parseAgreementMeta('')).toEqual({ title: '', declaredVersion: '', effectiveDate: '' });
|
||||
});
|
||||
});
|
||||
|
||||
describe('consent persistence', () => {
|
||||
let tmp: string;
|
||||
let cwd: string;
|
||||
|
||||
beforeEach(() => {
|
||||
cwd = process.cwd();
|
||||
tmp = fs.mkdtempSync(path.join(os.tmpdir(), 'snowluma-consent-'));
|
||||
process.chdir(tmp);
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
process.chdir(cwd);
|
||||
fs.rmSync(tmp, { recursive: true, force: true });
|
||||
});
|
||||
|
||||
it('records and reads back the accepted version', () => {
|
||||
expect(loadConsentRecord()).toBeNull();
|
||||
const rec = recordConsent('abc123');
|
||||
expect(rec.version).toBe('abc123');
|
||||
expect(Date.parse(rec.acceptedAt)).not.toBeNaN();
|
||||
|
||||
const loaded = loadConsentRecord();
|
||||
expect(loaded?.version).toBe('abc123');
|
||||
expect(fs.existsSync(path.join('config', 'consent.json'))).toBe(true);
|
||||
});
|
||||
|
||||
it('staleness check: stored version != current => re-consent needed', () => {
|
||||
recordConsent('old-version');
|
||||
const stored = loadConsentRecord();
|
||||
// mirrors isConsentRequired()'s comparison against the current version
|
||||
expect(stored?.version !== 'new-version').toBe(true);
|
||||
expect(stored?.version !== 'old-version').toBe(false);
|
||||
});
|
||||
|
||||
it('ignores a malformed consent.json (treated as no consent)', () => {
|
||||
fs.mkdirSync('config', { recursive: true });
|
||||
fs.writeFileSync(path.join('config', 'consent.json'), '{ not json');
|
||||
expect(loadConsentRecord()).toBeNull();
|
||||
});
|
||||
});
|
||||
@@ -83,6 +83,19 @@ if (missingNatives.length > 0) {
|
||||
);
|
||||
}
|
||||
|
||||
// Legal docs are served by the WebUI consent gate; a missing one would silently
|
||||
// disable consent in the shipped build, so fail the build instead (mirrors the
|
||||
// native-binary guard above).
|
||||
const missingAgreements = ['EULA.md', 'PRIVACY.md'].filter(
|
||||
(f) => !fs.existsSync(path.resolve(repoRoot, f)),
|
||||
);
|
||||
if (missingAgreements.length > 0) {
|
||||
throw new Error(
|
||||
`Missing legal documents required by the WebUI consent gate:\n` +
|
||||
missingAgreements.map((f) => ` - ${path.resolve(repoRoot, f)}`).join('\n'),
|
||||
);
|
||||
}
|
||||
|
||||
const BaseConfigPlugin: PluginOption[] = [
|
||||
// Proton substitutes every `protobuf_encode<T>` / `protobuf_decode<T>`
|
||||
// call site with a monomorphized codec at build time. WITHOUT this
|
||||
@@ -109,6 +122,13 @@ const BaseConfigPlugin: PluginOption[] = [
|
||||
dest: path.join(distDir, 'native', 'ffmpeg'),
|
||||
flatten: true,
|
||||
},
|
||||
// Legal docs served verbatim by the WebUI consent gate. Copied next to
|
||||
// the bundle so consent.ts's path probe finds them in a packaged deploy.
|
||||
...['EULA.md', 'PRIVACY.md'].map((file) => ({
|
||||
src: toPosix(path.resolve(repoRoot, file)),
|
||||
dest: distDir,
|
||||
flatten: true,
|
||||
})),
|
||||
]
|
||||
})
|
||||
];
|
||||
|
||||
Reference in new issue
Block a user