@marvalt/madapter 1.1.0 → 2.1.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.
@@ -0,0 +1,290 @@
1
+ /**
2
+ * @license GPL-3.0-or-later
3
+ *
4
+ * This file is part of the MarVAlt Open SDK.
5
+ * Copyright (c) 2025 Vibune Pty Ltd.
6
+ *
7
+ * This program is free software: you can redistribute it and/or modify
8
+ * it under the terms of the GNU General Public License as published by
9
+ * the Free Software Foundation, either version 3 of the License, or
10
+ * (at your option) any later version.
11
+ *
12
+ * This program is distributed in the hope that it will be useful,
13
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
14
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
15
+ * See the GNU General Public License for more details.
16
+ */
17
+ /**
18
+ * Verify Cloudflare Turnstile token server-side
19
+ * @param token - The Turnstile response token from the client
20
+ * @param secretKey - Your Turnstile secret key
21
+ * @returns Promise<boolean> - True if verification succeeds
22
+ */
23
+ async function verifyTurnstile(token, secretKey) {
24
+ if (!token || !secretKey) {
25
+ console.error('Missing Turnstile token or secret key');
26
+ return false;
27
+ }
28
+ try {
29
+ const response = await fetch('https://challenges.cloudflare.com/turnstile/v0/siteverify', {
30
+ method: 'POST',
31
+ headers: { 'Content-Type': 'application/json' },
32
+ body: JSON.stringify({
33
+ secret: secretKey,
34
+ response: token,
35
+ }),
36
+ });
37
+ if (!response.ok) {
38
+ console.error('Turnstile verification request failed:', response.status);
39
+ return false;
40
+ }
41
+ const data = await response.json();
42
+ if (!data.success) {
43
+ console.warn('Turnstile verification failed:', data['error-codes']);
44
+ return false;
45
+ }
46
+ return true;
47
+ }
48
+ catch (error) {
49
+ console.error('Turnstile verification error:', error);
50
+ return false;
51
+ }
52
+ }
53
+
54
+ /**
55
+ * @license GPL-3.0-or-later
56
+ *
57
+ * This file is part of the MarVAlt Open SDK.
58
+ * Copyright (c) 2025 Vibune Pty Ltd.
59
+ *
60
+ * This program is free software: you can redistribute it and/or modify
61
+ * it under the terms of the GNU General Public License as published by
62
+ * the Free Software Foundation, either version 3 of the License, or
63
+ * (at your option) any later version.
64
+ *
65
+ * This program is distributed in the hope that it will be useful,
66
+ * but WITHOUT ANY WARRANTY; without even the implied warranty of
67
+ * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
68
+ * See the GNU General Public License for more details.
69
+ */
70
+ // In-memory token cache (per worker instance)
71
+ let cachedToken = null;
72
+ async function getOAuth2Token(mauticUrl, clientId, clientSecret, cfAccessClientId, cfAccessClientSecret) {
73
+ // Check cache (with 5-minute buffer before expiry)
74
+ if (cachedToken && cachedToken.expires_at > Date.now() + 300000) {
75
+ console.log('🔑 Using cached OAuth2 token');
76
+ return cachedToken.access_token;
77
+ }
78
+ console.log('🔑 Fetching new OAuth2 token...');
79
+ const tokenUrl = `${mauticUrl}/oauth/v2/token`;
80
+ const body = new URLSearchParams({
81
+ grant_type: 'client_credentials',
82
+ client_id: clientId,
83
+ client_secret: clientSecret,
84
+ });
85
+ const headers = {
86
+ 'Content-Type': 'application/x-www-form-urlencoded',
87
+ };
88
+ // Add CF Access headers if available
89
+ if (cfAccessClientId && cfAccessClientSecret) {
90
+ headers['CF-Access-Client-Id'] = cfAccessClientId;
91
+ headers['CF-Access-Client-Secret'] = cfAccessClientSecret;
92
+ console.log('🔐 Added CF Access headers to OAuth2 request');
93
+ }
94
+ const response = await fetch(tokenUrl, {
95
+ method: 'POST',
96
+ headers,
97
+ body: body.toString(),
98
+ });
99
+ if (!response.ok) {
100
+ const errorText = await response.text();
101
+ throw new Error(`OAuth2 token request failed: ${response.status} ${errorText}`);
102
+ }
103
+ const data = await response.json();
104
+ // Cache token
105
+ cachedToken = {
106
+ access_token: data.access_token,
107
+ expires_at: Date.now() + (data.expires_in * 1000),
108
+ };
109
+ console.log('✅ OAuth2 token cached');
110
+ return cachedToken.access_token;
111
+ }
112
+ /**
113
+ * Cloudflare Pages Function handler for Mautic API proxy
114
+ *
115
+ * Environment variables required:
116
+ * - VITE_MAUTIC_URL or MAUTIC_URL: Mautic instance URL
117
+ * - VITE_MAUTIC_API_PUBLIC_KEY or MAUTIC_API_PUBLIC_KEY: OAuth2 client ID
118
+ * - VITE_MAUTIC_API_SECRET_KEY or MAUTIC_API_SECRET_KEY: OAuth2 client secret
119
+ * - VITE_CF_ACCESS_CLIENT_ID or CF_ACCESS_CLIENT_ID: (Optional) Cloudflare Access client ID
120
+ * - VITE_CF_ACCESS_CLIENT_SECRET or CF_ACCESS_CLIENT_SECRET: (Optional) Cloudflare Access client secret
121
+ */
122
+ async function handleMauticProxy(context) {
123
+ const { request, env } = context;
124
+ try {
125
+ // Parse the endpoint from query parameter (proxy interface)
126
+ const url = new URL(request.url);
127
+ const endpoint = url.searchParams.get('endpoint');
128
+ if (!endpoint) {
129
+ return new Response('Missing endpoint parameter', { status: 400 });
130
+ }
131
+ // ============================================
132
+ // SECURITY LAYER 1: Origin Validation
133
+ // ============================================
134
+ const origin = request.headers.get('Origin');
135
+ const referer = request.headers.get('Referer');
136
+ // Get allowed origins from environment (comma-separated)
137
+ const allowedOriginsStr = env.ALLOWED_ORIGINS || env.VITE_ALLOWED_ORIGINS || '';
138
+ const allowedOrigins = allowedOriginsStr
139
+ .split(',')
140
+ .map((o) => o.trim())
141
+ .filter(Boolean);
142
+ // Default to localhost if no origins configured (development mode)
143
+ if (allowedOrigins.length === 0) {
144
+ allowedOrigins.push('http://localhost:8080', 'http://localhost:5173');
145
+ console.log('âš ī¸ No ALLOWED_ORIGINS configured, defaulting to localhost');
146
+ }
147
+ const isAllowedOrigin = allowedOrigins.some((allowed) => origin?.startsWith(allowed) || referer?.startsWith(allowed));
148
+ // Block if origin/referer present but not allowed
149
+ if ((origin || referer) && !isAllowedOrigin) {
150
+ console.warn('đŸšĢ Blocked request from unauthorized origin:', origin || referer);
151
+ return new Response(JSON.stringify({
152
+ error: 'Forbidden origin',
153
+ message: 'This endpoint can only be accessed from authorized domains'
154
+ }), {
155
+ status: 403,
156
+ headers: { 'Content-Type': 'application/json' }
157
+ });
158
+ }
159
+ // ============================================
160
+ // SECURITY LAYER 2: Endpoint Whitelisting
161
+ // ============================================
162
+ const allowedPatterns = [
163
+ /^\/form\/submit/, // Form submissions
164
+ /^\/forms\/\d+\/submit/, // Legacy form endpoint
165
+ /^\/mtc\.js$/, // Tracking script (optional)
166
+ /^\/mtc\//, // Tracking API (optional)
167
+ /^\/mtracking\.gif$/, // Tracking pixel (optional)
168
+ ];
169
+ const isAllowedEndpoint = allowedPatterns.some(pattern => pattern.test(endpoint));
170
+ if (!isAllowedEndpoint) {
171
+ console.warn('đŸšĢ Blocked unauthorized endpoint:', endpoint);
172
+ return new Response(JSON.stringify({
173
+ error: 'Forbidden endpoint',
174
+ message: 'Only form submission endpoints are allowed'
175
+ }), {
176
+ status: 403,
177
+ headers: { 'Content-Type': 'application/json' }
178
+ });
179
+ }
180
+ // ============================================
181
+ // SECURITY LAYER 3: Turnstile Verification
182
+ // ============================================
183
+ const turnstileSecretKey = env.TURNSTILE_SECRET_KEY || env.VITE_TURNSTILE_SECRET_KEY;
184
+ const turnstileEnabled = !!turnstileSecretKey;
185
+ // Only verify Turnstile for POST requests (form submissions)
186
+ if (turnstileEnabled && request.method === 'POST') {
187
+ const turnstileToken = request.headers.get('cf-turnstile-response');
188
+ if (!turnstileToken) {
189
+ console.warn('đŸšĢ Missing Turnstile token for POST request');
190
+ return new Response(JSON.stringify({
191
+ error: 'Missing verification',
192
+ message: 'Bot verification required'
193
+ }), {
194
+ status: 403,
195
+ headers: { 'Content-Type': 'application/json' }
196
+ });
197
+ }
198
+ const isValid = await verifyTurnstile(turnstileToken, turnstileSecretKey);
199
+ if (!isValid) {
200
+ console.warn('đŸšĢ Invalid Turnstile token');
201
+ return new Response(JSON.stringify({
202
+ error: 'Verification failed',
203
+ message: 'Bot verification failed'
204
+ }), {
205
+ status: 403,
206
+ headers: { 'Content-Type': 'application/json' }
207
+ });
208
+ }
209
+ console.log('✅ Turnstile verification passed');
210
+ }
211
+ else if (turnstileEnabled) {
212
+ console.log('â„šī¸ Turnstile enabled but skipped for non-POST request');
213
+ }
214
+ // Get server-side credentials (prefer non-VITE_ prefixed env vars)
215
+ const mauticUrl = env.MAUTIC_URL || env.VITE_MAUTIC_URL;
216
+ const clientId = env.MAUTIC_API_PUBLIC_KEY || env.VITE_MAUTIC_API_PUBLIC_KEY;
217
+ const clientSecret = env.MAUTIC_API_SECRET_KEY || env.VITE_MAUTIC_API_SECRET_KEY;
218
+ const cfAccessClientId = env.CF_ACCESS_CLIENT_ID || env.VITE_CF_ACCESS_CLIENT_ID;
219
+ const cfAccessClientSecret = env.CF_ACCESS_CLIENT_SECRET || env.VITE_CF_ACCESS_CLIENT_SECRET;
220
+ if (!mauticUrl || !clientId || !clientSecret) {
221
+ console.error('❌ Mautic credentials not configured', {
222
+ mauticUrl: !!mauticUrl,
223
+ clientId: !!clientId,
224
+ clientSecret: !!clientSecret
225
+ });
226
+ return new Response('Mautic credentials not configured', { status: 500 });
227
+ }
228
+ // Get OAuth2 token
229
+ const accessToken = await getOAuth2Token(mauticUrl, clientId, clientSecret, cfAccessClientId, cfAccessClientSecret);
230
+ // Determine if this is a form submission (goes to /form/submit)
231
+ // or an API call (goes to /api/endpoint)
232
+ const isFormSubmission = endpoint.startsWith('/form/submit');
233
+ const targetUrl = isFormSubmission
234
+ ? `${mauticUrl}${endpoint}` // Form submissions don't use /api prefix
235
+ : `${mauticUrl}/api${endpoint}`; // API calls use /api prefix
236
+ // Prepare headers
237
+ const headers = {
238
+ 'Authorization': `Bearer ${accessToken}`,
239
+ };
240
+ // Copy relevant headers from original request
241
+ const contentType = request.headers.get('Content-Type');
242
+ if (contentType) {
243
+ headers['Content-Type'] = contentType;
244
+ }
245
+ // Add CF Access headers if available
246
+ if (cfAccessClientId && cfAccessClientSecret) {
247
+ headers['CF-Access-Client-Id'] = cfAccessClientId;
248
+ headers['CF-Access-Client-Secret'] = cfAccessClientSecret;
249
+ }
250
+ // Prepare request init
251
+ const init = {
252
+ method: request.method,
253
+ headers,
254
+ };
255
+ // Include body for POST/PATCH/PUT requests
256
+ if (request.method !== 'GET' && request.method !== 'HEAD') {
257
+ init.body = await request.text();
258
+ }
259
+ console.log(`📤 Proxying ${request.method} request to Mautic:`, {
260
+ endpoint,
261
+ targetUrl,
262
+ isFormSubmission
263
+ });
264
+ // Forward request to Mautic
265
+ const response = await fetch(targetUrl, init);
266
+ console.log(`đŸ“Ĩ Mautic response: ${response.status} ${response.statusText}`);
267
+ // Return response to client
268
+ const responseBody = await response.text();
269
+ return new Response(responseBody, {
270
+ status: response.status,
271
+ statusText: response.statusText,
272
+ headers: {
273
+ 'Content-Type': response.headers.get('Content-Type') || 'application/json',
274
+ },
275
+ });
276
+ }
277
+ catch (error) {
278
+ console.error('❌ Mautic proxy error:', error);
279
+ return new Response(JSON.stringify({
280
+ success: false,
281
+ error: error?.message || 'Unknown error',
282
+ }), {
283
+ status: 500,
284
+ headers: { 'Content-Type': 'application/json' },
285
+ });
286
+ }
287
+ }
288
+
289
+ export { handleMauticProxy, verifyTurnstile };
290
+ //# sourceMappingURL=server.esm.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"server.esm.js","sources":["../src/server/turnstile.ts","../src/server/mautic-proxy.ts"],"sourcesContent":[null,null],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;AAeG;AASH;;;;;AAKG;AACI,eAAe,eAAe,CACnC,KAAa,EACb,SAAiB,EAAA;AAEjB,IAAA,IAAI,CAAC,KAAK,IAAI,CAAC,SAAS,EAAE;AACxB,QAAA,OAAO,CAAC,KAAK,CAAC,uCAAuC,CAAC;AACtD,QAAA,OAAO,KAAK;IACd;AAEA,IAAA,IAAI;AACF,QAAA,MAAM,QAAQ,GAAG,MAAM,KAAK,CAC1B,2DAA2D,EAC3D;AACE,YAAA,MAAM,EAAE,MAAM;AACd,YAAA,OAAO,EAAE,EAAE,cAAc,EAAE,kBAAkB,EAAE;AAC/C,YAAA,IA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,EAAuB,QAAQ,CAAC,MAAM,CAAA,CAAA,EAAI,QAAQ,CAAC,UAAU,CAAA,CAAE,CAAC;;AAG5E,QAAA,MAAM,YAAY,GAAG,MAAM,QAAQ,CAAC,IAAI,EAAE;AAC1C,QAAA,OAAO,IAAI,QAAQ,CAAC,YAAY,EAAE;YAChC,MAAM,EAAE,QAAQ,CAAC,MAAM;YACvB,UAAU,EAAE,QAAQ,CAAC,UAAU;AAC/B,YAAA,OAAO,EAAE;gBACP,cAAc,EAAE,QAAQ,CAAC,OAAO,CAAC,GAAG,CAAC,cAAc,CAAC,IAAI,kBAAkB;AAC3E,aAAA;AACF,SAAA,CAAC;IAEJ;IAAE,OAAO,KAAU,EAAE;AACnB,QAAA,OAAO,CAAC,KAAK,CAAC,uBAAuB,EAAE,KAAK,CAAC;AAC7C,QAAA,OAAO,IAAI,QAAQ,CAAC,IAAI,CAAC,SAAS,CAAC;AACjC,YAAA,OAAO,EAAE,KAAK;AACd,YAAA,KAAK,EAAE,KAAK,EAAE,OAAO,IAAI,eAAe;AACzC,SAAA,CAAC,EAAE;AACF,YAAA,MAAM,EAAE,GAAG;AACX,YAAA,OAAO,EAAE,EAAE,cAAc,EAAE,kBAAkB,EAAE;AAChD,SAAA,CAAC;IACJ;AACF;;;;"}
@@ -15,15 +15,21 @@
15
15
  * See the GNU General Public License for more details.
16
16
  */
17
17
  export type AuthMode = 'cloudflare_proxy' | 'direct';
18
+ /**
19
+ * Mautic client configuration (for runtime/browser use)
20
+ * Convention-based: Uses /api/mautic-submit by default
21
+ */
18
22
  export interface MauticConfig {
19
- authMode: AuthMode;
23
+ /** Mautic instance URL (e.g., https://your-mautic.com) */
20
24
  apiUrl?: string;
21
- cloudflareWorkerUrl?: string;
22
- clientId?: string;
23
- clientSecret?: string;
24
- cfAccessClientId?: string;
25
- cfAccessClientSecret?: string;
25
+ /**
26
+ * Proxy endpoint for server-side authentication
27
+ * @default '/api/mautic-submit'
28
+ */
29
+ proxyEndpoint?: string;
30
+ /** Request timeout in milliseconds */
26
31
  timeout?: number;
32
+ /** Number of retry attempts */
27
33
  retries?: number;
28
34
  }
29
35
  export interface MauticGeneratorConfig {
@@ -1 +1 @@
1
- {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../../src/types/config.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,MAAM,MAAM,QAAQ,GAAG,kBAAkB,GAAG,QAAQ,CAAC;AAErD,MAAM,WAAW,YAAY;IAC3B,QAAQ,EAAE,QAAQ,CAAC;IACnB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAE7B,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,YAAY,CAAC,EAAE,MAAM,CAAC;IAEtB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,oBAAoB,CAAC,EAAE,MAAM,CAAC;IAC9B,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,qBAAqB;IACpC,QAAQ,EAAE,QAAQ,CAAC;IACnB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAE7B,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,YAAY,CAAC,EAAE,MAAM,CAAC;IAEtB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,oBAAoB,CAAC,EAAE,MAAM,CAAC;IAC9B,UAAU,EAAE,MAAM,CAAC;IACnB,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC;IACnB,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,oBAAoB;IACnC,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB"}
1
+ {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../../src/types/config.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,MAAM,MAAM,QAAQ,GAAG,kBAAkB,GAAG,QAAQ,CAAC;AAErD;;;GAGG;AACH,MAAM,WAAW,YAAY;IAC3B,0DAA0D;IAC1D,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB;;;OAGG;IACH,aAAa,CAAC,EAAE,MAAM,CAAC;IACvB,sCAAsC;IACtC,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,+BAA+B;IAC/B,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,qBAAqB;IACpC,QAAQ,EAAE,QAAQ,CAAC;IACnB,MAAM,CAAC,EAAE,MAAM,CAAC;IAChB,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAE7B,QAAQ,CAAC,EAAE,MAAM,CAAC;IAClB,YAAY,CAAC,EAAE,MAAM,CAAC;IAEtB,gBAAgB,CAAC,EAAE,MAAM,CAAC;IAC1B,oBAAoB,CAAC,EAAE,MAAM,CAAC;IAC9B,UAAU,EAAE,MAAM,CAAC;IACnB,OAAO,CAAC,EAAE,MAAM,EAAE,CAAC;IACnB,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B,OAAO,CAAC,EAAE,MAAM,CAAC;IACjB,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,oBAAoB;IACnC,OAAO,CAAC,EAAE,OAAO,CAAC;IAClB,SAAS,CAAC,EAAE,MAAM,CAAC;IACnB,QAAQ,CAAC,EAAE,MAAM,CAAC;CACnB"}
@@ -14,9 +14,10 @@
14
14
  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
15
15
  * See the GNU General Public License for more details.
16
16
  */
17
- import { MauticConfig, AuthMode } from '../types/config';
17
+ import { MauticConfig } from '../types/config';
18
18
  /**
19
19
  * Create Mautic configuration from environment variables
20
+ * Convention-based: Uses /api/mautic-submit by default
20
21
  */
21
22
  export declare const createMauticConfig: (overrides?: Partial<MauticConfig>) => MauticConfig;
22
23
  /**
@@ -42,9 +43,8 @@ export declare const isMauticEnabled: (config: MauticConfig) => boolean;
42
43
  * Get Mautic configuration summary (for debugging)
43
44
  */
44
45
  export declare const getMauticConfigSummary: (config: MauticConfig) => {
45
- authMode: AuthMode;
46
46
  hasApiUrl: boolean;
47
- hasCloudflareWorkerUrl: boolean;
47
+ proxyEndpoint: string;
48
48
  timeout: number | undefined;
49
49
  retries: number | undefined;
50
50
  isEnabled: boolean;
@@ -1 +1 @@
1
- {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../../src/utils/config.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,OAAO,EAAE,YAAY,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAEzD;;GAEG;AACH,eAAO,MAAM,kBAAkB,GAAI,YAAW,OAAO,CAAC,YAAY,CAAM,KAAG,YA8C1E,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,oBAAoB,GAAI,QAAQ,YAAY,KAAG;IAAE,OAAO,EAAE,OAAO,CAAC;IAAC,MAAM,EAAE,MAAM,EAAE,CAAA;CA6B/F,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,sBAAsB,QAAO,YAMzC,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,iBAAiB,GAAI,MAAM,YAAY,EAAE,WAAW,OAAO,CAAC,YAAY,CAAC,KAAG,YAKxF,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,eAAe,GAAI,QAAQ,YAAY,KAAG,OAOtD,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,sBAAsB,GAAI,QAAQ,YAAY;;;;;;;CAS1D,CAAC"}
1
+ {"version":3,"file":"config.d.ts","sourceRoot":"","sources":["../../src/utils/config.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AAEH,OAAO,EAAE,YAAY,EAAY,MAAM,iBAAiB,CAAC;AAEzD;;;GAGG;AACH,eAAO,MAAM,kBAAkB,GAAI,YAAW,OAAO,CAAC,YAAY,CAAM,KAAG,YAiC1E,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,oBAAoB,GAAI,QAAQ,YAAY,KAAG;IAAE,OAAO,EAAE,OAAO,CAAC;IAAC,MAAM,EAAE,MAAM,EAAE,CAAA;CAe/F,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,sBAAsB,QAAO,YAMzC,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,iBAAiB,GAAI,MAAM,YAAY,EAAE,WAAW,OAAO,CAAC,YAAY,CAAC,KAAG,YAKxF,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,eAAe,GAAI,QAAQ,YAAY,KAAG,OAEtD,CAAC;AAEF;;GAEG;AACH,eAAO,MAAM,sBAAsB,GAAI,QAAQ,YAAY;;;;;;CAQ1D,CAAC"}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@marvalt/madapter",
3
- "version": "1.1.0",
3
+ "version": "2.1.1",
4
4
  "description": "MarVAlt adapter for Mautic integration (React + static data generator)",
5
5
  "main": "dist/index.cjs",
6
6
  "module": "dist/index.esm.js",
@@ -8,6 +8,8 @@
8
8
  "type": "module",
9
9
  "files": [
10
10
  "dist",
11
+ "templates",
12
+ "scripts",
11
13
  "README.md",
12
14
  "LICENSE"
13
15
  ],
@@ -21,7 +23,8 @@
21
23
  "lint:fix": "eslint src --ext .ts,.tsx --fix",
22
24
  "type-check": "tsc --noEmit",
23
25
  "clean": "rimraf dist",
24
- "prepublishOnly": "npm run clean && npm run build"
26
+ "prepublishOnly": "npm run clean && npm run build",
27
+ "postinstall": "node scripts/postinstall.cjs"
25
28
  },
26
29
  "keywords": [
27
30
  "mautic",
@@ -46,6 +49,10 @@
46
49
  ".": {
47
50
  "import": "./dist/index.esm.js",
48
51
  "require": "./dist/index.cjs"
52
+ },
53
+ "./server": {
54
+ "import": "./dist/server.esm.js",
55
+ "require": "./dist/server.cjs"
49
56
  }
50
57
  },
51
58
  "peerDependencies": {
@@ -0,0 +1,127 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * Post-install script for @marvalt/madapter
5
+ * Automatically sets up the Cloudflare Pages Function for Mautic proxy
6
+ */
7
+
8
+ const fs = require('fs');
9
+ const path = require('path');
10
+
11
+ // Colors for terminal output
12
+ const colors = {
13
+ reset: '\x1b[0m',
14
+ green: '\x1b[32m',
15
+ yellow: '\x1b[33m',
16
+ blue: '\x1b[34m',
17
+ red: '\x1b[31m',
18
+ };
19
+
20
+ function log(message, color = 'reset') {
21
+ console.log(`${colors[color]}${message}${colors.reset}`);
22
+ }
23
+
24
+ function setupMauticFunction() {
25
+ try {
26
+ // Find the project root (where package.json with @marvalt/madapter dependency exists)
27
+ let currentDir = process.cwd();
28
+ let projectRoot = null;
29
+
30
+ // Walk up the directory tree to find the project root
31
+ while (currentDir !== path.parse(currentDir).root) {
32
+ const packageJsonPath = path.join(currentDir, 'package.json');
33
+ if (fs.existsSync(packageJsonPath)) {
34
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
35
+ // Check if this is the consuming project (not the package itself)
36
+ if (packageJson.dependencies && packageJson.dependencies['@marvalt/madapter']) {
37
+ projectRoot = currentDir;
38
+ break;
39
+ }
40
+ if (packageJson.devDependencies && packageJson.devDependencies['@marvalt/madapter']) {
41
+ projectRoot = currentDir;
42
+ break;
43
+ }
44
+ }
45
+ currentDir = path.dirname(currentDir);
46
+ }
47
+
48
+ // If we're being installed in the package itself (during development), skip
49
+ const thisPackageJson = path.join(__dirname, '..', 'package.json');
50
+ if (fs.existsSync(thisPackageJson)) {
51
+ const thisPackage = JSON.parse(fs.readFileSync(thisPackageJson, 'utf8'));
52
+ if (thisPackage.name === '@marvalt/madapter') {
53
+ // We're in the package itself, not a consuming project
54
+ if (!projectRoot || projectRoot === path.dirname(thisPackageJson)) {
55
+ log('đŸ“Ļ Skipping postinstall (running in package development mode)', 'blue');
56
+ return;
57
+ }
58
+ }
59
+ }
60
+
61
+ if (!projectRoot) {
62
+ log('âš ī¸ Could not find project root. Skipping Mautic function setup.', 'yellow');
63
+ return;
64
+ }
65
+
66
+ // Define paths
67
+ const functionsDir = path.join(projectRoot, 'functions', 'api');
68
+ const targetFile = path.join(functionsDir, 'mautic-submit.ts');
69
+ const templateFile = path.join(__dirname, '..', 'templates', 'mautic-submit.ts');
70
+
71
+ // Check if template exists
72
+ if (!fs.existsSync(templateFile)) {
73
+ log('âš ī¸ Template file not found. Skipping setup.', 'yellow');
74
+ return;
75
+ }
76
+
77
+ // Create functions/api directory if it doesn't exist
78
+ if (!fs.existsSync(functionsDir)) {
79
+ fs.mkdirSync(functionsDir, { recursive: true });
80
+ log('📁 Created /functions/api directory', 'blue');
81
+ }
82
+
83
+ // Check if file already exists
84
+ if (fs.existsSync(targetFile)) {
85
+ log('â„šī¸ Mautic Pages Function already exists at /functions/api/mautic-submit.ts', 'blue');
86
+ return;
87
+ }
88
+
89
+ // Copy template to target
90
+ const templateContent = fs.readFileSync(templateFile, 'utf8');
91
+ fs.writeFileSync(targetFile, templateContent);
92
+
93
+ // Copy security documentation
94
+ const docsTargetFile = path.join(projectRoot, 'MAUTIC_SECURITY.md');
95
+ const docsTemplateFile = path.join(__dirname, '..', 'templates', 'MAUTIC_SECURITY.md');
96
+
97
+ if (fs.existsSync(docsTemplateFile) && !fs.existsSync(docsTargetFile)) {
98
+ const docsContent = fs.readFileSync(docsTemplateFile, 'utf8');
99
+ fs.writeFileSync(docsTargetFile, docsContent);
100
+ log('📖 Installed: /MAUTIC_SECURITY.md', 'blue');
101
+ }
102
+
103
+ log('', 'reset');
104
+ log('✅ @marvalt/madapter setup complete!', 'green');
105
+ log('', 'reset');
106
+ log('📄 Installed: /functions/api/mautic-submit.ts', 'blue');
107
+ log('📖 Installed: /MAUTIC_SECURITY.md (security hardening guide)', 'blue');
108
+ log('', 'reset');
109
+ log('📋 Next steps:', 'blue');
110
+ log(' 1. Add to .env.local:', 'reset');
111
+ log(' VITE_MAUTIC_API_PUBLIC_KEY=your_client_id', 'yellow');
112
+ log(' VITE_MAUTIC_API_SECRET_KEY=your_client_secret', 'yellow');
113
+ log(' 2. Add to .env:', 'reset');
114
+ log(' VITE_MAUTIC_URL=https://your-mautic-instance.com', 'yellow');
115
+ log(' VITE_ALLOWED_ORIGINS=https://your-app.pages.dev', 'yellow');
116
+ log(' 3. 🔒 Read MAUTIC_SECURITY.md for security hardening!', 'green');
117
+ log('', 'reset');
118
+
119
+ } catch (error) {
120
+ log(`❌ Error during postinstall: ${error.message}`, 'red');
121
+ // Don't fail the installation if postinstall fails
122
+ }
123
+ }
124
+
125
+ // Run setup
126
+ setupMauticFunction();
127
+
@@ -0,0 +1,114 @@
1
+ #!/usr/bin/env node
2
+
3
+ /**
4
+ * Post-install script for @marvalt/madapter
5
+ * Automatically sets up the Cloudflare Pages Function for Mautic proxy
6
+ */
7
+
8
+ const fs = require('fs');
9
+ const path = require('path');
10
+
11
+ // Colors for terminal output
12
+ const colors = {
13
+ reset: '\x1b[0m',
14
+ green: '\x1b[32m',
15
+ yellow: '\x1b[33m',
16
+ blue: '\x1b[34m',
17
+ red: '\x1b[31m',
18
+ };
19
+
20
+ function log(message, color = 'reset') {
21
+ console.log(`${colors[color]}${message}${colors.reset}`);
22
+ }
23
+
24
+ function setupMauticFunction() {
25
+ try {
26
+ // Find the project root (where package.json with @marvalt/madapter dependency exists)
27
+ let currentDir = process.cwd();
28
+ let projectRoot = null;
29
+
30
+ // Walk up the directory tree to find the project root
31
+ while (currentDir !== path.parse(currentDir).root) {
32
+ const packageJsonPath = path.join(currentDir, 'package.json');
33
+ if (fs.existsSync(packageJsonPath)) {
34
+ const packageJson = JSON.parse(fs.readFileSync(packageJsonPath, 'utf8'));
35
+ // Check if this is the consuming project (not the package itself)
36
+ if (packageJson.dependencies && packageJson.dependencies['@marvalt/madapter']) {
37
+ projectRoot = currentDir;
38
+ break;
39
+ }
40
+ if (packageJson.devDependencies && packageJson.devDependencies['@marvalt/madapter']) {
41
+ projectRoot = currentDir;
42
+ break;
43
+ }
44
+ }
45
+ currentDir = path.dirname(currentDir);
46
+ }
47
+
48
+ // If we're being installed in the package itself (during development), skip
49
+ const thisPackageJson = path.join(__dirname, '..', 'package.json');
50
+ if (fs.existsSync(thisPackageJson)) {
51
+ const thisPackage = JSON.parse(fs.readFileSync(thisPackageJson, 'utf8'));
52
+ if (thisPackage.name === '@marvalt/madapter') {
53
+ // We're in the package itself, not a consuming project
54
+ if (!projectRoot || projectRoot === path.dirname(thisPackageJson)) {
55
+ log('đŸ“Ļ Skipping postinstall (running in package development mode)', 'blue');
56
+ return;
57
+ }
58
+ }
59
+ }
60
+
61
+ if (!projectRoot) {
62
+ log('âš ī¸ Could not find project root. Skipping Mautic function setup.', 'yellow');
63
+ return;
64
+ }
65
+
66
+ // Define paths
67
+ const functionsDir = path.join(projectRoot, 'functions', 'api');
68
+ const targetFile = path.join(functionsDir, 'mautic-submit.ts');
69
+ const templateFile = path.join(__dirname, '..', 'templates', 'mautic-submit.ts');
70
+
71
+ // Check if template exists
72
+ if (!fs.existsSync(templateFile)) {
73
+ log('âš ī¸ Template file not found. Skipping setup.', 'yellow');
74
+ return;
75
+ }
76
+
77
+ // Create functions/api directory if it doesn't exist
78
+ if (!fs.existsSync(functionsDir)) {
79
+ fs.mkdirSync(functionsDir, { recursive: true });
80
+ log('📁 Created /functions/api directory', 'blue');
81
+ }
82
+
83
+ // Check if file already exists
84
+ if (fs.existsSync(targetFile)) {
85
+ log('â„šī¸ Mautic Pages Function already exists at /functions/api/mautic-submit.ts', 'blue');
86
+ return;
87
+ }
88
+
89
+ // Copy template to target
90
+ const templateContent = fs.readFileSync(templateFile, 'utf8');
91
+ fs.writeFileSync(targetFile, templateContent);
92
+
93
+ log('', 'reset');
94
+ log('✅ @marvalt/madapter setup complete!', 'green');
95
+ log('', 'reset');
96
+ log('📄 Installed: /functions/api/mautic-submit.ts', 'blue');
97
+ log('', 'reset');
98
+ log('📋 Next steps:', 'blue');
99
+ log(' 1. Add to .env.local:', 'reset');
100
+ log(' VITE_MAUTIC_API_PUBLIC_KEY=your_client_id', 'yellow');
101
+ log(' VITE_MAUTIC_API_SECRET_KEY=your_client_secret', 'yellow');
102
+ log(' 2. Add to .env:', 'reset');
103
+ log(' VITE_MAUTIC_URL=https://your-mautic-instance.com', 'yellow');
104
+ log('', 'reset');
105
+
106
+ } catch (error) {
107
+ log(`❌ Error during postinstall: ${error.message}`, 'red');
108
+ // Don't fail the installation if postinstall fails
109
+ }
110
+ }
111
+
112
+ // Run setup
113
+ setupMauticFunction();
114
+