Skip to content

Commit d440377

Browse files
committed
feat(auth): signInWithUsernamePassword pide un código con PKCE en vez de tokens en la URL
OAuth 2.1: sin state y con flowType pkce, el login por contraseña manda response_type=code y un code_challenge S256, y guarda el verificador como un login social; la vuelta canjea el código como siempre. Con state (viene de un /authorize) no toca nada. Requiere auth con 707c8f1e. Backlog §447.
1 parent e373e24 commit d440377

2 files changed

Lines changed: 130 additions & 2 deletions

File tree

‎src/FaableAuthClient.ts‎

Lines changed: 26 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1667,15 +1667,39 @@ export class FaableAuthClient extends Base {
16671667
audience?: string
16681668
}): Promise<AuthResult<null>> {
16691669
const audience = data.audience ?? this.audience
1670+
const redirectUri =
1671+
data.redirectTo || this.redirectUri || window?.location.origin
1672+
// OAuth 2.1: a code bound by PKCE, not tokens in the redirect URL. Only
1673+
// for a login of our own — with a `state` the login continues an
1674+
// `/authorize` that already set its challenge, and its verifier is the
1675+
// one stored; minting another here would overwrite it.
1676+
const pkce =
1677+
this.flowType === 'pkce' && !data.state
1678+
? await getCodeChallengeAndMethod(
1679+
this.storage,
1680+
this.storageKey,
1681+
false,
1682+
undefined,
1683+
{ redirectUri }
1684+
)
1685+
: undefined
16701686
const rawAuthResponse = await _post<string>(
16711687
`${this.domainUrl}/usernamepassword/login`,
16721688
{
16731689
username: data.username,
16741690
password: data.password,
1675-
redirect_uri:
1676-
data.redirectTo || this.redirectUri || window?.location.origin,
1691+
redirect_uri: redirectUri,
16771692
client_id: this.clientId,
16781693
state: data.state,
1694+
// `plain` (no WebCrypto: an insecure context) is refused by the
1695+
// server; such a page keeps the old token response.
1696+
...(pkce && pkce[1] === 'S256'
1697+
? {
1698+
response_type: 'code',
1699+
code_challenge: pkce[0],
1700+
code_challenge_method: pkce[1]
1701+
}
1702+
: {}),
16791703
...(audience ? { audience } : {})
16801704
},
16811705
{ raw: true }
Lines changed: 104 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,104 @@
1+
import { beforeEach, describe, expect, it, vi } from 'vitest'
2+
import { createClient } from '../../src/createClient'
3+
import { _post } from '../../src/lib/fetch'
4+
import { loadCodeVerifier } from '../../src/lib/pkce_storage'
5+
import type { SupportedStorage } from '../../src/lib/types'
6+
7+
// OAuth 2.1 (backlog §447): the password login asked for nothing, so the
8+
// server answered with the implicit default — access AND refresh token in the
9+
// redirect URL. With PKCE it asks for a code the SDK then exchanges.
10+
11+
vi.mock('../../src/lib/fetch', () => ({
12+
_post: vi.fn(),
13+
_get: vi.fn(async () => ({ data: null, error: null }))
14+
}))
15+
const mPost = _post as unknown as ReturnType<typeof vi.fn>
16+
17+
const inMemoryStorage = (): SupportedStorage => {
18+
const store = new Map<string, string>()
19+
return {
20+
getItem: k => store.get(k) ?? null,
21+
setItem: (k, v) => void store.set(k, v),
22+
removeItem: k => void store.delete(k)
23+
}
24+
}
25+
26+
const REDIRECT = 'https://app.example.com/cb'
27+
28+
const makeClient = (storage: SupportedStorage, flowType: string) =>
29+
createClient({
30+
domain: 'https://tenant.auth.faable.link',
31+
clientId: 'test-client',
32+
storage,
33+
storageKey: 'faable-auth-token',
34+
autoRefreshToken: false,
35+
flowType,
36+
redirectUri: REDIRECT
37+
} as any)
38+
39+
// The request is what matters; a failed answer keeps the SDK from trying to
40+
// submit the callback form.
41+
const loginBody = () => {
42+
const call = mPost.mock.calls.find(c =>
43+
String(c[0]).endsWith('/usernamepassword/login')
44+
)
45+
return call?.[1] as Record<string, unknown>
46+
}
47+
48+
beforeEach(() => {
49+
mPost.mockReset()
50+
mPost.mockResolvedValue({ data: null, error: 'nope', status: 400 })
51+
})
52+
53+
describe('signInWithUsernamePassword asks for a PKCE-bound code', () => {
54+
it('sends response_type=code with an S256 challenge and stores its verifier', async () => {
55+
const storage = inMemoryStorage()
56+
const auth = makeClient(storage, 'pkce')
57+
58+
await auth.signInWithUsernamePassword({ username: 'a@b.c', password: 'x' })
59+
60+
const body = loginBody()
61+
expect(body.response_type).toBe('code')
62+
expect(body.code_challenge_method).toBe('S256')
63+
expect(typeof body.code_challenge).toBe('string')
64+
expect(body.redirect_uri).toBe(REDIRECT)
65+
66+
// The verifier the landing exchanges the code with, and the redirect_uri
67+
// the exchange has to repeat.
68+
const stored = await loadCodeVerifier(
69+
storage,
70+
'faable-auth-token-test-client-code-verifier'
71+
)
72+
expect(stored?.verifier).toBeTruthy()
73+
expect(stored?.redirectUri).toBe(REDIRECT)
74+
})
75+
76+
it('with a state, leaves the /authorize challenge and its verifier alone', async () => {
77+
const storage = inMemoryStorage()
78+
const auth = makeClient(storage, 'pkce')
79+
80+
await auth.signInWithUsernamePassword({
81+
username: 'a@b.c',
82+
password: 'x',
83+
state: 'st_1'
84+
})
85+
86+
const body = loginBody()
87+
expect(body.code_challenge).toBeUndefined()
88+
expect(body.response_type).toBeUndefined()
89+
expect(
90+
await loadCodeVerifier(
91+
storage,
92+
'faable-auth-token-test-client-code-verifier'
93+
)
94+
).toBeFalsy()
95+
})
96+
97+
it('an implicit client asks for nothing new', async () => {
98+
const auth = makeClient(inMemoryStorage(), 'implicit')
99+
await auth.signInWithUsernamePassword({ username: 'a@b.c', password: 'x' })
100+
const body = loginBody()
101+
expect(body.code_challenge).toBeUndefined()
102+
expect(body.response_type).toBeUndefined()
103+
})
104+
})

0 commit comments

Comments
 (0)