-
Notifications
You must be signed in to change notification settings - Fork 643
/
Copy pathauth.ts
218 lines (201 loc) · 5.57 KB
/
auth.ts
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
import assert from 'node:assert'
import { KeyObject } from 'node:crypto'
import * as jose from 'jose'
import * as ui8 from 'uint8arrays'
import * as crypto from '@atproto/crypto'
import { AuthScope } from '../../auth-verifier'
import { AccountDb } from '../db'
import { AppPassDescript } from './password'
export type AuthToken = {
scope: AuthScope
sub: string
exp: number
}
export type RefreshToken = AuthToken & { scope: AuthScope.Refresh; jti: string }
export const createTokens = async (opts: {
did: string
jwtKey: KeyObject
serviceDid: string
scope?: AuthScope
jti?: string
expiresIn?: string | number
}) => {
const { did, jwtKey, serviceDid, scope, jti, expiresIn } = opts
const [accessJwt, refreshJwt] = await Promise.all([
createAccessToken({ did, jwtKey, serviceDid, scope, expiresIn }),
createRefreshToken({ did, jwtKey, serviceDid, jti, expiresIn }),
])
return { accessJwt, refreshJwt }
}
export const createAccessToken = (opts: {
did: string
jwtKey: KeyObject
serviceDid: string
scope?: AuthScope
expiresIn?: string | number
}): Promise<string> => {
const {
did,
jwtKey,
serviceDid,
scope = AuthScope.Access,
expiresIn = '120mins',
} = opts
const signer = new jose.SignJWT({ scope })
.setProtectedHeader({
typ: 'at+jwt', // https://www.rfc-editor.org/rfc/rfc9068.html
alg: 'HS256', // only symmetric keys supported
})
.setAudience(serviceDid)
.setSubject(did)
.setIssuedAt()
.setExpirationTime(expiresIn)
return signer.sign(jwtKey)
}
export const createRefreshToken = (opts: {
did: string
jwtKey: KeyObject
serviceDid: string
jti?: string
expiresIn?: string | number
}): Promise<string> => {
const {
did,
jwtKey,
serviceDid,
jti = getRefreshTokenId(),
expiresIn = '90days',
} = opts
const signer = new jose.SignJWT({ scope: AuthScope.Refresh })
.setProtectedHeader({
typ: 'refresh+jwt',
alg: 'HS256', // only symmetric keys supported
})
.setAudience(serviceDid)
.setSubject(did)
.setJti(jti)
.setIssuedAt()
.setExpirationTime(expiresIn)
return signer.sign(jwtKey)
}
// @NOTE unsafe for verification, should only be used w/ direct output from createRefreshToken() or createTokens()
export const decodeRefreshToken = (jwt: string) => {
const token = jose.decodeJwt(jwt)
assert.ok(token.scope === AuthScope.Refresh, 'not a refresh token')
return token as RefreshToken
}
export const storeRefreshToken = async (
db: AccountDb,
payload: RefreshToken,
appPassword: AppPassDescript | null,
) => {
const [result] = await db.executeWithRetry(
db.db
.insertInto('refresh_token')
.values({
id: payload.jti,
did: payload.sub,
appPasswordName: appPassword?.name,
expiresAt: new Date(payload.exp * 1000).toISOString(),
})
.onConflict((oc) => oc.doNothing()), // E.g. when re-granting during a refresh grace period
)
return result
}
export const getRefreshToken = async (db: AccountDb, id: string) => {
const res = await db.db
.selectFrom('refresh_token')
.leftJoin('app_password', (join) =>
join
.onRef('app_password.did', '=', 'refresh_token.did')
.onRef('app_password.name', '=', 'refresh_token.appPasswordName'),
)
.where('id', '=', id)
.selectAll('refresh_token')
.select('app_password.privileged')
.executeTakeFirst()
if (!res) return null
const { did, expiresAt, appPasswordName, nextId, privileged } = res
return {
id,
did,
expiresAt,
nextId,
appPassword: appPasswordName
? {
name: appPasswordName,
privileged: privileged === 1 ? true : false,
}
: null,
}
}
export const deleteExpiredRefreshTokens = async (
db: AccountDb,
did: string,
now: string,
) => {
await db.executeWithRetry(
db.db
.deleteFrom('refresh_token')
.where('did', '=', did)
.where('expiresAt', '<=', now),
)
}
export const addRefreshGracePeriod = async (
db: AccountDb,
opts: {
id: string
expiresAt: string
nextId: string
},
) => {
const { id, expiresAt, nextId } = opts
const [res] = await db.executeWithRetry(
db.db
.updateTable('refresh_token')
.where('id', '=', id)
.where((inner) =>
inner.where('nextId', 'is', null).orWhere('nextId', '=', nextId),
)
.set({ expiresAt, nextId })
.returningAll(),
)
if (!res) {
throw new ConcurrentRefreshError()
}
}
export const revokeRefreshToken = async (db: AccountDb, id: string) => {
const [{ numDeletedRows }] = await db.executeWithRetry(
db.db.deleteFrom('refresh_token').where('id', '=', id),
)
return numDeletedRows > 0
}
export const revokeRefreshTokensByDid = async (db: AccountDb, did: string) => {
const [{ numDeletedRows }] = await db.executeWithRetry(
db.db.deleteFrom('refresh_token').where('did', '=', did),
)
return numDeletedRows > 0
}
export const revokeAppPasswordRefreshToken = async (
db: AccountDb,
did: string,
appPassName: string,
) => {
const [{ numDeletedRows }] = await db.executeWithRetry(
db.db
.deleteFrom('refresh_token')
.where('did', '=', did)
.where('appPasswordName', '=', appPassName),
)
return numDeletedRows > 0
}
export const getRefreshTokenId = () => {
return ui8.toString(crypto.randomBytes(32), 'base64')
}
export const formatScope = (appPassword: AppPassDescript | null): AuthScope => {
if (!appPassword) return AuthScope.Access
return appPassword.privileged
? AuthScope.AppPassPrivileged
: AuthScope.AppPass
}
export class ConcurrentRefreshError extends Error {}