|
1 | 1 | import 'cross-fetch/polyfill';
|
2 | 2 |
|
3 |
| -/** @ignore */ |
4 |
| -export async function fetchPrivate(input: RequestInfo, init?: RequestInit): Promise<Response> { |
5 |
| - const defaultFetchOpts: RequestInit = { |
6 |
| - referrer: 'no-referrer', |
7 |
| - referrerPolicy: 'no-referrer', |
| 3 | +export type FetchFn = (url: string, init?: RequestInit) => Promise<Response>; |
| 4 | + |
| 5 | +export interface RequestContext { |
| 6 | + fetch: FetchFn; |
| 7 | + url: string; |
| 8 | + init: RequestInit; |
| 9 | +} |
| 10 | + |
| 11 | +export interface ResponseContext { |
| 12 | + fetch: FetchFn; |
| 13 | + url: string; |
| 14 | + init: RequestInit; |
| 15 | + response: Response; |
| 16 | +} |
| 17 | + |
| 18 | +export interface FetchParams { |
| 19 | + url: string; |
| 20 | + init: RequestInit; |
| 21 | +} |
| 22 | + |
| 23 | +export interface FetchMiddleware { |
| 24 | + pre?: (context: RequestContext) => PromiseLike<FetchParams | void> | FetchParams | void; |
| 25 | + post?: (context: ResponseContext) => Promise<Response | void> | Response | void; |
| 26 | +} |
| 27 | + |
| 28 | +// TODO: make the value a promise so that multiple re-auth requests are not running in parallel |
| 29 | +// TODO: make the storage interface configurable |
| 30 | +// in-memory session auth data, keyed by the endpoint host |
| 31 | +const sessionAuthData = new Map<string, { authKey: string }>(); |
| 32 | + |
| 33 | +export interface ApiSessionAuthMiddlewareOpts { |
| 34 | + /** The middleware / API key header will only be added to requests matching this host. */ |
| 35 | + host?: RegExp | string; |
| 36 | + /** The http header name used for specifying the API key value. */ |
| 37 | + httpHeader?: string; |
| 38 | + authPath: string; |
| 39 | + authRequestMetadata: Record<string, string>; |
| 40 | +} |
| 41 | + |
| 42 | +export function getApiSessionAuthMiddleware({ |
| 43 | + host = /(.*)api(.*)\.stacks\.co$/i, |
| 44 | + httpHeader = 'x-api-key', |
| 45 | + authPath = '/request_key', |
| 46 | + authRequestMetadata = {}, |
| 47 | +}: ApiSessionAuthMiddlewareOpts): FetchMiddleware { |
| 48 | + const authMiddleware: FetchMiddleware = { |
| 49 | + pre: context => { |
| 50 | + const reqUrl = new URL(context.url); |
| 51 | + let hostMatches = false; |
| 52 | + if (typeof host === 'string') { |
| 53 | + hostMatches = host === reqUrl.host; |
| 54 | + } else { |
| 55 | + hostMatches = !!host.exec(reqUrl.host); |
| 56 | + } |
| 57 | + const authData = sessionAuthData.get(reqUrl.host); |
| 58 | + if (hostMatches && authData) { |
| 59 | + const headers = new Headers(context.init.headers); |
| 60 | + headers.set(httpHeader, authData.authKey); |
| 61 | + context.init.headers = headers; |
| 62 | + } |
| 63 | + }, |
| 64 | + post: async context => { |
| 65 | + const reqUrl = new URL(context.url); |
| 66 | + let hostMatches = false; |
| 67 | + if (typeof host === 'string') { |
| 68 | + hostMatches = host === reqUrl.host; |
| 69 | + } else { |
| 70 | + hostMatches = !!host.exec(reqUrl.host); |
| 71 | + } |
| 72 | + // if request is for configured host, and response was `401 Unauthorized`, |
| 73 | + // then request auth key and retry request. |
| 74 | + if (hostMatches && context.response.status === 401) { |
| 75 | + const authEndpoint = new URL(reqUrl.origin); |
| 76 | + authEndpoint.pathname = authPath; |
| 77 | + const authReq = await context.fetch(authEndpoint.toString(), { |
| 78 | + method: 'POST', |
| 79 | + headers: { |
| 80 | + 'Content-Type': 'application/json', |
| 81 | + Accept: 'application/json', |
| 82 | + }, |
| 83 | + body: JSON.stringify(authRequestMetadata), |
| 84 | + }); |
| 85 | + const authResponseBody = await authReq.text(); |
| 86 | + if (authReq.ok) { |
| 87 | + const authResp: { api_key: string } = JSON.parse(authResponseBody); |
| 88 | + sessionAuthData.set(reqUrl.host, { authKey: authResp.api_key }); |
| 89 | + return context.fetch(context.url, context.init); |
| 90 | + } else { |
| 91 | + throw new Error(`Error fetching API auth key: ${authReq.status}: ${authResponseBody}`); |
| 92 | + } |
| 93 | + } else { |
| 94 | + return context.response; |
| 95 | + } |
| 96 | + }, |
| 97 | + }; |
| 98 | + return authMiddleware; |
| 99 | +} |
| 100 | + |
| 101 | +export interface ApiKeyMiddlewareOpts { |
| 102 | + /** The middleware / API key header will only be added to requests matching this host. */ |
| 103 | + host?: RegExp | string; |
| 104 | + /** The http header name used for specifying the API key value. */ |
| 105 | + httpHeader?: string; |
| 106 | + /** The API key string to specify as an http header value. */ |
| 107 | + apiKey: string; |
| 108 | +} |
| 109 | + |
| 110 | +export function createApiKeyMiddleware({ |
| 111 | + apiKey, |
| 112 | + host = /(.*)api(.*)\.stacks\.co$/i, |
| 113 | + httpHeader = 'x-api-key', |
| 114 | +}: ApiKeyMiddlewareOpts): FetchMiddleware { |
| 115 | + return { |
| 116 | + pre: context => { |
| 117 | + const reqUrl = new URL(context.url); |
| 118 | + let hostMatches = false; |
| 119 | + if (typeof host === 'string') { |
| 120 | + hostMatches = host === reqUrl.host; |
| 121 | + } else { |
| 122 | + hostMatches = !!host.exec(reqUrl.host); |
| 123 | + } |
| 124 | + if (hostMatches) { |
| 125 | + const headers = new Headers(context.init.headers); |
| 126 | + headers.set(httpHeader, apiKey); |
| 127 | + context.init.headers = headers; |
| 128 | + } |
| 129 | + }, |
8 | 130 | };
|
9 |
| - const fetchOpts = Object.assign(defaultFetchOpts, init); |
10 |
| - const fetchResult = await fetch(input, fetchOpts); |
11 |
| - return fetchResult; |
12 |
| -} |
13 |
| - |
14 |
| -export async function soFetch( |
15 |
| - fetchLib: typeof fetch, |
16 |
| - input: RequestInfo, |
17 |
| - init?: RequestInit |
18 |
| -): Promise<Response> { |
19 |
| - const defaultFetchOpts: RequestInit = { |
20 |
| - referrer: 'no-referrer', |
21 |
| - referrerPolicy: 'no-referrer', |
| 131 | +} |
| 132 | + |
| 133 | +function getDefaultMiddleware(): FetchMiddleware[] { |
| 134 | + const setOriginMiddleware: FetchMiddleware = { |
| 135 | + pre: context => { |
| 136 | + // Send only the origin in the Referer header. For example, a document |
| 137 | + // at https://example.com/page.html will send the referrer https://example.com/ |
| 138 | + context.init.referrerPolicy = 'origin'; |
| 139 | + }, |
| 140 | + }; |
| 141 | + return [setOriginMiddleware]; |
| 142 | +} |
| 143 | + |
| 144 | +export function getDefaultFetchFn(fetchLib: FetchFn, ...middleware: FetchMiddleware[]): FetchFn; |
| 145 | +export function getDefaultFetchFn(...middleware: FetchMiddleware[]): FetchFn; |
| 146 | +export function getDefaultFetchFn(...args: any[]): FetchFn { |
| 147 | + let fetchLib: FetchFn = fetch; |
| 148 | + let middlewareOpt: FetchMiddleware[] = []; |
| 149 | + if (args.length > 0) { |
| 150 | + if (typeof args[0] === 'function') { |
| 151 | + fetchLib = args.shift(); |
| 152 | + } |
| 153 | + } |
| 154 | + if (args.length > 0) { |
| 155 | + middlewareOpt = args; |
| 156 | + } |
| 157 | + const middlewares = [...getDefaultMiddleware(), ...middlewareOpt]; |
| 158 | + const fetchFn = async (url: string, init?: RequestInit | undefined): Promise<Response> => { |
| 159 | + let fetchParams = { url, init: init || {} }; |
| 160 | + for (const middleware of middlewares) { |
| 161 | + if (middleware.pre) { |
| 162 | + const result = await Promise.resolve( |
| 163 | + middleware.pre({ |
| 164 | + fetch: fetchLib, |
| 165 | + ...fetchParams, |
| 166 | + }) |
| 167 | + ); |
| 168 | + fetchParams = result ?? fetchParams; |
| 169 | + } |
| 170 | + } |
| 171 | + let response = await fetchLib(fetchParams.url, fetchParams.init); |
| 172 | + for (const middleware of middlewares) { |
| 173 | + if (middleware.post) { |
| 174 | + const result = await Promise.resolve( |
| 175 | + middleware.post({ |
| 176 | + fetch: fetchLib, |
| 177 | + url: fetchParams.url, |
| 178 | + init: fetchParams.init, |
| 179 | + response: response.clone(), |
| 180 | + }) |
| 181 | + ); |
| 182 | + response = result ?? response; |
| 183 | + } |
| 184 | + } |
| 185 | + return response; |
22 | 186 | };
|
23 |
| - const fetchOpts = Object.assign(defaultFetchOpts, init); |
24 |
| - const fetchResult = await fetchLib(input, fetchOpts); |
25 |
| - return fetchResult; |
| 187 | + return fetchFn; |
26 | 188 | }
|
0 commit comments