-
Notifications
You must be signed in to change notification settings - Fork 264
Expand file tree
/
Copy pathserver.ts
More file actions
221 lines (191 loc) · 7.81 KB
/
server.ts
File metadata and controls
221 lines (191 loc) · 7.81 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
import 'server-only';
import { prisma } from '@/prisma';
import { Prisma } from '@prisma/client';
import {
generateOAuthRefreshToken,
generateOAuthToken,
hashSecret,
OAUTH_ACCESS_TOKEN_PREFIX,
OAUTH_REFRESH_TOKEN_PREFIX,
} from '@sourcebot/shared';
import crypto from 'crypto';
const AUTH_CODE_TTL_MS = 10 * 60 * 1000; // 10 minutes
const ACCESS_TOKEN_TTL_MS = 60 * 60 * 1000; // 1 hour
const REFRESH_TOKEN_TTL_MS = 90 * 24 * 60 * 60 * 1000; // 90 days
export const ACCESS_TOKEN_TTL_SECONDS = Math.floor(ACCESS_TOKEN_TTL_MS / 1000);
// Generates a random authorization code, hashes it, and stores it alongside the
// PKCE code challenge. Returns the raw code to be sent to the client.
export async function generateAndStoreAuthCode({
clientId,
userId,
redirectUri,
codeChallenge,
resource,
}: {
clientId: string;
userId: string;
redirectUri: string;
codeChallenge: string;
resource: string | null;
}): Promise<string> {
const rawCode = crypto.randomBytes(32).toString('hex');
const codeHash = hashSecret(rawCode);
await prisma.oAuthAuthorizationCode.create({
data: {
codeHash,
clientId,
userId,
redirectUri,
codeChallenge,
resource,
expiresAt: new Date(Date.now() + AUTH_CODE_TTL_MS),
},
});
return rawCode;
}
// Verifies the authorization code and PKCE code verifier, then exchanges them for
// an opaque access token. The auth code is deleted after use (single-use).
export async function verifyAndExchangeCode({
rawCode,
clientId,
redirectUri,
codeVerifier,
resource,
}: {
rawCode: string;
clientId: string;
redirectUri: string;
codeVerifier: string;
resource: string | null;
}): Promise<{ token: string; refreshToken: string; expiresIn: number } | { error: string; errorDescription: string }> {
const codeHash = hashSecret(rawCode);
const authCode = await prisma.oAuthAuthorizationCode.findUnique({
where: { codeHash },
});
if (!authCode) {
return { error: 'invalid_grant', errorDescription: 'Authorization code not found.' };
}
if (authCode.expiresAt < new Date()) {
await prisma.oAuthAuthorizationCode.delete({ where: { codeHash } });
return { error: 'invalid_grant', errorDescription: 'Authorization code has expired.' };
}
if (authCode.clientId !== clientId) {
return { error: 'invalid_grant', errorDescription: 'Client ID mismatch.' };
}
if (authCode.redirectUri !== redirectUri) {
return { error: 'invalid_grant', errorDescription: 'Redirect URI mismatch.' };
}
// PKCE verification: BASE64URL(SHA-256(codeVerifier)) must equal stored codeChallenge
const computedChallenge = crypto
.createHash('sha256')
.update(codeVerifier)
.digest('base64url');
if (computedChallenge !== authCode.codeChallenge) {
return { error: 'invalid_grant', errorDescription: 'PKCE code verifier is invalid.' };
}
// RFC 8707: if a resource was bound to the auth code, the token request must present the same value.
if (resource !== null && authCode.resource !== null && authCode.resource !== resource) {
return { error: 'invalid_target', errorDescription: 'resource parameter does not match the value bound to the authorization code.' };
}
// Single-use: delete the auth code before issuing token.
// Handle concurrent consume attempts gracefully.
try {
await prisma.oAuthAuthorizationCode.delete({ where: { codeHash } });
} catch (error) {
if (error instanceof Prisma.PrismaClientKnownRequestError && error.code === 'P2025') {
return { error: 'invalid_grant', errorDescription: 'Authorization code has already been used.' };
}
throw error;
}
const { token, hash } = generateOAuthToken();
const { token: refreshToken, hash: refreshHash } = generateOAuthRefreshToken();
await prisma.$transaction([
prisma.oAuthToken.create({
data: {
hash,
clientId,
userId: authCode.userId,
resource: authCode.resource,
expiresAt: new Date(Date.now() + ACCESS_TOKEN_TTL_MS),
},
}),
prisma.oAuthRefreshToken.create({
data: {
hash: refreshHash,
clientId,
userId: authCode.userId,
resource: authCode.resource,
expiresAt: new Date(Date.now() + REFRESH_TOKEN_TTL_MS),
},
}),
]);
return { token, refreshToken, expiresIn: ACCESS_TOKEN_TTL_SECONDS };
}
// Verifies a refresh token, rotates it, and issues a new access token + refresh token.
// If the refresh token has already been used (deleted), revokes all tokens for the client/user
// as a token theft signal (OAuth 2.1 Section 4.3.1).
export async function verifyAndRotateRefreshToken({
rawRefreshToken,
clientId,
resource,
}: {
rawRefreshToken: string;
clientId: string;
resource: string | null;
}): Promise<{ token: string; refreshToken: string; expiresIn: number } | { error: string; errorDescription: string }> {
if (!rawRefreshToken.startsWith(OAUTH_REFRESH_TOKEN_PREFIX)) {
return { error: 'invalid_grant', errorDescription: 'Refresh token is invalid.' };
}
const hash = hashSecret(rawRefreshToken.slice(OAUTH_REFRESH_TOKEN_PREFIX.length));
const existing = await prisma.oAuthRefreshToken.findUnique({ where: { hash } });
if (!existing) {
return { error: 'invalid_grant', errorDescription: 'Refresh token is invalid or has already been used.' };
}
if (existing.clientId !== clientId) {
return { error: 'invalid_grant', errorDescription: 'Client ID mismatch.' };
}
if (existing.expiresAt < new Date()) {
await prisma.oAuthRefreshToken.delete({ where: { hash } });
return { error: 'invalid_grant', errorDescription: 'Refresh token has expired.' };
}
if (resource !== null && existing.resource !== null && existing.resource !== resource) {
return { error: 'invalid_target', errorDescription: 'resource parameter does not match the refresh token.' };
}
const { token, hash: newTokenHash } = generateOAuthToken();
const { token: refreshToken, hash: newRefreshHash } = generateOAuthRefreshToken();
await prisma.$transaction([
prisma.oAuthRefreshToken.delete({ where: { hash } }),
prisma.oAuthToken.create({
data: {
hash: newTokenHash,
clientId,
userId: existing.userId,
resource: existing.resource,
expiresAt: new Date(Date.now() + ACCESS_TOKEN_TTL_MS),
},
}),
prisma.oAuthRefreshToken.create({
data: {
hash: newRefreshHash,
clientId,
userId: existing.userId,
resource: existing.resource,
expiresAt: new Date(Date.now() + REFRESH_TOKEN_TTL_MS),
},
}),
]);
return { token, refreshToken, expiresIn: ACCESS_TOKEN_TTL_SECONDS };
}
// Revokes an access token or refresh token by hashing it and deleting the DB record.
// Per RFC 7009, revocation always succeeds even if the token doesn't exist.
export async function revokeToken(rawToken: string): Promise<void> {
if (rawToken.startsWith(OAUTH_ACCESS_TOKEN_PREFIX)) {
const secret = rawToken.slice(OAUTH_ACCESS_TOKEN_PREFIX.length);
const hash = hashSecret(secret);
await prisma.oAuthToken.deleteMany({ where: { hash } });
} else if (rawToken.startsWith(OAUTH_REFRESH_TOKEN_PREFIX)) {
const secret = rawToken.slice(OAUTH_REFRESH_TOKEN_PREFIX.length);
const hash = hashSecret(secret);
await prisma.oAuthRefreshToken.deleteMany({ where: { hash } });
}
}