authenik8-core 1.0.3 → 1.0.22

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 (97) hide show
  1. package/README.md +6 -0
  2. package/dist/auth/guestModeService.d.ts +4 -1
  3. package/dist/auth/guestModeService.d.ts.map +1 -1
  4. package/dist/auth/guestModeService.js +31 -20
  5. package/dist/auth/guestModeService.js.map +1 -1
  6. package/dist/auth/jwtAuth.d.ts +2 -1
  7. package/dist/auth/jwtAuth.d.ts.map +1 -1
  8. package/dist/auth/jwtAuth.js +26 -8
  9. package/dist/auth/jwtAuth.js.map +1 -1
  10. package/dist/auth/refreshService.d.ts +2 -0
  11. package/dist/auth/refreshService.d.ts.map +1 -1
  12. package/dist/auth/refreshService.js +12 -5
  13. package/dist/auth/refreshService.js.map +1 -1
  14. package/dist/createAuthenik8.d.ts.map +1 -1
  15. package/dist/createAuthenik8.js +31 -13
  16. package/dist/createAuthenik8.js.map +1 -1
  17. package/dist/middleware/adminService.d.ts +1 -1
  18. package/dist/middleware/adminService.d.ts.map +1 -1
  19. package/dist/middleware/adminService.js +6 -10
  20. package/dist/middleware/adminService.js.map +1 -1
  21. package/dist/oauth/adapters/redisAdapter.d.ts +23 -0
  22. package/dist/oauth/adapters/redisAdapter.d.ts.map +1 -0
  23. package/dist/oauth/adapters/redisAdapter.js +116 -0
  24. package/dist/oauth/adapters/redisAdapter.js.map +1 -0
  25. package/dist/oauth/brain/identityEngine.d.ts.map +1 -1
  26. package/dist/oauth/brain/identityEngine.js +26 -7
  27. package/dist/oauth/brain/identityEngine.js.map +1 -1
  28. package/dist/oauth/identity/types.d.ts +6 -1
  29. package/dist/oauth/identity/types.d.ts.map +1 -1
  30. package/dist/oauth/providers/github.d.ts.map +1 -1
  31. package/dist/oauth/providers/github.js +6 -7
  32. package/dist/oauth/providers/github.js.map +1 -1
  33. package/dist/oauth/providers/google.d.ts.map +1 -1
  34. package/dist/oauth/providers/google.js +3 -28
  35. package/dist/oauth/providers/google.js.map +1 -1
  36. package/dist/oauth/types.d.ts +1 -0
  37. package/dist/oauth/types.d.ts.map +1 -1
  38. package/dist/redis/redisService.js +7 -8
  39. package/dist/redis/redisService.js.map +1 -1
  40. package/dist/security/ipService.d.ts +3 -0
  41. package/dist/security/ipService.d.ts.map +1 -1
  42. package/dist/security/ipService.js +30 -9
  43. package/dist/security/ipService.js.map +1 -1
  44. package/dist/security/limiter.d.ts +12 -1
  45. package/dist/security/limiter.d.ts.map +1 -1
  46. package/dist/security/limiter.js +29 -10
  47. package/dist/security/limiter.js.map +1 -1
  48. package/dist/storage/RedisTokenStore.d.ts.map +1 -1
  49. package/dist/storage/RedisTokenStore.js +3 -2
  50. package/dist/storage/RedisTokenStore.js.map +1 -1
  51. package/dist/storage/userStorage.js +1 -2
  52. package/dist/storage/userStorage.js.map +1 -1
  53. package/dist/types/config.d.ts +3 -0
  54. package/dist/types/config.d.ts.map +1 -1
  55. package/package.json +23 -13
  56. package/dump.rdb +0 -0
  57. package/jest.config.js +0 -11
  58. package/src/auth/guestModeService.ts +0 -31
  59. package/src/auth/jwtAuth.ts +0 -99
  60. package/src/auth/refreshService.ts +0 -157
  61. package/src/createAuthenik8.ts +0 -135
  62. package/src/dump.rdb +0 -0
  63. package/src/index.ts +0 -2
  64. package/src/middleware/adminService.ts +0 -50
  65. package/src/oauth/adapters/memoryAdapter.ts +0 -74
  66. package/src/oauth/brain/identityEngine.ts +0 -141
  67. package/src/oauth/brain/identityPolicy.ts +0 -4
  68. package/src/oauth/brain/identityResolver.ts +0 -43
  69. package/src/oauth/brain/types.ts +0 -9
  70. package/src/oauth/core.ts +0 -19
  71. package/src/oauth/identity/1 +0 -44
  72. package/src/oauth/identity/types.ts +0 -44
  73. package/src/oauth/providers/github.ts +0 -154
  74. package/src/oauth/providers/google.ts +0 -189
  75. package/src/oauth/types/identity.ts +0 -17
  76. package/src/oauth/types.ts +0 -24
  77. package/src/oauth/userStore.ts +0 -73
  78. package/src/redis/redisService.ts +0 -137
  79. package/src/security/ipService.ts +0 -180
  80. package/src/security/limiter.ts +0 -116
  81. package/src/storage/RedisTokenStore.ts +0 -110
  82. package/src/storage/userStorage.ts +0 -16
  83. package/src/tests/con.test.ts +0 -76
  84. package/src/tests/dump.rdb +0 -0
  85. package/src/tests/full.intergration.test.ts +0 -100
  86. package/src/tests/oauth.intergration.test.ts +0 -39
  87. package/src/tests/oauth1.test.ts +0 -145
  88. package/src/tests/oauth2.test.ts +0 -158
  89. package/src/tests/oauth3.test.ts +0 -171
  90. package/src/tests/testApp.ts +0 -56
  91. package/src/types/admin.ts +0 -7
  92. package/src/types/config.ts +0 -17
  93. package/src/types/public.ts +0 -48
  94. package/src/types/storage.ts +0 -15
  95. package/src/types/tokens.ts +0 -10
  96. package/src/utility/lockHelper.ts +0 -33
  97. package/tsconfig.json +0 -51
@@ -1,74 +0,0 @@
1
- import { randomUUID } from "crypto";
2
-
3
- type Provider = {
4
- provider: string;
5
- providerId: string;
6
- };
7
-
8
- type User = {
9
- id: string;
10
- email: string;
11
- providers: Provider[];
12
- };
13
-
14
- // 🔥 SINGLE SOURCE OF TRUTH (REAL MEMORY STORE)
15
- const users = new Map<string, User>();
16
-
17
- export const memoryAdapter = {
18
- async findUserByEmail(email: string) {
19
- return [...users.values()].find((u) => u.email === email) || null;
20
- },
21
-
22
- async findUserByProvider(provider: string, providerId: string) {
23
- return (
24
- [...users.values()].find((u) =>
25
- u.providers.some(
26
- (p) => p.provider === provider && p.providerId === providerId
27
- )
28
- ) || null
29
- );
30
- },
31
-
32
- async createUser(data: {
33
- email: string;
34
- provider: string;
35
- providerId: string;
36
- }) {
37
- const user: User = {
38
- id: randomUUID(),
39
- email: data.email,
40
- providers: [
41
- {
42
- provider: data.provider,
43
- providerId: data.providerId,
44
- },
45
- ],
46
- };
47
-
48
- users.set(user.id, user);
49
- return user;
50
- },
51
-
52
- async linkProvider(
53
- userId: string,
54
- provider: string,
55
- providerId: string
56
- ) {
57
- const user = users.get(userId);
58
-
59
- if (!user) {
60
- throw new Error(`User not found: ${userId}`);
61
- }
62
-
63
- user.providers.push({ provider, providerId });
64
- users.set(userId, user);
65
- },
66
-
67
- reset() {
68
- users.clear();
69
- },
70
-
71
- dump() {
72
- return [...users.values()];
73
- },
74
- };
@@ -1,141 +0,0 @@
1
- import { OAuthProfile } from "../types";
2
- import { memoryAdapter } from "../adapters/memoryAdapter";
3
- import { IdentityEngine } from "./types";
4
- import { IdentityContext, IdentityResult } from "../identity/types";
5
-
6
- const auditLogs: any[] = [];
7
- type IdentityAdapter = {
8
- findUserByEmail(email: string): Promise<any>;
9
- findUserByProvider(provider: string, providerId: string): Promise<any>;
10
- createUser(data: {
11
- email: string;
12
- provider: string;
13
- providerId: string;
14
- }): Promise<any>;
15
- linkProvider(
16
- userId: string,
17
- provider: string,
18
- providerId: string
19
- ): Promise<void>;
20
- };
21
- type TokenService = {
22
- signAccessToken(payload: any): string;
23
- generateRefreshToken(payload: any): Promise<string>;
24
- };
25
-
26
- export function createIdentityEngine(
27
- adapter:IdentityAdapter,
28
- tokenService:TokenService
29
- ): IdentityEngine {
30
- return {
31
- async resolveOAuth(args):Promise<IdentityResult>{
32
- const ctx:IdentityContext = {
33
- email: args.profile.email,
34
- provider:args.profile.provider,
35
- providerId:args.profile.providerId,
36
- mode:args.mode,
37
- userId: args.userId ?? undefined,
38
- }
39
-
40
- if (!ctx.email) {
41
- throw new Error("OAuth profile missing email");
42
- }
43
- // 1. Existing provider
44
- const existingProvider = await adapter.findUserByProvider(
45
- ctx.provider,
46
- ctx.providerId
47
- );
48
-
49
- if (existingProvider) {
50
- const payload ={userId:existingProvider.id}
51
- return {
52
- type:"EXISTING_PROVIDER_LOGIN",
53
- user: existingProvider,
54
- accessToken:tokenService.signAccessToken(payload),
55
- refreshToken: await tokenService.generateRefreshToken(payload),
56
- };
57
- }
58
-
59
- // 2. LINK FLOW
60
- if (ctx.mode === "link") {
61
-
62
- if (!ctx.userId) {
63
- return{
64
-
65
- type:"INVALID_LINK_REQUEST",
66
- message:"Missing authenticated user for linking",
67
- }
68
- }
69
- if (existingProvider && existingProvider.id !== ctx.userId) {
70
- throw new Error("Provider already linked to another user");
71
- }
72
-
73
- await adapter.linkProvider(
74
- ctx.userId,
75
- ctx.provider,
76
- ctx.providerId
77
- );
78
- let user = await adapter.findUserByEmail(ctx.email);
79
-
80
- if (!user) {
81
- user = await adapter.findUserByProvider(ctx.provider, ctx.providerId);
82
- }
83
- if (!user) {
84
- throw new Error("LINK_PROVIDER: user resolution failed");
85
- }
86
- auditLogs.push({
87
- userId: user.id,
88
- action: "PROVIDER_LINKED",
89
- timestamp: Date.now(),
90
- });
91
- return{
92
- type: "LINK_PROVIDER",
93
- user,
94
- success: true,
95
- }
96
- }
97
-
98
- // 3. Check existing by email OR provider (idempotency safety)
99
-
100
- let existingUser = await adapter.findUserByEmail(ctx.email);
101
-
102
-
103
- if (existingUser) {
104
- const payload = { userId: existingUser.id };
105
-
106
- return {
107
- type: "EXISTING_PROVIDER_LOGIN",
108
- user: existingUser,
109
- accessToken: tokenService.signAccessToken(payload),
110
- refreshToken: await tokenService.generateRefreshToken(payload),
111
- };
112
-
113
- }
114
-
115
-
116
- // 4. Create new user
117
- const user = await adapter.createUser({
118
- email:ctx.email,
119
- provider:ctx.provider,
120
- providerId:ctx.providerId,
121
- });
122
- if (!ctx.providerId) {
123
- throw new Error("Missing providerId");
124
- }
125
-
126
- const payload = { userId: user.id };
127
- auditLogs.push({
128
- userId: user.id,
129
- action: "USER_CREATED",
130
- timestamp: Date.now(),
131
- });
132
-
133
- return {
134
- type:"NEW_USER_CREATION",
135
- user,
136
- accessToken:tokenService.signAccessToken(payload),
137
- refreshToken:await tokenService.generateRefreshToken(payload)
138
- };
139
- },
140
- };
141
- }
@@ -1,4 +0,0 @@
1
- export const identityPolicy = {
2
- autoLinkOnVerifiedEmailMatch: false,
3
- allowUnverifiedAutoLink: false,
4
- };
@@ -1,43 +0,0 @@
1
- import { findUserByEmail, findUserByProvider, createUser, linkProvider } from "../userStore";
2
- import { identityPolicy } from "./identityPolicy";
3
- import { OAuthProfile } from "../types";
4
-
5
- export async function resolveIdentity(profile: OAuthProfile) {
6
- const { email, provider, providerId } = profile;
7
-
8
-
9
- const byProvider = await findUserByProvider(provider, providerId);
10
- if (byProvider) {
11
- return byProvider;
12
- }
13
-
14
-
15
- const existingUser = await findUserByEmail(email);
16
-
17
- if (!existingUser) {
18
- return createUser({
19
- email,
20
- provider,
21
- providerId,
22
- });
23
- }
24
-
25
-
26
-
27
- const isVerifiedEmail = true;
28
-
29
- if (
30
- identityPolicy.autoLinkOnVerifiedEmailMatch &&
31
- isVerifiedEmail
32
- ) {
33
- await linkProvider(existingUser.id, provider, providerId);
34
- return existingUser;
35
- }
36
-
37
-
38
- return {
39
- type: "IDENTITY_CONFLICT",
40
- user: existingUser,
41
- message: "Account exists. Explicit linking required.",
42
- };
43
- }
@@ -1,9 +0,0 @@
1
- import { OAuthProfile } from "../types";
2
-
3
- export type IdentityEngine = {
4
- resolveOAuth: (args: {
5
- profile: OAuthProfile;
6
- mode: "login" | "link";
7
- userId?: string | null;
8
- }) => Promise<any>;
9
- };
package/src/oauth/core.ts DELETED
@@ -1,19 +0,0 @@
1
- import { createGoogleProvider } from "./providers/google";
2
- import { GoogleOAuthConfig,GitHubOAuthConfig } from "./types";
3
- import type { Redis as RedisClient } from "ioredis";
4
- import { OAuthProfile } from "./types";
5
- import type { IdentityEngine } from "./brain/types";
6
-
7
- import { createGitHubProvider } from "./providers/github";
8
-
9
- export function createOAuth(config:{google?: GoogleOAuthConfig;github?:GitHubOAuthConfig;redisClient:RedisClient;identityEngine:IdentityEngine} ) {
10
- return {
11
- google: config.google
12
- ? createGoogleProvider(config.google,config.redisClient,config.identityEngine)
13
- : undefined,
14
- github: config.github
15
- ? createGitHubProvider(config.github,config.redisClient,config.identityEngine)
16
- : undefined,
17
- };
18
- }
19
-
@@ -1,44 +0,0 @@
1
- export type IdentityState =
2
- | "EXISTING_PROVIDER_LOGIN"
3
- | "EXISTING_EMAIL_CONFLICT"
4
- | "NEW_USER_CREATION"
5
- | "LINK_PROVIDER"
6
- | "INVALID_LINK_REQUEST";
7
-
8
- export type IdentityContext = {
9
- email: string;
10
- provider: string;
11
- providerId: string;
12
-
13
- mode: "login" | "link";
14
- userId?: string;
15
- };
16
-
17
- export type IdentityResult =
18
- | {
19
- type: "EXISTING_PROVIDER_LOGIN";
20
- user: any;
21
- accessToken: string;
22
- refreshToken: string;
23
- }
24
- | {
25
- type: "EXISTING_EMAIL_CONFLICT";
26
- email: string;
27
- user:any
28
- message: string;
29
- }
30
- | {
31
- type: "NEW_USER_CREATION";
32
- user: any;
33
- accessToken: string;
34
- refreshToken: string;
35
- }
36
- | {
37
- type: "LINK_PROVIDER";
38
- success: true;
39
- user:any;
40
- }
41
- | {
42
- type: "INVALID_LINK_REQUEST";
43
- message: string;
44
- };
@@ -1,44 +0,0 @@
1
- export type IdentityState =
2
- | "EXISTING_PROVIDER_LOGIN"
3
- | "EXISTING_EMAIL_CONFLICT"
4
- | "NEW_USER_CREATION"
5
- | "LINK_PROVIDER"
6
- | "INVALID_LINK_REQUEST";
7
-
8
- export type IdentityContext = {
9
- email: string;
10
- provider: string;
11
- providerId: string;
12
-
13
- mode: "login" | "link";
14
- userId?: string;
15
- };
16
-
17
- export type IdentityResult =
18
- | {
19
- type: "EXISTING_PROVIDER_LOGIN";
20
- user: any;
21
- accessToken: string;
22
- refreshToken: string;
23
- }
24
- | {
25
- type: "EXISTING_EMAIL_CONFLICT";
26
- email: string;
27
- user:any
28
- message: string;
29
- }
30
- | {
31
- type: "NEW_USER_CREATION";
32
- user: any;
33
- accessToken: string;
34
- refreshToken: string;
35
- }
36
- | {
37
- type: "LINK_PROVIDER";
38
- success: true;
39
- user:any;
40
- }
41
- | {
42
- type: "INVALID_LINK_REQUEST";
43
- message: string;
44
- };
@@ -1,154 +0,0 @@
1
- import crypto from "crypto";
2
- import { Request, Response } from "express";
3
- import { OAuthProfile } from "../types";
4
- import type { Redis as RedisClient } from "ioredis";
5
- import { GitHubOAuthConfig, GoogleOAuthConfig } from "../types";
6
- import { linkProvider } from "../userStore";
7
- import type { IdentityEngine } from "../brain/types";
8
-
9
- export function createGitHubProvider(config:GitHubOAuthConfig,
10
- redisClient:RedisClient,
11
- identityEngine:IdentityEngine) {
12
- const { clientId, clientSecret, redirectUri } = config;
13
-
14
- return {
15
- redirect: async (req: Request, res: Response,mode: "login" | "link" = "login"):Promise<void> => {
16
-
17
-
18
-
19
- if (res.headersSent) {
20
- console.log("🚨 HEADERS ALREADY SENT — SKIPPING");
21
- return;
22
- }
23
-
24
-
25
- const state= crypto.randomBytes(32).toString("hex");
26
- const authUser = (req as any).user ?? null;
27
-
28
-
29
-
30
-
31
- await redisClient.setex(
32
- `oauth:state:${state}`,
33
- 300,
34
- JSON.stringify({
35
- userId: authUser?.userId ?? null,
36
- mode,
37
- })
38
- );
39
-
40
-
41
-
42
- const url = new URL("https://github.com/login/oauth/authorize");
43
-
44
- url.searchParams.set("client_id", clientId);
45
- url.searchParams.set("redirect_uri", redirectUri);
46
- url.searchParams.set("scope", "read:user user:email");
47
- url.searchParams.set("state",state);
48
-
49
- console.log("REDIRECT STATE:", {
50
- userId: authUser?.userId,
51
- mode,
52
- });
53
-
54
- res.redirect(url.toString());
55
- return
56
-
57
- },
58
-
59
-
60
- handleCallback:
61
- async (req: Request): Promise<{
62
- profile: OAuthProfile;
63
- mode: "login" | "link";
64
- userId: string | null;
65
- }> => {
66
- const code = req.query.code as string;
67
- const state = req.query.state as string;
68
-
69
- if (!state) {
70
- throw new Error("OAuthError:Missing state");
71
- }
72
-
73
- const stored = await redisClient.get(`oauth:state:${state}`);
74
-
75
- if (!stored) {
76
- throw new Error("OAuthError:Invalid or expired state");
77
- }
78
-
79
-
80
-
81
- const { userId, mode } = JSON.parse(stored);
82
-
83
- if (!code) {
84
- throw new Error("OAuthError: Missing code");
85
- }
86
-
87
- const params = new URLSearchParams();
88
- params.append("client_id", clientId);
89
- params.append("client_secret", clientSecret);
90
- params.append("code", code);
91
-
92
- const tokenRes = await fetch("https://github.com/login/oauth/access_token", {
93
- method: "POST",
94
- headers: {
95
- Accept: "application/json",
96
- },
97
- body: params,
98
- });
99
-
100
- const tokenData = await tokenRes.json();
101
-
102
- if (!tokenData.access_token) {
103
- throw new Error("OAuthError: No access token from Github");
104
- }
105
-
106
- const accessToken = tokenData.access_token;
107
-
108
-
109
- const userRes = await fetch("https://api.github.com/user", {
110
- headers: {
111
- Authorization: `Bearer ${accessToken}`,
112
- },
113
- });
114
- if (!userRes.ok) {
115
- throw new Error("OAuthError: Failed to fetch GitHub user");
116
- }
117
-
118
- const userData = await userRes.json();
119
-
120
-
121
- const emailRes = await fetch("https://api.github.com/user/emails", {
122
- headers: {
123
- Authorization: `Bearer ${accessToken}`,
124
- },
125
- });
126
-
127
- const emails = await emailRes.json();
128
-
129
- const primaryEmail = emails.find((e: any) => e.primary)?.email;
130
-
131
- if (!primaryEmail) {
132
- throw new Error("OAuthError: No primary email found");
133
- }
134
-
135
- const profile: OAuthProfile = {
136
- email: primaryEmail,
137
- name: userData.name,
138
- provider: "github",
139
- providerId: userData.id.toString(),
140
- };
141
-
142
-
143
- await redisClient.del(`oauth:state:${state}`);
144
-
145
- return {
146
- profile,
147
- mode,
148
- userId
149
- };
150
-
151
- },
152
- };
153
- }
154
-