@xenterprises/fastify-xconfig 1.0.0 → 1.0.2

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 (55) hide show
  1. package/.github/workflows/ci.yml +19 -0
  2. package/.taprc +3 -0
  3. package/README.md +18 -171
  4. package/dist/utils/randomUUID.d.ts +1 -1
  5. package/dist/xConfig.d.ts +2 -1
  6. package/dist/xConfig.js +7 -2
  7. package/dist/xConfig.js.map +1 -1
  8. package/example.ts +13 -0
  9. package/package.json +41 -22
  10. package/src/xConfig.ts +20 -0
  11. package/test/index.test-d.ts +13 -0
  12. package/test/index.test.js +14 -0
  13. package/test/xConfig.js +115 -0
  14. package/tsconfig.json +16 -0
  15. package/server/app.js +0 -85
  16. package/src/auth/admin.js +0 -181
  17. package/src/auth/portal.js +0 -177
  18. package/src/integrations/cloudinary.js +0 -98
  19. package/src/integrations/geocode.js +0 -43
  20. package/src/integrations/prisma.js +0 -30
  21. package/src/integrations/sendgrid.js +0 -58
  22. package/src/integrations/twilio.js +0 -146
  23. package/src/lifecycle/xFastifyAfter.js +0 -27
  24. package/src/middleware/bugsnag.js +0 -10
  25. package/src/middleware/cors.js +0 -10
  26. package/src/middleware/fancyErrors.js +0 -26
  27. package/src/middleware/multipart.js +0 -6
  28. package/src/middleware/rateLimit.js +0 -6
  29. package/src/middleware/underPressure.js +0 -6
  30. package/src/utils/colorize.js +0 -37
  31. package/src/utils/cookie.js +0 -5
  32. package/src/utils/formatBytes.js +0 -16
  33. package/src/utils/health.js +0 -126
  34. package/src/utils/xEcho.js +0 -12
  35. package/src/utils/xSlugify.js +0 -20
  36. package/src/utils/xUUID.js +0 -14
  37. package/src/xConfig.js +0 -117
  38. package/test/index.js +0 -17
  39. package/xConfigReference.js +0 -1526
  40. package/xConfigWorkingList.js +0 -720
  41. /package/{ts-reference → src}/integrations/cloudinary.ts +0 -0
  42. /package/{ts-reference → src}/integrations/prisma.ts +0 -0
  43. /package/{ts-reference → src}/integrations/sendgrid.ts +0 -0
  44. /package/{ts-reference → src}/integrations/stripe.ts +0 -0
  45. /package/{ts-reference → src}/integrations/twilio.ts +0 -0
  46. /package/{ts-reference → src}/middleware/bugsnag.ts +0 -0
  47. /package/{ts-reference → src}/middleware/cors.ts +0 -0
  48. /package/{ts-reference → src}/middleware/errorHandler.ts +0 -0
  49. /package/{ts-reference → src}/middleware/multipart.ts +0 -0
  50. /package/{ts-reference → src}/middleware/rateLimit.ts +0 -0
  51. /package/{ts-reference → src}/middleware/underPressure.ts +0 -0
  52. /package/{ts-reference → src}/utils/colorize.ts +0 -0
  53. /package/{ts-reference → src}/utils/formatBytes.ts +0 -0
  54. /package/{ts-reference → src}/utils/randomUUID.ts +0 -0
  55. /package/{ts-reference → src}/utils/statAsync.ts +0 -0
package/src/auth/admin.js DELETED
@@ -1,181 +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
- if (!projectId) {
12
- throw new Error("Stack Auth admin project ID is required");
13
- }
14
-
15
- if (!publishableKey || !secretKey) {
16
- throw new Error("Stack Auth admin publishable and secret keys are required");
17
- }
18
-
19
- const adminExcludedPaths = options.admin.excludedPaths || [
20
- "/admin/auth/login",
21
- "/admin/auth/logout",
22
- ];
23
-
24
- // Base URL for Stack Auth API
25
- const stackAuthBaseUrl = `https://api.stack-auth.com/api/v1`;
26
- const jwksUrl = `${stackAuthBaseUrl}/projects/${projectId}/.well-known/jwks.json`;
27
-
28
- // Create JWKS for token verification
29
- const jwks = jose.createRemoteJWKSet(new URL(jwksUrl));
30
-
31
- // Helper for Stack Auth API headers
32
- fastify.decorate('getAdminStackAuthHeaders', function (accessType = "server") {
33
- const headers = {
34
- 'Content-Type': 'application/json',
35
- 'Accept': 'application/json',
36
- 'X-Stack-Access-Type': accessType,
37
- 'X-Stack-Project-Id': projectId,
38
- };
39
-
40
- if (accessType === "client") {
41
- headers['X-Stack-Publishable-Client-Key'] = publishableKey;
42
- } else if (accessType === "server") {
43
- headers['X-Stack-Secret-Server-Key'] = secretKey;
44
- }
45
-
46
- return headers;
47
- });
48
-
49
- // JWT verification helper
50
- fastify.decorate('verifyAdminStackJWT', async function (accessToken) {
51
- try {
52
- // Add validation to ensure accessToken is a valid string
53
- if (!accessToken || typeof accessToken !== 'string') {
54
- fastify.log.error('Invalid admin token format: token must be a non-empty string');
55
- return null;
56
- }
57
-
58
- const { payload } = await jose.jwtVerify(accessToken, jwks);
59
-
60
- // Verify the payload has expected properties
61
- if (!payload || !payload.sub) {
62
- fastify.log.error('Invalid admin token payload: missing required claims');
63
- return null;
64
- }
65
-
66
- return payload;
67
- } catch (error) {
68
- fastify.log.error(error);
69
- return null;
70
- }
71
- });
72
-
73
- // Admin authentication hook
74
- fastify.addHook("onRequest", async (request, reply) => {
75
- const url = request.url;
76
-
77
- // Skip authentication for excluded paths
78
- if (adminExcludedPaths.some((path) => url.startsWith(path))) {
79
- return;
80
- }
81
-
82
- if (url.startsWith("/admin")) {
83
- try {
84
- // Get token from header
85
- const authHeader = request.headers.authorization;
86
- if (!authHeader || !authHeader.startsWith("Bearer ")) {
87
- return reply.code(401).send({ error: "Admin access token required" });
88
- }
89
-
90
- // Verify token
91
- const token = authHeader.slice(7);
92
- const payload = await fastify.verifyAdminStackJWT(token);
93
-
94
- if (!payload) {
95
- return reply.code(401).send({ error: "Invalid admin token" });
96
- }
97
-
98
- // Set admin info on request
99
- request.admin = payload;
100
- request.adminAuth = { id: payload.sub };
101
- } catch (err) {
102
- return reply.code(401).send({ error: "Admin authentication failed" });
103
- }
104
- }
105
- });
106
-
107
- // Admin login endpoint
108
- fastify.post("/admin/auth/login", async (req, reply) => {
109
- try {
110
- const { email, password } = req.body;
111
-
112
- if (!email || !password) {
113
- return reply.code(400).send({ error: "Email and password required" });
114
- }
115
-
116
- // Call Stack Auth API for password sign-in
117
- const response = await fetch(
118
- `${stackAuthBaseUrl}/auth/password/sign-in`,
119
- {
120
- method: 'POST',
121
- headers: fastify.getAdminStackAuthHeaders("server"),
122
- body: JSON.stringify({ email, password })
123
- }
124
- );
125
-
126
- const data = await response.json().catch(() => ({}));
127
-
128
- if (!response.ok) {
129
- return reply.code(response.status || 400).send({
130
- error: data.message || "Authentication failed"
131
- });
132
- }
133
-
134
- // Check if we have the expected response properties
135
- if (!data.access_token || !data.refresh_token || !data.user_id) {
136
- return reply.code(500).send({ error: "Invalid response from authentication service" });
137
- }
138
-
139
- // Verify token
140
- const payload = await fastify.verifyAdminStackJWT(data.access_token);
141
- if (!payload) {
142
- return reply.code(401).send({ error: "Invalid token received" });
143
- }
144
-
145
- reply.send({
146
- accessToken: data.access_token,
147
- refreshToken: data.refresh_token,
148
- admin: payload,
149
- adminId: data.user_id
150
- });
151
- } catch (err) {
152
- fastify.log.error(err);
153
- reply.code(500).send({ error: "Internal server error" });
154
- }
155
- });
156
-
157
- // Admin info endpoint
158
- fastify.get("/admin/auth/me", async (req, reply) => {
159
- reply.send(req.admin || { authenticated: false });
160
- });
161
-
162
- // Token verification endpoint
163
- fastify.post("/admin/auth/verify", async (req, reply) => {
164
- const { token } = req.body;
165
-
166
- if (!token) {
167
- return reply.code(400).send({ error: "Token required" });
168
- }
169
-
170
- const payload = await fastify.verifyAdminStackJWT(token);
171
-
172
- if (!payload) {
173
- return reply.code(401).send({ valid: false });
174
- }
175
-
176
- reply.send({ valid: true, admin: payload });
177
- });
178
-
179
- console.info(" ✅ Auth Admin Enabled");
180
- }
181
- }
@@ -1,177 +0,0 @@
1
- import * as jose from "jose";
2
- import fetch from "node-fetch";
3
-
4
- export async function setupAuth(fastify, options) {
5
- if (options.user?.active !== false) {
6
- // Get configuration
7
- const projectId = options.user.portalStackProjectId || process.env.STACK_PROJECT_ID;
8
- const publishableKey = options.user.publishableKey || process.env.STACK_PUBLISHABLE_CLIENT_KEY;
9
- const secretKey = options.user.secretKey || process.env.STACK_SECRET_SERVER_KEY;
10
-
11
- if (!projectId) {
12
- throw new Error("Stack Auth project ID is required");
13
- }
14
-
15
- if (!publishableKey || !secretKey) {
16
- throw new Error("Stack Auth publishable and secret keys are required");
17
- }
18
-
19
- const userExcludedPaths = options.user.excludedPaths || [
20
- "/portal/auth/login",
21
- "/portal/auth/logout",
22
- "/portal/auth/register",
23
- "/portal/auth/forgot-password",
24
- "/portal/auth/reset-password"
25
- ];
26
-
27
- // Base URL for Stack Auth API
28
- const stackAuthBaseUrl = `https://api.stack-auth.com/api/v1`;
29
- const jwksUrl = `${stackAuthBaseUrl}/projects/${projectId}/.well-known/jwks.json`;
30
-
31
- // Create JWKS for token verification
32
- const jwks = jose.createRemoteJWKSet(new URL(jwksUrl));
33
-
34
- // Helper for Stack Auth API headers
35
- fastify.decorate('getStackAuthHeaders', function (accessType = "server") {
36
- const headers = {
37
- 'Content-Type': 'application/json',
38
- 'Accept': 'application/json',
39
- 'X-Stack-Access-Type': accessType,
40
- 'X-Stack-Project-Id': projectId,
41
- };
42
-
43
- if (accessType === "client") {
44
- headers['X-Stack-Publishable-Client-Key'] = publishableKey;
45
- } else if (accessType === "server") {
46
- headers['X-Stack-Secret-Server-Key'] = secretKey;
47
- }
48
-
49
- return headers;
50
- });
51
-
52
- // JWT verification helper
53
- fastify.decorate('verifyStackJWT', async function (accessToken) {
54
- try {
55
- const { payload } = await jose.jwtVerify(accessToken, jwks);
56
- return payload;
57
- } catch (error) {
58
- fastify.log.error(error);
59
- return null;
60
- }
61
- });
62
-
63
- // API URL helper
64
- fastify.decorate('getStackAuthApiUrl', function () {
65
- return stackAuthBaseUrl;
66
- });
67
-
68
- // Authentication middleware
69
- fastify.addHook("onRequest", async (request, reply) => {
70
- const url = request.url;
71
-
72
- // Skip excluded paths
73
- if (userExcludedPaths.some(path => url.startsWith(path))) {
74
- return;
75
- }
76
-
77
- if (url.startsWith("/portal")) {
78
- try {
79
- // Get token from header
80
- const authHeader = request.headers.authorization;
81
- if (!authHeader || !authHeader.startsWith("Bearer ")) {
82
- return reply.code(401).send({ error: "Access token required" });
83
- }
84
-
85
- // Verify token
86
- const token = authHeader.slice(7);
87
- const payload = await fastify.verifyStackJWT(token);
88
-
89
- if (!payload) {
90
- return reply.code(401).send({ error: "Invalid token" });
91
- }
92
-
93
- // Set user info on request
94
- request.user = payload;
95
- request.userAuth = { id: payload.sub };
96
- } catch (err) {
97
- return reply.code(401).send({ error: "Authentication failed" });
98
- }
99
- }
100
- });
101
-
102
- // Login endpoint
103
- fastify.post("/portal/auth/login", async (req, reply) => {
104
- try {
105
- const { email, password } = req.body;
106
-
107
- if (!email || !password) {
108
- return reply.code(400).send({ error: "Email and password required" });
109
- }
110
-
111
- // Call Stack Auth API for password sign-in
112
- const response = await fetch(
113
- `${stackAuthBaseUrl}/auth/password/sign-in`,
114
- {
115
- method: 'POST',
116
- headers: fastify.getStackAuthHeaders("server"),
117
- body: JSON.stringify({ email, password })
118
- }
119
- );
120
-
121
- const data = await response.json().catch(() => ({}));
122
-
123
- if (!response.ok) {
124
- return reply.code(response.status || 400).send({
125
- error: data.message || "Authentication failed"
126
- });
127
- }
128
-
129
- // Check if we have the expected response properties
130
- if (!data.access_token || !data.refresh_token || !data.user_id) {
131
- return reply.code(500).send({ error: "Invalid response from authentication service" });
132
- }
133
-
134
- // Verify token
135
- const payload = await fastify.verifyStackJWT(data.access_token);
136
- if (!payload) {
137
- return reply.code(401).send({ error: "Invalid token received" });
138
- }
139
-
140
- reply.send({
141
- accessToken: data.access_token,
142
- refreshToken: data.refresh_token,
143
- user: payload,
144
- userId: data.user_id
145
- });
146
- } catch (err) {
147
- fastify.log.error(err);
148
- reply.code(500).send({ error: "Internal server error" });
149
- }
150
- });
151
-
152
-
153
- // User info endpoint
154
- fastify.get("/portal/auth/me", async (req, reply) => {
155
- reply.send(req.user || { authenticated: false });
156
- });
157
-
158
- // Token verification endpoint
159
- fastify.post("/portal/auth/verify", async (req, reply) => {
160
- const { token } = req.body;
161
-
162
- if (!token) {
163
- return reply.code(400).send({ error: "Token required" });
164
- }
165
-
166
- const payload = await fastify.verifyStackJWT(token);
167
-
168
- if (!payload) {
169
- return reply.code(401).send({ valid: false });
170
- }
171
-
172
- reply.send({ valid: true, user: payload });
173
- });
174
-
175
- console.info(" ✅ Auth User Enabled");
176
- }
177
- }
@@ -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,30 +0,0 @@
1
-
2
- import { PrismaClient } from "@prisma/client";
3
- export async function setupPrisma(fastify, options) {
4
- if (options.active !== false) {
5
- delete options.active;
6
- const prisma = new PrismaClient(options);
7
-
8
- // Connect to the database
9
- await prisma.$connect();
10
-
11
- // Decorate Fastify instance with Prisma Client
12
- fastify.decorate("prisma", prisma);
13
-
14
- // Disconnect Prisma Client when Fastify closes
15
- fastify.addHook("onClose", async () => {
16
- await fastify.prisma.$disconnect();
17
- });
18
-
19
- console.info(" ✅ Prisma Enabled");
20
- }
21
- /*
22
- ===== Ensure Proper Cleanup on Server Shutdown =====
23
- */
24
- fastify.addHook("onClose", async () => {
25
- if (fastify.prisma) {
26
- await fastify.prisma.$disconnect();
27
- }
28
- // Add additional cleanup for other services if necessary
29
- });
30
- }
@@ -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
- }