@@ -6,39 +6,43 @@ import { findApiKeyByHash, optionsQx, touchApiKeyLastUsed } from '@crowd/data-ac
66
77export function staticApiKeyMiddleware ( ) : RequestHandler {
88 return async ( req : Request , _res : Response , next : NextFunction ) : Promise < void > => {
9- const authHeader = req . headers . authorization
9+ try {
10+ const authHeader = req . headers . authorization
1011
11- if ( ! authHeader || ! authHeader . startsWith ( 'Bearer ' ) ) {
12- next ( new UnauthorizedError ( 'Missing or invalid Authorization header' ) )
13- return
14- }
12+ if ( ! authHeader || ! authHeader . startsWith ( 'Bearer ' ) ) {
13+ next ( new UnauthorizedError ( 'Missing or invalid Authorization header' ) )
14+ return
15+ }
1516
16- const providedKey = authHeader . slice ( 'Bearer ' . length )
17- const keyHash = crypto . createHash ( 'sha256' ) . update ( providedKey ) . digest ( 'hex' )
17+ const providedKey = authHeader . slice ( 'Bearer ' . length )
18+ const keyHash = crypto . createHash ( 'sha256' ) . update ( providedKey ) . digest ( 'hex' )
1819
19- const qx = optionsQx ( req )
20- const apiKey = await findApiKeyByHash ( qx , keyHash )
20+ const qx = optionsQx ( req )
21+ const apiKey = await findApiKeyByHash ( qx , keyHash )
2122
22- if ( ! apiKey ) {
23- next ( new UnauthorizedError ( 'Invalid API key' ) )
24- return
25- }
23+ if ( ! apiKey ) {
24+ next ( new UnauthorizedError ( 'Invalid API key' ) )
25+ return
26+ }
2627
27- if ( apiKey . revokedAt ) {
28- next ( new UnauthorizedError ( 'API key has been revoked' ) )
29- return
30- }
28+ if ( apiKey . revokedAt ) {
29+ next ( new UnauthorizedError ( 'API key has been revoked' ) )
30+ return
31+ }
3132
32- if ( apiKey . expiresAt && apiKey . expiresAt < new Date ( ) ) {
33- next ( new UnauthorizedError ( 'API key has expired' ) )
34- return
35- }
33+ if ( apiKey . expiresAt && apiKey . expiresAt < new Date ( ) ) {
34+ next ( new UnauthorizedError ( 'API key has expired' ) )
35+ return
36+ }
3637
37- // fire and forget — don't block the request
38- touchApiKeyLastUsed ( qx , apiKey . id ) . catch ( ( ) => { } )
38+ // fire and forget — don't block the request
39+ touchApiKeyLastUsed ( qx , apiKey . id ) . catch ( ( ) => { } )
3940
40- req . actor = { id : apiKey . name , type : 'service' , scopes : apiKey . scopes }
41+ req . actor = { id : apiKey . name , type : 'service' , scopes : apiKey . scopes }
4142
42- next ( )
43+ next ( )
44+ } catch ( err ) {
45+ next ( err )
46+ }
4347 }
4448}
0 commit comments