Merge upstream/main to resolve conflicts

Both sides added adjacent LOGIN_* config entries (upstream:
loginShowHeading/loginShowSubtitle/logo sizing; this branch:
loginShowTotp/loginShowVersion) — resolution keeps both.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LrR2CVfvcPWxr9ub299VwW
This commit is contained in:
Maarten Draijer
2026-07-22 02:54:55 +00:00
co-authored by Claude Fable 5
298 changed files with 25468 additions and 2440 deletions
@@ -0,0 +1,59 @@
import { describe, it, expect, beforeEach, afterEach } from 'vitest';
import { mkdtemp, rm, readFile, writeFile } from 'node:fs/promises';
import { existsSync } from 'node:fs';
import { tmpdir } from 'node:os';
import path from 'node:path';
import { migratePolicyUnifiedMailbox } from '../migrate';
// migratePolicyUnifiedMailbox reads ADMIN_CONFIG_DIR at call time (see paths.ts),
// so each test points it at a fresh temp dir.
let dir: string;
const policyPath = () => path.join(dir, 'policy.json');
const markerPath = () => path.join(dir, '.migrated-unified-mailbox');
const writePolicy = (features: Record<string, unknown>) =>
writeFile(policyPath(), JSON.stringify({ features, restrictions: {} }, null, 2), 'utf-8');
const readFeatures = async () =>
JSON.parse(await readFile(policyPath(), 'utf-8')).features as Record<string, unknown>;
beforeEach(async () => {
dir = await mkdtemp(path.join(tmpdir(), 'bw-policy-'));
process.env.ADMIN_CONFIG_DIR = dir;
});
afterEach(async () => {
delete process.env.ADMIN_CONFIG_DIR;
await rm(dir, { recursive: true, force: true });
});
describe('migratePolicyUnifiedMailbox', () => {
it('enables unifiedCrossAccountEnabled when a cross view was active', async () => {
await writePolicy({ crossUnreadViewEnabled: true });
await migratePolicyUnifiedMailbox();
expect((await readFeatures()).unifiedCrossAccountEnabled).toBe(true);
expect(existsSync(markerPath())).toBe(true);
});
it('does not enable it for a standalone All-Mail-only policy', async () => {
await writePolicy({ allMailViewEnabled: true, crossUnreadViewEnabled: false, crossStarredViewEnabled: false, crossAllViewEnabled: false });
await migratePolicyUnifiedMailbox();
expect((await readFeatures()).unifiedCrossAccountEnabled).toBeUndefined();
});
it('is a one-shot: a later admin disable survives a re-run', async () => {
await writePolicy({ crossAllViewEnabled: true });
await migratePolicyUnifiedMailbox();
expect((await readFeatures()).unifiedCrossAccountEnabled).toBe(true);
// Admin turns it back off; the marker is present, so re-running is a no-op.
await writePolicy({ crossAllViewEnabled: true, unifiedCrossAccountEnabled: false });
await migratePolicyUnifiedMailbox();
expect((await readFeatures()).unifiedCrossAccountEnabled).toBe(false);
});
it('no policy.json: writes the marker and does not throw', async () => {
await migratePolicyUnifiedMailbox();
expect(existsSync(markerPath())).toBe(true);
expect(existsSync(policyPath())).toBe(false);
});
});
+17 -4
View File
@@ -33,12 +33,12 @@ class ConfigManager {
this.adminConfig = await this.readJsonFile('config.json') || {};
const policy = await this.readJsonFile('policy.json');
if (policy) {
this.policyCache = {
this.policyCache = ConfigManager.normalizePolicy({
...DEFAULT_POLICY,
...policy,
features: { ...DEFAULT_FEATURE_GATES, ...(policy.features || {}) },
themePolicy: { ...DEFAULT_THEME_POLICY, ...(policy.themePolicy || {}) },
};
});
} else {
this.policyCache = { ...DEFAULT_POLICY };
}
@@ -166,15 +166,28 @@ class ConfigManager {
*/
async setPolicy(policy: SettingsPolicy): Promise<void> {
assertWritable('update settings policy');
this.policyCache = {
this.policyCache = ConfigManager.normalizePolicy({
...DEFAULT_POLICY,
...policy,
features: { ...DEFAULT_FEATURE_GATES, ...(policy.features || {}) },
themePolicy: { ...DEFAULT_THEME_POLICY, ...(policy.themePolicy || {}) },
};
});
await this.writeJsonFile('policy.json', this.policyCache as unknown as Record<string, unknown>);
}
/**
* Migrates deprecated feature gates forward. The standalone "All Mail" view
* (`allMailViewEnabled`) was folded into the unified "All mail" entry, so an
* admin who enabled it keeps that entry available via `crossAllViewEnabled`.
* Idempotent - safe to run on every load.
*/
private static normalizePolicy(policy: SettingsPolicy): SettingsPolicy {
if (policy.features.allMailViewEnabled) {
policy.features.crossAllViewEnabled = true;
}
return policy;
}
/**
* Reload config from disk (for manual file edits or multi-instance).
*/
+9 -1
View File
@@ -113,7 +113,15 @@ type HeadersLike = Headers | { get(name: string): string | null };
* host header is set.
*/
export function pickRequestHost(headersOrReq: NextRequest | HeadersLike): string | null {
const headers: HeadersLike = 'headers' in headersOrReq ? (headersOrReq as NextRequest).headers : headersOrReq;
// A Headers / ReadonlyHeaders exposes `.get` directly; a NextRequest carries
// its headers under `.headers`. Discriminate on the callable `.get` rather
// than the presence of a `headers` property, since ReadonlyHeaders (returned
// by `await headers()`) also has an internal `headers` field (#585).
const candidate = headersOrReq as { get?: unknown };
const headers: HeadersLike =
typeof candidate.get === 'function'
? (headersOrReq as HeadersLike)
: (headersOrReq as NextRequest).headers;
const raw = headers.get('x-forwarded-host') || headers.get('host');
if (!raw) return null;
const first = raw.split(',')[0]?.trim();
+60
View File
@@ -11,6 +11,7 @@ import {
import type { AdminConfigData, AdminStateData } from './types';
const MIGRATION_MARKER = '.migrated-v2';
const POLICY_UNIFIED_MARKER = '.migrated-unified-mailbox';
interface LegacyAdminData {
passwordHash: string;
@@ -59,6 +60,65 @@ export async function migrateLegacyAdminLayout(): Promise<void> {
}
}
/**
* One-shot policy migration for the Unified Mailbox rework. Before it, the
* cross views (crossUnread/crossStarred/crossAll) merged across every logged-in
* account, so an admin who had any of them enabled was already permitting
* cross-account aggregation. The new `unifiedCrossAccountEnabled` gate (default
* false) controls that capability, so enable it whenever a cross view was active
* - otherwise existing cross-account installs would silently lose the behaviour
* on upgrade (the per-user `unifiedCrossAccount` is AND-ed with this gate).
*
* Persisted + marker-guarded (not a per-load normalization) so a later admin
* decision to disable the gate survives restarts. Skipped on read-only config
* dirs - operators who locked their config must migrate manually (mirrors
* migrateLegacyAdminLayout). The deprecated `allMailViewEnabled` (a single-account
* view, never cross-account) deliberately does NOT trigger this.
*/
export async function migratePolicyUnifiedMailbox(): Promise<void> {
if (isConfigReadOnly()) return;
const markerPath = getConfigPath(POLICY_UNIFIED_MARKER);
if (existsSync(markerPath)) return;
try {
const policyPath = getConfigPath('policy.json');
if (existsSync(policyPath)) {
let parsed: Record<string, unknown> | null = null;
try {
parsed = JSON.parse(await readFile(policyPath, 'utf-8')) as Record<string, unknown>;
} catch {
logger.warn('policy.json is not valid JSON; skipping Unified Mailbox policy migration');
}
const features =
parsed && typeof parsed.features === 'object' && parsed.features
? (parsed.features as Record<string, unknown>)
: null;
if (features) {
const hadCrossAccount = !!(
features.crossUnreadViewEnabled ||
features.crossStarredViewEnabled ||
features.crossAllViewEnabled
);
if (hadCrossAccount && features.unifiedCrossAccountEnabled !== true) {
features.unifiedCrossAccountEnabled = true;
const tmp = policyPath + '.tmp';
await writeFile(tmp, JSON.stringify(parsed, null, 2), 'utf-8');
await rename(tmp, policyPath);
logger.info('Migrated policy: enabled unifiedCrossAccountEnabled (cross-account views were active)');
}
}
}
await ensureConfigDir();
await writeFile(markerPath, new Date().toISOString(), 'utf-8');
} catch (error) {
logger.warn('Unified Mailbox policy migration failed; will retry on next boot', {
error: error instanceof Error ? error.message : 'Unknown error',
});
}
}
/**
* If the existing admin.json carries timestamp fields (legacy mixed layout),
* split them into admin-state.json and rewrite admin.json without them.
+12
View File
@@ -60,10 +60,12 @@ export interface FeatureGates {
hoverActionsConfigEnabled: boolean;
filesEnabled: boolean;
contactsEnabled: boolean;
/** @deprecated Folded into `crossAllViewEnabled`; normalized forward on policy load. */
allMailViewEnabled: boolean;
crossUnreadViewEnabled: boolean;
crossStarredViewEnabled: boolean;
crossAllViewEnabled: boolean;
unifiedCrossAccountEnabled: boolean;
}
export const DEFAULT_FEATURE_GATES: FeatureGates = {
@@ -89,6 +91,7 @@ export const DEFAULT_FEATURE_GATES: FeatureGates = {
crossUnreadViewEnabled: false,
crossStarredViewEnabled: false,
crossAllViewEnabled: false,
unifiedCrossAccountEnabled: false,
};
export interface ThemePolicy {
@@ -166,6 +169,15 @@ export const CONFIG_ENV_MAP: Record<string, { envVar: string; fileEnvVar?: strin
loginImprintUrl: { envVar: 'LOGIN_IMPRINT_URL', type: 'url', defaultValue: '' },
loginPrivacyPolicyUrl: { envVar: 'LOGIN_PRIVACY_POLICY_URL', type: 'url', defaultValue: '' },
loginWebsiteUrl: { envVar: 'LOGIN_WEBSITE_URL', type: 'url', defaultValue: '' },
// Login header customization. The logo box is otherwise a fixed 64×64
// (w-16/h-16), which fits a wide wordmark to ~13px tall; set a max height
// and/or width (any CSS length, e.g. "230px" or "3rem") to size it. The
// heading ({appName}) and subtitle can be hidden when the logo already
// reads as the brand (e.g. a wordmark) and they'd be redundant.
loginLogoMaxHeight: { envVar: 'LOGIN_LOGO_MAX_HEIGHT', type: 'string', defaultValue: '' },
loginLogoMaxWidth: { envVar: 'LOGIN_LOGO_MAX_WIDTH', type: 'string', defaultValue: '' },
loginShowHeading: { envVar: 'LOGIN_SHOW_HEADING', type: 'boolean', defaultValue: true },
loginShowSubtitle: { envVar: 'LOGIN_SHOW_SUBTITLE', type: 'boolean', defaultValue: true },
// Hide the manual "I have a 2FA code" toggle on the login form. Deployments
// that delegate auth to an external directory (LDAP/OIDC) where 2FA lives in
// the IdP have no server-side TOTP, so the toggle only leads to a failed