From b10ac206dc667bde671d7c5d396a78db383a9207 Mon Sep 17 00:00:00 2001 From: Marc Pomar Date: Thu, 19 Nov 2026 09:00:04 +0100 Subject: [PATCH] fix: createClient respeta el `scope` configurado MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit El constructor declaraba `scope` pero nunca asignaba `config.scope`, así que cada /authorize pedía `openid profile email` dijera lo que dijera la app. Con el `audience` de una Api con RBAC el access token salía con `permissions` vacío: auth concede los scopes pedidos ∩ catálogo ∩ roles, y no se pedía ninguno (visto en el admin de reservas de Kirbic). signIn, signInWithOauthConnection, linkOauthConnection y getTokenSilently ya caían en `_scope()`; ahora llega el configurado. buildAuthorizeUrl (y con él authorize y stepUp) también lo usa cuando la llamada no pasa uno; sin scope configurado sigue sin mandar ninguno. El `scopes`/`scope` de cada llamada manda sobre el configurado. La doc decía que el defecto era `profile email` con `openid` siempre añadido: es `openid profile email`, y un scope propio lo sustituye entero. Co-Authored-By: Claude --- src/FaableAuthClient.ts | 7 ++- src/lib/types.ts | 19 ++++-- tests/unit/configScope.test.ts | 105 +++++++++++++++++++++++++++++++++ 3 files changed, 124 insertions(+), 7 deletions(-) create mode 100644 tests/unit/configScope.test.ts diff --git a/src/FaableAuthClient.ts b/src/FaableAuthClient.ts index 8ea27ec..0177b54 100644 --- a/src/FaableAuthClient.ts +++ b/src/FaableAuthClient.ts @@ -379,6 +379,11 @@ export class FaableAuthClient extends Base { (...args) => this._debug(...args) ) this.audience = config.audience + // The default scope of every authorize this client starts. Never assigned + // up to 3.8.0: an SPA asking for an RBAC Api's permissions got a token + // with an empty `permissions` claim (Auth grants requested ∩ catalog ∩ + // role grants), and nothing said why. + this.scope = config.scope this.api = new FaableAuthApi(this.domainUrl, { debug }) @@ -2741,7 +2746,7 @@ export class FaableAuthClient extends Base { options.redirectTo || this.redirectUri || window?.location.origin, response_type: resolveResponseType(options, isBrowser()), audience: options.audience ?? this.audience, - scope: options.scope, + scope: options.scope || this.scope, connection: options.connection, // Space-delimited, per OIDC Core §3.1.2.1. acr_values: Array.isArray(options.acr_values) diff --git a/src/lib/types.ts b/src/lib/types.ts index 5afd92f..f7bf079 100644 --- a/src/lib/types.ts +++ b/src/lib/types.ts @@ -199,12 +199,11 @@ export interface AuthorizationParams { acr_values?: string /** - * The default scope to be used on authentication requests. + * The scope to request, space-separated. * - * This defaults to `profile email` if not set. If you are setting extra scopes and require - * `profile` and `email` to be included then you must include them in the provided scope. - * - * Note: The `openid` scope is **always applied** regardless of this setting. + * It replaces the default (`openid profile email`) instead of adding to it: + * include `openid`, `profile` and `email` yourself when you still want them + * alongside extra scopes such as an Api's permissions. */ scope?: string @@ -441,7 +440,15 @@ export type FaableAuthClientConfig = { clientId: string // Optional - /** Space-separated scopes. Defaults to `openid profile email`. */ + /** + * Default space-separated scope of the authorize requests this client + * starts (`signIn`, `signInWithOauthConnection`, `buildAuthorizeUrl`, + * `getTokenSilently`…); a `scopes`/`scope` passed to a call overrides it. + * Unset, they ask for `openid profile email` (`buildAuthorizeUrl` sends + * none and leaves it to the server). It replaces that default rather than + * extending it, so include `openid profile email` along with extra scopes — + * e.g. the permissions of an RBAC Api set as `audience`. + */ scope?: string /** * Default API audience the access tokens issued for this client should be diff --git a/tests/unit/configScope.test.ts b/tests/unit/configScope.test.ts new file mode 100644 index 0000000..69b1927 --- /dev/null +++ b/tests/unit/configScope.test.ts @@ -0,0 +1,105 @@ +import { beforeEach, describe, expect, it, vi } from 'vitest' +import { FaableAuthClient } from '../../src/FaableAuthClient' +import type { SupportedStorage } from '../../src/lib/types' + +// `createClient({ scope })` es el scope por defecto de cada /authorize. Hasta +// 3.8.0 el constructor no lo asignaba y viajaba siempre `openid profile +// email`: una SPA con `audience` de una Api con RBAC recibía un access token +// con `permissions` vacío (Auth concede pedidos ∩ catálogo ∩ roles). + +const h = vi.hoisted(() => { + const loc = { + href: 'https://app.example.com/admin', + origin: 'https://app.example.com' + } + return { + loc, + fakeWindow: { + location: loc, + history: { state: null, replaceState: () => {} }, + addEventListener: () => {}, + removeEventListener: () => {} + } + } +}) + +vi.mock('../../src/lib/globals', () => ({ + window: h.fakeWindow, + document: {}, + fetch: async () => ({ ok: true, status: 200, json: async () => ({}) }) +})) + +const inMemoryStorage = (): SupportedStorage => { + const store = new Map() + return { + getItem: k => store.get(k) ?? null, + setItem: (k, v) => void store.set(k, v), + removeItem: k => void store.delete(k) + } +} + +const SCOPE = 'openid profile email instances:admin bookings:read' + +const client = (scope?: string) => + new FaableAuthClient({ + domain: 'https://tenant.auth.faable.link', + clientId: 'test-client', + storage: inMemoryStorage(), + autoRefreshToken: false, + audience: 'https://api.example.com', + ...(scope !== undefined ? { scope } : {}) + } as any) + +const authorizeUrl = async ( + auth: FaableAuthClient, + call: 'signIn' | 'signInWithOauthConnection', + scopes?: string +) => { + const { data } = await auth[call]({ + skipBrowserRedirect: true, + ...(scopes ? { scopes } : {}) + }) + return new URL(data!.url!) +} + +beforeEach(() => { + vi.restoreAllMocks() + vi.stubGlobal('document', {}) + vi.stubGlobal('window', h.fakeWindow) +}) + +describe('scope de createClient', () => { + it.each(['signIn', 'signInWithOauthConnection'] as const)( + '%s pide el scope configurado', + async call => { + const url = await authorizeUrl(client(SCOPE), call) + + expect(url.searchParams.get('scope')).toBe(SCOPE) + expect(url.searchParams.get('audience')).toBe('https://api.example.com') + } + ) + + it('el `scopes` de la llamada manda sobre el configurado', async () => { + const url = await authorizeUrl(client(SCOPE), 'signIn', 'openid') + + expect(url.searchParams.get('scope')).toBe('openid') + }) + + it('sin scope configurado sigue pidiendo openid profile email', async () => { + const url = await authorizeUrl(client(), 'signIn') + + expect(url.searchParams.get('scope')).toBe('openid profile email') + }) + + it('buildAuthorizeUrl también usa el scope configurado', () => { + const url = new URL(client(SCOPE).buildAuthorizeUrl()) + + expect(url.searchParams.get('scope')).toBe(SCOPE) + }) + + it('buildAuthorizeUrl sin scope configurado no añade ninguno', () => { + const url = new URL(client().buildAuthorizeUrl()) + + expect(url.searchParams.has('scope')).toBe(false) + }) +})