@xenterprises/fastify-xconfig 1.1.9 → 2.0.1

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.
package/src/auth/admin.js DELETED
@@ -1,185 +0,0 @@
1
- import * as jose from "jose";
2
- const isProduction = process.env.NODE_ENV === 'production';
3
-
4
- export async function setupAdminAuth(fastify, options) {
5
- if (options.admin?.active !== false) {
6
- // Get configuration
7
- const projectId = options.admin.stackProjectId || process.env.ADMIN_STACK_PROJECT_ID;
8
- const publishableKey = options.admin.publishableKey || process.env.ADMIN_STACK_PUBLISHABLE_CLIENT_KEY;
9
- const secretKey = options.admin.secretKey || process.env.ADMIN_STACK_SECRET_SERVER_KEY;
10
-
11
- // Rest of the code remains the same
12
- if (!projectId) {
13
- throw new Error("Stack Auth admin project ID is required");
14
- }
15
-
16
- if (!publishableKey || !secretKey) {
17
- throw new Error("Stack Auth admin publishable and secret keys are required");
18
- }
19
-
20
- const adminExcludedPaths = options.admin.excludedPaths || [
21
- "/admin/auth/login",
22
- "/admin/auth/logout",
23
- ];
24
-
25
- // Base URL for Stack Auth API
26
- const stackAuthBaseUrl = `https://api.stack-auth.com/api/v1`;
27
- const jwksUrl = `${stackAuthBaseUrl}/projects/${projectId}/.well-known/jwks.json`;
28
-
29
- // Create JWKS for token verification
30
- const jwks = jose.createRemoteJWKSet(new URL(jwksUrl), {
31
- cooldownDuration: 30000, // 30 seconds between refetches
32
- cacheMaxAge: 1800000, // 5 minutes cache duration
33
- });
34
-
35
- // Helper for Stack Auth API headers
36
- fastify.decorate('getAdminStackAuthHeaders', function (accessType = "server") {
37
- const headers = {
38
- 'Content-Type': 'application/json',
39
- 'Accept': 'application/json',
40
- 'X-Stack-Access-Type': accessType,
41
- 'X-Stack-Project-Id': projectId,
42
- };
43
-
44
- if (accessType === "client") {
45
- headers['X-Stack-Publishable-Client-Key'] = publishableKey;
46
- } else if (accessType === "server") {
47
- headers['X-Stack-Secret-Server-Key'] = secretKey;
48
- }
49
-
50
- return headers;
51
- });
52
-
53
- // JWT verification helper
54
- fastify.decorate('verifyAdminStackJWT', async function (accessToken) {
55
- try {
56
- // Add validation to ensure accessToken is a valid string
57
- if (!accessToken || typeof accessToken !== 'string') {
58
- fastify.log.error('Invalid admin token format: token must be a non-empty string');
59
- return null;
60
- }
61
-
62
- const { payload } = await jose.jwtVerify(accessToken, jwks);
63
-
64
- // Verify the payload has expected properties
65
- if (!payload || !payload.sub) {
66
- fastify.log.error('Invalid admin token payload: missing required claims');
67
- return null;
68
- }
69
-
70
- return payload;
71
- } catch (error) {
72
- fastify.log.error(error);
73
- return null;
74
- }
75
- });
76
-
77
- // Admin authentication hook
78
- fastify.addHook("onRequest", async (request, reply) => {
79
- const url = request.url;
80
-
81
- // Skip authentication for excluded paths
82
- if (adminExcludedPaths.some((path) => url.startsWith(path))) {
83
- return;
84
- }
85
-
86
- if (url.startsWith("/admin")) {
87
- try {
88
- // Get token from header
89
- const authHeader = request.headers.authorization;
90
- if (!authHeader || !authHeader.startsWith("Bearer ")) {
91
- return reply.code(401).send({ error: "Admin access token required" });
92
- }
93
-
94
- // Verify token
95
- const token = authHeader.slice(7);
96
- const payload = await fastify.verifyAdminStackJWT(token);
97
-
98
- if (!payload) {
99
- return reply.code(401).send({ error: "Invalid admin token" });
100
- }
101
-
102
- // Set admin info on request
103
- request.admin = payload;
104
- request.adminAuth = { id: payload.sub };
105
- } catch (err) {
106
- return reply.code(401).send({ error: "Admin authentication failed" });
107
- }
108
- }
109
- });
110
-
111
- // Admin login endpoint
112
- fastify.post("/admin/auth/login", async (req, reply) => {
113
- try {
114
- const { email, password } = req.body;
115
-
116
- if (!email || !password) {
117
- return reply.code(400).send({ error: "Email and password required" });
118
- }
119
-
120
- // Call Stack Auth API for password sign-in
121
- const response = await fetch(
122
- `${stackAuthBaseUrl}/auth/password/sign-in`,
123
- {
124
- method: 'POST',
125
- headers: fastify.getAdminStackAuthHeaders("server"),
126
- body: JSON.stringify({ email, password })
127
- }
128
- );
129
-
130
- const data = await response.json().catch(() => ({}));
131
-
132
- if (!response.ok) {
133
- return reply.code(response.status || 400).send({
134
- error: data.message || "Authentication failed"
135
- });
136
- }
137
-
138
- // Check if we have the expected response properties
139
- if (!data.access_token || !data.refresh_token || !data.user_id) {
140
- return reply.code(500).send({ error: "Invalid response from authentication service" });
141
- }
142
-
143
- // Verify token
144
- const payload = await fastify.verifyAdminStackJWT(data.access_token);
145
- if (!payload) {
146
- return reply.code(401).send({ error: "Invalid token received" });
147
- }
148
-
149
- reply.send({
150
- accessToken: data.access_token,
151
- refreshToken: data.refresh_token,
152
- admin: payload,
153
- adminId: data.user_id
154
- });
155
- } catch (err) {
156
- fastify.log.error(err);
157
- reply.code(500).send({ error: "Internal server error" });
158
- }
159
- });
160
-
161
- // Admin info endpoint
162
- fastify.get("/admin/auth/me", async (req, reply) => {
163
- reply.send(req.admin || { authenticated: false });
164
- });
165
-
166
- // Token verification endpoint
167
- fastify.post("/admin/auth/verify", async (req, reply) => {
168
- const { token } = req.body;
169
-
170
- if (!token) {
171
- return reply.code(400).send({ error: "Token required" });
172
- }
173
-
174
- const payload = await fastify.verifyAdminStackJWT(token);
175
-
176
- if (!payload) {
177
- return reply.code(401).send({ valid: false });
178
- }
179
-
180
- reply.send({ valid: true, admin: payload });
181
- });
182
-
183
- console.info(" ✅ Auth Admin Enabled");
184
- }
185
- }
@@ -1,179 +0,0 @@
1
- import * as jose from "jose";
2
-
3
- export async function setupAuth(fastify, options) {
4
- if (options.user?.active !== false) {
5
- // Get configuration
6
- const projectId = options.user.portalStackProjectId || process.env.STACK_PROJECT_ID;
7
- const publishableKey = options.user.publishableKey || process.env.STACK_PUBLISHABLE_CLIENT_KEY;
8
- const secretKey = options.user.secretKey || process.env.STACK_SECRET_SERVER_KEY;
9
-
10
- if (!projectId) {
11
- throw new Error("Stack Auth project ID is required");
12
- }
13
-
14
- if (!publishableKey || !secretKey) {
15
- throw new Error("Stack Auth publishable and secret keys are required");
16
- }
17
-
18
- const userExcludedPaths = options.user.excludedPaths || [
19
- "/portal/auth/login",
20
- "/portal/auth/logout",
21
- "/portal/auth/register",
22
- "/portal/auth/forgot-password",
23
- "/portal/auth/reset-password"
24
- ];
25
-
26
- // Base URL for Stack Auth API
27
- const stackAuthBaseUrl = `https://api.stack-auth.com/api/v1`;
28
- const jwksUrl = `${stackAuthBaseUrl}/projects/${projectId}/.well-known/jwks.json`;
29
-
30
- // Create JWKS for token verification
31
- const jwks = jose.createRemoteJWKSet(new URL(jwksUrl), {
32
- cooldownDuration: 30000, // 30 seconds between refetches
33
- cacheMaxAge: 1800000, // 5 minutes cache duration
34
- });
35
-
36
- // Helper for Stack Auth API headers
37
- fastify.decorate('getStackAuthHeaders', function (accessType = "server") {
38
- const headers = {
39
- 'Content-Type': 'application/json',
40
- 'Accept': 'application/json',
41
- 'X-Stack-Access-Type': accessType,
42
- 'X-Stack-Project-Id': projectId,
43
- };
44
-
45
- if (accessType === "client") {
46
- headers['X-Stack-Publishable-Client-Key'] = publishableKey;
47
- } else if (accessType === "server") {
48
- headers['X-Stack-Secret-Server-Key'] = secretKey;
49
- }
50
-
51
- return headers;
52
- });
53
-
54
- // JWT verification helper
55
- fastify.decorate('verifyStackJWT', async function (accessToken) {
56
- try {
57
- const { payload } = await jose.jwtVerify(accessToken, jwks);
58
- return payload;
59
- } catch (error) {
60
- fastify.log.error(error);
61
- return null;
62
- }
63
- });
64
-
65
- // API URL helper
66
- fastify.decorate('getStackAuthApiUrl', function () {
67
- return stackAuthBaseUrl;
68
- });
69
-
70
- // Authentication middleware
71
- fastify.addHook("onRequest", async (request, reply) => {
72
- const url = request.url;
73
-
74
- // Skip excluded paths
75
- if (userExcludedPaths.some(path => url.startsWith(path))) {
76
- return;
77
- }
78
-
79
- if (url.startsWith("/portal")) {
80
- try {
81
- // Get token from header
82
- const authHeader = request.headers.authorization;
83
- if (!authHeader || !authHeader.startsWith("Bearer ")) {
84
- return reply.code(401).send({ error: "Access token required" });
85
- }
86
-
87
- // Verify token
88
- const token = authHeader.slice(7);
89
- const payload = await fastify.verifyStackJWT(token);
90
-
91
- if (!payload) {
92
- return reply.code(401).send({ error: "Invalid token" });
93
- }
94
-
95
- // Set user info on request
96
- request.user = payload;
97
- request.userAuth = { id: payload.sub };
98
- } catch (err) {
99
- return reply.code(401).send({ error: "Authentication failed" });
100
- }
101
- }
102
- });
103
-
104
- // Login endpoint
105
- fastify.post("/portal/auth/login", async (req, reply) => {
106
- try {
107
- const { email, password } = req.body;
108
-
109
- if (!email || !password) {
110
- return reply.code(400).send({ error: "Email and password required" });
111
- }
112
-
113
- // Call Stack Auth API for password sign-in using native fetch
114
- const response = await fetch(
115
- `${stackAuthBaseUrl}/auth/password/sign-in`,
116
- {
117
- method: 'POST',
118
- headers: fastify.getStackAuthHeaders("server"),
119
- body: JSON.stringify({ email, password })
120
- }
121
- );
122
-
123
- const data = await response.json().catch(() => ({}));
124
-
125
- if (!response.ok) {
126
- return reply.code(response.status || 400).send({
127
- error: data.message || "Authentication failed"
128
- });
129
- }
130
-
131
- // Check if we have the expected response properties
132
- if (!data.access_token || !data.refresh_token || !data.user_id) {
133
- return reply.code(500).send({ error: "Invalid response from authentication service" });
134
- }
135
-
136
- // Verify token
137
- const payload = await fastify.verifyStackJWT(data.access_token);
138
- if (!payload) {
139
- return reply.code(401).send({ error: "Invalid token received" });
140
- }
141
-
142
- reply.send({
143
- accessToken: data.access_token,
144
- refreshToken: data.refresh_token,
145
- user: payload,
146
- userId: data.user_id
147
- });
148
- } catch (err) {
149
- fastify.log.error(err);
150
- reply.code(500).send({ error: "Internal server error" });
151
- }
152
- });
153
-
154
-
155
- // User info endpoint
156
- fastify.get("/portal/auth/me", async (req, reply) => {
157
- reply.send(req.user || { authenticated: false });
158
- });
159
-
160
- // Token verification endpoint
161
- fastify.post("/portal/auth/verify", async (req, reply) => {
162
- const { token } = req.body;
163
-
164
- if (!token) {
165
- return reply.code(400).send({ error: "Token required" });
166
- }
167
-
168
- const payload = await fastify.verifyStackJWT(token);
169
-
170
- if (!payload) {
171
- return reply.code(401).send({ valid: false });
172
- }
173
-
174
- reply.send({ valid: true, user: payload });
175
- });
176
-
177
- console.info(" ✅ Auth User Enabled");
178
- }
179
- }
@@ -1,98 +0,0 @@
1
- import { v2 as Cloudinary } from "cloudinary";
2
-
3
- export async function setupCloudinary(fastify, options) {
4
-
5
- if (options.active !== false) {
6
- if (
7
- !options.cloudName ||
8
- !options.apiKey ||
9
- !options.apiSecret
10
- ) {
11
- throw new Error(
12
- "Cloudinary cloudName, apiKey, and apiSecret must be provided."
13
- );
14
- }
15
-
16
- Cloudinary.config({
17
- cloud_name: options.cloudName,
18
- api_key: options.apiKey,
19
- api_secret: options.apiSecret,
20
- },
21
- );
22
-
23
- fastify.decorate('cloudinary', {
24
- upload: async (fileStream, options = {}) => {
25
- return new Promise((resolve, reject) => {
26
- if (options.folder) {
27
- options.folder = options.folder || options.folder;
28
- }
29
- options.resource_type = options.resource_type || 'auto';
30
- options.timestamp = Math.floor(Date.now() / 1000); // Add timestamp to options
31
- options.use_filename = options.use_filename !== undefined ? options.use_filename : true;
32
- options.unique_filename = options.unique_filename !== undefined ? options.unique_filename : true;
33
-
34
- const uploadStream = Cloudinary.uploader.upload_stream(options, (error, result) => {
35
- if (error) {
36
- fastify.log.error("Cloudinary upload failed:", error);
37
- reject(new Error(`Failed to upload to Cloudinary: ${JSON.stringify(error)}`));
38
- } else {
39
- resolve(result); // Resolve with the result from Cloudinary
40
- }
41
- });
42
-
43
- fileStream.pipe(uploadStream)
44
- .on('error', (streamError) => {
45
- fastify.log.error("Stream error:", streamError);
46
- reject(new Error(`Stream error during Cloudinary upload: ${streamError.message}`));
47
- })
48
- .on('end', () => {
49
- fastify.log.info("Stream ended successfully.");
50
- });
51
- });
52
- },
53
-
54
- uploadLarge: async (fileStream, options = {}) => {
55
- return new Promise((resolve, reject) => {
56
- if (options.folder) {
57
- options.folder = options.folder || options.folder;
58
- }
59
- options.resource_type = options.resource_type || 'auto';
60
- options.timestamp = Math.floor(Date.now() / 1000);
61
- options.use_filename = options.use_filename !== undefined ? options.use_filename : true;
62
- options.unique_filename = options.unique_filename !== undefined ? options.unique_filename : true;
63
- options.overwrite = options.overwrite !== undefined ? options.overwrite : false;
64
-
65
- const uploadStream = Cloudinary.uploader.upload_stream(options, (error, result) => {
66
- if (error) {
67
- fastify.log.error("Cloudinary upload failed:", error);
68
- reject(new Error(`Failed to upload to Cloudinary: ${JSON.stringify(error)}`));
69
- } else {
70
- resolve(result);
71
- }
72
- });
73
-
74
- fileStream.pipe(uploadStream)
75
- .on('error', (streamError) => {
76
- fastify.log.error("Stream error:", streamError);
77
- reject(new Error(`Stream error during Cloudinary upload: ${streamError.message}`));
78
- })
79
- .on('end', () => {
80
- fastify.log.info("Stream ended successfully.");
81
- });
82
- });
83
- },
84
-
85
- delete: async (publicId) => {
86
- try {
87
- const response = await Cloudinary.uploader.destroy(publicId);
88
- return response;
89
- } catch (error) {
90
- fastify.log.error("Cloudinary delete failed:", error);
91
- throw new Error("Failed to delete from Cloudinary.");
92
- }
93
- }
94
- });
95
-
96
- console.info(" ✅ Cloudinary Enabled");
97
- }
98
- }
@@ -1,43 +0,0 @@
1
- export async function setupGeocode(fastify, options) {
2
- if (options.active !== false) {
3
- if (!options.apiKey) {
4
- throw new Error("Geocode API key must be provided.");
5
- }
6
- const geocodioEndpoint = 'https://api.geocod.io/v1.7/geocode';
7
- const geocodioApiKey = options.apiKey;
8
-
9
- fastify.decorate('geocode', {
10
- // Method to get lat/long and county from a zip code
11
- async getLatLongByZip(zipCode) {
12
- try {
13
- const url = `${geocodioEndpoint}?q=${zipCode}&fields=cd,stateleg&api_key=${geocodioApiKey}`;
14
- const response = await fetch(url);
15
- const result = await response.json();
16
-
17
- if (result.results && result.results.length > 0) {
18
- const location = result.results[0].location;
19
- const addressComponents = result.results[0].address_components;
20
-
21
- return {
22
- zip: zipCode,
23
- lat: location.lat,
24
- lng: location.lng,
25
- city: addressComponents.city,
26
- county: addressComponents.county,
27
- country: addressComponents.country,
28
- state: addressComponents.state,
29
- addressComponents: addressComponents
30
- };
31
- } else {
32
- throw new Error('No results found for the provided zip code.');
33
- }
34
- } catch (error) {
35
- fastify.log.error('Failed to fetch geolocation data:', error);
36
- throw new Error('Failed to fetch geolocation data.');
37
- }
38
- }
39
- });
40
-
41
- console.info(' ✅ Geocodio Enabled');
42
- }
43
- }
@@ -1,58 +0,0 @@
1
- import Sendgrid from '@sendgrid/mail';
2
- import sgClient from '@sendgrid/client';
3
- export async function setupSendgrid(fastify, options) {
4
- if (options.active !== false) {
5
- if (!options.apiKey)
6
- throw new Error("SendGrid API key must be provided.");
7
-
8
- Sendgrid.setApiKey(options.apiKey);
9
- sgClient.setApiKey(options.apiKeyEmailValidation);
10
- // Decorator to group SendGrid-related methods under fastify.sendGrid
11
- fastify.decorate('sendgrid', {
12
- sendEmail: async (to, subject, templateId, dynamicTemplateData) => {
13
- try {
14
-
15
- const msg = {
16
- to: to,
17
- from: options.fromEmail,
18
- subject: subject,
19
- templateId: templateId,
20
- dynamicTemplateData: { ...dynamicTemplateData, subject: subject },
21
- };
22
- await Sendgrid.send(msg);
23
- return true;
24
- } catch (error) {
25
- fastify.log.error("SendGrid send email failed:", error);
26
- throw new Error("Failed to send email.");
27
- }
28
- },
29
- validateEmail: async (email) => {
30
- const data = {
31
- email: email,
32
- // source: 'signup',
33
- };
34
-
35
- const request = {
36
- url: `/v3/validations/email`,
37
- method: 'POST',
38
- body: data,
39
- };
40
-
41
- try {
42
- const [response, body] = await sgClient.request(request);
43
- console.log(body)
44
- if (response.statusCode === 200) {
45
- return body?.result; // Return the validation result
46
- } else {
47
- throw new Error(body.errors ? body.errors.map(err => err.message).join(', ') : 'Failed to validate email.');
48
- }
49
- } catch (error) {
50
- fastify.log.error('SendGrid email validation failed:', error);
51
- throw new Error('Failed to validate email.');
52
- }
53
- }
54
- });
55
-
56
- console.info(" ✅ SendGrid Enabled");
57
- }
58
- }