Repository navigation
Expand file tree
/
Copy pathapp.ts
More file actions
1020 lines (948 loc) · 37 KB
/
Copy pathapp.ts
File metadata and controls
1020 lines (948 loc) · 37 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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import path from 'node:path'
import {hrtime} from 'node:process'
import {checkOptionName} from 'api/check-option-name'
import {contact} from 'api/contact'
import {createVote} from 'api/create-vote'
import {createVoteComment} from 'api/create-vote-comment'
import {deleteCompatibilityPrompt} from 'api/delete-compatibility-prompt'
import {deleteMessage} from 'api/delete-message'
import {deleteOption} from 'api/delete-option'
import {editMessage} from 'api/edit-message'
import {editVoteComment} from 'api/edit-vote-comment'
import {getChannelMemberships} from 'api/get-channel-memberships'
import {getLastSeenChannelTime, setChannelLastSeenTime} from 'api/get-channel-seen-time'
import {getChannelsCountEndpoint} from 'api/get-channels-count'
import {getCompatibilityQuestionDegeneracy} from 'api/get-compatibility-question-degeneracy'
import {getHiddenProfiles} from 'api/get-hidden-profiles'
import {getLastMessages} from 'api/get-last-messages'
import {getMessagesCountEndpoint} from 'api/get-messages-count'
import {getOptionsEndpoint} from 'api/get-options'
import {getOptionsAdmin} from 'api/get-options-admin'
import {getPinnedCompatibilityQuestions} from 'api/get-pinned-compatibility-questions'
import {getChannelMessagesEndpoint} from 'api/get-private-messages'
import {getUser} from 'api/get-user'
import {hideProfile} from 'api/hide-profile'
import {mergeOptionsEndpoint} from 'api/merge-options'
import {reactToMessage} from 'api/react-to-message'
import {recomputeAllCompatibilityScoresHandler} from 'api/recompute-all-compatibility-scores'
import {renameOption} from 'api/rename-option'
import {saveSubscription} from 'api/save-subscription'
import {saveSubscriptionMobile} from 'api/save-subscription-mobile'
import {searchOptionsEndpoint} from 'api/search-options'
import {sendCityNumberEmails} from 'api/send-city-number-emails'
import {sendEmptyRoomEmails} from 'api/send-empty-room-emails'
import {sendSearchNotifications} from 'api/send-search-notifications'
import {setOptionAlias} from 'api/set-option-alias'
import {sweepUnfinishedSignups} from 'api/sweep-unfinished-signups'
import {localSendTestEmail} from 'api/test'
import {unhideProfile} from 'api/unhide-profile'
import {updateCompatibilityQuestionPin} from 'api/update-compatibility-question-pin'
import {updateConnectionInterests} from 'api/update-connection-interests'
import {updateOptions} from 'api/update-options'
import {updateVoteStatus} from 'api/update-vote-status'
import {vote} from 'api/vote'
import {getVoteMute, setVoteMute} from 'api/vote-mute'
import {API, type APIPath} from 'common/api/schema'
import {APIError, APIErrors, pathWithPrefix} from 'common/api/utils'
import {sendDiscordMessage} from 'common/discord/core'
import {DEPLOYED_WEB_URL, IS_DEV} from 'common/envs/constants'
import {IS_LOCAL} from 'common/hosting/constants'
import {filterDefined} from 'common/util/array'
import compression from 'compression'
import cors from 'cors'
import * as crypto from 'crypto'
import express, {type ErrorRequestHandler, type RequestHandler} from 'express'
import {OpenAPIV3} from 'openapi-types'
import {withMonitoringContext} from 'shared/monitoring/context'
import {log} from 'shared/monitoring/log'
import {metrics} from 'shared/monitoring/metrics'
import {refreshProfileAges} from 'shared/profiles/refresh-ages'
import {createSupabaseDirectClient} from 'shared/supabase/init'
import swaggerUi from 'swagger-ui-express'
import {z, ZodFirstPartyTypeKind, ZodTypeAny} from 'zod'
import {git} from './../metadata.json'
import {version as pkgVersion} from './../package.json'
import {banUser} from './ban-user'
import {blockUser, unblockUser} from './block-user'
import {cancelEvent} from './cancel-event'
import {cancelRsvp} from './cancel-rsvp'
import {getCompatibleProfilesHandler} from './compatible-profiles'
import {createBlogPost} from './create-blog-post'
import {createBookmarkedSearch} from './create-bookmarked-search'
import {createComment} from './create-comment'
import {createCompatibilityQuestion} from './create-compatibility-question'
import {createEvent} from './create-event'
import {createOutreachSearch} from './create-outreach-search'
import {createPrivateUserMessage} from './create-private-user-message'
import {createPrivateUserMessageChannel} from './create-private-user-message-channel'
import {createSpotlight} from './create-spotlight'
import {createTestimonial} from './create-testimonial'
import {createUserAndProfile} from './create-user-and-profile'
import {deleteBookmarkedSearch} from './delete-bookmarked-search'
import {deleteCompatibilityAnswer} from './delete-compatibility-answer'
import {deleteMe} from './delete-me'
import {deleteUnfinishedSignup} from './delete-unfinished-signup'
import {getBlogPost} from './get-blog-post'
import {getBlogPosts} from './get-blog-posts'
import {getBlogPostsAdmin} from './get-blog-posts-admin'
import {getCompatibilityQuestions} from './get-compatibililty-questions'
import {getConnectionInterestsEndpoint} from './get-connection-interests'
import {getCountries} from './get-countries'
import {getCurrentPrivateUser} from './get-current-private-user'
import {getEvents} from './get-events'
import {getLikesAndShips} from './get-likes-and-ships'
import {getMe} from './get-me'
import {getMyReferralCount} from './get-my-referral-count'
import {getMyReferrals} from './get-my-referrals'
import {getNotifications} from './get-notifications'
import {getOutreachQueue} from './get-outreach-queue'
import {getOutreachStats} from './get-outreach-stats'
import {getProfileAnswers} from './get-profile-answers'
import {getProfileFeed} from './get-profile-feed'
import {getProfiles} from './get-profiles'
import {getReferralLeaderboardHandler} from './get-referral-leaderboard'
import {getReferralTreeHandler} from './get-referral-tree'
import {getSearchAlert} from './get-search-alert'
import {getSpotlights} from './get-spotlights'
import {getSpotlightsAdmin} from './get-spotlights-admin'
import {getSupabaseToken} from './get-supabase-token'
import {getTestimonials} from './get-testimonials'
import {getTestimonialsMod} from './get-testimonials-mod'
import {getProfileHandler, getUserAndProfileHandler} from './get-user-and-profile'
import {getUserDataExport} from './get-user-data-export'
import {getUserJourneys} from './get-user-journeys'
import {hasFreeLike} from './has-free-like'
import {health} from './health'
import {type APIHandler, typedEndpoint} from './helpers/endpoint'
import {hideComment} from './hide-comment'
import {leavePrivateUserMessageChannel} from './leave-private-user-message-channel'
import {likeProfile} from './like-profile'
import {llmExtractProfileEndpoint} from './llm-extract-profile'
import {markAllNotifsRead} from './mark-all-notifications-read'
import {removePinnedPhoto} from './remove-pinned-photo'
import {repoStats} from './repo-stats'
import {report} from './report'
import {requestReviewPrompt} from './request-review-prompt'
import {requestSharePrompt} from './request-share-prompt'
import {rsvpEvent} from './rsvp-event'
import {searchLocationEndpoint} from './search-location'
import {searchNearCity} from './search-near-city'
import {searchUsers} from './search-users'
import {setCompatibilityAnswer} from './set-compatibility-answer'
import {setLastOnlineTime} from './set-last-online-time'
import {shipProfiles} from './ship-profiles'
import {starProfile} from './star-profile'
import {stats} from './stats'
import {transcribeAudio} from './transcribe-audio'
import {unsubscribe} from './unsubscribe'
import {updateBlogPost} from './update-blog-post'
import {updateEvent} from './update-event'
import {updateMe} from './update-me'
import {updateNotifSettings} from './update-notif-setting'
import {updateOutreachContact} from './update-outreach-contact'
import {updatePrivateUserMessageChannel} from './update-private-user-message-channel'
import {updateProfileEndpoint} from './update-profile'
import {updateSpotlight} from './update-spotlight'
import {updateTestimonialStatus} from './update-testimonial-status'
import {updateUserLocale} from './update-user-locale'
import {validateUsernameEndpoint} from './validate-username'
// const corsOptions: CorsOptions = {
// origin: ['*'], // Only allow requests from this domain
// methods: ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'OPTIONS'],
// allowedHeaders: ['Content-Type', 'Authorization'],
// credentials: true, // if you use cookies or auth headers
// };
// Deliberately unrestricted: `Access-Control-Allow-Origin: *`, no `Access-Control-Allow-Credentials`.
// The API has no ambient authority to protect — auth is an `Authorization` header the caller must attach
// explicitly (see helpers/endpoint.ts), there is no session cookie, and a cross-origin page cannot read a
// visitor's Firebase token out of compassmeet.com's storage. That, not CORS, is what rules out CSRF here;
// CORS is a browser policy that curl and the native shells ignore anyway. The API is also meant to be
// publicly callable (Swagger docs, signed-out reads) and the Capacitor shells request from origins
// (capacitor://localhost, ionic://localhost) that an allowlist keeps breaking on.
//
// If auth ever becomes cookie-based — or this gains `credentials: true` — the wildcard has to be replaced
// with an explicit origin allowlist in the same change. See the CORS section of SECURITY.md.
const allowCorsUnrestricted: RequestHandler = cors({})
function cacheController(policy?: string): RequestHandler {
return (_req, res, next) => {
if (policy) res.appendHeader('Cache-Control', policy)
next()
}
}
const requestMonitoring: RequestHandler = (req, _res, next) => {
const traceContext = req.get('X-Cloud-Trace-Context')
const traceId = traceContext ? traceContext.split('/')[0] : crypto.randomUUID()
const context = {endpoint: req.path, traceId}
withMonitoringContext(context, () => {
const startTs = hrtime.bigint()
log(`${req.method} ${req.url}`)
metrics.inc('http/request_count', {endpoint: req.path})
next()
// There's a bug worth flagging in that middleware. The timing/cleanup code after next() won't work as you expect:
// next() is synchronous — it just hands off to the next middleware. The response hasn't been sent by the time endTs is captured. To measure actual latency you'd want to hook into res.on('finish', ...)
const endTs = hrtime.bigint()
const latencyMs = Number(endTs - startTs) / 1e6
metrics.push('http/request_latency', latencyMs, {endpoint: req.path})
})
}
const apiErrorHandler: ErrorRequestHandler = (error, _req, res, _next) => {
if (error instanceof APIError) {
log.info(error)
if (!res.headersSent) {
res.status(error.code).json(error.toJSON())
}
} else {
log.error(error)
if (!res.headersSent) {
const apiError = APIErrors.internalServerError(error.message || 'Internal server error', {
originalError: error.toString(),
context: 'Unhandled exception in request processing',
})
res.status(500).json(apiError.toJSON())
}
}
}
export const app = express()
// Cloud Run's frontend does not compress responses for us, so without this every JSON body goes out
// raw. API payloads are repetitive (the same keys across every row of a list) and compress heavily.
app.use(compression())
app.use(requestMonitoring)
const schemaCache = new WeakMap<ZodTypeAny, any>()
export function zodToOpenApiSchema(zodObj: ZodTypeAny): any {
if (schemaCache.has(zodObj)) {
return schemaCache.get(zodObj)
}
const def: any = (zodObj as any)._def
const typeName = def.typeName as ZodFirstPartyTypeKind
// Placeholder so recursive references can point here
const placeholder: any = {}
schemaCache.set(zodObj, placeholder)
let schema: any
switch (typeName) {
case 'ZodString':
schema = {type: 'string'}
break
case 'ZodNumber':
schema = {type: 'number'}
break
case 'ZodBoolean':
schema = {type: 'boolean'}
break
case 'ZodEnum':
schema = {type: 'string', enum: def.values}
break
case 'ZodArray':
schema = {type: 'array', items: zodToOpenApiSchema(def.type)}
break
case 'ZodObject': {
const shape = def.shape()
const properties: Record<string, any> = {}
const required: string[] = []
for (const key in shape) {
const child = shape[key]
properties[key] = zodToOpenApiSchema(child)
if (!child.isOptional()) required.push(key)
}
schema = {
type: 'object',
properties,
...(required.length ? {required} : {}),
}
break
}
case 'ZodRecord':
schema = {
type: 'object',
additionalProperties: zodToOpenApiSchema(def.valueType),
}
break
case 'ZodIntersection': {
const left = zodToOpenApiSchema(def.left)
const right = zodToOpenApiSchema(def.right)
schema = {allOf: [left, right]}
break
}
case 'ZodLazy':
schema = {type: 'object', description: 'Lazy schema - details omitted'}
break
case 'ZodUnion':
schema = {
oneOf: def.options.map((opt: ZodTypeAny) => zodToOpenApiSchema(opt)),
}
break
default:
schema = {type: 'string'} // fallback for unhandled
}
Object.assign(placeholder, schema)
return schema
}
function inferTag(route: string) {
let tag = 'General'
if (route.includes('user') || route.includes('profile')) tag = 'Profiles'
if (route.includes('auth') || route.includes('login') || route === 'me') tag = 'Authentication'
if (route.includes('search') || route.includes('location')) tag = 'Search'
if (route.includes('message') || route.includes('channel')) tag = 'Messaging'
if (route.includes('compatibility') || route.includes('question')) tag = 'Compatibility'
if (
route.includes('like') ||
route.includes('ship') ||
route.includes('star') ||
route.includes('block')
)
tag = 'Relations'
if (route.includes('event') || route.includes('rsvp')) tag = 'Events'
if (route.includes('notification') || route.includes('notif')) tag = 'Notifications'
if (route.includes('comment')) tag = 'Comments'
if (route.includes('report') || route.includes('ban')) tag = 'Moderation'
if (route.includes('option') || route.includes('locale')) tag = 'Utilities'
return tag
}
function generateSwaggerPaths(api: typeof API) {
const paths: Record<string, any> = {}
for (const [route, config] of Object.entries(api)) {
const pathKey = '/' + route.replace(/_/g, '-') // optional: convert underscores to dashes
const method = config.method.toLowerCase()
const summary = (config as any).summary ?? route
const tag = (config as any).tag ?? inferTag(route)
const operation: any = {
summary,
description: (config as any).description ?? '',
tags: [tag],
responses: {
200: {
description: 'Success',
content: {
'application/json': {
schema: {type: 'object'},
example: (config as any).exampleResponse ?? {},
},
},
},
400: {
description: 'Bad Request - Invalid input or malformed request',
content: {
'application/json': {
schema: {
type: 'object',
properties: {
message: {type: 'string'},
details: {type: 'object'},
},
},
},
},
},
401: {
description: 'Unauthorized - Authentication required',
content: {
'application/json': {
schema: {
type: 'object',
properties: {
message: {type: 'string'},
},
},
},
},
},
403: {
description: 'Forbidden - Insufficient permissions',
content: {
'application/json': {
schema: {
type: 'object',
properties: {
message: {type: 'string'},
},
},
},
},
},
404: {
description: 'Not Found - Resource does not exist',
content: {
'application/json': {
schema: {
type: 'object',
properties: {
message: {type: 'string'},
},
},
},
},
},
500: {
description: 'Internal Server Error - Something went wrong on our end',
content: {
'application/json': {
schema: {
type: 'object',
properties: {
message: {type: 'string'},
},
},
},
},
},
},
}
// Include props in request body for POST/PUT
if (config.props && ['post', 'put', 'patch'].includes(method)) {
operation.requestBody = {
required: true,
content: {
'application/json': {
schema: zodToOpenApiSchema(config.props),
example: (config as any).exampleRequest ?? {},
},
},
}
}
// Include props as query parameters for GET/DELETE
if (config.props && ['get', 'delete'].includes(method)) {
const shape = (config.props as z.ZodObject<any>)._def.shape()
operation.parameters = Object.entries(shape).map(([key, zodType]) => {
const typeMap: Record<string, string> = {
ZodString: 'string',
ZodNumber: 'number',
ZodBoolean: 'boolean',
ZodArray: 'array',
}
const t = zodType as z.ZodTypeAny // assert type to ZodTypeAny
const typeName = t._def.typeName
return {
name: key,
in: 'query',
description: (config as any).paramDescriptions?.[key] ?? '',
required: !(t.isOptional ?? false),
schema: {type: typeMap[typeName] ?? 'string'},
}
})
}
paths[pathKey] = {
[method]: operation,
}
if (config.authed) {
operation.security = [{BearerAuth: []}]
}
}
return paths
}
const apiKey = process.env.NEXT_PUBLIC_FIREBASE_API_KEY ?? 'API_KEY'
const accessInfo = `
To obtain a token:
**In your browser console while logged in (CTRL+SHIFT+C, then select the Console tab):**
\`\`\`js
const db = await new Promise((res, rej) => {
const req = indexedDB.open('firebaseLocalStorageDb')
req.onsuccess = () => res(req.result)
req.onerror = rej
})
const req = db.transaction('firebaseLocalStorage', 'readonly').objectStore('firebaseLocalStorage').getAll()
req.onsuccess = () => {
const id_token = req.result[0].value.stsTokenManager.accessToken
console.log('YOUR_FIREBASE_JWT_TOKEN is the string below:')
console.log(id_token)
copy(id_token)
}
\`\`\`
**For testing (REST):**
\`\`\`bash
curl 'https://identitytoolkit.googleapis.com/v1/accounts:signInWithPassword?key=${apiKey}' \\
-H 'Content-Type: application/json' \\
--data '{"email":"you@example.com","password":"yourpassword","returnSecureToken":true}'
# Use the returned idToken as your Bearer token
\`\`\`
Tokens expire after **1 hour**. Refresh by calling \`getIdToken(true)\`.
Pass the token in the Authorization header for all authenticated requests:
\`\`\`
Authorization: Bearer YOUR_FIREBASE_JWT_TOKEN
\`\`\`
In the API docs, authenticate through the green button at the bottom right of this section (BearerAuth token).
`
const securitySchemes: OpenAPIV3.ComponentsObject['securitySchemes'] = {
BearerAuth: {
type: 'http',
scheme: 'bearer',
bearerFormat: 'JWT',
description: 'Firebase JWT token obtained through authentication',
},
}
if (IS_LOCAL) {
securitySchemes.ApiKeyAuth = {
type: 'apiKey',
in: 'header',
name: 'x-api-key',
description: 'API key for internal/non-user endpoints',
}
}
const swaggerDocument: OpenAPIV3.Document = {
openapi: '3.0.0',
info: {
title: 'Compass API' + (IS_DEV ? ' (dev)' : ''),
description: `
Compass is a free, open-source platform to help people form deep, meaningful, and lasting connections — whether platonic, romantic, or collaborative. Our API provides programmatic access to core platform features including user profiles, messaging, compatibility scoring, and community features.
## Access Tiers
### Tier 1 — Public Access (no authentication required)
Some endpoints are publicly accessible without authentication, such as events and server health. These are marked as **public** in the endpoint documentation.
### Tier 2 — User Access (Firebase authentication required)
Most endpoints require a valid Firebase JWT token. This gives you access to your own user data, profile, messages, and all interactive features.
${IS_LOCAL ? accessInfo : ''}
**Don't have an account?** [Register on Compass](${DEPLOYED_WEB_URL}/register) to get started.
## Rate Limiting
API requests are subject to rate limiting to ensure fair usage and platform stability. Exceeding limits will result in a \`429 Too Many Requests\` response. Rate limits are applied per authenticated user. Unauthenticated requests are limited by IP.
## Versioning
This documentation reflects API version ${pkgVersion}. Endpoints marked as **deprecated** will include a \`Sunset\` header indicating when they will be removed, and a \`Link\` header pointing to the replacement endpoint. Breaking changes are avoided where possible.
## Error Handling
All API responses follow a consistent error format:
\`\`\`json
{
"message": "Human-readable error description",
"details": { /* Optional additional context */ }
}
\`\`\`
Common HTTP status codes:
- \`200\` Success
- \`400\` Bad Request — invalid or missing input
- \`401\` Unauthorized — missing or expired token
- \`403\` Forbidden — valid token but insufficient permissions
- \`404\` Not Found — resource does not exist
- \`429\` Too Many Requests — rate limit exceeded
- \`500\` Internal Server Error
## Open Source
Compass is open source. Contributions, bug reports, and feature requests are welcome on [GitHub](https://github.com/CompassConnections/Compass).
## Git Information
Commit: ${git.revision} (${git.commitDate})`,
version: pkgVersion,
contact: {
name: 'Compass Team',
email: 'hello@compassmeet.com',
url: 'https://compassmeet.com',
},
},
paths: generateSwaggerPaths(API),
components: {securitySchemes},
tags: filterDefined([
{
name: 'General',
description: 'General endpoints and health checks',
},
{
name: 'Authentication',
description: 'User authentication and account management endpoints',
},
{
name: 'Users',
description: 'User accounts',
},
{
name: 'Profiles',
description: 'User profile creation, retrieval, updating, and deletion',
},
{
name: 'Search',
description: 'User discovery and search functionality',
},
{
name: 'Messages',
description: 'Direct messaging between users',
},
{
name: 'Compatibility',
description: 'Compatibility questions, answers, and scoring',
},
{
name: 'Relations',
description: 'User relationships (likes, ships, blocks, comments)',
},
{
name: 'Notifications',
description: 'User notifications and preferences',
},
{
name: 'Events',
description: 'Community events and RSVP management',
},
{
name: 'Votes',
description: 'Voting system for user content and polls',
},
{
name: 'Testimonials',
description:
'The public testimonials wall, plus the moderation endpoints that decide what appears on it',
},
{
name: 'Blog',
description:
'The Compass blog: the public index and post reads, plus the admin endpoints that write and publish them',
},
{
name: 'Spotlights',
description:
'Member spotlights on the home page: consent-gated, admin-curated snapshots of real profiles',
},
{
name: 'Reviews',
description:
'Deciding when to show the native App Store / Play Store review card (docs/app-store-reviews.md) and the share-or-donate video',
},
{
name: 'Moderation',
description: 'Report system and user moderation',
},
{
name: 'Admin',
description: 'Administrative functions including user bans and moderation',
},
{
name: 'Contact',
description: 'Contact form and support requests',
},
{
name: 'Utilities',
description: 'Helper functions and utilities',
},
IS_LOCAL && {
name: 'Local',
description: 'Local development and testing endpoints',
},
]),
} as OpenAPIV3.Document
// Triggers Missing parameter name at index 3: *; visit https://git.new/pathToRegexpError for info
// May not be necessary
// app.options('*', allowCorsUnrestricted)
const handlers: {[k in APIPath]: APIHandler<k>} = {
'ban-user': banUser,
'compatible-profiles': getCompatibleProfilesHandler,
contact: contact,
'create-bookmarked-search': createBookmarkedSearch,
'create-comment': createComment,
'create-compatibility-question': createCompatibilityQuestion,
'create-private-user-message': createPrivateUserMessage,
'create-private-user-message-channel': createPrivateUserMessageChannel,
'create-user-and-profile': createUserAndProfile,
'create-vote': createVote,
'create-vote-comment': createVoteComment,
'delete-bookmarked-search': deleteBookmarkedSearch,
'delete-compatibility-answer': deleteCompatibilityAnswer,
'delete-message': deleteMessage,
'edit-message': editMessage,
'edit-vote-comment': editVoteComment,
'get-channel-memberships': getChannelMemberships,
'get-channel-messages': getChannelMessagesEndpoint,
'get-channel-seen-time': getLastSeenChannelTime,
'get-last-messages': getLastMessages,
'get-compatibility-questions': getCompatibilityQuestions,
'get-likes-and-ships': getLikesAndShips,
'get-messages-count': getMessagesCountEndpoint,
'get-channels-count': getChannelsCountEndpoint,
'get-notifications': getNotifications,
'get-options': getOptionsEndpoint,
'search-options': searchOptionsEndpoint,
'check-option-name': checkOptionName,
'delete-compatibility-prompt': deleteCompatibilityPrompt,
'recompute-all-compatibility-scores': recomputeAllCompatibilityScoresHandler,
'get-compatibility-question-degeneracy': getCompatibilityQuestionDegeneracy,
'get-options-admin': getOptionsAdmin,
'merge-options': mergeOptionsEndpoint,
'delete-option': deleteOption,
'rename-option': renameOption,
'set-option-alias': setOptionAlias,
'get-outreach-queue': getOutreachQueue,
'get-outreach-stats': getOutreachStats,
'get-my-referrals': getMyReferrals,
'get-my-referral-count': getMyReferralCount,
'get-referral-tree': getReferralTreeHandler,
'get-referral-leaderboard': getReferralLeaderboardHandler,
'update-outreach-contact': updateOutreachContact,
'create-outreach-search': createOutreachSearch,
'get-search-alert': getSearchAlert,
'get-testimonials': getTestimonials,
'get-testimonials-mod': getTestimonialsMod,
'create-testimonial': createTestimonial,
'update-testimonial-status': updateTestimonialStatus,
'get-blog-posts': getBlogPosts,
'get-blog-post': getBlogPost,
'get-blog-posts-admin': getBlogPostsAdmin,
'create-blog-post': createBlogPost,
'update-blog-post': updateBlogPost,
'request-review-prompt': requestReviewPrompt,
'request-share-prompt': requestSharePrompt,
'get-spotlights': getSpotlights,
'get-spotlights-admin': getSpotlightsAdmin,
'create-spotlight': createSpotlight,
'update-spotlight': updateSpotlight,
'get-profile-answers': getProfileAnswers,
'get-profile-feed': getProfileFeed,
'get-countries': getCountries,
'get-profiles': getProfiles,
'get-supabase-token': getSupabaseToken,
'get-user-journeys': getUserJourneys,
'has-free-like': hasFreeLike,
'hide-comment': hideComment,
'hide-profile': hideProfile,
'unhide-profile': unhideProfile,
'get-hidden-profiles': getHiddenProfiles,
'leave-private-user-message-channel': leavePrivateUserMessageChannel,
'like-profile': likeProfile,
'mark-all-notifs-read': markAllNotifsRead,
'me/delete': deleteMe,
'delete-unfinished-signup': deleteUnfinishedSignup,
'me/data': getUserDataExport,
'me/private': getCurrentPrivateUser,
'me/update': updateMe,
'react-to-message': reactToMessage,
'remove-pinned-photo': removePinnedPhoto,
'save-subscription': saveSubscription,
'save-subscription-mobile': saveSubscriptionMobile,
'search-location': searchLocationEndpoint,
'search-near-city': searchNearCity,
'search-users': searchUsers,
'set-channel-seen-time': setChannelLastSeenTime,
'set-compatibility-answer': setCompatibilityAnswer,
'set-last-online-time': setLastOnlineTime,
'ship-profiles': shipProfiles,
'star-profile': starProfile,
'update-notif-settings': updateNotifSettings,
'update-options': updateOptions,
'update-user-locale': updateUserLocale,
'update-private-user-message-channel': updatePrivateUserMessageChannel,
'update-profile': updateProfileEndpoint,
'update-compatibility-question-pin': updateCompatibilityQuestionPin,
'get-pinned-compatibility-questions': getPinnedCompatibilityQuestions,
'get-connection-interests': getConnectionInterestsEndpoint,
'update-connection-interest': updateConnectionInterests,
'user/by-id/:id': getUser,
'user/by-id/:id/block': blockUser,
'user/by-id/:id/unblock': unblockUser,
vote: vote,
'set-vote-mute': setVoteMute,
'update-vote-status': updateVoteStatus,
'get-vote-mute': getVoteMute,
'validate-username': validateUsernameEndpoint,
'llm-extract-profile': llmExtractProfileEndpoint,
'transcribe-audio': transcribeAudio,
// 'user/:username': getUser,
// 'user/:username/lite': getDisplayUser,
// 'user/by-id/:id/lite': getDisplayUser,
'cancel-event': cancelEvent,
'cancel-rsvp': cancelRsvp,
'create-event': createEvent,
'get-events': getEvents,
'rsvp-event': rsvpEvent,
'update-event': updateEvent,
health: health,
stats: stats,
'repo-stats': repoStats,
'unsubscribe/:token': unsubscribe,
me: getMe,
'get-user-and-profile': getUserAndProfileHandler,
'get-profile': getProfileHandler,
report: report,
}
Object.entries(handlers).forEach(([path, handler]) => {
const api = API[path as APIPath]
const cache = cacheController((api as any).cache)
const url = pathWithPrefix(('/' + path) as APIPath)
const apiRoute = [
url,
// Endpoints that carry binary payloads (e.g. base64 audio) declare a larger `bodyLimit`.
express.json({limit: (api as any).bodyLimit ?? '1mb'}),
allowCorsUnrestricted,
cache,
typedEndpoint(path as any, handler as any),
apiErrorHandler,
] as const
if (api.method === 'POST') {
app.post(...apiRoute)
} else if (api.method === 'GET') {
app.get(...apiRoute)
// } else if (api.method === 'PUT') {
// app.put(...apiRoute)
} else {
throw new Error('Unsupported API method')
}
})
// Internal Endpoints
app.post(pathWithPrefix('/internal/send-search-notifications'), async (req, res) => {
const apiKey = req.header('x-api-key')
if (!IS_LOCAL && apiKey !== process.env.COMPASS_API_KEY) {
return res.status(401).json({error: 'Unauthorized'})
}
try {
const result = await sendSearchNotifications()
return res.status(200).json(result)
} catch (err) {
console.error('Failed to send notifications:', err)
await sendDiscordMessage(
'Failed to send [daily notifications](https://console.cloud.google.com/cloudscheduler?project=compass-130ba) for bookmarked searches...',
'health',
)
return res.status(500).json({error: 'Internal server error'})
}
})
// Ages tick over at midnight rather than on save, so `profiles.age` needs a daily nudge (see
// refreshProfileAges). The daily search-alert job above already runs it — this is the same pass on
// its own, for scheduling it independently or catching up by hand after an outage. Running it twice
// costs nothing: it only touches rows whose cached age is wrong.
app.post(pathWithPrefix('/internal/refresh-profile-ages'), async (req, res) => {
const apiKey = req.header('x-api-key')
if (!IS_LOCAL && apiKey !== process.env.COMPASS_API_KEY) {
return res.status(401).json({error: 'Unauthorized'})
}
try {
const updated = await refreshProfileAges(createSupabaseDirectClient())
return res.status(200).json({status: 'success', updated})
} catch (err) {
console.error('Failed to refresh profile ages:', err)
await sendDiscordMessage('Failed to refresh profile ages...', 'health')
return res.status(500).json({error: 'Internal server error'})
}
})
/**
* The two automated outreach jobs. They partition the directory between them — above the nearby-count
* threshold gets the personalised share email, below it gets Contact #E — and both refuse to touch
* anyone already in a hand-written founder thread. Run them on separate schedules; running either
* twice is harmless, since the send ledger is what decides, not the cadence.
*/
const internalOutreachJob = (
path: string,
run: (opts: {batchSize?: number; dryRun?: boolean}) => Promise<unknown>,
failureMessage: string,
) =>
// JSON parsing is per-route here rather than app-wide, so an internal endpoint that reads a body
// has to ask for it explicitly. Without this `req.body` is undefined and every run silently uses
// the default batch size.
app.post(pathWithPrefix(path), express.json(), async (req, res) => {
const apiKey = req.header('x-api-key')
if (!IS_LOCAL && apiKey !== process.env.COMPASS_API_KEY) {
return res.status(401).json({error: 'Unauthorized'})
}
try {
const batchSize = req.body?.batchSize ? Number(req.body.batchSize) : undefined
const result = await run({batchSize, dryRun: !!req.body?.dryRun})
return res.status(200).json(result)
} catch (err) {
console.error(failureMessage, err)
await sendDiscordMessage(failureMessage, 'health')
return res.status(500).json({error: 'Internal server error'})
}
})
internalOutreachJob(
'/internal/send-city-number-emails',
sendCityNumberEmails,
'Failed to send city-number outreach emails...',
)
internalOutreachJob(
'/internal/send-empty-room-emails',
sendEmptyRoomEmails,
'Failed to send empty-room (Contact #E) outreach emails...',
)
/**
* Not outreach, but the same shape — a batch-capped, dry-runnable, key-protected job — so it shares
* the wrapper. Daily: the grace period it enforces is a number quoted in an email, and a job that
* runs less often keeps that promise late. See `sweepUnfinishedSignups` and
* `common/unfinished-signups` for the rule.
*/
internalOutreachJob(
'/internal/sweep-unfinished-signups',
sweepUnfinishedSignups,
'Failed to sweep unfinished sign-ups (notice + retention job)...',
)
const responses = {
200: {
description: 'Request successful',
content: {
'application/json': {
schema: {
type: 'object',
properties: {
status: {type: 'string', example: 'success'},
},
},
},
},
},
401: {
description: 'Unauthorized (e.g., invalid or missing API key)',
content: {
'application/json': {
schema: {
type: 'object',
properties: {
error: {type: 'string', example: 'Unauthorized'},
},
},
},
},
},
500: {
description: 'Internal server error during request processing',
content: {
'application/json': {
schema: {
type: 'object',
properties: {
error: {type: 'string', example: 'Internal server error'},
},
},
},
},
},
}
// `/internal/send-search-notifications` is deliberately omitted from the public OpenAPI spec: it has no
// external consumer, and documenting it only advertises the `x-api-key` header and the scheduler surface.
// Local Endpoints
if (IS_LOCAL) {
app.post(pathWithPrefix('/local/send-test-email'), async (req, res) => {
if (!IS_LOCAL) {
return res.status(401).json({error: 'Unauthorized'})
}
try {
const result = await localSendTestEmail()
return res.status(200).json(result)
} catch (err) {
return res.status(500).json({error: err})
}
})
swaggerDocument.paths['/local/send-test-email'] = {
post: {
summary: 'Send a test email',
description: 'Local endpoint to send a test email.',
tags: ['Local'],
requestBody: {
required: false,
},
responses: responses,
},
} as any
}
const rootPath = pathWithPrefix('/')
app.get(
rootPath,
swaggerUi.setup(swaggerDocument, {
customSiteTitle: 'Compass API Docs',
customCssUrl: '/swagger.css',
customJs: `
const meta = document.createElement('meta');
meta.name = 'viewport';
meta.content = 'width=device-width, initial-scale=1';