commit dd613614f3fc7b8cc11cc64658d1a1c117526b3b
parent f12f72504318e6a7ebd3ce0571ec7b900a3fa698
Author: finwo <finwo@pm.me>
Date: Thu, 22 Oct 2026 17:31:49 +0200
Added client consent flow and client-host revocation
Diffstat:
25 files changed, 1576 insertions(+), 46 deletions(-)
diff --git a/app/account/package-lock.json b/app/account/package-lock.json
@@ -6,6 +6,7 @@
"": {
"name": "auth-account",
"dependencies": {
+ "lucide": "^1.61.0",
"mithril": "^2.3.8"
},
"devDependencies": {
@@ -496,6 +497,12 @@
"@esbuild/win32-x64": "0.28.2"
}
},
+ "node_modules/lucide": {
+ "version": "1.61.0",
+ "resolved": "https://registry.npmjs.org/lucide/-/lucide-1.61.0.tgz",
+ "integrity": "sha512-RPNMBgej6WjPKuCNEODg83CF8lnraCeDOsZ3HZ7KvUYf0O5hdJBzer/Ax/meBHl3xvrp5NmKX0IDA5myyzlvGw==",
+ "license": "ISC"
+ },
"node_modules/mithril": {
"version": "2.3.8",
"resolved": "https://registry.npmjs.org/mithril/-/mithril-2.3.8.tgz",
diff --git a/app/account/package.json b/app/account/package.json
@@ -6,6 +6,7 @@
"build": "node esbuild.cjs"
},
"dependencies": {
+ "lucide": "^1.61.0",
"mithril": "^2.3.8"
},
"devDependencies": {
diff --git a/app/account/src/assets/account.css b/app/account/src/assets/account.css
@@ -173,6 +173,49 @@ body {
font-size: 0.875rem;
}
+.account-notice {
+ margin: 0 0 1.5rem;
+ padding: 0.75rem 1rem;
+ border: 1pt solid var(--account-border);
+ border-left: 3pt solid var(--account-accent);
+ background: var(--account-surface);
+ font-size: 0.875rem;
+ line-height: 1.5;
+}
+
+.account-card-note {
+ margin-top: 1rem;
+}
+
+.account-actions {
+ display: flex;
+ flex-wrap: wrap;
+ align-items: center;
+ gap: 1rem;
+ margin-top: 1.5rem;
+}
+
+.account-danger {
+ padding: 0.5rem 0.75rem;
+ border: 1pt solid var(--account-danger);
+ border-radius: 0;
+ background: transparent;
+ color: var(--account-danger);
+ font: inherit;
+ font-size: 0.875rem;
+ cursor: pointer;
+}
+
+.account-danger:hover:not(:disabled) {
+ background: var(--account-danger);
+ color: var(--account-surface);
+}
+
+.account-danger:disabled {
+ opacity: 0.5;
+ cursor: default;
+}
+
.account-status-page {
display: grid;
place-items: center;
diff --git a/app/account/src/screen/account.tsx b/app/account/src/screen/account.tsx
@@ -1,8 +1,12 @@
import m from 'mithril';
import {
appUrl,
+ getClientConsent,
getClientSession,
getDiscovery,
+ getFullAccountUrl,
+ revokeClientConsent,
+ type ClientConsentInfo,
type SessionInfo,
type UserInfo,
} from '../util/api';
@@ -37,8 +41,12 @@ export const Account: m.Component = {
mode: null as Mode | null,
user: null as UserInfo | null,
session: null as SessionInfo | null,
+ consent: null as ClientConsentInfo | null,
+ fullAccountUrl: null as string | null,
+ notice: null as string | null,
error: null as Error | null,
pending: false,
+ revokePending: false,
oninit(this: any) {
this.load();
@@ -50,6 +58,11 @@ export const Account: m.Component = {
if (!discovery) {
this.mode = 'client';
this.session = await getClientSession();
+ const clientId = this.session.scope.client_id;
+ if (clientId) {
+ this.consent = await getClientConsent(clientId);
+ }
+ this.fullAccountUrl = this.consent?.account_url || (await getFullAccountUrl());
document.title = 'Account';
} else if (!getAccountTokens()) {
await startAccountLogin();
@@ -97,6 +110,22 @@ export const Account: m.Component = {
await accountSignOut();
},
+ async revokeConsent(this: any) {
+ const clientId = this.session?.scope.client_id;
+ if (!clientId) return;
+ this.revokePending = true;
+ this.error = null;
+ this.notice = null;
+ try {
+ this.consent = await revokeClientConsent(clientId);
+ this.notice = 'Access revoked. You can still use your account here.';
+ } catch (e) {
+ this.error = e as Error;
+ }
+ this.revokePending = false;
+ m.redraw();
+ },
+
view(this: any) {
const tokens = getAccountTokens();
const user = this.user;
@@ -128,6 +157,12 @@ export const Account: m.Component = {
</div>
) : null}
+ {this.notice ? (
+ <div class="account-notice" role="status">
+ {this.notice}
+ </div>
+ ) : null}
+
{!name ? (
<div class="account-loading">Loading account</div>
) : (
@@ -171,17 +206,81 @@ export const Account: m.Component = {
</div>
<div>
<dt>Permissions</dt>
- <dd>{session ? 'Current client' : 'Full account'}</dd>
+ <dd>
+ {session
+ ? this.consent?.active
+ ? 'Granted'
+ : 'Not granted'
+ : 'Full account'}
+ </dd>
</div>
</dl>
</section>
- <section class="account-card account-card-wide">
- <h2>Permissions</h2>
- <p class="account-note">
- App permissions and consent management arrive in the next account slice.
- </p>
- </section>
+ {this.mode === 'client' ? (
+ <section class="account-card account-card-wide">
+ <h2>App access</h2>
+ <dl class="account-definition">
+ <div>
+ <dt>App</dt>
+ <dd>{this.consent?.client.name || session?.scope.client_id}</dd>
+ </div>
+ <div>
+ <dt>Scopes</dt>
+ <dd>
+ {this.consent?.scopes.length
+ ? this.consent.scopes.join(', ')
+ : 'None'}
+ </dd>
+ </div>
+ <div>
+ <dt>Granted</dt>
+ <dd>
+ {this.consent?.consent
+ ? formatTime(this.consent.consent.created_at)
+ : 'Not granted'}
+ </dd>
+ </div>
+ <div>
+ <dt>Revoked</dt>
+ <dd>
+ {this.consent?.consent?.revoked_at
+ ? formatTime(this.consent.consent.revoked_at)
+ : 'Not revoked'}
+ </dd>
+ </div>
+ </dl>
+ <p class="account-note account-card-note">
+ {this.consent?.active
+ ? `${this.consent.client.name} can use the access above. Revoking it does not sign you out here.`
+ : `${session?.scope.client_id || 'This app'} no longer has access to your account.`}
+ </p>
+ <div class="account-actions">
+ {this.consent?.active ? (
+ <button
+ class="account-danger"
+ type="button"
+ disabled={this.revokePending}
+ onclick={() => this.revokeConsent()}
+ >
+ {this.revokePending ? 'Revoking' : 'Revoke access'}
+ </button>
+ ) : null}
+ {this.fullAccountUrl ? (
+ <a class="account-link" href={this.fullAccountUrl}>
+ Open full account
+ </a>
+ ) : null}
+ </div>
+ </section>
+ ) : (
+ <section class="account-card account-card-wide">
+ <h2>Permissions</h2>
+ <p class="account-note">
+ App permissions and consent management arrive in the next account slice.
+ </p>
+ </section>
+ )}
</div>
)}
</main>
diff --git a/app/account/src/util/api.ts b/app/account/src/util/api.ts
@@ -57,6 +57,32 @@ export interface SessionInfo {
accounts: unknown[];
}
+export interface ClientConsentInfo {
+ client: {
+ id: string;
+ name: string;
+ };
+ realm: {
+ slug: string;
+ display_name: string;
+ branding: Record<string, string>;
+ } | null;
+ user: {
+ id: string;
+ username: string;
+ display_name: string | null;
+ };
+ scopes: string[];
+ account_url: string;
+ active: boolean;
+ consent: {
+ granted_via: 'user' | 'trusted';
+ created_at: number;
+ updated_at: number;
+ revoked_at: number | null;
+ } | null;
+}
+
export interface ApiError extends Error {
code?: string;
status?: number;
@@ -217,3 +243,44 @@ export async function getClientSession(): Promise<SessionInfo> {
}
return payload as SessionInfo;
}
+
+async function clientConsentRequest(
+ clientId: string,
+ method = 'GET'
+): Promise<ClientConsentInfo> {
+ const response = await fetch(
+ `/api/v1/account/clients/${encodeURIComponent(clientId)}/consent`,
+ {
+ method,
+ credentials: 'same-origin',
+ }
+ );
+ let payload: any = null;
+ try {
+ payload = await response.json();
+ } catch {
+ payload = null;
+ }
+ if (!response.ok) {
+ const error = new Error(
+ payload?.error?.message || response.statusText
+ ) as ApiError;
+ error.code = payload?.error?.code;
+ error.status = response.status;
+ throw error;
+ }
+ return payload as ClientConsentInfo;
+}
+
+export function getClientConsent(clientId: string): Promise<ClientConsentInfo> {
+ return clientConsentRequest(clientId);
+}
+
+export function revokeClientConsent(clientId: string): Promise<ClientConsentInfo> {
+ return clientConsentRequest(clientId, 'DELETE');
+}
+
+export async function getFullAccountUrl() {
+ const authUrl = (await getAuthUrl()).replace(/\/+$/, '');
+ return `${authUrl}/app/account`;
+}
diff --git a/app/account/src/util/icon.ts b/app/account/src/util/icon.ts
@@ -0,0 +1,23 @@
+import m from 'mithril';
+
+type IconNode = ReadonlyArray<readonly [string, Record<string, string | number>]>;
+
+export function icon(nodes: IconNode, attrs: Record<string, unknown> = {}) {
+ return m(
+ 'svg',
+ {
+ xmlns: 'http://www.w3.org/2000/svg',
+ width: 24,
+ height: 24,
+ viewBox: '0 0 24 24',
+ fill: 'none',
+ stroke: 'currentColor',
+ 'stroke-width': 2,
+ 'stroke-linecap': 'round',
+ 'stroke-linejoin': 'round',
+ 'aria-hidden': 'true',
+ ...attrs,
+ },
+ nodes.map(([tag, nodeAttrs]) => m(tag, nodeAttrs))
+ );
+}
diff --git a/app/login/package-lock.json b/app/login/package-lock.json
@@ -6,6 +6,7 @@
"": {
"name": "auth-login",
"dependencies": {
+ "lucide": "^1.61.0",
"mithril": "^2.3.8"
},
"devDependencies": {
@@ -496,6 +497,12 @@
"@esbuild/win32-x64": "0.28.2"
}
},
+ "node_modules/lucide": {
+ "version": "1.61.0",
+ "resolved": "https://registry.npmjs.org/lucide/-/lucide-1.61.0.tgz",
+ "integrity": "sha512-RPNMBgej6WjPKuCNEODg83CF8lnraCeDOsZ3HZ7KvUYf0O5hdJBzer/Ax/meBHl3xvrp5NmKX0IDA5myyzlvGw==",
+ "license": "ISC"
+ },
"node_modules/mithril": {
"version": "2.3.8",
"resolved": "https://registry.npmjs.org/mithril/-/mithril-2.3.8.tgz",
diff --git a/app/login/package.json b/app/login/package.json
@@ -7,6 +7,7 @@
"assets:hex": "node scripts/generate-hex-grid.js"
},
"dependencies": {
+ "lucide": "^1.61.0",
"mithril": "^2.3.8"
},
"devDependencies": {
diff --git a/app/login/src/assets/login.css b/app/login/src/assets/login.css
@@ -211,6 +211,85 @@ body {
cursor: pointer;
}
+.auth-card-consent {
+ width: min(28rem, 100%);
+}
+
+.auth-consent-account {
+ display: flex;
+ align-items: center;
+ gap: 0.75rem;
+ margin-top: 1.5rem;
+ padding: 0.75rem;
+ background: rgba(0, 0, 0, 0.05);
+}
+
+.auth-consent-account svg {
+ flex: none;
+ width: 1.5rem;
+ height: 1.5rem;
+}
+
+.auth-consent-account-body {
+ display: grid;
+ gap: 0.125rem;
+ min-width: 0;
+}
+
+.auth-consent-account-name {
+ font-size: 0.875rem;
+ font-weight: 500;
+ line-height: 1.4;
+}
+
+.auth-consent-account-meta {
+ overflow-wrap: anywhere;
+ color: rgba(0, 0, 0, 0.6);
+ font-size: 0.75rem;
+ line-height: 1.4;
+}
+
+.auth-consent-account .auth-link {
+ flex: none;
+ margin-left: auto;
+ font-size: 0.8125rem;
+}
+
+.auth-consent-title {
+ margin: 1.5rem 0 0;
+ font-size: 0.875rem;
+ font-weight: 500;
+ line-height: 1.5;
+}
+
+.auth-consent-scopes {
+ display: grid;
+ gap: 0.5rem;
+ margin: 0.75rem 0 0;
+ padding: 0;
+ list-style: none;
+}
+
+.auth-consent-scope {
+ display: flex;
+ align-items: flex-start;
+ gap: 0.5rem;
+ color: rgba(0, 0, 0, 0.6);
+ font-size: 0.875rem;
+ line-height: 1.5;
+}
+
+.auth-consent-scope svg {
+ flex: none;
+ width: 1rem;
+ height: 1rem;
+ margin-top: 0.125rem;
+}
+
+.auth-consent-footer {
+ margin: 1.5rem 0 0;
+}
+
@media (prefers-color-scheme: dark) {
:root {
--auth-surface: #222;
@@ -228,7 +307,9 @@ body {
.auth-field label,
.auth-identifier,
.auth-note,
- .auth-account-username {
+ .auth-account-username,
+ .auth-consent-account-meta,
+ .auth-consent-scope {
color: rgba(255, 255, 255, 0.6);
}
@@ -236,6 +317,10 @@ body {
border-bottom-color: rgba(255, 255, 255, 0.16);
}
+ .auth-consent-account {
+ background: rgba(255, 255, 255, 0.08);
+ }
+
.auth-error {
color: #f28b82;
}
diff --git a/app/login/src/main.ts b/app/login/src/main.ts
@@ -7,9 +7,15 @@ const routes: m.RouteDefs = {
'/oidc/:clientId/login': {
render: (vnode) => m(Login, { clientId: (vnode.attrs as any).clientId }),
},
+ '/oidc/:clientId/consent': {
+ render: (vnode) => m(Login, { clientId: (vnode.attrs as any).clientId }),
+ },
'/oidc/login': {
render: () => m(Login, {}),
},
+ '/oidc/consent': {
+ render: () => m(Login, {}),
+ },
};
m.route.prefix = '';
diff --git a/app/login/src/screen/login.tsx b/app/login/src/screen/login.tsx
@@ -1,17 +1,23 @@
+import { Check, CircleUserRound } from 'lucide';
import m from 'mithril';
+import { icon } from '../util/icon';
import {
+ decideConsent,
getClientDiscovery,
+ getConsent,
getSession,
resolveLogin,
selectSession,
signInPassword,
+ signOut,
type ClientDiscovery,
+ type ConsentRequest,
type LoginResolution,
type PasswordLoginResult,
type SessionAccount,
} from '../util/api';
-type Step = 'accounts' | 'identifier' | 'password' | 'oidc' | 'done';
+type Step = 'accounts' | 'identifier' | 'password' | 'oidc' | 'consent' | 'done';
interface TextFieldAttrs {
id: string;
@@ -29,15 +35,29 @@ function queryParam(name: string) {
return new URLSearchParams(query).get(name);
}
+function currentPath() {
+ return (m.route.get() || '').split('?')[0];
+}
+
function authorizeRoute() {
- const path = (m.route.get() || '').split('?')[0];
- return path.replace(/\/login$/, '/authorize');
+ return currentPath().replace(/\/(login|consent)$/, '/authorize');
+}
+
+function loginRoute() {
+ return currentPath().replace(/\/consent$/, '/login');
}
function continueAuthorization() {
window.location.assign(authorizeRoute());
}
+function scopeDescription(scope: string, realmName: string) {
+ if (scope === 'openid') return `Sign you in with your ${realmName} account.`;
+ if (scope === 'profile') return 'See your name and username.';
+ if (scope === 'email') return 'See your email address.';
+ return `Use the ${scope} permission.`;
+}
+
const TextField: m.Component<TextFieldAttrs> = {
view({ attrs }) {
return (
@@ -69,6 +89,8 @@ export const Login: m.Component<{ clientId?: string }> = {
longSession: false,
provider: null as LoginResolution['provider'] | null,
signedIn: null as PasswordLoginResult['user'] | null,
+ consentRequest: null as ConsentRequest | null,
+ consentRoute: false,
error: null as Error | null,
pending: false,
reauth: false,
@@ -76,6 +98,7 @@ export const Login: m.Component<{ clientId?: string }> = {
oninit(this: any, vnode: any) {
this.clientId = vnode.attrs.clientId ?? null;
this.reauth = queryParam('reauth') === '1';
+ this.consentRoute = /\/consent$/.test(currentPath());
this.loadClient();
},
@@ -86,13 +109,22 @@ export const Login: m.Component<{ clientId?: string }> = {
this.discovery = discovery;
this.clientId = discovery.client_id;
document.title = discovery.display_name;
- await this.loadAccounts();
+ if (this.consentRoute) {
+ this.step = 'consent';
+ await this.loadConsent();
+ } else {
+ await this.loadAccounts();
+ }
} catch (e) {
this.error = e as Error;
}
m.redraw();
},
+ async loadConsent(this: any) {
+ this.consentRequest = await getConsent(this.clientId);
+ },
+
async loadAccounts(this: any) {
if (this.reauth) {
this.accounts = [];
@@ -173,6 +205,34 @@ export const Login: m.Component<{ clientId?: string }> = {
m.redraw();
},
+ async decideConsent(this: any, decision: 'allow' | 'deny') {
+ this.pending = true;
+ this.error = null;
+ try {
+ const result = await decideConsent(this.clientId, decision);
+ window.location.assign(result.redirect || authorizeRoute());
+ return;
+ } catch (e) {
+ this.error = e as Error;
+ }
+ this.pending = false;
+ m.redraw();
+ },
+
+ async differentConsentAccount(this: any) {
+ this.pending = true;
+ this.error = null;
+ try {
+ await signOut();
+ window.location.assign(loginRoute());
+ return;
+ } catch (e) {
+ this.error = e as Error;
+ }
+ this.pending = false;
+ m.redraw();
+ },
+
differentAccount(this: any) {
this.step = 'identifier';
this.identifier = '';
@@ -214,11 +274,16 @@ export const Login: m.Component<{ clientId?: string }> = {
);
}
- const title = this.discovery?.display_name || 'Sign in';
+ const title =
+ this.step === 'consent'
+ ? this.consentRequest
+ ? `Authorize ${this.consentRequest.client.name}`
+ : 'Authorize access'
+ : this.discovery?.display_name || 'Sign in';
return (
<div class="auth-page" style={style}>
- <div class="auth-card">
+ <div class={`auth-card${this.step === 'consent' ? ' auth-card-consent' : ''}`}>
{typeof branding.logo_url === 'string' && branding.logo_url ? (
<img class="auth-logo" src={branding.logo_url} alt={title} />
) : null}
@@ -228,6 +293,7 @@ export const Login: m.Component<{ clientId?: string }> = {
{this.step === 'identifier' ? this.renderIdentifier() : null}
{this.step === 'password' ? this.renderPassword() : null}
{this.step === 'oidc' ? this.renderProvider() : null}
+ {this.step === 'consent' ? this.renderConsent() : null}
{this.step === 'done' ? this.renderDone() : null}
</div>
</div>
@@ -374,6 +440,80 @@ export const Login: m.Component<{ clientId?: string }> = {
);
},
+ renderConsent(this: any) {
+ const request = this.consentRequest;
+ if (!request) {
+ return <p class="auth-note">Loading request</p>;
+ }
+
+ const realmName = request.realm?.display_name || 'account';
+ const name = request.user.display_name || request.user.username;
+ const secondary =
+ request.user.display_name && request.user.display_name !== request.user.username
+ ? request.user.username
+ : 'Signed in';
+
+ return (
+ <div>
+ <p class="auth-note">
+ {request.client.name} is requesting access to your {realmName} account.
+ </p>
+
+ <div class="auth-consent-account">
+ {icon(CircleUserRound)}
+ <span class="auth-consent-account-body">
+ <span class="auth-consent-account-name">{name}</span>
+ <span class="auth-consent-account-meta">{secondary}</span>
+ </span>
+ <button
+ class="auth-link"
+ type="button"
+ disabled={this.pending}
+ onclick={() => this.differentConsentAccount()}
+ >
+ Not you?
+ </button>
+ </div>
+
+ <p class="auth-consent-title">
+ This will allow {request.client.name} to:
+ </p>
+ <ul class="auth-consent-scopes">
+ {request.scopes.map((scope: string) => (
+ <li class="auth-consent-scope">
+ {icon(Check)}
+ <span>{scopeDescription(scope, realmName)}</span>
+ </li>
+ ))}
+ </ul>
+
+ <p class="auth-note auth-consent-footer">
+ You can revoke access at any time from your account settings.
+ </p>
+ {this.error ? <p class="auth-error">{this.error.message}</p> : null}
+
+ <div class="auth-actions">
+ <button
+ class="auth-link"
+ type="button"
+ disabled={this.pending}
+ onclick={() => this.decideConsent('deny')}
+ >
+ Deny
+ </button>
+ <button
+ class="auth-button"
+ type="button"
+ disabled={this.pending}
+ onclick={() => this.decideConsent('allow')}
+ >
+ {this.pending ? 'Working' : 'Allow access'}
+ </button>
+ </div>
+ </div>
+ );
+ },
+
renderDone(this: any) {
const user = this.signedIn;
return (
diff --git a/app/login/src/util/api.ts b/app/login/src/util/api.ts
@@ -82,6 +82,26 @@ export interface SelectSessionResult {
pending_auth_request: boolean;
}
+export interface ConsentRequest {
+ client: {
+ id: string;
+ name: string;
+ };
+ realm: RealmInfo | null;
+ user: {
+ id: string;
+ username: string;
+ display_name: string | null;
+ };
+ scopes: string[];
+ consent_mode: 'remembered' | 'trusted';
+}
+
+export interface ConsentDecision {
+ ok: boolean;
+ redirect: string;
+}
+
export interface ApiError extends Error {
code?: string;
status?: number;
@@ -156,6 +176,21 @@ export function getSession(): Promise<SessionInfo> {
return request<SessionInfo>('/api/v1/session');
}
+export function getConsent(clientId?: string | null): Promise<ConsentRequest> {
+ const query = clientId ? `?client_id=${encodeURIComponent(clientId)}` : '';
+ return request<ConsentRequest>(`/api/v1/consent${query}`);
+}
+
+export function decideConsent(
+ clientId: string,
+ decision: 'allow' | 'deny'
+): Promise<ConsentDecision> {
+ return request<ConsentDecision>('/api/v1/consent', {
+ method: 'POST',
+ body: JSON.stringify({ client_id: clientId, decision }),
+ });
+}
+
export function selectSession(
publicId: string,
clientId?: string | null
diff --git a/app/login/src/util/icon.ts b/app/login/src/util/icon.ts
@@ -0,0 +1,23 @@
+import m from 'mithril';
+
+type IconNode = ReadonlyArray<readonly [string, Record<string, string | number>]>;
+
+export function icon(nodes: IconNode, attrs: Record<string, unknown> = {}) {
+ return m(
+ 'svg',
+ {
+ xmlns: 'http://www.w3.org/2000/svg',
+ width: 24,
+ height: 24,
+ viewBox: '0 0 24 24',
+ fill: 'none',
+ stroke: 'currentColor',
+ 'stroke-width': 2,
+ 'stroke-linecap': 'round',
+ 'stroke-linejoin': 'round',
+ 'aria-hidden': 'true',
+ ...attrs,
+ },
+ nodes.map(([tag, nodeAttrs]) => m(tag, nodeAttrs))
+ );
+}
diff --git a/server/migrations/sqlite/realm/004_consent_mode.sql b/server/migrations/sqlite/realm/004_consent_mode.sql
@@ -0,0 +1 @@
+ALTER TABLE oidc_clients ADD COLUMN consent_mode TEXT NOT NULL DEFAULT 'remembered' CHECK (consent_mode IN ('remembered', 'trusted'));
diff --git a/server/migrations/sqlite/system/007_client_consents.sql b/server/migrations/sqlite/system/007_client_consents.sql
@@ -0,0 +1,14 @@
+CREATE TABLE client_consents (
+ user_id TEXT NOT NULL,
+ realm_id TEXT NOT NULL REFERENCES realms(id) ON DELETE CASCADE,
+ client_id TEXT NOT NULL,
+ scopes TEXT NOT NULL,
+ granted_via TEXT NOT NULL CHECK (granted_via IN ('user', 'trusted')),
+ created_at INTEGER NOT NULL,
+ updated_at INTEGER NOT NULL,
+ revoked_at INTEGER,
+ PRIMARY KEY (user_id, realm_id, client_id)
+);
+
+CREATE INDEX client_consents_client ON client_consents(client_id);
+CREATE INDEX client_consents_user ON client_consents(user_id);
diff --git a/server/scripts/seed-demo.js b/server/scripts/seed-demo.js
@@ -134,6 +134,7 @@ async function ensureClient(
clientSecret = null,
branding = {},
requirePkce = true,
+ consentMode = 'remembered',
}
) {
const mapping = await findClientRealm(clientId);
@@ -149,11 +150,11 @@ async function ensureClient(
`INSERT INTO oidc_clients
(id, client_id, name, redirect_uris, scopes, access_mode, enabled, branding,
client_secret_hash, token_endpoint_auth_method, require_pkce,
- post_logout_redirect_uris, created_at, updated_at)
+ post_logout_redirect_uris, consent_mode, created_at, updated_at)
VALUES
({id}, {clientId}, {name}, {redirectUris}, 'openid profile email', {accessMode}, 1, {branding},
{clientSecretHash}, {tokenEndpointAuthMethod}, {requirePkce},
- {postLogoutRedirectUris}, {createdAt}, {updatedAt})`,
+ {postLogoutRedirectUris}, {consentMode}, {createdAt}, {updatedAt})`,
{
id: client.id,
clientId,
@@ -165,6 +166,7 @@ async function ensureClient(
tokenEndpointAuthMethod,
requirePkce: requirePkce ? 1 : 0,
postLogoutRedirectUris: JSON.stringify(postLogoutRedirectUris),
+ consentMode,
createdAt: now,
updatedAt: now,
}
diff --git a/server/src/controller/account/client-consent.js b/server/src/controller/account/client-consent.js
@@ -0,0 +1,119 @@
+import { app } from '../../app.js';
+import {
+ getConsent,
+ revokeConsent,
+ revokeConsentRefreshTokens,
+ splitScopes,
+} from '../../lib/consents.js';
+import { resolveHostContext } from '../../lib/host-context.js';
+import { HttpError } from '../../lib/http/http-error.js';
+import { getClient } from '../../lib/oidc/clients.js';
+import { canonicalBaseUrl } from '../../lib/oidc/context.js';
+import { getSystemDatabase, openRealmDatabase, realmMetadata } from '../../lib/realm.js';
+import { authenticateRequest } from '../../lib/session.js';
+
+async function resolveClientAccount(req, res, clientId) {
+ const hostContext = await resolveHostContext(req, {
+ publicUrl: app.config.server.public_url,
+ });
+ if (hostContext.mode !== 'client' || hostContext.clientId !== clientId) {
+ throw new HttpError(404, 'not_found', 'Not found');
+ }
+
+ const realmDb = await openRealmDatabase(hostContext.realm);
+ const systemDb = getSystemDatabase();
+ const client = await getClient(realmDb, hostContext.clientId);
+ if (!client || !client.enabled) {
+ throw new HttpError(404, 'unknown_client', 'Unknown client');
+ }
+
+ const auth = await authenticateRequest({
+ systemDb,
+ realmDb,
+ req,
+ res,
+ context: hostContext,
+ });
+ if (!auth) {
+ throw new HttpError(401, 'not_authenticated', 'Not signed in');
+ }
+
+ return { hostContext, realmDb, systemDb, client, auth };
+}
+
+async function consentResponse({ hostContext, systemDb, client, auth }) {
+ const consent = await getConsent(systemDb, {
+ userId: auth.user.id,
+ realmId: hostContext.realm.id,
+ clientId: client.client_id,
+ });
+ const realm = await realmMetadata(hostContext.realm);
+
+ return {
+ client: {
+ id: client.client_id,
+ name: client.name,
+ },
+ realm,
+ user: {
+ id: auth.user.id,
+ username: auth.user.username,
+ display_name: auth.user.display_name,
+ },
+ scopes: splitScopes(consent?.scopes),
+ account_url: `${canonicalBaseUrl(app.config.server.public_url)}/app/account`,
+ active: Boolean(consent && !consent.revoked_at),
+ consent: consent
+ ? {
+ granted_via: consent.granted_via,
+ created_at: consent.created_at,
+ updated_at: consent.updated_at,
+ revoked_at: consent.revoked_at,
+ }
+ : null,
+ };
+}
+
+export default [
+ {
+ method: 'get',
+ path: '/api/v1/account/clients/:clientId/consent',
+ name: 'account.client_consent.show',
+ async handler(req, res) {
+ const context = await resolveClientAccount(req, res, req.params.clientId);
+ return new app.HttpOk(await consentResponse(context), {
+ 'cache-control': 'no-store',
+ });
+ },
+ },
+ {
+ method: 'delete',
+ path: '/api/v1/account/clients/:clientId/consent',
+ name: 'account.client_consent.revoke',
+ async handler(req, res) {
+ const context = await resolveClientAccount(req, res, req.params.clientId);
+ const now = Date.now();
+ const consent = await revokeConsent(context.systemDb, {
+ userId: context.auth.user.id,
+ realmId: context.hostContext.realm.id,
+ clientId: context.client.client_id,
+ now,
+ });
+ await revokeConsentRefreshTokens(context.systemDb, {
+ userId: context.auth.user.id,
+ realmId: context.hostContext.realm.id,
+ clientId: context.client.client_id,
+ now,
+ });
+
+ return new app.HttpOk(
+ {
+ ...(await consentResponse(context)),
+ ok: true,
+ revoked_at: consent.revoked_at,
+ },
+ { 'cache-control': 'no-store' }
+ );
+ },
+ },
+];
diff --git a/server/src/controller/consent/decide.js b/server/src/controller/consent/decide.js
@@ -0,0 +1,67 @@
+import { app } from '../../app.js';
+import { resolveConsentRequest } from '../../lib/consent-request.js';
+import { recordConsent } from '../../lib/consents.js';
+import { HttpError } from '../../lib/http/http-error.js';
+import { endpointUrls, requestOrigin } from '../../lib/oidc/context.js';
+import { clearAuthRequestCookie, deleteAuthRequest } from '../../lib/oidc/requests.js';
+
+function withQuery(url, params) {
+ const target = new URL(url);
+ for (const [key, value] of Object.entries(params)) {
+ if (value !== undefined && value !== null && value !== '') {
+ target.searchParams.set(key, String(value));
+ }
+ }
+ return target.toString();
+}
+
+export default {
+ method: 'post',
+ path: '/api/v1/consent',
+ name: 'consent.decide',
+ async handler(req, res) {
+ const body = req.body || {};
+ if (body.decision !== 'allow' && body.decision !== 'deny') {
+ throw new HttpError(400, 'invalid_request', 'decision must be allow or deny');
+ }
+
+ const request = await resolveConsentRequest({
+ req,
+ res,
+ publicUrl: app.config.server.public_url,
+ clientId: body.client_id,
+ });
+
+ if (body.decision === 'deny') {
+ const redirect = withQuery(request.pending.redirect_uri, {
+ error: 'access_denied',
+ error_description: 'The user denied access',
+ state: request.pending.state,
+ });
+ await deleteAuthRequest(request.store, request.pending.id);
+ clearAuthRequestCookie(res, req, request.target);
+ return new app.HttpOk({ ok: true, redirect }, { 'cache-control': 'no-store' });
+ }
+
+ await recordConsent(request.systemDb, {
+ userId: request.auth.user.id,
+ realmId: request.target.realm.id,
+ clientId: request.target.clientId,
+ scopes: request.pending.scope,
+ grantedVia: 'user',
+ });
+
+ const context = {
+ ...request.hostContext,
+ origin: requestOrigin(req),
+ clientId: request.target.clientId,
+ realm: request.target.realm,
+ systemClient: false,
+ };
+
+ return new app.HttpOk(
+ { ok: true, redirect: endpointUrls(context).authorize },
+ { 'cache-control': 'no-store' }
+ );
+ },
+};
diff --git a/server/src/controller/consent/show.js b/server/src/controller/consent/show.js
@@ -0,0 +1,38 @@
+import { app } from '../../app.js';
+import { resolveConsentRequest } from '../../lib/consent-request.js';
+import { splitScopes } from '../../lib/consents.js';
+import { realmMetadata } from '../../lib/realm.js';
+
+export default {
+ method: 'get',
+ path: '/api/v1/consent',
+ name: 'consent.show',
+ async handler(req, res) {
+ const url = new URL(req.url, 'http://localhost');
+ const request = await resolveConsentRequest({
+ req,
+ res,
+ publicUrl: app.config.server.public_url,
+ clientId: url.searchParams.get('client_id'),
+ });
+ const realm = await realmMetadata(request.target.realm);
+
+ return new app.HttpOk(
+ {
+ client: {
+ id: request.client.client_id,
+ name: request.client.name,
+ },
+ realm,
+ user: {
+ id: request.auth.user.id,
+ username: request.auth.user.username,
+ display_name: request.auth.user.display_name,
+ },
+ scopes: splitScopes(request.pending.scope),
+ consent_mode: request.client.consent_mode,
+ },
+ { 'cache-control': 'no-store' }
+ );
+ },
+};
diff --git a/server/src/controller/oidc.js b/server/src/controller/oidc.js
@@ -5,6 +5,7 @@ import {
systemClientPostLogoutUris,
systemClientRedirectUris,
} from '../lib/apps.js';
+import { consentStatus, getConsent, recordConsent } from '../lib/consents.js';
import { HttpError } from '../lib/http/http-error.js';
import {
authenticateClient,
@@ -31,6 +32,7 @@ import {
getAuthRequest,
purgeExpired,
readAuthRequestId,
+ selectAuthRequestAccount,
setAuthRequestCookie,
} from '../lib/oidc/requests.js';
import { canUseClient } from '../lib/policy.js';
@@ -336,6 +338,41 @@ async function authorize(context, client, req, res) {
await bindSessionRealm(systemDb, auth.session.id, context.realm.id);
}
+ const consent = client.system_client
+ ? null
+ : await getConsent(systemDb, {
+ userId: auth.user.id,
+ realmId: context.realm.id,
+ clientId: client.client_id,
+ });
+ const consentState = consentStatus({
+ client,
+ user: auth.user,
+ realm: context.realm,
+ consent,
+ scope,
+ });
+
+ if (consentState.required) {
+ await selectAuthRequestAccount(store, pending.id, {
+ userId: auth.user.id,
+ sessionId: auth.session.id,
+ authTime: auth.session.auth_time,
+ });
+ setAuthRequestCookie(res, req, context, pending.id);
+ return redirect(res, endpointUrls(context).consent);
+ }
+
+ if (consentState.autoGrant) {
+ await recordConsent(systemDb, {
+ userId: auth.user.id,
+ realmId: context.realm.id,
+ clientId: client.client_id,
+ scopes: scope,
+ grantedVia: 'trusted',
+ });
+ }
+
await completeAuthRequest(store, pending.id, {
userId: auth.user.id,
sessionId: auth.session.id,
@@ -497,6 +534,33 @@ async function token(context, client, req) {
}
}
+ if (!client.system_client) {
+ const consent = await getConsent(systemDb, {
+ userId: user.id,
+ realmId: context.realm.id,
+ clientId: client.client_id,
+ });
+ const consentState = consentStatus({
+ client,
+ user,
+ realm: context.realm,
+ consent,
+ scope: code.scope,
+ });
+ if (consentState.required) {
+ return oidcError(400, 'invalid_grant', 'The user has not consented to this client');
+ }
+ if (consentState.autoGrant) {
+ await recordConsent(systemDb, {
+ userId: user.id,
+ realmId: context.realm.id,
+ clientId: client.client_id,
+ scopes: code.scope,
+ grantedVia: 'trusted',
+ });
+ }
+ }
+
const response = await accessTokenResponse({
systemDb,
realmDb,
@@ -539,7 +603,24 @@ async function token(context, client, req) {
const user = await findUserById(tx, row.user_id);
if (!user || user.status !== 'active') return false;
- if (!(await canUseSystemClient(tx, { user, client }))) return false;
+
+ if (client.system_client) {
+ if (!(await canUseSystemClient(tx, { user, client }))) return false;
+ } else {
+ const consent = await getConsent(tx, {
+ userId: row.user_id,
+ realmId: row.realm_id,
+ clientId: row.client_id,
+ });
+ const consentState = consentStatus({
+ client,
+ user,
+ realm: context.realm,
+ consent,
+ scope: row.scopes,
+ });
+ if (consentState.required) return false;
+ }
if (row.realm_id) {
const binding = await getSessionRealmBinding(tx, row.session_id, row.realm_id);
@@ -673,7 +754,7 @@ export default {
const context = await resolveOidcContext(req, {
publicUrl: app.config.server.public_url,
});
- if (context.action === 'login') {
+ if (context.action === 'login' || context.action === 'consent') {
serveAppDocument(res, 'login');
return;
}
diff --git a/server/src/lib/consent-request.js b/server/src/lib/consent-request.js
@@ -0,0 +1,65 @@
+import { resolveClientForHost, resolveHostContext } from './host-context.js';
+import { HttpError } from './http/http-error.js';
+import { getClient, getSystemClient } from './oidc/clients.js';
+import { getAuthRequest, readAuthRequestId } from './oidc/requests.js';
+import { getSystemDatabase, openRealmDatabase } from './realm.js';
+import { authenticateRequest } from './session.js';
+
+export async function resolveConsentRequest({ req, res, publicUrl, clientId }) {
+ const hostContext = await resolveHostContext(req, { publicUrl });
+ const target = await resolveClientForHost(
+ hostContext,
+ clientId || hostContext.clientId
+ );
+ const realmDb = target.realm ? await openRealmDatabase(target.realm) : null;
+ const systemDb = getSystemDatabase();
+ const client = target.systemClient
+ ? getSystemClient(target.clientId)
+ : await getClient(realmDb, target.clientId);
+
+ if (!client || !client.enabled) {
+ throw new HttpError(404, 'unknown_client', 'Unknown client');
+ }
+ if (client.system_client) {
+ throw new HttpError(400, 'invalid_request', 'System clients do not use consent');
+ }
+
+ const auth = await authenticateRequest({
+ systemDb,
+ realmDb,
+ req,
+ res,
+ context: hostContext,
+ });
+ if (!auth) {
+ throw new HttpError(401, 'not_authenticated', 'Not signed in');
+ }
+
+ const store = realmDb;
+ const pending = await getAuthRequest(store, readAuthRequestId(req, target));
+ if (!pending || pending.completed_at || pending.client_id !== client.client_id) {
+ throw new HttpError(
+ 400,
+ 'invalid_request',
+ 'There is no pending authorization request'
+ );
+ }
+ if (pending.user_id !== auth.user.id || pending.session_id !== auth.session.id) {
+ throw new HttpError(
+ 409,
+ 'consent_not_ready',
+ 'The authorization request is not ready for consent'
+ );
+ }
+
+ return {
+ hostContext,
+ target,
+ realmDb,
+ systemDb,
+ client,
+ pending,
+ store,
+ auth,
+ };
+}
diff --git a/server/src/lib/consents.js b/server/src/lib/consents.js
@@ -0,0 +1,162 @@
+export function splitScopes(value) {
+ return [...new Set(String(value || '').split(/\s+/).filter(Boolean))];
+}
+
+function scopeSet(value) {
+ return new Set(splitScopes(value));
+}
+
+export function scopesCovered(consented, requested) {
+ const granted = scopeSet(consented);
+ return splitScopes(requested).every((scope) => granted.has(scope));
+}
+
+function mergeScopes(left, right) {
+ return splitScopes([...splitScopes(left), ...splitScopes(right)].join(' ')).join(' ');
+}
+
+export async function getConsent(db, { userId, realmId, clientId }) {
+ return db.get(
+ `SELECT user_id, realm_id, client_id, scopes, granted_via, created_at,
+ updated_at, revoked_at
+ FROM client_consents
+ WHERE user_id = {userId} AND realm_id = {realmId} AND client_id = {clientId}`,
+ { userId, realmId, clientId }
+ );
+}
+
+export async function recordConsent(
+ db,
+ { userId, realmId, clientId, scopes: requestedScopes, grantedVia = 'user', now = Date.now() }
+) {
+ return db.transaction(async (tx) => {
+ const existing = await getConsent(tx, { userId, realmId, clientId });
+ const scopes =
+ existing && !existing.revoked_at
+ ? mergeScopes(existing.scopes, requestedScopes)
+ : splitScopes(requestedScopes).join(' ');
+ const granted_via =
+ grantedVia === 'user' || existing?.granted_via === 'user' ? 'user' : 'trusted';
+
+ if (existing) {
+ await tx.run(
+ `UPDATE client_consents
+ SET scopes = {scopes}, granted_via = {grantedVia}, updated_at = {now},
+ revoked_at = NULL
+ WHERE user_id = {userId} AND realm_id = {realmId} AND client_id = {clientId}`,
+ { scopes, grantedVia: granted_via, now, userId, realmId, clientId }
+ );
+ return {
+ ...existing,
+ scopes,
+ granted_via,
+ updated_at: now,
+ revoked_at: null,
+ };
+ }
+
+ await tx.run(
+ `INSERT INTO client_consents
+ (user_id, realm_id, client_id, scopes, granted_via, created_at,
+ updated_at, revoked_at)
+ VALUES
+ ({userId}, {realmId}, {clientId}, {scopes}, {grantedVia}, {now}, {now}, NULL)`,
+ { userId, realmId, clientId, scopes, grantedVia: granted_via, now }
+ );
+ return {
+ user_id: userId,
+ realm_id: realmId,
+ client_id: clientId,
+ scopes,
+ granted_via,
+ created_at: now,
+ updated_at: now,
+ revoked_at: null,
+ };
+ });
+}
+
+export async function revokeConsent(
+ db,
+ { userId, realmId, clientId, now = Date.now() }
+) {
+ return db.transaction(async (tx) => {
+ const existing = await getConsent(tx, { userId, realmId, clientId });
+ if (existing) {
+ await tx.run(
+ `UPDATE client_consents
+ SET revoked_at = {now}, updated_at = {now}
+ WHERE user_id = {userId} AND realm_id = {realmId} AND client_id = {clientId}`,
+ { now, userId, realmId, clientId }
+ );
+ return { ...existing, revoked_at: now, updated_at: now };
+ }
+
+ await tx.run(
+ `INSERT INTO client_consents
+ (user_id, realm_id, client_id, scopes, granted_via, created_at,
+ updated_at, revoked_at)
+ VALUES
+ ({userId}, {realmId}, {clientId}, '', 'user', {now}, {now}, {now})`,
+ { userId, realmId, clientId, now }
+ );
+ return {
+ user_id: userId,
+ realm_id: realmId,
+ client_id: clientId,
+ scopes: '',
+ granted_via: 'user',
+ created_at: now,
+ updated_at: now,
+ revoked_at: now,
+ };
+ });
+}
+
+export async function revokeConsentRefreshTokens(
+ db,
+ { userId, realmId, clientId, now = Date.now() }
+) {
+ const result = await db.run(
+ `UPDATE refresh_tokens
+ SET revoked_at = {now}
+ WHERE user_id = {userId} AND realm_id = {realmId}
+ AND client_id = {clientId} AND revoked_at IS NULL`,
+ { userId, realmId, clientId, now }
+ );
+ return result.changes;
+}
+
+export function consentStatus({ client, user, realm, consent, scope }) {
+ if (client?.system_client) {
+ return { required: false, autoGrant: false, reason: 'system', consent: null };
+ }
+ if (!client || !realm) {
+ return { required: true, autoGrant: false, reason: 'context', consent: null };
+ }
+
+ const homeRealm = user?.home_realm_id === realm.id;
+ if (client.consent_mode === 'trusted' && homeRealm) {
+ if (consent?.revoked_at) {
+ return { required: true, autoGrant: false, reason: 'revoked', consent };
+ }
+ return { required: false, autoGrant: true, reason: 'trusted', consent };
+ }
+
+ if (!consent || consent.revoked_at) {
+ return {
+ required: true,
+ autoGrant: false,
+ reason: consent?.revoked_at ? 'revoked' : 'missing',
+ consent,
+ };
+ }
+ if (consent.granted_via !== 'user') {
+ return { required: true, autoGrant: false, reason: 'trusted_grant', consent };
+ }
+ if (!scopesCovered(consent.scopes, scope)) {
+ return { required: true, autoGrant: false, reason: 'scopes', consent };
+ }
+
+ return { required: false, autoGrant: false, reason: 'granted', consent };
+}
diff --git a/server/src/lib/oidc/clients.js b/server/src/lib/oidc/clients.js
@@ -59,7 +59,7 @@ export async function getClient(db, clientId) {
const row = await db.get(
`SELECT id, client_id, name, redirect_uris, scopes, access_mode, enabled,
client_secret_hash, token_endpoint_auth_method, require_pkce,
- post_logout_redirect_uris, branding
+ post_logout_redirect_uris, branding, consent_mode
FROM oidc_clients
WHERE client_id = {clientId}`,
{ clientId }
diff --git a/server/src/lib/oidc/context.js b/server/src/lib/oidc/context.js
@@ -74,6 +74,7 @@ export function endpointUrls(context) {
openid_configuration: `${base}/openid-configuration`,
login: `${base}/login`,
authorize: `${base}/authorize`,
+ consent: `${base}/consent`,
token: `${base}/token`,
userinfo: `${base}/userinfo`,
jwks: `${base}/jwks`,
diff --git a/server/test/http.test.js b/server/test/http.test.js
@@ -204,6 +204,27 @@ function activeSessionPublicId(env, cookie) {
});
}
+function clearConsent(env, { username, realm, clientId }) {
+ withSystemDatabase(env, (database) => {
+ database
+ .prepare(
+ `DELETE FROM client_consents
+ WHERE user_id = (SELECT id FROM users WHERE username = ?)
+ AND client_id = ?
+ AND realm_id = (SELECT id FROM realms WHERE slug = ?)`
+ )
+ .run(username, clientId, realm);
+ });
+}
+
+function setConsentMode(env, { realm, clientId, mode }) {
+ withRealmDatabase(env, realm, (database) => {
+ database
+ .prepare('UPDATE oidc_clients SET consent_mode = ? WHERE client_id = ?')
+ .run(mode, clientId);
+ });
+}
+
function withRealmDatabase(env, slug, fn) {
const system = new DatabaseSync(env.AUTH_DATABASE_PATH);
try {
@@ -247,6 +268,36 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => {
const globex = (options = {}) => request(port, { host: `globex.localhost:${port}`, ...options });
const app = (options = {}) => request(port, { host: `app.acme.localhost:${port}`, ...options });
+ async function completeAuthorization(requester, { path, cookie, clientId }) {
+ let response = await requester({ path, cookie });
+ let jar = cookie || '';
+
+ for (let attempt = 0; attempt < 2; attempt += 1) {
+ if (response.status !== 302) break;
+ const location = locationQuery(response);
+ if (!location.pathname.endsWith('/consent')) break;
+
+ jar = mergeCookies(jar, response);
+ const consent = await requester({
+ path: `/api/v1/consent?client_id=${encodeURIComponent(clientId)}`,
+ cookie: jar,
+ });
+ assert.equal(consent.status, 200);
+ assert.deepEqual(consent.json.client.id, clientId);
+
+ const allow = await requester({
+ method: 'POST',
+ path: '/api/v1/consent',
+ body: { client_id: clientId, decision: 'allow' },
+ cookie: jar,
+ });
+ assert.equal(allow.status, 200);
+ response = await requester({ path: path.split('?')[0], cookie: jar });
+ }
+
+ return { response, cookie: jar };
+ }
+
async function accessToken(
requester,
{ clientId, identifier, redirectUri, scope = 'openid profile' }
@@ -269,12 +320,13 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => {
assert.equal(login.status, 200);
jar = mergeCookies(jar, login);
- const second = await requester({
+ const completed = await completeAuthorization(requester, {
path: authorizePath.split('?')[0],
cookie: jar,
+ clientId,
});
- assert.equal(second.status, 302);
- const code = locationQuery(second).searchParams.get('code');
+ assert.equal(completed.response.status, 302);
+ const code = locationQuery(completed.response).searchParams.get('code');
assert.ok(code);
const tokenResponse = await requester({
@@ -292,7 +344,7 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => {
return {
access_token: tokenResponse.json.access_token,
refresh_token: tokenResponse.json.refresh_token,
- cookie: jar,
+ cookie: completed.cookie,
};
}
@@ -572,9 +624,13 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => {
assert.equal(selected.json.pending_auth_request, true);
assert.equal(selected.json.user.username, 'alice');
- const second = await app({ path: authorizePath, cookie: jar });
- assert.equal(second.status, 302);
- const redirected = locationQuery(second);
+ const completed = await completeAuthorization(app, {
+ path: authorizePath,
+ cookie: jar,
+ clientId: 'internal-app',
+ });
+ assert.equal(completed.response.status, 302);
+ const redirected = locationQuery(completed.response);
assert.equal(redirected.searchParams.get('state'), 'state-select');
const code = redirected.searchParams.get('code');
assert.ok(code);
@@ -617,9 +673,13 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => {
`&redirect_uri=${encodeURIComponent(redirectUri)}&scope=openid%20email` +
`&state=state-revoked&code_challenge=${challenge}&code_challenge_method=S256`;
- const first = await acme({ path: authorizePath, cookie: jar });
- assert.equal(first.status, 302);
- assert.ok(locationQuery(first).searchParams.get('code'));
+ const completed = await completeAuthorization(acme, {
+ path: authorizePath,
+ cookie: jar,
+ clientId: 'internal-app',
+ });
+ assert.equal(completed.response.status, 302);
+ assert.ok(locationQuery(completed.response).searchParams.get('code'));
const sessionId = activeSessionId(env, jar);
const revokedAt = Date.now();
@@ -651,9 +711,13 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => {
assert.equal(relogin.json.pending_auth_request, true);
jar = mergeCookies(jar, relogin);
- const second = await acme({ path: authorizePath, cookie: jar });
- assert.equal(second.status, 302);
- const code = locationQuery(second).searchParams.get('code');
+ const second = await completeAuthorization(acme, {
+ path: authorizePath,
+ cookie: jar,
+ clientId: 'internal-app',
+ });
+ assert.equal(second.response.status, 302);
+ const code = locationQuery(second.response).searchParams.get('code');
assert.ok(code);
const binding = withSystemDatabase(env, (database) =>
@@ -722,9 +786,13 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => {
assert.equal(selected.status, 200);
assert.equal(selected.json.pending_auth_request, true);
- const authorized = await acme({ path: authorizePath, cookie: jar });
- assert.equal(authorized.status, 302);
- assert.ok(locationQuery(authorized).searchParams.get('code'));
+ const authorized = await completeAuthorization(acme, {
+ path: authorizePath,
+ cookie: jar,
+ clientId: 'internal-app',
+ });
+ assert.equal(authorized.response.status, 302);
+ assert.ok(locationQuery(authorized.response).searchParams.get('code'));
const sessionId = activeSessionId(env, jar);
withSystemDatabase(env, (database) => {
@@ -877,9 +945,13 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => {
assert.equal(login.json.pending_auth_request, true);
jar = mergeCookies(jar, login);
- const second = await app({ path: authorizePath, cookie: jar });
- assert.equal(second.status, 302);
- const redirected = locationQuery(second);
+ const second = await completeAuthorization(app, {
+ path: authorizePath,
+ cookie: jar,
+ clientId: 'internal-app',
+ });
+ assert.equal(second.response.status, 302);
+ const redirected = locationQuery(second.response);
assert.equal(redirected.origin + redirected.pathname, redirectUri);
assert.equal(redirected.searchParams.get('state'), 'state-1');
const code = redirected.searchParams.get('code');
@@ -959,9 +1031,13 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => {
assert.equal(login.json.pending_auth_request, true);
jar = mergeCookies(jar, login);
- const second = await identity({ path: authorizePath, cookie: jar });
- assert.equal(second.status, 302);
- const redirected = locationQuery(second);
+ const second = await completeAuthorization(identity, {
+ path: authorizePath,
+ cookie: jar,
+ clientId: 'internal-app',
+ });
+ assert.equal(second.response.status, 302);
+ const redirected = locationQuery(second.response);
assert.equal(redirected.searchParams.get('state'), 'state-canonical');
const code = redirected.searchParams.get('code');
assert.ok(code);
@@ -1022,9 +1098,13 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => {
assert.equal(login.json.pending_auth_request, true);
jar = mergeCookies(jar, login);
- const second = await acme({ path: authorizePath, cookie: jar });
- assert.equal(second.status, 302);
- const code = locationQuery(second).searchParams.get('code');
+ const second = await completeAuthorization(acme, {
+ path: authorizePath,
+ cookie: jar,
+ clientId: 'acme-public-app',
+ });
+ assert.equal(second.response.status, 302);
+ const code = locationQuery(second.response).searchParams.get('code');
assert.ok(code);
const tokenResponse = await acme({
@@ -1041,6 +1121,365 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => {
assert.equal(tokenResponse.status, 200);
});
+ await t.test('remembered consent prompts once and can be denied', async () => {
+ clearConsent(env, { username: 'alice', realm: 'acme', clientId: 'internal-app' });
+
+ const login = await acme({
+ method: 'POST',
+ path: '/api/v1/login/password',
+ body: { client_id: 'internal-app', identifier: 'alice@acme.test', password: 'demo' },
+ });
+ let jar = mergeCookies('', login);
+
+ const { verifier, challenge } = pkce();
+ const redirectUri = `${origin('app.acme.localhost')}/callback`;
+ const authorizePath =
+ `/oidc/internal-app/authorize?response_type=code&client_id=internal-app` +
+ `&redirect_uri=${encodeURIComponent(redirectUri)}&scope=openid%20email` +
+ `&state=consent-once&code_challenge=${challenge}&code_challenge_method=S256`;
+
+ const prompt = await acme({ path: authorizePath, cookie: jar });
+ assert.equal(prompt.status, 302);
+ assert.equal(locationQuery(prompt).pathname, '/oidc/internal-app/consent');
+ jar = mergeCookies(jar, prompt);
+
+ const request = await acme({
+ path: '/api/v1/consent?client_id=internal-app',
+ cookie: jar,
+ });
+ assert.equal(request.status, 200);
+ assert.equal(request.json.client.id, 'internal-app');
+ assert.equal(request.json.user.username, 'alice');
+ assert.ok(request.json.scopes.includes('email'));
+
+ const allow = await acme({
+ method: 'POST',
+ path: '/api/v1/consent',
+ body: { client_id: 'internal-app', decision: 'allow' },
+ cookie: jar,
+ });
+ assert.equal(allow.status, 200);
+ assert.equal(new URL(allow.json.redirect).pathname, '/oidc/internal-app/authorize');
+
+ const approved = await acme({ path: authorizePath.split('?')[0], cookie: jar });
+ assert.equal(approved.status, 302);
+ assert.ok(locationQuery(approved).searchParams.get('code'));
+
+ const stored = withSystemDatabase(env, (database) =>
+ database
+ .prepare(
+ `SELECT scopes, granted_via, revoked_at
+ FROM client_consents
+ WHERE user_id = (SELECT id FROM users WHERE username = 'alice')
+ AND client_id = 'internal-app'
+ AND realm_id = (SELECT id FROM realms WHERE slug = 'acme')`
+ )
+ .get()
+ );
+ assert.equal(stored.granted_via, 'user');
+ assert.equal(stored.revoked_at, null);
+ assert.ok(stored.scopes.includes('email'));
+
+ const repeat = pkce();
+ const repeatPath =
+ `/oidc/internal-app/authorize?response_type=code&client_id=internal-app` +
+ `&redirect_uri=${encodeURIComponent(redirectUri)}&scope=openid%20email` +
+ `&state=consent-repeat&code_challenge=${repeat.challenge}&code_challenge_method=S256`;
+ const direct = await acme({ path: repeatPath, cookie: jar });
+ assert.equal(direct.status, 302);
+ assert.ok(locationQuery(direct).searchParams.get('code'));
+
+ clearConsent(env, { username: 'alice', realm: 'acme', clientId: 'internal-app' });
+ const denied = pkce();
+ const denyPath =
+ `/oidc/internal-app/authorize?response_type=code&client_id=internal-app` +
+ `&redirect_uri=${encodeURIComponent(redirectUri)}&scope=openid%20email` +
+ `&state=consent-deny&code_challenge=${denied.challenge}&code_challenge_method=S256`;
+ const denyPrompt = await acme({ path: denyPath, cookie: jar });
+ assert.equal(locationQuery(denyPrompt).pathname, '/oidc/internal-app/consent');
+ jar = mergeCookies(jar, denyPrompt);
+
+ const deny = await acme({
+ method: 'POST',
+ path: '/api/v1/consent',
+ body: { client_id: 'internal-app', decision: 'deny' },
+ cookie: jar,
+ });
+ assert.equal(deny.status, 200);
+ const deniedRedirect = new URL(deny.json.redirect);
+ assert.equal(deniedRedirect.searchParams.get('error'), 'access_denied');
+ assert.equal(deniedRedirect.searchParams.get('state'), 'consent-deny');
+
+ const missing = await acme({
+ path: '/api/v1/consent?client_id=internal-app',
+ cookie: jar,
+ });
+ assert.equal(missing.status, 400);
+ });
+
+ await t.test('consent scope upgrades require a new prompt', async () => {
+ clearConsent(env, { username: 'alice', realm: 'acme', clientId: 'internal-app' });
+
+ const login = await acme({
+ method: 'POST',
+ path: '/api/v1/login/password',
+ body: { client_id: 'internal-app', identifier: 'alice@acme.test', password: 'demo' },
+ });
+ let jar = mergeCookies('', login);
+ const redirectUri = `${origin('app.acme.localhost')}/callback`;
+
+ const base = pkce();
+ const basePath =
+ `/oidc/internal-app/authorize?response_type=code&client_id=internal-app` +
+ `&redirect_uri=${encodeURIComponent(redirectUri)}&scope=openid%20profile` +
+ `&state=scope-base&code_challenge=${base.challenge}&code_challenge_method=S256`;
+ const approved = await completeAuthorization(acme, {
+ path: basePath,
+ cookie: jar,
+ clientId: 'internal-app',
+ });
+ jar = approved.cookie;
+ assert.ok(locationQuery(approved.response).searchParams.get('code'));
+
+ const upgrade = pkce();
+ const upgradePath =
+ `/oidc/internal-app/authorize?response_type=code&client_id=internal-app` +
+ `&redirect_uri=${encodeURIComponent(redirectUri)}&scope=openid%20profile%20email` +
+ `&state=scope-upgrade&code_challenge=${upgrade.challenge}&code_challenge_method=S256`;
+ const prompt = await acme({ path: upgradePath, cookie: jar });
+ assert.equal(prompt.status, 302);
+ assert.equal(locationQuery(prompt).pathname, '/oidc/internal-app/consent');
+ });
+
+ await t.test('trusted clients skip consent for home users but guests still prompt', async () => {
+ setConsentMode(env, { realm: 'acme', clientId: 'acme-members-app', mode: 'trusted' });
+ clearConsent(env, { username: 'alice', realm: 'acme', clientId: 'acme-members-app' });
+ try {
+ const login = await acme({
+ method: 'POST',
+ path: '/api/v1/login/password',
+ body: {
+ client_id: 'acme-members-app',
+ identifier: 'alice@acme.test',
+ password: 'demo',
+ },
+ });
+ const jar = mergeCookies('', login);
+ const home = pkce();
+ const homePath =
+ `/oidc/acme-members-app/authorize?response_type=code&client_id=acme-members-app` +
+ `&redirect_uri=${encodeURIComponent(`${origin('members.localhost')}/callback`)}` +
+ `&scope=openid%20email&state=trusted-home` +
+ `&code_challenge=${home.challenge}&code_challenge_method=S256`;
+ const direct = await acme({ path: homePath, cookie: jar });
+ assert.equal(direct.status, 302);
+ assert.ok(locationQuery(direct).searchParams.get('code'));
+
+ const stored = withSystemDatabase(env, (database) =>
+ database
+ .prepare(
+ `SELECT granted_via
+ FROM client_consents
+ WHERE user_id = (SELECT id FROM users WHERE username = 'alice')
+ AND client_id = 'acme-members-app'
+ AND realm_id = (SELECT id FROM realms WHERE slug = 'acme')`
+ )
+ .get()
+ );
+ assert.equal(stored.granted_via, 'trusted');
+
+ setConsentMode(env, {
+ realm: 'acme',
+ clientId: 'acme-members-app',
+ mode: 'remembered',
+ });
+ const changed = pkce();
+ const changedPath =
+ `/oidc/acme-members-app/authorize?response_type=code&client_id=acme-members-app` +
+ `&redirect_uri=${encodeURIComponent(`${origin('members.localhost')}/callback`)}` +
+ `&scope=openid%20email&state=trusted-changed` +
+ `&code_challenge=${changed.challenge}&code_challenge_method=S256`;
+ const prompt = await acme({ path: changedPath, cookie: jar });
+ assert.equal(prompt.status, 302);
+ assert.equal(locationQuery(prompt).pathname, '/oidc/acme-members-app/consent');
+ } finally {
+ setConsentMode(env, {
+ realm: 'acme',
+ clientId: 'acme-members-app',
+ mode: 'remembered',
+ });
+ clearConsent(env, {
+ username: 'alice',
+ realm: 'acme',
+ clientId: 'acme-members-app',
+ });
+ }
+
+ setConsentMode(env, { realm: 'acme', clientId: 'acme-public-app', mode: 'trusted' });
+ clearConsent(env, {
+ username: 'contractor',
+ realm: 'acme',
+ clientId: 'acme-public-app',
+ });
+ try {
+ const guest = pkce();
+ const guestPath =
+ `/oidc/acme-public-app/authorize?response_type=code&client_id=acme-public-app` +
+ `&redirect_uri=${encodeURIComponent(`${origin('public.localhost')}/callback`)}` +
+ `&scope=openid%20email&state=trusted-guest` +
+ `&code_challenge=${guest.challenge}&code_challenge_method=S256`;
+ const first = await acme({ path: guestPath });
+ let jar = mergeCookies('', first);
+ const login = await acme({
+ method: 'POST',
+ path: '/api/v1/login/password',
+ body: {
+ client_id: 'acme-public-app',
+ identifier: 'contractor@personal.test',
+ password: 'demo',
+ },
+ cookie: jar,
+ });
+ assert.equal(login.status, 200);
+ assert.equal(login.json.pending_auth_request, true);
+ jar = mergeCookies(jar, login);
+
+ const prompt = await acme({ path: guestPath, cookie: jar });
+ assert.equal(prompt.status, 302);
+ assert.equal(locationQuery(prompt).pathname, '/oidc/acme-public-app/consent');
+ } finally {
+ setConsentMode(env, {
+ realm: 'acme',
+ clientId: 'acme-public-app',
+ mode: 'remembered',
+ });
+ clearConsent(env, {
+ username: 'contractor',
+ realm: 'acme',
+ clientId: 'acme-public-app',
+ });
+ }
+ });
+
+ await t.test('client-host account shows and revokes current app consent', async () => {
+ clearConsent(env, { username: 'alice', realm: 'acme', clientId: 'internal-app' });
+
+ const login = await app({
+ method: 'POST',
+ path: '/api/v1/login/password',
+ body: { client_id: 'internal-app', identifier: 'alice@acme.test', password: 'demo' },
+ });
+ let jar = mergeCookies('', login);
+ const redirectUri = `${origin('app.acme.localhost')}/callback`;
+ const { challenge } = pkce();
+ const authorizePath =
+ `/oidc/authorize?response_type=code&client_id=internal-app` +
+ `&redirect_uri=${encodeURIComponent(redirectUri)}&scope=openid%20email` +
+ `&state=client-consent&code_challenge=${challenge}&code_challenge_method=S256`;
+
+ const prompt = await app({ path: authorizePath, cookie: jar });
+ assert.equal(prompt.status, 302);
+ assert.equal(locationQuery(prompt).pathname, '/oidc/consent');
+ jar = mergeCookies(jar, prompt);
+
+ const allow = await app({
+ method: 'POST',
+ path: '/api/v1/consent',
+ body: { client_id: 'internal-app', decision: 'allow' },
+ cookie: jar,
+ });
+ assert.equal(allow.status, 200);
+ const approved = await app({ path: authorizePath.split('?')[0], cookie: jar });
+ assert.ok(locationQuery(approved).searchParams.get('code'));
+
+ const current = await app({
+ path: '/api/v1/account/clients/internal-app/consent',
+ cookie: jar,
+ });
+ assert.equal(current.status, 200);
+ assert.equal(current.json.active, true);
+ assert.equal(current.json.client.id, 'internal-app');
+ assert.equal(current.json.account_url, `${publicUrl}/app/account`);
+
+ const wrongClient = await app({
+ path: '/api/v1/account/clients/acme-members-app/consent',
+ cookie: jar,
+ });
+ assert.equal(wrongClient.status, 404);
+
+ const revoked = await app({
+ method: 'DELETE',
+ path: '/api/v1/account/clients/internal-app/consent',
+ cookie: jar,
+ });
+ assert.equal(revoked.status, 200);
+ assert.equal(revoked.json.ok, true);
+ assert.equal(revoked.json.active, false);
+
+ const session = await app({ path: '/api/v1/session', cookie: jar });
+ assert.equal(session.status, 200);
+
+ const next = pkce();
+ const nextPath =
+ `/oidc/authorize?response_type=code&client_id=internal-app` +
+ `&redirect_uri=${encodeURIComponent(redirectUri)}&scope=openid%20email` +
+ `&state=client-revoked&code_challenge=${next.challenge}&code_challenge_method=S256`;
+ const reprompt = await app({ path: nextPath, cookie: jar });
+ assert.equal(reprompt.status, 302);
+ assert.equal(locationQuery(reprompt).pathname, '/oidc/consent');
+ });
+
+ await t.test('revoking consent after authorization blocks the code exchange', async () => {
+ clearConsent(env, { username: 'alice', realm: 'acme', clientId: 'internal-app' });
+
+ const login = await acme({
+ method: 'POST',
+ path: '/api/v1/login/password',
+ body: { client_id: 'internal-app', identifier: 'alice@acme.test', password: 'demo' },
+ });
+ const jar = mergeCookies('', login);
+ const { verifier, challenge } = pkce();
+ const redirectUri = `${origin('app.acme.localhost')}/callback`;
+ const authorizePath =
+ `/oidc/internal-app/authorize?response_type=code&client_id=internal-app` +
+ `&redirect_uri=${encodeURIComponent(redirectUri)}&scope=openid%20email` +
+ `&state=revoked-code&code_challenge=${challenge}&code_challenge_method=S256`;
+
+ const approved = await completeAuthorization(acme, {
+ path: authorizePath,
+ cookie: jar,
+ clientId: 'internal-app',
+ });
+ const code = locationQuery(approved.response).searchParams.get('code');
+ assert.ok(code);
+
+ withSystemDatabase(env, (database) => {
+ database
+ .prepare(
+ `UPDATE client_consents
+ SET revoked_at = ?
+ WHERE user_id = (SELECT id FROM users WHERE username = 'alice')
+ AND client_id = 'internal-app'
+ AND realm_id = (SELECT id FROM realms WHERE slug = 'acme')`
+ )
+ .run(Date.now());
+ });
+
+ const tokenResponse = await acme({
+ method: 'POST',
+ path: '/oidc/internal-app/token',
+ form: {
+ grant_type: 'authorization_code',
+ code,
+ redirect_uri: redirectUri,
+ client_id: 'internal-app',
+ code_verifier: verifier,
+ },
+ });
+ assert.equal(tokenResponse.status, 400);
+ assert.equal(tokenResponse.json.error, 'invalid_grant');
+ });
+
await t.test('system admins can use the admin client on the canonical host', async () => {
const admin = await adminToken();
assert.ok(admin.access_token);
@@ -1588,8 +2027,12 @@ test('HTTP realm, login, OIDC and logout flows', async (t) => {
cookie: jar,
});
jar = mergeCookies(jar, login);
- const second = await acme({ path: authorizePath, cookie: jar });
- const code = locationQuery(second).searchParams.get('code');
+ const second = await completeAuthorization(acme, {
+ path: authorizePath,
+ cookie: jar,
+ clientId: 'confidential-app',
+ });
+ const code = locationQuery(second.response).searchParams.get('code');
const tokenResponse = await acme({
method: 'POST',