Skip to content

Build your personal knowledge base with Trilium Notes

feat(oauth): enforce enrolled identity and add TOTP-style SSO enrollment

Elian Doranb7812d3f7967
diff --git a/apps/client/src/translations/en/translation.json b/apps/client/src/translations/en/translation.json
index 121fe42922..b6271a60e2 100644
--- a/apps/client/src/translations/en/translation.json
+++ b/apps/client/src/translations/en/translation.json
@@ -1749,7 +1749,16 @@
"oauth_server_env_hint": "Or set the following environment variables:",
"oauth_user_account": "Account name",
"oauth_user_email": "Email address",
- "oauth_user_not_logged_in": "Not logged in!"
+ "oauth_user_not_logged_in": "Not logged in!",
+ "oauth_not_enrolled_hint": "OpenID Connect is configured but no account is connected yet. Connect your account to make it the active sign-in method — until then, you'll keep signing in with your password.",
+ "oauth_connect_label": "Connect account",
+ "oauth_connect_description": "Sign in with your provider once to bind your account. Only this account will be able to sign in afterwards.",
+ "oauth_connect_button": "Connect account",
+ "oauth_disconnect_label": "Disconnect account",
+ "oauth_disconnect_description": "Unbind the connected account. Sign-in will fall back to your password until you connect an account again.",
+ "oauth_disconnect_button": "Disconnect",
+ "oauth_disconnect_confirm": "Are you sure you want to disconnect this account? Sign-in will fall back to your password until you connect an account again.",
+ "oauth_disconnected": "Account disconnected."
},
"shortcuts": {
"keyboard_shortcuts": "Keyboard Shortcuts",
diff --git a/apps/client/src/widgets/type_widgets/options/password.tsx b/apps/client/src/widgets/type_widgets/options/password.tsx
index 040c02fe30..aee5be6c2f 100644
--- a/apps/client/src/widgets/type_widgets/options/password.tsx
+++ b/apps/client/src/widgets/type_widgets/options/password.tsx
@@ -196,10 +196,14 @@ function SignInMethod() {
server.get<TOTPStatus>("totp/status").then(setTotpStatus);
}, []);
+ const refreshOauthStatus = useCallback(() => {
+ server.get<OAuthStatus>("oauth/status").then(setOauthStatus);
+ }, []);
+
useEffect(() => {
refreshTotpStatus();
- server.get<OAuthStatus>("oauth/status").then(setOauthStatus);
- }, [ refreshTotpStatus ]);
+ refreshOauthStatus();
+ }, [ refreshTotpStatus, refreshOauthStatus ]);
const usingOAuth = mfaMethod === "oauth";
@@ -226,21 +230,42 @@ function SignInMethod() {
</OptionsSection>
{ usingOAuth
- ? <OAuthStatusCard status={oauthStatus} />
+ ? <OAuthStatusCard status={oauthStatus} refreshStatus={refreshOauthStatus} />
: <TotpSettings totpStatus={totpStatus} refreshTotpStatus={refreshTotpStatus} /> }
</>
);
}
/**
- * Read-only OAuth status card, shown when OAuth is the selected sign-in method. OAuth is configured
- * entirely server-side (env vars / config.ini), so this card offers no controls — it just reflects
- * whether OAuth is available and, once signed in, the connected account.
+ * OAuth status card, shown when OAuth is the selected sign-in method. The provider credentials are
+ * configured server-side (env vars / config.ini), but binding an account is an explicit in-app step —
+ * mirroring TOTP's verify-before-enable. Three states:
+ * - **not configured** → show the config hint (the server vars are missing);
+ * - **configured, not enrolled** → offer "Connect account", which runs the provider round-trip and
+ * binds the returned identity. SSO only becomes the live login method once this completes;
+ * - **enrolled** → show the connected account and a "Disconnect" action.
*/
-function OAuthStatusCard({ status }: { status?: OAuthStatus }) {
+function OAuthStatusCard({ status, refreshStatus }: { status?: OAuthStatus, refreshStatus: () => void }) {
// "Configured" is purely about the server-side variables being present (the server's `enabled` flag
// additionally requires mfaMethod === 'oauth', which is implied here since this card only renders then).
const configured = (status?.missingVars?.length ?? 1) === 0;
+ const enrolled = status?.enrolled ?? false;
+
+ // Enrollment is a full-page provider round-trip (not an XHR): navigate to the OIDC login route,
+ // which on return binds the identity to this still-authenticated session (see open_id afterCallback).
+ const connectAccount = useCallback(() => {
+ window.location.href = "authenticate";
+ }, []);
+
+ const disconnectAccount = useCallback(async () => {
+ if (!await dialog.confirm(t("multi_factor_authentication.oauth_disconnect_confirm"))) {
+ return;
+ }
+
+ await server.post("oauth/disconnect");
+ toast.showMessage(t("multi_factor_authentication.oauth_disconnected"));
+ refreshStatus();
+ }, [ refreshStatus ]);
return (
<OptionsSection
@@ -258,16 +283,7 @@ function OAuthStatusCard({ status }: { status?: OAuthStatus }) {
</span>
}
>
- { configured ? (
- <>
- <OptionsRow name="oauth-user-account" label={t("multi_factor_authentication.oauth_user_account")}>
- <span>{status?.name ?? t("multi_factor_authentication.oauth_user_not_logged_in")}</span>
- </OptionsRow>
- <OptionsRow name="oauth-user-email" label={t("multi_factor_authentication.oauth_user_email")}>
- <span>{status?.email ?? t("multi_factor_authentication.oauth_user_not_logged_in")}</span>
- </OptionsRow>
- </>
- ) : (
+ { !configured ? (
<>
<p>{t("multi_factor_authentication.oauth_not_configured_hint")}</p>
@@ -281,6 +297,36 @@ function OAuthStatusCard({ status }: { status?: OAuthStatus }) {
<OAuthConfigHint />
</>
+ ) : enrolled ? (
+ <>
+ <OptionsRow name="oauth-user-account" label={t("multi_factor_authentication.oauth_user_account")}>
+ <span>{status?.name ?? t("multi_factor_authentication.oauth_user_not_logged_in")}</span>
+ </OptionsRow>
+ <OptionsRow name="oauth-user-email" label={t("multi_factor_authentication.oauth_user_email")}>
+ <span>{status?.email ?? t("multi_factor_authentication.oauth_user_not_logged_in")}</span>
+ </OptionsRow>
+
+ <OptionsRowWithButton
+ label={t("multi_factor_authentication.oauth_disconnect_label")}
+ description={t("multi_factor_authentication.oauth_disconnect_description")}
+ icon="bx-trash"
+ buttonClassName="oauth-disconnect-button"
+ buttonText={t("multi_factor_authentication.oauth_disconnect_button")}
+ onClick={() => void disconnectAccount()}
+ />
+ </>
+ ) : (
+ <>
+ <Admonition type="note">{t("multi_factor_authentication.oauth_not_enrolled_hint")}</Admonition>
+
+ <OptionsRowWithButton
+ label={t("multi_factor_authentication.oauth_connect_label")}
+ description={t("multi_factor_authentication.oauth_connect_description")}
+ icon="bx-log-in"
+ buttonText={t("multi_factor_authentication.oauth_connect_button")}
+ onClick={connectAccount}
+ />
+ </>
)}
</OptionsSection>
);
diff --git a/apps/server/src/app.ts b/apps/server/src/app.ts
index ab8cfcba7c..73840f0197 100644
--- a/apps/server/src/app.ts
+++ b/apps/server/src/app.ts
@@ -111,7 +111,9 @@ export default async function buildApp() {
startSessionCleanup();
app.use(favicon(path.join(assetsDir, isDev ? "icon-dev.ico" : "icon.ico")));
- if (openID.isOpenIDEnabled())
+ // Mount the OIDC middleware whenever OAuth is configured — not only once an account is enrolled —
+ // so the provider round-trip is available for the owner's first (enrollment) sign-in too.
+ if (openID.isOpenIDConfigured())
app.use(auth(openID.generateOAuthConfig()));
await assets.register(app);
diff --git a/apps/server/src/routes/routes.ts b/apps/server/src/routes/routes.ts
index 02d2143bff..93d794db23 100644
--- a/apps/server/src/routes/routes.ts
+++ b/apps/server/src/routes/routes.ts
@@ -74,6 +74,7 @@ function register(app: express.Application) {
apiRoute(GET, '/api/oauth/status', openID.getOAuthStatus);
asyncApiRoute(GET, '/api/oauth/validate', openID.isTokenValid);
+ apiRoute(PST, '/api/oauth/disconnect', openID.clearSavedUser);
apiRoute(PST, '/api/totp_recovery/verify', recoveryCodes.verifyRecoveryCode);
apiRoute(PST, '/api/totp_recovery/regenerate', recoveryCodes.regenerateRecoveryCodes);
diff --git a/apps/server/src/services/encryption/open_id_encryption.spec.ts b/apps/server/src/services/encryption/open_id_encryption.spec.ts
index 4c7e58d00b..49ead05fdd 100644
--- a/apps/server/src/services/encryption/open_id_encryption.spec.ts
+++ b/apps/server/src/services/encryption/open_id_encryption.spec.ts
@@ -36,6 +36,18 @@ describe("open_id_encryption", () => {
expect(openIDEncryption.saveUser("other", "Bob", "[email protected]")).toBe(false);
});
+ it("verifySubjectIdentifier matches only the enrolled subject identifier", () => {
+ // No account enrolled yet → nothing matches.
+ expect(openIDEncryption.verifySubjectIdentifier("subject-123")).toBe(false);
+
+ openIDEncryption.saveUser("subject-123", "Alice", "[email protected]");
+
+ expect(openIDEncryption.verifySubjectIdentifier("subject-123")).toBe(true);
+ expect(openIDEncryption.verifySubjectIdentifier("someone-else")).toBe(false);
+ // A prefix of the real identifier must not pass (length-safe comparison).
+ expect(openIDEncryption.verifySubjectIdentifier("subject-12")).toBe(false);
+ });
+
it("setDataKey encrypts the data key so it can be recovered with the derived key", () => {
const salt = "fixed-salt";
const plainKey = "0123456789abcdef";
diff --git a/apps/server/src/services/encryption/open_id_encryption.ts b/apps/server/src/services/encryption/open_id_encryption.ts
index d56ed87f25..7a48026c8d 100644
--- a/apps/server/src/services/encryption/open_id_encryption.ts
+++ b/apps/server/src/services/encryption/open_id_encryption.ts
@@ -1,4 +1,5 @@
import { data_encryption } from "@triliumnext/core";
+import crypto from "crypto";
import sql from "../sql.js";
import utils from "../utils.js";
@@ -42,6 +43,39 @@ function isSubjectIdentifierSaved() {
return true;
}
+/**
+ * Checks whether an OAuth subject identifier matches the one bound to this instance during
+ * enrollment. Used at login to enforce that only the enrolled account may sign in — without it, any
+ * identity the IdP authenticates would be granted access. The plaintext `sub` is never stored; we
+ * recompute its scrypt verification hash against the saved salt and compare it (in constant time) to
+ * the stored hash, mirroring how passwords are verified.
+ */
+function verifySubjectIdentifier(subjectIdentifier: string): boolean {
+ const row = sql.getRowOrNull<{ userIDVerificationHash: string; salt: string }>(
+ "SELECT userIDVerificationHash, salt FROM user_data;"
+ );
+
+ if (!row || !row.userIDVerificationHash || !row.salt) {
+ return false;
+ }
+
+ const computedHash = utils.toBase64(
+ myScryptService.getSubjectIdentifierVerificationHash(subjectIdentifier, row.salt)
+ );
+
+ return constantTimeEquals(computedHash, row.userIDVerificationHash);
+}
+
+/** Length-safe, constant-time string comparison so the match check can't be timing-probed. */
+function constantTimeEquals(a: string, b: string): boolean {
+ const aBuffer = Buffer.from(a);
+ const bBuffer = Buffer.from(b);
+ if (aBuffer.length !== bBuffer.length) {
+ return false;
+ }
+ return crypto.timingSafeEqual(aBuffer, bBuffer);
+}
+
function isUserSaved() {
const isSaved = sql.getValue<string>("SELECT isSetup FROM user_data;");
return isSaved === "true";
@@ -62,4 +96,5 @@ export default {
setDataKey,
saveUser,
isSubjectIdentifierSaved,
+ verifySubjectIdentifier,
};
diff --git a/apps/server/src/services/open_id.spec.ts b/apps/server/src/services/open_id.spec.ts
index 34440b9068..3e25ce6e5b 100644
--- a/apps/server/src/services/open_id.spec.ts
+++ b/apps/server/src/services/open_id.spec.ts
@@ -42,16 +42,31 @@ describe("open_id", () => {
expect(status.enabled).toBe(false);
});
- it("isOpenIDEnabled requires full config and mfaMethod=oauth", () => {
+ it("isOpenIDConfigured requires full config and mfaMethod=oauth", () => {
setOauthConfig(true);
cls.init(() => options.setOption("mfaMethod", "totp"));
- expect(openID.isOpenIDEnabled()).toBe(false); // method not oauth
+ expect(openID.isOpenIDConfigured()).toBe(false); // method not oauth
cls.init(() => options.setOption("mfaMethod", "oauth"));
- expect(openID.isOpenIDEnabled()).toBe(true);
+ expect(openID.isOpenIDConfigured()).toBe(true);
expect(openID.getOAuthStatus().missingVars).toEqual([]);
});
+ it("isOpenIDEnabled additionally requires an enrolled account", () => {
+ setOauthConfig(true);
+ cls.init(() => options.setOption("mfaMethod", "oauth"));
+
+ // Configured but not enrolled → SSO is not yet the active login method.
+ vi.spyOn(openIDEncryption, "isSubjectIdentifierSaved").mockReturnValue(false);
+ expect(openID.isOpenIDEnabled()).toBe(false);
+ expect(openID.getOAuthStatus().enrolled).toBe(false);
+
+ // Once an identity is bound, OAuth becomes active.
+ vi.spyOn(openIDEncryption, "isSubjectIdentifierSaved").mockReturnValue(true);
+ expect(openID.isOpenIDEnabled()).toBe(true);
+ expect(openID.getOAuthStatus().enrolled).toBe(true);
+ });
+
it("exposes issuer name/icon from config", () => {
setOauthConfig(true);
expect(openID.getSSOIssuerName()).toBe("Acme");
@@ -147,22 +162,20 @@ describe("open_id", () => {
it("returns the session unchanged when there is no user", async () => {
const cfg = buildConfig();
- const logSpy = vi.spyOn(console, "log").mockImplementation(() => {});
const session = { marker: 2 } as never;
const result = await cfg.afterCallback({ oidc: { user: undefined } } as never, {} as never, session);
expect(result).toBe(session);
- logSpy.mockRestore();
});
- it("saves the user and sets the session login flags", async () => {
- cls.init(() => {
- sql.transactional(() => sql.execute("DELETE FROM user_data"));
- });
+ it("enrolls the user when an authenticated owner signs in and none is enrolled yet", async () => {
const cfg = buildConfig();
+ // No account enrolled yet, and the request comes from an already-logged-in session (the owner
+ // enrolling from Settings) → bind the identity and keep them logged in.
+ vi.spyOn(openIDEncryption, "isSubjectIdentifierSaved").mockReturnValue(false);
const saveSpy = vi.spyOn(openIDEncryption, "saveUser").mockReturnValue(true);
const req = {
oidc: { user: { sub: "sub-1", name: "Alice", email: "[email protected]" } },
- session: {} as Record<string, unknown>
+ session: { loggedIn: true } as Record<string, unknown>
} as never;
const session = { marker: 3 } as never;
@@ -172,5 +185,56 @@ describe("open_id", () => {
expect((req as { session: { loggedIn: boolean } }).session.loggedIn).toBe(true);
expect(result).toBe(session);
});
+
+ it("refuses enrollment from an unauthenticated session (no first-login claim)", async () => {
+ const cfg = buildConfig();
+ vi.spyOn(openIDEncryption, "isSubjectIdentifierSaved").mockReturnValue(false);
+ const saveSpy = vi.spyOn(openIDEncryption, "saveUser").mockReturnValue(true);
+ const req = {
+ oidc: { user: { sub: "stranger", name: "Mallory", email: "[email protected]" } },
+ session: {} as Record<string, unknown>
+ } as never;
+ const session = { marker: 4 } as never;
+
+ const result = await cfg.afterCallback(req, {} as never, session);
+
+ expect(saveSpy).not.toHaveBeenCalled();
+ expect((req as { session: { loggedIn?: boolean } }).session.loggedIn).toBeFalsy();
+ expect(result).toBe(session);
+ });
+
+ it("logs in an enrolled user only when the subject identifier matches", async () => {
+ const cfg = buildConfig();
+ vi.spyOn(openIDEncryption, "isSubjectIdentifierSaved").mockReturnValue(true);
+ const verifySpy = vi.spyOn(openIDEncryption, "verifySubjectIdentifier").mockReturnValue(true);
+ const req = {
+ oidc: { user: { sub: "enrolled-sub", name: "Alice", email: "[email protected]" } },
+ session: {} as Record<string, unknown>
+ } as never;
+ const session = { marker: 5 } as never;
+
+ const result = await cfg.afterCallback(req, {} as never, session);
+
+ expect(verifySpy).toHaveBeenCalledWith("enrolled-sub");
+ expect((req as { session: { loggedIn: boolean } }).session.loggedIn).toBe(true);
+ expect((req as { session: { lastAuthState: { ssoEnabled: boolean } } }).session.lastAuthState.ssoEnabled).toBe(true);
+ expect(result).toBe(session);
+ });
+
+ it("rejects login when the authenticated account is not the enrolled one", async () => {
+ const cfg = buildConfig();
+ vi.spyOn(openIDEncryption, "isSubjectIdentifierSaved").mockReturnValue(true);
+ vi.spyOn(openIDEncryption, "verifySubjectIdentifier").mockReturnValue(false);
+ const req = {
+ oidc: { user: { sub: "other-sub", name: "Mallory", email: "[email protected]" } },
+ session: {} as Record<string, unknown>
+ } as never;
+ const session = { marker: 6 } as never;
+
+ const result = await cfg.afterCallback(req, {} as never, session);
+
+ expect((req as { session: { loggedIn: boolean } }).session.loggedIn).toBe(false);
+ expect(result).toBe(session);
+ });
});
});
diff --git a/apps/server/src/services/open_id.ts b/apps/server/src/services/open_id.ts
index 142cdc497f..1f4a2c3cb4 100644
--- a/apps/server/src/services/open_id.ts
+++ b/apps/server/src/services/open_id.ts
@@ -1,4 +1,4 @@
-import { options } from "@triliumnext/core";
+import { getLog, options } from "@triliumnext/core";
import type { NextFunction, Request, Response } from "express";
import type { Session } from "express-openid-connect";
@@ -21,10 +21,26 @@ function checkOpenIDConfig() {
return missingVars;
}
-function isOpenIDEnabled() {
+/**
+ * Whether OAuth is configured and selected as the sign-in method. This is what gates the OIDC
+ * middleware (so the provider round-trip — and therefore enrollment — is available) and is
+ * deliberately independent of whether an account has been enrolled yet. Before enrollment the login
+ * page still falls back to the password form, letting the owner sign in and enroll without a lockout.
+ */
+function isOpenIDConfigured() {
return !(checkOpenIDConfig().length > 0) && options.getOptionOrNull('mfaMethod') === 'oauth';
}
+/**
+ * Whether OAuth is the *active* login method. Beyond being configured, this additionally requires an
+ * enrolled account: until the owner has bound their provider identity (see {@link generateOAuthConfig}'s
+ * `afterCallback`), SSO is not yet live and the login page keeps offering the password form. Mirrors
+ * TOTP, where selecting the method isn't enough — a secret must be committed before it's enforced.
+ */
+function isOpenIDEnabled() {
+ return isOpenIDConfigured() && openIDEncryption.isSubjectIdentifierSaved();
+}
+
function isUserSaved() {
const data = sql.getValue<string>("SELECT isSetup FROM user_data;");
return data === "true";
@@ -55,6 +71,7 @@ function getOAuthStatus() {
name: getUsername(),
email: getUserEmail(),
enabled: isOpenIDEnabled(),
+ enrolled: openIDEncryption.isSubjectIdentifierSaved(),
missingVars: checkOpenIDConfig()
};
}
@@ -126,16 +143,38 @@ function generateOAuthConfig() {
afterCallback: async (req: Request, res: Response, session: Session) => {
if (!sqlInit.isDbInitialized()) return session;
- if (!req.oidc.user) {
- console.log("user invalid!");
+ const user = req.oidc.user;
+ if (!user || user.sub === undefined || user.sub === null) {
+ getLog().info("OAuth callback received without a usable user; ignoring.");
return session;
}
- openIDEncryption.saveUser(
- req.oidc.user.sub.toString(),
- req.oidc.user.name.toString(),
- req.oidc.user.email.toString()
- );
+ const incomingSubject = user.sub.toString();
+
+ if (openIDEncryption.isSubjectIdentifierSaved()) {
+ // An account is already enrolled, so this is a login attempt. Only the enrolled identity
+ // may proceed — otherwise any user the IdP authenticates could sign in to this instance.
+ if (!openIDEncryption.verifySubjectIdentifier(incomingSubject)) {
+ getLog().info("OAuth login rejected: the authenticated account is not the enrolled one.");
+ req.session.loggedIn = false;
+ return session;
+ }
+ } else {
+ // No account is enrolled yet. Binding the identity is only allowed when the request comes
+ // from an already-authenticated session — i.e. the owner enrolling from Settings. A
+ // sign-in from an anonymous session is refused so a stranger can't claim the instance by
+ // simply being the first to authenticate.
+ if (!req.session.loggedIn) {
+ getLog().info("OAuth enrollment rejected: sign-in attempted before an account was enrolled.");
+ return session;
+ }
+
+ openIDEncryption.saveUser(
+ incomingSubject,
+ user.name?.toString() ?? "",
+ user.email?.toString() ?? ""
+ );
+ }
req.session.loggedIn = true;
req.session.lastAuthState = {
@@ -154,6 +193,7 @@ export default {
getOAuthStatus,
getSSOIssuerName,
getSSOIssuerIcon,
+ isOpenIDConfigured,
isOpenIDEnabled,
clearSavedUser,
isTokenValid,
diff --git a/packages/commons/src/lib/server_api.ts b/packages/commons/src/lib/server_api.ts
index 1420d534ed..a9b9583b6a 100644
--- a/packages/commons/src/lib/server_api.ts
+++ b/packages/commons/src/lib/server_api.ts
@@ -164,7 +164,10 @@ export interface TOTPRecoveryKeysResponse {
}
export interface OAuthStatus {
+ /** Whether OAuth is the active login method (configured *and* an account has been enrolled). */
enabled: boolean;
+ /** Whether the owner has bound their provider identity to this instance (enrollment complete). */
+ enrolled?: boolean;
name?: string;
email?: string;
missingVars?: string[];