@appconda/nextjs 1.0.86 → 1.0.88

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.
@@ -0,0 +1,102 @@
1
+ import jwt from "jsonwebtoken";
2
+ import { symmetricDecrypt, symmetricEncrypt } from "./crypto";
3
+ import { getEnv } from "./env";
4
+ export const createToken = (userId, userEmail, options = {}) => {
5
+ const encryptedUserId = symmetricEncrypt(userId, getEnv().ENCRYPTION_KEY);
6
+ return jwt.sign({ id: encryptedUserId }, getEnv().NEXTAUTH_SECRET + userEmail, options);
7
+ };
8
+ export const createTokenForLinkSurvey = (surveyId, userEmail) => {
9
+ const encryptedEmail = symmetricEncrypt(userEmail, getEnv().ENCRYPTION_KEY);
10
+ return jwt.sign({ email: encryptedEmail }, getEnv().NEXTAUTH_SECRET + surveyId);
11
+ };
12
+ export const createEmailToken = (email) => {
13
+ const encryptedEmail = symmetricEncrypt(email, getEnv().ENCRYPTION_KEY);
14
+ return jwt.sign({ email: encryptedEmail }, getEnv().NEXTAUTH_SECRET);
15
+ };
16
+ export const getEmailFromEmailToken = (token) => {
17
+ const payload = jwt.verify(token, getEnv().NEXTAUTH_SECRET);
18
+ try {
19
+ // Try to decrypt first (for newer tokens)
20
+ const decryptedEmail = symmetricDecrypt(payload.email, getEnv().ENCRYPTION_KEY);
21
+ return decryptedEmail;
22
+ }
23
+ catch {
24
+ // If decryption fails, return the original email (for older tokens)
25
+ return payload.email;
26
+ }
27
+ };
28
+ export const createInviteToken = (inviteId, email, options = {}) => {
29
+ const encryptedInviteId = symmetricEncrypt(inviteId, getEnv().ENCRYPTION_KEY);
30
+ const encryptedEmail = symmetricEncrypt(email, getEnv().ENCRYPTION_KEY);
31
+ return jwt.sign({ inviteId: encryptedInviteId, email: encryptedEmail }, getEnv().NEXTAUTH_SECRET, options);
32
+ };
33
+ export const verifyTokenForLinkSurvey = (token, surveyId) => {
34
+ try {
35
+ const { email } = jwt.verify(token, getEnv().NEXTAUTH_SECRET + surveyId);
36
+ try {
37
+ // Try to decrypt first (for newer tokens)
38
+ const decryptedEmail = symmetricDecrypt(email, getEnv().ENCRYPTION_KEY);
39
+ return decryptedEmail;
40
+ }
41
+ catch {
42
+ // If decryption fails, return the original email (for older tokens)
43
+ return email;
44
+ }
45
+ }
46
+ catch (err) {
47
+ return null;
48
+ }
49
+ };
50
+ export const verifyToken = async (token) => {
51
+ // First decode to get the ID
52
+ const decoded = jwt.decode(token);
53
+ const payload = decoded;
54
+ const { id } = payload;
55
+ if (!id) {
56
+ throw new Error("Token missing required field: id");
57
+ }
58
+ // Try to decrypt the ID (for newer tokens), if it fails use the ID as-is (for older tokens)
59
+ let decryptedId;
60
+ try {
61
+ decryptedId = symmetricDecrypt(id, getEnv().ENCRYPTION_KEY);
62
+ }
63
+ catch {
64
+ decryptedId = id;
65
+ }
66
+ // If no email provided, look up the user
67
+ const foundUser = null; /* await prisma.user.findUnique({
68
+ where: { id: decryptedId },
69
+ }); */
70
+ if (!foundUser) {
71
+ throw new Error("User not found");
72
+ }
73
+ const userEmail = foundUser.email;
74
+ return { id: decryptedId, email: userEmail };
75
+ };
76
+ export const verifyInviteToken = (token) => {
77
+ try {
78
+ const decoded = jwt.decode(token);
79
+ const payload = decoded;
80
+ const { inviteId, email } = payload;
81
+ let decryptedInviteId;
82
+ let decryptedEmail;
83
+ try {
84
+ // Try to decrypt first (for newer tokens)
85
+ decryptedInviteId = symmetricDecrypt(inviteId, getEnv().ENCRYPTION_KEY);
86
+ decryptedEmail = symmetricDecrypt(email, getEnv().ENCRYPTION_KEY);
87
+ }
88
+ catch {
89
+ // If decryption fails, use original values (for older tokens)
90
+ decryptedInviteId = inviteId;
91
+ decryptedEmail = email;
92
+ }
93
+ return {
94
+ inviteId: decryptedInviteId,
95
+ email: decryptedEmail,
96
+ };
97
+ }
98
+ catch (error) {
99
+ console.error(`Error verifying invite token: ${error}`);
100
+ throw new Error("Invalid or expired invite token");
101
+ }
102
+ };
package/package.json CHANGED
@@ -2,7 +2,7 @@
2
2
  "name": "@appconda/nextjs",
3
3
  "homepage": "https://appconda.io/support",
4
4
  "description": "Appconda is an open-source self-hosted backend server that abstract and simplify complex and repetitive development tasks behind a very simple REST API",
5
- "version": "1.0.86",
5
+ "version": "1.0.88",
6
6
  "license": "BSD-3-Clause",
7
7
  "main": "dist/index.js",
8
8
  "types": "dist/index.d.ts",
@@ -24,6 +24,7 @@
24
24
  "jsdelivr": "dist/iife/sdk.js",
25
25
  "unpkg": "dist/iife/sdk.js",
26
26
  "dependencies": {
27
+ "jsonwebtoken": "^9.0.2",
27
28
  "next": "^15.2.3",
28
29
  "next-auth": "^4.24.11",
29
30
  "next-safe-action": "^7.10.4",
@@ -27,7 +27,7 @@ export const actionClient = createSafeActionClient({
27
27
  });
28
28
 
29
29
  export const authenticatedActionClient = actionClient.use(async ({ next }) => {
30
- const session = await getServerSession(authOptions);
30
+ const session = await getServerSession(authOptions());
31
31
  if (!session?.user) {
32
32
  throw new AuthenticationError("Not authenticated");
33
33
  }
@@ -2,5 +2,5 @@ import { getServerSession } from "next-auth"
2
2
  import { authOptions } from "./authOptions";
3
3
 
4
4
  export const auth = async ()=> {
5
- return await getServerSession(authOptions);
5
+ return await getServerSession(authOptions());
6
6
  }
@@ -1,20 +1,20 @@
1
- import type { NextAuthOptions } from "next-auth";
1
+ import type { NextAuthOptions } from "next-auth";
2
2
  import CredentialsProvider from "next-auth/providers/credentials";
3
3
  import { cookies } from "next/headers";
4
4
  import { getAppcondaClient } from "../getAppcondaClient";
5
5
  import { Account } from "../modules/account/service";
6
- //import { getEnv } from "../lib/env";
6
+ import { getEnv } from "../lib/env";
7
7
  import { getSDKForCurrentUser } from "../getSDKForCurrentUser";
8
8
  import { Query } from "../query";
9
9
 
10
- const getEnv = () => {
10
+ /* const getEnv = () => {
11
11
  return {
12
12
  APPCONDA_ENDPOINT: 'process.env.APPCONDA_ENDPOINT',
13
13
  APPCONDA_CLIENT_ENDPOINT: 'process.env.APPCONDA_CLIENT_ENDPOINT',
14
14
  _SERVICE_TOKEN: 'process.env._SERVICE_TOKEN',
15
15
  ENTERPRISE_LICENSE_KEY: 'process.env.ENTERPRISE_LICENSE_KEY',
16
16
  };
17
- };
17
+ }; */
18
18
 
19
19
  export async function signIn({ userName, password }: { userName: string, password: string }) {
20
20
  const adminClient = await getAppcondaClient();
@@ -36,210 +36,219 @@ export async function signIn({ userName, password }: { userName: string, passwor
36
36
 
37
37
  }
38
38
 
39
- export const authOptions: NextAuthOptions = {
40
- providers: [
41
- CredentialsProvider({
42
- id: "credentials",
43
- // The name to display on the sign in form (e.g. "Sign in with...")
44
- name: "Credentials",
45
- // The credentials is used to generate a suitable form on the sign in page.
46
- // You can specify whatever fields you are expecting to be submitted.
47
- // e.g. domain, username, password, 2FA token, etc.
48
- // You can pass any HTML attribute to the <input> tag through the object.
49
- credentials: {
50
- email: {
51
- label: "Email Address",
52
- type: "email",
53
- placeholder: "Your email address",
39
+ export const authOptions = (() => {
40
+ let options = null;
41
+
42
+ return () => {
43
+ if (options == null) {
44
+ options = {
45
+ providers: [
46
+ CredentialsProvider({
47
+ id: "credentials",
48
+ // The name to display on the sign in form (e.g. "Sign in with...")
49
+ name: "Credentials",
50
+ // The credentials is used to generate a suitable form on the sign in page.
51
+ // You can specify whatever fields you are expecting to be submitted.
52
+ // e.g. domain, username, password, 2FA token, etc.
53
+ // You can pass any HTML attribute to the <input> tag through the object.
54
+ credentials: {
55
+ email: {
56
+ label: "Email Address",
57
+ type: "email",
58
+ placeholder: "Your email address",
59
+ },
60
+ password: {
61
+ label: "Password",
62
+ type: "password",
63
+ placeholder: "Your password",
64
+ },
65
+ totpCode: { label: "Two-factor Code", type: "input", placeholder: "Code from authenticator app" },
66
+ backupCode: { label: "Backup Code", type: "input", placeholder: "Two-factor backup code" },
67
+ },
68
+ async authorize(credentials, _req) {
69
+ let user;
70
+ const appcondaSession = await signIn({ userName: credentials?.email as string, password: credentials?.password as string });
71
+
72
+ console.log(credentials);
73
+ /* try {
74
+ user = await prisma.user.findUnique({
75
+ where: {
76
+ email: credentials?.email,
77
+ },
78
+ });
79
+ } catch (e) {
80
+ console.error(e);
81
+ throw Error("Internal server error. Please try again later");
82
+ }
83
+ if (!user || !credentials) {
84
+ throw new Error("Invalid credentials");
85
+ }
86
+ if (!user.password) {
87
+ throw new Error("Invalid credentials");
88
+ }
89
+
90
+ const isValid = await verifyPassword(credentials.password, user.password);
91
+
92
+ if (!isValid) {
93
+ throw new Error("Invalid credentials");
94
+ }
95
+
96
+ if (user.twoFactorEnabled && credentials.backupCode) {
97
+ if (!ENCRYPTION_KEY) {
98
+ console.error("Missing encryption key; cannot proceed with backup code login.");
99
+ throw new Error("Internal Server Error");
100
+ }
101
+
102
+ if (!user.backupCodes) throw new Error("No backup codes found");
103
+
104
+ const backupCodes = JSON.parse(symmetricDecrypt(user.backupCodes, ENCRYPTION_KEY));
105
+
106
+ // check if user-supplied code matches one
107
+ const index = backupCodes.indexOf(credentials.backupCode.replaceAll("-", ""));
108
+ if (index === -1) throw new Error("Invalid backup code");
109
+
110
+ // delete verified backup code and re-encrypt remaining
111
+ backupCodes[index] = null;
112
+ await prisma.user.update({
113
+ where: {
114
+ id: user.id,
115
+ },
116
+ data: {
117
+ backupCodes: symmetricEncrypt(JSON.stringify(backupCodes), ENCRYPTION_KEY),
118
+ },
119
+ });
120
+ } else if (user.twoFactorEnabled) {
121
+ if (!credentials.totpCode) {
122
+ throw new Error("second factor required");
123
+ }
124
+
125
+ if (!user.twoFactorSecret) {
126
+ throw new Error("Internal Server Error");
127
+ }
128
+
129
+ if (!ENCRYPTION_KEY) {
130
+ throw new Error("Internal Server Error");
131
+ }
132
+
133
+ const secret = symmetricDecrypt(user.twoFactorSecret, ENCRYPTION_KEY);
134
+ if (secret.length !== 32) {
135
+ throw new Error("Internal Server Error");
136
+ }
137
+
138
+ const isValidToken = (await import("./totp")).totpAuthenticatorCheck(credentials.totpCode, secret);
139
+ if (!isValidToken) {
140
+ throw new Error("Invalid second factor code");
141
+ }
142
+ } */
143
+
144
+ console.log("asafdf")
145
+
146
+ return {
147
+ id: appcondaSession.userId,
148
+ email: appcondaSession.providerUid,
149
+ emailVerified: true,
150
+ imageUrl: "",
151
+ };
152
+ },
153
+ }),
154
+ CredentialsProvider({
155
+ id: "token",
156
+ // The name to display on the sign in form (e.g. "Sign in with...")
157
+ name: "Token",
158
+ // The credentials is used to generate a suitable form on the sign in page.
159
+ // You can specify whatever fields you are expecting to be submitted.
160
+ // e.g. domain, username, password, 2FA token, etc.
161
+ // You can pass any HTML attribute to the <input> tag through the object.
162
+ credentials: {
163
+ token: {
164
+ label: "Verification Token",
165
+ type: "string",
166
+ },
167
+ },
168
+ async authorize(credentials, _req) {
169
+
170
+ let user;
171
+ /* try {
172
+ if (!credentials?.token) {
173
+ throw new Error("Token not found");
174
+ }
175
+ const { id } = await verifyToken(credentials?.token);
176
+ user = await prisma.user.findUnique({
177
+ where: {
178
+ id: id,
179
+ },
180
+ });
181
+ } catch (e) {
182
+ console.error(e);
183
+ throw new Error("Either a user does not match the provided token or the token is invalid");
184
+ }
185
+
186
+ if (!user) {
187
+ throw new Error("Either a user does not match the provided token or the token is invalid");
188
+ }
189
+
190
+ if (user.emailVerified) {
191
+ throw new Error("Email already verified");
192
+ }
193
+
194
+ user = await updateUser(user.id, { emailVerified: new Date() }); */
195
+
196
+ return user || null;
197
+ },
198
+ }),
199
+ // Conditionally add enterprise SSO providers
200
+ ...(getEnv().ENTERPRISE_LICENSE_KEY ? [] : []),
201
+ ],
202
+ callbacks: {
203
+ async jwt({ token }) {
204
+
205
+ const { users } = await getSDKForCurrentUser();
206
+ const userList = await users.list([Query.equal("email", token.email!)])
207
+
208
+ const user = userList.users[0] ?? {};
209
+
210
+ /* const existingUser = await getUserByEmail(token?.email!);
211
+
212
+ if (!existingUser) {
213
+ return token;
214
+ } */
215
+
216
+ return {
217
+ ...token,
218
+ //@ts-ignore
219
+ profile: { id: user.$id, ...user },
220
+ };
221
+ },
222
+ async session({ session, token }) {
223
+ //@ts-ignore
224
+ session.user.id = token?.id;
225
+ //@ts-ignore
226
+ session.user = token.profile;
227
+
228
+ return session;
229
+ },
230
+ //@ts-ignore
231
+ async signIn({ user, account }: { user: any; account: Account | null }) {
232
+ /* if (account?.provider === "credentials" || account?.provider === "token") {
233
+ // check if user's email is verified or not
234
+ if (!user.emailVerified && !EMAIL_VERIFICATION_DISABLED) {
235
+ throw new Error("Email Verification is Pending");
236
+ }
237
+ return true;
238
+ }
239
+ if (ENTERPRISE_LICENSE_KEY) {
240
+ return handleSSOCallback({ user, account });
241
+ } */
242
+ return true;
243
+ },
54
244
  },
55
- password: {
56
- label: "Password",
57
- type: "password",
58
- placeholder: "Your password",
245
+ pages: {
246
+ signIn: "/auth/login",
247
+ signOut: "/auth/logout",
248
+ error: "/auth/login", // Error code passed in query string as ?error=
59
249
  },
60
- totpCode: { label: "Two-factor Code", type: "input", placeholder: "Code from authenticator app" },
61
- backupCode: { label: "Backup Code", type: "input", placeholder: "Two-factor backup code" },
62
- },
63
- async authorize(credentials, _req) {
64
- let user;
65
- const appcondaSession = await signIn({ userName: credentials?.email as string, password: credentials?.password as string });
66
-
67
- console.log(credentials);
68
- /* try {
69
- user = await prisma.user.findUnique({
70
- where: {
71
- email: credentials?.email,
72
- },
73
- });
74
- } catch (e) {
75
- console.error(e);
76
- throw Error("Internal server error. Please try again later");
77
- }
78
- if (!user || !credentials) {
79
- throw new Error("Invalid credentials");
80
- }
81
- if (!user.password) {
82
- throw new Error("Invalid credentials");
83
- }
84
-
85
- const isValid = await verifyPassword(credentials.password, user.password);
86
-
87
- if (!isValid) {
88
- throw new Error("Invalid credentials");
89
- }
90
-
91
- if (user.twoFactorEnabled && credentials.backupCode) {
92
- if (!ENCRYPTION_KEY) {
93
- console.error("Missing encryption key; cannot proceed with backup code login.");
94
- throw new Error("Internal Server Error");
95
- }
96
-
97
- if (!user.backupCodes) throw new Error("No backup codes found");
98
-
99
- const backupCodes = JSON.parse(symmetricDecrypt(user.backupCodes, ENCRYPTION_KEY));
100
-
101
- // check if user-supplied code matches one
102
- const index = backupCodes.indexOf(credentials.backupCode.replaceAll("-", ""));
103
- if (index === -1) throw new Error("Invalid backup code");
104
-
105
- // delete verified backup code and re-encrypt remaining
106
- backupCodes[index] = null;
107
- await prisma.user.update({
108
- where: {
109
- id: user.id,
110
- },
111
- data: {
112
- backupCodes: symmetricEncrypt(JSON.stringify(backupCodes), ENCRYPTION_KEY),
113
- },
114
- });
115
- } else if (user.twoFactorEnabled) {
116
- if (!credentials.totpCode) {
117
- throw new Error("second factor required");
118
- }
119
-
120
- if (!user.twoFactorSecret) {
121
- throw new Error("Internal Server Error");
122
- }
123
-
124
- if (!ENCRYPTION_KEY) {
125
- throw new Error("Internal Server Error");
126
- }
127
-
128
- const secret = symmetricDecrypt(user.twoFactorSecret, ENCRYPTION_KEY);
129
- if (secret.length !== 32) {
130
- throw new Error("Internal Server Error");
131
- }
132
-
133
- const isValidToken = (await import("./totp")).totpAuthenticatorCheck(credentials.totpCode, secret);
134
- if (!isValidToken) {
135
- throw new Error("Invalid second factor code");
136
- }
137
- } */
138
-
139
- console.log("asafdf")
140
-
141
- return {
142
- id: appcondaSession.userId,
143
- email: appcondaSession.providerUid,
144
- emailVerified: true,
145
- imageUrl: "",
146
- };
147
- },
148
- }),
149
- CredentialsProvider({
150
- id: "token",
151
- // The name to display on the sign in form (e.g. "Sign in with...")
152
- name: "Token",
153
- // The credentials is used to generate a suitable form on the sign in page.
154
- // You can specify whatever fields you are expecting to be submitted.
155
- // e.g. domain, username, password, 2FA token, etc.
156
- // You can pass any HTML attribute to the <input> tag through the object.
157
- credentials: {
158
- token: {
159
- label: "Verification Token",
160
- type: "string",
161
- },
162
- },
163
- async authorize(credentials, _req) {
164
-
165
- let user;
166
- /* try {
167
- if (!credentials?.token) {
168
- throw new Error("Token not found");
169
- }
170
- const { id } = await verifyToken(credentials?.token);
171
- user = await prisma.user.findUnique({
172
- where: {
173
- id: id,
174
- },
175
- });
176
- } catch (e) {
177
- console.error(e);
178
- throw new Error("Either a user does not match the provided token or the token is invalid");
179
- }
180
-
181
- if (!user) {
182
- throw new Error("Either a user does not match the provided token or the token is invalid");
183
- }
184
-
185
- if (user.emailVerified) {
186
- throw new Error("Email already verified");
187
- }
188
-
189
- user = await updateUser(user.id, { emailVerified: new Date() }); */
190
-
191
- return user || null;
192
- },
193
- }),
194
- // Conditionally add enterprise SSO providers
195
- ...(getEnv().ENTERPRISE_LICENSE_KEY ? [] : []),
196
- ],
197
- callbacks: {
198
- async jwt({ token }) {
199
-
200
- const { users } = await getSDKForCurrentUser();
201
- const userList = await users.list([Query.equal("email", token.email!)])
202
-
203
- const user = userList.users[0] ?? {};
204
-
205
- /* const existingUser = await getUserByEmail(token?.email!);
206
-
207
- if (!existingUser) {
208
- return token;
209
- } */
210
-
211
- return {
212
- ...token,
213
- //@ts-ignore
214
- profile: { id: user.$id, ...user },
215
- };
216
- },
217
- async session({ session, token }) {
218
- //@ts-ignore
219
- session.user.id = token?.id;
220
- //@ts-ignore
221
- session.user = token.profile;
222
-
223
- return session;
224
- },
225
- //@ts-ignore
226
- async signIn({ user, account }: { user: any; account: Account | null }) {
227
- /* if (account?.provider === "credentials" || account?.provider === "token") {
228
- // check if user's email is verified or not
229
- if (!user.emailVerified && !EMAIL_VERIFICATION_DISABLED) {
230
- throw new Error("Email Verification is Pending");
231
- }
232
- return true;
233
- }
234
- if (ENTERPRISE_LICENSE_KEY) {
235
- return handleSSOCallback({ user, account });
236
- } */
237
- return true;
238
- },
239
- },
240
- pages: {
241
- signIn: "/auth/login",
242
- signOut: "/auth/logout",
243
- error: "/auth/login", // Error code passed in query string as ?error=
244
- },
245
- };
250
+ }
251
+ }
252
+ return options;
253
+ }
254
+ })();
package/src/index.ts CHANGED
@@ -40,3 +40,4 @@ export { getAppcondaClient } from './getAppcondaClient';
40
40
  export * from './modules';
41
41
  export type { SafeActionFn } from 'next-safe-action';
42
42
  export * from './actions';
43
+ export * from './lib';