@baukit/auth-native 0.8.0 → 0.10.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/src/workos.ts ADDED
@@ -0,0 +1,109 @@
1
+ import {
2
+ NativeOidcClient,
3
+ OidcError,
4
+ type NativeOidcConfig,
5
+ type NativeOidcEnvironment,
6
+ type NativeTokenProtocol,
7
+ } from './index.js';
8
+
9
+ /** Reads scheduling claims only. The backend verifies the token before accepting it. */
10
+ export function tokenTiming(token: string): { subject: string; expiresAt: number } {
11
+ try {
12
+ const encoded = token.split('.')[1];
13
+ if (encoded === undefined) throw new OidcError('invalid_token_response');
14
+ const value: unknown = JSON.parse(
15
+ globalThis.atob(encoded.replaceAll('-', '+').replaceAll('_', '/')),
16
+ );
17
+ if (
18
+ typeof value !== 'object' ||
19
+ value === null ||
20
+ !('sub' in value) ||
21
+ !('exp' in value) ||
22
+ typeof value.sub !== 'string' ||
23
+ value.sub.length === 0 ||
24
+ typeof value.exp !== 'number' ||
25
+ !Number.isFinite(value.exp)
26
+ ) {
27
+ throw new OidcError('invalid_token_response');
28
+ }
29
+ return { subject: value.sub, expiresAt: value.exp * 1000 };
30
+ } catch {
31
+ throw new OidcError('invalid_token_response');
32
+ }
33
+ }
34
+
35
+ function workosProtocol(
36
+ config: NativeOidcConfig,
37
+ environment: NativeOidcEnvironment,
38
+ ): NativeTokenProtocol {
39
+ const base = config.issuer.replace(/\/+$/u, '');
40
+ return {
41
+ async logout(session, redirectUri) {
42
+ const encoded = session.accessToken.split('.')[1];
43
+ if (encoded === undefined) throw new OidcError('invalid_token_response');
44
+ const claims: unknown = JSON.parse(
45
+ globalThis.atob(encoded.replaceAll('-', '+').replaceAll('_', '/')),
46
+ );
47
+ if (
48
+ typeof claims !== 'object' ||
49
+ claims === null ||
50
+ !('sid' in claims) ||
51
+ typeof claims.sid !== 'string' ||
52
+ claims.sid.length === 0
53
+ )
54
+ throw new OidcError('invalid_token_response');
55
+ const url = new URL(`${base}/user_management/sessions/logout`);
56
+ url.searchParams.set('session_id', claims.sid);
57
+ url.searchParams.set('return_to', redirectUri);
58
+ return environment.browser.endSession({ url: url.toString(), redirectUri });
59
+ },
60
+ discover: () =>
61
+ Promise.resolve({
62
+ issuer: base,
63
+ authorizationEndpoint: `${base}/user_management/authorize?provider=authkit`,
64
+ tokenEndpoint: `${base}/user_management/authenticate`,
65
+ userInfoEndpoint: `${base}/user_management/users`,
66
+ }),
67
+ async exchange(endpoint, body) {
68
+ const payload = Object.fromEntries(body);
69
+ delete payload['scope'];
70
+ const response = await environment.fetch(endpoint, {
71
+ method: 'POST',
72
+ headers: { 'content-type': 'application/json' },
73
+ body: JSON.stringify(payload),
74
+ });
75
+ if (!response.ok) return response;
76
+ const value: unknown = await response.json();
77
+ if (
78
+ typeof value !== 'object' ||
79
+ value === null ||
80
+ !('access_token' in value) ||
81
+ typeof value.access_token !== 'string'
82
+ )
83
+ throw new OidcError('invalid_token_response');
84
+ const timing = tokenTiming(value.access_token);
85
+ return new Response(
86
+ JSON.stringify({
87
+ ...value,
88
+ expires_in: Math.max(0, (timing.expiresAt - environment.now()) / 1000),
89
+ }),
90
+ {
91
+ status: response.status,
92
+ headers: { 'content-type': 'application/json' },
93
+ },
94
+ );
95
+ },
96
+ subject: (token) => Promise.resolve(tokenTiming(token).subject),
97
+ };
98
+ }
99
+
100
+ /** AuthKit public-client PKCE, without an API key in the application bundle. */
101
+ export function createWorkOsNativeClient(
102
+ config: NativeOidcConfig,
103
+ environment: NativeOidcEnvironment,
104
+ ): NativeOidcClient {
105
+ return new NativeOidcClient(config, {
106
+ ...environment,
107
+ protocol: workosProtocol(config, environment),
108
+ });
109
+ }