authenik8-core 2.0.3 → 2.0.6

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 (190) hide show
  1. package/CHANGELOG.md +86 -0
  2. package/README.md +40 -350
  3. package/THREAT_MODEL.md +162 -0
  4. package/dist/agent/agentIdentity.d.ts +13 -1
  5. package/dist/agent/agentIdentity.d.ts.map +1 -1
  6. package/dist/agent/agentIdentity.js +203 -51
  7. package/dist/agent/agentIdentity.js.map +1 -1
  8. package/dist/audit/auditDispatcher.d.ts +13 -0
  9. package/dist/audit/auditDispatcher.d.ts.map +1 -0
  10. package/dist/audit/auditDispatcher.js +212 -0
  11. package/dist/audit/auditDispatcher.js.map +1 -0
  12. package/dist/audit/types.d.ts +40 -0
  13. package/dist/audit/types.d.ts.map +1 -0
  14. package/dist/{types/storage.js → audit/types.js} +1 -1
  15. package/dist/audit/types.js.map +1 -0
  16. package/dist/auth/guestModeService.d.ts +3 -5
  17. package/dist/auth/guestModeService.d.ts.map +1 -1
  18. package/dist/auth/guestModeService.js +15 -14
  19. package/dist/auth/guestModeService.js.map +1 -1
  20. package/dist/auth/jwk.d.ts +4 -1
  21. package/dist/auth/jwk.d.ts.map +1 -1
  22. package/dist/auth/jwk.js +181 -41
  23. package/dist/auth/jwk.js.map +1 -1
  24. package/dist/auth/jwtAuth.d.ts +17 -1
  25. package/dist/auth/jwtAuth.d.ts.map +1 -1
  26. package/dist/auth/jwtAuth.js +191 -27
  27. package/dist/auth/jwtAuth.js.map +1 -1
  28. package/dist/auth/refreshService.d.ts +12 -1
  29. package/dist/auth/refreshService.d.ts.map +1 -1
  30. package/dist/auth/refreshService.js +199 -48
  31. package/dist/auth/refreshService.js.map +1 -1
  32. package/dist/auth/requestIdentity.d.ts +4 -0
  33. package/dist/auth/requestIdentity.d.ts.map +1 -0
  34. package/dist/auth/requestIdentity.js +16 -0
  35. package/dist/auth/requestIdentity.js.map +1 -0
  36. package/dist/auth/sessionStore.d.ts +5 -1
  37. package/dist/auth/sessionStore.d.ts.map +1 -1
  38. package/dist/auth/sessionStore.js +103 -16
  39. package/dist/auth/sessionStore.js.map +1 -1
  40. package/dist/auth/tokenFingerprint.d.ts +3 -0
  41. package/dist/auth/tokenFingerprint.d.ts.map +1 -0
  42. package/dist/auth/tokenFingerprint.js +13 -0
  43. package/dist/auth/tokenFingerprint.js.map +1 -0
  44. package/dist/authorization/authorizationService.d.ts +22 -0
  45. package/dist/authorization/authorizationService.d.ts.map +1 -0
  46. package/dist/authorization/authorizationService.js +132 -0
  47. package/dist/authorization/authorizationService.js.map +1 -0
  48. package/dist/authorization/types.d.ts +10 -0
  49. package/dist/authorization/types.d.ts.map +1 -0
  50. package/dist/authorization/types.js +3 -0
  51. package/dist/authorization/types.js.map +1 -0
  52. package/dist/createAuthenik8.d.ts.map +1 -1
  53. package/dist/createAuthenik8.js +87 -18
  54. package/dist/createAuthenik8.js.map +1 -1
  55. package/dist/index.d.ts +16 -1
  56. package/dist/index.d.ts.map +1 -1
  57. package/dist/index.js +10 -1
  58. package/dist/index.js.map +1 -1
  59. package/dist/middleware/adminService.d.ts +3 -5
  60. package/dist/middleware/adminService.d.ts.map +1 -1
  61. package/dist/middleware/adminService.js +18 -19
  62. package/dist/middleware/adminService.js.map +1 -1
  63. package/dist/oauth/adapters/memoryAdapter.d.ts.map +1 -1
  64. package/dist/oauth/adapters/memoryAdapter.js +47 -17
  65. package/dist/oauth/adapters/memoryAdapter.js.map +1 -1
  66. package/dist/oauth/adapters/redisAdapter.d.ts +1 -1
  67. package/dist/oauth/adapters/redisAdapter.d.ts.map +1 -1
  68. package/dist/oauth/adapters/redisAdapter.js +163 -84
  69. package/dist/oauth/adapters/redisAdapter.js.map +1 -1
  70. package/dist/oauth/brain/identityEngine.d.ts +13 -14
  71. package/dist/oauth/brain/identityEngine.d.ts.map +1 -1
  72. package/dist/oauth/brain/identityEngine.js +162 -68
  73. package/dist/oauth/brain/identityEngine.js.map +1 -1
  74. package/dist/oauth/brain/identityPolicy.d.ts +7 -4
  75. package/dist/oauth/brain/identityPolicy.d.ts.map +1 -1
  76. package/dist/oauth/brain/identityPolicy.js +15 -2
  77. package/dist/oauth/brain/identityPolicy.js.map +1 -1
  78. package/dist/oauth/core.d.ts +8 -4
  79. package/dist/oauth/core.d.ts.map +1 -1
  80. package/dist/oauth/core.js +59 -16
  81. package/dist/oauth/core.js.map +1 -1
  82. package/dist/oauth/identityValidation.d.ts +14 -0
  83. package/dist/oauth/identityValidation.d.ts.map +1 -0
  84. package/dist/oauth/identityValidation.js +90 -0
  85. package/dist/oauth/identityValidation.js.map +1 -0
  86. package/dist/oauth/providerSecurity.d.ts +13 -0
  87. package/dist/oauth/providerSecurity.d.ts.map +1 -0
  88. package/dist/oauth/providerSecurity.js +100 -0
  89. package/dist/oauth/providerSecurity.js.map +1 -0
  90. package/dist/oauth/providers/github.d.ts +2 -1
  91. package/dist/oauth/providers/github.d.ts.map +1 -1
  92. package/dist/oauth/providers/github.js +97 -20
  93. package/dist/oauth/providers/github.js.map +1 -1
  94. package/dist/oauth/providers/google.d.ts +3 -2
  95. package/dist/oauth/providers/google.d.ts.map +1 -1
  96. package/dist/oauth/providers/google.js +81 -24
  97. package/dist/oauth/providers/google.js.map +1 -1
  98. package/dist/oauth/state.d.ts +9 -0
  99. package/dist/oauth/state.d.ts.map +1 -0
  100. package/dist/oauth/state.js +55 -0
  101. package/dist/oauth/state.js.map +1 -0
  102. package/dist/oauth/types.d.ts +48 -23
  103. package/dist/oauth/types.d.ts.map +1 -1
  104. package/dist/oauth/types.js +0 -1
  105. package/dist/oauth/types.js.map +1 -1
  106. package/dist/redis/keyNamespace.d.ts +4 -0
  107. package/dist/redis/keyNamespace.d.ts.map +1 -0
  108. package/dist/redis/keyNamespace.js +34 -0
  109. package/dist/redis/keyNamespace.js.map +1 -0
  110. package/dist/redis/redisService.d.ts.map +1 -1
  111. package/dist/redis/redisService.js +17 -2
  112. package/dist/redis/redisService.js.map +1 -1
  113. package/dist/risk/redisSessionRiskStore.d.ts +13 -0
  114. package/dist/risk/redisSessionRiskStore.d.ts.map +1 -0
  115. package/dist/risk/redisSessionRiskStore.js +29 -0
  116. package/dist/risk/redisSessionRiskStore.js.map +1 -0
  117. package/dist/risk/sessionRiskService.d.ts +31 -0
  118. package/dist/risk/sessionRiskService.d.ts.map +1 -0
  119. package/dist/risk/sessionRiskService.js +311 -0
  120. package/dist/risk/sessionRiskService.js.map +1 -0
  121. package/dist/risk/types.d.ts +50 -0
  122. package/dist/risk/types.d.ts.map +1 -0
  123. package/dist/risk/types.js +3 -0
  124. package/dist/risk/types.js.map +1 -0
  125. package/dist/security/ipService.d.ts +27 -12
  126. package/dist/security/ipService.d.ts.map +1 -1
  127. package/dist/security/ipService.js +238 -80
  128. package/dist/security/ipService.js.map +1 -1
  129. package/dist/security/limiter.d.ts +7 -5
  130. package/dist/security/limiter.d.ts.map +1 -1
  131. package/dist/security/limiter.js +70 -29
  132. package/dist/security/limiter.js.map +1 -1
  133. package/dist/security/requestContext.d.ts +15 -0
  134. package/dist/security/requestContext.d.ts.map +1 -0
  135. package/dist/security/requestContext.js +156 -0
  136. package/dist/security/requestContext.js.map +1 -0
  137. package/dist/storage/RedisTokenStore.d.ts +2 -2
  138. package/dist/storage/RedisTokenStore.d.ts.map +1 -1
  139. package/dist/storage/RedisTokenStore.js +10 -2
  140. package/dist/storage/RedisTokenStore.js.map +1 -1
  141. package/dist/types/config.d.ts +41 -3
  142. package/dist/types/config.d.ts.map +1 -1
  143. package/dist/types/public.d.ts +39 -18
  144. package/dist/types/public.d.ts.map +1 -1
  145. package/dist/types/tokens.d.ts +7 -1
  146. package/dist/types/tokens.d.ts.map +1 -1
  147. package/dist/utility/safeString.d.ts +2 -0
  148. package/dist/utility/safeString.d.ts.map +1 -0
  149. package/dist/utility/safeString.js +13 -0
  150. package/dist/utility/safeString.js.map +1 -0
  151. package/docs/agent-service-identity.md +69 -0
  152. package/docs/api-overview.md +56 -0
  153. package/docs/architecture.md +41 -0
  154. package/docs/authorization-tenants-audit.md +53 -0
  155. package/docs/final-thought.md +9 -0
  156. package/docs/getting-started.md +57 -0
  157. package/docs/how-it-works-internally.md +15 -0
  158. package/docs/key-rotation.md +13 -0
  159. package/docs/refresh-token-rotation.md +15 -0
  160. package/docs/replay-attack-detection.md +16 -0
  161. package/docs/replay-attack-prevention.md +15 -0
  162. package/docs/repository-setup.md +13 -0
  163. package/docs/requirements.md +31 -0
  164. package/docs/secure-refresh-flow.md +21 -0
  165. package/docs/security-audit.md +133 -0
  166. package/docs/security-layer.md +54 -0
  167. package/docs/session-risk-quarantine.md +36 -0
  168. package/docs/stateful-session-control.md +16 -0
  169. package/docs/testing.md +37 -0
  170. package/docs/threats-addressed.md +25 -0
  171. package/docs/use-cases.md +12 -0
  172. package/docs/what-authenik8-does.md +17 -0
  173. package/docs/why-authenik8.md +15 -0
  174. package/docs/why-stateful-matters.md +11 -0
  175. package/package.json +16 -6
  176. package/dist/oauth/brain/identityResolver.d.ts +0 -7
  177. package/dist/oauth/brain/identityResolver.d.ts.map +0 -1
  178. package/dist/oauth/brain/identityResolver.js +0 -32
  179. package/dist/oauth/brain/identityResolver.js.map +0 -1
  180. package/dist/oauth/userStore.d.ts +0 -11
  181. package/dist/oauth/userStore.d.ts.map +0 -1
  182. package/dist/oauth/userStore.js +0 -46
  183. package/dist/oauth/userStore.js.map +0 -1
  184. package/dist/storage/userStorage.d.ts +0 -8
  185. package/dist/storage/userStorage.d.ts.map +0 -1
  186. package/dist/storage/userStorage.js +0 -28
  187. package/dist/storage/userStorage.js.map +0 -1
  188. package/dist/types/storage.d.ts +0 -14
  189. package/dist/types/storage.d.ts.map +0 -1
  190. package/dist/types/storage.js.map +0 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,91 @@
1
1
  # Changelog
2
2
 
3
+ ## Unreleased
4
+
5
+ ### Added
6
+ - Human `requireRole()`, `requirePermission()`, `requireScope()`, and tenant-aware authorization middleware.
7
+ - Versioned structured audit events with application-owned sinks and configurable best-effort or strict delivery.
8
+ - Stateful session-risk signals for refresh replay, concurrent refresh use, IP/device changes, and suspicious agent activity.
9
+ - Automatic, TTL-bound human and agent session quarantine with an explicit release API.
10
+ - Stable, configurable Redis key namespaces derived from issuer and audience by
11
+ default.
12
+ - Explicit trusted-proxy CIDRs and right-to-left forwarding-chain validation.
13
+ - Configurable enforcing Helmet policy through `security.helmetOptions`.
14
+
15
+ ### Changed
16
+ - Reorganized the root README into a concise entry point with each detailed topic in a dedicated document under `docs/`.
17
+ - HMAC secrets now require 32-4096 bytes of material. Access, refresh, and agent
18
+ token lifetimes have explicit upper bounds.
19
+ - OAuth state stores must implement atomic `take()`, and identity adapters now
20
+ return explicit creation outcomes and resolve users by ID.
21
+ - IP allowlist entries are canonicalized, loopback requires an explicit entry,
22
+ and exact/CIDR expiry cleanup is enforced without N+1 Redis checks.
23
+ - SDK modules no longer call `dotenv.config()` at import time; environment
24
+ loading belongs to the host application.
25
+ - Removed obsolete deep-import in-memory identity/password stores and their
26
+ duplicate resolver; the hardened identity adapter is now the single OAuth
27
+ account-resolution path.
28
+ - Removed stateless `jwtSecret` fallbacks from internal admin and incognito
29
+ helpers. The instance always supplies purpose-bound, session-aware
30
+ verification functions.
31
+ - CI remains Redis-service-free and exercises Redis behavior with
32
+ `ioredis-mock`.
33
+ - Package exports are restricted to the reviewed root API; public identity,
34
+ token, session, and refresh types are exported from that entry point.
35
+
36
+ ### Security
37
+ - `incognito` now enforces active Redis session and quarantine state for authenticated users.
38
+ - Access and refresh bearer tokens are represented by SHA-256 fingerprints in Redis, with read migration support for existing raw records.
39
+ - Legacy HS256 verification now enforces issuer and audience.
40
+ - Token issuance and rotation roll back session state when a dependent security operation fails.
41
+ - OAuth state is consumed before token exchange and Redis uses atomic `GETDEL` where available.
42
+ - Closed an OAuth identity-create race that could issue tokens for an existing
43
+ same-email account.
44
+ - Closed a link-mode account-confusion path that could return the existing
45
+ provider owner's login instead of rejecting the link.
46
+ - OAuth state fallback consumption now uses an atomic Lua transaction; the
47
+ nonatomic `get()`/`del()` fallback was removed.
48
+ - Redis OAuth identity creation and linking now use atomic, cluster-slot-safe
49
+ transactions with post-link verification.
50
+ - Forwarding headers cannot affect allowlist, rate-limit, or risk context unless
51
+ the socket peer belongs to an explicit trusted proxy network.
52
+ - Audit metadata is detached, bounded, recursively cloned, and deeply frozen,
53
+ preventing a sink from mutating authorization requirements.
54
+ - Default CSP is enforcing and removes `unsafe-inline`, report-only behavior,
55
+ and placeholder domains.
56
+ - OTP rate limiting uses bounded, hashed identifiers and both IP and normalized
57
+ email buckets.
58
+ - Dependency lockfile updated to patched versions; `npm audit
59
+ --package-lock-only --audit-level=low` reports zero vulnerabilities.
60
+ - Refresh and lock keys use collision-resistant compound identifiers, and
61
+ refresh-family deletion uses bounded batches.
62
+ - OAuth provider JSON is bounded while streaming; state, identity records,
63
+ provider counts, and adapter index integrity are validated before token
64
+ issuance.
65
+ - Stored session/risk records and audit envelopes receive strict runtime
66
+ validation. Authorization claims are bounded at issuance and verification.
67
+ - Identity, delegation, and registry policy decisions require exact boolean
68
+ values instead of truthy coercion.
69
+ - Published JWKS fields use a public allowlist, local verification rejects
70
+ private/oversized key sets, and remote JWKS URLs require credential-free
71
+ HTTPS.
72
+
73
+ ### Upgrade notes
74
+
75
+ - Existing Redis sessions use earlier key names and will be treated as logged
76
+ out unless they are deliberately migrated. Set `redisKeyPrefix` explicitly
77
+ before rollout when coordinating a migration.
78
+ - Tokens without an exact `tokenUse` claim are rejected.
79
+ - `trustProxyHeaders: true` without `trustedProxyCidrs` now fails startup.
80
+ - Google link routes must pass `"link"` explicitly to `redirect()`; route-path
81
+ substring inference was removed.
82
+ - Numeric token lifetimes are relative seconds. Access tokens are limited to one
83
+ day, refresh tokens to 31 days, and agent tokens to one hour.
84
+ - Internal package deep imports are no longer supported. Import runtime APIs and
85
+ public types from `authenik8-core`.
86
+ - Refresh and lock Redis key shapes changed; existing refresh credentials are
87
+ intentionally invalidated during this security upgrade.
88
+
3
89
  ## [2.0.0] - 2026-07-15
4
90
  ### Added
5
91
  - JOSE-based ES256 signing with explicit `kid`, issuer, audience, expiry, and token-purpose validation.
package/README.md CHANGED
@@ -1,372 +1,62 @@
1
1
  <div align="center">
2
2
 
3
- <img src="./logo.svg" alt="Authenik8" width="180" />
3
+ ![Authenik8-core logo](https://raw.githubusercontent.com/COD434/authenik8-core-Beta-/main/logo.svg)
4
4
 
5
5
  # Authenik8-core [Beta]
6
6
 
7
-
8
-
9
-
10
7
  [![Pipeline status](https://gitlab.com/COD434/authenik8-core/badges/main/pipeline.svg)](https://gitlab.com/COD434/authenik8-core/-/pipelines)
11
8
  [![Coverage](https://gitlab.com/COD434/authenik8-core/badges/main/coverage.svg)](https://gitlab.com/COD434/authenik8-core/-/pipelines)
12
9
  [![NPM Version](https://img.shields.io/npm/v/authenik8-core.svg)](https://www.npmjs.com/package/authenik8-core)
13
- </div>
14
- Most JWT authentication systems break under real-world attacks.
15
- Authenik8-core is built to handle them.
16
-
17
- ***
18
- ## What Authenik8-core Does
19
- Authenik8-core adds a security layer on top of JWT:
20
-
21
- •Refresh token rotation with replay protection (jti-based)
22
-
23
- •Stateful session control using Redis
24
-
25
- •Built-in security middleware (rate limiting, IP control)
26
-
27
- •Unified authentication + security logic
28
-
29
- •Scoped identities for AI agents, workers, bots, and M2M callers
30
-
31
- ## Example: Replay Attack Prevention
32
- ```
33
- TypeScript
34
- // First request → valid
35
- await auth.refreshToken(token);
36
-
37
- // Reusing same token → blocked
38
- await auth.refreshToken(token); // rejected
39
- ```
40
- ***
41
-
42
- ## Getting started
43
-
44
- Generate and persist an ES256 private JWK once. Do not generate a new key every time the process starts.
45
-
46
- ```ts
47
- import {
48
- createAuthenik8,
49
- generateSigningJwk,
50
- verifyAccessTokenWithJwks,
51
- } from "authenik8-core";
52
-
53
- const privateJwk = await generateSigningJwk("2026-07-primary");
54
- // Store privateJwk in your secret manager before constructing the engine.
55
-
56
- const auth = await createAuthenik8({
57
- jwt: {
58
- keys: [privateJwk],
59
- activeKid: "2026-07-primary",
60
- issuer: "https://api.example.com",
61
- audience: "example-api",
62
- },
63
- refreshSecret: process.env.REFRESH_SECRET!,
64
- });
65
-
66
- app.get("/.well-known/jwks.json", (_req, res) => res.json(auth.getJwks()));
67
- app.get("/protected", auth.requireAuth, (_req, res) => res.sendStatus(204));
68
-
69
- const tokens = await auth.issueTokens({
70
- userId: "user_1",
71
- email: "test@example.com",
72
- });
73
- const payload = await auth.verifyToken(tokens.accessToken);
74
-
75
- // A separate service can verify with public keys only (or pass a JWKS URL).
76
- const publicPayload = await verifyAccessTokenWithJwks(
77
- tokens.accessToken,
78
- auth.getJwks(),
79
- { issuer: "https://api.example.com", audience: "example-api" },
80
- );
81
- ```
82
-
83
- `jwtSecret` remains available as a deprecated JOSE/HS256 migration path. It does not provide a public JWKS and should not be used for new applications.
84
-
85
- ## Key rotation
86
-
87
- 1. Generate and securely persist a new key with a unique `kid`.
88
- 2. Put the new private JWK and previous verification keys in `jwt.keys`.
89
- 3. Set `activeKid` to the new key. New tokens now carry the new `kid`.
90
- 4. Keep old public keys until every token they signed has expired, then remove them.
91
-
92
- `auth.getJwks()` strips private key material and returns every configured public verification key. Verification enforces ES256, `kid`, issuer, audience, expiry, and token purpose.
93
-
94
- ## Agent and service identity
95
-
96
- Agent identity is optional and fails closed. The application supplies the source
97
- of truth for registered agents and their maximum scopes:
98
-
99
- ```ts
100
- const auth = await createAuthenik8({
101
- jwt,
102
- refreshSecret,
103
- redis,
104
- agent: {
105
- resolveAgent: async (agentId) => agentRepository.findActive(agentId),
106
- authorizeDelegation: async ({ user, agent, requestedScopes }) =>
107
- user.role === "admin" &&
108
- agent.agentId === "build-worker" &&
109
- requestedScopes.every((scope) => scope === "tasks:read"),
110
- },
111
- });
112
- ```
113
-
114
- Mint M2M tokens only after a trusted workload-authentication exchange such as
115
- mTLS, cloud workload identity, or a signed client assertion:
116
-
117
- ```ts
118
- const machine = await auth.agent!.issueToken({
119
- agentId: "build-worker",
120
- scopes: ["tasks:read"],
121
- label: "production queue worker",
122
- });
123
-
124
- app.post(
125
- "/internal/tasks",
126
- auth.agent!.requireScopes("tasks:write"),
127
- handler,
128
- );
129
- ```
130
-
131
- `issueToken()` is a privileged SDK primitive and must not be exposed as an
132
- unauthenticated HTTP endpoint. Agent tokens use a distinct `tokenUse`, carry an
133
- exact scope set and `actorChain`, and are stored under
134
- `agent-sessions:<agentId>`. Human middleware rejects agent tokens.
135
-
136
- Delegated tokens require an active human access-token session and an explicit
137
- `authorizeDelegation` decision:
138
-
139
- ```ts
140
- const delegated = await auth.agent!.issueDelegatedToken({
141
- agentId: "build-worker",
142
- userAccessToken,
143
- scopes: ["tasks:read"],
144
- });
145
- ```
146
-
147
- They identify the human subject and agent actor through `sub`, `act`, and
148
- `actorChain` claims. Revoking the originating human session invalidates the
149
- delegation. Removing an agent or scope from `resolveAgent` invalidates existing
150
- tokens during verification.
151
-
152
- ```ts
153
- await auth.agent!.revokeSession(agentId, sessionId);
154
- await auth.agent!.revokeAgent(agentId);
155
- await auth.agent!.activateAgent(agentId);
156
- ```
157
10
 
158
- Public JWKS verification establishes signature validity but cannot observe
159
- Redis session revocation. Security-sensitive agent routes should use the
160
- session-aware SDK middleware or a trusted introspection boundary.
161
- ***
162
-
163
- ## Why Authenik8-core?
164
-
165
-
166
- JWT makes authentication look simple…
167
- …but introduces hidden problems:
168
-
169
- Refresh token reuse (replay attacks)
170
- Stateless logout issues
171
- Broken token rotation
172
- Scattered security logic
173
-
174
- Authenik8 solves this with:
175
-
176
- Refresh token rotation (with uniqueness via jti)
177
- Stateful session control (Redis)
178
- Built-in security (rate limit, IP whitelist, helmet)
179
- Clean, unified API
180
-
181
- ***
182
- ## Secure Refresh Flow
183
- ```
184
- // first use → valid
185
- await auth.refreshToken(token);
186
-
187
- // reuse same token → rejected
188
- await auth.refreshToken(token); // ❌ throws
189
- ```
190
- ***
191
-
192
- ## API Overview
193
- ```
194
- const auth = await createAuthenik8(config);
195
-
196
- // auth
197
- await auth.signToken(payload);
198
- await auth.verifyToken(token);
199
- auth.getJwks();
200
-
201
- // refresh
202
- auth.refreshToken(refreshToken);
203
- auth.generateRefreshToken(payload);
204
-
205
- // Redis-backed sessions
206
- await auth.listSessions(userId);
207
- await auth.revokeSession(userId, sessionId);
208
- await auth.revokeAllSessions(userId);
209
-
210
- // optional agent identity
211
- await auth.agent?.issueToken({ agentId, scopes });
212
- await auth.agent?.issueDelegatedToken({ agentId, userAccessToken, scopes });
213
- auth.agent?.requireAgent;
214
- auth.agent?.requireScopes("tasks:write");
215
- await auth.agent?.revokeAgent(agentId);
216
-
217
- // security
218
- auth.rateLimit;
219
- auth.ipWhitelist;
220
- auth.helmet;
221
-
222
- // middleware
223
- auth.requireAuth;
224
- auth.requireAdmin;
225
- ```
226
- ***
227
- ## Architecture
228
-
229
- ```
230
- ┌───────────────┐
231
- │ Client │
232
- │ (Web / Mobile)│
233
- └───────┬───────┘
234
- │
235
- ▼
236
- ┌─────────────────────┐
237
- │ API / Backend │
238
- └─────────┬───────────┘
239
- │
240
- ▼
241
- ┌─────────────────────┐
242
- │ Authenik8-core │
243
- │─────────────────────│
244
- │ JWT Service │
245
- │ - Sign / Verify │
246
- │ │
247
- │ Refresh Service │
248
- │ - Rotation │
249
- │ - Replay Detection │
250
- │ │
251
- │ Security Module │
252
- │ - Rate Limiting │
253
- │ - IP Controls │
254
- │ - Middleware │
255
- └─────────┬───────────┘
256
- │
257
- ▼
258
- ┌─────────────────────┐
259
- │ Redis │
260
- │─────────────────────│
261
- │ Session Store │
262
- │ Token State │
263
- │ Revocation Data │
264
- └─────────────────────┘
265
-
266
- ```
267
- ***
268
-
269
- ## Important
270
-
271
- Authenik8-core uses stateful JWT authentication.
272
- This means:
273
- Requires Redis (or compatible store)
274
- Provides stronger security and control than stateless JWT
275
-
276
- ## Add your files
277
-
278
- ```
279
- cd existing_repo
280
- git remote add origin https://gitlab.com/COD434/authenik8-core.git
281
- git branch -M main
282
- git push -uf origin main
283
- ```
284
-
285
- ***
286
- ## Built with Real Testing
287
-
288
- Authenik8-core includes integration-tested flows for:
289
-
290
- Token rotation
291
- Replay attack prevention
292
- Secure refresh logic
293
-
294
- ***
295
- ### Threats Addressed
296
-
297
- - Refresh token replay attacks
298
- - Concurrent token refresh abuse
299
- - Stateless session vulnerabilities
300
- - Basic rate limit bypass (IP rotation)
301
-
302
- ***
303
- ## How It Works Internally
304
- Authenik8-core is designed around stateful JWT authentication to address real-world attack scenarios.
305
- ## Refresh Token Rotation
306
-
307
- Each refresh token includes a unique identifier (jti).
308
- Flow:
309
-
310
- Token is issued with a jti
311
-
312
- jti is stored in Redis
313
- On refresh:
314
-
315
- Token is validated
316
- jti is checked against Redis
317
-
318
- If valid:
319
-
320
- Old token is invalidated
321
- New token is issued with a new jti
11
+ </div>
322
12
 
323
- ## Replay Attack Detection
13
+ Authenik8-core is a stateful JWT authentication SDK with refresh-token replay
14
+ protection, Redis-backed revocation, authorization, audit events, risk
15
+ quarantine, and scoped agent identities.
324
16
 
325
- If a refresh token is reused:
17
+ Start with [Getting Started](docs/getting-started.md), then review the
18
+ [requirements](docs/requirements.md) and [threat model](THREAT_MODEL.md) before
19
+ deploying.
326
20
 
327
- The jti no longer exists or is marked as used
328
- The request is rejected immediately
329
- This prevents:
21
+ ## Documentation
330
22
 
331
- Token replay attacks
332
- Concurrent refresh abuse
23
+ ### Start Here
333
24
 
334
- ## Stateful Session Control
335
- Unlike traditional JWT systems:
336
- Sessions are tracked in Redis
337
- Tokens can be revoked
338
- Logout is fully enforced
25
+ - [What Authenik8-core does](docs/what-authenik8-does.md)
26
+ - [Getting started](docs/getting-started.md)
27
+ - [Requirements](docs/requirements.md)
28
+ - [Why Authenik8-core?](docs/why-authenik8.md)
29
+ - [Use cases](docs/use-cases.md)
30
+ - [Final thought](docs/final-thought.md)
339
31
 
340
- ## Security Layer
341
- Authenik8-core includes built-in middleware for:
342
- Rate limiting
343
- IP-based controls
344
- Secure headers (Helmet)
345
- These operate alongside authentication to provide: 👉 a unified security layer
32
+ ### Authentication and Sessions
346
33
 
347
- ## Why Stateful Matters
348
- Stateless JWT:
349
- Cannot revoke tokens easily
350
- Cannot detect reuse
351
- Cannot track behavior
352
- Authenik8-core:
353
- Tracks token lifecycle
354
- Detects anomalies
355
- Enables real control over sessions
356
- ***
34
+ - [Replay-attack prevention example](docs/replay-attack-prevention.md)
35
+ - [Secure refresh flow](docs/secure-refresh-flow.md)
36
+ - [Key rotation](docs/key-rotation.md)
37
+ - [Session risk and quarantine](docs/session-risk-quarantine.md)
38
+ - [Agent and service identity](docs/agent-service-identity.md)
357
39
 
40
+ ### Authorization and API
358
41
 
359
- ## Use Cases
42
+ - [Authorization, tenants, and audit events](docs/authorization-tenants-audit.md)
43
+ - [API overview](docs/api-overview.md)
44
+ - [Security layer](docs/security-layer.md)
360
45
 
361
- SaaS backends
362
- APIs with authentication
363
- Secure admin systems
364
- Systems requiring session control
46
+ ### Design and Internals
365
47
 
366
- ***
48
+ - [Architecture](docs/architecture.md)
49
+ - [How it works internally](docs/how-it-works-internally.md)
50
+ - [Refresh-token rotation](docs/refresh-token-rotation.md)
51
+ - [Replay-attack detection](docs/replay-attack-detection.md)
52
+ - [Stateful session control](docs/stateful-session-control.md)
53
+ - [Why stateful authentication matters](docs/why-stateful-matters.md)
367
54
 
368
- ## Final Thought
55
+ ### Assurance and Project Information
369
56
 
370
- JWT alone is not an authentication system.
371
- Authenik8-core makes it one.
372
- ***
57
+ - [Testing](docs/testing.md)
58
+ - [Security audit](docs/security-audit.md)
59
+ - [Threats addressed](docs/threats-addressed.md)
60
+ - [Full threat model](THREAT_MODEL.md)
61
+ - [Repository setup](docs/repository-setup.md)
62
+ - [Changelog](CHANGELOG.md)
@@ -0,0 +1,162 @@
1
+ # Authenik8-core Threat Model
2
+
3
+ This document describes the controls implemented by the SDK and the security
4
+ responsibilities that remain with its operator. It is not a certification or a
5
+ claim of compliance with a military, government, or industry assurance scheme.
6
+ Those claims require independently defined requirements, accredited assessment,
7
+ deployment review, and operational evidence.
8
+
9
+ ## Assets
10
+
11
+ - Access, refresh, and agent signing keys.
12
+ - Human, guest, administrator, and agent identities.
13
+ - Active sessions, refresh families, revocation markers, and quarantine state.
14
+ - OAuth state, identity records, provider links, and email/provider indexes.
15
+ - Authorization claims, tenant boundaries, and audit-event integrity.
16
+ - Redis availability and integrity.
17
+
18
+ ## Adversaries
19
+
20
+ - Unauthenticated attackers sending malformed tokens, OAuth parameters,
21
+ forwarding headers, IP values, or high request volumes.
22
+ - Authenticated users attempting claim, tenant, role, permission, or account-link
23
+ escalation.
24
+ - Token thieves replaying access, refresh, guest, or agent bearer credentials.
25
+ - Concurrent attackers racing refresh, OAuth-state, identity-create, or
26
+ provider-link operations.
27
+ - Compromised agents attempting scope or delegation escalation.
28
+ - Attackers with partial infrastructure access, including an untrusted proxy or
29
+ the ability to submit data consumed by an audit sink.
30
+
31
+ ## Trust Boundaries
32
+
33
+ The application, its signing-key source, its identity adapter, and Redis are in
34
+ the trusted computing base. Redis compromise can alter sessions, OAuth indexes,
35
+ refresh state, rate limits, and quarantine records; it can therefore cause
36
+ account takeover, forced logout, policy bypass, or denial of service.
37
+
38
+ Google and GitHub responses are trusted only after HTTPS success checks and
39
+ provider-specific identity verification. Forwarding headers are trusted only
40
+ when the direct socket peer and each intervening hop match explicitly configured
41
+ proxy CIDRs.
42
+
43
+ ## Enforced Security Invariants
44
+
45
+ ### Tokens and sessions
46
+
47
+ - New deployments use ES256 P-256 JWKs with bounded key rings, unique `kid`
48
+ values, issuer, audience, expiry, and exact `tokenUse` verification.
49
+ - Published JWKS documents contain only allowlisted public EC fields. Local
50
+ verification rejects private or oversized key sets; remote JWKS URLs require
51
+ credential-free HTTPS.
52
+ - The HS256 migration path requires an independent secret containing at least 32
53
+ bytes. Refresh and access HMAC secrets may not be the same.
54
+ - Access tokens are limited to 24 hours, refresh tokens to 31 days, and agent
55
+ tokens to one hour. Compact JWT and signed-payload sizes are bounded.
56
+ - Stateful verification requires the token fingerprint to match the current
57
+ Redis session and rejects revoked or quarantined sessions.
58
+ - Refresh rotation uses a per-session lock plus atomic compare-and-set. Replay or
59
+ a lost rotation race revokes the refresh family.
60
+ - Redis stores SHA-256 token fingerprints rather than newly issued raw bearer
61
+ tokens. Read-only migration support remains for older access-session records.
62
+ - Compound refresh and lock keys use collision-resistant identifiers, and
63
+ persisted sessions must match the Redis hash field from which they were read.
64
+ - Authorization claim collections and values are bounded at issuance and again
65
+ after signature verification.
66
+
67
+ ### OAuth identity
68
+
69
+ - State is 256 random bits, expires within five minutes, has a strict shape, and
70
+ is atomically read and deleted before token exchange. Custom state stores must
71
+ implement the same one-time `take()` guarantee.
72
+ - Link mode must be explicit and is rejected before state creation unless an
73
+ authenticated user ID is present.
74
+ - A link callback can modify only the authenticated user recorded in state.
75
+ Provider-supplied email is never used to choose the link target.
76
+ - Redis identity creation atomically distinguishes `created`,
77
+ `existing-provider`, and `existing-email`. An email collision never authorizes
78
+ token issuance.
79
+ - Provider linking uses optimistic compare-and-set with bounded retries and
80
+ verifies the resulting link before success. Identity transaction keys share a
81
+ Redis Cluster hash slot.
82
+ - Identity indexes are cross-checked against resolved records. Adapter-returned
83
+ users are bounded and validated before any account decision or token
84
+ issuance.
85
+ - Automatic verified-email linking is disabled by default. If an application
86
+ explicitly enables it, policy and email-verification values must be actual
87
+ booleans and the adapter must persist and verify the link before tokens are
88
+ issued.
89
+ - OAuth provider requests time out and decompressed JSON responses are capped at
90
+ 64 KiB before strict response-shape validation.
91
+
92
+ ### Network and HTTP controls
93
+
94
+ - Client IP resolution starts at `socket.remoteAddress`; it never trusts
95
+ Express's already-processed `req.ip`.
96
+ - `X-Forwarded-For` is ignored unless `trustedProxyCidrs` is configured. The
97
+ chain is walked right-to-left and stops at the first untrusted hop. Malformed,
98
+ excessively long, or excessively deep chains fail closed.
99
+ - IPv4, IPv6, IPv4-mapped IPv6, and CIDR entries are canonicalized. Loopback is
100
+ not implicitly allowlisted.
101
+ - Exact IP allowlist membership and TTL are checked atomically. CIDR TTL cleanup
102
+ is batched instead of issuing one Redis request per entry.
103
+ - Rate-limit keys are bounded SHA-256 digests. OTP limiting applies both an
104
+ IP bucket and a normalized, bounded email bucket.
105
+ - Default CSP is enforcing and contains no `unsafe-inline` or placeholder
106
+ origins. HSTS, frame denial, MIME sniffing protection, and a no-referrer policy
107
+ are enabled.
108
+
109
+ ### State isolation and audit
110
+
111
+ - SDK Redis keys are isolated by an explicit prefix or a stable prefix derived
112
+ from issuer and audience. Caller-controlled identity index components are
113
+ hashed.
114
+ - Audit metadata is detached, bounded, recursively cloned, and deeply frozen.
115
+ One sink cannot mutate authorization state or the event delivered to another
116
+ sink.
117
+ - Audit envelope identifiers are bounded and control-character free. Stored
118
+ risk records, principals, counters, actions, and fingerprints are validated
119
+ before they influence quarantine decisions.
120
+ - Best-effort audit delivery contains synchronous and asynchronous sink
121
+ failures. Strict mode can deliberately fail the security operation.
122
+
123
+ ## Residual Risks and Operator Responsibilities
124
+
125
+ 1. Bearer credentials remain usable by a thief until expiry, revocation, or
126
+ quarantine. The SDK does not implement proof-of-possession or TLS channel
127
+ binding.
128
+ 2. Cookie authentication is disabled by default and has no built-in CSRF token
129
+ mechanism. Applications enabling it must enforce `Secure`, `HttpOnly`,
130
+ suitable `SameSite`, origin checks, and CSRF validation.
131
+ 3. Redis is security-critical. Use authenticated encrypted connections,
132
+ network isolation, least-privilege credentials, persistence, tested failover,
133
+ monitoring, protected backups, and a topology compatible with the Lua
134
+ operations used here.
135
+ 4. IP controls are defense in depth, not identity proof. NAT, mobile networks,
136
+ IPv6 privacy addresses, botnets, and IP rotation limit their effectiveness.
137
+ 5. The application must authenticate workloads before calling agent issuance.
138
+ Use mTLS, cloud workload identity, signed client assertions, or an equivalent
139
+ credential exchange.
140
+ 6. Offline JWKS verification cannot observe Redis revocation. Services that need
141
+ immediate revocation require a trusted online session/introspection boundary.
142
+ 7. Custom OAuth identity and state adapters are part of the trusted computing
143
+ base and must preserve uniqueness, atomicity, one-time consumption, and
144
+ authenticated-link invariants.
145
+ 8. The SDK does not replace TLS termination, secret-manager access controls,
146
+ host/container hardening, application input validation, CORS policy, XSS
147
+ prevention, durable audit storage, incident response, or supply-chain
148
+ controls.
149
+ 9. Fail-closed Redis behavior protects authorization but can reduce
150
+ availability. Capacity planning and failure-mode testing are required.
151
+ 10. CI intentionally uses `ioredis-mock` and starts no Redis service; operators must separately qualify
152
+ their exact Redis version, cluster/failover topology, and persistence
153
+ settings before production.
154
+
155
+ ## Verification Expectations
156
+
157
+ Every security fix should retain a regression test for its abuse case. Release
158
+ gates should include type checking, unit and mocked-Redis integration tests,
159
+ build verification, a lockfile-based dependency audit, secret scanning, static
160
+ analysis, and independent review of high-risk changes. Production qualification
161
+ should add real-topology Redis tests outside CI, penetration testing, deployment
162
+ configuration review, and recovery exercises.