Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion backend/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -138,7 +138,8 @@
"uuid": "^9.0.0",
"validator": "^13.7.0",
"verify-github-webhook": "^1.0.1",
"zlib-sync": "^0.1.8"
"zlib-sync": "^0.1.8",
"zod": "^4.3.6"
},
"private": true,
"devDependencies": {
Expand All @@ -150,6 +151,7 @@
"@types/bunyan-format": "^0.2.5",
"@types/config": "^3.3.0",
"@types/cron": "^2.0.0",
"@types/express": "^4.17.17",
"@types/html-to-text": "^8.1.1",
"@types/node": "~18.0.4",
"@types/sanitize-html": "^2.6.2",
Expand Down
20 changes: 10 additions & 10 deletions backend/src/api/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,16 @@ setImmediate(async () => {

app.use(bodyParser.urlencoded({ limit: '5mb', extended: true }))

app.use((req, res, next) => {
// @ts-ignore
req.userData = {
ip: req.ip,
userAgent: req.headers ? req.headers['user-agent'] : null,
}

next()
})

// Public API uses its own OAuth2 auth and error flow
// Must be mounted before internal endpoints.
app.use('/', publicRouter())
Expand All @@ -164,16 +174,6 @@ setImmediate(async () => {
// to set the currentUser to the requests
app.use(authMiddleware)

app.use((req, res, next) => {
// @ts-ignore
req.userData = {
ip: req.ip,
userAgent: req.headers ? req.headers['user-agent'] : null,
}

next()
})

app.use('/health', async (req: any, res) => {
try {
const seq = SequelizeRepository.getSequelize(req)
Expand Down
29 changes: 10 additions & 19 deletions backend/src/api/member/memberMerge.ts
Original file line number Diff line number Diff line change
@@ -1,36 +1,27 @@
import { CommonMemberService } from '@crowd/common_services'
import { CommonMemberService, invalidateMemberQueryCache } from '@crowd/common_services'
import { optionsQx } from '@crowd/data-access-layer'

import MemberService from '@/services/memberService'

import Permissions from '../../security/permissions'
import track from '../../segment/track'
import PermissionChecker from '../../services/user/permissionChecker'

export default async (req, res) => {
new PermissionChecker(req).validateHas(Permissions.values.memberEdit)

const commonMemberService = new CommonMemberService(optionsQx(req), req.temporal, req.log)
const memberService = new MemberService(req)
const { memberId } = req.params
const { memberToMerge } = req.body

const service = new CommonMemberService(optionsQx(req), req.temporal, req.log)

const payload = await commonMemberService.merge(req.params.memberId, req.body.memberToMerge, req)
const payload = await service.merge(memberId, memberToMerge, req)

// Invalidate member query cache after merge
try {
await memberService.invalidateMemberQueryCache([req.params.memberId, req.body.memberToMerge])
req.log.debug('Invalidated member query cache after merge')
await invalidateMemberQueryCache(req.redis, [memberId, memberToMerge])
} catch (error) {
// Don't fail the merge if cache invalidation fails
req.log.warn('Failed to invalidate member query cache after merge', { error })
req.log.warn({ error }, 'Cache invalidation failed after member merge')
}

track(
'Merge members',
{ memberId: req.params.memberId, memberToMergeId: req.body.memberToMerge },
{ ...req },
)

const status = payload.status || 200
track('Merge members', { memberId, memberToMergeId: memberToMerge }, req)

await req.responseHandler.success(req, res, payload, status)
return req.responseHandler.success(req, res, payload, payload.status ?? 200)
}
2 changes: 1 addition & 1 deletion backend/src/api/member/memberUnmerge.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,5 @@ export default async (req, res) => {

const payload = await new MemberService(req).unmerge(req.params.memberId, req.body)

await req.responseHandler.success(req, res, payload, 200)
return req.responseHandler.success(req, res, payload)
}
30 changes: 30 additions & 0 deletions backend/src/api/public/middlewares/errorHandler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
} from 'express-oauth2-jwt-bearer'

import { HttpError, InsufficientScopeError, InternalError, UnauthorizedError } from '@crowd/common'
import { SlackChannel, SlackPersona, sendSlackNotification } from '@crowd/slack'

/**
* Converts errors to structured JSON: `{ error: { code, message } }`.
Expand Down Expand Up @@ -33,6 +34,35 @@ export const errorHandler: ErrorRequestHandler = (
return
}

req.log.error(
{ error, url: req.url, method: req.method, query: req.query, body: req.body },
'Unhandled error in public API',
)

sendSlackNotification(
SlackChannel.ALERTS,
SlackPersona.ERROR_REPORTER,
`Public API Error 500: ${req.method} ${req.url}`,
[
{
title: 'Request',
text: `*Method:* \`${req.method}\`\n*URL:* \`${req.url}\``,
},
{
title: 'Error',
text: `*Name:* \`${error?.name || 'Unknown'}\`\n*Message:* ${error?.message || 'No message'}`,
},
...(error?.stack
? [
{
title: 'Stack Trace',
text: `\`\`\`${error.stack.substring(0, 2700)}\`\`\``,
},
]
: []),
],
)

const unknownError = new InternalError()
res.status(unknownError.status).json(unknownError.toJSON())
}
6 changes: 2 additions & 4 deletions backend/src/api/public/middlewares/oauth2Middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { auth } from 'express-oauth2-jwt-bearer'
import { UnauthorizedError } from '@crowd/common'

import type { Auth0Configuration } from '@/conf/configTypes'
import type { ApiRequest, Auth0TokenPayload } from '@/types/api'
import type { Auth0TokenPayload } from '@/types/api'

function resolveActor(req: Request, _res: Response, next: NextFunction): void {
const payload = (req.auth?.payload ?? {}) as Auth0TokenPayload
Expand All @@ -18,11 +18,9 @@ function resolveActor(req: Request, _res: Response, next: NextFunction): void {

const id = rawId.replace(/@clients$/, '')

const authReq = req as ApiRequest

const scopes = typeof payload.scope === 'string' ? payload.scope.split(' ').filter(Boolean) : []

authReq.actor = { id, type: 'service', scopes }
req.actor = { id, type: 'service', scopes }

next()
}
Expand Down
5 changes: 2 additions & 3 deletions backend/src/api/public/middlewares/requireScopes.ts
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
import type { NextFunction, Response } from 'express'
import type { NextFunction, Request, Response } from 'express'

import { InsufficientScopeError, UnauthorizedError } from '@crowd/common'

import { Scope } from '@/security/scopes'
import type { ApiRequest } from '@/types/api'

export const requireScopes =
(required: Scope[], mode: 'all' | 'any' = 'all') =>
(req: ApiRequest, _res: Response, next: NextFunction) => {
(req: Request, _res: Response, next: NextFunction) => {
if (!req.actor) {
next(new UnauthorizedError())
return
Expand Down
10 changes: 0 additions & 10 deletions backend/src/api/public/v1/identities/getIdentities.ts

This file was deleted.

15 changes: 0 additions & 15 deletions backend/src/api/public/v1/identities/index.ts

This file was deleted.

6 changes: 4 additions & 2 deletions backend/src/api/public/v1/index.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import { Router } from 'express'

import { identitiesRouter } from './identities'
import { membersRouter } from './members'
import { organizationsRouter } from './organizations'

export function v1Router(): Router {
const router = Router()

router.use('/identities', identitiesRouter())
router.use('/members', membersRouter())
router.use('/organizations', organizationsRouter())

return router
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import type { Request, Response } from 'express'
import { z } from 'zod'

import { NotFoundError } from '@crowd/common'
import {
MemberField,
fetchMemberIdentities,
findMemberById,
optionsQx,
} from '@crowd/data-access-layer'

import { ok } from '@/utils/api'
import { validateOrThrow } from '@/utils/validation'

const paramsSchema = z.object({
memberId: z.uuid(),
})

export async function getMemberIdentities(req: Request, res: Response): Promise<void> {
const { memberId } = validateOrThrow(paramsSchema, req.params)
const qx = optionsQx(req)

const member = await findMemberById(qx, memberId, [MemberField.ID])

if (!member) throw new NotFoundError('Member not found')

const rawIdentities = await fetchMemberIdentities(qx, memberId)

const identities = rawIdentities.map(
({ id, value, platform, verified, source, createdAt, updatedAt }) => ({
id,
value,
platform,
verified,
source,
createdAt,
updatedAt,
}),
)

ok(res, { identities })
}
Loading