@oxog/authkeeper 1.3.0 → 1.4.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/CHANGELOG.md +24 -0
- package/README.md +80 -2
- package/dist/auth-source-BaZ_-Fu7.d.cts +24 -0
- package/dist/auth-source-Cm0R6C6I.d.ts +24 -0
- package/dist/chunk-62XK5QLP.cjs +19 -0
- package/dist/chunk-62XK5QLP.cjs.map +1 -0
- package/dist/chunk-CYCWWUCJ.js +17 -0
- package/dist/chunk-CYCWWUCJ.js.map +1 -0
- package/dist/{chunk-7KKUG6IF.cjs → chunk-EXV2RG6T.cjs} +71 -45
- package/dist/chunk-EXV2RG6T.cjs.map +1 -0
- package/dist/{chunk-3YDUKFDO.js → chunk-KE7V52DI.js} +61 -34
- package/dist/chunk-KE7V52DI.js.map +1 -0
- package/dist/chunk-KLT44YR2.cjs +69 -0
- package/dist/chunk-KLT44YR2.cjs.map +1 -0
- package/dist/chunk-SUGFPZ6O.js +66 -0
- package/dist/chunk-SUGFPZ6O.js.map +1 -0
- package/dist/index-BF4j_buH.d.ts +488 -0
- package/dist/index-CuvfPscu.d.cts +488 -0
- package/dist/index.cjs +69 -54
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +9 -3
- package/dist/index.d.ts +9 -3
- package/dist/index.js +21 -5
- package/dist/index.js.map +1 -1
- package/dist/plugins/index.cjs +15 -14
- package/dist/plugins/index.d.cts +2 -1
- package/dist/plugins/index.d.ts +2 -1
- package/dist/plugins/index.js +2 -1
- package/dist/react/index.cjs +40 -3
- package/dist/react/index.cjs.map +1 -1
- package/dist/react/index.d.cts +42 -5
- package/dist/react/index.d.ts +42 -5
- package/dist/react/index.js +38 -3
- package/dist/react/index.js.map +1 -1
- package/dist/svelte/index.cjs +37 -3
- package/dist/svelte/index.cjs.map +1 -1
- package/dist/svelte/index.d.cts +23 -5
- package/dist/svelte/index.d.ts +23 -5
- package/dist/svelte/index.js +37 -3
- package/dist/svelte/index.js.map +1 -1
- package/dist/types-Bmo8S8O4.d.cts +421 -0
- package/dist/types-Bmo8S8O4.d.ts +421 -0
- package/dist/vue/index.cjs +46 -3
- package/dist/vue/index.cjs.map +1 -1
- package/dist/vue/index.d.cts +45 -5
- package/dist/vue/index.d.ts +45 -5
- package/dist/vue/index.js +43 -3
- package/dist/vue/index.js.map +1 -1
- package/package.json +10 -5
- package/dist/chunk-3YDUKFDO.js.map +0 -1
- package/dist/chunk-7KKUG6IF.cjs.map +0 -1
- package/dist/index-B05Msx7M.d.cts +0 -898
- package/dist/index-B05Msx7M.d.ts +0 -898
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,30 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [1.4.0] - 2026-12-02
|
|
11
|
+
|
|
12
|
+
### Added
|
|
13
|
+
|
|
14
|
+
- Framework adapters, replacing the placeholder entry points: `@oxog/authkeeper/react` (`AuthProvider`, `useAuth()`, `useAuthKeeper()`; `useSyncExternalStore`, signed-out state on the server and during hydration), `@oxog/authkeeper/vue` (`useAuth()` composable with read-only refs, `provideAuth()`, `injectAuth()`, `authKeeperPlugin()`) and `@oxog/authkeeper/svelte` (`createAuthStore()`, a readable store for Svelte 3–5). They share one state shape (`isAuthenticated`, `accessToken`, `user`, `expiresAt`, `error`), update on login / refresh / logout / error events and at token expiry, and stop listening on unmount.
|
|
15
|
+
|
|
16
|
+
### Changed
|
|
17
|
+
|
|
18
|
+
- Peer dependencies (all optional): `react` `>=18.0.0` (was `>=17.0.0`; the hooks need `useSyncExternalStore`), `vue` `>=3.2.0` (was `>=3.0.0`; `onScopeDispose`), and `@types/react` `>=18.0.0` is declared because the React adapter's types import React's (React 19 no longer bundles them).
|
|
19
|
+
|
|
20
|
+
### Fixed
|
|
21
|
+
|
|
22
|
+
- A handler subscribed after an event was emitted, but before its next-tick delivery, still received that event (e.g. `auth.setTokens(...)` then `auth.on('login', ...)` fired for that earlier login). Events now go only to handlers subscribed when they are emitted and still subscribed at delivery.
|
|
23
|
+
- Events emitted just before `destroy()` (e.g. `logout()` then `destroy()`) were still delivered to the handlers afterwards, and their delivery timers outlived the instance. `destroy()` now cancels deliveries that have not run yet.
|
|
24
|
+
- Tokens restored from storage whose access token had already expired were never refreshed on start, so the user stayed logged out until a request got a 401, although a refresh token was stored. `createAuthKeeper()` now starts a refresh for them in the background (not with `autoRefresh: false`); `await auth.refresh()` waits for it.
|
|
25
|
+
|
|
26
|
+
## [1.3.1] - 2026-12-02
|
|
27
|
+
|
|
28
|
+
### Fixed
|
|
29
|
+
|
|
30
|
+
- `createFetch()` / `wrapFetch()`: a 401 for a request sent with the old access token, arriving after another request's refresh had already finished, started a second token refresh. Such a request is now retried with the current token without refreshing again (likewise a request sent before login is retried with the new token). A 401 for the current token still refreshes.
|
|
31
|
+
- `refresh()` after a logout and a new login, while a failed refresh of the old session was waiting to retry, returned that old refresh, which then failed with "Session changed while refreshing" instead of refreshing the new session. It now refreshes the new session, and the old refresh gives up at once instead of after its retry delay.
|
|
32
|
+
- `destroy()` during a refresh retry delay left the timer running (up to `retryDelay * 2^n` ms), after which another attempt started (`onRefreshStart` was called on a destroyed instance). The timer is now cleared and the pending `refresh()` is rejected at once.
|
|
33
|
+
|
|
10
34
|
## [1.3.0] - 2026-12-02
|
|
11
35
|
|
|
12
36
|
### Added
|
package/README.md
CHANGED
|
@@ -145,6 +145,10 @@ const auth = await createAuthKeeper({
|
|
|
145
145
|
```
|
|
146
146
|
|
|
147
147
|
- Persisted tokens are restored by `createAuthKeeper()` and auto-refresh resumes.
|
|
148
|
+
If the restored access token has already expired and a refresh token is
|
|
149
|
+
stored, a refresh starts in the background right away (unless
|
|
150
|
+
`autoRefresh: false`); `await auth.refresh()` waits for it, and a failure is
|
|
151
|
+
reported like any refresh failure (`error` event, `onError`).
|
|
148
152
|
- `logout()` / `clearTokens()` remove them; `destroy()` does not.
|
|
149
153
|
- Corrupt entries are discarded; storage failures are reported as `error`
|
|
150
154
|
events with `context: 'storage'` instead of throwing.
|
|
@@ -229,6 +233,11 @@ auth.on('error', (event) => {
|
|
|
229
233
|
})
|
|
230
234
|
```
|
|
231
235
|
|
|
236
|
+
Handlers run asynchronously, on the next tick after the change. An event goes
|
|
237
|
+
to the handlers that were subscribed when it happened (and are still
|
|
238
|
+
subscribed when it is delivered): subscribing right after `setTokens()` does
|
|
239
|
+
not replay that login. `destroy()` cancels deliveries that have not run yet.
|
|
240
|
+
|
|
232
241
|
### JWT Decoding
|
|
233
242
|
|
|
234
243
|
```typescript
|
|
@@ -256,8 +265,77 @@ auth.logout({ redirect: '/login' })
|
|
|
256
265
|
|
|
257
266
|
## 🧩 Framework Adapters
|
|
258
267
|
|
|
259
|
-
|
|
260
|
-
|
|
268
|
+
Thin bindings over the same instance; the frameworks are optional peer
|
|
269
|
+
dependencies (install the one you use). Every adapter exposes the same state:
|
|
270
|
+
|
|
271
|
+
```typescript
|
|
272
|
+
interface AuthState {
|
|
273
|
+
isAuthenticated: boolean // access token set and not expired
|
|
274
|
+
accessToken: string | null
|
|
275
|
+
user: TokenPayload | null // decoded JWT payload (null for opaque tokens)
|
|
276
|
+
expiresAt: Date | null
|
|
277
|
+
error: AuthError | null // last 'error' event while subscribed
|
|
278
|
+
}
|
|
279
|
+
```
|
|
280
|
+
|
|
281
|
+
It updates after `login` (`setTokens()`), `refresh`, `logout` and `error`
|
|
282
|
+
events and when the access token expires. `clearTokens()` emits no event, so
|
|
283
|
+
use `logout()` to sign out.
|
|
284
|
+
|
|
285
|
+
**React** (18+): `useSyncExternalStore`, so components re-render only when the
|
|
286
|
+
state changes. On the server and during hydration the state is signed out.
|
|
287
|
+
|
|
288
|
+
```tsx
|
|
289
|
+
import { AuthProvider, useAuth } from '@oxog/authkeeper/react'
|
|
290
|
+
|
|
291
|
+
const auth = await createAuthKeeper({ refreshToken: refreshFn })
|
|
292
|
+
|
|
293
|
+
function App() {
|
|
294
|
+
return (
|
|
295
|
+
<AuthProvider auth={auth}>
|
|
296
|
+
<Profile />
|
|
297
|
+
</AuthProvider>
|
|
298
|
+
)
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
function Profile() {
|
|
302
|
+
const { isAuthenticated, user, logout } = useAuth() // or useAuth(auth)
|
|
303
|
+
return isAuthenticated ? <button onClick={() => logout()}>{user?.name}</button> : <Login />
|
|
304
|
+
}
|
|
305
|
+
```
|
|
306
|
+
|
|
307
|
+
`useAuthKeeper()` returns the instance from `<AuthProvider>`.
|
|
308
|
+
|
|
309
|
+
**Vue** (3.2+): read-only refs; stops listening when the component (or effect
|
|
310
|
+
scope) is unmounted.
|
|
311
|
+
|
|
312
|
+
```typescript
|
|
313
|
+
import { authKeeperPlugin, useAuth } from '@oxog/authkeeper/vue'
|
|
314
|
+
|
|
315
|
+
app.use(authKeeperPlugin(auth)) // or provideAuth(auth) in a parent's setup()
|
|
316
|
+
|
|
317
|
+
// in setup()
|
|
318
|
+
const { isAuthenticated, user, logout } = useAuth() // or useAuth(auth)
|
|
319
|
+
```
|
|
320
|
+
|
|
321
|
+
Outside a component, call the returned `stop()` when done.
|
|
322
|
+
|
|
323
|
+
**Svelte** (3, 4 and 5): a readable store, listening to the instance only
|
|
324
|
+
while subscribed.
|
|
325
|
+
|
|
326
|
+
```svelte
|
|
327
|
+
<script>
|
|
328
|
+
import { createAuthStore } from '@oxog/authkeeper/svelte'
|
|
329
|
+
const authStore = createAuthStore(auth)
|
|
330
|
+
</script>
|
|
331
|
+
|
|
332
|
+
{#if $authStore.isAuthenticated}
|
|
333
|
+
<button on:click={() => authStore.logout()}>{$authStore.user?.name}</button>
|
|
334
|
+
{/if}
|
|
335
|
+
```
|
|
336
|
+
|
|
337
|
+
Every adapter also offers `setTokens(tokens)`, `logout(options?)` and
|
|
338
|
+
`refresh()`.
|
|
261
339
|
|
|
262
340
|
## 🔌 Custom Plugins
|
|
263
341
|
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { a as TokenPayload, b as AuthError } from './types-Bmo8S8O4.cjs';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Framework-neutral view of an AuthKeeper instance, shared by the React, Vue
|
|
5
|
+
* and Svelte adapters: a cached state snapshot plus a change subscription.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Authentication state exposed by the adapters
|
|
10
|
+
*/
|
|
11
|
+
interface AuthState {
|
|
12
|
+
/** An access token is set and has not expired */
|
|
13
|
+
isAuthenticated: boolean;
|
|
14
|
+
/** Current access token */
|
|
15
|
+
accessToken: string | null;
|
|
16
|
+
/** Decoded access token payload (null for opaque tokens or no token) */
|
|
17
|
+
user: TokenPayload | null;
|
|
18
|
+
/** Access token expiry */
|
|
19
|
+
expiresAt: Date | null;
|
|
20
|
+
/** Last error reported while subscribed (cleared by a login or refresh) */
|
|
21
|
+
error: AuthError | null;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export type { AuthState as A };
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { a as TokenPayload, b as AuthError } from './types-Bmo8S8O4.js';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Framework-neutral view of an AuthKeeper instance, shared by the React, Vue
|
|
5
|
+
* and Svelte adapters: a cached state snapshot plus a change subscription.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
/**
|
|
9
|
+
* Authentication state exposed by the adapters
|
|
10
|
+
*/
|
|
11
|
+
interface AuthState {
|
|
12
|
+
/** An access token is set and has not expired */
|
|
13
|
+
isAuthenticated: boolean;
|
|
14
|
+
/** Current access token */
|
|
15
|
+
accessToken: string | null;
|
|
16
|
+
/** Decoded access token payload (null for opaque tokens or no token) */
|
|
17
|
+
user: TokenPayload | null;
|
|
18
|
+
/** Access token expiry */
|
|
19
|
+
expiresAt: Date | null;
|
|
20
|
+
/** Last error reported while subscribed (cleared by a login or refresh) */
|
|
21
|
+
error: AuthError | null;
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export type { AuthState as A };
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
// src/types.ts
|
|
4
|
+
var AuthError = class _AuthError extends Error {
|
|
5
|
+
constructor(code, message, options) {
|
|
6
|
+
super(message);
|
|
7
|
+
this.name = "AuthError";
|
|
8
|
+
this.code = code;
|
|
9
|
+
this.context = options?.context;
|
|
10
|
+
this.cause = options?.cause;
|
|
11
|
+
if (Error.captureStackTrace) {
|
|
12
|
+
Error.captureStackTrace(this, _AuthError);
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
exports.AuthError = AuthError;
|
|
18
|
+
//# sourceMappingURL=chunk-62XK5QLP.cjs.map
|
|
19
|
+
//# sourceMappingURL=chunk-62XK5QLP.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/types.ts"],"names":[],"mappings":";;;AAmJO,IAAM,SAAA,GAAN,MAAM,UAAA,SAAkB,KAAA,CAAM;AAAA,EAQnC,WAAA,CAAY,IAAA,EAAqB,OAAA,EAAiB,OAAA,EAA4B;AAC5E,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,WAAA;AACZ,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,IAAA,CAAK,UAAU,OAAA,EAAS,OAAA;AACxB,IAAA,IAAA,CAAK,QAAQ,OAAA,EAAS,KAAA;AAGtB,IAAA,IAAI,MAAM,iBAAA,EAAmB;AAC3B,MAAA,KAAA,CAAM,iBAAA,CAAkB,MAAM,UAAS,CAAA;AAAA,IACzC;AAAA,EACF;AACF","file":"chunk-62XK5QLP.cjs","sourcesContent":["/**\n * AuthKeeper Type Definitions\n *\n * Complete type system for the AuthKeeper library.\n * All interfaces and types are exported for use by consumers.\n */\n\n// ============================================================================\n// Token Types\n// ============================================================================\n\n/**\n * Token set returned from authentication/refresh operations\n */\nexport interface TokenSet {\n /** JWT access token */\n accessToken: string\n /** Optional refresh token for obtaining new access tokens */\n refreshToken?: string\n /** Token expiration in seconds from now */\n expiresIn?: number\n /** Token expiration as Unix timestamp (seconds) */\n expiresAt?: number\n /** Token type (default: 'Bearer') */\n tokenType?: string\n}\n\n/**\n * Standard JWT payload with common claims\n */\nexport interface TokenPayload {\n // Standard JWT claims (RFC 7519)\n /** Subject - usually the user ID */\n sub?: string\n /** Issuer - who created the token */\n iss?: string\n /** Audience - who the token is intended for */\n aud?: string | string[]\n /** Expiration time (Unix timestamp in seconds) */\n exp?: number\n /** Not before time (Unix timestamp in seconds) */\n nbf?: number\n /** Issued at time (Unix timestamp in seconds) */\n iat?: number\n /** JWT ID - unique identifier */\n jti?: string\n\n // Common custom claims\n /** User email address */\n email?: string\n /** User display name */\n name?: string\n /** User roles */\n roles?: string[]\n /** User permissions */\n permissions?: string[]\n /** OAuth2 scope */\n scope?: string\n\n // Allow any additional custom claims\n [key: string]: unknown\n}\n\n/**\n * JWT header information\n */\nexport interface TokenHeader {\n /** Algorithm used to sign the token */\n alg: string\n /** Token type (usually 'JWT') */\n typ?: string\n /** Key ID used to sign the token */\n kid?: string\n [key: string]: unknown\n}\n\n/**\n * Complete token information including decoded parts\n */\nexport interface TokenInfo {\n /** Raw JWT string */\n raw: string\n /** Decoded payload */\n payload: TokenPayload\n /** Decoded header */\n header: TokenHeader\n /** When the token expires (null if no expiry) */\n expiresAt: Date | null\n /** Whether the token is expired */\n isExpired: boolean\n /** Time until expiry in milliseconds (null if no expiry) */\n expiresIn: number | null\n}\n\n/**\n * Stored token data with metadata\n */\nexport interface StoredTokens {\n /** Access token */\n accessToken: string\n /** Refresh token (null if not available) */\n refreshToken: string | null\n /** Token type (e.g., 'Bearer') */\n tokenType: string\n /** Expiration timestamp in milliseconds (null if no expiry) */\n expiresAt: number | null\n /** When tokens were set (timestamp in milliseconds) */\n setAt: number\n /** Number of times tokens have been refreshed */\n refreshCount: number\n}\n\n// ============================================================================\n// Error Types\n// ============================================================================\n\n/**\n * Error codes for authentication errors\n */\nexport type AuthErrorCode =\n | 'TOKEN_EXPIRED'\n | 'TOKEN_INVALID'\n | 'TOKEN_DECODE_FAILED'\n | 'REFRESH_FAILED'\n | 'REFRESH_TOKEN_MISSING'\n | 'STORAGE_ERROR'\n | 'NETWORK_ERROR'\n | 'UNAUTHORIZED'\n | 'FORBIDDEN'\n | 'OAUTH_ERROR'\n | 'PKCE_ERROR'\n | 'CALLBACK_ERROR'\n | 'CONFIG_ERROR'\n\n/**\n * Options for creating an AuthError\n */\nexport interface AuthErrorOptions {\n /** Additional context about the error */\n context?: Record<string, unknown>\n /** Original error that caused this error */\n cause?: Error\n}\n\n/**\n * Custom error class for authentication errors\n */\nexport class AuthError extends Error {\n /** Error code identifying the type of error */\n code: AuthErrorCode\n /** Additional context about the error */\n context?: Record<string, unknown>\n /** Original error that caused this error */\n cause?: Error\n\n constructor(code: AuthErrorCode, message: string, options?: AuthErrorOptions) {\n super(message)\n this.name = 'AuthError'\n this.code = code\n this.context = options?.context\n this.cause = options?.cause\n\n // Maintains proper stack trace for where error was thrown\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, AuthError)\n }\n }\n}\n\n// ============================================================================\n// Event Types\n// ============================================================================\n\n/**\n * All possible event types\n */\nexport type EventType =\n | 'login'\n | 'logout'\n | 'refresh'\n | 'expired'\n | 'error'\n | 'storage-change'\n | 'tab-sync'\n\n/**\n * Login event - fired when user logs in\n */\nexport interface LoginEvent {\n type: 'login'\n tokens: TokenSet\n timestamp: number\n}\n\n/**\n * Logout event - fired when user logs out\n */\nexport interface LogoutEvent {\n type: 'logout'\n reason: 'manual' | 'expired' | 'error' | 'tab-sync'\n timestamp: number\n}\n\n/**\n * Refresh event - fired when tokens are refreshed\n */\nexport interface RefreshEvent {\n type: 'refresh'\n tokens: TokenSet\n previousExpiresAt: Date | null\n newExpiresAt: Date | null\n timestamp: number\n}\n\n/**\n * Expired event - fired when token expires\n */\nexport interface ExpiredEvent {\n type: 'expired'\n expiredAt: Date\n timestamp: number\n}\n\n/**\n * Error event - fired when an error occurs\n */\nexport interface ErrorEvent {\n type: 'error'\n error: AuthError\n context: 'refresh' | 'storage' | 'decode' | 'network' | 'plugin'\n timestamp: number\n}\n\n/**\n * Storage change event - fired when storage changes\n */\nexport interface StorageChangeEvent {\n type: 'storage-change'\n key: string\n oldValue: string | null\n newValue: string | null\n timestamp: number\n}\n\n/**\n * Tab sync event - fired when syncing across tabs\n */\nexport interface TabSyncEvent {\n type: 'tab-sync'\n action: 'login' | 'logout' | 'refresh'\n sourceTabId: string\n timestamp: number\n}\n\n/**\n * Union of all event types\n */\nexport type AuthEvent =\n | LoginEvent\n | LogoutEvent\n | RefreshEvent\n | ExpiredEvent\n | ErrorEvent\n | StorageChangeEvent\n | TabSyncEvent\n\n/**\n * Event handler function type\n */\nexport type EventHandler<E extends EventType> = (\n event: Extract<AuthEvent, { type: E }>\n) => void\n\n/**\n * Unsubscribe function returned from event handlers\n */\nexport type Unsubscribe = () => void\n\n// ============================================================================\n// Storage Types\n// ============================================================================\n\n/**\n * Storage adapter interface for token persistence\n */\nexport interface StorageAdapter {\n /** Get value by key */\n get(key: string): string | null\n /** Set value by key */\n set(key: string, value: string): void\n /** Remove value by key */\n remove(key: string): void\n /** Clear all values */\n clear(): void\n}\n\n/**\n * Built-in storage types\n */\nexport type StorageType = 'memory' | 'localStorage' | 'sessionStorage' | 'cookie'\n\n// ============================================================================\n// Plugin Types\n// ============================================================================\n\n/**\n * Plugin interface for extending AuthKeeper\n */\nexport interface Plugin {\n /** Unique plugin name */\n name: string\n /** Plugin version */\n version: string\n /** Plugin type */\n type: 'core' | 'optional'\n\n /** Install plugin and return API */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- kept (not `unknown`) so existing plugin APIs stay usable without casts\n install(kernel: AuthKeeper): any\n /** Uninstall plugin and cleanup */\n uninstall?(): void | Promise<void>\n\n /** Reserved lifecycle hooks; not invoked by the kernel yet */\n hooks?: {\n /** Called before tokens are set */\n beforeSetTokens?: (tokens: TokenSet) => TokenSet | false\n /** Called after tokens are set */\n afterSetTokens?: (tokens: TokenSet) => void\n /** Called before refresh */\n beforeRefresh?: () => boolean\n /** Called after refresh */\n afterRefresh?: (tokens: TokenSet) => void\n /** Called before logout */\n beforeLogout?: () => boolean\n /** Called after logout */\n afterLogout?: () => void\n /** Called when token expires */\n onExpired?: () => void\n /** Called on error */\n onError?: (error: AuthError) => void\n /** Called before request */\n beforeRequest?: (request: Request) => Request\n /** Called after response */\n afterResponse?: (response: Response) => Response\n }\n\n /** Plugin API exposed to consumers */\n api?: Record<string, unknown>\n}\n\n/**\n * Plugin information\n */\nexport interface PluginInfo {\n name: string\n version: string\n type: 'core' | 'optional'\n enabled: boolean\n}\n\n// ============================================================================\n// Configuration Types\n// ============================================================================\n\n/**\n * Refresh token function type\n */\nexport type RefreshTokenFn = (refreshToken: string) => Promise<TokenSet>\n\n/**\n * Kernel configuration options\n */\nexport interface KernelOptions {\n /**\n * Where tokens are persisted (default: 'memory', i.e. not persisted).\n * 'localStorage' / 'sessionStorage' / 'cookie' fall back to memory where\n * unavailable. Persistent storage is readable by any script on the page.\n */\n storage?: StorageType | StorageAdapter\n /** Function to refresh tokens */\n refreshToken: RefreshTokenFn\n /** Enable automatic token refresh (default: true) */\n autoRefresh?: boolean\n /** Seconds before expiry to refresh (default: 60) */\n refreshThreshold?: number\n /**\n * Reserved for multi-tab sync; not implemented yet (currently a no-op).\n * `getOptions().syncTabs` always reports `false`.\n */\n syncTabs?: boolean\n /** Error handler */\n onError?: (error: AuthError) => void\n /** Additional plugins to install */\n plugins?: Plugin[]\n}\n\n/**\n * Logout options\n */\nexport interface LogoutOptions {\n /** Reserved for multi-tab logout; not implemented yet (currently a no-op) */\n allTabs?: boolean\n /** Redirect URL after logout */\n redirect?: string\n}\n\n// ============================================================================\n// Fetch Interceptor Types\n// ============================================================================\n\n/**\n * Authenticated fetch function\n */\nexport type AuthFetch = (\n input: RequestInfo | URL,\n init?: RequestInit\n) => Promise<Response>\n\n/**\n * Fetch interceptor options\n */\nexport interface FetchInterceptorOptions {\n /** Header name for auth token (default: 'Authorization') */\n headerName?: string\n /** Header prefix (default: 'Bearer ') */\n headerPrefix?: string\n /** Only include auth header for these URLs */\n includeUrls?: (string | RegExp)[]\n /** Exclude auth header for these URLs */\n excludeUrls?: (string | RegExp)[]\n /** Callback on 401 response */\n onUnauthorized?: (response: Response) => void\n /** Retry on 401 after refresh (default: true) */\n retry401?: boolean\n /** Max retries (default: 1) */\n maxRetries?: number\n}\n\n// ============================================================================\n// OAuth2 Types\n// ============================================================================\n\n/**\n * OAuth2 login options\n */\nexport interface LoginOptions {\n /** OAuth2 scope */\n scope?: string\n /** OAuth2 state parameter */\n state?: string\n /** OAuth2 prompt parameter */\n prompt?: 'none' | 'login' | 'consent' | 'select_account'\n /** Login hint (email, etc.) */\n loginHint?: string\n /** Additional OAuth2 parameters */\n extraParams?: Record<string, string>\n}\n\n/**\n * User info from OIDC userinfo endpoint\n */\nexport interface UserInfo {\n sub: string\n email?: string\n name?: string\n picture?: string\n [key: string]: unknown\n}\n\n// ============================================================================\n// Main AuthKeeper Interface\n// ============================================================================\n\n/**\n * Main AuthKeeper interface - the kernel\n */\nexport interface AuthKeeper {\n // Token Management\n /** Set authentication tokens */\n setTokens(tokens: TokenSet): void\n /** Get access token */\n getAccessToken(): string | null\n /** Get refresh token */\n getRefreshToken(): string | null\n /** Clear all tokens */\n clearTokens(): void\n\n // Auth State\n /** Check if user is authenticated */\n isAuthenticated(): boolean\n /** Check if token is expired */\n isExpired(): boolean\n /** Get token expiration date */\n getExpiresAt(): Date | null\n /** Get time until expiry in milliseconds */\n getTimeUntilExpiry(): number | null\n\n // Token Decoding\n /** Decode token payload */\n decode<T = TokenPayload>(): T | null\n /** Get specific claim from token */\n getClaim<K extends keyof TokenPayload>(key: K): TokenPayload[K] | undefined\n /** Get multiple claims from token */\n getClaims<K extends keyof TokenPayload>(keys: K[]): Pick<TokenPayload, K>\n\n // Refresh\n /** Manually refresh tokens */\n refresh(): Promise<TokenSet>\n /** Schedule automatic refresh */\n scheduleRefresh(): void\n /** Cancel scheduled refresh */\n cancelScheduledRefresh(): void\n\n // Logout\n /** Logout user */\n logout(options?: LogoutOptions): void\n\n // Interceptors\n /** Create authenticated fetch function */\n createFetch(options?: FetchInterceptorOptions): AuthFetch\n /** Wrap global fetch with auth */\n wrapFetch(fetch: typeof globalThis.fetch): void\n\n // Plugin Management\n /**\n * Register and install a plugin. Rejects if installation fails; the failure\n * is also emitted as an 'error' event with context 'plugin'.\n */\n register(plugin: Plugin): Promise<void>\n /** Unregister a plugin */\n unregister(pluginName: string): Promise<void>\n /** Get plugin by name */\n getPlugin<P extends Plugin>(name: string): P | undefined\n /** List all plugins */\n listPlugins(): PluginInfo[]\n\n // Event System\n /** Emit an event */\n emit(event: AuthEvent): void\n /** Subscribe to events */\n on<E extends EventType>(eventType: E, handler: EventHandler<E>): Unsubscribe\n /** Unsubscribe from events */\n off<E extends EventType>(eventType: E, handler: EventHandler<E>): void\n\n // Lifecycle\n /** Initialize kernel */\n init(): Promise<void>\n /** Destroy kernel and cleanup */\n destroy(): void\n\n // Configuration\n /** Update configuration */\n configure(options: Partial<KernelOptions>): void\n /** Get current configuration */\n getOptions(): KernelOptions\n}\n\n// ============================================================================\n// Export all types\n// ============================================================================\n\nexport type {\n // Re-export for convenience\n AuthKeeper as default,\n}\n"]}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
// src/types.ts
|
|
2
|
+
var AuthError = class _AuthError extends Error {
|
|
3
|
+
constructor(code, message, options) {
|
|
4
|
+
super(message);
|
|
5
|
+
this.name = "AuthError";
|
|
6
|
+
this.code = code;
|
|
7
|
+
this.context = options?.context;
|
|
8
|
+
this.cause = options?.cause;
|
|
9
|
+
if (Error.captureStackTrace) {
|
|
10
|
+
Error.captureStackTrace(this, _AuthError);
|
|
11
|
+
}
|
|
12
|
+
}
|
|
13
|
+
};
|
|
14
|
+
|
|
15
|
+
export { AuthError };
|
|
16
|
+
//# sourceMappingURL=chunk-CYCWWUCJ.js.map
|
|
17
|
+
//# sourceMappingURL=chunk-CYCWWUCJ.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/types.ts"],"names":[],"mappings":";AAmJO,IAAM,SAAA,GAAN,MAAM,UAAA,SAAkB,KAAA,CAAM;AAAA,EAQnC,WAAA,CAAY,IAAA,EAAqB,OAAA,EAAiB,OAAA,EAA4B;AAC5E,IAAA,KAAA,CAAM,OAAO,CAAA;AACb,IAAA,IAAA,CAAK,IAAA,GAAO,WAAA;AACZ,IAAA,IAAA,CAAK,IAAA,GAAO,IAAA;AACZ,IAAA,IAAA,CAAK,UAAU,OAAA,EAAS,OAAA;AACxB,IAAA,IAAA,CAAK,QAAQ,OAAA,EAAS,KAAA;AAGtB,IAAA,IAAI,MAAM,iBAAA,EAAmB;AAC3B,MAAA,KAAA,CAAM,iBAAA,CAAkB,MAAM,UAAS,CAAA;AAAA,IACzC;AAAA,EACF;AACF","file":"chunk-CYCWWUCJ.js","sourcesContent":["/**\n * AuthKeeper Type Definitions\n *\n * Complete type system for the AuthKeeper library.\n * All interfaces and types are exported for use by consumers.\n */\n\n// ============================================================================\n// Token Types\n// ============================================================================\n\n/**\n * Token set returned from authentication/refresh operations\n */\nexport interface TokenSet {\n /** JWT access token */\n accessToken: string\n /** Optional refresh token for obtaining new access tokens */\n refreshToken?: string\n /** Token expiration in seconds from now */\n expiresIn?: number\n /** Token expiration as Unix timestamp (seconds) */\n expiresAt?: number\n /** Token type (default: 'Bearer') */\n tokenType?: string\n}\n\n/**\n * Standard JWT payload with common claims\n */\nexport interface TokenPayload {\n // Standard JWT claims (RFC 7519)\n /** Subject - usually the user ID */\n sub?: string\n /** Issuer - who created the token */\n iss?: string\n /** Audience - who the token is intended for */\n aud?: string | string[]\n /** Expiration time (Unix timestamp in seconds) */\n exp?: number\n /** Not before time (Unix timestamp in seconds) */\n nbf?: number\n /** Issued at time (Unix timestamp in seconds) */\n iat?: number\n /** JWT ID - unique identifier */\n jti?: string\n\n // Common custom claims\n /** User email address */\n email?: string\n /** User display name */\n name?: string\n /** User roles */\n roles?: string[]\n /** User permissions */\n permissions?: string[]\n /** OAuth2 scope */\n scope?: string\n\n // Allow any additional custom claims\n [key: string]: unknown\n}\n\n/**\n * JWT header information\n */\nexport interface TokenHeader {\n /** Algorithm used to sign the token */\n alg: string\n /** Token type (usually 'JWT') */\n typ?: string\n /** Key ID used to sign the token */\n kid?: string\n [key: string]: unknown\n}\n\n/**\n * Complete token information including decoded parts\n */\nexport interface TokenInfo {\n /** Raw JWT string */\n raw: string\n /** Decoded payload */\n payload: TokenPayload\n /** Decoded header */\n header: TokenHeader\n /** When the token expires (null if no expiry) */\n expiresAt: Date | null\n /** Whether the token is expired */\n isExpired: boolean\n /** Time until expiry in milliseconds (null if no expiry) */\n expiresIn: number | null\n}\n\n/**\n * Stored token data with metadata\n */\nexport interface StoredTokens {\n /** Access token */\n accessToken: string\n /** Refresh token (null if not available) */\n refreshToken: string | null\n /** Token type (e.g., 'Bearer') */\n tokenType: string\n /** Expiration timestamp in milliseconds (null if no expiry) */\n expiresAt: number | null\n /** When tokens were set (timestamp in milliseconds) */\n setAt: number\n /** Number of times tokens have been refreshed */\n refreshCount: number\n}\n\n// ============================================================================\n// Error Types\n// ============================================================================\n\n/**\n * Error codes for authentication errors\n */\nexport type AuthErrorCode =\n | 'TOKEN_EXPIRED'\n | 'TOKEN_INVALID'\n | 'TOKEN_DECODE_FAILED'\n | 'REFRESH_FAILED'\n | 'REFRESH_TOKEN_MISSING'\n | 'STORAGE_ERROR'\n | 'NETWORK_ERROR'\n | 'UNAUTHORIZED'\n | 'FORBIDDEN'\n | 'OAUTH_ERROR'\n | 'PKCE_ERROR'\n | 'CALLBACK_ERROR'\n | 'CONFIG_ERROR'\n\n/**\n * Options for creating an AuthError\n */\nexport interface AuthErrorOptions {\n /** Additional context about the error */\n context?: Record<string, unknown>\n /** Original error that caused this error */\n cause?: Error\n}\n\n/**\n * Custom error class for authentication errors\n */\nexport class AuthError extends Error {\n /** Error code identifying the type of error */\n code: AuthErrorCode\n /** Additional context about the error */\n context?: Record<string, unknown>\n /** Original error that caused this error */\n cause?: Error\n\n constructor(code: AuthErrorCode, message: string, options?: AuthErrorOptions) {\n super(message)\n this.name = 'AuthError'\n this.code = code\n this.context = options?.context\n this.cause = options?.cause\n\n // Maintains proper stack trace for where error was thrown\n if (Error.captureStackTrace) {\n Error.captureStackTrace(this, AuthError)\n }\n }\n}\n\n// ============================================================================\n// Event Types\n// ============================================================================\n\n/**\n * All possible event types\n */\nexport type EventType =\n | 'login'\n | 'logout'\n | 'refresh'\n | 'expired'\n | 'error'\n | 'storage-change'\n | 'tab-sync'\n\n/**\n * Login event - fired when user logs in\n */\nexport interface LoginEvent {\n type: 'login'\n tokens: TokenSet\n timestamp: number\n}\n\n/**\n * Logout event - fired when user logs out\n */\nexport interface LogoutEvent {\n type: 'logout'\n reason: 'manual' | 'expired' | 'error' | 'tab-sync'\n timestamp: number\n}\n\n/**\n * Refresh event - fired when tokens are refreshed\n */\nexport interface RefreshEvent {\n type: 'refresh'\n tokens: TokenSet\n previousExpiresAt: Date | null\n newExpiresAt: Date | null\n timestamp: number\n}\n\n/**\n * Expired event - fired when token expires\n */\nexport interface ExpiredEvent {\n type: 'expired'\n expiredAt: Date\n timestamp: number\n}\n\n/**\n * Error event - fired when an error occurs\n */\nexport interface ErrorEvent {\n type: 'error'\n error: AuthError\n context: 'refresh' | 'storage' | 'decode' | 'network' | 'plugin'\n timestamp: number\n}\n\n/**\n * Storage change event - fired when storage changes\n */\nexport interface StorageChangeEvent {\n type: 'storage-change'\n key: string\n oldValue: string | null\n newValue: string | null\n timestamp: number\n}\n\n/**\n * Tab sync event - fired when syncing across tabs\n */\nexport interface TabSyncEvent {\n type: 'tab-sync'\n action: 'login' | 'logout' | 'refresh'\n sourceTabId: string\n timestamp: number\n}\n\n/**\n * Union of all event types\n */\nexport type AuthEvent =\n | LoginEvent\n | LogoutEvent\n | RefreshEvent\n | ExpiredEvent\n | ErrorEvent\n | StorageChangeEvent\n | TabSyncEvent\n\n/**\n * Event handler function type\n */\nexport type EventHandler<E extends EventType> = (\n event: Extract<AuthEvent, { type: E }>\n) => void\n\n/**\n * Unsubscribe function returned from event handlers\n */\nexport type Unsubscribe = () => void\n\n// ============================================================================\n// Storage Types\n// ============================================================================\n\n/**\n * Storage adapter interface for token persistence\n */\nexport interface StorageAdapter {\n /** Get value by key */\n get(key: string): string | null\n /** Set value by key */\n set(key: string, value: string): void\n /** Remove value by key */\n remove(key: string): void\n /** Clear all values */\n clear(): void\n}\n\n/**\n * Built-in storage types\n */\nexport type StorageType = 'memory' | 'localStorage' | 'sessionStorage' | 'cookie'\n\n// ============================================================================\n// Plugin Types\n// ============================================================================\n\n/**\n * Plugin interface for extending AuthKeeper\n */\nexport interface Plugin {\n /** Unique plugin name */\n name: string\n /** Plugin version */\n version: string\n /** Plugin type */\n type: 'core' | 'optional'\n\n /** Install plugin and return API */\n // eslint-disable-next-line @typescript-eslint/no-explicit-any -- kept (not `unknown`) so existing plugin APIs stay usable without casts\n install(kernel: AuthKeeper): any\n /** Uninstall plugin and cleanup */\n uninstall?(): void | Promise<void>\n\n /** Reserved lifecycle hooks; not invoked by the kernel yet */\n hooks?: {\n /** Called before tokens are set */\n beforeSetTokens?: (tokens: TokenSet) => TokenSet | false\n /** Called after tokens are set */\n afterSetTokens?: (tokens: TokenSet) => void\n /** Called before refresh */\n beforeRefresh?: () => boolean\n /** Called after refresh */\n afterRefresh?: (tokens: TokenSet) => void\n /** Called before logout */\n beforeLogout?: () => boolean\n /** Called after logout */\n afterLogout?: () => void\n /** Called when token expires */\n onExpired?: () => void\n /** Called on error */\n onError?: (error: AuthError) => void\n /** Called before request */\n beforeRequest?: (request: Request) => Request\n /** Called after response */\n afterResponse?: (response: Response) => Response\n }\n\n /** Plugin API exposed to consumers */\n api?: Record<string, unknown>\n}\n\n/**\n * Plugin information\n */\nexport interface PluginInfo {\n name: string\n version: string\n type: 'core' | 'optional'\n enabled: boolean\n}\n\n// ============================================================================\n// Configuration Types\n// ============================================================================\n\n/**\n * Refresh token function type\n */\nexport type RefreshTokenFn = (refreshToken: string) => Promise<TokenSet>\n\n/**\n * Kernel configuration options\n */\nexport interface KernelOptions {\n /**\n * Where tokens are persisted (default: 'memory', i.e. not persisted).\n * 'localStorage' / 'sessionStorage' / 'cookie' fall back to memory where\n * unavailable. Persistent storage is readable by any script on the page.\n */\n storage?: StorageType | StorageAdapter\n /** Function to refresh tokens */\n refreshToken: RefreshTokenFn\n /** Enable automatic token refresh (default: true) */\n autoRefresh?: boolean\n /** Seconds before expiry to refresh (default: 60) */\n refreshThreshold?: number\n /**\n * Reserved for multi-tab sync; not implemented yet (currently a no-op).\n * `getOptions().syncTabs` always reports `false`.\n */\n syncTabs?: boolean\n /** Error handler */\n onError?: (error: AuthError) => void\n /** Additional plugins to install */\n plugins?: Plugin[]\n}\n\n/**\n * Logout options\n */\nexport interface LogoutOptions {\n /** Reserved for multi-tab logout; not implemented yet (currently a no-op) */\n allTabs?: boolean\n /** Redirect URL after logout */\n redirect?: string\n}\n\n// ============================================================================\n// Fetch Interceptor Types\n// ============================================================================\n\n/**\n * Authenticated fetch function\n */\nexport type AuthFetch = (\n input: RequestInfo | URL,\n init?: RequestInit\n) => Promise<Response>\n\n/**\n * Fetch interceptor options\n */\nexport interface FetchInterceptorOptions {\n /** Header name for auth token (default: 'Authorization') */\n headerName?: string\n /** Header prefix (default: 'Bearer ') */\n headerPrefix?: string\n /** Only include auth header for these URLs */\n includeUrls?: (string | RegExp)[]\n /** Exclude auth header for these URLs */\n excludeUrls?: (string | RegExp)[]\n /** Callback on 401 response */\n onUnauthorized?: (response: Response) => void\n /** Retry on 401 after refresh (default: true) */\n retry401?: boolean\n /** Max retries (default: 1) */\n maxRetries?: number\n}\n\n// ============================================================================\n// OAuth2 Types\n// ============================================================================\n\n/**\n * OAuth2 login options\n */\nexport interface LoginOptions {\n /** OAuth2 scope */\n scope?: string\n /** OAuth2 state parameter */\n state?: string\n /** OAuth2 prompt parameter */\n prompt?: 'none' | 'login' | 'consent' | 'select_account'\n /** Login hint (email, etc.) */\n loginHint?: string\n /** Additional OAuth2 parameters */\n extraParams?: Record<string, string>\n}\n\n/**\n * User info from OIDC userinfo endpoint\n */\nexport interface UserInfo {\n sub: string\n email?: string\n name?: string\n picture?: string\n [key: string]: unknown\n}\n\n// ============================================================================\n// Main AuthKeeper Interface\n// ============================================================================\n\n/**\n * Main AuthKeeper interface - the kernel\n */\nexport interface AuthKeeper {\n // Token Management\n /** Set authentication tokens */\n setTokens(tokens: TokenSet): void\n /** Get access token */\n getAccessToken(): string | null\n /** Get refresh token */\n getRefreshToken(): string | null\n /** Clear all tokens */\n clearTokens(): void\n\n // Auth State\n /** Check if user is authenticated */\n isAuthenticated(): boolean\n /** Check if token is expired */\n isExpired(): boolean\n /** Get token expiration date */\n getExpiresAt(): Date | null\n /** Get time until expiry in milliseconds */\n getTimeUntilExpiry(): number | null\n\n // Token Decoding\n /** Decode token payload */\n decode<T = TokenPayload>(): T | null\n /** Get specific claim from token */\n getClaim<K extends keyof TokenPayload>(key: K): TokenPayload[K] | undefined\n /** Get multiple claims from token */\n getClaims<K extends keyof TokenPayload>(keys: K[]): Pick<TokenPayload, K>\n\n // Refresh\n /** Manually refresh tokens */\n refresh(): Promise<TokenSet>\n /** Schedule automatic refresh */\n scheduleRefresh(): void\n /** Cancel scheduled refresh */\n cancelScheduledRefresh(): void\n\n // Logout\n /** Logout user */\n logout(options?: LogoutOptions): void\n\n // Interceptors\n /** Create authenticated fetch function */\n createFetch(options?: FetchInterceptorOptions): AuthFetch\n /** Wrap global fetch with auth */\n wrapFetch(fetch: typeof globalThis.fetch): void\n\n // Plugin Management\n /**\n * Register and install a plugin. Rejects if installation fails; the failure\n * is also emitted as an 'error' event with context 'plugin'.\n */\n register(plugin: Plugin): Promise<void>\n /** Unregister a plugin */\n unregister(pluginName: string): Promise<void>\n /** Get plugin by name */\n getPlugin<P extends Plugin>(name: string): P | undefined\n /** List all plugins */\n listPlugins(): PluginInfo[]\n\n // Event System\n /** Emit an event */\n emit(event: AuthEvent): void\n /** Subscribe to events */\n on<E extends EventType>(eventType: E, handler: EventHandler<E>): Unsubscribe\n /** Unsubscribe from events */\n off<E extends EventType>(eventType: E, handler: EventHandler<E>): void\n\n // Lifecycle\n /** Initialize kernel */\n init(): Promise<void>\n /** Destroy kernel and cleanup */\n destroy(): void\n\n // Configuration\n /** Update configuration */\n configure(options: Partial<KernelOptions>): void\n /** Get current configuration */\n getOptions(): KernelOptions\n}\n\n// ============================================================================\n// Export all types\n// ============================================================================\n\nexport type {\n // Re-export for convenience\n AuthKeeper as default,\n}\n"]}
|
|
@@ -1,18 +1,6 @@
|
|
|
1
1
|
'use strict';
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
var AuthError = class _AuthError extends Error {
|
|
5
|
-
constructor(code, message, options) {
|
|
6
|
-
super(message);
|
|
7
|
-
this.name = "AuthError";
|
|
8
|
-
this.code = code;
|
|
9
|
-
this.context = options?.context;
|
|
10
|
-
this.cause = options?.cause;
|
|
11
|
-
if (Error.captureStackTrace) {
|
|
12
|
-
Error.captureStackTrace(this, _AuthError);
|
|
13
|
-
}
|
|
14
|
-
}
|
|
15
|
-
};
|
|
3
|
+
var chunk62XK5QLP_cjs = require('./chunk-62XK5QLP.cjs');
|
|
16
4
|
|
|
17
5
|
// src/utils/base64.ts
|
|
18
6
|
function base64UrlEncode(buffer) {
|
|
@@ -66,7 +54,7 @@ function decodeJwt(token) {
|
|
|
66
54
|
const parts = token.split(".");
|
|
67
55
|
const [headerPart, payloadPart] = parts;
|
|
68
56
|
if (parts.length !== 3 || headerPart === void 0 || payloadPart === void 0) {
|
|
69
|
-
throw new AuthError("TOKEN_DECODE_FAILED", "Invalid JWT format: must have 3 parts", {
|
|
57
|
+
throw new chunk62XK5QLP_cjs.AuthError("TOKEN_DECODE_FAILED", "Invalid JWT format: must have 3 parts", {
|
|
70
58
|
context: { parts: parts.length }
|
|
71
59
|
});
|
|
72
60
|
}
|
|
@@ -77,7 +65,7 @@ function decodeJwt(token) {
|
|
|
77
65
|
const payload = JSON.parse(payloadJson);
|
|
78
66
|
return { header, payload };
|
|
79
67
|
} catch (error) {
|
|
80
|
-
throw new AuthError("TOKEN_DECODE_FAILED", "Failed to decode JWT", {
|
|
68
|
+
throw new chunk62XK5QLP_cjs.AuthError("TOKEN_DECODE_FAILED", "Failed to decode JWT", {
|
|
81
69
|
cause: error
|
|
82
70
|
});
|
|
83
71
|
}
|
|
@@ -209,10 +197,10 @@ var TokenStorePlugin = class {
|
|
|
209
197
|
*/
|
|
210
198
|
set(tokens) {
|
|
211
199
|
if (typeof tokens?.accessToken !== "string" || tokens.accessToken === "") {
|
|
212
|
-
throw new AuthError("TOKEN_INVALID", "accessToken must be a non-empty string");
|
|
200
|
+
throw new chunk62XK5QLP_cjs.AuthError("TOKEN_INVALID", "accessToken must be a non-empty string");
|
|
213
201
|
}
|
|
214
202
|
if (this.options.validateOnSet && !isValidJwtFormat(tokens.accessToken)) {
|
|
215
|
-
throw new AuthError("TOKEN_INVALID", "accessToken is not a valid JWT");
|
|
203
|
+
throw new chunk62XK5QLP_cjs.AuthError("TOKEN_INVALID", "accessToken is not a valid JWT");
|
|
216
204
|
}
|
|
217
205
|
let expiresAt;
|
|
218
206
|
if (isFiniteNumber(tokens.expiresAt)) {
|
|
@@ -315,7 +303,7 @@ var TokenStorePlugin = class {
|
|
|
315
303
|
this.reportStorageError("Discarded malformed persisted tokens");
|
|
316
304
|
}
|
|
317
305
|
reportStorageError(message, cause) {
|
|
318
|
-
const error = new AuthError("STORAGE_ERROR", message, {
|
|
306
|
+
const error = new chunk62XK5QLP_cjs.AuthError("STORAGE_ERROR", message, {
|
|
319
307
|
// eslint-disable-next-line @typescript-eslint/no-base-to-string -- a non-Error cause is kept as its string form
|
|
320
308
|
cause: cause === void 0 ? void 0 : cause instanceof Error ? cause : new Error(String(cause))
|
|
321
309
|
});
|
|
@@ -468,6 +456,11 @@ var RefreshEnginePlugin = class {
|
|
|
468
456
|
this.isRefreshingFlag = false;
|
|
469
457
|
this.applyingRefresh = false;
|
|
470
458
|
this.refreshPromise = null;
|
|
459
|
+
/** Refresh token of the session the in-flight refresh belongs to */
|
|
460
|
+
this.refreshPromiseToken = null;
|
|
461
|
+
/** Pending retry backoff waits (ended early on session change / uninstall) */
|
|
462
|
+
this.backoffs = /* @__PURE__ */ new Set();
|
|
463
|
+
this.uninstalled = false;
|
|
471
464
|
this.scheduledRefreshTimeout = null;
|
|
472
465
|
this.options = options;
|
|
473
466
|
this.refreshFn = options.refreshFn;
|
|
@@ -477,6 +470,7 @@ var RefreshEnginePlugin = class {
|
|
|
477
470
|
}
|
|
478
471
|
install(kernel) {
|
|
479
472
|
this.kernel = kernel;
|
|
473
|
+
this.uninstalled = false;
|
|
480
474
|
return {
|
|
481
475
|
refresh: this.refresh.bind(this),
|
|
482
476
|
scheduleRefresh: this.scheduleRefresh.bind(this),
|
|
@@ -498,32 +492,59 @@ var RefreshEnginePlugin = class {
|
|
|
498
492
|
* Queues concurrent requests - only one refresh executes at a time.
|
|
499
493
|
*/
|
|
500
494
|
async refresh() {
|
|
501
|
-
|
|
495
|
+
const refreshToken = this.kernel.getRefreshToken();
|
|
496
|
+
if (this.refreshPromise && this.refreshPromiseToken === refreshToken) {
|
|
502
497
|
return this.refreshPromise;
|
|
503
498
|
}
|
|
499
|
+
this.endBackoffs();
|
|
504
500
|
this.isRefreshingFlag = true;
|
|
505
|
-
|
|
501
|
+
const promise = this.executeRefresh();
|
|
502
|
+
this.refreshPromise = promise;
|
|
503
|
+
this.refreshPromiseToken = refreshToken;
|
|
506
504
|
try {
|
|
507
|
-
const tokens = await
|
|
505
|
+
const tokens = await promise;
|
|
508
506
|
return tokens;
|
|
509
507
|
} finally {
|
|
510
|
-
this.
|
|
511
|
-
|
|
508
|
+
if (this.refreshPromise === promise) {
|
|
509
|
+
this.isRefreshingFlag = false;
|
|
510
|
+
this.refreshPromise = null;
|
|
511
|
+
this.refreshPromiseToken = null;
|
|
512
|
+
}
|
|
512
513
|
}
|
|
513
514
|
}
|
|
515
|
+
/** Wait before a retry; endBackoffs() cuts the wait short */
|
|
516
|
+
waitBackoff(ms) {
|
|
517
|
+
return new Promise((resolve) => {
|
|
518
|
+
const entry = {
|
|
519
|
+
timer: setTimeout(() => {
|
|
520
|
+
this.backoffs.delete(entry);
|
|
521
|
+
resolve();
|
|
522
|
+
}, ms),
|
|
523
|
+
resolve
|
|
524
|
+
};
|
|
525
|
+
this.backoffs.add(entry);
|
|
526
|
+
});
|
|
527
|
+
}
|
|
528
|
+
endBackoffs() {
|
|
529
|
+
this.backoffs.forEach((entry) => {
|
|
530
|
+
clearTimeout(entry.timer);
|
|
531
|
+
entry.resolve();
|
|
532
|
+
});
|
|
533
|
+
this.backoffs.clear();
|
|
534
|
+
}
|
|
514
535
|
/**
|
|
515
536
|
* Execute token refresh with retry logic
|
|
516
537
|
*/
|
|
517
538
|
async executeRefresh(retryCount = 0, initialRefreshToken) {
|
|
518
|
-
|
|
519
|
-
this.options.onRefreshStart();
|
|
520
|
-
}
|
|
521
|
-
const refreshToken = this.kernel.getRefreshToken();
|
|
539
|
+
const refreshToken = this.uninstalled ? null : this.kernel.getRefreshToken();
|
|
522
540
|
if (initialRefreshToken !== void 0 && refreshToken !== initialRefreshToken) {
|
|
523
541
|
throw supersededError();
|
|
524
542
|
}
|
|
543
|
+
if (this.options.onRefreshStart) {
|
|
544
|
+
this.options.onRefreshStart();
|
|
545
|
+
}
|
|
525
546
|
if (!refreshToken) {
|
|
526
|
-
const error = new AuthError("REFRESH_TOKEN_MISSING", "No refresh token available");
|
|
547
|
+
const error = new chunk62XK5QLP_cjs.AuthError("REFRESH_TOKEN_MISSING", "No refresh token available");
|
|
527
548
|
this.kernel.emit({
|
|
528
549
|
type: "error",
|
|
529
550
|
error,
|
|
@@ -565,10 +586,10 @@ var RefreshEnginePlugin = class {
|
|
|
565
586
|
}
|
|
566
587
|
if (retryCount < this.maxRetries) {
|
|
567
588
|
const delay = this.retryDelay * Math.pow(2, retryCount);
|
|
568
|
-
await
|
|
589
|
+
await this.waitBackoff(Math.min(delay, MAX_TIMEOUT_DELAY));
|
|
569
590
|
return this.executeRefresh(retryCount + 1, refreshToken);
|
|
570
591
|
}
|
|
571
|
-
const authError = new AuthError("REFRESH_FAILED", "Token refresh failed", {
|
|
592
|
+
const authError = new chunk62XK5QLP_cjs.AuthError("REFRESH_FAILED", "Token refresh failed", {
|
|
572
593
|
cause: error instanceof Error ? error : new Error(String(error)),
|
|
573
594
|
context: { retryCount }
|
|
574
595
|
});
|
|
@@ -654,17 +675,19 @@ var RefreshEnginePlugin = class {
|
|
|
654
675
|
*/
|
|
655
676
|
uninstall() {
|
|
656
677
|
this.cancelScheduledRefresh();
|
|
678
|
+
this.uninstalled = true;
|
|
679
|
+
this.endBackoffs();
|
|
657
680
|
}
|
|
658
681
|
};
|
|
659
682
|
function supersededError() {
|
|
660
|
-
return new AuthError(
|
|
683
|
+
return new chunk62XK5QLP_cjs.AuthError(
|
|
661
684
|
"REFRESH_FAILED",
|
|
662
685
|
"Session changed while refreshing (logout or new login); refresh result discarded",
|
|
663
686
|
{ context: { superseded: true } }
|
|
664
687
|
);
|
|
665
688
|
}
|
|
666
689
|
function isSupersededError(error) {
|
|
667
|
-
return error instanceof AuthError && error.context?.["superseded"] === true;
|
|
690
|
+
return error instanceof chunk62XK5QLP_cjs.AuthError && error.context?.["superseded"] === true;
|
|
668
691
|
}
|
|
669
692
|
function createRefreshEnginePlugin(options) {
|
|
670
693
|
return new RefreshEnginePlugin(options);
|
|
@@ -868,7 +891,7 @@ var CookieStorageAdapter = class {
|
|
|
868
891
|
setCookie(this.prefix + key, value, this.attributes);
|
|
869
892
|
this.keys.add(key);
|
|
870
893
|
if (typeof document !== "undefined" && this.get(key) !== value) {
|
|
871
|
-
throw new AuthError("STORAGE_ERROR", `Cookie "${this.prefix + key}" was not stored (too large or blocked)`);
|
|
894
|
+
throw new chunk62XK5QLP_cjs.AuthError("STORAGE_ERROR", `Cookie "${this.prefix + key}" was not stored (too large or blocked)`);
|
|
872
895
|
}
|
|
873
896
|
}
|
|
874
897
|
remove(key) {
|
|
@@ -903,7 +926,7 @@ function resolveStorage(storage) {
|
|
|
903
926
|
case "cookie":
|
|
904
927
|
return typeof document !== "undefined" ? new CookieStorageAdapter() : createMemoryStorage();
|
|
905
928
|
default:
|
|
906
|
-
throw new AuthError("CONFIG_ERROR", `Unknown storage type: ${String(storage)}`, {
|
|
929
|
+
throw new chunk62XK5QLP_cjs.AuthError("CONFIG_ERROR", `Unknown storage type: ${String(storage)}`, {
|
|
907
930
|
context: { storage }
|
|
908
931
|
});
|
|
909
932
|
}
|
|
@@ -961,10 +984,10 @@ var FetchInterceptorPlugin = class {
|
|
|
961
984
|
const isRequest = typeof Request !== "undefined" && input instanceof Request;
|
|
962
985
|
const canRetry = retry401 && maxRetries > 0;
|
|
963
986
|
const pristineRequest = canRetry && isRequest ? input.clone() : null;
|
|
964
|
-
|
|
987
|
+
let sentToken = this.kernel.getAccessToken();
|
|
965
988
|
const headers = new Headers(init?.headers ?? (isRequest ? input.headers : void 0));
|
|
966
|
-
if (
|
|
967
|
-
headers.set(headerName, headerPrefix +
|
|
989
|
+
if (sentToken) {
|
|
990
|
+
headers.set(headerName, headerPrefix + sentToken);
|
|
968
991
|
}
|
|
969
992
|
let response = await this.baseFetch(input, {
|
|
970
993
|
...init,
|
|
@@ -974,16 +997,20 @@ var FetchInterceptorPlugin = class {
|
|
|
974
997
|
if (onUnauthorized) {
|
|
975
998
|
onUnauthorized(response);
|
|
976
999
|
}
|
|
977
|
-
|
|
978
|
-
|
|
979
|
-
|
|
980
|
-
|
|
981
|
-
|
|
1000
|
+
const current = this.kernel.getAccessToken();
|
|
1001
|
+
if (!current || current === sentToken) {
|
|
1002
|
+
try {
|
|
1003
|
+
await this.kernel.refresh();
|
|
1004
|
+
} catch (error) {
|
|
1005
|
+
console.error("[AuthKeeper] Token refresh failed during 401 retry:", error);
|
|
1006
|
+
break;
|
|
1007
|
+
}
|
|
982
1008
|
}
|
|
983
1009
|
const newToken = this.kernel.getAccessToken();
|
|
984
1010
|
if (!newToken) {
|
|
985
1011
|
break;
|
|
986
1012
|
}
|
|
1013
|
+
sentToken = newToken;
|
|
987
1014
|
headers.set(headerName, headerPrefix + newToken);
|
|
988
1015
|
response = await this.baseFetch(pristineRequest ? pristineRequest.clone() : input, {
|
|
989
1016
|
...init,
|
|
@@ -1020,7 +1047,6 @@ function createFetchInterceptorPlugin() {
|
|
|
1020
1047
|
return new FetchInterceptorPlugin();
|
|
1021
1048
|
}
|
|
1022
1049
|
|
|
1023
|
-
exports.AuthError = AuthError;
|
|
1024
1050
|
exports.CookieStorageAdapter = CookieStorageAdapter;
|
|
1025
1051
|
exports.FetchInterceptorPlugin = FetchInterceptorPlugin;
|
|
1026
1052
|
exports.MemoryStorageAdapter = MemoryStorageAdapter;
|
|
@@ -1056,5 +1082,5 @@ exports.safeSetItem = safeSetItem;
|
|
|
1056
1082
|
exports.serializeCookie = serializeCookie;
|
|
1057
1083
|
exports.setCookie = setCookie;
|
|
1058
1084
|
exports.stringToBase64Url = stringToBase64Url;
|
|
1059
|
-
//# sourceMappingURL=chunk-
|
|
1060
|
-
//# sourceMappingURL=chunk-
|
|
1085
|
+
//# sourceMappingURL=chunk-EXV2RG6T.cjs.map
|
|
1086
|
+
//# sourceMappingURL=chunk-EXV2RG6T.cjs.map
|