@oxog/authkeeper 1.0.0 → 1.2.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 CHANGED
@@ -5,6 +5,153 @@ 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.0] - 2026-11-30
9
+
10
+ 1.1.0 was never published to npm; this release also ships everything listed
11
+ under 1.1.0 below.
12
+
13
+ ### Security
14
+
15
+ - A token refresh that completed after `logout()` stored the refreshed tokens
16
+ again, silently logging the user back in (and re-persisting the session). A
17
+ refresh whose session changed while it was in flight (logout or a login with
18
+ different tokens) is now discarded and rejects with `REFRESH_FAILED`
19
+ (`context.superseded: true`); a stale refresh no longer overwrites a newer login.
20
+ - `createFetch()` string `includeUrls` / `excludeUrls` patterns are matched
21
+ against the URL without its query string and fragment, so
22
+ `https://evil.example/?next=api.example.com` no longer receives the bearer
23
+ token when `includeUrls: ['api.example.com']`.
24
+ - `serializeCookie()` rejects `path` / `domain` values containing `;`, CR, LF
25
+ or NUL (attribute injection) and adds `Secure` whenever `SameSite=None`.
26
+ - When no `expiresIn` / `expiresAt` is supplied, the expiry now comes from the
27
+ access token's JWT `exp` claim; previously an already expired JWT made
28
+ `isAuthenticated()` return `true` forever.
29
+
30
+ ### Fixed
31
+
32
+ - `wrapFetch()` recursed into itself (`RangeError: Maximum call stack size
33
+ exceeded`) on the first request, because the wrapper called the global
34
+ `fetch` it had just replaced. It now calls the original fetch.
35
+ - `createFetch()` dropped the headers of a `Request` object (e.g.
36
+ `Content-Type`) when adding the `Authorization` header.
37
+ - The 401 retry of a `Request` with a body always failed (the first attempt had
38
+ consumed the body) and the original 401 was returned; the request is now
39
+ cloned before the first attempt. `maxRetries` above 1 is honoured, and a
40
+ network error from the retried request is propagated instead of being
41
+ reported as a refresh failure.
42
+ - Refresh errors (`REFRESH_TOKEN_MISSING`, `REFRESH_FAILED`) were plain `Error`
43
+ objects: `instanceof AuthError` was `false`. `REFRESH_FAILED.cause` is always
44
+ an `Error`.
45
+ - `RefreshEnginePlugin` ignored `threshold: 0`, `maxRetries: 0` and
46
+ `retryDelay: 0` (`||` defaults).
47
+ - `expiresIn: 0` / `expiresAt: 0` were treated as "never expires".
48
+ - Every token refresh also emitted a `login` event.
49
+ - Auto-refresh stopped after the first refresh when the issued token lifetime
50
+ was not longer than `refreshThreshold`; the next refresh is now scheduled
51
+ halfway through the remaining lifetime (at least 1 s apart).
52
+ - A manual `refresh()` scheduled automatic refreshes even with
53
+ `autoRefresh: false`.
54
+ - `isValidJwtFormat()` accepted `..` and tokens whose header/payload are not
55
+ JSON objects.
56
+ - Base64URL helpers threw `ReferenceError: Buffer is not defined` in Web
57
+ Workers, Deno and edge runtimes (they chose `Buffer` whenever `window` was
58
+ missing); they now use `atob`/`btoa` and fall back to `Buffer`.
59
+ - `parseCookies()` / `getCookie()` threw `URIError` when any cookie on the page
60
+ was malformed, and did not decode cookie names written by `serializeCookie()`.
61
+ - `KernelOptions.storage` was required by the types although the README
62
+ omitted it (README examples did not compile). It is now optional.
63
+ - README examples used non-existent options and events (`baseURL`,
64
+ `includeURLs`, `refresh:success`, plugin `type: 'custom'`); they are now
65
+ type-checked by the test suite.
66
+
67
+ ### Added
68
+
69
+ - Token persistence: the `storage` option (`'memory'` (default),
70
+ `'localStorage'`, `'sessionStorage'`, `'cookie'` or a `StorageAdapter`) was
71
+ accepted but ignored. Tokens are now persisted, restored by
72
+ `createAuthKeeper()` (auto-refresh resumes), removed by `logout()` /
73
+ `clearTokens()` and kept by `destroy()`. Malformed entries are discarded and
74
+ storage failures are reported as `error` events (`context: 'storage'`,
75
+ code `STORAGE_ERROR`). New exports: `WebStorageAdapter`,
76
+ `CookieStorageAdapter`, `resolveStorage` (from `./plugins`).
77
+ - `TokenStoreOptions.validateOnSet` (previously a no-op) rejects access tokens
78
+ that are not structurally valid JWTs; `setTokens()` rejects an empty access
79
+ token with `TOKEN_INVALID`.
80
+ - The cookie and storage helpers advertised in the README are exported:
81
+ `parseCookies`, `getCookie`, `serializeCookie`, `setCookie`, `deleteCookie`,
82
+ `CookieAttributes`, `isStorageAvailable`, `safeGetItem`, `safeSetItem`,
83
+ `safeRemoveItem`.
84
+ - `scripts/check-package.mjs` (`npm run test:package`): installs the packed
85
+ archive and checks every entry point with ESM, CommonJS and TypeScript
86
+ `NodeNext`, plus smoke tests in `tests/package/`.
87
+ - CI workflow (Node 18, 20, 22, 24) and a manual npm Trusted Publishing workflow.
88
+
89
+ ### Changed
90
+
91
+ - Build uses code splitting: `@oxog/authkeeper` and `@oxog/authkeeper/plugins`
92
+ previously each bundled their own copy of every class
93
+ (`TokenStorePlugin` from one entry was not the one from the other).
94
+ - `exports` now has per-condition types (`.d.ts` for `import`, `.d.cts` for
95
+ `require`) and exposes `./package.json`.
96
+ - `TokenStorePlugin.uninstall()` (run by `destroy()`) clears only the
97
+ in-memory tokens and no longer calls `onClear`.
98
+ - `syncTabs`, `LogoutOptions.allTabs` and `Plugin.hooks` are documented as
99
+ reserved (not implemented yet); the `/react`, `/vue`, `/svelte` entry points
100
+ are documented as placeholders.
101
+ - `npm test` runs once (`vitest run`); `typecheck` also checks the tests;
102
+ `lint` covers `src` and `tests` with `--max-warnings=0`; 100% coverage
103
+ thresholds are enforced; `prepublishOnly` runs lint, typecheck, coverage,
104
+ build and the package check.
105
+ - `repository` / `bugs` URLs use the repository's exact name (`AuthKeeper`).
106
+
107
+ ---
108
+
109
+ ## [1.1.0] - 2025-12-28
110
+
111
+ ### ✨ Improvements
112
+
113
+ #### Testing
114
+ - ✅ **100% Code Coverage Achieved!**
115
+ - Statements: 100% (was 99.83%)
116
+ - Branches: 100% (was 99.24%)
117
+ - Functions: 100% (was 100%)
118
+ - Lines: 100% (was 99.83%)
119
+ - ✅ Added Node.js environment tests for base64 utilities
120
+ - ✅ Fixed 6 unhandled promise rejections in refresh-engine tests
121
+ - ✅ Improved test reliability and stability
122
+ - ✅ Total tests: 546 (was 541)
123
+
124
+ #### Documentation
125
+ - 📚 Created comprehensive documentation website
126
+ - Modern React + Vite + TypeScript stack
127
+ - shadcn/ui components with Tailwind CSS
128
+ - Dark/Light theme support
129
+ - JetBrains Mono fonts for code
130
+ - Fully responsive design
131
+ - Pages: Home, Docs, API, Examples, Playground
132
+ - 🚀 Automatic deployment to GitHub Pages
133
+ - GitHub Actions workflow
134
+ - Custom domain: https://authkeeper.oxog.dev
135
+ - Continuous deployment on every commit
136
+
137
+ #### Quality
138
+ - ✅ All tests passing with 100% success rate
139
+ - ✅ Zero unhandled errors in test suite
140
+ - ✅ Improved code reliability
141
+ - ✅ Enhanced browser and Node.js compatibility
142
+
143
+ ### 🔧 Fixed
144
+ - Fixed unhandled promise rejections in async refresh tests
145
+ - Fixed test timing issues with promise error handling
146
+ - Improved error handling in test suites
147
+
148
+ ### 📦 Build
149
+ - Build successful: 36 files, 531.4 kB unpacked
150
+ - Package size: 108.8 kB (gzipped)
151
+ - All TypeScript definitions generated correctly
152
+
153
+ ---
154
+
8
155
  ## [1.0.0] - 2025-12-28
9
156
 
10
157
  ### 🎉 Initial Release
@@ -151,4 +298,5 @@ npm run test:coverage # Run with coverage report
151
298
 
152
299
  **For testing details, see [TESTING.md](TESTING.md)**
153
300
 
301
+ [1.1.0]: https://github.com/ersinkoc/authkeeper/releases/tag/v1.1.0
154
302
  [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,15 @@ 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') and storage failures
225
+ // (event.context === 'storage'); event.error is an AuthError
189
226
  auth.on('error', (event) => {
190
- console.error('Auth error:', event.error)
227
+ console.error('Auth error:', event.error.code, event.error)
191
228
  })
192
229
  ```
193
230
 
@@ -216,6 +253,11 @@ auth.logout()
216
253
  auth.logout({ redirect: '/login' })
217
254
  ```
218
255
 
256
+ ## 🧩 Framework Adapters
257
+
258
+ The `@oxog/authkeeper/react`, `/vue` and `/svelte` entry points are reserved
259
+ placeholders in this release and do not export hooks or stores yet.
260
+
219
261
  ## 🔌 Custom Plugins
220
262
 
221
263
  Create your own plugins to extend functionality:
@@ -226,7 +268,7 @@ import type { Plugin, AuthKeeper } from '@oxog/authkeeper'
226
268
  const myPlugin: Plugin = {
227
269
  name: 'my-plugin',
228
270
  version: '1.0.0',
229
- type: 'custom',
271
+ type: 'optional',
230
272
 
231
273
  install(kernel: AuthKeeper) {
232
274
  // Plugin initialization
@@ -252,30 +294,23 @@ await auth.register(myPlugin)
252
294
  AuthKeeper has comprehensive test coverage:
253
295
 
254
296
  ```bash
255
- # Run tests
297
+ # Run tests once
256
298
  npm test
257
299
 
258
- # Run with coverage
259
- npm test -- --coverage
300
+ # Run with coverage (100% thresholds are enforced)
301
+ npm run test:coverage
260
302
 
261
- # Run in watch mode
262
- npm test -- --watch
303
+ # Watch mode
304
+ npm run test:watch
263
305
 
264
- # Run with UI
265
- npm test -- --ui
266
- ```
306
+ # Lint + typecheck + coverage
307
+ npm run check
267
308
 
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
309
+ # Verify the packed package (ESM, CJS, TypeScript NodeNext)
310
+ npm run test:package
276
311
  ```
277
312
 
278
- See [TESTING.md](TESTING.md) for detailed testing documentation.
313
+ See [docs/testing/TESTING.md](docs/testing/TESTING.md) for detailed testing documentation.
279
314
 
280
315
  ## 📖 API Reference
281
316
 
@@ -343,10 +378,10 @@ interface KernelOptions {
343
378
  // Optional
344
379
  autoRefresh?: boolean // Default: true
345
380
  refreshThreshold?: number // Default: 60 (seconds)
346
- syncTabs?: boolean // Default: true
347
- storage?: StorageAdapter
381
+ storage?: StorageType | StorageAdapter // Default: 'memory'
348
382
  plugins?: Plugin[]
349
- onError?: (error: Error) => void
383
+ onError?: (error: AuthError) => void
384
+ syncTabs?: boolean // Reserved: multi-tab sync is not implemented yet
350
385
  }
351
386
  ```
352
387
 
@@ -364,7 +399,8 @@ src/
364
399
  │ ├── token-decoder.ts # JWT decoding
365
400
  │ ├── refresh-engine.ts # Auto-refresh logic
366
401
  │ ├── fetch-interceptor.ts # HTTP interception
367
- │ └── storage-memory.ts # In-memory storage
402
+ │ ├── storage-memory.ts # In-memory storage
403
+ │ └── storage-web.ts # localStorage / sessionStorage / cookie storage
368
404
  └── utils/
369
405
  ├── base64.ts # Base64URL encoding
370
406
  ├── cookie.ts # Cookie utilities
@@ -393,10 +429,10 @@ MIT © Ersin KOÇ
393
429
  ## 🔗 Links
394
430
 
395
431
  - [Documentation](./docs)
396
- - [Testing Guide](./TESTING.md)
397
- - [Test Report](./TEST_REPORT.md)
432
+ - [Testing Guide](./docs/testing/TESTING.md)
433
+ - [Test Report](./docs/testing/TEST_REPORT.md)
398
434
  - [Changelog](./CHANGELOG.md)
399
- - [Issues](https://github.com/oxog/authkeeper/issues)
435
+ - [Issues](https://github.com/ersinkoc/AuthKeeper/issues)
400
436
 
401
437
  ## 💡 Inspiration
402
438