|
| 1 | +// **NOTE** This is an untested proof-of-concept for using fetch middleware to handle |
| 2 | +// session API key based authentication. |
| 3 | + |
| 4 | +import { FetchMiddleware, ResponseContext } from './fetchUtil'; |
| 5 | + |
| 6 | +export interface SessionAuthDataStore { |
| 7 | + get(host: string): Promise<{ authKey: string } | undefined> | { authKey: string } | undefined; |
| 8 | + set(host: string, authData: { authKey: string }): Promise<void> | void; |
| 9 | + delete(host: string): Promise<void> | void; |
| 10 | +} |
| 11 | + |
| 12 | +export interface ApiSessionAuthMiddlewareOpts { |
| 13 | + /** The middleware / API key header will only be added to requests matching this host. */ |
| 14 | + host?: RegExp | string; |
| 15 | + /** The http header name used for specifying the API key value. */ |
| 16 | + httpHeader?: string; |
| 17 | + authPath: string; |
| 18 | + authRequestMetadata: Record<string, string>; |
| 19 | + authDataStore?: SessionAuthDataStore; |
| 20 | +} |
| 21 | + |
| 22 | +export function createApiSessionAuthMiddleware({ |
| 23 | + host = /(.*)api(.*)\.stacks\.co$/i, |
| 24 | + httpHeader = 'x-api-key', |
| 25 | + authPath = '/request_key', |
| 26 | + authRequestMetadata = {}, |
| 27 | + authDataStore = createInMemoryAuthDataStore(), |
| 28 | +}: ApiSessionAuthMiddlewareOpts): FetchMiddleware { |
| 29 | + // Local temporary cache of auth request promises, used so that multiple re-auth requests are |
| 30 | + // not running in parallel. Key is the request host. |
| 31 | + const pendingAuthRequests = new Map<string, Promise<{ authKey: string }>>(); |
| 32 | + |
| 33 | + const authMiddleware: FetchMiddleware = { |
| 34 | + pre: async context => { |
| 35 | + const reqUrl = new URL(context.url); |
| 36 | + let hostMatches = false; |
| 37 | + if (typeof host === 'string') { |
| 38 | + hostMatches = host === reqUrl.host; |
| 39 | + } else { |
| 40 | + hostMatches = !!host.exec(reqUrl.host); |
| 41 | + } |
| 42 | + const authData = await authDataStore.get(reqUrl.host); |
| 43 | + if (hostMatches && authData) { |
| 44 | + try { |
| 45 | + context.init.headers = setRequestHeader(context.init, httpHeader, authData.authKey); |
| 46 | + } catch (error) { |
| 47 | + console.error(`Error awaiting key auth response: ${error}`); |
| 48 | + } |
| 49 | + } |
| 50 | + }, |
| 51 | + post: async context => { |
| 52 | + const reqUrl = new URL(context.url); |
| 53 | + let hostMatches = false; |
| 54 | + if (typeof host === 'string') { |
| 55 | + hostMatches = host === reqUrl.host; |
| 56 | + } else { |
| 57 | + hostMatches = !!host.exec(reqUrl.host); |
| 58 | + } |
| 59 | + |
| 60 | + // If request is for configured host, and response was `401 Unauthorized`, |
| 61 | + // then request auth key and retry request. |
| 62 | + if (hostMatches && context.response.status === 401) { |
| 63 | + // Check if for any currently pending auth requests and re-use it to avoid creating multiple in parallel. |
| 64 | + let pendingAuthRequest = pendingAuthRequests.get(reqUrl.host); |
| 65 | + if (!pendingAuthRequest) { |
| 66 | + pendingAuthRequest = resolveAuthToken(context, authPath, authRequestMetadata) |
| 67 | + .then(async result => { |
| 68 | + // If the request is successfull, add the key to storage. |
| 69 | + await authDataStore.set(reqUrl.host, result); |
| 70 | + return result; |
| 71 | + }) |
| 72 | + .finally(() => { |
| 73 | + // When the request is completed (either successful or rejected) clear the promise. |
| 74 | + pendingAuthRequests.delete(reqUrl.host); |
| 75 | + }); |
| 76 | + } |
| 77 | + const { authKey } = await pendingAuthRequest; |
| 78 | + // Retry the request using the new API key auth header. |
| 79 | + context.init.headers = setRequestHeader(context.init, httpHeader, authKey); |
| 80 | + return context.fetch(context.url, context.init); |
| 81 | + } else { |
| 82 | + return context.response; |
| 83 | + } |
| 84 | + }, |
| 85 | + }; |
| 86 | + return authMiddleware; |
| 87 | +} |
| 88 | + |
| 89 | +function createInMemoryAuthDataStore(): SessionAuthDataStore { |
| 90 | + const map = new Map<string, { authKey: string }>(); |
| 91 | + const store: SessionAuthDataStore = { |
| 92 | + get: host => { |
| 93 | + return map.get(host); |
| 94 | + }, |
| 95 | + set: (host, authData) => { |
| 96 | + map.set(host, authData); |
| 97 | + }, |
| 98 | + delete: host => { |
| 99 | + map.delete(host); |
| 100 | + }, |
| 101 | + }; |
| 102 | + return store; |
| 103 | +} |
| 104 | + |
| 105 | +function setRequestHeader(requestInit: RequestInit, headerKey: string, headerValue: string) { |
| 106 | + const headers = new Headers(requestInit.headers); |
| 107 | + headers.set(headerKey, headerValue); |
| 108 | + return headers; |
| 109 | +} |
| 110 | + |
| 111 | +async function resolveAuthToken( |
| 112 | + context: ResponseContext, |
| 113 | + authPath: string, |
| 114 | + authRequestMetadata: Record<string, string> |
| 115 | +) { |
| 116 | + const reqUrl = new URL(context.url); |
| 117 | + const authEndpoint = new URL(reqUrl.origin); |
| 118 | + authEndpoint.pathname = authPath; |
| 119 | + const authReq = await context.fetch(authEndpoint.toString(), { |
| 120 | + method: 'POST', |
| 121 | + headers: { |
| 122 | + 'Content-Type': 'application/json', |
| 123 | + Accept: 'application/json', |
| 124 | + }, |
| 125 | + body: JSON.stringify(authRequestMetadata), |
| 126 | + }); |
| 127 | + if (authReq.ok) { |
| 128 | + const authRespBody: { auth_key: string } = await authReq.json(); |
| 129 | + return { authKey: authRespBody.auth_key }; |
| 130 | + } else { |
| 131 | + let respBody = ''; |
| 132 | + try { |
| 133 | + respBody = await authReq.text(); |
| 134 | + } catch (error) { |
| 135 | + respBody = `Error fetching API auth key: ${authReq.status} - Error fetching response body: ${error}`; |
| 136 | + } |
| 137 | + throw new Error(`Error fetching API auth key: ${authReq.status} - ${respBody}`); |
| 138 | + } |
| 139 | +} |
0 commit comments