-
Notifications
You must be signed in to change notification settings - Fork 23
Expand file tree
/
Copy pathauth.service.ts
More file actions
309 lines (277 loc) · 9.27 KB
/
Copy pathauth.service.ts
File metadata and controls
309 lines (277 loc) · 9.27 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
import {
BadRequestException,
Injectable,
UnauthorizedException,
} from "@nestjs/common";
import { ConfigService } from "@nestjs/config";
import { AuthEventType } from "@prisma/client";
import { Keypair, StrKey } from "@stellar/stellar-base";
import { createHash, randomBytes } from "crypto";
import { PrismaService } from "../database/prisma.service";
import { sha256 } from "../common/crypto/hash";
import { AuthAuditService } from "./auth-audit.service";
import { AuthRateLimiterService } from "./auth-rate-limiter.service";
import { SessionService } from "./session.service";
@Injectable()
export class AuthService {
private readonly appUrl: string;
private readonly networkPassphrase: string;
constructor(
private readonly prisma: PrismaService,
private readonly sessionService: SessionService,
private readonly auditService: AuthAuditService,
private readonly rateLimiter: AuthRateLimiterService,
configService: ConfigService,
) {
this.appUrl = configService.getOrThrow<string>("appUrl");
this.networkPassphrase = configService.getOrThrow<string>(
"stellar.networkPassphrase",
);
}
async createChallenge(walletAddress: string, clientMetadata?: string) {
this.assertValidPublicKey(walletAddress);
// Check rate limits before creating challenge
await this.rateLimiter.checkChallengeCreationLimit(
walletAddress,
clientMetadata,
);
const nonce = randomBytes(24).toString("base64url");
const expiresAt = new Date(Date.now() + 5 * 60 * 1000);
const message = [
"EarnProof wallet authentication",
`Domain: ${this.appUrl}`,
`Network: ${this.networkPassphrase}`,
`Wallet: ${walletAddress}`,
`Nonce: ${nonce}`,
`Expires At: ${expiresAt.toISOString()}`,
].join("\n");
const challenge = await this.prisma.walletChallenge.create({
data: {
walletAddress,
nonceHash: sha256(nonce),
message,
expiresAt,
},
select: {
id: true,
message: true,
expiresAt: true,
},
});
// Record successful challenge creation
await this.auditService.recordEvent(
AuthEventType.CHALLENGE_CREATED,
walletAddress,
{
challengeId: challenge.id,
success: true,
clientMetadata,
},
);
return challenge;
}
async verifyChallenge(input: {
challengeId: string;
walletAddress: string;
signature: string;
clientMetadata?: string;
}) {
this.assertValidPublicKey(input.walletAddress);
// Check rate limits before verification attempt
await this.rateLimiter.checkVerificationLimit(
input.walletAddress,
input.clientMetadata,
);
// Atomically mark the challenge as consumed only if it exists, is not used,
// and is not expired. This closes the TOCTOU window in which two concurrent
// requests could both pass an existence check before either marked it used.
// Atomically mark challenge as consumed only if it exists, is not used, and is not expired.
// This prevents TOCTOU race conditions where multiple concurrent requests could both
// pass the existence check before any are marked as used.
const consumedChallenge = await this.prisma.walletChallenge.updateMany({
where: {
id: input.challengeId,
walletAddress: input.walletAddress,
usedAt: null, // Not yet consumed
expiresAt: {
gt: new Date(), // Not expired
},
},
data: {
usedAt: new Date(),
},
});
if (consumedChallenge.count === 0) {
// Nothing was consumed: the challenge was already used (a replay), or it
// expired or never existed. The two are audited separately; both return
// the same message, so the caller learns nothing either way.
// The atomic update matched nothing — either the challenge doesn't
// exist, was already consumed (replay), or is expired. Distinguish
// those for the audit trail with a read-only lookup; this happens
// after the fact, so it cannot reintroduce the race the update above
// closes.
const usedChallenge = await this.prisma.walletChallenge.findFirst({
where: {
id: input.challengeId,
walletAddress: input.walletAddress,
usedAt: { not: null },
},
});
if (usedChallenge) {
await this.auditService.recordEvent(
AuthEventType.CHALLENGE_REPLAYED,
input.walletAddress,
{
challengeId: input.challengeId,
success: false,
failureReason: "Challenge already used",
clientMetadata: input.clientMetadata,
},
);
} else {
await this.auditService.recordEvent(
AuthEventType.CHALLENGE_EXPIRED,
input.walletAddress,
{
challengeId: input.challengeId,
success: false,
failureReason: "Challenge expired or not found",
clientMetadata: input.clientMetadata,
},
);
}
throw new UnauthorizedException("Challenge is expired or unavailable");
}
// Fetch the challenge again to get the message for signature verification.
// It is already marked used, so a failed verification cannot be retried.
// The challenge is now marked as used, so even if verification fails, it cannot be reused.
const challenge = await this.prisma.walletChallenge.findUnique({
where: {
id: input.challengeId,
},
});
if (!challenge) {
// Unreachable unless the row was deleted between the two statements;
// safeguarded rather than dereferenced.
// Should be unreachable: updateMany just matched and updated this row,
// so it exists. Safeguard against a concurrent deletion between the
// two statements.
throw new UnauthorizedException("Challenge is expired or unavailable");
}
const isValid = this.verifySignature(
input.walletAddress,
challenge.message,
input.signature,
);
if (!isValid) {
await this.auditService.recordEvent(
AuthEventType.SIGNATURE_INVALID,
input.walletAddress,
{
challengeId: input.challengeId,
success: false,
failureReason: "Invalid signature",
clientMetadata: input.clientMetadata,
},
);
throw new UnauthorizedException("Invalid wallet signature");
}
const walletHash = `sha256:${sha256(input.walletAddress)}`;
const user = await this.prisma.user.upsert({
where: { walletAddress: input.walletAddress },
update: { walletHash, lastLoginAt: new Date() },
create: {
walletAddress: input.walletAddress,
walletHash,
lastLoginAt: new Date(),
},
});
// Create a persisted, revocable session. Only the hash is stored.
const { token, sessionId, expiresAt } = await this.sessionService.create({
id: user.id,
walletAddress: user.walletAddress,
walletHash: user.walletHash,
role: user.role,
});
// Record successful verification
await this.auditService.recordEvent(
AuthEventType.CHALLENGE_VERIFIED,
input.walletAddress,
{
challengeId: input.challengeId,
success: true,
clientMetadata: input.clientMetadata,
},
);
return {
user: {
id: user.id,
walletAddress: user.walletAddress,
walletHash: user.walletHash,
role: user.role,
},
session: {
token,
tokenType: "Bearer",
sessionId,
expiresAt,
},
};
}
async getSession(userId: string) {
const user = await this.prisma.user.findUnique({
where: { id: userId },
select: {
id: true,
walletAddress: true,
walletHash: true,
role: true,
status: true,
lastLoginAt: true,
},
});
if (!user) {
throw new UnauthorizedException("User session is no longer valid");
}
return { user };
}
/**
* Revoke the caller's active session server-side.
* The sessionId is extracted from the authenticated request context by
* the controller — the raw token is never passed here.
*/
async logout(sessionId: string): Promise<void> {
await this.sessionService.revoke(sessionId);
}
// ---------------------------------------------------------------------------
// Private helpers
// ---------------------------------------------------------------------------
private verifySignature(
walletAddress: string,
message: string,
signature: string,
) {
const signatureBuffer = this.decodeSignature(signature);
return Keypair.fromPublicKey(walletAddress).verify(
this.sep53MessageHash(message),
signatureBuffer,
);
}
private sep53MessageHash(message: string) {
return createHash("sha256")
.update("Stellar Signed Message:\n", "utf8")
.update(message, "utf8")
.digest();
}
private decodeSignature(signature: string) {
if (/^[a-f0-9]+$/i.test(signature) && signature.length % 2 === 0) {
return Buffer.from(signature, "hex");
}
return Buffer.from(signature, "base64");
}
private assertValidPublicKey(walletAddress: string) {
if (!StrKey.isValidEd25519PublicKey(walletAddress)) {
throw new BadRequestException("Invalid Stellar public key");
}
}
}