-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathindex.ts
More file actions
415 lines (367 loc) · 12.1 KB
/
index.ts
File metadata and controls
415 lines (367 loc) · 12.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
import { createJobApp } from '@constructive-io/knative-job-fn';
import { GraphQLClient } from 'graphql-request';
import gql from 'graphql-tag';
import { generate } from '@launchql/mjml';
import { send as sendPostmaster } from '@constructive-io/postmaster';
import { send as sendSmtp } from 'simple-smtp-server';
import { parseEnvBoolean } from '@pgpmjs/env';
import { createLogger } from '@pgpmjs/logger';
const isDryRun = parseEnvBoolean(process.env.SEND_EMAIL_LINK_DRY_RUN) ?? false;
const useSmtp = parseEnvBoolean(process.env.EMAIL_SEND_USE_SMTP) ?? false;
const logger = createLogger('send-email-link');
const app = createJobApp();
const GetUser = gql`
query GetUser($userId: UUID!) {
users(filter: { id: { equalTo: $userId } }, first: 1) {
nodes {
username
displayName
profilePicture
}
}
}
`;
const GetDatabaseInfo = gql`
query GetDatabaseInfo($databaseId: UUID!) {
databases(filter: { id: { equalTo: $databaseId } }, first: 1) {
nodes {
sites {
nodes {
domains {
nodes {
subdomain
domain
}
}
logo
title
siteThemes {
nodes {
theme
}
}
siteModules(filter: { name: { equalTo: "legal_terms_module" } }) {
nodes {
data
}
}
}
}
}
}
}
`;
type SendEmailParams = {
email_type: 'invite_email' | 'forgot_password' | 'email_verification';
email: string;
invite_type?: number | string;
invite_token?: string;
sender_id?: string;
user_id?: string;
reset_token?: string;
email_id?: string;
verification_token?: string;
};
type GraphQLContext = {
client: GraphQLClient;
meta: GraphQLClient;
databaseId: string;
};
const getRequiredEnv = (name: string): string => {
const value = process.env[name];
if (!value) {
throw new Error(`Missing required environment variable ${name}`);
}
return value;
};
type GraphQLClientOptions = {
hostHeaderEnvVar?: string;
databaseId?: string;
useMetaSchema?: boolean;
apiName?: string;
schemata?: string;
};
// TODO: Consider moving this to @constructive-io/knative-job-fn as a shared
// utility so all job functions can create GraphQL clients with consistent
// header-based routing without duplicating this logic.
const createGraphQLClient = (
url: string,
options: GraphQLClientOptions = {}
): GraphQLClient => {
const headers: Record<string, string> = {};
if (process.env.GRAPHQL_AUTH_TOKEN) {
headers.Authorization = `Bearer ${process.env.GRAPHQL_AUTH_TOKEN}`;
}
const envName = options.hostHeaderEnvVar || 'GRAPHQL_HOST_HEADER';
const hostHeader = process.env[envName];
if (hostHeader) {
headers.host = hostHeader;
}
// Header-based routing for internal cluster services (API_IS_PUBLIC=false)
if (options.databaseId) {
headers['X-Database-Id'] = options.databaseId;
}
if (options.useMetaSchema) {
headers['X-Meta-Schema'] = 'true';
}
if (options.apiName) {
headers['X-Api-Name'] = options.apiName;
}
if (options.schemata) {
headers['X-Schemata'] = options.schemata;
}
return new GraphQLClient(url, { headers });
};
export const sendEmailLink = async (
params: SendEmailParams,
context: GraphQLContext
) => {
const { client, meta, databaseId } = context;
const validateForType = (): { missing?: string } | null => {
switch (params.email_type) {
case 'invite_email':
if (!params.invite_token || !params.sender_id) {
return { missing: 'invite_token_or_sender_id' };
}
return null;
case 'forgot_password':
if (!params.user_id || !params.reset_token) {
return { missing: 'user_id_or_reset_token' };
}
return null;
case 'email_verification':
if (!params.email_id || !params.verification_token) {
return { missing: 'email_id_or_verification_token' };
}
return null;
default:
return { missing: 'email_type' };
}
};
if (!params.email_type) {
return { missing: 'email_type' };
}
if (!params.email) {
return { missing: 'email' };
}
const typeValidation = validateForType();
if (typeValidation) {
return typeValidation;
}
const databaseInfo = await meta.request<any>(GetDatabaseInfo, {
databaseId
});
const database = databaseInfo?.databases?.nodes?.[0];
const site = database?.sites?.nodes?.[0];
if (!site) {
throw new Error('Site not found for database');
}
const legalTermsModule = site.siteModules?.nodes?.[0];
const domainNode = site.domains?.nodes?.[0];
const theme = site.siteThemes?.nodes?.[0]?.theme;
if (!legalTermsModule || !domainNode || !theme) {
throw new Error('Missing site configuration for email');
}
const subdomain = domainNode.subdomain;
const domain = domainNode.domain;
const supportEmail = legalTermsModule.data.emails.support;
const logo = site.logo?.url;
const company = legalTermsModule.data.company;
const website = company.website;
const nick = company.nick;
const name = company.name;
const primary = theme.primary;
// Check if this is a localhost-style domain before building hostname
// TODO: Security consideration - this only affects localhost domains which
// should not exist in production. The isLocalHost check ensures special
// behavior (http, custom port) only applies in dev environments.
const isLocalDomain =
domain === 'localhost' ||
domain.startsWith('localhost') ||
domain === '0.0.0.0';
// For localhost, skip subdomain to generate cleaner URLs (http://localhost:3000)
const hostname = subdomain && !isLocalDomain
? [subdomain, domain].join('.')
: domain;
// Treat localhost-style hosts specially so we can generate
// http://localhost[:port]/... links for local dev without
// breaking production URLs.
const isLocalHost =
hostname.startsWith('localhost') ||
hostname.startsWith('0.0.0.0') ||
hostname.endsWith('.localhost');
// When localhost + LOCAL_APP_PORT: use http://localhost:PORT (local dev)
// Otherwise: https (production)
const useLocalUrl = isLocalHost && process.env.LOCAL_APP_PORT;
const localPort = useLocalUrl ? `:${process.env.LOCAL_APP_PORT}` : '';
const protocol = useLocalUrl ? 'http' : 'https';
const url = new URL(`${protocol}://${hostname}${localPort}`);
let subject: string;
let subMessage: string;
let linkText: string;
let inviterName: string | undefined;
switch (params.email_type) {
case 'invite_email': {
if (!params.invite_token || !params.sender_id) {
return { missing: 'invite_token_or_sender_id' };
}
url.pathname = 'register';
url.searchParams.append('invite_token', params.invite_token);
url.searchParams.append('email', params.email);
const scope = Number(params.invite_type) === 2 ? 'org' : 'app';
url.searchParams.append('type', scope);
const inviter = await client.request<any>(GetUser, {
userId: params.sender_id
});
inviterName = inviter?.users?.nodes?.[0]?.displayName;
if (inviterName) {
subject = `${inviterName} invited you to ${nick}!`;
subMessage = `You've been invited to ${nick}`;
} else {
subject = `Welcome to ${nick}!`;
subMessage = `You've been invited to ${nick}`;
}
linkText = 'Join Us';
break;
}
case 'forgot_password': {
if (!params.user_id || !params.reset_token) {
return { missing: 'user_id_or_reset_token' };
}
url.pathname = 'reset-password';
url.searchParams.append('role_id', params.user_id);
url.searchParams.append('reset_token', params.reset_token);
subject = `${nick} Password Reset Request`;
subMessage = 'Click below to reset your password';
linkText = 'Reset Password';
break;
}
case 'email_verification': {
if (!params.email_id || !params.verification_token) {
return { missing: 'email_id_or_verification_token' };
}
url.pathname = 'verify-email';
url.searchParams.append('email_id', params.email_id);
url.searchParams.append('verification_token', params.verification_token);
subject = `${nick} Email Verification`;
subMessage = 'Please confirm your email address';
linkText = 'Confirm Email';
break;
}
default:
return false;
}
const link = url.href;
const html = generate({
title: subject,
link,
linkText,
message: subject,
subMessage,
bodyBgColor: 'white',
headerBgColor: 'white',
messageBgColor: 'white',
messageTextColor: '#414141',
messageButtonBgColor: primary,
messageButtonTextColor: 'white',
companyName: name,
supportEmail,
website,
logo,
headerImageProps: {
alt: 'logo',
align: 'center',
border: 'none',
width: '162px',
paddingLeft: '0px',
paddingRight: '0px',
paddingBottom: '0px',
paddingTop: '0'
}
});
if (isDryRun) {
logger.info('DRY RUN email (skipping send)', {
email_type: params.email_type,
email: params.email,
subject,
link
});
} else {
const sendEmail = useSmtp ? sendSmtp : sendPostmaster;
await sendEmail({
to: params.email,
subject,
html
});
}
return {
complete: true,
...(isDryRun ? { dryRun: true } : null)
};
};
// HTTP/Knative entrypoint (used by @constructive-io/knative-job-fn wrapper)
app.post('/', async (req: any, res: any, next: any) => {
try {
const params = (req.body || {}) as SendEmailParams;
const databaseId =
req.get('X-Database-Id') || req.get('x-database-id') || process.env.DEFAULT_DATABASE_ID;
if (!databaseId) {
return res.status(400).json({ error: 'Missing X-Database-Id header or DEFAULT_DATABASE_ID' });
}
const graphqlUrl = getRequiredEnv('GRAPHQL_URL');
const metaGraphqlUrl = process.env.META_GRAPHQL_URL || graphqlUrl;
// Get API name or schemata from env (for tenant queries like GetUser)
const apiName = process.env.GRAPHQL_API_NAME;
const schemata = process.env.GRAPHQL_SCHEMATA;
// For GetUser query - needs tenant API access via X-Api-Name or X-Schemata
const client = createGraphQLClient(graphqlUrl, {
hostHeaderEnvVar: 'GRAPHQL_HOST_HEADER',
databaseId,
...(apiName && { apiName }),
...(schemata && { schemata }),
});
// For GetDatabaseInfo query - uses same API routing as client
// The private API exposes both user and database queries
const meta = createGraphQLClient(metaGraphqlUrl, {
hostHeaderEnvVar: 'META_GRAPHQL_HOST_HEADER',
databaseId,
...(apiName && { apiName }),
...(schemata && { schemata }),
});
const result = await sendEmailLink(params, {
client,
meta,
databaseId
});
// Validation failures return { missing: '...' } - treat as client error
if (result && typeof result === 'object' && 'missing' in result) {
return res.status(400).json({ error: `Missing required field: ${result.missing}` });
}
res.status(200).json(result);
} catch (err) {
next(err);
}
});
export default app;
// When executed directly (e.g. via `node dist/index.js`), start an HTTP server.
if (require.main === module) {
const port = Number(process.env.PORT ?? 8080);
// Log startup configuration (non-sensitive values only - no API keys or tokens)
logger.info('[send-email-link] Starting with config:', {
port,
graphqlUrl: process.env.GRAPHQL_URL || 'not set',
metaGraphqlUrl: process.env.META_GRAPHQL_URL || process.env.GRAPHQL_URL || 'not set',
apiName: process.env.GRAPHQL_API_NAME || 'not set',
defaultDatabaseId: process.env.DEFAULT_DATABASE_ID || 'not set',
dryRun: isDryRun,
useSmtp,
mailgunDomain: process.env.MAILGUN_DOMAIN || 'not set',
mailgunFrom: process.env.MAILGUN_FROM || 'not set',
localAppPort: process.env.LOCAL_APP_PORT || 'not set',
hasAuthToken: !!process.env.GRAPHQL_AUTH_TOKEN
});
// @constructive-io/knative-job-fn exposes a .listen method that delegates to the Express app
(app as any).listen(port, () => {
logger.info(`listening on port ${port}`);
});
}