@oxog/authkeeper 1.5.1 → 1.6.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 +9 -0
- package/README.md +59 -2
- package/dist/{auth-source-CXqrhLDO.d.ts → auth-source-BwPxq1Za.d.ts} +1 -1
- package/dist/{auth-source-rjMWiP1Q.d.cts → auth-source-MSiTDST6.d.cts} +1 -1
- package/dist/{chunk-DLCD3SBV.js → chunk-K3XXGKGO.js} +2 -2
- package/dist/chunk-K3XXGKGO.js.map +1 -0
- package/dist/{chunk-XGKVBZSF.cjs → chunk-MONA6MGX.cjs} +2 -2
- package/dist/chunk-MONA6MGX.cjs.map +1 -0
- package/dist/{chunk-VVSZPARR.cjs → chunk-SI7KITBT.cjs} +323 -273
- package/dist/chunk-SI7KITBT.cjs.map +1 -0
- package/dist/{chunk-7B77NZGY.js → chunk-ZZMKSCXQ.js} +312 -263
- package/dist/chunk-ZZMKSCXQ.js.map +1 -0
- package/dist/{index-CQwGO-Wk.d.ts → index-BqxH4X40.d.ts} +52 -6
- package/dist/{index-C4pGS-TI.d.cts → index-ChJtNH74.d.cts} +52 -6
- package/dist/index.cjs +461 -52
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +32 -4
- package/dist/index.d.ts +32 -4
- package/dist/index.js +416 -7
- package/dist/index.js.map +1 -1
- package/dist/plugins/index.cjs +15 -15
- package/dist/plugins/index.d.cts +2 -2
- package/dist/plugins/index.d.ts +2 -2
- package/dist/plugins/index.js +2 -2
- package/dist/react/index.cjs +3 -3
- package/dist/react/index.d.cts +2 -2
- package/dist/react/index.d.ts +2 -2
- package/dist/react/index.js +1 -1
- package/dist/svelte/index.d.cts +2 -2
- package/dist/svelte/index.d.ts +2 -2
- package/dist/{types-DMPBl-Ym.d.ts → types-DWB4dbp8.d.cts} +26 -4
- package/dist/{types-DMPBl-Ym.d.cts → types-DWB4dbp8.d.ts} +26 -4
- package/dist/vue/index.cjs +2 -2
- package/dist/vue/index.d.cts +2 -2
- package/dist/vue/index.d.ts +2 -2
- package/dist/vue/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-7B77NZGY.js.map +0 -1
- package/dist/chunk-DLCD3SBV.js.map +0 -1
- package/dist/chunk-VVSZPARR.cjs.map +0 -1
- package/dist/chunk-XGKVBZSF.cjs.map +0 -1
package/CHANGELOG.md
CHANGED
|
@@ -7,6 +7,15 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
|
|
|
7
7
|
|
|
8
8
|
## [Unreleased]
|
|
9
9
|
|
|
10
|
+
## [1.6.0] - 2026-12-02
|
|
11
|
+
|
|
12
|
+
### Added
|
|
13
|
+
|
|
14
|
+
- `syncTabs: true` (until now reserved and a no-op): the open tabs of an app share one session. A login (`setTokens()`) or refresh in one tab is adopted by the others, which update their in-memory session and auto-refresh schedule and emit the same `login` / `refresh` event marked `remote: true` (with `sourceTabId`), followed by a `tab-sync` event. Only one tab refreshes at a time (Web Locks, or a lease in localStorage where `navigator.locks` is missing), and a tab whose refresh waited for another tab's uses that result: with rotating refresh tokens a second tab no longer fails with `REFRESH_FAILED`. Messages go over a BroadcastChannel named after the storage prefix and key, or over `storage` events on localStorage where there is no BroadcastChannel; a tab ignores its own, repeated and outdated messages. Sync needs storage the tabs share in a browser (`'localStorage'`; `'cookie'` or a custom adapter where BroadcastChannel exists) and is a no-op with `'memory'` / `'sessionStorage'` and during SSR. `getOptions().syncTabs` reports whether it is active, `configure({ syncTabs })` turns it on or off, and `destroy()` closes the channel, removes the listener and releases the lock.
|
|
15
|
+
- `logout({ allTabs: true })` (until now reserved): with `syncTabs`, signs out every tab; the others emit `logout` with `reason: 'tab-sync'` and `remote: true`. Plain `logout()` still signs out this tab only.
|
|
16
|
+
- Additive API for it: `remote` / `sourceTabId` on `LoginEvent`, `RefreshEvent` and `LogoutEvent`; optional `TokenStoreAPI.replace()`, `readPersisted()` and `getStorage()`, and `RefreshEngineAPI.setCoordinator()` (type `RefreshCoordinator`); `WebStorageAdapter.storage` / `prefix` and `CookieStorageAdapter.prefix` are public read-only properties.
|
|
17
|
+
- Browser tests for it (`tests/browser/sync.browser.ts`): two and three real tabs over BroadcastChannel + Web Locks and over the storage-event + lease fallback (login, refresh and `allTabs` logout propagation, one refresh request for concurrent and for simultaneously scheduled refreshes against the local auth server's rotating refresh tokens, nothing left in localStorage), and `destroy()` closing the channel and releasing a held lock or lease.
|
|
18
|
+
|
|
10
19
|
## [1.5.1] - 2026-12-02
|
|
11
20
|
|
|
12
21
|
### Fixed
|
package/README.md
CHANGED
|
@@ -261,8 +261,64 @@ auth.logout()
|
|
|
261
261
|
|
|
262
262
|
// Logout with redirect
|
|
263
263
|
auth.logout({ redirect: '/login' })
|
|
264
|
+
|
|
265
|
+
// Sign out every tab of the app (needs `syncTabs`, see below)
|
|
266
|
+
auth.logout({ allTabs: true })
|
|
264
267
|
```
|
|
265
268
|
|
|
269
|
+
`logout()` signs out this tab only: it clears the in-memory session and
|
|
270
|
+
removes the persisted one, but other open tabs keep their session until they
|
|
271
|
+
reload (or until `logout({ allTabs: true })` with `syncTabs`).
|
|
272
|
+
|
|
273
|
+
### Cross-Tab Sync
|
|
274
|
+
|
|
275
|
+
With `syncTabs: true` the open tabs of an app share one session:
|
|
276
|
+
|
|
277
|
+
```typescript
|
|
278
|
+
const auth = await createAuthKeeper({
|
|
279
|
+
refreshToken: refreshFn,
|
|
280
|
+
storage: 'localStorage', // storage the tabs share
|
|
281
|
+
syncTabs: true,
|
|
282
|
+
})
|
|
283
|
+
|
|
284
|
+
auth.on('login', (event) => {
|
|
285
|
+
if (event.remote) console.log('Signed in in another tab:', event.sourceTabId)
|
|
286
|
+
})
|
|
287
|
+
|
|
288
|
+
auth.logout() // this tab only
|
|
289
|
+
auth.logout({ allTabs: true }) // every tab
|
|
290
|
+
```
|
|
291
|
+
|
|
292
|
+
- A login (`setTokens()`) or refresh in one tab is adopted by the others: they
|
|
293
|
+
update their in-memory session and auto-refresh schedule, and emit the same
|
|
294
|
+
`login` / `refresh` event with `remote: true` and `sourceTabId`, followed by
|
|
295
|
+
a `tab-sync` event. A tab that signed out with a plain `logout()` ignores
|
|
296
|
+
refreshes of its old session, but adopts a new login.
|
|
297
|
+
- Only one tab refreshes at a time (a Web Lock, or a lease in localStorage
|
|
298
|
+
where `navigator.locks` is missing). A tab whose refresh waited for another
|
|
299
|
+
tab's refresh uses that result instead of refreshing again with a refresh
|
|
300
|
+
token the other tab has just rotated out (which the server would reject).
|
|
301
|
+
- `logout({ allTabs: true })` signs out every tab; the others emit `logout`
|
|
302
|
+
with `reason: 'tab-sync'` and `remote: true`. Plain `logout()` stays local.
|
|
303
|
+
- Messages go over a `BroadcastChannel` named after the storage
|
|
304
|
+
(`authkeeper-sync:` + key prefix + key), so apps with different storage
|
|
305
|
+
prefixes keep apart. Without BroadcastChannel, `storage` events on
|
|
306
|
+
localStorage carry them (only with `storage: 'localStorage'`; the message is
|
|
307
|
+
removed right away). Each message carries the sending tab's id, a sequence
|
|
308
|
+
number and the session's generation: a tab ignores its own, repeated and
|
|
309
|
+
outdated messages.
|
|
310
|
+
- Sync needs storage the tabs share, in a browser: `'localStorage'`, or
|
|
311
|
+
`'cookie'` / a custom adapter where BroadcastChannel exists (a custom
|
|
312
|
+
adapter's channel is named after its key only). With `'memory'` or
|
|
313
|
+
`'sessionStorage'`, where storage falls back to memory, and during SSR it is
|
|
314
|
+
a no-op. `getOptions().syncTabs` reports whether sync is active;
|
|
315
|
+
`configure({ syncTabs })` turns it on or off.
|
|
316
|
+
- `destroy()` closes the channel, removes the listener and gives up or
|
|
317
|
+
releases the refresh lock.
|
|
318
|
+
|
|
319
|
+
> Messages carry the session (tokens) to the other tabs of the same origin,
|
|
320
|
+
> which can read the shared storage anyway.
|
|
321
|
+
|
|
266
322
|
## 🧩 Framework Adapters
|
|
267
323
|
|
|
268
324
|
Thin bindings over the same instance; the frameworks are optional peer
|
|
@@ -533,7 +589,7 @@ interface KernelOptions {
|
|
|
533
589
|
storage?: StorageType | StorageAdapter // Default: 'memory'
|
|
534
590
|
plugins?: Plugin[]
|
|
535
591
|
onError?: (error: AuthError) => void
|
|
536
|
-
syncTabs?: boolean //
|
|
592
|
+
syncTabs?: boolean // Default: false. Share the session between tabs (see Cross-Tab Sync)
|
|
537
593
|
}
|
|
538
594
|
```
|
|
539
595
|
|
|
@@ -545,7 +601,8 @@ src/
|
|
|
545
601
|
├── kernel/
|
|
546
602
|
│ ├── kernel.ts # Main kernel
|
|
547
603
|
│ ├── event-bus.ts # Event system
|
|
548
|
-
│
|
|
604
|
+
│ ├── plugin-registry.ts # Plugin management
|
|
605
|
+
│ └── tab-sync.ts # Cross-tab messaging and refresh lock
|
|
549
606
|
├── plugins/core/
|
|
550
607
|
│ ├── token-store.ts # Token state management
|
|
551
608
|
│ ├── token-decoder.ts # JWT decoding
|
|
@@ -13,5 +13,5 @@ var AuthError = class _AuthError extends Error {
|
|
|
13
13
|
};
|
|
14
14
|
|
|
15
15
|
export { AuthError };
|
|
16
|
-
//# sourceMappingURL=chunk-
|
|
17
|
-
//# sourceMappingURL=chunk-
|
|
16
|
+
//# sourceMappingURL=chunk-K3XXGKGO.js.map
|
|
17
|
+
//# sourceMappingURL=chunk-K3XXGKGO.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-K3XXGKGO.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 /** True when the change was made in another tab (`syncTabs`) */\n remote?: boolean\n /** Id of the tab (AuthKeeper instance) the change came from, for remote changes */\n sourceTabId?: string\n}\n\n/**\n * Logout event - fired when user logs out\n */\nexport interface LogoutEvent {\n type: 'logout'\n /** 'tab-sync': another tab called `logout({ allTabs: true })` */\n reason: 'manual' | 'expired' | 'error' | 'tab-sync'\n timestamp: number\n /** True when the change was made in another tab (`syncTabs`) */\n remote?: boolean\n /** Id of the tab (AuthKeeper instance) the change came from, for remote changes */\n sourceTabId?: string\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 /** True when the change was made in another tab (`syncTabs`) */\n remote?: boolean\n /** Id of the tab (AuthKeeper instance) the change came from, for remote changes */\n sourceTabId?: string\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 this tab adopted a change made in another tab\n * (`syncTabs`), after the 'login' / 'refresh' / 'logout' event it caused\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> = (event: Extract<AuthEvent, { type: E }>) => 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 * Keep the tabs of this app in sync (default: false): logins and refreshes\n * made in one tab are adopted by the others, only one tab refreshes at a\n * time, and `logout({ allTabs: true })` signs every tab out. Needs storage\n * the tabs share ('localStorage', 'cookie' or a custom adapter) in a\n * browser; a no-op with 'memory' / 'sessionStorage' and outside browsers.\n * `getOptions().syncTabs` reports whether sync is active.\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 /**\n * Also sign out the other tabs of this app (needs `syncTabs`; without it,\n * or where sync is unavailable, only this tab is signed out). Default:\n * false, i.e. only this tab is signed out.\n */\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 = (input: RequestInfo | URL, init?: RequestInit) => 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"]}
|
|
@@ -15,5 +15,5 @@ var AuthError = class _AuthError extends Error {
|
|
|
15
15
|
};
|
|
16
16
|
|
|
17
17
|
exports.AuthError = AuthError;
|
|
18
|
-
//# sourceMappingURL=chunk-
|
|
19
|
-
//# sourceMappingURL=chunk-
|
|
18
|
+
//# sourceMappingURL=chunk-MONA6MGX.cjs.map
|
|
19
|
+
//# sourceMappingURL=chunk-MONA6MGX.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-MONA6MGX.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 /** True when the change was made in another tab (`syncTabs`) */\n remote?: boolean\n /** Id of the tab (AuthKeeper instance) the change came from, for remote changes */\n sourceTabId?: string\n}\n\n/**\n * Logout event - fired when user logs out\n */\nexport interface LogoutEvent {\n type: 'logout'\n /** 'tab-sync': another tab called `logout({ allTabs: true })` */\n reason: 'manual' | 'expired' | 'error' | 'tab-sync'\n timestamp: number\n /** True when the change was made in another tab (`syncTabs`) */\n remote?: boolean\n /** Id of the tab (AuthKeeper instance) the change came from, for remote changes */\n sourceTabId?: string\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 /** True when the change was made in another tab (`syncTabs`) */\n remote?: boolean\n /** Id of the tab (AuthKeeper instance) the change came from, for remote changes */\n sourceTabId?: string\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 this tab adopted a change made in another tab\n * (`syncTabs`), after the 'login' / 'refresh' / 'logout' event it caused\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> = (event: Extract<AuthEvent, { type: E }>) => 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 * Keep the tabs of this app in sync (default: false): logins and refreshes\n * made in one tab are adopted by the others, only one tab refreshes at a\n * time, and `logout({ allTabs: true })` signs every tab out. Needs storage\n * the tabs share ('localStorage', 'cookie' or a custom adapter) in a\n * browser; a no-op with 'memory' / 'sessionStorage' and outside browsers.\n * `getOptions().syncTabs` reports whether sync is active.\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 /**\n * Also sign out the other tabs of this app (needs `syncTabs`; without it,\n * or where sync is unavailable, only this tab is signed out). Default:\n * false, i.e. only this tab is signed out.\n */\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 = (input: RequestInfo | URL, init?: RequestInit) => 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"]}
|