authenik8-core 0.1.5 → 1.0.3

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 (104) hide show
  1. package/dist/auth/refreshService.d.ts.map +1 -1
  2. package/dist/auth/refreshService.js +3 -3
  3. package/dist/auth/refreshService.js.map +1 -1
  4. package/dist/createAuthenik8.d.ts.map +1 -1
  5. package/dist/createAuthenik8.js +51 -8
  6. package/dist/createAuthenik8.js.map +1 -1
  7. package/dist/oauth/adapters/memoryAdapter.d.ts +23 -0
  8. package/dist/oauth/adapters/memoryAdapter.d.ts.map +1 -0
  9. package/dist/oauth/adapters/memoryAdapter.js +43 -0
  10. package/dist/oauth/adapters/memoryAdapter.js.map +1 -0
  11. package/dist/oauth/brain/identityEngine.d.ts +18 -0
  12. package/dist/oauth/brain/identityEngine.d.ts.map +1 -0
  13. package/dist/oauth/brain/identityEngine.js +95 -0
  14. package/dist/oauth/brain/identityEngine.js.map +1 -0
  15. package/dist/oauth/brain/identityPolicy.d.ts +5 -0
  16. package/dist/oauth/brain/identityPolicy.d.ts.map +1 -0
  17. package/dist/oauth/brain/identityPolicy.js +8 -0
  18. package/dist/oauth/brain/identityPolicy.js.map +1 -0
  19. package/dist/oauth/brain/identityResolver.d.ts +7 -0
  20. package/dist/oauth/brain/identityResolver.d.ts.map +1 -0
  21. package/dist/oauth/brain/identityResolver.js +32 -0
  22. package/dist/oauth/brain/identityResolver.js.map +1 -0
  23. package/dist/oauth/brain/types.d.ts +9 -0
  24. package/dist/oauth/brain/types.d.ts.map +1 -0
  25. package/dist/oauth/brain/types.js +3 -0
  26. package/dist/oauth/brain/types.js.map +1 -0
  27. package/dist/oauth/core.d.ts +28 -0
  28. package/dist/oauth/core.d.ts.map +1 -0
  29. package/dist/oauth/core.js +16 -0
  30. package/dist/oauth/core.js.map +1 -0
  31. package/dist/oauth/identity/types.d.ts +32 -0
  32. package/dist/oauth/identity/types.d.ts.map +1 -0
  33. package/dist/oauth/identity/types.js +3 -0
  34. package/dist/oauth/identity/types.js.map +1 -0
  35. package/dist/oauth/providers/github.d.ts +14 -0
  36. package/dist/oauth/providers/github.d.ts.map +1 -0
  37. package/dist/oauth/providers/github.js +100 -0
  38. package/dist/oauth/providers/github.js.map +1 -0
  39. package/dist/oauth/providers/google.d.ts +13 -0
  40. package/dist/oauth/providers/google.d.ts.map +1 -0
  41. package/dist/oauth/providers/google.js +138 -0
  42. package/dist/oauth/providers/google.js.map +1 -0
  43. package/dist/oauth/types/identity.d.ts +16 -0
  44. package/dist/oauth/types/identity.d.ts.map +1 -0
  45. package/dist/oauth/types/identity.js +3 -0
  46. package/dist/oauth/types/identity.js.map +1 -0
  47. package/dist/oauth/types.d.ts +23 -0
  48. package/dist/oauth/types.d.ts.map +1 -0
  49. package/dist/oauth/types.js +3 -0
  50. package/dist/oauth/types.js.map +1 -0
  51. package/dist/oauth/userStore.d.ts +19 -0
  52. package/dist/oauth/userStore.d.ts.map +1 -0
  53. package/dist/oauth/userStore.js +41 -0
  54. package/dist/oauth/userStore.js.map +1 -0
  55. package/dist/tests/oauth.intergration.test.d.ts +2 -0
  56. package/dist/tests/oauth.intergration.test.d.ts.map +1 -0
  57. package/dist/tests/oauth.intergration.test.js +38 -0
  58. package/dist/tests/oauth.intergration.test.js.map +1 -0
  59. package/dist/tests/oauth1.test.d.ts +9 -0
  60. package/dist/tests/oauth1.test.d.ts.map +1 -0
  61. package/dist/tests/oauth1.test.js +126 -0
  62. package/dist/tests/oauth1.test.js.map +1 -0
  63. package/dist/tests/oauth2.test.d.ts +2 -0
  64. package/dist/tests/oauth2.test.d.ts.map +1 -0
  65. package/dist/tests/oauth2.test.js +145 -0
  66. package/dist/tests/oauth2.test.js.map +1 -0
  67. package/dist/tests/oauth3.test.d.ts +2 -0
  68. package/dist/tests/oauth3.test.d.ts.map +1 -0
  69. package/dist/tests/oauth3.test.js +148 -0
  70. package/dist/tests/oauth3.test.js.map +1 -0
  71. package/dist/types/config.d.ts +2 -0
  72. package/dist/types/config.d.ts.map +1 -1
  73. package/dist/types/public.d.ts +25 -0
  74. package/dist/types/public.d.ts.map +1 -1
  75. package/dist/types/tokens.d.ts +10 -0
  76. package/dist/types/tokens.d.ts.map +1 -0
  77. package/dist/types/tokens.js +3 -0
  78. package/dist/types/tokens.js.map +1 -0
  79. package/dump.rdb +0 -0
  80. package/package.json +2 -1
  81. package/src/auth/refreshService.ts +4 -3
  82. package/src/createAuthenik8.ts +78 -11
  83. package/src/dump.rdb +0 -0
  84. package/src/oauth/adapters/memoryAdapter.ts +74 -0
  85. package/src/oauth/brain/identityEngine.ts +141 -0
  86. package/src/oauth/brain/identityPolicy.ts +4 -0
  87. package/src/oauth/brain/identityResolver.ts +43 -0
  88. package/src/oauth/brain/types.ts +9 -0
  89. package/src/oauth/core.ts +19 -0
  90. package/src/oauth/identity/1 +44 -0
  91. package/src/oauth/identity/types.ts +44 -0
  92. package/src/oauth/providers/github.ts +154 -0
  93. package/src/oauth/providers/google.ts +189 -0
  94. package/src/oauth/types/identity.ts +17 -0
  95. package/src/oauth/types.ts +24 -0
  96. package/src/oauth/userStore.ts +73 -0
  97. package/src/tests/dump.rdb +0 -0
  98. package/src/tests/oauth.intergration.test.ts +39 -0
  99. package/src/tests/oauth1.test.ts +145 -0
  100. package/src/tests/oauth2.test.ts +158 -0
  101. package/src/tests/oauth3.test.ts +171 -0
  102. package/src/types/config.ts +6 -0
  103. package/src/types/public.ts +26 -0
  104. package/src/types/tokens.ts +10 -0
@@ -0,0 +1,141 @@
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
+ }
@@ -0,0 +1,4 @@
1
+ export const identityPolicy = {
2
+ autoLinkOnVerifiedEmailMatch: false,
3
+ allowUnverifiedAutoLink: false,
4
+ };
@@ -0,0 +1,43 @@
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
+ }
@@ -0,0 +1,9 @@
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
+ };
@@ -0,0 +1,19 @@
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
+
@@ -0,0 +1,44 @@
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
+ };
@@ -0,0 +1,44 @@
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
+ };
@@ -0,0 +1,154 @@
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
+
@@ -0,0 +1,189 @@
1
+ import { OAuthProfile, GoogleOAuthConfig } from "../types";
2
+ import { OAuth2Client } from "google-auth-library";
3
+ import {Request,Response} from "express";
4
+ import jwt from "jsonwebtoken";
5
+ import crypto from "crypto";
6
+ import type { Redis as RedisClient } from "ioredis";
7
+ import type { IdentityEngine } from "../brain/types";
8
+
9
+ export function createGoogleProvider(config: GoogleOAuthConfig,
10
+ redisClient:RedisClient,
11
+ identityEngine: IdentityEngine
12
+ ) {
13
+ const { clientId, clientSecret, redirectUri } = config;
14
+
15
+ return {
16
+
17
+ redirect:async (req:Request, res:Response): Promise<void> => {
18
+ try{
19
+
20
+
21
+ const state = crypto.randomBytes(32).toString("hex");
22
+
23
+
24
+ const mode = req.path.includes("link") ? "link" : "login";
25
+ const authUser = (req as any).user ?? null;
26
+
27
+ await redisClient.setex(
28
+ `oauth:state:${state}`,
29
+ 300,
30
+ JSON.stringify({
31
+ userId: authUser?.userId ?? null,
32
+ mode,
33
+ })
34
+ );
35
+
36
+
37
+
38
+
39
+ const url = new URL("https://accounts.google.com/o/oauth2/v2/auth");
40
+ url.searchParams.set("client_id", clientId);
41
+ url.searchParams.set("redirect_uri", redirectUri);
42
+ url.searchParams.set("response_type", "code");
43
+ url.searchParams.set("scope", "openid email profile");
44
+ url.searchParams.set("access_type", "offline");
45
+ url.searchParams.set("prompt", "consent");
46
+
47
+ url.searchParams.set("state", state)
48
+
49
+
50
+ res.redirect(url.toString());
51
+ return;
52
+ } catch (err) {
53
+ console.error("Google redirect error:", err);
54
+ res.status(500).json({ error: "OAuth redirect failed" });
55
+ return;
56
+ }
57
+ },
58
+ handleCallback: async (req:Request): Promise<{
59
+ profile: OAuthProfile;
60
+ mode: "login" | "link";
61
+ userId: string | null;
62
+ }> => {
63
+ const code = req.query.code as string;
64
+ const client = new OAuth2Client(clientId);
65
+
66
+ const state = req.query.state as string;
67
+
68
+ if (!state) {
69
+ throw new Error("OAuthError:Missing state");
70
+ }
71
+
72
+ const stored = await redisClient.get(`oauth:state:${state}`);
73
+
74
+ if (!stored) {
75
+ throw new Error("OAuthError:Invalid or expired state");
76
+ }
77
+
78
+ const { userId, mode } = JSON.parse(stored);
79
+
80
+
81
+ if (!code) {
82
+ throw new Error("OauthError:Missing authorization code");
83
+ }
84
+ const params = new URLSearchParams();
85
+ params.append("client_id", clientId);
86
+ params.append("client_secret", clientSecret);
87
+ params.append("code", code);
88
+ params.append("grant_type", "authorization_code");
89
+ params.append("redirect_uri", redirectUri);
90
+
91
+
92
+
93
+ // 1. Exchange code for tokens
94
+ const tokenRes = await fetch("https://oauth2.googleapis.com/token", {
95
+ method: "POST",
96
+ headers: {
97
+ "Content-Type": "application/x-www-form-urlencoded",
98
+ },
99
+ body:params
100
+ });
101
+
102
+ if(!tokenRes.ok){
103
+ const err = await tokenRes.text();
104
+ throw new Error(`OAuthError:Token exchange failed->${err}`)
105
+ }
106
+
107
+ const tokenData = await tokenRes.json();
108
+ if(!tokenData.access_token){
109
+
110
+ throw new Error("OAuthError:No access token returned")
111
+ }
112
+ if (!tokenData.id_token) {
113
+ console.log("TOKEN DATA:", tokenData);
114
+ throw new Error("OAuthError:No id_token returned from Google");
115
+ }
116
+ const ticket = await client.verifyIdToken({
117
+ idToken: tokenData.id_token,
118
+ audience: clientId,
119
+ });
120
+
121
+ const payload = ticket.getPayload();
122
+
123
+ if(!payload){
124
+ throw new Error("OAuthError:Invalid ID token payload");
125
+ }
126
+ if(!payload.email){
127
+ throw new Error("OAuthError:Email not present in ID token");
128
+ }
129
+ if(!payload.email_verified){
130
+ throw new Error("OAuthError:Email not verified");
131
+ }
132
+
133
+ if (
134
+ payload.iss !== "https://accounts.google.com" &&
135
+ payload.iss !== "accounts.google.com"
136
+ ) {
137
+ throw new Error("OAuthError: Invalid issuer");
138
+ }
139
+
140
+ const profile: OAuthProfile = {
141
+ email: payload.email,
142
+ name: payload.name,
143
+ provider: "google",
144
+ providerId: payload.sub,
145
+ };
146
+
147
+ const accessToken = tokenData.access_token;
148
+ console.log("Token data:",tokenData);
149
+ console.log("[OAuth] Fetching user profile...");
150
+
151
+ console.log("FINAL ENGINE INPUT:", {
152
+ profile,
153
+ mode,
154
+ userId,
155
+ });
156
+
157
+ let result
158
+ try{
159
+ result = await identityEngine.resolveOAuth({
160
+ profile,
161
+ mode,
162
+ userId,
163
+ })
164
+
165
+ }catch(err){
166
+ console.error("ENGINE ERROR:",err)
167
+ throw err;
168
+ }
169
+ if (
170
+ result.type !== "INVALID_LINK_REQUEST" &&
171
+ result.type !== "EXISTING_EMAIL_CONFLICT" &&
172
+ !result.user
173
+ ) {
174
+ throw new Error("Invalid engine result: missing user");
175
+ }
176
+
177
+
178
+ await redisClient.del(`oauth:state:${state}`);
179
+
180
+ return {
181
+ profile,
182
+ mode,
183
+ userId,
184
+ };
185
+
186
+ }
187
+ }
188
+ }
189
+
@@ -0,0 +1,17 @@
1
+ export type Provider = "google" | "github";
2
+
3
+ export type Identity = {
4
+ provider: Provider;
5
+ providerId: string;
6
+ email?: string;
7
+ verified: boolean;
8
+ };
9
+
10
+ export type User = {
11
+ userId: string;
12
+ email: string;
13
+ emailVerified: boolean;
14
+ providers: Identity[];
15
+ createdAt: number;
16
+ lastLoginAt?: number;
17
+ };
@@ -0,0 +1,24 @@
1
+
2
+ export type Provider ="google" | "github"
3
+ export type OAuthProfile = {
4
+ email: string;
5
+ name?: string;
6
+ provider: Provider;
7
+ providerId: string;
8
+ };
9
+
10
+ export type GoogleOAuthConfig = {
11
+ clientId: string;
12
+ clientSecret: string;
13
+ redirectUri: string;
14
+ };
15
+ export type GitHubOAuthConfig = {
16
+ clientId: string;
17
+ clientSecret: string;
18
+ redirectUri: string;
19
+ enterprise?:boolean
20
+ };
21
+ export type OAuthConfig = {
22
+ google?: GoogleOAuthConfig;
23
+ github?: GitHubOAuthConfig;
24
+ };