@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,103 @@
1
+ import crypto from "crypto";
2
+ import { createCipheriv, createDecipheriv, createHash, createHmac, randomBytes } from "crypto";
3
+ import { getEnv } from "./env";
4
+
5
+
6
+ const ALGORITHM = "aes256";
7
+ const INPUT_ENCODING = "utf8";
8
+ const OUTPUT_ENCODING = "hex";
9
+ const BUFFER_ENCODING = getEnv().ENCRYPTION_KEY!.length === 32 ? "latin1" : "hex";
10
+ const IV_LENGTH = 16; // AES blocksize
11
+
12
+ /**
13
+ *
14
+ * @param text Value to be encrypted
15
+ * @param key Key used to encrypt value must be 32 bytes for AES256 encryption algorithm
16
+ *
17
+ * @returns Encrypted value using key
18
+ */
19
+ export const symmetricEncrypt = (text: string, key: string) => {
20
+ const _key = Buffer.from(key, BUFFER_ENCODING);
21
+ const iv = crypto.randomBytes(IV_LENGTH);
22
+
23
+ // @ts-ignore -- the package needs to be built
24
+ const cipher = crypto.createCipheriv(ALGORITHM, _key, iv);
25
+ let ciphered = cipher.update(text, INPUT_ENCODING, OUTPUT_ENCODING);
26
+ ciphered += cipher.final(OUTPUT_ENCODING);
27
+ const ciphertext = iv.toString(OUTPUT_ENCODING) + ":" + ciphered;
28
+
29
+ return ciphertext;
30
+ };
31
+
32
+ /**
33
+ *
34
+ * @param text Value to decrypt
35
+ * @param key Key used to decrypt value must be 32 bytes for AES256 encryption algorithm
36
+ */
37
+ export const symmetricDecrypt = (text: string, key: string) => {
38
+ const _key = Buffer.from(key, BUFFER_ENCODING);
39
+
40
+ const components = text.split(":");
41
+ const iv_from_ciphertext = Buffer.from(components.shift() || "", OUTPUT_ENCODING);
42
+ // @ts-ignore -- the package needs to be built
43
+ const decipher = crypto.createDecipheriv(ALGORITHM, _key, iv_from_ciphertext);
44
+ let deciphered = decipher.update(components.join(":"), OUTPUT_ENCODING, INPUT_ENCODING);
45
+ deciphered += decipher.final(INPUT_ENCODING);
46
+
47
+ return deciphered;
48
+ };
49
+
50
+ export const getHash = (key: string): string => createHash("sha256").update(key).digest("hex");
51
+
52
+ // create an aes128 encryption function
53
+ export const encryptAES128 = (encryptionKey: string, data: string): string => {
54
+ // @ts-ignore -- the package needs to be built
55
+ const cipher = createCipheriv("aes-128-ecb", Buffer.from(encryptionKey, "base64"), "");
56
+ let encrypted = cipher.update(data, "utf-8", "hex");
57
+ encrypted += cipher.final("hex");
58
+ return encrypted;
59
+ };
60
+ // create an aes128 decryption function
61
+ export const decryptAES128 = (encryptionKey: string, data: string): string => {
62
+ // @ts-ignore -- the package needs to be built
63
+ const cipher = createDecipheriv("aes-128-ecb", Buffer.from(encryptionKey, "base64"), "");
64
+ let decrypted = cipher.update(data, "hex", "utf-8");
65
+ decrypted += cipher.final("utf-8");
66
+ return decrypted;
67
+ };
68
+
69
+ export const generateLocalSignedUrl = (
70
+ fileName: string,
71
+ environmentId: string,
72
+ fileType: string
73
+ ): { signature: string; uuid: string; timestamp: number } => {
74
+ const uuid = randomBytes(16).toString("hex");
75
+ const timestamp = Date.now();
76
+ const data = `${uuid}:${fileName}:${environmentId}:${fileType}:${timestamp}`;
77
+ const signature = createHmac("sha256", getEnv().ENCRYPTION_KEY!).update(data).digest("hex");
78
+ return { signature, uuid, timestamp };
79
+ };
80
+
81
+ export const validateLocalSignedUrl = (
82
+ uuid: string,
83
+ fileName: string,
84
+ environmentId: string,
85
+ fileType: string,
86
+ timestamp: number,
87
+ signature: string,
88
+ secret: string
89
+ ): boolean => {
90
+ const data = `${uuid}:${fileName}:${environmentId}:${fileType}:${timestamp}`;
91
+ const expectedSignature = createHmac("sha256", secret).update(data).digest("hex");
92
+
93
+ if (expectedSignature !== signature) {
94
+ return false;
95
+ }
96
+
97
+ // valid for 5 minutes
98
+ if (Date.now() - timestamp > 1000 * 60 * 5) {
99
+ return false;
100
+ }
101
+
102
+ return true;
103
+ };
package/src/lib/env.ts CHANGED
@@ -16,6 +16,8 @@ export const getEnv = (() => {
16
16
  APPCONDA_CLIENT_ENDPOINT: z.string(),
17
17
  _SERVICE_TOKEN: z.string(),
18
18
  ENTERPRISE_LICENSE_KEY: z.string(),
19
+ NEXTAUTH_SECRET: z.string().min(1),
20
+ ENCRYPTION_KEY: z.string().length(64).or(z.string().length(32)),
19
21
  /* AI_AZURE_LLM_API_KEY: z.string().optional(),
20
22
  AI_AZURE_EMBEDDINGS_DEPLOYMENT_ID: z.string().optional(),
21
23
  AI_AZURE_LLM_DEPLOYMENT_ID: z.string().optional(),
@@ -35,7 +37,7 @@ export const getEnv = (() => {
35
37
  E2E_TESTING: z.enum(["1", "0"]).optional(),
36
38
  EMAIL_AUTH_DISABLED: z.enum(["1", "0"]).optional(),
37
39
  EMAIL_VERIFICATION_DISABLED: z.enum(["1", "0"]).optional(),
38
- ENCRYPTION_KEY: z.string().length(64).or(z.string().length(32)),
40
+
39
41
  ENTERPRISE_LICENSE_KEY: z.string().optional(),
40
42
  FORMBRICKS_ENCRYPTION_KEY: z.string().length(24).or(z.string().length(0)).optional(),
41
43
  GITHUB_ID: z.string().optional(),
@@ -57,7 +59,7 @@ export const getEnv = (() => {
57
59
  INTERCOM_SECRET_KEY: z.string().optional(),
58
60
  IS_FORMBRICKS_CLOUD: z.enum(["1", "0"]).optional(),
59
61
  MAIL_FROM: z.string().email().optional(),
60
- NEXTAUTH_SECRET: z.string().min(1),
62
+
61
63
  NOTION_OAUTH_CLIENT_ID: z.string().optional(),
62
64
  NOTION_OAUTH_CLIENT_SECRET: z.string().optional(),
63
65
  OIDC_CLIENT_ID: z.string().optional(),
@@ -122,6 +124,8 @@ export const getEnv = (() => {
122
124
  APPCONDA_CLIENT_ENDPOINT: process.env.APPCONDA_CLIENT_ENDPOINT,
123
125
  _SERVICE_TOKEN: process.env._SERVICE_TOKEN,
124
126
  ENTERPRISE_LICENSE_KEY: process.env.ENTERPRISE_LICENSE_KEY,
127
+ NEXTAUTH_SECRET: process.env.NEXTAUTH_SECRET,
128
+ ENCRYPTION_KEY: process.env.ENCRYPTION_KEY,
125
129
  },
126
130
  });
127
131
  console.log(env);
@@ -0,0 +1 @@
1
+ export * from "./jwt";
package/src/lib/jwt.ts ADDED
@@ -0,0 +1,113 @@
1
+ import jwt, { JwtPayload } from "jsonwebtoken";
2
+ import { symmetricDecrypt, symmetricEncrypt } from "./crypto";
3
+ import { getEnv } from "./env";
4
+
5
+ export const createToken = (userId: string, userEmail: string, options = {}): string => {
6
+ const encryptedUserId = symmetricEncrypt(userId, getEnv().ENCRYPTION_KEY);
7
+ return jwt.sign({ id: encryptedUserId }, getEnv().NEXTAUTH_SECRET + userEmail, options);
8
+ };
9
+ export const createTokenForLinkSurvey = (surveyId: string, userEmail: string): string => {
10
+ const encryptedEmail = symmetricEncrypt(userEmail, getEnv().ENCRYPTION_KEY);
11
+ return jwt.sign({ email: encryptedEmail }, getEnv().NEXTAUTH_SECRET + surveyId);
12
+ };
13
+
14
+ export const createEmailToken = (email: string): string => {
15
+ const encryptedEmail = symmetricEncrypt(email, getEnv().ENCRYPTION_KEY);
16
+ return jwt.sign({ email: encryptedEmail }, getEnv().NEXTAUTH_SECRET);
17
+ };
18
+
19
+ export const getEmailFromEmailToken = (token: string): string => {
20
+ const payload = jwt.verify(token, getEnv().NEXTAUTH_SECRET) as JwtPayload;
21
+ try {
22
+ // Try to decrypt first (for newer tokens)
23
+ const decryptedEmail = symmetricDecrypt(payload.email, getEnv().ENCRYPTION_KEY);
24
+ return decryptedEmail;
25
+ } catch {
26
+ // If decryption fails, return the original email (for older tokens)
27
+ return payload.email;
28
+ }
29
+ };
30
+
31
+ export const createInviteToken = (inviteId: string, email: string, options = {}): string => {
32
+ const encryptedInviteId = symmetricEncrypt(inviteId, getEnv().ENCRYPTION_KEY);
33
+ const encryptedEmail = symmetricEncrypt(email, getEnv().ENCRYPTION_KEY);
34
+ return jwt.sign({ inviteId: encryptedInviteId, email: encryptedEmail }, getEnv().NEXTAUTH_SECRET, options);
35
+ };
36
+
37
+ export const verifyTokenForLinkSurvey = (token: string, surveyId: string): string | null => {
38
+ try {
39
+ const { email } = jwt.verify(token, getEnv().NEXTAUTH_SECRET + surveyId) as JwtPayload;
40
+ try {
41
+ // Try to decrypt first (for newer tokens)
42
+ const decryptedEmail = symmetricDecrypt(email, getEnv().ENCRYPTION_KEY);
43
+ return decryptedEmail;
44
+ } catch {
45
+ // If decryption fails, return the original email (for older tokens)
46
+ return email;
47
+ }
48
+ } catch (err) {
49
+ return null;
50
+ }
51
+ };
52
+
53
+ export const verifyToken = async (token: string): Promise<JwtPayload> => {
54
+ // First decode to get the ID
55
+ const decoded = jwt.decode(token);
56
+ const payload: JwtPayload = decoded as JwtPayload;
57
+
58
+ const { id } = payload;
59
+ if (!id) {
60
+ throw new Error("Token missing required field: id");
61
+ }
62
+
63
+ // Try to decrypt the ID (for newer tokens), if it fails use the ID as-is (for older tokens)
64
+ let decryptedId: string;
65
+ try {
66
+ decryptedId = symmetricDecrypt(id, getEnv().ENCRYPTION_KEY);
67
+ } catch {
68
+ decryptedId = id;
69
+ }
70
+
71
+ // If no email provided, look up the user
72
+ const foundUser = null;/* await prisma.user.findUnique({
73
+ where: { id: decryptedId },
74
+ }); */
75
+
76
+ if (!foundUser) {
77
+ throw new Error("User not found");
78
+ }
79
+
80
+ const userEmail = foundUser.email;
81
+
82
+ return { id: decryptedId, email: userEmail };
83
+ };
84
+
85
+ export const verifyInviteToken = (token: string): { inviteId: string; email: string } => {
86
+ try {
87
+ const decoded = jwt.decode(token);
88
+ const payload: JwtPayload = decoded as JwtPayload;
89
+
90
+ const { inviteId, email } = payload;
91
+
92
+ let decryptedInviteId: string;
93
+ let decryptedEmail: string;
94
+
95
+ try {
96
+ // Try to decrypt first (for newer tokens)
97
+ decryptedInviteId = symmetricDecrypt(inviteId, getEnv().ENCRYPTION_KEY);
98
+ decryptedEmail = symmetricDecrypt(email, getEnv().ENCRYPTION_KEY);
99
+ } catch {
100
+ // If decryption fails, use original values (for older tokens)
101
+ decryptedInviteId = inviteId;
102
+ decryptedEmail = email;
103
+ }
104
+
105
+ return {
106
+ inviteId: decryptedInviteId,
107
+ email: decryptedEmail,
108
+ };
109
+ } catch (error) {
110
+ console.error(`Error verifying invite token: ${error}`);
111
+ throw new Error("Invalid or expired invite token");
112
+ }
113
+ };