-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathaccept-request-to-join.ts
More file actions
277 lines (245 loc) · 7.65 KB
/
Copy pathaccept-request-to-join.ts
File metadata and controls
277 lines (245 loc) · 7.65 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
import { Prisma } from "@prisma/client";
import type { Request, Response } from "express";
import { z } from "zod";
import { prisma } from "@/utils/prisma";
const acceptRequestParams = z.object({
requestId: z.string().min(1, "Request ID is required"),
});
export type AcceptRequestToJoinParams = z.infer<typeof acceptRequestParams>;
export type AcceptRequestToJoinResponse = {
id: string;
accepted: boolean;
inviteCodeUse: {
id: string;
usedAt: string;
};
};
/**
* Accept a join request and create an InviteCodeUse record
* Only the invite creator or notification targets can accept requests
*/
export async function acceptRequestToJoin(req: Request, res: Response) {
try {
const params = await acceptRequestParams.parseAsync(req.params);
const { xmtpId } = res.locals;
// Find the authenticated user's identity
const authenticatedIdentity = await prisma.deviceIdentity.findFirst({
where: { xmtpId },
});
if (!authenticatedIdentity) {
res.status(404).json({
success: false,
message: "Request not found",
});
return;
}
// Load the join request with related entities
const requestToJoin = await prisma.inviteCodeRequest.findUnique({
where: { id: params.requestId },
include: {
requester: true,
inviteCode: {
include: {
createdBy: true,
notificationTargets: {
include: {
deviceIdentity: true,
},
},
},
},
},
});
if (!requestToJoin) {
res.status(404).json({
success: false,
message: "Request not found",
});
return;
}
// Authorization: only invite creator OR notification targets can accept
const isCreator = requestToJoin.inviteCode.createdBy.xmtpId === xmtpId;
const isNotificationTarget =
requestToJoin.inviteCode.notificationTargets.some(
(target) => target.deviceIdentity.xmtpId === xmtpId,
);
if (!isCreator && !isNotificationTarget) {
res.status(404).json({
success: false,
message: "Request not found",
});
return;
}
// Check if user has already been accepted (has InviteCodeUse record)
// This check is done AFTER authorization to prevent information disclosure
const existingUse = await prisma.inviteCodeUse.findUnique({
where: {
inviteCodeId_usedById: {
inviteCodeId: requestToJoin.inviteCodeId,
usedById: requestToJoin.requesterId,
},
},
});
if (existingUse) {
// Return success for idempotency - request was already processed
res.status(200).json({
id: params.requestId,
accepted: true,
alreadyAccepted: true,
inviteCodeUse: {
id: existingUse.id,
usedAt: existingUse.usedAt.toISOString(),
},
});
return;
}
// Check if invite is still valid
const inviteCode = requestToJoin.inviteCode;
if (inviteCode.status !== "ACTIVE") {
res.status(400).json({
success: false,
message: "Invite is no longer active",
});
return;
}
if (inviteCode.expiresAt && inviteCode.expiresAt < new Date()) {
res.status(400).json({
success: false,
message: "Invite has expired",
});
return;
}
// Accept the request and create InviteCodeUse in a transaction
const result = await prisma.$transaction(async (tx) => {
// First fetch the current invite to get maxUses value
const currentInvite = await tx.inviteCode.findUnique({
where: { id: requestToJoin.inviteCodeId },
select: { maxUses: true, usesCount: true },
});
if (!currentInvite) {
throw new Error("INVITE_NOT_FOUND");
}
// Atomically claim a slot by incrementing uses count with a guard
const whereConditions: Array<
{ maxUses: null } | { usesCount: { lt: number } }
> = [{ maxUses: null }];
// Only add the usesCount comparison if maxUses is not null
if (currentInvite.maxUses !== null) {
whereConditions.push({ usesCount: { lt: currentInvite.maxUses } });
}
const updateResult = await tx.inviteCode.updateMany({
where: {
id: requestToJoin.inviteCodeId,
OR: whereConditions,
},
data: {
usesCount: {
increment: 1,
},
},
});
// Check if we successfully claimed a slot
if (updateResult.count === 0) {
throw new Error("INVITE_MAX_USES_REACHED");
}
// Create InviteCodeUse record
const inviteCodeUse = await tx.inviteCodeUse.create({
data: {
inviteCodeId: requestToJoin.inviteCodeId,
usedById: requestToJoin.requesterId,
},
});
// Delete the original request (it's been processed)
await tx.inviteCodeRequest.delete({
where: { id: params.requestId },
});
return { inviteCodeUse };
});
const response: AcceptRequestToJoinResponse = {
id: params.requestId,
accepted: true,
inviteCodeUse: {
id: result.inviteCodeUse.id,
usedAt: result.inviteCodeUse.usedAt.toISOString(),
},
};
res.status(200).json(response);
} catch (error) {
if (error instanceof z.ZodError) {
res.status(400).json({
success: false,
message: "Invalid request data",
errors: error.errors,
});
return;
}
if (error instanceof Error && error.message === "INVITE_MAX_USES_REACHED") {
res.status(400).json({
success: false,
message: "Invite has reached maximum uses",
});
return;
}
if (error instanceof Error && error.message === "INVITE_NOT_FOUND") {
res.status(404).json({
success: false,
message: "Invite not found",
});
return;
}
// Handle race condition where another request already created the InviteCodeUse
if (
error instanceof Prisma.PrismaClientKnownRequestError &&
error.code === "P2002" &&
Array.isArray(error.meta?.target) &&
(error.meta.target as string[]).some((field) =>
["inviteCodeId_usedById", "inviteCodeId", "usedById"].includes(field),
)
) {
// Another request already created the InviteCodeUse - fetch it for idempotent response
// We need the original request data to look up the correct record
const requestId = req.params.requestId;
const requestData = await prisma.inviteCodeRequest.findUnique({
where: { id: requestId },
});
if (!requestData) {
// Request was already deleted, which means it was processed successfully
// Return success for idempotency
res.status(200).json({
id: requestId,
accepted: true,
inviteCodeUse: {
id: "unknown",
usedAt: new Date().toISOString(),
},
});
return;
}
const existingUse = await prisma.inviteCodeUse.findUnique({
where: {
inviteCodeId_usedById: {
inviteCodeId: requestData.inviteCodeId,
usedById: requestData.requesterId,
},
},
});
if (existingUse) {
const response: AcceptRequestToJoinResponse = {
id: requestId,
accepted: true,
inviteCodeUse: {
id: existingUse.id,
usedAt: existingUse.usedAt.toISOString(),
},
};
res.status(200).json(response);
return;
}
}
req.log.error({ error }, "Error accepting request to join");
res.status(500).json({
success: false,
message: "Failed to accept request",
});
}
}