@openstax/ts-utils 1.16.0 → 1.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -32,7 +32,7 @@ export const createSlowResponseMiddleware = (config) => {
32
32
  });
33
33
  resolve(apiTextResponse(504, '504 Gateway Timeout'));
34
34
  }, timeoutAfter));
35
- const requestPromise = response.then(response => {
35
+ const requestPromise = response.finally(() => {
36
36
  const time = Date.now() - start;
37
37
  if (timeout !== undefined) {
38
38
  clearTimeout(timeout);
@@ -43,7 +43,6 @@ export const createSlowResponseMiddleware = (config) => {
43
43
  time,
44
44
  });
45
45
  }
46
- return response;
47
46
  });
48
47
  return timeoutPromise ? Promise.race([timeoutPromise, requestPromise]) : requestPromise;
49
48
  });
@@ -130,6 +130,6 @@ export const browserAuthProvider = ({ window, configSpace }) => (configProvider)
130
130
  /**
131
131
  * loads current user identity. does not reflect changes in identity after being called the first time.
132
132
  */
133
- getUser
133
+ getUser,
134
134
  };
135
135
  };
@@ -8,12 +8,12 @@ declare type Config = {
8
8
  interface Initializer<C> {
9
9
  configSpace?: C;
10
10
  }
11
- export declare type DecryptionAuthProvider = CookieAuthProvider<AuthProvider & {
12
- getTokenExpiration: () => Promise<number | undefined>;
13
- }>;
11
+ export declare type DecryptionAuthProvider = AuthProvider & {
12
+ getTokenExpiration: (tokenString?: string) => Promise<number | null | undefined>;
13
+ };
14
14
  export declare const decryptionAuthProvider: <C extends string = "decryption">(initializer: Initializer<C>) => (configProvider: { [key in C]: {
15
15
  cookieName: import("../../config").ConfigValueProvider<string>;
16
16
  encryptionPrivateKey: import("../../config").ConfigValueProvider<string>;
17
17
  signaturePublicKey: import("../../config").ConfigValueProvider<string>;
18
- }; }) => DecryptionAuthProvider;
18
+ }; }) => CookieAuthProvider<DecryptionAuthProvider>;
19
19
  export {};
@@ -18,8 +18,8 @@ export const decryptionAuthProvider = (initializer) => (configProvider) => {
18
18
  }
19
19
  return { headers };
20
20
  };
21
- const getPayload = async () => {
22
- const [token] = getAuthTokenOrCookie(request, await cookieName());
21
+ const getPayload = async (tokenString) => {
22
+ const token = tokenString !== null && tokenString !== void 0 ? tokenString : getAuthTokenOrCookie(request, await cookieName())[0];
23
23
  if (!token) {
24
24
  return undefined;
25
25
  }
@@ -37,9 +37,10 @@ export const decryptionAuthProvider = (initializer) => (configProvider) => {
37
37
  };
38
38
  return {
39
39
  getAuthorizedFetchConfig,
40
- getTokenExpiration: async () => {
41
- const result = await getPayload();
42
- return result ? result.exp : undefined;
40
+ getTokenExpiration: async (tokenString) => {
41
+ var _a;
42
+ const payload = await getPayload(tokenString);
43
+ return payload ? ((_a = payload.exp) !== null && _a !== void 0 ? _a : null) : undefined;
43
44
  },
44
45
  getUser: async () => {
45
46
  if (!user) {
@@ -51,7 +51,7 @@ export const fileSystemUnversionedDocumentStore = (initializer) => () => (config
51
51
  await mkTableDir;
52
52
  const data = await load(filename);
53
53
  if (!data) {
54
- throw new Error(`Item with ${hashKey.toString()} "${id}" does not exist`);
54
+ throw new NotFoundError(`Item with ${hashKey.toString()} "${id}" does not exist`);
55
55
  }
56
56
  const newValue = typeof data[attribute] === 'number' ? data[attribute] + 1 : 1;
57
57
  const newItem = { ...data, [hashKey]: id, [attribute]: newValue };
@@ -21,7 +21,7 @@ export declare const createLaunchSigner: <C extends string = "launch">({ configS
21
21
  jwks: () => Promise<{
22
22
  keys: JWK.RawKey[];
23
23
  }>;
24
- sign: (subject: string, maxExpiresIn?: string | number | undefined) => Promise<string>;
24
+ sign: (subject: string, maxExp?: number | null | undefined) => Promise<string>;
25
25
  };
26
26
  export declare type LaunchSigner = ReturnType<ReturnType<typeof createLaunchSigner>>;
27
27
  export {};
@@ -28,17 +28,21 @@ export const createLaunchSigner = ({ configSpace }) => (configProvider) => {
28
28
  return keystore;
29
29
  });
30
30
  const jwks = async () => (await getKeyStore()).toJSON(false);
31
- const getExpiresInWithMax = async (maxExpiresIn) => {
31
+ const getExpiresInWithMax = async (maxExp) => {
32
32
  const expiresIn = await getExpiresIn();
33
- const maxExpiresInSeconds = typeof maxExpiresIn === 'number' ? maxExpiresIn :
34
- typeof maxExpiresIn === 'string' ? Math.floor(ms(maxExpiresIn) / 1000) :
35
- undefined;
36
- return maxExpiresInSeconds ? Math.min(Math.floor(ms(expiresIn) / 1000), maxExpiresInSeconds) : expiresIn;
33
+ // The ms library used by jsonwebtoken can handle a value in seconds as well as a string like '1d'
34
+ if (!maxExp) {
35
+ return expiresIn;
36
+ }
37
+ // Convert both values to seconds for comparison
38
+ const expiresInSeconds = Math.floor(ms(expiresIn) / 1000);
39
+ const maxExpSeconds = maxExp - Math.floor(Date.now() / 1000);
40
+ return Math.min(expiresInSeconds, maxExpSeconds);
37
41
  };
38
- const sign = async (subject, maxExpiresIn) => {
42
+ const sign = async (subject, maxExp) => {
39
43
  const alg = await getAlg();
40
44
  // expiresIn can be a number of seconds or a string like '1h' or '1d'
41
- const expiresIn = await getExpiresInWithMax(maxExpiresIn);
45
+ const expiresIn = await getExpiresInWithMax(maxExp);
42
46
  const iss = await getIss();
43
47
  const header = { alg, iss };
44
48
  return jwt.sign({}, await getPrivateKey(), { algorithm: alg, expiresIn, header, issuer: iss, subject });
@@ -1,3 +1,4 @@
1
+ import jwt from 'jsonwebtoken';
1
2
  import type { JWK } from 'node-jose';
2
3
  import { ConfigProviderForConfig } from '../../config';
3
4
  declare type Config = {
@@ -15,7 +16,7 @@ interface Initializer<C> {
15
16
  export declare const createLaunchVerifier: <C extends string = "launch">({ configSpace, fetcher }: Initializer<C>) => (configProvider: { [key in C]: {
16
17
  trustedDomain: import("../../config").ConfigValueProvider<string>;
17
18
  }; }) => {
18
- verify: (token: string) => Promise<string>;
19
+ verify: <T = undefined>(...[token, validator]: T extends undefined ? [string] : [string, (input: any) => T]) => Promise<T extends undefined ? jwt.JwtPayload : T>;
19
20
  };
20
21
  export declare type LaunchVerifier = ReturnType<ReturnType<typeof createLaunchVerifier>>;
21
22
  export {};
@@ -34,7 +34,7 @@ export const createLaunchVerifier = ({ configSpace, fetcher }) => (configProvide
34
34
  callback(error);
35
35
  }
36
36
  };
37
- const verify = (token) => new Promise((resolve, reject) => jwt.verify(token, getKey, {}, (err, payload) => {
37
+ const verify = (...[token, validator]) => new Promise((resolve, reject) => jwt.verify(token, getKey, {}, (err, payload) => {
38
38
  if (err && err instanceof TokenExpiredError) {
39
39
  reject(new SessionExpiredError());
40
40
  }
@@ -48,7 +48,19 @@ export const createLaunchVerifier = ({ configSpace, fetcher }) => (configProvide
48
48
  reject(new Error('JWT payload missing sub claim'));
49
49
  }
50
50
  else {
51
- resolve(payload.sub);
51
+ // we are migrating away from json encoding all the parameters into the `sub` claim
52
+ // and into using separate claims for each parameter. in transition, we check if the sub
53
+ // is json and return it if it is. this is still a breaking change when using this
54
+ // utility because applications no longer need to independently json parse the result
55
+ // starting now.
56
+ const parsed = payload;
57
+ try {
58
+ const jsonSubContents = JSON.parse(payload.sub);
59
+ Object.assign(parsed, jsonSubContents);
60
+ }
61
+ catch (e) { } // eslint-disable-line no-empty
62
+ // conditional return types are annoying
63
+ resolve((validator ? validator(parsed) : parsed));
52
64
  }
53
65
  }));
54
66
  return { verify };