From 8759cd743df68798893c058ebf97e38c7ed4b5df Mon Sep 17 00:00:00 2001
From: Claude
Date: Sun, 15 Nov 2026 23:14:59 +0000
Subject: [PATCH 1/7] feat(plugin-auth): the environment-access refusal can
carry the host's reason
oidcAuthorizeGate may answer { allowed: false, reason, message } in place of
false. The 403 envelope gains the validated reason and the host's sentence,
the redirect back sends the sentence as error_description plus the
objectstack_error_reason parameter, and the page shows the sentence escaped.
A boolean answer is delivered exactly as before.
Co-Authored-By: Claude
Claude-Session: https://claude.ai/code/session_01QsR2jVPGBoi3MCGoKbW1Hv
---
.../src/auth-manager-before-hook.ts | 24 ++--
.../plugins/plugin-auth/src/auth-manager.ts | 8 +-
.../src/oauth-authorize-refusal.ts | 122 +++++++++++++++++-
3 files changed, 139 insertions(+), 15 deletions(-)
diff --git a/packages/plugins/plugin-auth/src/auth-manager-before-hook.ts b/packages/plugins/plugin-auth/src/auth-manager-before-hook.ts
index 169dbb80e0f..4cfce306432 100644
--- a/packages/plugins/plugin-auth/src/auth-manager-before-hook.ts
+++ b/packages/plugins/plugin-auth/src/auth-manager-before-hook.ts
@@ -69,7 +69,7 @@ import {
LAST_LOCAL_CREDENTIAL_CODE,
LAST_LOCAL_CREDENTIAL_MESSAGE,
} from './last-local-credential.js';
-import { answerRefusedAuthorization } from './oauth-authorize-refusal.js';
+import { answerRefusedAuthorization, gateAnswerRefuses, refusalDetailOf } from './oauth-authorize-refusal.js';
import { refuseRequestNamingDifferentAccounts } from './one-account-per-request.js';
import {
SSO_ONLY_RESET_UNREADABLE_MESSAGE,
@@ -588,19 +588,27 @@ export async function globalBeforeHook(
// D5.1 host contract is `(userId, clientId)` and the control plane
// derives org membership / app assignment from the user itself.
if (actor?.userId) {
- let allowed = true;
+ // The first refusing answer, kept: a boolean `false`, or the host's
+ // refusal object with its reason and sentence.
+ let refusal: { answer: unknown } | undefined;
for (const clientId of clientIds) {
- allowed = await this.config.oidcAuthorizeGate({ userId: actor.userId, clientId });
- if (!allowed) break;
+ const answer: unknown = await this.config.oidcAuthorizeGate({ userId: actor.userId, clientId });
+ if (gateAnswerRefuses(answer)) {
+ refusal = { answer };
+ break;
+ }
}
- if (!allowed) {
+ if (refusal) {
// The refusal, delivered by who is asking (`oauth-authorize-refusal.ts`):
- // the `403` envelope for a fetch or an API client, unchanged; for a
- // browser navigating here, `access_denied` back to the client's
- // REGISTERED `redirect_uri`, or a readable page when there is none.
+ // the `403` envelope for a fetch or an API client; for a browser
+ // navigating here, `access_denied` back to the client's REGISTERED
+ // `redirect_uri`, or a readable page when there is none. A boolean
+ // refusal is answered as it always was; a refusal object adds the
+ // host's validated reason and sentence (`refusalDetailOf`).
return answerRefusedAuthorization(ctx, {
userId: actor.userId,
consoleUrl: this.getConsolePageUrl('/'),
+ detail: refusalDetailOf(refusal.answer),
});
}
}
diff --git a/packages/plugins/plugin-auth/src/auth-manager.ts b/packages/plugins/plugin-auth/src/auth-manager.ts
index 9affdd9d3aa..71a7c2f20d8 100644
--- a/packages/plugins/plugin-auth/src/auth-manager.ts
+++ b/packages/plugins/plugin-auth/src/auth-manager.ts
@@ -321,6 +321,7 @@ import { resolveTurnstileKeys } from './turnstile-sign-up.js';
import { assertTrustedAppSchemes, registeredAppSchemesOf } from './one-time-token-handoff.js';
import type { MintScimConnectionCredentialInput, MintedScimConnectionCredential } from './scim-connection-service.js';
import type { OrganizationBoundaryJudge } from './scim-group-projection.js';
+import type { OidcAuthorizeGateAnswer, OidcAuthorizeGateRefusal } from './oauth-authorize-refusal.js';
/**
* Detect WebContainer (StackBlitz) environment.
@@ -968,8 +969,13 @@ export interface AuthManagerOptions extends Partial {
* may only obtain a code for an env client (`project_`) of an org
* they belong to. Unset (open editions / self-host, where the OP is not a
* multi-tenant issuer) = allow. Host is expected to fail CLOSED on error.
+ *
+ * In place of `false` the gate may answer an {@link OidcAuthorizeGateRefusal}
+ * (`{ allowed: false, reason, message }`) to say why: the refusal then
+ * carries the reason and the host's sentence to the caller
+ * (`oauth-authorize-refusal.ts`). A boolean is answered as it always was.
*/
- oidcAuthorizeGate?: (params: { userId: string; clientId: string }) => boolean | Promise;
+ oidcAuthorizeGate?: (params: { userId: string; clientId: string }) => OidcAuthorizeGateAnswer | Promise;
/**
* The host's own check on `POST /organization/delete`: answer a
diff --git a/packages/plugins/plugin-auth/src/oauth-authorize-refusal.ts b/packages/plugins/plugin-auth/src/oauth-authorize-refusal.ts
index de2843adc01..4ada020e300 100644
--- a/packages/plugins/plugin-auth/src/oauth-authorize-refusal.ts
+++ b/packages/plugins/plugin-auth/src/oauth-authorize-refusal.ts
@@ -60,6 +60,29 @@
* must also accept the URI, as it has the last word at the provider.
*
* Anything else, including any failure to read the client, answers the page.
+ *
+ * ## The host's reason
+ *
+ * The gate may answer a refusal object instead of `false`
+ * ({@link OidcAuthorizeGateRefusal}): a reason code from the host's own closed
+ * set and the sentence the person should read. A boolean is answered exactly
+ * as before, byte for byte, on all three doors. A refusal object adds:
+ *
+ * - the envelope's `reason` beside the unchanged `code`, and the host's
+ * sentence as its `message`;
+ * - on the redirect, the host's sentence as `error_description` and the
+ * reason as {@link OAUTH_REFUSAL_REASON_PARAM}; `error` stays
+ * `access_denied`;
+ * - on the page, the host's sentence, escaped, in place of the fixed one.
+ *
+ * Nothing the host answers is trusted as markup or as a URL fragment. A reason
+ * outside {@link REFUSAL_REASON_PATTERN} is dropped (the refusal stands, with
+ * no reason). A sentence that is not plain text (a control character, an
+ * angle bracket) or is longer than {@link REFUSAL_MESSAGE_MAX_LENGTH} is
+ * replaced by the fixed sentence; on the redirect, a sentence outside the
+ * character set RFC 6749 §4.1.2.1 allows `error_description` (printable ASCII
+ * without `"` and `\`) is replaced by the fixed sentence too, so the client
+ * always receives a conforming value.
*/
import { isPageNavigation } from './one-time-token-handoff.js';
@@ -76,12 +99,86 @@ export const OAUTH_ACCESS_DENIED_ERROR = 'access_denied';
/** The provider's RP-initiated logout, relative to the auth base URL: the page's "switch account". */
export const OAUTH_END_SESSION_PATH = '/oauth2/end-session';
+/**
+ * The redirect parameter that carries the host's reason beside
+ * `error=access_denied`. RFC 6749 §8.2 asks an unregistered extension
+ * parameter to carry a vendor prefix, so it cannot collide with a registered
+ * name or another vendor's (`error_reason` is one some providers already send
+ * with their own values).
+ */
+export const OAUTH_REFUSAL_REASON_PARAM = 'objectstack_error_reason';
+
+/** The shape a host's reason code must have to travel: lower-case letters and `_`, at most 40. */
+export const REFUSAL_REASON_PATTERN = /^[a-z_]{1,40}$/;
+
+/** The longest host sentence that is shown or sent; a longer one is replaced by the fixed sentence. */
+export const REFUSAL_MESSAGE_MAX_LENGTH = 300;
+
+/**
+ * A refusal with the host's reason: what `oidcAuthorizeGate` may answer in
+ * place of `false`. `reason` is a code from the host's own closed set (the
+ * cloud control plane answers `not_member`, `invitation_pending`,
+ * `unavailable`); `message` is the sentence the refused person reads, plain
+ * text.
+ */
+export interface OidcAuthorizeGateRefusal {
+ readonly allowed: false;
+ readonly reason: string;
+ readonly message: string;
+}
+
+/** What the gate may answer: `true` admits, `false` or a refusal object refuses. */
+export type OidcAuthorizeGateAnswer = boolean | OidcAuthorizeGateRefusal;
+
+/** The host's reason and sentence, as validated here; both absent for a boolean refusal. */
+export interface RefusalDetail {
+ /** The reason code, when it has {@link REFUSAL_REASON_PATTERN}'s shape. */
+ readonly reason?: string;
+ /** The host's sentence, when it is plain text within {@link REFUSAL_MESSAGE_MAX_LENGTH}. */
+ readonly message?: string;
+}
+
+/**
+ * Whether a gate answer refuses. A boolean (and any other value) keeps the
+ * truthiness the gate has always been read with; an object refuses only when
+ * it says `allowed: false`.
+ */
+export function gateAnswerRefuses(answer: unknown): boolean {
+ if (answer !== null && typeof answer === 'object') return (answer as { allowed?: unknown }).allowed === false;
+ return !answer;
+}
+
+/** The reason and sentence a refusing gate answer carries, validated; empty for a boolean. */
+export function refusalDetailOf(answer: unknown): RefusalDetail {
+ if (answer === null || typeof answer !== 'object') return {};
+ const { reason, message } = answer as { reason?: unknown; message?: unknown };
+ return {
+ ...(typeof reason === 'string' && REFUSAL_REASON_PATTERN.test(reason) ? { reason } : {}),
+ ...(isPlainSentence(message) ? { message: message.trim() } : {}),
+ };
+}
+
+/** Plain text, one line, no angle brackets, within the length bound. */
+function isPlainSentence(value: unknown): value is string {
+ if (typeof value !== 'string') return false;
+ const text = value.trim();
+ // eslint-disable-next-line no-control-regex
+ return text.length > 0 && text.length <= REFUSAL_MESSAGE_MAX_LENGTH && !/[\u0000-\u001f\u007f<>]/.test(text);
+}
+
+/** RFC 6749 §4.1.2.1: `error_description` is limited to %x20-21 / %x23-5B / %x5D-7E. */
+function isOAuthErrorDescription(value: string): boolean {
+ return /^[\x20\x21\x23-\x5b\x5d-\x7e]*$/.test(value);
+}
+
/** What the gate hands this module beside the request. */
export interface RefusedAuthorizationContext {
/** The refused subject. */
readonly userId: string;
/** The absolute URL of the console's home page: the page's "back to console". */
readonly consoleUrl: string;
+ /** The host's reason and sentence ({@link refusalDetailOf}); absent for a boolean refusal. */
+ readonly detail?: RefusalDetail;
}
const NO_STORE_HEADERS = {
@@ -97,11 +194,13 @@ const NO_STORE_HEADERS = {
*/
export async function answerRefusedAuthorization(ctx: any, refused: RefusedAuthorizationContext): Promise {
const headers: Headers | undefined = ctx?.request?.headers ?? ctx?.headers;
+ const { reason, message } = refused.detail ?? {};
if (!(headers instanceof Headers) || !isPageNavigation(headers)) {
const { APIError } = await import('better-auth/api');
throw new APIError('FORBIDDEN', {
- message: ENV_ACCESS_DENIED_MESSAGE,
+ message: message ?? ENV_ACCESS_DENIED_MESSAGE,
code: ENV_ACCESS_DENIED_CODE,
+ ...(reason ? { reason } : {}),
});
}
@@ -109,7 +208,11 @@ export async function answerRefusedAuthorization(ctx: any, refused: RefusedAutho
if (back) {
const location = new URL(back.redirectUri);
location.searchParams.append('error', OAUTH_ACCESS_DENIED_ERROR);
- location.searchParams.append('error_description', ENV_ACCESS_DENIED_MESSAGE);
+ location.searchParams.append(
+ 'error_description',
+ message && isOAuthErrorDescription(message) ? message : ENV_ACCESS_DENIED_MESSAGE,
+ );
+ if (reason) location.searchParams.append(OAUTH_REFUSAL_REASON_PARAM, reason);
if (back.state !== undefined) location.searchParams.append('state', back.state);
location.searchParams.append('iss', back.issuer);
return new Response(null, {
@@ -119,6 +222,7 @@ export async function answerRefusedAuthorization(ctx: any, refused: RefusedAutho
}
return refusalPage({
+ message,
email: await signedInEmail(ctx, refused.userId),
switchAccountUrl: `${String(ctx?.context?.baseURL ?? '').replace(/\/$/, '')}${OAUTH_END_SESSION_PATH}`,
consoleUrl: refused.consoleUrl,
@@ -180,10 +284,16 @@ function escapeHtml(value: string): string {
}
/** The page a browser sees when no registered `redirect_uri` can carry the refusal. */
-function refusalPage(page: { email?: string; switchAccountUrl: string; consoleUrl: string }): Response {
- const who = page.email
- ? `You are signed in as ${escapeHtml(page.email)}, and this account does not have access to this environment.`
- : 'The account you are signed in with does not have access to this environment.';
+function refusalPage(page: { message?: string; email?: string; switchAccountUrl: string; consoleUrl: string }): Response {
+ const account = page.email
+ ? `You are signed in as ${escapeHtml(page.email)}`
+ : undefined;
+ // The host's sentence says why; the account line still says who is refused.
+ const who = page.message
+ ? `${account ? `${account}. ` : ''}${escapeHtml(page.message)}`
+ : account
+ ? `${account}, and this account does not have access to this environment.`
+ : 'The account you are signed in with does not have access to this environment.';
const html = [
'',
'',
From 62a7a5a6e9dfe111e658357285dae98374c3ec34 Mon Sep 17 00:00:00 2001
From: Claude
Date: Mon, 16 Nov 2026 01:04:09 +0000
Subject: [PATCH 2/7] test(plugin-auth): pin the refusal reason on the
envelope, the redirect and the page
A boolean gate is pinned byte for byte as served at the merge base (CONTROL);
a refusal object's reason and sentence are pinned on each door, a reason
outside [a-z_]{1,40} is dropped, and a sentence that is not plain text within
the bound is replaced by the fixed sentence.
Co-Authored-By: Claude
Claude-Session: https://claude.ai/code/session_01QsR2jVPGBoi3MCGoKbW1Hv
---
.../src/oauth-authorize-refusal.test.ts | 243 +++++++++++++++++-
1 file changed, 241 insertions(+), 2 deletions(-)
diff --git a/packages/plugins/plugin-auth/src/oauth-authorize-refusal.test.ts b/packages/plugins/plugin-auth/src/oauth-authorize-refusal.test.ts
index 7aacabebb34..2d17e0c946e 100644
--- a/packages/plugins/plugin-auth/src/oauth-authorize-refusal.test.ts
+++ b/packages/plugins/plugin-auth/src/oauth-authorize-refusal.test.ts
@@ -15,6 +15,7 @@
* the allowing control mints a code on the very same request.
*/
+import { createHash } from 'node:crypto';
import { describe, it, expect, vi, beforeEach, afterEach, afterAll } from 'vitest';
import { AuthManager } from './auth-manager';
import { createMemoryEngine } from './impersonation-bearer-rotation.test';
@@ -25,6 +26,8 @@ import {
ENV_ACCESS_DENIED_MESSAGE,
OAUTH_ACCESS_DENIED_ERROR,
OAUTH_END_SESSION_PATH,
+ OAUTH_REFUSAL_REASON_PARAM,
+ REFUSAL_MESSAGE_MAX_LENGTH,
} from './oauth-authorize-refusal';
const SECRET = 'test-secret-at-least-32-chars-long-authorize-refusal';
@@ -68,14 +71,16 @@ interface GateCall {
const arrange = async () => {
const engine = createMemoryEngine();
- // `allow` admits every client; `admitted` admits the clients it names.
- const gate = { allow: false, admitted: new Set(), calls: [] as GateCall[] };
+ // `allow` admits every client; `admitted` admits the clients it names;
+ // `answer`, when set, is what the gate answers for every client instead.
+ const gate = { allow: false, admitted: new Set(), calls: [] as GateCall[], answer: undefined as unknown };
const manager = new AuthManager({
secret: SECRET,
baseUrl: ORIGIN,
dataEngine: engine,
oidcAuthorizeGate: (params: GateCall) => {
gate.calls.push({ userId: params.userId, clientId: params.clientId });
+ if (gate.answer !== undefined) return gate.answer;
return gate.allow || gate.admitted.has(params.clientId);
},
} as any);
@@ -600,3 +605,237 @@ describe('the environment-access gate judges every pass that resumes an authoriz
});
}
});
+
+describe("a refused /oauth2/authorize carries the host's reason when the gate answers a refusal object", () => {
+ /** The cloud control plane's answer for a signed-in account that is not a member of the organization. */
+ const NOT_MEMBER = {
+ allowed: false,
+ reason: 'not_member',
+ message: 'You are not a member of Acme Corp. Ask an administrator of Acme Corp to invite you.',
+ } as const;
+
+ type Rig = Awaited>;
+ type Door = 'envelope' | 'redirect' | 'page';
+
+ /** The same refused request, delivered through one door. */
+ const refuse = async (rig: Rig, door: Door): Promise => {
+ const clientId = await rig.register(ENV_CALLBACK, 'web');
+ const res = door === 'envelope'
+ ? await rig.authorize(codeRequest(clientId, ENV_CALLBACK), CONSOLE_FETCH)
+ : door === 'redirect'
+ ? await rig.authorize(codeRequest(clientId, ENV_CALLBACK), NAVIGATION)
+ : await rig.authorize(codeRequest(clientId, 'https://attacker.example/cb'), NAVIGATION);
+ expect(rig.gate.calls).toEqual([{ userId: rig.userId, clientId }]);
+ return res;
+ };
+
+ /** Every byte a door answers with: status, the headers a refusal sets, and the body (or the redirect target). */
+ const bytesOf = async (res: Response) => ({
+ status: res.status,
+ contentType: res.headers.get('content-type'),
+ location: res.headers.get('location'),
+ body: await res.text(),
+ });
+
+ describe('CONTROL: a boolean gate answers byte for byte as before', () => {
+ // The literals below were read off this suite at the merge base, before
+ // the gate could answer anything but a boolean; they hold there and here.
+ const PAGE_SHA256_AT_MERGE_BASE = '60b2309f3a19756c308cd06e4277a3c1c22595c738ed42f15f26c93c1a410c70';
+ const PAGE_SENTENCE = `You are signed in as ${EMAIL}, and this account does not have access to this environment.
`;
+
+ it('the envelope', async () => {
+ const rig = await arrange();
+ const res = await bytesOf(await refuse(rig, 'envelope'));
+ expect(res.status).toBe(403);
+ expect(res.location).toBeNull();
+ expect(JSON.parse(res.body)).toEqual({ code: ENV_ACCESS_DENIED_CODE, message: ENV_ACCESS_DENIED_MESSAGE });
+ });
+
+ it('the redirect', async () => {
+ const rig = await arrange();
+ const res = await bytesOf(await refuse(rig, 'redirect'));
+ expect(res.status).toBe(302);
+ expect(res.body).toBe('');
+ const location = new URL(res.location ?? '');
+ expect(`${location.origin}${location.pathname}`).toBe(ENV_CALLBACK);
+ expect([...location.searchParams]).toEqual([
+ ['error', OAUTH_ACCESS_DENIED_ERROR],
+ ['error_description', ENV_ACCESS_DENIED_MESSAGE],
+ ['state', STATE],
+ ['iss', ISSUER],
+ ]);
+ });
+
+ it('the page', async () => {
+ const rig = await arrange();
+ const res = await bytesOf(await refuse(rig, 'page'));
+ expect(res.status).toBe(403);
+ expect(res.contentType).toBe('text/html; charset=utf-8');
+ expect(res.body).toContain(PAGE_SENTENCE);
+ expect(createHash('sha256').update(res.body).digest('hex')).toBe(PAGE_SHA256_AT_MERGE_BASE);
+ });
+
+ });
+
+ it('a refusal object whose reason and sentence are both refused answers the same bytes as `false`, on every door', async () => {
+ for (const door of ['envelope', 'redirect', 'page'] as const) {
+ const boolean = await arrange();
+ const object = await arrange();
+ object.gate.answer = { allowed: false, reason: 'Not-A-Code', message: 'no' };
+ expect(await bytesOf(await refuse(object, door)), door).toEqual(await bytesOf(await refuse(boolean, door)));
+ }
+ });
+
+ it('the envelope keeps code ENV_ACCESS_DENIED and gains the reason; the message is the host\'s sentence', async () => {
+ const rig = await arrange();
+ rig.gate.answer = NOT_MEMBER;
+
+ const res = await refuse(rig, 'envelope');
+
+ expect(res.status).toBe(403);
+ expect(await res.json()).toEqual({ code: ENV_ACCESS_DENIED_CODE, message: NOT_MEMBER.message, reason: 'not_member' });
+ });
+
+ it('the redirect keeps error=access_denied, sends the host\'s sentence as error_description and the reason as its own parameter', async () => {
+ const rig = await arrange();
+ rig.gate.answer = NOT_MEMBER;
+
+ const res = await refuse(rig, 'redirect');
+
+ expect(res.status).toBe(302);
+ const location = new URL(res.headers.get('location') ?? '');
+ expect(`${location.origin}${location.pathname}`).toBe(ENV_CALLBACK);
+ expect([...location.searchParams]).toEqual([
+ ['error', OAUTH_ACCESS_DENIED_ERROR],
+ ['error_description', NOT_MEMBER.message],
+ [OAUTH_REFUSAL_REASON_PARAM, 'not_member'],
+ ['state', STATE],
+ ['iss', ISSUER],
+ ]);
+ expect(location.searchParams.has('code')).toBe(false);
+ });
+
+ it('the page shows the host\'s sentence, escaped, beside the signed-in account', async () => {
+ const rig = await arrange();
+ rig.gate.answer = { ...NOT_MEMBER, message: 'You are not a member of "Smith & Sons". Ask them to invite you.' };
+
+ const res = await refuse(rig, 'page');
+
+ expect(res.status).toBe(403);
+ const html = await res.text();
+ expect(html).toContain(
+ `You are signed in as ${EMAIL}. You are not a member of "Smith & Sons". Ask them to invite you.
`,
+ );
+ expect(html).not.toContain('does not have access to this environment.
');
+ });
+
+ const refusedReasons: ReadonlyArray<[string, unknown]> = [
+ ['upper case', 'NOT_MEMBER'],
+ ['a digit', 'not_member2'],
+ ['a hyphen', 'not-member'],
+ ['markup', '