@xenterprises/fastify-xconfig 1.0.1 → 1.1.0

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 (99) hide show
  1. package/README.md +171 -18
  2. package/dist/integrations/cloudinary.d.ts +1 -0
  3. package/dist/integrations/cloudinary.js +25 -0
  4. package/dist/integrations/cloudinary.js.map +1 -0
  5. package/dist/integrations/prisma.d.ts +1 -0
  6. package/dist/integrations/prisma.js +13 -0
  7. package/dist/integrations/prisma.js.map +1 -0
  8. package/dist/integrations/sendgrid.d.ts +1 -0
  9. package/dist/integrations/sendgrid.js +22 -0
  10. package/dist/integrations/sendgrid.js.map +1 -0
  11. package/dist/integrations/stripe.d.ts +1 -0
  12. package/dist/integrations/stripe.js +15 -0
  13. package/dist/integrations/stripe.js.map +1 -0
  14. package/dist/integrations/twilio.d.ts +1 -0
  15. package/dist/integrations/twilio.js +17 -0
  16. package/dist/integrations/twilio.js.map +1 -0
  17. package/dist/middleware/bugsnag.d.ts +2 -0
  18. package/dist/middleware/bugsnag.js +9 -0
  19. package/dist/middleware/bugsnag.js.map +1 -0
  20. package/dist/middleware/cors.d.ts +2 -0
  21. package/dist/middleware/cors.js +11 -0
  22. package/dist/middleware/cors.js.map +1 -0
  23. package/dist/middleware/errorHandler.d.ts +2 -0
  24. package/dist/middleware/errorHandler.js +19 -0
  25. package/dist/middleware/errorHandler.js.map +1 -0
  26. package/dist/middleware/multipart.d.ts +2 -0
  27. package/dist/middleware/multipart.js +7 -0
  28. package/dist/middleware/multipart.js.map +1 -0
  29. package/dist/middleware/rateLimit.d.ts +2 -0
  30. package/dist/middleware/rateLimit.js +7 -0
  31. package/dist/middleware/rateLimit.js.map +1 -0
  32. package/dist/middleware/underPressure.d.ts +2 -0
  33. package/dist/middleware/underPressure.js +7 -0
  34. package/dist/middleware/underPressure.js.map +1 -0
  35. package/dist/utils/colorize.d.ts +4 -0
  36. package/dist/utils/colorize.js +33 -0
  37. package/dist/utils/colorize.js.map +1 -0
  38. package/dist/utils/formatBytes.d.ts +1 -0
  39. package/dist/utils/formatBytes.js +10 -0
  40. package/dist/utils/formatBytes.js.map +1 -0
  41. package/dist/utils/randomUUID.d.ts +1 -0
  42. package/dist/utils/randomUUID.js +3 -0
  43. package/dist/utils/randomUUID.js.map +1 -0
  44. package/dist/utils/statAsync.d.ts +2 -0
  45. package/dist/utils/statAsync.js +4 -0
  46. package/dist/utils/statAsync.js.map +1 -0
  47. package/dist/xConfig.d.ts +3 -0
  48. package/dist/xConfig.js +9 -0
  49. package/dist/xConfig.js.map +1 -0
  50. package/package.json +39 -33
  51. package/server/app.js +78 -0
  52. package/src/auth/admin.js +181 -0
  53. package/src/auth/portal.js +177 -0
  54. package/src/integrations/cloudinary.js +98 -0
  55. package/src/integrations/geocode.js +43 -0
  56. package/src/integrations/prisma.js +30 -0
  57. package/src/integrations/sendgrid.js +58 -0
  58. package/src/integrations/twilio.js +146 -0
  59. package/src/lifecycle/xFastifyAfter.js +27 -0
  60. package/src/middleware/bugsnag.js +10 -0
  61. package/src/middleware/cors.js +10 -0
  62. package/src/middleware/fancyErrors.js +26 -0
  63. package/src/middleware/multipart.js +6 -0
  64. package/src/middleware/rateLimit.js +6 -0
  65. package/src/middleware/underPressure.js +6 -0
  66. package/src/utils/colorize.js +37 -0
  67. package/src/utils/cookie.js +5 -0
  68. package/src/utils/formatBytes.js +16 -0
  69. package/src/utils/health.js +126 -0
  70. package/src/utils/xEcho.js +12 -0
  71. package/src/utils/xSlugify.js +20 -0
  72. package/src/utils/xUUID.js +14 -0
  73. package/src/xConfig.js +117 -0
  74. package/test/index.js +17 -0
  75. package/ts-reference/integrations/cloudinary.ts +26 -0
  76. package/ts-reference/integrations/prisma.ts +13 -0
  77. package/ts-reference/integrations/sendgrid.ts +27 -0
  78. package/ts-reference/integrations/stripe.ts +15 -0
  79. package/ts-reference/integrations/twilio.ts +20 -0
  80. package/ts-reference/middleware/bugsnag.ts +10 -0
  81. package/ts-reference/middleware/cors.ts +13 -0
  82. package/ts-reference/middleware/errorHandler.ts +24 -0
  83. package/ts-reference/middleware/multipart.ts +8 -0
  84. package/ts-reference/middleware/rateLimit.ts +8 -0
  85. package/ts-reference/middleware/underPressure.ts +11 -0
  86. package/ts-reference/utils/colorize.ts +45 -0
  87. package/ts-reference/utils/formatBytes.ts +8 -0
  88. package/ts-reference/utils/randomUUID.ts +3 -0
  89. package/ts-reference/utils/statAsync.ts +4 -0
  90. package/tsconfig.json +13 -8
  91. package/xConfigReference.js +1526 -0
  92. package/xConfigWorkingList.js +720 -0
  93. package/.github/workflows/ci.yml +0 -19
  94. package/.taprc +0 -3
  95. package/index.d.ts +0 -13
  96. package/index.js +0 -9
  97. package/test/index.test-d.ts +0 -13
  98. package/test/index.test.js +0 -14
  99. package/test/xConfig.js +0 -115
package/package.json CHANGED
@@ -1,42 +1,48 @@
1
1
  {
2
2
  "name": "@xenterprises/fastify-xconfig",
3
- "version": "1.0.1",
4
- "description": "[![js-standard-style](https://img.shields.io/badge/code%20style-standard-brightgreen.svg?style=flat)](http://standardjs.com/) ![CI workflow](__MY_PLUGIN_URL__ /workflows/CI%20workflow/badge.svg)",
5
- "main": "index.js",
6
- "directories": {
7
- "test": "test"
8
- },
3
+ "type": "module",
4
+ "version": "1.1.0",
5
+ "description": "Fastify configuration plugin for setting up middleware, services, and route handling.",
6
+ "main": "src/xConfig.js",
9
7
  "scripts": {
10
- "test": "npm run lint && npm run unit && npm run test:typescript",
11
- "lint": "standard && npm run lint:typescript",
12
- "lint:typescript": "ts-standard",
13
- "test:typescript": "tsd",
14
- "unit": "node --test"
8
+ "start": "fastify start -l info server/app.js",
9
+ "dev": "fastify start -w -l info -P server/app.js",
10
+ "test": "node --test test/**/*.test.js"
15
11
  },
16
- "keywords": [],
17
12
  "author": "Tim Mushen",
18
- "license": "MIT",
19
- "types": "index.d.ts",
20
- "dependencies": {
21
- "fastify-plugin": "^4.0.0"
22
- },
13
+ "license": "ISC",
23
14
  "devDependencies": {
24
- "@types/node": "^20.4.4",
15
+ "@types/node": "^22.7.4",
16
+ "c8": "^9.0.0",
17
+ "fastify": "^4.28.1",
18
+ "fastify-plugin": "^4.0.0",
25
19
  "fastify-tsconfig": "^2.0.0",
26
- "standard": "^17.0.0",
27
- "ts-standard": "^12.0.1",
28
- "tsd": "^0.31.0",
29
- "typescript": "^5.2.2"
30
- },
31
- "tsd": {
32
- "directory": "test"
20
+ "typescript": "^5.6.3"
33
21
  },
34
- "repository": {
35
- "type": "git",
36
- "url": "git+https://github.com/xenterprises/module-fastify-xconfig.git"
37
- },
38
- "bugs": {
39
- "url": "https://github.com/xenterprises/module-fastify-xconfig/issues"
40
- },
41
- "homepage": "https://github.com/xenterprises/module-fastify-xconfig#readme"
22
+ "dependencies": {
23
+ "@fastify/autoload": "^6.0.2",
24
+ "@fastify/cookie": "^9.4.0",
25
+ "@fastify/cors": "^9.0.1",
26
+ "@fastify/multipart": "^8.3.0",
27
+ "@fastify/rate-limit": "^9.1.0",
28
+ "@fastify/sensible": "^5.6.0",
29
+ "@fastify/under-pressure": "^9.0.1",
30
+ "@prisma/client": "^6.3.1",
31
+ "@sendgrid/client": "^8.1.3",
32
+ "@sendgrid/mail": "^8.1.3",
33
+ "bcrypt": "^5.1.1",
34
+ "check-disk-space": "^3.4.0",
35
+ "fastify": "^4.28.1",
36
+ "fastify-bugsnag": "^4.1.4",
37
+ "fastify-cli": "^6.2.1",
38
+ "fastify-cloudinary": "^2.0.0",
39
+ "fastify-list-routes": "^1.0.0",
40
+ "fastify-multipart": "^5.4.0",
41
+ "fastify-plugin": "^4.0.0",
42
+ "fastify-rate-limit": "^5.9.0",
43
+ "jose": "^6.0.11",
44
+ "stripe": "^16.12.0",
45
+ "twilio": "^5.3.2",
46
+ "uncrypto": "^0.1.3"
47
+ }
42
48
  }
package/server/app.js ADDED
@@ -0,0 +1,78 @@
1
+ // server/app.js
2
+ import Fastify from 'fastify';
3
+ import xConfig from '../src/xConfig.js'; // Import your plugin correctly
4
+
5
+ const fastify = Fastify();
6
+
7
+
8
+ export default async function (fastify, opts) {
9
+ fastify.register(xConfig, {
10
+ professional: false,
11
+ fancyErrors: true,
12
+ prisma: {
13
+ active: false,
14
+ },
15
+ bugsnag: {
16
+ apiKey: process.env.BUGSNAG_API_KEY
17
+ },
18
+ rateLimit: {
19
+ max: process.env.RATE_LIMIT_MAX || 100,
20
+ timeWindow: process.env.RATE_LIMIT_TIME_WINDOW || '1 minute'
21
+ },
22
+ stripe: {
23
+ active: false,
24
+ apiKey: process.env.STRIPE_API_KEY
25
+ },
26
+ sendGrid: {
27
+ active: true,
28
+ apiKey: process.env.SENDGRID_API_KEY,
29
+ apiKeyEmailValidation: process.env.SENDGRID_API_EMAIL_VALIDATION_KEY,
30
+ fromEmail: process.env.SENDGRID_FROM_EMAIL || 'ops@getx.io',
31
+ },
32
+ twilio: {
33
+ active: true,
34
+ accountSid: process.env.TWILIO_ACCOUNT_SID,
35
+ authToken: process.env.TWILIO_AUTH_TOKEN,
36
+ phoneNumber: process.env.TWILIO_PHONE_NUMBER
37
+ },
38
+ cloudinary: {
39
+ active: false,
40
+ cloudName: process.env.CLOUDINARY_CLOUD_NAME,
41
+ apiKey: process.env.CLOUDINARY_API_KEY,
42
+ apiSecret: process.env.CLOUDINARY_API_SECRET,
43
+ basePath: process.env.CLOUDINARY_BASE_PATH || 'basepath'
44
+ },
45
+ cors: {
46
+ active: true,
47
+ origin: process.env.CORS_ORIGIN || ['http://localhost:3000', 'https://app.bandmate.io'],
48
+ credentials: true
49
+ },
50
+ auth: {
51
+ excludedPaths: ['/public', '/portal/auth/register'],
52
+ admin: {
53
+ active: true,
54
+ secret: process.env.ADMIN_STACK_PROJECT_ID,
55
+ },
56
+ user: {
57
+ active: true,
58
+ portalStackProjectId: process.env.STACK_PROJECT_ID,
59
+ me: {
60
+ isOnboarded: true
61
+ },
62
+ registerEmail: {
63
+ subject: 'Welcome to Bandmate!',
64
+ templateId: ''
65
+ }
66
+ },
67
+ },
68
+ geocode: {
69
+ active: true,
70
+ apiKey: process.env.GEOCODIO_API_KEY
71
+ }
72
+ }); // Register the default export, which should be a function
73
+ fastify.get('/', async (request, reply) => {
74
+ console.log(fastify.xEcho())
75
+ return { status: fastify.xEcho() }
76
+ })
77
+
78
+ };
@@ -0,0 +1,181 @@
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
+ }
@@ -0,0 +1,177 @@
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
+ }
@@ -0,0 +1,98 @@
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
+ }
@@ -0,0 +1,43 @@
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
+ }
@@ -0,0 +1,30 @@
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
+ }