Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,12 @@
# Changelog

## 0.3.0 - 2026-11-20

- `MAILVIEW_USERS` entries can be email addresses (`alice@example.com=alice`), matched case-insensitively and only
when the provider marks the address verified. No more looking up a provider's user id (with Google, only a refused
sign-in shows it). User ids work as before; with no email entries, only the `openid` scope is requested.
- The "sign-in refused" log line says why (not listed, no verified email, or no key) and never logs the email.

## 0.2.0 - 2026-11-14

First public release.
Expand Down
20 changes: 11 additions & 9 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,8 @@ mailview is an independent project, not part of Mail-Archiver.
key, so **Mail-Archiver decides what each person may see**, and its Access Log names the person. mailview adds no
access rules of its own beyond "who is signed in".
- Sign-in uses any **OpenID Connect** provider (Keycloak, Authentik, Authelia, Google, ...). An allowlist maps each
provider user id to a label, and each label to that person's API key. Anyone not on the list is turned away.
person's email address (only if the provider says it's verified) or provider user id to a label, and each label to
that person's API key. Anyone not on the list is turned away.
- Email HTML is shown in a sandboxed frame with a strict Content Security Policy: scripts never run. Pictures from
the internet are blocked until the reader asks for them, unless you set `REMOTE_IMAGES=allow`.
- Inline (`cid:`) images and the "Original" download are read from the stored original message, so these work best
Expand All @@ -39,19 +40,20 @@ Create a confidential client (client id + secret) with:

- Redirect URI: `https://<your mailview host>/auth/callback`
- Post-logout redirect URI: `https://<your mailview host>/`
- Scope: `openid` (nothing else is requested)
- Scope: `openid`, plus `email` when `MAILVIEW_USERS` lists email addresses (nothing else is requested)

### 2. One Mail-Archiver user and API key per person

For each person:

1. In Mail-Archiver, create a normal (non-admin) user and assign their mailbox(es) to it.
2. Sign in to Mail-Archiver as that user and create an API key (API keys are per user and self-service).
3. Find the person's user id at your OpenID Connect provider: the `sub` claim of their ID token (Keycloak: Users →
user → ID). If you don't know it, let them try to sign in: mailview logs
`sign-in refused: user <id> is not set up`.
4. Pick a label for them (lowercase letters, digits and `-`, e.g. `alice`), add `<id>=alice` to `MAILVIEW_USERS`
and set `MAILVIEW_KEY_ALICE` to their key. Restart mailview.
3. Pick a label for them (lowercase letters, digits and `-`, e.g. `alice`) and add them to `MAILVIEW_USERS`, either
by **email**, `alice@example.com=alice` (the address they sign in with; it must be marked verified by the
provider, as Google and most others do), or by **user id**, `<id>=alice` (the `sub` claim of their ID token, e.g.
Keycloak: Users → user → ID; if you don't know it, let them try to sign in: mailview logs
`sign-in refused: user <id> is not set up`).
4. Set `MAILVIEW_KEY_ALICE` to their key. Restart mailview.

### 3. Run it

Expand All @@ -66,7 +68,7 @@ services:
OIDC_ISSUER: https://auth.example.com/realms/home
OIDC_CLIENT_ID: mailview
MAILARCHIVER_API_URL: http://mailarchive-app:5000/api/v1
MAILVIEW_USERS: "3f2a1b4c-0000-4000-8000-000000000001=alice;3f2a1b4c-0000-4000-8000-000000000002=bob"
MAILVIEW_USERS: "alice@example.com=alice;3f2a1b4c-0000-4000-8000-000000000002=bob"
read_only: true
tmpfs:
- /tmp
Expand All @@ -87,7 +89,7 @@ services:
| `OIDC_CLIENT_ID` | yes | | |
| `OIDC_CLIENT_SECRET` | yes | | Keep it in an env file, not in the compose file |
| `MAILARCHIVER_API_URL` | yes | | Mail-Archiver's API base, e.g. `http://mailarchive-app:5000/api/v1` |
| `MAILVIEW_USERS` | yes | | `<provider user id>=<label>`, `;` between people. Ids are matched exactly (case-sensitive) |
| `MAILVIEW_USERS` | yes | | `<email or provider user id>=<label>`, `;` between people. An entry with `@` is an email: matched case-insensitively, and only when the provider marks it verified (`email_verified`). Otherwise it's the user id (`sub`), matched exactly (case-sensitive) |
| `MAILVIEW_KEY_<LABEL>` | one per label | | That person's Mail-Archiver API key. Label in upper case, `-` becomes `_`: `family-member-1` → `MAILVIEW_KEY_FAMILY_MEMBER_1`. A person without a key can't sign in; everyone else is unaffected |
| `APP_NAME` | | `Mail archive` | Name in the title bar and on the sign-in page |
| `APP_TAGLINE` | | `A searchable, read-only copy of your email.` | Line under the name on the sign-in page |
Expand Down
4 changes: 2 additions & 2 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion package.json
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
{
"name": "mailview",
"private": true,
"version": "0.2.0",
"version": "0.3.0",
"description": "A read-only web UI for Mail-Archiver: search, read and download archived email, one account per person.",
"license": "MIT",
"repository": {
Expand Down
32 changes: 26 additions & 6 deletions server/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ const LOGIN_TTL_MS = 10 * 60_000;

export interface Session {
sub: string;
/** Lowercased, and only if the provider marked it verified; null otherwise. */
email: string | null;
idToken: string | null;
expires: number;
}
Expand All @@ -28,6 +30,19 @@ interface PendingLogin {

export type AuthEnv = { Variables: { session: Session } };

/** The ID token's email, lowercased, only when `email_verified` is true (some providers send the string "true"). */
export function verifiedEmail(claims: Record<string, unknown> | undefined): string | null {
if (!claims) return null;
const verified = claims.email_verified === true || claims.email_verified === 'true';
const email = typeof claims.email === 'string' ? claims.email.trim().toLowerCase() : '';
return verified && email ? email : null;
}

/** The person's label from the user list: by user id first, then by verified email. */
export function labelOf(users: Config['users'], session: Pick<Session, 'sub' | 'email'>): string | null {
return users.bySub.get(session.sub) ?? (session.email ? users.byEmail.get(session.email) : undefined) ?? null;
}

function token(): string {
return randomBytes(32).toString('base64url');
}
Expand Down Expand Up @@ -73,14 +88,14 @@ export class Auth {

/** The person's label if they're set up (listed in MAILVIEW_USERS and have a key), else null. */
labelFor(session: Session): string | null {
const label = this.cfg.users.get(session.sub);
const label = labelOf(this.cfg.users, session);
return label && this.cfg.keys.has(label) ? label : null;
}

requireSession(): MiddlewareHandler<AuthEnv> {
return async (c, next) => {
if (this.cfg.demo) {
c.set('session', { sub: [...this.cfg.users.keys()][0], idToken: null, expires: Infinity });
c.set('session', { sub: [...this.cfg.users.bySub.keys()][0], email: null, idToken: null, expires: Infinity });
return next();
}
const id = getCookie(c, SESSION_COOKIE);
Expand Down Expand Up @@ -108,7 +123,8 @@ export class Auth {
this.cookie(c, LOGIN_COOKIE, key, LOGIN_TTL_MS / 1000);
const url = oidc.buildAuthorizationUrl(config, {
redirect_uri: `${this.cfg.publicUrl}/auth/callback`,
scope: 'openid',
// Email only when the list has email entries, so id-only setups still request nothing but `openid`.
scope: this.cfg.users.byEmail.size > 0 ? 'openid email' : 'openid',
code_challenge: await oidc.calculatePKCECodeChallenge(login.verifier),
code_challenge_method: 'S256',
state: login.state,
Expand Down Expand Up @@ -139,16 +155,20 @@ export class Auth {
console.warn(`sign-in failed: ${err instanceof Error ? err.name : 'error'}`);
return c.redirect('/?signin=failed');
}
const sub = String(tokens.claims()?.sub ?? '');
const claims = tokens.claims() as Record<string, unknown> | undefined;
const sub = String(claims?.sub ?? '');
const session: Session = {
sub,
email: verifiedEmail(claims),
idToken: tokens.id_token ?? null,
expires: Date.now() + SESSION_DAYS * 86_400_000,
};
const label = this.labelFor(session);
if (label === null) {
// The log line gives the admin the id to add to MAILVIEW_USERS.
console.warn(`sign-in refused: user ${sub} is not set up (MAILVIEW_USERS + key)`);
// The log line gives the admin the id to add to MAILVIEW_USERS (the email isn't logged).
const listed = labelOf(this.cfg.users, session);
const why = listed ? `"${listed}" has no key` : session.email ? 'not in MAILVIEW_USERS' : 'not in MAILVIEW_USERS, no verified email';
console.warn(`sign-in refused: user ${sub} is not set up (${why})`);
return c.redirect('/?signin=no-mailbox');
}
const id = token();
Expand Down
46 changes: 32 additions & 14 deletions server/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,39 +9,57 @@ export interface UiSettings {
remoteImages: 'allow' | 'ask';
}

export interface Users {
/** The ID token's `sub` (matched exactly) → label. */
bySub: Map<string, string>;
/** Lowercased email (matched only when the provider says it's verified) → label. */
byEmail: Map<string, string>;
}

export interface Config {
port: number;
demo: boolean;
publicUrl: string;
oidc: { issuer: string; clientId: string; clientSecret: string };
apiUrl: string;
/** The sign-in provider's user id (the ID token's `sub`) → that person's label, e.g. "alice". */
users: Map<string, string>;
/** Who may sign in, and their label (e.g. "alice"): by the provider's user id and/or by verified email. */
users: Users;
/** Label → that person's own Mail-Archiver API key (from MAILVIEW_KEY_<LABEL>). */
keys: Map<string, string>;
staticDir: string;
ui: UiSettings;
}

/**
* MAILVIEW_USERS, e.g. "3f2a…=alice;109876543210=bob": the sign-in provider's user id (`sub`, matched exactly) and a
* label, ";" between people. Each label needs a key in MAILVIEW_KEY_<LABEL> ("family-member-1" →
* MAILVIEW_KEY_FAMILY_MEMBER_1): an API key created for that person's own Mail-Archiver user, so Mail-Archiver
* decides what they may see and its access log names them.
* MAILVIEW_USERS, e.g. "alice@example.com=alice;3f2a…=bob": who may sign in and their label, ";" between people.
* Each entry is either an email address (contains "@"; matched case-insensitively, and only if the provider marks it
* verified) or the provider's user id (`sub`, matched exactly). Each label needs a key in MAILVIEW_KEY_<LABEL>
* ("family-member-1" → MAILVIEW_KEY_FAMILY_MEMBER_1): an API key created for that person's own Mail-Archiver user,
* so Mail-Archiver decides what they may see and its access log names them.
*/
export function parseUsers(value: string): Map<string, string> {
const map = new Map<string, string>();
export function parseUsers(value: string): Users {
const users: Users = { bySub: new Map(), byEmail: new Map() };
for (const entry of value.split(';').map((s) => s.trim()).filter(Boolean)) {
const eq = entry.lastIndexOf('=');
if (eq <= 0) throw new Error('MAILVIEW_USERS: entry without "="');
const sub = entry.slice(0, eq).trim();
const who = entry.slice(0, eq).trim();
const label = entry.slice(eq + 1).trim();
// OIDC allows any ASCII string up to 255 characters; whitespace and ";" can't be written in this list anyway.
if (!/^[\x21-\x7e]{1,255}$/.test(sub)) throw new Error('MAILVIEW_USERS: user id must be 1-255 visible ASCII characters');
if (!/^[\x21-\x7e]{1,255}$/.test(who)) throw new Error('MAILVIEW_USERS: user id or email must be 1-255 visible ASCII characters');
if (!/^[a-z0-9][a-z0-9-]{0,40}$/.test(label)) throw new Error('MAILVIEW_USERS: labels are lowercase a-z, 0-9 and "-"');
map.set(sub, label);
if (who.includes('@')) {
if (!/^[^@]+@[^@]+\.[^@]+$/.test(who)) throw new Error('MAILVIEW_USERS: not an email address');
users.byEmail.set(who.toLowerCase(), label);
} else {
users.bySub.set(who, label);
}
}
return map;
return users;
}

/** All labels in the list, each once. */
export function labels(users: Users): Set<string> {
return new Set([...users.bySub.values(), ...users.byEmail.values()]);
}

export function keyVariable(label: string): string {
Expand Down Expand Up @@ -83,7 +101,7 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env, argv: string[]
publicUrl: env.PUBLIC_URL ?? `http://localhost:${port}`,
oidc: { issuer: '', clientId: '', clientSecret: '' },
apiUrl: '',
users: new Map([['00000000-0000-0000-0000-000000000000', 'demo']]),
users: { bySub: new Map([['00000000-0000-0000-0000-000000000000', 'demo']]), byEmail: new Map() },
keys: new Map([['demo', 'demo']]),
staticDir,
ui,
Expand All @@ -93,7 +111,7 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env, argv: string[]
if (!publicUrl.startsWith('https://')) throw new Error('PUBLIC_URL must be https');
const users = parseUsers(required(env, 'MAILVIEW_USERS'));
const keys = new Map<string, string>();
for (const label of new Set(users.values())) {
for (const label of labels(users)) {
const key = env[keyVariable(label)]?.trim();
// A person without a key yet can't sign in, but doesn't stop everyone else.
if (key && !key.startsWith('change-me')) keys.set(label, key);
Expand Down
39 changes: 29 additions & 10 deletions server/security.test.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import assert from 'node:assert/strict';
import { test } from 'node:test';
import { safeReturnPath } from './auth.ts';
import { keyVariable, loadConfig, loadUiSettings, parseUsers } from './config.ts';
import { labelOf, safeReturnPath, verifiedEmail } from './auth.ts';
import { keyVariable, labels, loadConfig, loadUiSettings, parseUsers } from './config.ts';
import { attachmentHeaders, previewType } from './files.ts';
import { bodyCsp, emailDocument, hasRemoteContent, referencedCids } from './html.ts';
import { parseOriginal } from './mime.ts';
Expand Down Expand Up @@ -74,19 +74,38 @@ test('return paths stay on this site', () => {
assert.equal(safeReturnPath(undefined), '/');
});

test('MAILVIEW_USERS parsing: any provider\'s user id, matched exactly', () => {
const m = parseUsers(' 3f2a1b4c-0000-4000-8000-000000000001=alice ; 109876543210987654321=family-member-1 ; Ab=Cd=x=bob ');
assert.equal(m.get('3f2a1b4c-0000-4000-8000-000000000001'), 'alice');
assert.equal(m.get('109876543210987654321'), 'family-member-1');
assert.equal(m.get('Ab=Cd=x'), 'bob', 'the label is after the last "="');
assert.equal(m.has('ab=cd=x'), false, 'ids are case-sensitive');
test('MAILVIEW_USERS parsing: provider user ids matched exactly, emails case-insensitively', () => {
const u = parseUsers(' 3f2a1b4c-0000-4000-8000-000000000001=alice ; 109876543210987654321=family-member-1 ; Ab=Cd=x=bob ; Carol@Example.COM=carol ');
assert.equal(u.bySub.get('3f2a1b4c-0000-4000-8000-000000000001'), 'alice');
assert.equal(u.bySub.get('109876543210987654321'), 'family-member-1');
assert.equal(u.bySub.get('Ab=Cd=x'), 'bob', 'the label is after the last "="');
assert.equal(u.bySub.has('ab=cd=x'), false, 'ids are case-sensitive');
assert.equal(u.byEmail.get('carol@example.com'), 'carol', 'emails are stored lowercased');
assert.equal(u.bySub.has('Carol@Example.COM'), false, 'an email is never treated as an id');
assert.deepEqual([...labels(u)].sort(), ['alice', 'bob', 'carol', 'family-member-1']);
assert.throws(() => parseUsers('3f2a1b4c-0000-4000-8000-000000000001=Real Name'));
assert.throws(() => parseUsers('=alice'));
assert.throws(() => parseUsers('caf\u00e9=alice'), 'non-ASCII id');
assert.throws(() => parseUsers('café=alice'), 'non-ASCII id');
assert.throws(() => parseUsers(`${'x'.repeat(256)}=alice`), 'id longer than 255');
assert.throws(() => parseUsers('carol@=carol'), 'not an email');
assert.throws(() => parseUsers('a@b@c.com=carol'), 'not an email');
assert.equal(keyVariable('family-member-1'), 'MAILVIEW_KEY_FAMILY_MEMBER_1');
});

test('sign-in matching: id first, then only a verified email', () => {
const u = parseUsers('109876543210987654321=alice;carol@example.com=carol');
assert.equal(labelOf(u, { sub: '109876543210987654321', email: null }), 'alice');
assert.equal(labelOf(u, { sub: 'other', email: 'carol@example.com' }), 'carol');
assert.equal(labelOf(u, { sub: 'other', email: null }), null);
assert.equal(labelOf(u, { sub: 'other', email: 'mallory@example.com' }), null);
assert.equal(verifiedEmail({ email: ' Carol@Example.com ', email_verified: true }), 'carol@example.com');
assert.equal(verifiedEmail({ email: 'carol@example.com', email_verified: 'true' }), 'carol@example.com');
assert.equal(verifiedEmail({ email: 'carol@example.com', email_verified: false }), null, 'unverified email never matches');
assert.equal(verifiedEmail({ email: 'carol@example.com' }), null, 'missing email_verified counts as unverified');
assert.equal(verifiedEmail({ email_verified: true }), null);
assert.equal(verifiedEmail(undefined), null);
});

test('UI settings: defaults, choices checked', () => {
const d = loadUiSettings({});
assert.equal(d.appName, 'Mail archive');
Expand Down Expand Up @@ -117,7 +136,7 @@ test('each person gets only their own key; a person without a key is left out',
OIDC_CLIENT_ID: 'mailview',
OIDC_CLIENT_SECRET: 's',
MAILARCHIVER_API_URL: 'http://api',
MAILVIEW_USERS: '3f2a1b4c-0000-4000-8000-000000000001=alice;3f2a1b4c-0000-4000-8000-000000000002=family-member-1',
MAILVIEW_USERS: '3f2a1b4c-0000-4000-8000-000000000001=alice;member1@example.com=family-member-1',
MAILVIEW_KEY_ALICE: 'ma_alice',
MAILVIEW_KEY_FAMILY_MEMBER_1: 'change-me',
};
Expand Down