@eventuras/fides-auth 0.3.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.
Files changed (46) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +311 -0
  3. package/dist/build-CNL3v39v.js +977 -0
  4. package/dist/decode_jwt-1J26fl4I.js +25 -0
  5. package/dist/decrypt-Cahlu_6Y.js +92 -0
  6. package/dist/deflate-koSuX7FB.js +1015 -0
  7. package/dist/index.d.ts +11 -0
  8. package/dist/index.d.ts.map +1 -0
  9. package/dist/index.js +6 -0
  10. package/dist/logger.d.ts +83 -0
  11. package/dist/logger.d.ts.map +1 -0
  12. package/dist/logger.js +46 -0
  13. package/dist/oauth-browser.d.ts +62 -0
  14. package/dist/oauth-browser.d.ts.map +1 -0
  15. package/dist/oauth-browser.js +49 -0
  16. package/dist/oauth.d.ts +145 -0
  17. package/dist/oauth.d.ts.map +1 -0
  18. package/dist/oauth.js +165 -0
  19. package/dist/providers/vipps/client.d.ts +62 -0
  20. package/dist/providers/vipps/client.d.ts.map +1 -0
  21. package/dist/providers/vipps/index.d.ts +11 -0
  22. package/dist/providers/vipps/index.d.ts.map +1 -0
  23. package/dist/providers/vipps/index.js +120 -0
  24. package/dist/providers/vipps/types.d.ts +107 -0
  25. package/dist/providers/vipps/types.d.ts.map +1 -0
  26. package/dist/rate-limit.d.ts +28 -0
  27. package/dist/rate-limit.d.ts.map +1 -0
  28. package/dist/rate-limit.js +26 -0
  29. package/dist/session-refresh.d.ts +13 -0
  30. package/dist/session-refresh.d.ts.map +1 -0
  31. package/dist/session-refresh.js +27 -0
  32. package/dist/session-validation-BxObT3wC.js +66 -0
  33. package/dist/session-validation.d.ts +24 -0
  34. package/dist/session-validation.d.ts.map +1 -0
  35. package/dist/session-validation.js +2 -0
  36. package/dist/silent-login.d.ts +103 -0
  37. package/dist/silent-login.d.ts.map +1 -0
  38. package/dist/silent-login.js +50 -0
  39. package/dist/types.d.ts +24 -0
  40. package/dist/types.d.ts.map +1 -0
  41. package/dist/types.js +0 -0
  42. package/dist/utils-ByMRF7b2.js +379 -0
  43. package/dist/utils.d.ts +83 -0
  44. package/dist/utils.d.ts.map +1 -0
  45. package/dist/utils.js +2 -0
  46. package/package.json +101 -0
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 losol
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,311 @@
1
+ # @eventuras/fides-auth
2
+
3
+ Framework-agnostic OAuth 2.0 / OpenID Connect library with PKCE, encrypted sessions, rate limiting, and pluggable logging.
4
+
5
+ ## Features
6
+
7
+ - **OAuth 2.0 + OIDC** — Authorization Code with PKCE, token refresh, client credentials
8
+ - **Dual environment** — Node.js (`openid-client`) and browser (Web Crypto) entry points
9
+ - **Encrypted sessions** — AES-256-GCM encrypted JWTs for secure session storage
10
+ - **Rate limiting** — Generic token-bucket algorithm, ready for login protection
11
+ - **Silent login** — Detect `prompt=none` results without user interaction
12
+ - **Pluggable logging** — Bring your own logger (pino, winston, etc.) or use the built-in console logger
13
+ - **Tree-shakeable** — Each module is a separate entry point; import only what you need
14
+ - **TypeScript-first** — Full type safety with exported interfaces
15
+ - **Identity providers** — Includes a Vipps Login provider; designed to support additional providers
16
+
17
+ ## Installation
18
+
19
+ ```bash
20
+ npm install @eventuras/fides-auth
21
+ # or
22
+ pnpm add @eventuras/fides-auth
23
+ # or
24
+ yarn add @eventuras/fides-auth
25
+ ```
26
+
27
+ **Requirements:** Node.js ≥ 18 (uses Web Crypto API)
28
+
29
+ ## Quick Start
30
+
31
+ ### Node.js — OAuth with PKCE
32
+
33
+ ```typescript
34
+ import {
35
+ buildPKCEOptions,
36
+ buildAuthorizationUrl,
37
+ exchangeAuthorizationCode,
38
+ } from "@eventuras/fides-auth/oauth";
39
+ import { validateSessionJwt, createEncryptedJWT } from "@eventuras/fides-auth";
40
+
41
+ const oauthConfig = {
42
+ issuer: "https://auth.example.com",
43
+ clientId: "your-client-id",
44
+ clientSecret: "your-client-secret",
45
+ redirect_uri: "https://app.example.com/callback",
46
+ scope: "openid profile email offline_access",
47
+ };
48
+
49
+ // 1. Start login — redirect user to auth URL
50
+ const pkce = await buildPKCEOptions(oauthConfig);
51
+ const authUrl = await buildAuthorizationUrl(oauthConfig, pkce);
52
+
53
+ // 2. Handle callback — exchange code for tokens
54
+ const tokens = await exchangeAuthorizationCode(
55
+ oauthConfig,
56
+ callbackUrl,
57
+ pkce.code_verifier,
58
+ pkce.state,
59
+ );
60
+
61
+ // 3. Create encrypted session
62
+ const secret = "0123456789abcdef..."; // 64 hex chars (32 bytes)
63
+ const jwt = await createEncryptedJWT({ user, tokens }, secret);
64
+
65
+ // 4. Validate session later
66
+ const { status, session } = await validateSessionJwt(jwt, secret);
67
+ ```
68
+
69
+ ### Browser — OAuth SPA Flow
70
+
71
+ ```typescript
72
+ import {
73
+ generatePKCE,
74
+ buildAuthorizationUrl,
75
+ exchangeCodeForTokens,
76
+ } from "@eventuras/fides-auth/oauth-browser";
77
+
78
+ const config = {
79
+ issuer: "https://auth.example.com",
80
+ clientId: "my-client-id",
81
+ redirect_uri: "https://myapp.com/callback",
82
+ scope: "openid profile email",
83
+ };
84
+
85
+ // Start flow
86
+ const pkce = await generatePKCE();
87
+ sessionStorage.setItem("code_verifier", pkce.code_verifier);
88
+ sessionStorage.setItem("state", pkce.state);
89
+ window.location.href = buildAuthorizationUrl(config, pkce);
90
+
91
+ // Handle callback
92
+ const code = new URLSearchParams(location.search).get("code");
93
+ const tokens = await exchangeCodeForTokens(
94
+ config,
95
+ code,
96
+ sessionStorage.getItem("code_verifier")!,
97
+ );
98
+ ```
99
+
100
+ ## Modules
101
+
102
+ Each module is available as a separate entry point for tree-shaking:
103
+
104
+ | Entry Point | Environment | Description |
105
+ | ------------------------------------------ | ----------- | ----------------------------------------------------- |
106
+ | `@eventuras/fides-auth` | Node.js | Main entry — re-exports utils, session, types, logger |
107
+ | `@eventuras/fides-auth/oauth` | Node.js | OAuth/OIDC flows with `openid-client` |
108
+ | `@eventuras/fides-auth/oauth-browser` | Browser | OAuth/OIDC flows with Web Crypto API |
109
+ | `@eventuras/fides-auth/session-validation` | Node.js | Encrypted JWT session validation |
110
+ | `@eventuras/fides-auth/session-refresh` | Node.js | Automatic token refresh for sessions |
111
+ | `@eventuras/fides-auth/silent-login` | Node.js | Silent login (`prompt=none`) utilities |
112
+ | `@eventuras/fides-auth/utils` | Universal | Crypto helpers, hashing, token generation |
113
+ | `@eventuras/fides-auth/rate-limit` | Universal | Token-bucket rate limiter |
114
+ | `@eventuras/fides-auth/logger` | Universal | Pluggable logger interface and configuration |
115
+ | `@eventuras/fides-auth/types` | Universal | TypeScript types (Session, Tokens, etc.) |
116
+ | `@eventuras/fides-auth/providers/vipps` | Node.js | Vipps Login identity provider |
117
+
118
+ ### OAuth — Node.js (`/oauth`)
119
+
120
+ Full OIDC flows using `openid-client`:
121
+
122
+ ```typescript
123
+ import {
124
+ buildPKCEOptions,
125
+ buildAuthorizationUrl,
126
+ exchangeAuthorizationCode,
127
+ refreshAccessToken,
128
+ extractUserFromTokens,
129
+ buildSessionFromTokens,
130
+ validateReturnUrl,
131
+ buildOidcLogoutUrl,
132
+ clientCredentialsGrant,
133
+ } from "@eventuras/fides-auth/oauth";
134
+ ```
135
+
136
+ ### OAuth — Browser (`/oauth-browser`)
137
+
138
+ Lightweight browser-only flows using Web Crypto:
139
+
140
+ ```typescript
141
+ import {
142
+ generatePKCE,
143
+ buildAuthorizationUrl,
144
+ exchangeCodeForTokens,
145
+ } from "@eventuras/fides-auth/oauth-browser";
146
+ ```
147
+
148
+ ### Session Management
149
+
150
+ ```typescript
151
+ import { createEncryptedJWT, validateSessionJwt } from "@eventuras/fides-auth";
152
+ import { refreshSession } from "@eventuras/fides-auth/session-refresh";
153
+
154
+ // Secrets accept hex strings or Uint8Array
155
+ const secret = process.env.SESSION_SECRET!; // 64 hex chars = 32 bytes
156
+
157
+ // Create session JWT (AES-256-GCM encrypted)
158
+ const jwt = await createEncryptedJWT(sessionData, secret);
159
+
160
+ // Validate and decrypt
161
+ const { status, session } = await validateSessionJwt(jwt, secret);
162
+ if (status === "VALID") {
163
+ // session is typed as Session
164
+ }
165
+
166
+ // Refresh expired tokens
167
+ const refreshed = await refreshSession(session, oauthConfig);
168
+ ```
169
+
170
+ ### Crypto Utilities (`/utils`)
171
+
172
+ Standalone cryptographic helpers using Web Crypto API:
173
+
174
+ ```typescript
175
+ import {
176
+ encrypt,
177
+ decrypt,
178
+ sha256,
179
+ sha512,
180
+ generateToken,
181
+ toHex,
182
+ hexToUint8Array,
183
+ } from "@eventuras/fides-auth/utils";
184
+
185
+ // AES-256-GCM encryption
186
+ const secret = "0123456789abcdef".repeat(4); // 64 hex chars
187
+ const encrypted = await encrypt("sensitive data", secret);
188
+ const decrypted = await decrypt(encrypted, secret);
189
+
190
+ // Hashing
191
+ const hash = await sha256("hello world");
192
+
193
+ // Random token generation
194
+ const token = generateToken(32); // 64 hex char token
195
+
196
+ // Hex conversions
197
+ const bytes = hexToUint8Array("deadbeef");
198
+ const hex = toHex(new Uint8Array([0xde, 0xad]));
199
+ ```
200
+
201
+ ### Rate Limiting (`/rate-limit`)
202
+
203
+ Generic token-bucket rate limiter:
204
+
205
+ ```typescript
206
+ import { TokenBucket } from "@eventuras/fides-auth/rate-limit";
207
+
208
+ // 5 attempts per 60 seconds per IP
209
+ const loginLimiter = new TokenBucket<string>(5, 60);
210
+
211
+ function handleLogin(ip: string) {
212
+ if (!loginLimiter.consume(ip, 1)) {
213
+ throw new Error("Too many login attempts");
214
+ }
215
+ // proceed with login
216
+ }
217
+ ```
218
+
219
+ ### Silent Login (`/silent-login`)
220
+
221
+ Detect whether a user has an active session without showing UI:
222
+
223
+ ```typescript
224
+ import {
225
+ buildSilentLoginUrl,
226
+ checkSilentLoginResult,
227
+ requiresInteractiveLogin,
228
+ SilentLoginErrors,
229
+ } from "@eventuras/fides-auth/silent-login";
230
+ ```
231
+
232
+ ### Pluggable Logging (`/logger`)
233
+
234
+ The library uses console logging by default. Plug in your preferred logger at startup:
235
+
236
+ ```typescript
237
+ import { configureLogger } from "@eventuras/fides-auth/logger";
238
+
239
+ // Example: plug in pino
240
+ import pino from "pino";
241
+ const pinoInstance = pino();
242
+
243
+ configureLogger({
244
+ create({ namespace, context }) {
245
+ return pinoInstance.child({ namespace, ...context });
246
+ },
247
+ });
248
+ ```
249
+
250
+ Any object implementing `{ debug, info, warn, error }` works — pino, winston, bunyan, or your own.
251
+
252
+ ### Vipps Login Provider (`/providers/vipps`)
253
+
254
+ ```typescript
255
+ import {
256
+ VippsLoginClient,
257
+ VippsEnvironments,
258
+ VippsLoginScopes,
259
+ } from "@eventuras/fides-auth/providers/vipps";
260
+
261
+ const client = new VippsLoginClient({
262
+ clientId: "your-client-id",
263
+ clientSecret: "your-client-secret",
264
+ redirectUri: "https://app.example.com/callback",
265
+ subscriptionKey: "your-subscription-key",
266
+ issuer: VippsEnvironments.Production,
267
+ scope: [
268
+ VippsLoginScopes.OpenId,
269
+ VippsLoginScopes.Email,
270
+ VippsLoginScopes.Name,
271
+ ].join(" "),
272
+ });
273
+
274
+ const pkce = await client.buildPKCEOptions();
275
+ const authUrl = await client.buildAuthorizationUrl(pkce);
276
+ // redirect user → callback → exchange code → getUserInfo
277
+ ```
278
+
279
+ ## Security
280
+
281
+ - **PKCE** — All OAuth flows use Proof Key for Code Exchange
282
+ - **AES-256-GCM** — Sessions encrypted with authenticated encryption
283
+ - **Open redirect protection** — `validateReturnUrl` prevents redirect attacks
284
+ - **No secret logging** — Tokens, keys, and PII are never logged
285
+ - **Web Crypto API** — Uses the platform cryptographic primitives (not userland crypto)
286
+
287
+ ## TypeScript
288
+
289
+ All types are exported from `@eventuras/fides-auth/types`:
290
+
291
+ ```typescript
292
+ import type {
293
+ Session,
294
+ Tokens,
295
+ CreateSessionOptions,
296
+ } from "@eventuras/fides-auth/types";
297
+ import type {
298
+ OAuthConfig,
299
+ OidcUserInfo,
300
+ PKCEOptions,
301
+ } from "@eventuras/fides-auth/oauth";
302
+ import type {
303
+ FidesLogger,
304
+ FidesLoggerFactory,
305
+ FidesLoggerOptions,
306
+ } from "@eventuras/fides-auth/logger";
307
+ ```
308
+
309
+ ## License
310
+
311
+ [MIT](./LICENSE)