@oxog/authkeeper 1.0.0 → 1.2.1

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 CHANGED
@@ -5,6 +5,178 @@ All notable changes to this project will be documented in this file.
5
5
  The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
6
6
  and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
7
7
 
8
+ ## [1.2.1] - 2026-12-01
9
+
10
+ ### Fixed
11
+
12
+ - Tokens living longer than about 24.8 days (lifetime minus `refreshThreshold`
13
+ above the 2^31-1 ms `setTimeout` limit) were refreshed in an endless loop:
14
+ the overflowing timer fired after ~1 ms and every refresh scheduled the next
15
+ one immediately, hammering the refresh endpoint. Long waits are now split
16
+ into chunks and the refresh happens `refreshThreshold` seconds before expiry.
17
+ - `clearTokens()` did not cancel the scheduled refresh, which later failed with
18
+ a `REFRESH_TOKEN_MISSING` error event and a `console.error`. A refresh retry
19
+ waiting out its backoff when the session is cleared, replaced or destroyed is
20
+ now abandoned (rejecting with `REFRESH_FAILED`, `context.superseded: true`)
21
+ instead of reporting a missing refresh token; scheduled refreshes abandoned
22
+ this way are not logged.
23
+ - `register()` / `unregister()` were typed as returning `void` although they
24
+ return a promise, so a plugin whose `install()` failed produced an unhandled
25
+ promise rejection. They are now typed `Promise<void>`; `register()` rejects
26
+ for callers that await it and also emits an `error` event with the new
27
+ context `'plugin'` (and calls `onError`), so ignoring the promise no longer
28
+ causes an unhandled rejection. A plugin that failed to install is no longer
29
+ left half-registered, so it can be registered again.
30
+ - `getOptions()` reported `syncTabs: true` although multi-tab sync is not
31
+ implemented. It now reports `false`; the option remains reserved.
32
+
33
+ ## [1.2.0] - 2026-11-30
34
+
35
+ 1.1.0 was never published to npm; this release also ships everything listed
36
+ under 1.1.0 below.
37
+
38
+ ### Security
39
+
40
+ - A token refresh that completed after `logout()` stored the refreshed tokens
41
+ again, silently logging the user back in (and re-persisting the session). A
42
+ refresh whose session changed while it was in flight (logout or a login with
43
+ different tokens) is now discarded and rejects with `REFRESH_FAILED`
44
+ (`context.superseded: true`); a stale refresh no longer overwrites a newer login.
45
+ - `createFetch()` string `includeUrls` / `excludeUrls` patterns are matched
46
+ against the URL without its query string and fragment, so
47
+ `https://evil.example/?next=api.example.com` no longer receives the bearer
48
+ token when `includeUrls: ['api.example.com']`.
49
+ - `serializeCookie()` rejects `path` / `domain` values containing `;`, CR, LF
50
+ or NUL (attribute injection) and adds `Secure` whenever `SameSite=None`.
51
+ - When no `expiresIn` / `expiresAt` is supplied, the expiry now comes from the
52
+ access token's JWT `exp` claim; previously an already expired JWT made
53
+ `isAuthenticated()` return `true` forever.
54
+
55
+ ### Fixed
56
+
57
+ - `wrapFetch()` recursed into itself (`RangeError: Maximum call stack size
58
+ exceeded`) on the first request, because the wrapper called the global
59
+ `fetch` it had just replaced. It now calls the original fetch.
60
+ - `createFetch()` dropped the headers of a `Request` object (e.g.
61
+ `Content-Type`) when adding the `Authorization` header.
62
+ - The 401 retry of a `Request` with a body always failed (the first attempt had
63
+ consumed the body) and the original 401 was returned; the request is now
64
+ cloned before the first attempt. `maxRetries` above 1 is honoured, and a
65
+ network error from the retried request is propagated instead of being
66
+ reported as a refresh failure.
67
+ - Refresh errors (`REFRESH_TOKEN_MISSING`, `REFRESH_FAILED`) were plain `Error`
68
+ objects: `instanceof AuthError` was `false`. `REFRESH_FAILED.cause` is always
69
+ an `Error`.
70
+ - `RefreshEnginePlugin` ignored `threshold: 0`, `maxRetries: 0` and
71
+ `retryDelay: 0` (`||` defaults).
72
+ - `expiresIn: 0` / `expiresAt: 0` were treated as "never expires".
73
+ - Every token refresh also emitted a `login` event.
74
+ - Auto-refresh stopped after the first refresh when the issued token lifetime
75
+ was not longer than `refreshThreshold`; the next refresh is now scheduled
76
+ halfway through the remaining lifetime (at least 1 s apart).
77
+ - A manual `refresh()` scheduled automatic refreshes even with
78
+ `autoRefresh: false`.
79
+ - `isValidJwtFormat()` accepted `..` and tokens whose header/payload are not
80
+ JSON objects.
81
+ - Base64URL helpers threw `ReferenceError: Buffer is not defined` in Web
82
+ Workers, Deno and edge runtimes (they chose `Buffer` whenever `window` was
83
+ missing); they now use `atob`/`btoa` and fall back to `Buffer`.
84
+ - `parseCookies()` / `getCookie()` threw `URIError` when any cookie on the page
85
+ was malformed, and did not decode cookie names written by `serializeCookie()`.
86
+ - `KernelOptions.storage` was required by the types although the README
87
+ omitted it (README examples did not compile). It is now optional.
88
+ - README examples used non-existent options and events (`baseURL`,
89
+ `includeURLs`, `refresh:success`, plugin `type: 'custom'`); they are now
90
+ type-checked by the test suite.
91
+
92
+ ### Added
93
+
94
+ - Token persistence: the `storage` option (`'memory'` (default),
95
+ `'localStorage'`, `'sessionStorage'`, `'cookie'` or a `StorageAdapter`) was
96
+ accepted but ignored. Tokens are now persisted, restored by
97
+ `createAuthKeeper()` (auto-refresh resumes), removed by `logout()` /
98
+ `clearTokens()` and kept by `destroy()`. Malformed entries are discarded and
99
+ storage failures are reported as `error` events (`context: 'storage'`,
100
+ code `STORAGE_ERROR`). New exports: `WebStorageAdapter`,
101
+ `CookieStorageAdapter`, `resolveStorage` (from `./plugins`).
102
+ - `TokenStoreOptions.validateOnSet` (previously a no-op) rejects access tokens
103
+ that are not structurally valid JWTs; `setTokens()` rejects an empty access
104
+ token with `TOKEN_INVALID`.
105
+ - The cookie and storage helpers advertised in the README are exported:
106
+ `parseCookies`, `getCookie`, `serializeCookie`, `setCookie`, `deleteCookie`,
107
+ `CookieAttributes`, `isStorageAvailable`, `safeGetItem`, `safeSetItem`,
108
+ `safeRemoveItem`.
109
+ - `scripts/check-package.mjs` (`npm run test:package`): installs the packed
110
+ archive and checks every entry point with ESM, CommonJS and TypeScript
111
+ `NodeNext`, plus smoke tests in `tests/package/`.
112
+ - CI workflow (Node 18, 20, 22, 24) and a manual npm Trusted Publishing workflow.
113
+
114
+ ### Changed
115
+
116
+ - Build uses code splitting: `@oxog/authkeeper` and `@oxog/authkeeper/plugins`
117
+ previously each bundled their own copy of every class
118
+ (`TokenStorePlugin` from one entry was not the one from the other).
119
+ - `exports` now has per-condition types (`.d.ts` for `import`, `.d.cts` for
120
+ `require`) and exposes `./package.json`.
121
+ - `TokenStorePlugin.uninstall()` (run by `destroy()`) clears only the
122
+ in-memory tokens and no longer calls `onClear`.
123
+ - `syncTabs`, `LogoutOptions.allTabs` and `Plugin.hooks` are documented as
124
+ reserved (not implemented yet); the `/react`, `/vue`, `/svelte` entry points
125
+ are documented as placeholders.
126
+ - `npm test` runs once (`vitest run`); `typecheck` also checks the tests;
127
+ `lint` covers `src` and `tests` with `--max-warnings=0`; 100% coverage
128
+ thresholds are enforced; `prepublishOnly` runs lint, typecheck, coverage,
129
+ build and the package check.
130
+ - `repository` / `bugs` URLs use the repository's exact name (`AuthKeeper`).
131
+
132
+ ---
133
+
134
+ ## [1.1.0] - 2025-12-28
135
+
136
+ ### ✨ Improvements
137
+
138
+ #### Testing
139
+ - ✅ **100% Code Coverage Achieved!**
140
+ - Statements: 100% (was 99.83%)
141
+ - Branches: 100% (was 99.24%)
142
+ - Functions: 100% (was 100%)
143
+ - Lines: 100% (was 99.83%)
144
+ - ✅ Added Node.js environment tests for base64 utilities
145
+ - ✅ Fixed 6 unhandled promise rejections in refresh-engine tests
146
+ - ✅ Improved test reliability and stability
147
+ - ✅ Total tests: 546 (was 541)
148
+
149
+ #### Documentation
150
+ - 📚 Created comprehensive documentation website
151
+ - Modern React + Vite + TypeScript stack
152
+ - shadcn/ui components with Tailwind CSS
153
+ - Dark/Light theme support
154
+ - JetBrains Mono fonts for code
155
+ - Fully responsive design
156
+ - Pages: Home, Docs, API, Examples, Playground
157
+ - 🚀 Automatic deployment to GitHub Pages
158
+ - GitHub Actions workflow
159
+ - Custom domain: https://authkeeper.oxog.dev
160
+ - Continuous deployment on every commit
161
+
162
+ #### Quality
163
+ - ✅ All tests passing with 100% success rate
164
+ - ✅ Zero unhandled errors in test suite
165
+ - ✅ Improved code reliability
166
+ - ✅ Enhanced browser and Node.js compatibility
167
+
168
+ ### 🔧 Fixed
169
+ - Fixed unhandled promise rejections in async refresh tests
170
+ - Fixed test timing issues with promise error handling
171
+ - Improved error handling in test suites
172
+
173
+ ### 📦 Build
174
+ - Build successful: 36 files, 531.4 kB unpacked
175
+ - Package size: 108.8 kB (gzipped)
176
+ - All TypeScript definitions generated correctly
177
+
178
+ ---
179
+
8
180
  ## [1.0.0] - 2025-12-28
9
181
 
10
182
  ### 🎉 Initial Release
@@ -151,4 +323,5 @@ npm run test:coverage # Run with coverage report
151
323
 
152
324
  **For testing details, see [TESTING.md](TESTING.md)**
153
325
 
326
+ [1.1.0]: https://github.com/ersinkoc/authkeeper/releases/tag/v1.1.0
154
327
  [1.0.0]: https://github.com/ersinkoc/authkeeper/releases/tag/v1.0.0
package/README.md CHANGED
@@ -2,8 +2,8 @@
2
2
 
3
3
  > A micro-kernel authentication library with plugin-based architecture
4
4
 
5
- [![Tests](https://img.shields.io/badge/tests-541%20passing-brightgreen)]()
6
- [![Coverage](https://img.shields.io/badge/coverage-99.83%25-brightgreen)]()
5
+ [![CI](https://github.com/ersinkoc/AuthKeeper/actions/workflows/ci.yml/badge.svg)](https://github.com/ersinkoc/AuthKeeper/actions/workflows/ci.yml)
6
+ [![Coverage](https://img.shields.io/badge/coverage-100%25-brightgreen)]()
7
7
  [![TypeScript](https://img.shields.io/badge/TypeScript-5.x-blue)]()
8
8
  [![License](https://img.shields.io/badge/license-MIT-blue)]()
9
9
 
@@ -14,12 +14,12 @@ AuthKeeper is a lightweight, plugin-based authentication library that provides J
14
14
  - 🔌 **Plugin-Based Architecture** - Extensible micro-kernel design
15
15
  - 🔄 **Automatic Token Refresh** - Smart refresh with queuing and retry logic
16
16
  - 🎯 **Fetch Interception** - Automatic auth header injection and 401 retry
17
- - 💾 **Flexible Storage** - Memory, localStorage, sessionStorage, or custom adapters
17
+ - 💾 **Flexible Storage** - Memory (default), localStorage, sessionStorage, cookie, or custom adapters
18
18
  - 📡 **Event System** - Subscribe to auth lifecycle events
19
- - 🔒 **JWT Support** - Built-in JWT decoding and validation
20
- - 🍪 **Cookie Support** - Parse and manage authentication cookies
19
+ - 🔒 **JWT Support** - Built-in JWT decoding and expiry checks (signatures are verified by your server, not here)
20
+ - 🍪 **Cookie Support** - Parse and serialize cookies (`parseCookies`, `serializeCookie`, ...)
21
21
  - ⚡ **Zero Dependencies** - Pure TypeScript implementation
22
- - 🧪 **100% Tested** - 541 tests with 99.83% coverage
22
+ - 🧪 **100% Tested** - 100% line/branch coverage, enforced in CI
23
23
  - 📦 **Tree-Shakeable** - Only bundle what you use
24
24
 
25
25
  ## 📦 Installation
@@ -30,6 +30,8 @@ npm install @oxog/authkeeper
30
30
  yarn add @oxog/authkeeper
31
31
  # or
32
32
  pnpm add @oxog/authkeeper
33
+ # or
34
+ bun add @oxog/authkeeper
33
35
  ```
34
36
 
35
37
  ## 🚀 Quick Start
@@ -87,7 +89,7 @@ AuthKeeper uses a plugin-based architecture where most functionality is provided
87
89
  All core plugins are automatically registered when using `createAuthKeeper()`:
88
90
 
89
91
  - **token-store** - Manages token state and expiration
90
- - **token-decoder** - Decodes and validates JWT tokens
92
+ - **token-decoder** - Decodes JWT tokens (no signature verification)
91
93
  - **refresh-engine** - Handles automatic token refresh with retry logic
92
94
  - **fetch-interceptor** - Injects auth headers and handles 401 responses
93
95
 
@@ -125,6 +127,35 @@ const timeUntilExpiry = auth.getTimeUntilExpiry()
125
127
  auth.clearTokens()
126
128
  ```
127
129
 
130
+ If neither `expiresIn` nor `expiresAt` is given, the expiry is taken from the
131
+ access token's JWT `exp` claim (opaque tokens without an expiry never expire
132
+ client-side).
133
+
134
+ ### Token Storage
135
+
136
+ Tokens are kept in memory by default (the safest option: not reachable by
137
+ other scripts and not persisted). To survive page reloads, choose a
138
+ persistent storage:
139
+
140
+ ```typescript
141
+ const auth = await createAuthKeeper({
142
+ refreshToken: refreshFn,
143
+ storage: 'localStorage', // 'memory' | 'localStorage' | 'sessionStorage' | 'cookie' | StorageAdapter
144
+ })
145
+ ```
146
+
147
+ - Persisted tokens are restored by `createAuthKeeper()` and auto-refresh resumes.
148
+ - `logout()` / `clearTokens()` remove them; `destroy()` does not.
149
+ - Corrupt entries are discarded; storage failures are reported as `error`
150
+ events with `context: 'storage'` instead of throwing.
151
+ - Unavailable storage (SSR, disabled storage) falls back to memory.
152
+ - `'cookie'` writes `Secure; SameSite=Strict; Path=/` cookies. Cookies set from
153
+ JavaScript cannot be `HttpOnly`.
154
+
155
+ > ⚠️ localStorage, sessionStorage and JavaScript-set cookies are readable by any
156
+ > script on the page. Prefer memory storage plus an `HttpOnly` refresh cookie set
157
+ > by your server where possible.
158
+
128
159
  ### Manual Token Refresh
129
160
 
130
161
  ```typescript
@@ -155,17 +186,24 @@ const auth = await createAuthKeeper({
155
186
  ```typescript
156
187
  // Create authenticated fetch
157
188
  const authFetch = auth.createFetch({
158
- baseURL: 'https://api.example.com',
159
- retry401: true, // Retry with refreshed token on 401
160
- includeURLs: ['/api/*'], // Only add auth to these URLs
161
- excludeURLs: ['/api/public/*'], // Except these
189
+ retry401: true, // Refresh and retry on 401 (up to maxRetries, default 1)
190
+ includeUrls: [/^https:\/\/api\.example\.com\//], // Only add auth to these URLs
191
+ excludeUrls: ['/public/'], // Except these
162
192
  })
163
193
 
164
194
  // Use like normal fetch
165
- const response = await authFetch('/api/users')
195
+ const response = await authFetch('https://api.example.com/users')
166
196
  const data = await response.json()
167
197
  ```
168
198
 
199
+ URL patterns: a `RegExp` is tested against the full URL; a string matches if it
200
+ appears anywhere in the URL **before** the query string / fragment. Without
201
+ `includeUrls` the token is sent to **every** URL, so set `includeUrls` (ideally
202
+ anchored RegExps for your API origin) whenever the app talks to third parties.
203
+
204
+ `auth.wrapFetch(fetch)` replaces `globalThis.fetch` with an authenticated
205
+ version (default `createFetch()` options); `auth.destroy()` restores it.
206
+
169
207
  ### Event Handling
170
208
 
171
209
  ```typescript
@@ -178,16 +216,16 @@ auth.on('logout', (event) => {
178
216
  console.log('User logged out:', event.reason)
179
217
  })
180
218
 
181
- auth.on('refresh:success', (event) => {
219
+ // Fired for token refreshes ('login' is only fired by setTokens() calls)
220
+ auth.on('refresh', (event) => {
182
221
  console.log('Tokens refreshed:', event.tokens)
183
222
  })
184
223
 
185
- auth.on('refresh:error', (event) => {
186
- console.error('Refresh failed:', event.error)
187
- })
188
-
224
+ // Refresh failures (event.context === 'refresh'), storage failures
225
+ // (event.context === 'storage') and plugin install failures
226
+ // (event.context === 'plugin'); event.error is an AuthError
189
227
  auth.on('error', (event) => {
190
- console.error('Auth error:', event.error)
228
+ console.error('Auth error:', event.error.code, event.error)
191
229
  })
192
230
  ```
193
231
 
@@ -216,6 +254,11 @@ auth.logout()
216
254
  auth.logout({ redirect: '/login' })
217
255
  ```
218
256
 
257
+ ## 🧩 Framework Adapters
258
+
259
+ The `@oxog/authkeeper/react`, `/vue` and `/svelte` entry points are reserved
260
+ placeholders in this release and do not export hooks or stores yet.
261
+
219
262
  ## 🔌 Custom Plugins
220
263
 
221
264
  Create your own plugins to extend functionality:
@@ -226,7 +269,7 @@ import type { Plugin, AuthKeeper } from '@oxog/authkeeper'
226
269
  const myPlugin: Plugin = {
227
270
  name: 'my-plugin',
228
271
  version: '1.0.0',
229
- type: 'custom',
272
+ type: 'optional',
230
273
 
231
274
  install(kernel: AuthKeeper) {
232
275
  // Plugin initialization
@@ -243,7 +286,8 @@ const myPlugin: Plugin = {
243
286
  },
244
287
  }
245
288
 
246
- // Register custom plugin
289
+ // Register custom plugin (rejects if install() fails; the failure is also
290
+ // emitted as an 'error' event with context 'plugin')
247
291
  await auth.register(myPlugin)
248
292
  ```
249
293
 
@@ -252,30 +296,23 @@ await auth.register(myPlugin)
252
296
  AuthKeeper has comprehensive test coverage:
253
297
 
254
298
  ```bash
255
- # Run tests
299
+ # Run tests once
256
300
  npm test
257
301
 
258
- # Run with coverage
259
- npm test -- --coverage
302
+ # Run with coverage (100% thresholds are enforced)
303
+ npm run test:coverage
260
304
 
261
- # Run in watch mode
262
- npm test -- --watch
305
+ # Watch mode
306
+ npm run test:watch
263
307
 
264
- # Run with UI
265
- npm test -- --ui
266
- ```
308
+ # Lint + typecheck + coverage
309
+ npm run check
267
310
 
268
- ### Test Coverage
269
-
270
- ```
271
- Test Files: 16/16 passing
272
- Total Tests: 541/541 passing
273
- Coverage: 99.83%
274
- Functions: 100%
275
- Execution: ~2.5 seconds
311
+ # Verify the packed package (ESM, CJS, TypeScript NodeNext)
312
+ npm run test:package
276
313
  ```
277
314
 
278
- See [TESTING.md](TESTING.md) for detailed testing documentation.
315
+ See [docs/testing/TESTING.md](docs/testing/TESTING.md) for detailed testing documentation.
279
316
 
280
317
  ## 📖 API Reference
281
318
 
@@ -343,10 +380,10 @@ interface KernelOptions {
343
380
  // Optional
344
381
  autoRefresh?: boolean // Default: true
345
382
  refreshThreshold?: number // Default: 60 (seconds)
346
- syncTabs?: boolean // Default: true
347
- storage?: StorageAdapter
383
+ storage?: StorageType | StorageAdapter // Default: 'memory'
348
384
  plugins?: Plugin[]
349
- onError?: (error: Error) => void
385
+ onError?: (error: AuthError) => void
386
+ syncTabs?: boolean // Reserved: multi-tab sync is not implemented yet (getOptions() reports false)
350
387
  }
351
388
  ```
352
389
 
@@ -364,7 +401,8 @@ src/
364
401
  │ ├── token-decoder.ts # JWT decoding
365
402
  │ ├── refresh-engine.ts # Auto-refresh logic
366
403
  │ ├── fetch-interceptor.ts # HTTP interception
367
- │ └── storage-memory.ts # In-memory storage
404
+ │ ├── storage-memory.ts # In-memory storage
405
+ │ └── storage-web.ts # localStorage / sessionStorage / cookie storage
368
406
  └── utils/
369
407
  ├── base64.ts # Base64URL encoding
370
408
  ├── cookie.ts # Cookie utilities
@@ -393,10 +431,10 @@ MIT © Ersin KOÇ
393
431
  ## 🔗 Links
394
432
 
395
433
  - [Documentation](./docs)
396
- - [Testing Guide](./TESTING.md)
397
- - [Test Report](./TEST_REPORT.md)
434
+ - [Testing Guide](./docs/testing/TESTING.md)
435
+ - [Test Report](./docs/testing/TEST_REPORT.md)
398
436
  - [Changelog](./CHANGELOG.md)
399
- - [Issues](https://github.com/oxog/authkeeper/issues)
437
+ - [Issues](https://github.com/ersinkoc/AuthKeeper/issues)
400
438
 
401
439
  ## 💡 Inspiration
402
440