-
Notifications
You must be signed in to change notification settings - Fork 70
Expand file tree
/
Copy pathroute.ts
More file actions
135 lines (116 loc) · 3.63 KB
/
route.ts
File metadata and controls
135 lines (116 loc) · 3.63 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
import { NextRequest, NextResponse } from 'next/server';
import { Keypair, StrKey } from '@stellar/stellar-sdk';
import { getAndClearNonce } from '@/lib/auth-cache';
import { createSession, getSessionCookieHeader } from '@/lib/session';
import { prisma } from '@/lib/prisma';
import { auditLog, createAuditEvent, extractIp, AuditAction } from '@/lib/audit';
// Force dynamic rendering for this route
export const dynamic = 'force-dynamic';
export const runtime = 'nodejs';
/**
* POST /api/auth/login
* Verify a signature and authenticate user
*/
export async function POST(request: NextRequest) {
try {
const body = await request.json();
const { address, message, signature } = body;
if (!address || !message || !signature) {
return NextResponse.json(
{ error: 'Missing required fields: address, message, signature' },
{ status: 400 }
);
}
// Validate Stellar address format
if (!StrKey.isValidEd25519PublicKey(address)) {
return NextResponse.json(
{ error: 'Invalid Stellar address format' },
{ status: 400 }
);
}
// Verify nonce exists and matches (atomic read + delete)
const storedNonce = getAndClearNonce(address);
if (!storedNonce || storedNonce !== message) {
// Log failed login attempt
await auditLog(
createAuditEvent(AuditAction.LOGIN_FAIL, 'failure', {
address,
ip: extractIp(request),
error: 'Invalid or expired nonce',
})
);
return NextResponse.json(
{ error: 'Invalid or expired nonce' },
{ status: 401 }
);
}
// Verify signature
// The client signs Buffer.from(nonce, 'utf8') so we must decode the same way
const keypair = Keypair.fromPublicKey(address);
const messageBuffer = Buffer.from(message, 'utf8');
const signatureBuffer = Buffer.from(signature, 'base64');
const isValid = keypair.verify(messageBuffer, signatureBuffer);
if (!isValid) {
// Log failed login attempt
await auditLog(
createAuditEvent(AuditAction.LOGIN_FAIL, 'failure', {
address,
ip: extractIp(request),
error: 'Invalid signature',
})
);
return NextResponse.json(
{ error: 'Invalid signature' },
{ status: 401 }
);
}
// Upsert user in database (best-effort — don't fail login if DB is unavailable)
try {
await prisma.user.upsert({
where: { stellar_address: address },
update: {},
create: {
stellar_address: address,
preferences: {
create: {},
},
},
});
} catch (dbErr) {
console.warn('DB upsert skipped (non-fatal):', dbErr);
}
// Create encrypted session
const sealed = await createSession(address);
const response = NextResponse.json({
success: true,
address,
});
response.headers.set(
'Set-Cookie',
getSessionCookieHeader(sealed)
);
// Log successful login
await auditLog(
createAuditEvent(AuditAction.LOGIN_SUCCESS, 'success', {
address,
ip: extractIp(request),
})
);
return response;
} catch (error) {
console.error('Login error:', error);
// Log failed login due to internal error
const body = await request.clone().json().catch(() => ({}));
await auditLog(
createAuditEvent(AuditAction.LOGIN_FAIL, 'failure', {
address: body.address,
ip: extractIp(request),
error: 'Internal server error',
})
);
return NextResponse.json(
{ error: 'Internal Server Error' },
{ status: 500 }
);
}
}