@baukit/auth-native 0.8.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +17 -0
- package/dist/clerk-expo.d.ts +9 -0
- package/dist/clerk-expo.d.ts.map +1 -0
- package/dist/clerk-expo.js +37 -0
- package/dist/clerk-expo.js.map +1 -0
- package/dist/clerk.d.ts +31 -0
- package/dist/clerk.d.ts.map +1 -0
- package/dist/clerk.js +101 -0
- package/dist/clerk.js.map +1 -0
- package/dist/expo.js +4 -0
- package/dist/expo.js.map +1 -1
- package/dist/index.d.ts +11 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +32 -8
- package/dist/index.js.map +1 -1
- package/dist/workos.d.ts +9 -0
- package/dist/workos.d.ts.map +1 -0
- package/dist/workos.js +85 -0
- package/dist/workos.js.map +1 -0
- package/package.json +31 -3
- package/src/clerk-expo.test.ts +88 -0
- package/src/clerk-expo.ts +40 -0
- package/src/clerk.ts +119 -0
- package/src/expo.test.ts +17 -0
- package/src/expo.ts +4 -0
- package/src/index.test.ts +19 -0
- package/src/index.ts +48 -12
- package/src/providers.test.ts +147 -0
- package/src/workos.ts +109 -0
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@baukit/auth-native",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.9.0",
|
|
4
4
|
"description": "Provider-neutral native OIDC authorization-code client with S256 PKCE, secure-storage and browser-flow ports, and refresh rotation.",
|
|
5
5
|
"license": "MIT",
|
|
6
6
|
"author": "Patrick Koss",
|
|
@@ -31,6 +31,21 @@
|
|
|
31
31
|
"types": "./dist/expo.d.ts",
|
|
32
32
|
"import": "./dist/expo.js",
|
|
33
33
|
"default": "./dist/expo.js"
|
|
34
|
+
},
|
|
35
|
+
"./clerk": {
|
|
36
|
+
"types": "./dist/clerk.d.ts",
|
|
37
|
+
"import": "./dist/clerk.js",
|
|
38
|
+
"default": "./dist/clerk.js"
|
|
39
|
+
},
|
|
40
|
+
"./clerk-expo": {
|
|
41
|
+
"types": "./dist/clerk-expo.d.ts",
|
|
42
|
+
"import": "./dist/clerk-expo.js",
|
|
43
|
+
"default": "./dist/clerk-expo.js"
|
|
44
|
+
},
|
|
45
|
+
"./workos": {
|
|
46
|
+
"types": "./dist/workos.d.ts",
|
|
47
|
+
"import": "./dist/workos.js",
|
|
48
|
+
"default": "./dist/workos.js"
|
|
34
49
|
}
|
|
35
50
|
},
|
|
36
51
|
"files": [
|
|
@@ -50,11 +65,24 @@
|
|
|
50
65
|
"expo-auth-session": "57.0.13",
|
|
51
66
|
"expo-secure-store": "57.0.4",
|
|
52
67
|
"expo-web-browser": "57.0.3",
|
|
53
|
-
"typescript": "6.0.3"
|
|
68
|
+
"typescript": "6.0.3",
|
|
69
|
+
"@clerk/expo": "4.8.1",
|
|
70
|
+
"react": "19.3.0",
|
|
71
|
+
"@types/react": "19.3.0"
|
|
54
72
|
},
|
|
55
73
|
"peerDependencies": {
|
|
56
74
|
"expo-auth-session": "^57.0.13",
|
|
57
75
|
"expo-secure-store": "^57.0.4",
|
|
58
|
-
"expo-web-browser": "^57.0.3"
|
|
76
|
+
"expo-web-browser": "^57.0.3",
|
|
77
|
+
"@clerk/expo": "^4.8.1",
|
|
78
|
+
"react": "^19.2.3"
|
|
79
|
+
},
|
|
80
|
+
"peerDependenciesMeta": {
|
|
81
|
+
"@clerk/expo": {
|
|
82
|
+
"optional": true
|
|
83
|
+
},
|
|
84
|
+
"react": {
|
|
85
|
+
"optional": true
|
|
86
|
+
}
|
|
59
87
|
}
|
|
60
88
|
}
|
|
@@ -0,0 +1,88 @@
|
|
|
1
|
+
import { createElement, isValidElement, type PropsWithChildren, type ReactNode } from 'react';
|
|
2
|
+
import { expect, it, vi } from 'vitest';
|
|
3
|
+
import { createClerkExpoClient } from './clerk-expo.js';
|
|
4
|
+
import type { SecureStoragePort } from './index.js';
|
|
5
|
+
|
|
6
|
+
const sdk = vi.hoisted(() => ({
|
|
7
|
+
loaded: true,
|
|
8
|
+
user: { id: 'user_123' },
|
|
9
|
+
getToken: vi.fn<() => Promise<string | null>>(),
|
|
10
|
+
signOut: vi.fn<() => Promise<void>>(),
|
|
11
|
+
hosted: vi.fn<() => Promise<{ createdSessionId: string | null }>>(),
|
|
12
|
+
}));
|
|
13
|
+
vi.mock('react', async (importOriginal) => {
|
|
14
|
+
const actual = await importOriginal<typeof import('react')>();
|
|
15
|
+
return {
|
|
16
|
+
...actual,
|
|
17
|
+
useEffect: (effect: () => void) => {
|
|
18
|
+
effect();
|
|
19
|
+
},
|
|
20
|
+
};
|
|
21
|
+
});
|
|
22
|
+
vi.mock('@clerk/expo', () => ({
|
|
23
|
+
ClerkProvider: ({ children }: PropsWithChildren) => children,
|
|
24
|
+
useAuth: () => ({ isLoaded: sdk.loaded }),
|
|
25
|
+
useClerk: () => ({ user: sdk.user, session: { getToken: sdk.getToken }, signOut: sdk.signOut }),
|
|
26
|
+
}));
|
|
27
|
+
vi.mock('@clerk/expo/hosted-auth', () => ({
|
|
28
|
+
useHostedAuth: () => ({ startHostedAuth: sdk.hosted }),
|
|
29
|
+
}));
|
|
30
|
+
|
|
31
|
+
interface ProviderProps {
|
|
32
|
+
publishableKey: string;
|
|
33
|
+
tokenCache: {
|
|
34
|
+
getToken(key: string): Promise<string | null>;
|
|
35
|
+
saveToken(key: string, value: string): Promise<void>;
|
|
36
|
+
clearToken(key: string): Promise<void>;
|
|
37
|
+
};
|
|
38
|
+
children: ReactNode;
|
|
39
|
+
}
|
|
40
|
+
function functionComponent(value: unknown): value is (props: PropsWithChildren) => ReactNode {
|
|
41
|
+
return typeof value === 'function';
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
it('binds hosted Clerk auth only after loading and delegates the SDK cache to secure storage', async () => {
|
|
45
|
+
const values = new Map<string, string>();
|
|
46
|
+
const storage: SecureStoragePort = {
|
|
47
|
+
get: (key) => Promise.resolve(values.get(key) ?? null),
|
|
48
|
+
set: (key, value) => {
|
|
49
|
+
values.set(key, value);
|
|
50
|
+
return Promise.resolve();
|
|
51
|
+
},
|
|
52
|
+
delete: (key) => {
|
|
53
|
+
values.delete(key);
|
|
54
|
+
return Promise.resolve();
|
|
55
|
+
},
|
|
56
|
+
};
|
|
57
|
+
const { client, Provider } = createClerkExpoClient('pk_test', storage);
|
|
58
|
+
const bind = vi.spyOn(client, 'bind');
|
|
59
|
+
const tree = Provider({ children: createElement('div', {}, 'content') });
|
|
60
|
+
if (!isValidElement<ProviderProps>(tree)) throw new Error('Expected Clerk provider');
|
|
61
|
+
expect(tree.props.publishableKey).toBe('pk_test');
|
|
62
|
+
const cache = tree.props.tokenCache;
|
|
63
|
+
await cache.saveToken('session', 'secret');
|
|
64
|
+
expect(await cache.getToken('session')).toBe('secret');
|
|
65
|
+
await cache.clearToken('session');
|
|
66
|
+
expect(await cache.getToken('session')).toBeNull();
|
|
67
|
+
const bridge = tree.props.children;
|
|
68
|
+
if (!isValidElement<PropsWithChildren>(bridge) || !functionComponent(bridge.type))
|
|
69
|
+
throw new Error('Expected auth bridge');
|
|
70
|
+
sdk.loaded = false;
|
|
71
|
+
await bridge.type(bridge.props);
|
|
72
|
+
expect(bind).not.toHaveBeenCalled();
|
|
73
|
+
sdk.loaded = true;
|
|
74
|
+
await bridge.type(bridge.props);
|
|
75
|
+
const port = bind.mock.calls[0]?.[0];
|
|
76
|
+
if (port === undefined) throw new Error('SDK port was not bound');
|
|
77
|
+
expect(port.subject()).toBe('user_123');
|
|
78
|
+
sdk.getToken.mockResolvedValue('access-token');
|
|
79
|
+
expect(await port.getToken(true)).toBe('access-token');
|
|
80
|
+
expect(sdk.getToken).toHaveBeenCalledWith({ skipCache: true });
|
|
81
|
+
sdk.hosted.mockResolvedValue({ createdSessionId: 'session_123' });
|
|
82
|
+
expect(await port.signIn()).toBe(true);
|
|
83
|
+
sdk.hosted.mockResolvedValue({ createdSessionId: null });
|
|
84
|
+
expect(await port.signIn()).toBe(false);
|
|
85
|
+
sdk.signOut.mockResolvedValue();
|
|
86
|
+
await port.signOut();
|
|
87
|
+
expect(sdk.signOut).toHaveBeenCalledTimes(1);
|
|
88
|
+
});
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import { createElement, useEffect, type ReactElement, type PropsWithChildren } from 'react';
|
|
2
|
+
import { ClerkProvider, useAuth, useClerk } from '@clerk/expo';
|
|
3
|
+
import { useHostedAuth } from '@clerk/expo/hosted-auth';
|
|
4
|
+
import type { SecureStoragePort } from './index.js';
|
|
5
|
+
import { ClerkNativeClient } from './clerk.js';
|
|
6
|
+
|
|
7
|
+
/** Creates a Clerk SDK provider and its product-facing client together. */
|
|
8
|
+
export function createClerkExpoClient(
|
|
9
|
+
publishableKey: string,
|
|
10
|
+
storage: SecureStoragePort,
|
|
11
|
+
): { client: ClerkNativeClient; Provider: (props: PropsWithChildren) => ReactElement } {
|
|
12
|
+
const client = new ClerkNativeClient();
|
|
13
|
+
function Bridge({ children }: PropsWithChildren) {
|
|
14
|
+
const { isLoaded } = useAuth();
|
|
15
|
+
const clerk = useClerk();
|
|
16
|
+
const { startHostedAuth } = useHostedAuth();
|
|
17
|
+
useEffect(() => {
|
|
18
|
+
if (!isLoaded) return;
|
|
19
|
+
client.bind({
|
|
20
|
+
subject: () => clerk.user?.id,
|
|
21
|
+
getToken: async (skipCache) => (await clerk.session?.getToken({ skipCache })) ?? null,
|
|
22
|
+
signIn: async () => (await startHostedAuth()).createdSessionId !== null,
|
|
23
|
+
signOut: () => clerk.signOut(),
|
|
24
|
+
});
|
|
25
|
+
}, [isLoaded, clerk, startHostedAuth]);
|
|
26
|
+
return children;
|
|
27
|
+
}
|
|
28
|
+
function Provider({ children }: PropsWithChildren) {
|
|
29
|
+
return createElement(ClerkProvider, {
|
|
30
|
+
publishableKey,
|
|
31
|
+
children: createElement(Bridge, {}, children),
|
|
32
|
+
tokenCache: {
|
|
33
|
+
getToken: (key: string) => storage.get(key),
|
|
34
|
+
saveToken: (key: string, value: string) => storage.set(key, value),
|
|
35
|
+
clearToken: (key: string) => storage.delete(key),
|
|
36
|
+
},
|
|
37
|
+
});
|
|
38
|
+
}
|
|
39
|
+
return { client, Provider };
|
|
40
|
+
}
|
package/src/clerk.ts
ADDED
|
@@ -0,0 +1,119 @@
|
|
|
1
|
+
import {
|
|
2
|
+
OidcError,
|
|
3
|
+
type OidcSession,
|
|
4
|
+
type SessionExpiredEvent,
|
|
5
|
+
type SignInResult,
|
|
6
|
+
type SignOutResult,
|
|
7
|
+
} from './index.js';
|
|
8
|
+
import { tokenTiming } from './workos.js';
|
|
9
|
+
|
|
10
|
+
export interface ClerkNativePort {
|
|
11
|
+
subject(): string | undefined;
|
|
12
|
+
getToken(skipCache: boolean): Promise<string | null>;
|
|
13
|
+
signIn(): Promise<boolean>;
|
|
14
|
+
signOut(): Promise<void>;
|
|
15
|
+
}
|
|
16
|
+
|
|
17
|
+
/** Keeps SDK session transitions behind the native authentication contract. */
|
|
18
|
+
export class ClerkNativeClient {
|
|
19
|
+
private port: ClerkNativePort | undefined;
|
|
20
|
+
private current: OidcSession | undefined;
|
|
21
|
+
private cleared = false;
|
|
22
|
+
private readonly listeners = new Set<(session: OidcSession | undefined) => void>();
|
|
23
|
+
private readonly expired = new Set<(event: SessionExpiredEvent) => void>();
|
|
24
|
+
private readonly ready: Promise<void>;
|
|
25
|
+
private resolveReady: (() => void) | undefined;
|
|
26
|
+
|
|
27
|
+
public constructor() {
|
|
28
|
+
this.ready = new Promise((resolve) => {
|
|
29
|
+
this.resolveReady = resolve;
|
|
30
|
+
});
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
public bind(port: ClerkNativePort): void {
|
|
34
|
+
this.port = port;
|
|
35
|
+
this.resolveReady?.();
|
|
36
|
+
this.resolveReady = undefined;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
public async initialize(): Promise<OidcSession | undefined> {
|
|
40
|
+
await this.accessToken();
|
|
41
|
+
return this.current;
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
public session(): OidcSession | undefined {
|
|
45
|
+
return this.current;
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
public subscribe(listener: (session: OidcSession | undefined) => void): () => void {
|
|
49
|
+
this.listeners.add(listener);
|
|
50
|
+
return () => {
|
|
51
|
+
this.listeners.delete(listener);
|
|
52
|
+
};
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
public subscribeSessionExpired(listener: (event: SessionExpiredEvent) => void): () => void {
|
|
56
|
+
this.expired.add(listener);
|
|
57
|
+
return () => {
|
|
58
|
+
this.expired.delete(listener);
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
public async accessToken(
|
|
63
|
+
options: { readonly forceRefresh?: boolean } = {},
|
|
64
|
+
): Promise<string | undefined> {
|
|
65
|
+
await this.ready;
|
|
66
|
+
const port = this.port;
|
|
67
|
+
if (this.cleared || port?.subject() === undefined) {
|
|
68
|
+
this.setSession(undefined);
|
|
69
|
+
return undefined;
|
|
70
|
+
}
|
|
71
|
+
const token = await port.getToken(options.forceRefresh ?? false);
|
|
72
|
+
if (token === null) {
|
|
73
|
+
const hadSession = this.current !== undefined;
|
|
74
|
+
await this.clearSession();
|
|
75
|
+
if (hadSession)
|
|
76
|
+
for (const listener of this.expired)
|
|
77
|
+
listener({ type: 'session-expired', reason: 'refresh_rejected' });
|
|
78
|
+
return undefined;
|
|
79
|
+
}
|
|
80
|
+
const timing = tokenTiming(token);
|
|
81
|
+
if (timing.subject !== port.subject()) throw new OidcError('invalid_token_response');
|
|
82
|
+
this.setSession({ subject: timing.subject, accessToken: token, expiresAt: timing.expiresAt });
|
|
83
|
+
return token;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
public async signIn(): Promise<SignInResult> {
|
|
87
|
+
await this.ready;
|
|
88
|
+
if (this.port === undefined) throw new OidcError('authorization_failed');
|
|
89
|
+
if (!(await this.port.signIn())) return { status: 'cancelled', reason: 'cancel' };
|
|
90
|
+
this.cleared = false;
|
|
91
|
+
await this.accessToken({ forceRefresh: true });
|
|
92
|
+
if (this.current === undefined) throw new OidcError('authorization_failed');
|
|
93
|
+
return { status: 'success', subject: this.current.subject };
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
public clearSession(): Promise<void> {
|
|
97
|
+
this.cleared = true;
|
|
98
|
+
this.setSession(undefined);
|
|
99
|
+
return Promise.resolve();
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
public async signOut(): Promise<SignOutResult> {
|
|
103
|
+
await this.clearSession();
|
|
104
|
+
await this.ready;
|
|
105
|
+
if (this.port === undefined) return { providerLogout: 'unavailable' };
|
|
106
|
+
try {
|
|
107
|
+
await this.port.signOut();
|
|
108
|
+
return { providerLogout: 'completed' };
|
|
109
|
+
} catch {
|
|
110
|
+
return { providerLogout: 'failed' };
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
private setSession(session: OidcSession | undefined): void {
|
|
115
|
+
if (session?.accessToken === this.current?.accessToken) return;
|
|
116
|
+
this.current = session;
|
|
117
|
+
for (const listener of this.listeners) listener(session);
|
|
118
|
+
}
|
|
119
|
+
}
|
package/src/expo.test.ts
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { afterEach, describe, expect, it, vi } from 'vitest';
|
|
2
2
|
|
|
3
3
|
interface AuthRequestConfig {
|
|
4
|
+
readonly extraParams?: Readonly<Record<string, string>>;
|
|
4
5
|
readonly state?: string;
|
|
5
6
|
readonly prompt?: string;
|
|
6
7
|
}
|
|
@@ -68,6 +69,22 @@ describe('createExpoOidcEnvironment', () => {
|
|
|
68
69
|
});
|
|
69
70
|
|
|
70
71
|
describe('createExpoBrowserFlow', () => {
|
|
72
|
+
it('passes resource and audience to AuthSession while retaining PKCE and state', async () => {
|
|
73
|
+
const result = await createExpoBrowserFlow().authorize({
|
|
74
|
+
...request,
|
|
75
|
+
audience: 'https://api.example.test',
|
|
76
|
+
resource: 'https://api.example.test',
|
|
77
|
+
});
|
|
78
|
+
expect(authRequestConfigs[0]?.extraParams).toEqual({
|
|
79
|
+
audience: 'https://api.example.test',
|
|
80
|
+
resource: 'https://api.example.test',
|
|
81
|
+
});
|
|
82
|
+
expect(result).toMatchObject({
|
|
83
|
+
type: 'success',
|
|
84
|
+
codeVerifier: 'pkce-verifier',
|
|
85
|
+
expectedState: DEFAULT_STATE,
|
|
86
|
+
});
|
|
87
|
+
});
|
|
71
88
|
it('prefixes the decoration to a random nonce', async () => {
|
|
72
89
|
const browser = createExpoBrowserFlow({ randomBytes: zeroBytes });
|
|
73
90
|
|
package/src/expo.ts
CHANGED
|
@@ -101,6 +101,10 @@ async function authorizeWithAuthSession(
|
|
|
101
101
|
responseType: AuthSession.ResponseType.Code,
|
|
102
102
|
scopes: [...request.scopes],
|
|
103
103
|
usePKCE: true,
|
|
104
|
+
extraParams: {
|
|
105
|
+
...(request.audience === undefined ? {} : { audience: request.audience }),
|
|
106
|
+
...(request.resource === undefined ? {} : { resource: request.resource }),
|
|
107
|
+
},
|
|
104
108
|
...(request.prompt === undefined ? {} : { prompt: AuthSession.Prompt.Login }),
|
|
105
109
|
...(state === undefined ? {} : { state }),
|
|
106
110
|
});
|
package/src/index.test.ts
CHANGED
|
@@ -264,6 +264,25 @@ describe('NativeOidcClient', () => {
|
|
|
264
264
|
expect(keys.size).toBe(4);
|
|
265
265
|
});
|
|
266
266
|
|
|
267
|
+
it('passes external API token binding through the browser port', async () => {
|
|
268
|
+
const test = makeHarness({
|
|
269
|
+
config: {
|
|
270
|
+
issuer,
|
|
271
|
+
clientId: 'product-mobile',
|
|
272
|
+
redirectUri: 'product://oauth',
|
|
273
|
+
audience: 'https://api.example.test',
|
|
274
|
+
resource: 'https://api.example.test',
|
|
275
|
+
scopes: ['openid', 'api/read'],
|
|
276
|
+
},
|
|
277
|
+
});
|
|
278
|
+
await expect(test.client.signIn()).resolves.toMatchObject({ status: 'success' });
|
|
279
|
+
expect(test.browser.authorizationRequests[0]).toMatchObject({
|
|
280
|
+
audience: 'https://api.example.test',
|
|
281
|
+
resource: 'https://api.example.test',
|
|
282
|
+
scopes: ['openid', 'api/read'],
|
|
283
|
+
});
|
|
284
|
+
});
|
|
285
|
+
|
|
267
286
|
it('discovers standard endpoints, exchanges PKCE, and stores the UserInfo subject', async () => {
|
|
268
287
|
const test = makeHarness();
|
|
269
288
|
const updates: (string | undefined)[] = [];
|
package/src/index.ts
CHANGED
|
@@ -58,6 +58,8 @@ export interface NativeOidcConfig {
|
|
|
58
58
|
readonly issuer: string;
|
|
59
59
|
readonly clientId: string;
|
|
60
60
|
readonly redirectUri: string;
|
|
61
|
+
readonly audience?: string;
|
|
62
|
+
readonly resource?: string;
|
|
61
63
|
/** `openid` is prepended when omitted. Defaults to `openid profile email`. */
|
|
62
64
|
readonly scopes?: readonly string[];
|
|
63
65
|
/** Adds `offline_access` to the requested scopes. Defaults to false. */
|
|
@@ -119,6 +121,8 @@ export interface AuthorizationRequest {
|
|
|
119
121
|
readonly clientId: string;
|
|
120
122
|
readonly redirectUri: string;
|
|
121
123
|
readonly scopes: readonly string[];
|
|
124
|
+
readonly audience?: string;
|
|
125
|
+
readonly resource?: string;
|
|
122
126
|
readonly prompt?: 'login';
|
|
123
127
|
/** Segments a decorating browser flow puts in front of its random state. Other flows ignore them. */
|
|
124
128
|
readonly stateDecoration?: readonly string[];
|
|
@@ -149,7 +153,15 @@ export interface BrowserFlowPort {
|
|
|
149
153
|
|
|
150
154
|
export type FetchPort = (input: string, init?: RequestInit) => Promise<Response>;
|
|
151
155
|
|
|
156
|
+
export interface NativeTokenProtocol {
|
|
157
|
+
discover(): Promise<OidcProviderMetadata>;
|
|
158
|
+
exchange(endpoint: string, body: URLSearchParams): Promise<Response>;
|
|
159
|
+
subject(accessToken: string): Promise<string>;
|
|
160
|
+
logout?(session: OidcSession, redirectUri: string): Promise<boolean>;
|
|
161
|
+
}
|
|
162
|
+
|
|
152
163
|
export interface NativeOidcEnvironment {
|
|
164
|
+
readonly protocol?: NativeTokenProtocol;
|
|
153
165
|
readonly fetch: FetchPort;
|
|
154
166
|
readonly storage: SecureStoragePort;
|
|
155
167
|
readonly browser: BrowserFlowPort;
|
|
@@ -160,6 +172,8 @@ interface NormalizedConfig {
|
|
|
160
172
|
readonly issuer: string;
|
|
161
173
|
readonly clientId: string;
|
|
162
174
|
readonly redirectUri: string;
|
|
175
|
+
readonly audience?: string;
|
|
176
|
+
readonly resource?: string;
|
|
163
177
|
readonly scopes: readonly string[];
|
|
164
178
|
readonly postLogoutRedirectUri: string;
|
|
165
179
|
readonly refreshLeewayMs: number;
|
|
@@ -239,7 +253,9 @@ export class NativeOidcClient {
|
|
|
239
253
|
}
|
|
240
254
|
|
|
241
255
|
public discover(): Promise<OidcProviderMetadata> {
|
|
242
|
-
this.metadataPromise ??=
|
|
256
|
+
this.metadataPromise ??=
|
|
257
|
+
this.environment.protocol?.discover() ??
|
|
258
|
+
discoverProvider(this.config.issuer, this.environment.fetch);
|
|
243
259
|
return this.metadataPromise;
|
|
244
260
|
}
|
|
245
261
|
|
|
@@ -254,6 +270,8 @@ export class NativeOidcClient {
|
|
|
254
270
|
clientId: this.config.clientId,
|
|
255
271
|
redirectUri: this.config.redirectUri,
|
|
256
272
|
scopes: this.config.scopes,
|
|
273
|
+
...(this.config.audience === undefined ? {} : { audience: this.config.audience }),
|
|
274
|
+
...(this.config.resource === undefined ? {} : { resource: this.config.resource }),
|
|
257
275
|
...(forceLogin ? { prompt: 'login' as const } : {}),
|
|
258
276
|
...(options.stateDecoration === undefined
|
|
259
277
|
? {}
|
|
@@ -287,11 +305,8 @@ export class NativeOidcClient {
|
|
|
287
305
|
}),
|
|
288
306
|
'token_exchange_failed',
|
|
289
307
|
);
|
|
290
|
-
const subject = await
|
|
291
|
-
metadata.userInfoEndpoint,
|
|
292
|
-
tokens.access_token,
|
|
293
|
-
this.environment.fetch,
|
|
294
|
-
);
|
|
308
|
+
const subject = await (this.environment.protocol?.subject(tokens.access_token) ??
|
|
309
|
+
fetchSubject(metadata.userInfoEndpoint, tokens.access_token, this.environment.fetch));
|
|
295
310
|
const session = makeSession(tokens, subject);
|
|
296
311
|
await this.writeSession(session);
|
|
297
312
|
await this.deleteForceLoginBestEffort();
|
|
@@ -332,10 +347,24 @@ export class NativeOidcClient {
|
|
|
332
347
|
/** Clears local state first, then makes a best-effort provider logout attempt. */
|
|
333
348
|
public async signOut(): Promise<SignOutResult> {
|
|
334
349
|
await this.initialize();
|
|
335
|
-
const
|
|
350
|
+
const session = this.currentSession;
|
|
351
|
+
const idToken = session?.idToken;
|
|
336
352
|
await this.clearSession();
|
|
337
353
|
await this.setForceLogin();
|
|
338
354
|
|
|
355
|
+
if (session !== undefined && this.environment.protocol?.logout !== undefined) {
|
|
356
|
+
try {
|
|
357
|
+
const completed = await this.environment.protocol.logout(
|
|
358
|
+
session,
|
|
359
|
+
this.config.postLogoutRedirectUri,
|
|
360
|
+
);
|
|
361
|
+
if (completed) await this.deleteForceLoginBestEffort();
|
|
362
|
+
return { providerLogout: completed ? 'completed' : 'failed' };
|
|
363
|
+
} catch {
|
|
364
|
+
return { providerLogout: 'failed' };
|
|
365
|
+
}
|
|
366
|
+
}
|
|
367
|
+
|
|
339
368
|
let metadata: OidcProviderMetadata;
|
|
340
369
|
try {
|
|
341
370
|
metadata = await this.discover();
|
|
@@ -442,11 +471,12 @@ export class NativeOidcClient {
|
|
|
442
471
|
): Promise<ReceivedTokenResponse> {
|
|
443
472
|
let response: Response;
|
|
444
473
|
try {
|
|
445
|
-
response = await this.environment.
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
474
|
+
response = await (this.environment.protocol?.exchange(endpoint, body) ??
|
|
475
|
+
this.environment.fetch(endpoint, {
|
|
476
|
+
method: 'POST',
|
|
477
|
+
headers: { 'content-type': 'application/x-www-form-urlencoded' },
|
|
478
|
+
body,
|
|
479
|
+
}));
|
|
450
480
|
} catch {
|
|
451
481
|
throw new OidcError(failureCode, { retryable: failureCode === 'refresh_failed' });
|
|
452
482
|
}
|
|
@@ -642,6 +672,12 @@ function normalizeConfig(config: NativeOidcConfig): NormalizedConfig {
|
|
|
642
672
|
issuer,
|
|
643
673
|
clientId,
|
|
644
674
|
redirectUri,
|
|
675
|
+
...(config.audience === undefined
|
|
676
|
+
? {}
|
|
677
|
+
: { audience: requiredText(config.audience, 'OIDC audience') }),
|
|
678
|
+
...(config.resource === undefined
|
|
679
|
+
? {}
|
|
680
|
+
: { resource: requiredText(config.resource, 'OIDC resource') }),
|
|
645
681
|
scopes: normalizeScopes(config.scopes, config.offlineAccess),
|
|
646
682
|
postLogoutRedirectUri: requiredUrl(
|
|
647
683
|
config.postLogoutRedirectUri ?? redirectUri,
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import { describe, expect, it, vi } from 'vitest';
|
|
2
|
+
import { ClerkNativeClient } from './clerk.js';
|
|
3
|
+
import { createWorkOsNativeClient, tokenTiming } from './workos.js';
|
|
4
|
+
import type { NativeOidcEnvironment } from './index.js';
|
|
5
|
+
|
|
6
|
+
function token(subject = 'user_123', expires = 300, sid = 'session_123'): string {
|
|
7
|
+
return `header.${btoa(JSON.stringify({ sub: subject, exp: expires, sid }))}.signature`;
|
|
8
|
+
}
|
|
9
|
+
|
|
10
|
+
function requestPayload(body: BodyInit | null | undefined): unknown {
|
|
11
|
+
if (typeof body !== 'string') throw new Error('Expected JSON request body');
|
|
12
|
+
return JSON.parse(body);
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
it('rejects missing and malformed scheduling claims without exposing token text', () => {
|
|
16
|
+
for (const value of [
|
|
17
|
+
'secret',
|
|
18
|
+
'header.invalid.signature',
|
|
19
|
+
`header.${btoa('{"sub":false,"exp":30}')}.signature`,
|
|
20
|
+
])
|
|
21
|
+
expect(() => tokenTiming(value)).toThrow('OIDC token endpoint returned an invalid response.');
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
describe('Clerk native contract', () => {
|
|
25
|
+
it('waits for the SDK bridge, refreshes, emits expiry and signs out', async () => {
|
|
26
|
+
const client = new ClerkNativeClient();
|
|
27
|
+
const initialize = client.initialize();
|
|
28
|
+
const getToken = vi
|
|
29
|
+
.fn<(skipCache: boolean) => Promise<string | null>>()
|
|
30
|
+
.mockResolvedValue(token());
|
|
31
|
+
const signOut = vi.fn<() => Promise<void>>().mockResolvedValue();
|
|
32
|
+
client.bind({
|
|
33
|
+
subject: () => 'user_123',
|
|
34
|
+
getToken,
|
|
35
|
+
signIn: () => Promise.resolve(true),
|
|
36
|
+
signOut,
|
|
37
|
+
});
|
|
38
|
+
expect((await initialize)?.subject).toBe('user_123');
|
|
39
|
+
const changes = vi.fn();
|
|
40
|
+
const expired = vi.fn();
|
|
41
|
+
client.subscribe(changes);
|
|
42
|
+
client.subscribeSessionExpired(expired);
|
|
43
|
+
expect(await client.signIn()).toEqual({ status: 'success', subject: 'user_123' });
|
|
44
|
+
expect(getToken).toHaveBeenLastCalledWith(true);
|
|
45
|
+
getToken.mockResolvedValue(null);
|
|
46
|
+
expect(await client.accessToken()).toBeUndefined();
|
|
47
|
+
expect(changes).toHaveBeenCalledWith(undefined);
|
|
48
|
+
expect(expired).toHaveBeenCalledWith({ type: 'session-expired', reason: 'refresh_rejected' });
|
|
49
|
+
expect(await client.signOut()).toEqual({ providerLogout: 'completed' });
|
|
50
|
+
expect(signOut).toHaveBeenCalledTimes(1);
|
|
51
|
+
});
|
|
52
|
+
it('handles cancellation, subject mismatch and logout failure', async () => {
|
|
53
|
+
const client = new ClerkNativeClient();
|
|
54
|
+
const getToken = vi.fn<() => Promise<string | null>>().mockResolvedValue(token('another_user'));
|
|
55
|
+
client.bind({
|
|
56
|
+
subject: () => 'user_123',
|
|
57
|
+
getToken,
|
|
58
|
+
signIn: () => Promise.resolve(false),
|
|
59
|
+
signOut: () => Promise.reject(new Error('network')),
|
|
60
|
+
});
|
|
61
|
+
expect(await client.signIn()).toEqual({ status: 'cancelled', reason: 'cancel' });
|
|
62
|
+
await expect(client.initialize()).rejects.toMatchObject({ code: 'invalid_token_response' });
|
|
63
|
+
expect(await client.signOut()).toEqual({ providerLogout: 'failed' });
|
|
64
|
+
expect(client.session()).toBeUndefined();
|
|
65
|
+
});
|
|
66
|
+
});
|
|
67
|
+
|
|
68
|
+
it('uses WorkOS public-client PKCE, JSON exchange, refresh rotation and session logout', async () => {
|
|
69
|
+
const values = new Map<string, string>();
|
|
70
|
+
let now = 1000;
|
|
71
|
+
const authorize = vi.fn<NativeOidcEnvironment['browser']['authorize']>().mockResolvedValue({
|
|
72
|
+
type: 'success',
|
|
73
|
+
code: 'code_123',
|
|
74
|
+
state: 'state',
|
|
75
|
+
expectedState: 'state',
|
|
76
|
+
codeVerifier: 'verifier',
|
|
77
|
+
});
|
|
78
|
+
const endSession = vi
|
|
79
|
+
.fn<NativeOidcEnvironment['browser']['endSession']>()
|
|
80
|
+
.mockImplementation(() => {
|
|
81
|
+
expect([...values.keys()].some((key) => key.endsWith('.session'))).toBe(false);
|
|
82
|
+
return Promise.resolve(true);
|
|
83
|
+
});
|
|
84
|
+
const fetch = vi
|
|
85
|
+
.fn<NativeOidcEnvironment['fetch']>()
|
|
86
|
+
.mockResolvedValueOnce(
|
|
87
|
+
new Response(JSON.stringify({ access_token: token(), refresh_token: 'refresh_1' })),
|
|
88
|
+
)
|
|
89
|
+
.mockResolvedValueOnce(
|
|
90
|
+
new Response(
|
|
91
|
+
JSON.stringify({ access_token: token('user_123', 600), refresh_token: 'refresh_2' }),
|
|
92
|
+
),
|
|
93
|
+
);
|
|
94
|
+
const environment: NativeOidcEnvironment = {
|
|
95
|
+
fetch,
|
|
96
|
+
now: () => now,
|
|
97
|
+
browser: { authorize, endSession },
|
|
98
|
+
storage: {
|
|
99
|
+
get: (key) => Promise.resolve(values.get(key) ?? null),
|
|
100
|
+
set: (key, value) => {
|
|
101
|
+
values.set(key, value);
|
|
102
|
+
return Promise.resolve();
|
|
103
|
+
},
|
|
104
|
+
delete: (key) => {
|
|
105
|
+
values.delete(key);
|
|
106
|
+
return Promise.resolve();
|
|
107
|
+
},
|
|
108
|
+
},
|
|
109
|
+
};
|
|
110
|
+
const client = createWorkOsNativeClient(
|
|
111
|
+
{
|
|
112
|
+
issuer: 'https://api.workos.com/',
|
|
113
|
+
clientId: 'client_app',
|
|
114
|
+
redirectUri: 'app://oauth',
|
|
115
|
+
offlineAccess: true,
|
|
116
|
+
},
|
|
117
|
+
environment,
|
|
118
|
+
);
|
|
119
|
+
expect(await client.signIn()).toEqual({ status: 'success', subject: 'user_123' });
|
|
120
|
+
expect(authorize).toHaveBeenCalledWith(
|
|
121
|
+
expect.objectContaining({
|
|
122
|
+
authorizationEndpoint: 'https://api.workos.com/user_management/authorize?provider=authkit',
|
|
123
|
+
clientId: 'client_app',
|
|
124
|
+
}),
|
|
125
|
+
);
|
|
126
|
+
expect(fetch.mock.calls[0]?.[0]).toBe('https://api.workos.com/user_management/authenticate');
|
|
127
|
+
expect(requestPayload(fetch.mock.calls[0]?.[1]?.body)).toEqual({
|
|
128
|
+
grant_type: 'authorization_code',
|
|
129
|
+
client_id: 'client_app',
|
|
130
|
+
code: 'code_123',
|
|
131
|
+
redirect_uri: 'app://oauth',
|
|
132
|
+
code_verifier: 'verifier',
|
|
133
|
+
});
|
|
134
|
+
now = 290000;
|
|
135
|
+
expect(await client.accessToken()).toBe(token('user_123', 600));
|
|
136
|
+
expect(client.session()?.refreshToken).toBe('refresh_2');
|
|
137
|
+
expect(requestPayload(fetch.mock.calls[1]?.[1]?.body)).toEqual({
|
|
138
|
+
grant_type: 'refresh_token',
|
|
139
|
+
client_id: 'client_app',
|
|
140
|
+
refresh_token: 'refresh_1',
|
|
141
|
+
});
|
|
142
|
+
expect(await client.signOut()).toEqual({ providerLogout: 'completed' });
|
|
143
|
+
expect(endSession).toHaveBeenCalledWith({
|
|
144
|
+
url: 'https://api.workos.com/user_management/sessions/logout?session_id=session_123&return_to=app%3A%2F%2Foauth',
|
|
145
|
+
redirectUri: 'app://oauth',
|
|
146
|
+
});
|
|
147
|
+
});
|