@baukit/auth-web 0.18.2 → 0.19.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 +78 -33
- package/dist/browser-session-client.d.ts +85 -0
- package/dist/browser-session-client.d.ts.map +1 -0
- package/dist/browser-session-client.js +339 -0
- package/dist/browser-session-client.js.map +1 -0
- package/dist/browser-session-support.d.ts +44 -0
- package/dist/browser-session-support.d.ts.map +1 -0
- package/dist/browser-session-support.js +102 -0
- package/dist/browser-session-support.js.map +1 -0
- package/dist/clerk.d.ts +1 -1
- package/dist/clerk.d.ts.map +1 -1
- package/dist/clerk.js.map +1 -1
- package/dist/index.d.ts +5 -95
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +3 -466
- package/dist/index.js.map +1 -1
- package/dist/oidc-client.d.ts +67 -0
- package/dist/oidc-client.d.ts.map +1 -0
- package/dist/oidc-client.js +135 -0
- package/dist/oidc-client.js.map +1 -0
- package/dist/oidc-errors.d.ts +15 -0
- package/dist/oidc-errors.d.ts.map +1 -0
- package/dist/oidc-errors.js +30 -0
- package/dist/oidc-errors.js.map +1 -0
- package/dist/oidc-helpers.d.ts +1 -1
- package/dist/oidc-helpers.d.ts.map +1 -1
- package/dist/oidc-validation.d.ts +15 -0
- package/dist/oidc-validation.d.ts.map +1 -0
- package/dist/oidc-validation.js +76 -0
- package/dist/oidc-validation.js.map +1 -0
- package/dist/session-events.d.ts +10 -0
- package/dist/session-events.d.ts.map +1 -0
- package/dist/session-events.js +2 -0
- package/dist/session-events.js.map +1 -0
- package/dist/silent-token-broker.d.ts.map +1 -1
- package/dist/silent-token-broker.js +39 -28
- package/dist/silent-token-broker.js.map +1 -1
- package/dist/workos.d.ts +1 -1
- package/dist/workos.d.ts.map +1 -1
- package/dist/workos.js +1 -1
- package/dist/workos.js.map +1 -1
- package/package.json +5 -3
- package/src/browser-session-client.test.ts +426 -0
- package/src/browser-session-client.ts +414 -0
- package/src/browser-session-refresh.test.ts +58 -0
- package/src/browser-session-storage.test.ts +113 -0
- package/src/browser-session-support.ts +153 -0
- package/src/clerk.ts +5 -1
- package/src/index.test.ts +98 -594
- package/src/index.ts +28 -663
- package/src/oidc-client.ts +229 -0
- package/src/oidc-errors.ts +46 -0
- package/src/oidc-helpers.ts +1 -1
- package/src/oidc-validation.ts +93 -0
- package/src/session-events.ts +12 -0
- package/src/silent-token-broker.ts +49 -33
- package/src/test-support/browser-session.ts +203 -0
- package/src/test-support/session-backend.ts +104 -0
- package/src/workos.ts +6 -6
|
@@ -0,0 +1,229 @@
|
|
|
1
|
+
import { OidcError } from './oidc-errors.js';
|
|
2
|
+
import {
|
|
3
|
+
base64UrlEncode,
|
|
4
|
+
buildAuthorizationUrl,
|
|
5
|
+
normalizeIssuer,
|
|
6
|
+
normalizeScopes,
|
|
7
|
+
randomUrlSafe,
|
|
8
|
+
requiredText,
|
|
9
|
+
requiredUrl,
|
|
10
|
+
} from './oidc-helpers.js';
|
|
11
|
+
import { discoverProvider, readTransaction } from './oidc-validation.js';
|
|
12
|
+
|
|
13
|
+
export interface OidcClientConfig {
|
|
14
|
+
readonly issuer: string;
|
|
15
|
+
readonly clientId: string;
|
|
16
|
+
readonly redirectUri: string;
|
|
17
|
+
readonly audience?: string;
|
|
18
|
+
readonly resource?: string;
|
|
19
|
+
/** `openid` is prepended when omitted. Defaults to `openid profile email`. */
|
|
20
|
+
readonly scopes?: readonly string[];
|
|
21
|
+
/** Adds `offline_access` to the requested scopes. Defaults to false. */
|
|
22
|
+
readonly offlineAccess?: boolean;
|
|
23
|
+
/** Overrides the deterministic, issuer/client-specific storage prefix. */
|
|
24
|
+
readonly storageKeyPrefix?: string;
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export interface OidcProviderMetadata {
|
|
28
|
+
readonly issuer: string;
|
|
29
|
+
readonly authorizationEndpoint: string;
|
|
30
|
+
readonly tokenEndpoint: string;
|
|
31
|
+
readonly endSessionEndpoint?: string;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export interface OidcClientEnvironment {
|
|
35
|
+
readonly fetch: typeof globalThis.fetch;
|
|
36
|
+
readonly crypto: Crypto;
|
|
37
|
+
readonly localStorage: Storage;
|
|
38
|
+
readonly sessionStorage: Storage;
|
|
39
|
+
readonly currentUrl: () => string;
|
|
40
|
+
readonly navigate: (url: string) => void;
|
|
41
|
+
readonly replaceUrl: (url: string) => void;
|
|
42
|
+
readonly now: () => number;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export interface PkceAuthorizationRequest {
|
|
46
|
+
readonly state: string;
|
|
47
|
+
readonly challenge: string;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** The verified authorization response, ready for the backend to redeem. */
|
|
51
|
+
export interface AuthorizationCallback {
|
|
52
|
+
readonly code: string;
|
|
53
|
+
readonly codeVerifier: string;
|
|
54
|
+
readonly redirectUri: string;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
interface NormalizedConfig {
|
|
58
|
+
readonly issuer: string;
|
|
59
|
+
readonly clientId: string;
|
|
60
|
+
readonly redirectUri: string;
|
|
61
|
+
readonly audience?: string;
|
|
62
|
+
readonly resource?: string;
|
|
63
|
+
readonly scopes: readonly string[];
|
|
64
|
+
readonly storageKeyPrefix: string;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
const CALLBACK_PARAMETERS = [
|
|
68
|
+
'code',
|
|
69
|
+
'state',
|
|
70
|
+
'session_state',
|
|
71
|
+
'iss',
|
|
72
|
+
'error',
|
|
73
|
+
'error_description',
|
|
74
|
+
'error_uri',
|
|
75
|
+
] as const;
|
|
76
|
+
|
|
77
|
+
/**
|
|
78
|
+
* Browser OIDC authorization-code redirect with S256 PKCE. It never redeems the
|
|
79
|
+
* code and never holds tokens; `BrowserSessionClient` hands the code to the backend.
|
|
80
|
+
*/
|
|
81
|
+
export class OidcClient {
|
|
82
|
+
public readonly storageKeyPrefix: string;
|
|
83
|
+
private readonly config: NormalizedConfig;
|
|
84
|
+
private readonly environment: OidcClientEnvironment;
|
|
85
|
+
private readonly transactionStorageKey: string;
|
|
86
|
+
private readonly forceLoginStorageKey: string;
|
|
87
|
+
private metadataPromise: Promise<OidcProviderMetadata> | undefined;
|
|
88
|
+
|
|
89
|
+
public constructor(
|
|
90
|
+
config: OidcClientConfig,
|
|
91
|
+
environment: OidcClientEnvironment = browserOidcEnvironment(),
|
|
92
|
+
) {
|
|
93
|
+
this.config = normalizeConfig(config);
|
|
94
|
+
this.environment = environment;
|
|
95
|
+
this.storageKeyPrefix = this.config.storageKeyPrefix;
|
|
96
|
+
this.transactionStorageKey = `${this.storageKeyPrefix}:transaction`;
|
|
97
|
+
this.forceLoginStorageKey = `${this.storageKeyPrefix}:force-login`;
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
public discover(): Promise<OidcProviderMetadata> {
|
|
101
|
+
this.metadataPromise ??= discoverProvider(this.config.issuer, this.environment.fetch);
|
|
102
|
+
return this.metadataPromise;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** Stores the PKCE transaction in sessionStorage and navigates to the provider. */
|
|
106
|
+
public async login(): Promise<void> {
|
|
107
|
+
const metadata = await this.discover();
|
|
108
|
+
const state = randomUrlSafe(this.environment.crypto, 32);
|
|
109
|
+
const verifier = randomUrlSafe(this.environment.crypto, 64);
|
|
110
|
+
const challenge = base64UrlEncode(
|
|
111
|
+
new Uint8Array(
|
|
112
|
+
await this.environment.crypto.subtle.digest('SHA-256', new TextEncoder().encode(verifier)),
|
|
113
|
+
),
|
|
114
|
+
);
|
|
115
|
+
this.environment.sessionStorage.setItem(
|
|
116
|
+
this.transactionStorageKey,
|
|
117
|
+
JSON.stringify({ state, verifier }),
|
|
118
|
+
);
|
|
119
|
+
const authorizationUrl = buildAuthorizationUrl(
|
|
120
|
+
this.config,
|
|
121
|
+
metadata.authorizationEndpoint,
|
|
122
|
+
{ state, challenge },
|
|
123
|
+
this.environment.localStorage.getItem(this.forceLoginStorageKey) === null
|
|
124
|
+
? undefined
|
|
125
|
+
: 'login',
|
|
126
|
+
);
|
|
127
|
+
this.environment.navigate(authorizationUrl.toString());
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Strips the callback parameters from the URL and checks state and issuer.
|
|
132
|
+
* Returns `undefined` when the current URL is not a callback.
|
|
133
|
+
*/
|
|
134
|
+
public completeCallback(): AuthorizationCallback | undefined {
|
|
135
|
+
const callback = new URL(this.environment.currentUrl());
|
|
136
|
+
if (!hasCallbackParameters(callback)) {
|
|
137
|
+
return undefined;
|
|
138
|
+
}
|
|
139
|
+
const code = callback.searchParams.get('code');
|
|
140
|
+
const returnedState = callback.searchParams.get('state');
|
|
141
|
+
const returnedIssuer = callback.searchParams.get('iss');
|
|
142
|
+
const providerError = callback.searchParams.has('error');
|
|
143
|
+
for (const parameter of CALLBACK_PARAMETERS) {
|
|
144
|
+
callback.searchParams.delete(parameter);
|
|
145
|
+
}
|
|
146
|
+
this.environment.replaceUrl(callback.toString());
|
|
147
|
+
|
|
148
|
+
const transaction = readTransaction(
|
|
149
|
+
this.environment.sessionStorage.getItem(this.transactionStorageKey),
|
|
150
|
+
);
|
|
151
|
+
this.clearTransaction();
|
|
152
|
+
if (returnedState === null || transaction?.state !== returnedState) {
|
|
153
|
+
throw new OidcError('callback_state_mismatch');
|
|
154
|
+
}
|
|
155
|
+
if (returnedIssuer !== null && normalizeIssuer(returnedIssuer) !== this.config.issuer) {
|
|
156
|
+
throw new OidcError('issuer_mismatch');
|
|
157
|
+
}
|
|
158
|
+
if (providerError) {
|
|
159
|
+
throw new OidcError('authorization_failed');
|
|
160
|
+
}
|
|
161
|
+
if (code === null) {
|
|
162
|
+
throw new OidcError('callback_state_mismatch');
|
|
163
|
+
}
|
|
164
|
+
return { code, codeVerifier: transaction.verifier, redirectUri: this.config.redirectUri };
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
/** Makes the next `login()` request `prompt=login`, surviving reloads. */
|
|
168
|
+
public requireFreshLogin(): void {
|
|
169
|
+
this.environment.localStorage.setItem(this.forceLoginStorageKey, '1');
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
/** Drops the fresh-login requirement after a successful sign-in. */
|
|
173
|
+
public confirmFreshLogin(): void {
|
|
174
|
+
this.environment.localStorage.removeItem(this.forceLoginStorageKey);
|
|
175
|
+
}
|
|
176
|
+
|
|
177
|
+
public clearTransaction(): void {
|
|
178
|
+
this.environment.sessionStorage.removeItem(this.transactionStorageKey);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function normalizeConfig(config: OidcClientConfig): NormalizedConfig {
|
|
183
|
+
const issuer = normalizeIssuer(config.issuer);
|
|
184
|
+
const clientId = requiredText(config.clientId, 'OIDC client ID');
|
|
185
|
+
const storageKeyPrefix =
|
|
186
|
+
config.storageKeyPrefix ?? `@baukit/auth-web:${encodeURIComponent(issuer)}:${clientId}`;
|
|
187
|
+
if (storageKeyPrefix.length === 0) {
|
|
188
|
+
throw new TypeError('OIDC storage key prefix must not be empty.');
|
|
189
|
+
}
|
|
190
|
+
return {
|
|
191
|
+
issuer,
|
|
192
|
+
clientId,
|
|
193
|
+
redirectUri: requiredUrl(config.redirectUri, 'OIDC redirect URI'),
|
|
194
|
+
...(config.audience === undefined
|
|
195
|
+
? {}
|
|
196
|
+
: { audience: requiredText(config.audience, 'OIDC audience') }),
|
|
197
|
+
...(config.resource === undefined
|
|
198
|
+
? {}
|
|
199
|
+
: { resource: requiredText(config.resource, 'OIDC resource') }),
|
|
200
|
+
scopes: normalizeScopes(config.scopes, config.offlineAccess),
|
|
201
|
+
storageKeyPrefix,
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
function hasCallbackParameters(url: URL): boolean {
|
|
206
|
+
return ['code', 'state', 'error', 'iss', 'session_state'].some((name) =>
|
|
207
|
+
url.searchParams.has(name),
|
|
208
|
+
);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
export function browserOidcEnvironment(): OidcClientEnvironment {
|
|
212
|
+
if (typeof window === 'undefined') {
|
|
213
|
+
throw new Error('OidcClient requires a browser environment or an explicit environment.');
|
|
214
|
+
}
|
|
215
|
+
return {
|
|
216
|
+
fetch: globalThis.fetch.bind(globalThis),
|
|
217
|
+
crypto: globalThis.crypto,
|
|
218
|
+
localStorage: window.localStorage,
|
|
219
|
+
sessionStorage: window.sessionStorage,
|
|
220
|
+
currentUrl: () => window.location.href,
|
|
221
|
+
navigate: (url) => {
|
|
222
|
+
window.location.assign(url);
|
|
223
|
+
},
|
|
224
|
+
replaceUrl: (url) => {
|
|
225
|
+
window.history.replaceState({}, '', url);
|
|
226
|
+
},
|
|
227
|
+
now: () => Date.now(),
|
|
228
|
+
};
|
|
229
|
+
}
|
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
export type OidcErrorCode =
|
|
2
|
+
| 'authorization_failed'
|
|
3
|
+
| 'callback_state_mismatch'
|
|
4
|
+
| 'discovery_failed'
|
|
5
|
+
| 'invalid_discovery_document'
|
|
6
|
+
| 'invalid_token_response'
|
|
7
|
+
| 'issuer_mismatch'
|
|
8
|
+
| 'logout_failed'
|
|
9
|
+
| 'refresh_failed'
|
|
10
|
+
| 'token_exchange_failed';
|
|
11
|
+
|
|
12
|
+
const SAFE_ERROR_MESSAGES = {
|
|
13
|
+
authorization_failed: 'OIDC authorization failed.',
|
|
14
|
+
callback_state_mismatch: 'OIDC callback state did not match the login transaction.',
|
|
15
|
+
discovery_failed: 'OIDC provider discovery failed.',
|
|
16
|
+
invalid_discovery_document: 'OIDC provider returned invalid discovery metadata.',
|
|
17
|
+
invalid_token_response: 'The session endpoint returned an invalid response.',
|
|
18
|
+
issuer_mismatch: 'OIDC provider issuer did not match the configured issuer.',
|
|
19
|
+
logout_failed: 'Sign-out failed.',
|
|
20
|
+
refresh_failed: 'OIDC token refresh failed.',
|
|
21
|
+
token_exchange_failed: 'OIDC token exchange failed.',
|
|
22
|
+
} as const satisfies Record<OidcErrorCode, string>;
|
|
23
|
+
|
|
24
|
+
/** An authentication failure whose message is safe to display or log. */
|
|
25
|
+
export class OidcError extends Error {
|
|
26
|
+
public readonly code: OidcErrorCode;
|
|
27
|
+
public readonly status: number | undefined;
|
|
28
|
+
/** True only when retrying the failed operation may succeed without signing in again. */
|
|
29
|
+
public readonly retryable: boolean;
|
|
30
|
+
|
|
31
|
+
public constructor(
|
|
32
|
+
code: OidcErrorCode,
|
|
33
|
+
options: { readonly retryable?: boolean; readonly status?: number } = {},
|
|
34
|
+
) {
|
|
35
|
+
super(SAFE_ERROR_MESSAGES[code]);
|
|
36
|
+
this.name = 'OidcError';
|
|
37
|
+
this.code = code;
|
|
38
|
+
this.status = options.status;
|
|
39
|
+
this.retryable = options.retryable ?? false;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
/** Returns an allowlisted message without reflecting untrusted error content. */
|
|
44
|
+
export function safeAuthErrorMessage(cause: unknown): string {
|
|
45
|
+
return cause instanceof OidcError ? SAFE_ERROR_MESSAGES[cause.code] : 'OIDC login failed.';
|
|
46
|
+
}
|
package/src/oidc-helpers.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { OidcClientConfig, PkceAuthorizationRequest } from './
|
|
1
|
+
import type { OidcClientConfig, PkceAuthorizationRequest } from './oidc-client.js';
|
|
2
2
|
|
|
3
3
|
/** Removes trailing issuer slashes while rejecting query strings and fragments. */
|
|
4
4
|
export function normalizeIssuer(issuer: string): string {
|
|
@@ -0,0 +1,93 @@
|
|
|
1
|
+
import { isRecord } from '@baukit/type-guards';
|
|
2
|
+
|
|
3
|
+
import { OidcError } from './oidc-errors.js';
|
|
4
|
+
import { normalizeIssuer, requiredUrl } from './oidc-helpers.js';
|
|
5
|
+
import type { OidcProviderMetadata } from './oidc-client.js';
|
|
6
|
+
|
|
7
|
+
export interface LoginTransaction {
|
|
8
|
+
readonly state: string;
|
|
9
|
+
readonly verifier: string;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export interface RawProviderMetadata {
|
|
13
|
+
readonly issuer: string;
|
|
14
|
+
readonly authorization_endpoint: string;
|
|
15
|
+
readonly token_endpoint: string;
|
|
16
|
+
readonly end_session_endpoint?: string;
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
export function readTransaction(raw: string | null): LoginTransaction | undefined {
|
|
20
|
+
if (raw === null) {
|
|
21
|
+
return undefined;
|
|
22
|
+
}
|
|
23
|
+
try {
|
|
24
|
+
const value: unknown = JSON.parse(raw);
|
|
25
|
+
return isRecord(value) &&
|
|
26
|
+
typeof value['state'] === 'string' &&
|
|
27
|
+
value['state'].length > 0 &&
|
|
28
|
+
typeof value['verifier'] === 'string' &&
|
|
29
|
+
value['verifier'].length > 0
|
|
30
|
+
? { state: value['state'], verifier: value['verifier'] }
|
|
31
|
+
: undefined;
|
|
32
|
+
} catch {
|
|
33
|
+
return undefined;
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export function isProviderMetadata(value: unknown): value is RawProviderMetadata {
|
|
38
|
+
if (
|
|
39
|
+
!isRecord(value) ||
|
|
40
|
+
typeof value['issuer'] !== 'string' ||
|
|
41
|
+
typeof value['authorization_endpoint'] !== 'string' ||
|
|
42
|
+
typeof value['token_endpoint'] !== 'string' ||
|
|
43
|
+
(value['end_session_endpoint'] !== undefined &&
|
|
44
|
+
typeof value['end_session_endpoint'] !== 'string')
|
|
45
|
+
) {
|
|
46
|
+
return false;
|
|
47
|
+
}
|
|
48
|
+
try {
|
|
49
|
+
requiredUrl(value['authorization_endpoint'], 'OIDC authorization endpoint');
|
|
50
|
+
requiredUrl(value['token_endpoint'], 'OIDC token endpoint');
|
|
51
|
+
if (value['end_session_endpoint'] !== undefined) {
|
|
52
|
+
requiredUrl(value['end_session_endpoint'], 'OIDC end-session endpoint');
|
|
53
|
+
}
|
|
54
|
+
return true;
|
|
55
|
+
} catch {
|
|
56
|
+
return false;
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
export async function discoverProvider(
|
|
61
|
+
issuer: string,
|
|
62
|
+
fetchImplementation: typeof globalThis.fetch,
|
|
63
|
+
): Promise<OidcProviderMetadata> {
|
|
64
|
+
let response: Response;
|
|
65
|
+
try {
|
|
66
|
+
response = await fetchImplementation(`${issuer}/.well-known/openid-configuration`);
|
|
67
|
+
} catch {
|
|
68
|
+
throw new OidcError('discovery_failed');
|
|
69
|
+
}
|
|
70
|
+
if (!response.ok) {
|
|
71
|
+
throw new OidcError('discovery_failed', { status: response.status });
|
|
72
|
+
}
|
|
73
|
+
let value: unknown;
|
|
74
|
+
try {
|
|
75
|
+
value = await response.json();
|
|
76
|
+
} catch {
|
|
77
|
+
throw new OidcError('invalid_discovery_document');
|
|
78
|
+
}
|
|
79
|
+
if (!isProviderMetadata(value)) {
|
|
80
|
+
throw new OidcError('invalid_discovery_document');
|
|
81
|
+
}
|
|
82
|
+
if (normalizeIssuer(value.issuer) !== issuer) {
|
|
83
|
+
throw new OidcError('issuer_mismatch');
|
|
84
|
+
}
|
|
85
|
+
return {
|
|
86
|
+
issuer,
|
|
87
|
+
authorizationEndpoint: value.authorization_endpoint,
|
|
88
|
+
tokenEndpoint: value.token_endpoint,
|
|
89
|
+
...(value.end_session_endpoint === undefined
|
|
90
|
+
? {}
|
|
91
|
+
: { endSessionEndpoint: value.end_session_endpoint }),
|
|
92
|
+
};
|
|
93
|
+
}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
export type SessionExpiredReason = 'refresh_rejected' | 'signed_out' | 'profile_erased';
|
|
2
|
+
|
|
3
|
+
export interface ClearSessionOptions {
|
|
4
|
+
readonly reason?: 'profile_erased';
|
|
5
|
+
}
|
|
6
|
+
|
|
7
|
+
export interface SessionExpiredEvent {
|
|
8
|
+
readonly type: 'session-expired';
|
|
9
|
+
readonly reason: SessionExpiredReason;
|
|
10
|
+
}
|
|
11
|
+
|
|
12
|
+
export type SessionExpiredListener = (event: SessionExpiredEvent) => void;
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { isNonEmptyString, isRecord } from '@baukit/type-guards';
|
|
1
2
|
import { createLocalJWKSet, jwtVerify, type JSONWebKeySet } from 'jose';
|
|
2
3
|
import {
|
|
3
4
|
base64UrlEncode,
|
|
@@ -242,7 +243,8 @@ export class SilentTokenBroker {
|
|
|
242
243
|
target = this.environment.open(interactive);
|
|
243
244
|
if (interactive) {
|
|
244
245
|
popupPoll = setInterval(() => {
|
|
245
|
-
if (target?.closed
|
|
246
|
+
if (target?.closed === true)
|
|
247
|
+
controller.abort(new AuthorizationError('interaction_cancelled'));
|
|
246
248
|
}, POPUP_POLL_INTERVAL_MS);
|
|
247
249
|
}
|
|
248
250
|
return await abortable(
|
|
@@ -312,9 +314,7 @@ export class SilentTokenBroker {
|
|
|
312
314
|
const tokens = validateTokenResponse(value, receivedAt);
|
|
313
315
|
const signedExpiresAt = await this.verifyTokenClaims(
|
|
314
316
|
product,
|
|
315
|
-
metadata.jwksUri,
|
|
316
|
-
tokens,
|
|
317
|
-
transaction.nonce,
|
|
317
|
+
{ jwksUri: metadata.jwksUri, tokens, nonce: transaction.nonce },
|
|
318
318
|
signal,
|
|
319
319
|
);
|
|
320
320
|
signal.throwIfAborted();
|
|
@@ -325,13 +325,12 @@ export class SilentTokenBroker {
|
|
|
325
325
|
|
|
326
326
|
private async verifyTokenClaims(
|
|
327
327
|
product: SilentTokenProduct,
|
|
328
|
-
jwksUri:
|
|
329
|
-
tokens: TokenResponse,
|
|
330
|
-
nonce: string,
|
|
328
|
+
{ jwksUri, tokens, nonce }: TokenVerification,
|
|
331
329
|
signal: AbortSignal,
|
|
332
330
|
): Promise<number> {
|
|
333
331
|
const { value: jwks } = await this.json(jwksUri, signal);
|
|
334
|
-
|
|
332
|
+
if (!isJsonWebKeySet(jwks)) throw new SilentTokenError('invalid_response');
|
|
333
|
+
const keys = createLocalJWKSet(jwks);
|
|
335
334
|
const options = {
|
|
336
335
|
issuer: product.issuer,
|
|
337
336
|
algorithms: ['RS256'],
|
|
@@ -353,7 +352,7 @@ export class SilentTokenBroker {
|
|
|
353
352
|
audience: product.audience,
|
|
354
353
|
});
|
|
355
354
|
if (
|
|
356
|
-
!id.sub ||
|
|
355
|
+
!isNonEmptyString(id.sub) ||
|
|
357
356
|
access.sub !== id.sub ||
|
|
358
357
|
access['azp'] !== product.clientId ||
|
|
359
358
|
access[this.accountBinding.claim] !== this.accountBinding.value
|
|
@@ -403,9 +402,8 @@ export class SilentTokenBroker {
|
|
|
403
402
|
if (!response.ok) throw new SilentTokenError('http_error');
|
|
404
403
|
const value: unknown = await response.json();
|
|
405
404
|
signal.throwIfAborted();
|
|
406
|
-
if (
|
|
407
|
-
|
|
408
|
-
return { value: value as Record<string, unknown>, receivedAt };
|
|
405
|
+
if (!isRecord(value)) throw new SilentTokenError('invalid_response');
|
|
406
|
+
return { value, receivedAt };
|
|
409
407
|
}
|
|
410
408
|
}
|
|
411
409
|
|
|
@@ -432,13 +430,24 @@ function validateTokenResponse(tokens: Record<string, unknown>, receivedAt: numb
|
|
|
432
430
|
|
|
433
431
|
function callbackCode(callback: string, product: SilentTokenProduct, state: string): string {
|
|
434
432
|
const returned = new URL(callback);
|
|
435
|
-
|
|
433
|
+
assertCallbackShape(returned, new URL(product.redirectUri));
|
|
434
|
+
if (returned.searchParams.get('state') !== state) throw new SilentTokenError('invalid_state');
|
|
435
|
+
if (returned.searchParams.get('iss') !== product.issuer)
|
|
436
|
+
throw new SilentTokenError('invalid_issuer');
|
|
437
|
+
const error = returned.searchParams.get('error');
|
|
438
|
+
if (error !== null) throw callbackError(error, returned.searchParams.has('code'));
|
|
439
|
+
const code = returned.searchParams.get('code');
|
|
440
|
+
if (!isNonEmptyString(code)) throw new SilentTokenError('missing_code');
|
|
441
|
+
return code;
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
function assertCallbackShape(returned: URL, expected: URL): void {
|
|
436
445
|
if (
|
|
437
446
|
returned.origin !== expected.origin ||
|
|
438
447
|
returned.pathname !== expected.pathname ||
|
|
439
|
-
returned.hash ||
|
|
440
|
-
returned.username ||
|
|
441
|
-
returned.password
|
|
448
|
+
returned.hash !== '' ||
|
|
449
|
+
returned.username !== '' ||
|
|
450
|
+
returned.password !== ''
|
|
442
451
|
) {
|
|
443
452
|
throw new SilentTokenError('invalid_callback');
|
|
444
453
|
}
|
|
@@ -446,23 +455,30 @@ function callbackCode(callback: string, product: SilentTokenProduct, state: stri
|
|
|
446
455
|
if (returned.searchParams.getAll(field).length > 1)
|
|
447
456
|
throw new SilentTokenError('invalid_callback');
|
|
448
457
|
}
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
if (
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
458
|
+
}
|
|
459
|
+
|
|
460
|
+
function callbackError(error: string, hasCode: boolean): Error {
|
|
461
|
+
if (hasCode) return new SilentTokenError('invalid_callback');
|
|
462
|
+
if (
|
|
463
|
+
error === 'login_required' ||
|
|
464
|
+
error === 'interaction_required' ||
|
|
465
|
+
error === 'consent_required'
|
|
466
|
+
)
|
|
467
|
+
return new AuthorizationError(error);
|
|
468
|
+
return new SilentTokenError('authorization_rejected');
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
interface TokenVerification {
|
|
472
|
+
readonly jwksUri: string;
|
|
473
|
+
readonly tokens: TokenResponse;
|
|
474
|
+
readonly nonce: string;
|
|
475
|
+
}
|
|
476
|
+
|
|
477
|
+
function isJsonWebKeySet(
|
|
478
|
+
value: Record<string, unknown>,
|
|
479
|
+
): value is Record<string, unknown> & JSONWebKeySet {
|
|
480
|
+
const keys = value['keys'];
|
|
481
|
+
return Array.isArray(keys) && keys.every((key) => isRecord(key) && isNonEmptyString(key['kty']));
|
|
466
482
|
}
|
|
467
483
|
|
|
468
484
|
function failureResult(
|