From 34649b86b5f0e7e2a5819f1e4f0f249e2a43a432 Mon Sep 17 00:00:00 2001 From: Simon Date: Fri, 13 Nov 2026 15:56:23 +0100 Subject: [PATCH 1/3] fix: store and return engine auth context --- src/hooks/useOID4VCIFlow.ts | 16 +++-- .../OIDFlowWebSocketTransport.test.ts | 65 +++++++++++++++++++ .../transports/OIDFlowWebSocketTransport.ts | 7 ++ src/lib/openid-flow/types/OID4VCITypes.ts | 9 +++ .../OpenIDFlowCallback.test.tsx | 32 +++++++++ .../OpenIDFlowCallback/OpenIDFlowCallback.tsx | 11 +++- 6 files changed, 134 insertions(+), 6 deletions(-) diff --git a/src/hooks/useOID4VCIFlow.ts b/src/hooks/useOID4VCIFlow.ts index 9c7db861..d58f458d 100644 --- a/src/hooks/useOID4VCIFlow.ts +++ b/src/hooks/useOID4VCIFlow.ts @@ -36,7 +36,7 @@ export interface UseOID4VCIFlowReturn { /** * Continue flow with authorization code (after redirect) */ - handleAuthorizationResponse: (authCode: string, state?: string) => Promise; + handleAuthorizationResponse: (authCode: string, state?: string, iss?: string) => Promise; /** * Continue flow with pre-authorized code and optional TX code */ @@ -191,7 +191,7 @@ export function useOID4VCIFlow(options: UseOID4VCIFlowOptions = {}): UseOID4VCIF assertNotAborted(); - if (result.authorizationUrl && result.codeVerifier) { + if (result.authorizationUrl && result.authorizationContext) { // Persist the flow's client-held key (+ its WIA) so the // post-redirect token leg reuses it: the issuer binds the // WIA to the issuance session, so PAR and token must carry @@ -203,6 +203,7 @@ export function useOID4VCIFlow(options: UseOID4VCIFlowOptions = {}): UseOID4VCIF flowId: result.transactionId, codeVerifier: result.codeVerifier, state: result.issuerState, + authorizationContext: result.authorizationContext, credentialOffer: result.credentialOffer ? JSON.stringify(result.credentialOffer) : undefined, @@ -261,7 +262,8 @@ export function useOID4VCIFlow(options: UseOID4VCIFlowOptions = {}): UseOID4VCIF */ const handleAuthorizationResponse = useCallback(async ( authCode: string, - state?: string + state?: string, + iss?: string, ): Promise => { setIsLoading(true); setError(null); @@ -290,6 +292,9 @@ export function useOID4VCIFlow(options: UseOID4VCIFlowOptions = {}): UseOID4VCIF credentialOffer: storedFlow?.credentialOffer, authorizationCode: authCode, codeVerifier: storedFlow?.codeVerifier, + state, + authorizationResponseIssuer: iss, + authorizationContext: storedFlow?.authorizationContext, redirectUri: OPENID4VCI_REDIRECT_URI, }); @@ -537,6 +542,7 @@ export interface PendingOID4VCIFlow { flowId?: string; codeVerifier?: string; state?: string; + authorizationContext?: string; credentialOffer?: string; clientAuthKey?: SerializedClientAuthMaterial; timestamp: number; @@ -560,8 +566,8 @@ function loadAndClearPendingFlow(): PendingOID4VCIFlow | null { try { const flow = JSON.parse(stored) as PendingOID4VCIFlow; - // Expire after 10 minutes - if (Date.now() - flow.timestamp > 10 * 60 * 1000) { + // Matches the backend's authorization_context lifetime + if (Date.now() - flow.timestamp > 5 * 60 * 1000) { return null; } return flow; diff --git a/src/lib/openid-flow/__tests__/OIDFlowWebSocketTransport.test.ts b/src/lib/openid-flow/__tests__/OIDFlowWebSocketTransport.test.ts index a63c69fb..d7b7363e 100644 --- a/src/lib/openid-flow/__tests__/OIDFlowWebSocketTransport.test.ts +++ b/src/lib/openid-flow/__tests__/OIDFlowWebSocketTransport.test.ts @@ -221,6 +221,8 @@ describe('OIDFlowWebSocketTransport', () => { const flowPromise = transport.startOID4VCIFlow({ authorizationCode: 'auth-code-123', codeVerifier: 'verifier-abc', + state: 'state-xyz', + authorizationResponseIssuer: 'https://as.example.com', }); await vi.waitFor(() => { @@ -232,6 +234,8 @@ describe('OIDFlowWebSocketTransport', () => { expect(sentMessage.action).toBe('authorization_complete'); expect(sentMessage.payload.code).toBe('auth-code-123'); expect(sentMessage.payload.code_verifier).toBe('verifier-abc'); + expect(sentMessage.payload.state).toBe('state-xyz'); + expect(sentMessage.payload.iss).toBe('https://as.example.com'); // Respond with credential sockets[0].simulateMessage({ @@ -244,6 +248,67 @@ describe('OIDFlowWebSocketTransport', () => { expect(result.success).toBe(true); }); + it('should resume a same-tab redirect with state, iss and authorization_context', async () => { + const transport = new OIDFlowWebSocketTransport(wsUrl, authToken); + await transport.connect(); + + const flowPromise = transport.startOID4VCIFlow({ + credentialOffer: '{"credential_issuer":"https://issuer.example.com"}', + authorizationCode: 'auth-code-123', + codeVerifier: 'verifier-abc', + state: 'state-xyz', + authorizationResponseIssuer: 'https://as.example.com', + authorizationContext: 'signed.context.jwt', + redirectUri: 'https://wallet.example.com/cb', + }); + + await vi.waitFor(() => { + expect(sockets[0].sentMessages.length).toBeGreaterThan(1); + }); + + const sentMessage = JSON.parse(sockets[0].sentMessages[1]); + expect(sentMessage.type).toBe('flow_start'); + expect(sentMessage.auth_code).toBe('auth-code-123'); + expect(sentMessage.state).toBe('state-xyz'); + expect(sentMessage.iss).toBe('https://as.example.com'); + expect(sentMessage.authorization_context).toBe('signed.context.jwt'); + + sockets[0].simulateMessage({ + flow_id: sentMessage.flow_id, + type: 'flow_complete', + credential: 'eyJ...', + }); + + const result = await flowPromise; + expect(result.success).toBe(true); + }); + + it('should omit iss on resume when the callback had none', async () => { + const transport = new OIDFlowWebSocketTransport(wsUrl, authToken); + await transport.connect(); + + const flowPromise = transport.startOID4VCIFlow({ + credentialOffer: '{"credential_issuer":"https://issuer.example.com"}', + authorizationCode: 'auth-code-123', + state: 'state-xyz', + authorizationContext: 'signed.context.jwt', + }); + + await vi.waitFor(() => { + expect(sockets[0].sentMessages.length).toBeGreaterThan(1); + }); + + const sentMessage = JSON.parse(sockets[0].sentMessages[1]); + expect(sentMessage).not.toHaveProperty('iss'); + + sockets[0].simulateMessage({ + flow_id: sentMessage.flow_id, + type: 'flow_complete', + credential: 'eyJ...', + }); + await flowPromise; + }); + it('should handle error responses by returning success: false', async () => { const transport = new OIDFlowWebSocketTransport(wsUrl, authToken); await transport.connect(); diff --git a/src/lib/openid-flow/transports/OIDFlowWebSocketTransport.ts b/src/lib/openid-flow/transports/OIDFlowWebSocketTransport.ts index abda7fc4..a7298f98 100644 --- a/src/lib/openid-flow/transports/OIDFlowWebSocketTransport.ts +++ b/src/lib/openid-flow/transports/OIDFlowWebSocketTransport.ts @@ -484,6 +484,9 @@ export class OIDFlowWebSocketTransport implements IOIDFlowTransport { redirect_uri: params.redirectUri, auth_code: params.authorizationCode, code_verifier: params.codeVerifier, + state: params.state, + iss: params.authorizationResponseIssuer, + authorization_context: params.authorizationContext, }); return this.mapOID4VCIResponse(response); @@ -532,6 +535,7 @@ export class OIDFlowWebSocketTransport implements IOIDFlowTransport { code: params.authorizationCode, code_verifier: params.codeVerifier, state: params.state, + iss: params.authorizationResponseIssuer, }, }); @@ -637,6 +641,9 @@ export class OIDFlowWebSocketTransport implements IOIDFlowTransport { if (payload?.state) { result.issuerState = payload.state as string; } + if (payload?.authorization_context) { + result.authorizationContext = payload.authorization_context as string; + } // Credential offer (for storage and resumption after redirect) if (payload?.credential_offer) { diff --git a/src/lib/openid-flow/types/OID4VCITypes.ts b/src/lib/openid-flow/types/OID4VCITypes.ts index 1f56721c..603a5966 100644 --- a/src/lib/openid-flow/types/OID4VCITypes.ts +++ b/src/lib/openid-flow/types/OID4VCITypes.ts @@ -57,6 +57,12 @@ export interface OID4VCIFlowParams { /** PKCE code verifier */ codeVerifier?: string; + /** RFC 9207 `iss` from the authorization response, exactly as received */ + authorizationResponseIssuer?: string; + + /** Opaque backend-signed context saved before the redirect */ + authorizationContext?: string; + // ===== Resumption context (for same-tab redirect flow) ===== /** Issuer identifier for resumption */ @@ -127,6 +133,9 @@ export interface OID4VCIFlowResult { /** Issuer state (for authorization flow) */ issuerState?: string; + /** Opaque backend-signed context, required to resume after a same-tab redirect */ + authorizationContext?: string; + // ===== Pre-authorized flow ===== /** Pre-authorized code */ diff --git a/src/pages/OpenIDFlowCallback/OpenIDFlowCallback.test.tsx b/src/pages/OpenIDFlowCallback/OpenIDFlowCallback.test.tsx index addd4334..eb25fbf2 100644 --- a/src/pages/OpenIDFlowCallback/OpenIDFlowCallback.test.tsx +++ b/src/pages/OpenIDFlowCallback/OpenIDFlowCallback.test.tsx @@ -90,6 +90,38 @@ describe('OpenIDFlowCallback: logging a completed offer', () => { }); }); +describe('OpenIDFlowCallback: authorization response iss', () => { + beforeEach(() => { + flow.handleAuthorizationResponse.mockReset(); + flow.handleAuthorizationResponse.mockResolvedValue({ success: true }); + }); + + it('forwards a single iss exactly as received', async () => { + window.history.pushState({}, '', '/cb?code=abc&state=xyz&iss=https%3A%2F%2Fas.example.com%2F'); + + render(); + + await waitFor(() => expect(flow.handleAuthorizationResponse).toHaveBeenCalledWith('abc', 'xyz', 'https://as.example.com/')); + }); + + it('forwards no iss when the callback has none', async () => { + window.history.pushState({}, '', '/cb?code=abc&state=xyz'); + + render(); + + await waitFor(() => expect(flow.handleAuthorizationResponse).toHaveBeenCalledWith('abc', 'xyz', undefined)); + }); + + it('rejects duplicate iss parameters, even identical ones', async () => { + window.history.pushState({}, '', '/cb?code=abc&state=xyz&iss=https%3A%2F%2Fas.example.com&iss=https%3A%2F%2Fas.example.com'); + + render(); + + await waitFor(() => expect(log.error).toHaveBeenCalledWith('Error in OID4VCI flow:', expect.anything())); + expect(flow.handleAuthorizationResponse).not.toHaveBeenCalled(); + }); +}); + describe('OpenIDFlowCallback: no whole result or response is ever handed to the logger', () => { it('passes no flow result variable to a logger call', () => { const source = readFileSync(resolve(process.cwd(), 'src/pages/OpenIDFlowCallback/OpenIDFlowCallback.tsx'), 'utf8'); diff --git a/src/pages/OpenIDFlowCallback/OpenIDFlowCallback.tsx b/src/pages/OpenIDFlowCallback/OpenIDFlowCallback.tsx index 583c7759..306f342b 100644 --- a/src/pages/OpenIDFlowCallback/OpenIDFlowCallback.tsx +++ b/src/pages/OpenIDFlowCallback/OpenIDFlowCallback.tsx @@ -216,10 +216,19 @@ const OpenID4VCIFlow: OpenIDFlowCallbackHandler = ({ callbackUrl }) => { const processAuthorizationCode = async (url: URL) => { const code = url.searchParams.get('code'); const state = url.searchParams.get('state'); + const issValues = url.searchParams.getAll('iss'); cleanupUrl(); - const result = await handleAuthorizationResponse(code, state); + // RFC 9207: never pick one of several iss values, even identical ones. + if (issValues.length > 1) { + throw new OIDFlowError({ + code: 'DUPLICATE_ISS', + message: 'Authorization response contains more than one iss parameter', + }); + } + + const result = await handleAuthorizationResponse(code, state, issValues[0]); if (result.success && result.credentials?.length) { await handleReceivedCredentials( From 3bdf85e8d665bb3f8408d49e52a733c42cce25df Mon Sep 17 00:00:00 2001 From: Simon Date: Fri, 13 Nov 2026 15:57:56 +0100 Subject: [PATCH 2/3] docs(changeset): Accept, store and return engine authorization context --- .changeset/new-lies-film.md | 5 +++++ 1 file changed, 5 insertions(+) create mode 100644 .changeset/new-lies-film.md diff --git a/.changeset/new-lies-film.md b/.changeset/new-lies-film.md new file mode 100644 index 00000000..051b65f5 --- /dev/null +++ b/.changeset/new-lies-film.md @@ -0,0 +1,5 @@ +--- +"wallet-frontend": patch +--- + +Accept, store and return engine authorization context From b2fd6f9c05d1db36257fcf1897afdd4dff299c62 Mon Sep 17 00:00:00 2001 From: Simon Date: Wed, 18 Nov 2026 14:02:02 +0100 Subject: [PATCH 3/3] test: make bot happy --- src/hooks/useOID4VCIFlow.test.tsx | 161 ++++++++++++++++++++++++++++-- 1 file changed, 155 insertions(+), 6 deletions(-) diff --git a/src/hooks/useOID4VCIFlow.test.tsx b/src/hooks/useOID4VCIFlow.test.tsx index 15838671..c5cc20b1 100644 --- a/src/hooks/useOID4VCIFlow.test.tsx +++ b/src/hooks/useOID4VCIFlow.test.tsx @@ -1,7 +1,13 @@ import type { ReactNode } from 'react'; -import { describe, it, expect, vi } from 'vitest'; +import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import { renderHook } from '@testing-library/react'; -import CredentialsContext, { type CredentialsContextValue } from '@/context/CredentialsContext'; +import CredentialsContext, { + type CredentialsContextValue, +} from '@/context/CredentialsContext'; +import SessionContext, { + type SessionContextValue, +} from '@/context/SessionContext'; +import type { OID4VCIFlowResult } from '@/lib/openid-flow/types/OID4VCITypes'; import useOID4VCIFlow from './useOID4VCIFlow'; const { transport } = vi.hoisted(() => ({ @@ -17,10 +23,39 @@ vi.mock('@/context/OIDFlowTransportContext', () => ({ })); // The credentials context has no default value: the hook needs a provider (only the engine is read here). -const credentials = { credentialEngine: new Promise(() => undefined) } as unknown as CredentialsContextValue; +const credentials = { + credentialEngine: new Promise(() => undefined), +} as unknown as CredentialsContextValue; +const session = { + oidFlowClientAuthMaterialManager: { + exportAuthMaterial: vi.fn().mockResolvedValue(undefined), + seedMaterial: vi.fn(), + }, +} as unknown as SessionContextValue; const wrapper = ({ children }: { children: ReactNode }) => ( - {children} + + + {children} + + +); + +const OFFER_URL = new URL( + 'openid-credential-offer://?credential_offer_uri=https%3A%2F%2Fissuer.example.com%2Foffer', ); +const OFFER = { + credential_issuer: 'https://issuer.example.com', + credential_configuration_ids: ['pid'], +}; +const AUTHORIZATION_RESULT: OID4VCIFlowResult = { + success: true, + authorizationUrl: 'https://as.example.com/authorize?request_uri=urn:x', + codeVerifier: 'saved-verifier', + issuerState: 'saved-state', + authorizationContext: 'signed.authorization.context', + credentialOffer: OFFER, +}; +const CONTEXT_LIFETIME_MS = 5 * 60 * 1000; describe('useOID4VCIFlow: aborting a flow reaches the transport', () => { it('releases what the transport holds for the flow when the hook unmounts', () => { @@ -43,7 +78,11 @@ describe('useOID4VCIFlow: aborting a flow reaches the transport', () => { }), ); const { result, unmount } = renderHook(() => useOID4VCIFlow(), { wrapper }); - const outcome = result.current.handleCredentialOffer(new URL('openid-credential-offer://?credential_offer_uri=https%3A%2F%2Fissuer.example.com%2Foffer')); + const outcome = result.current.handleCredentialOffer( + new URL( + 'openid-credential-offer://?credential_offer_uri=https%3A%2F%2Fissuer.example.com%2Foffer', + ), + ); await vi.waitFor(() => expect(failStart).toBeTypeOf('function')); unmount(); @@ -60,9 +99,119 @@ describe('useOID4VCIFlow: aborting a flow reaches the transport', () => { transport.startOID4VCIFlow.mockRejectedValue(new Error('boom')); const { result } = renderHook(() => useOID4VCIFlow(), { wrapper }); - const outcome = await result.current.handleCredentialOffer(new URL('openid-credential-offer://?credential_offer_uri=https%3A%2F%2Fissuer.example.com%2Foffer')); + const outcome = await result.current.handleCredentialOffer( + new URL( + 'openid-credential-offer://?credential_offer_uri=https%3A%2F%2Fissuer.example.com%2Foffer', + ), + ); expect(outcome.success).toBe(false); expect(transport.releaseFlow).toHaveBeenCalled(); }); }); + +describe('useOID4VCIFlow: resuming after a same-tab redirect', () => { + beforeEach(() => { + sessionStorage.clear(); + transport.startOID4VCIFlow.mockReset(); + }); + + afterEach(() => { + vi.useRealTimers(); + }); + + it('sends the saved context and verifier with the callback state and iss after a remount', async () => { + await saveAuthorizationResult(AUTHORIZATION_RESULT); + transport.startOID4VCIFlow.mockResolvedValueOnce({ success: true }); + const { result } = renderHook(() => useOID4VCIFlow(), { wrapper }); + + const outcome = await result.current.handleAuthorizationResponse( + 'auth-code', + 'saved-state', + 'https://as.example.com', + ); + + expect(outcome.success).toBe(true); + expect(transport.startOID4VCIFlow).toHaveBeenLastCalledWith( + expect.objectContaining({ + credentialOffer: JSON.stringify(OFFER), + authorizationCode: 'auth-code', + codeVerifier: 'saved-verifier', + state: 'saved-state', + authorizationResponseIssuer: 'https://as.example.com', + authorizationContext: 'signed.authorization.context', + }), + ); + }); + + it('saves and sends the context when the authorization result has no verifier', async () => { + await saveAuthorizationResult({ + ...AUTHORIZATION_RESULT, + codeVerifier: undefined, + }); + transport.startOID4VCIFlow.mockResolvedValueOnce({ success: true }); + const { result } = renderHook(() => useOID4VCIFlow(), { wrapper }); + + const outcome = await result.current.handleAuthorizationResponse( + 'auth-code', + 'saved-state', + undefined, + ); + + expect(outcome.success).toBe(true); + const [params] = transport.startOID4VCIFlow.mock.lastCall!; + expect(params.authorizationContext).toBe('signed.authorization.context'); + expect(params.state).toBe('saved-state'); + expect(params.codeVerifier).toBeUndefined(); + expect(params.authorizationResponseIssuer).toBeUndefined(); + }); + + it('still resumes at exactly five minutes', async () => { + vi.useFakeTimers({ toFake: ['Date'] }); + await saveAuthorizationResult(AUTHORIZATION_RESULT); + vi.setSystemTime(Date.now() + CONTEXT_LIFETIME_MS); + transport.startOID4VCIFlow.mockResolvedValueOnce({ success: true }); + const { result } = renderHook(() => useOID4VCIFlow(), { wrapper }); + + const outcome = await result.current.handleAuthorizationResponse( + 'auth-code', + 'saved-state', + 'https://as.example.com', + ); + + expect(outcome.success).toBe(true); + expect(transport.startOID4VCIFlow).toHaveBeenCalledTimes(2); + }); + + it('drops the saved flow once five minutes have passed and never resumes it', async () => { + vi.useFakeTimers({ toFake: ['Date'] }); + await saveAuthorizationResult(AUTHORIZATION_RESULT); + vi.setSystemTime(Date.now() + CONTEXT_LIFETIME_MS + 1); + const { result } = renderHook(() => useOID4VCIFlow(), { wrapper }); + + const outcome = await result.current.handleAuthorizationResponse( + 'auth-code', + 'saved-state', + 'https://as.example.com', + ); + + expect(outcome.success).toBe(false); + expect(transport.startOID4VCIFlow).toHaveBeenCalledTimes(1); + expect(sessionStorage.length).toBe(0); + }); +}); + +/** + * Runs a credential offer that ends in an authorization redirect, then unmounts the hook like the page leaving. + */ +async function saveAuthorizationResult( + authorizationResult: OID4VCIFlowResult, +): Promise { + transport.startOID4VCIFlow.mockResolvedValueOnce(authorizationResult); + const { result, unmount } = renderHook(() => useOID4VCIFlow(), { wrapper }); + + const outcome = await result.current.handleCredentialOffer(OFFER_URL); + + expect(outcome.authorizationUrl).toBe(authorizationResult.authorizationUrl); + unmount(); +}