@openstax/ts-utils 1.31.2 → 1.32.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.
Files changed (32) hide show
  1. package/dist/cjs/services/apiGateway/index.d.ts +1 -1
  2. package/dist/cjs/services/authProvider/browser.d.ts +3 -3
  3. package/dist/cjs/services/authProvider/decryption.d.ts +5 -1
  4. package/dist/cjs/services/authProvider/decryption.js +28 -18
  5. package/dist/cjs/services/authProvider/index.d.ts +6 -6
  6. package/dist/cjs/services/authProvider/subrequest.d.ts +1 -1
  7. package/dist/cjs/services/authProvider/subrequest.js +2 -7
  8. package/dist/cjs/services/authProvider/utils/userSubrequest.d.ts +3 -0
  9. package/dist/cjs/services/authProvider/utils/userSubrequest.js +13 -0
  10. package/dist/cjs/services/fileServer/index.d.ts +0 -12
  11. package/dist/cjs/services/fileServer/localFileServer.js +1 -52
  12. package/dist/cjs/services/fileServer/s3FileServer.d.ts +0 -1
  13. package/dist/cjs/services/fileServer/s3FileServer.js +0 -78
  14. package/dist/cjs/services/searchProvider/openSearch.js +4 -6
  15. package/dist/cjs/tsconfig.without-specs.cjs.tsbuildinfo +1 -1
  16. package/dist/esm/services/apiGateway/index.d.ts +1 -1
  17. package/dist/esm/services/authProvider/browser.d.ts +3 -3
  18. package/dist/esm/services/authProvider/decryption.d.ts +5 -1
  19. package/dist/esm/services/authProvider/decryption.js +28 -18
  20. package/dist/esm/services/authProvider/index.d.ts +6 -6
  21. package/dist/esm/services/authProvider/subrequest.d.ts +1 -1
  22. package/dist/esm/services/authProvider/subrequest.js +2 -4
  23. package/dist/esm/services/authProvider/utils/userSubrequest.d.ts +3 -0
  24. package/dist/esm/services/authProvider/utils/userSubrequest.js +6 -0
  25. package/dist/esm/services/fileServer/index.d.ts +0 -12
  26. package/dist/esm/services/fileServer/localFileServer.js +2 -53
  27. package/dist/esm/services/fileServer/s3FileServer.d.ts +0 -1
  28. package/dist/esm/services/fileServer/s3FileServer.js +1 -76
  29. package/dist/esm/services/searchProvider/openSearch.js +4 -6
  30. package/dist/esm/tsconfig.without-specs.esm.tsbuildinfo +1 -1
  31. package/package.json +3 -4
  32. package/script/bin/.init-params-script.bash.swp +0 -0
@@ -38,7 +38,7 @@ export type ApiClientResponse<Ro> = Ro extends any ? {
38
38
  } : never;
39
39
  export type ExpandRoute<T> = T extends ((...args: infer A) => infer R) & {
40
40
  renderUrl: (...args: infer Ar) => Promise<string>;
41
- } ? ((...args: A) => R) & {
41
+ } ? (...args: A) => R & {
42
42
  renderUrl: (...args: Ar) => Promise<string>;
43
43
  } : never;
44
44
  export type MapRoutesToClient<Ru> = [Ru] extends [AnyRoute<Ru>] ? {
@@ -1,6 +1,6 @@
1
1
  import { ConfigProviderForConfig } from '../../config';
2
2
  import { FetchConfig, GenericFetch } from '../../fetch';
3
- import { User } from '.';
3
+ import { ApiUser, User } from '.';
4
4
  type Config = {
5
5
  accountsBase: string;
6
6
  };
@@ -26,7 +26,7 @@ export interface Window {
26
26
  addEventListener: (event: 'message', callback: EventHandler) => void;
27
27
  removeEventListener: (event: 'message', callback: EventHandler) => void;
28
28
  }
29
- export type UpdatableUserFields = Partial<Pick<User, 'consent_preferences' | 'first_name' | 'last_name'>>;
29
+ export type UpdatableUserFields = Partial<Pick<ApiUser, 'consent_preferences' | 'first_name' | 'last_name'>>;
30
30
  export declare const browserAuthProvider: <C extends string = "auth">({ window, configSpace }: Initializer<C>) => (configProvider: { [_key in C]: ConfigProviderForConfig<Config>; }) => {
31
31
  /**
32
32
  * gets the authentication token
@@ -65,7 +65,7 @@ export declare const browserAuthProvider: <C extends string = "auth">({ window,
65
65
  * updates user settings, for example the cookie consent preferences
66
66
  */
67
67
  updateUser: (updates: UpdatableUserFields) => Promise<{
68
- user: User;
68
+ user: ApiUser;
69
69
  token: string | null;
70
70
  }>;
71
71
  };
@@ -1,15 +1,19 @@
1
1
  import type { ConfigProviderForConfig } from '../../config';
2
- import { AuthProvider, CookieAuthProvider } from '.';
2
+ import { GenericFetch } from '../../fetch';
3
+ import { ApiUser, AuthProvider, CookieAuthProvider } from '.';
3
4
  type Config = {
5
+ accountsBase: string;
4
6
  cookieName: string;
5
7
  encryptionPrivateKey: string;
6
8
  signaturePublicKey: string;
7
9
  };
8
10
  interface Initializer<C> {
9
11
  configSpace?: C;
12
+ fetch: GenericFetch;
10
13
  }
11
14
  export type DecryptionAuthProvider = AuthProvider & {
12
15
  getTokenExpiration: (tokenString?: string) => Promise<number | null | undefined>;
16
+ loadUserData: () => Promise<ApiUser | undefined>;
13
17
  };
14
18
  export declare const decryptionAuthProvider: <C extends string = "decryption">(initializer: Initializer<C>) => (configProvider: { [_key in C]: ConfigProviderForConfig<Config>; }) => CookieAuthProvider<DecryptionAuthProvider>;
15
19
  export {};
@@ -3,14 +3,17 @@ import { SessionExpiredError } from '../../errors';
3
3
  import { ifDefined } from '../../guards';
4
4
  import { once } from '../../misc/helpers';
5
5
  import { decryptAndVerify } from './utils/decryptAndVerify';
6
+ import { loadUserData } from './utils/userSubrequest';
6
7
  import { getAuthTokenOrCookie } from '.';
7
8
  export const decryptionAuthProvider = (initializer) => (configProvider) => {
8
9
  const config = configProvider[ifDefined(initializer.configSpace, 'decryption')];
10
+ const accountsBase = once(() => resolveConfigValue(config.accountsBase));
9
11
  const cookieName = once(() => resolveConfigValue(config.cookieName));
10
12
  const encryptionPrivateKey = once(() => resolveConfigValue(config.encryptionPrivateKey));
11
13
  const signaturePublicKey = once(() => resolveConfigValue(config.signaturePublicKey));
12
14
  return ({ request, logger }) => {
13
15
  let user;
16
+ let userData;
14
17
  const getAuthToken = async () => getAuthTokenOrCookie(request, await cookieName())[0];
15
18
  const getAuthorizedFetchConfig = async () => {
16
19
  const [token, headers] = getAuthTokenOrCookie(request, await cookieName());
@@ -19,40 +22,47 @@ export const decryptionAuthProvider = (initializer) => (configProvider) => {
19
22
  }
20
23
  return { headers };
21
24
  };
22
- const getPayload = async (tokenString) => {
25
+ const getDecryptedPayload = async (tokenString) => {
23
26
  const token = tokenString !== null && tokenString !== void 0 ? tokenString : await getAuthToken();
24
27
  if (!token) {
25
28
  return undefined;
26
29
  }
27
30
  return decryptAndVerify(token, await encryptionPrivateKey(), await signaturePublicKey());
28
31
  };
29
- const loadUser = async () => {
30
- const result = await getPayload();
31
- if (!result) {
32
- return undefined;
33
- }
34
- if ('error' in result && result.error == 'expired token') {
35
- throw new SessionExpiredError();
36
- }
37
- if ('user' in result) {
38
- logger.setContext({ user: result.user.uuid });
39
- return result.user;
32
+ const getUser = async () => {
33
+ if (!user) {
34
+ const result = await getDecryptedPayload();
35
+ if (!result) {
36
+ return undefined;
37
+ }
38
+ if ('error' in result && result.error == 'expired token') {
39
+ throw new SessionExpiredError();
40
+ }
41
+ if ('user' in result) {
42
+ logger.setContext({ user: result.user.uuid });
43
+ user = result.user;
44
+ }
40
45
  }
41
- return undefined;
46
+ return user;
42
47
  };
43
48
  return {
44
49
  getAuthToken,
45
50
  getAuthorizedFetchConfig,
46
51
  getTokenExpiration: async (tokenString) => {
47
52
  var _a;
48
- const payload = await getPayload(tokenString);
53
+ const payload = await getDecryptedPayload(tokenString);
49
54
  return payload ? ((_a = payload.exp) !== null && _a !== void 0 ? _a : null) : undefined;
50
55
  },
51
- getUser: async () => {
52
- if (!user) {
53
- user = await loadUser();
56
+ getUser,
57
+ loadUserData: async () => {
58
+ if (!userData) {
59
+ const token = await getAuthToken();
60
+ if (!token) {
61
+ return undefined;
62
+ }
63
+ userData = await loadUserData(initializer.fetch, await accountsBase(), await cookieName(), token);
54
64
  }
55
- return user;
65
+ return userData;
56
66
  },
57
67
  };
58
68
  };
@@ -10,14 +10,14 @@ export type ConsentPreferences = {
10
10
  export type TokenUser = {
11
11
  id: number;
12
12
  name: string;
13
+ uuid: string;
14
+ faculty_status: string;
15
+ is_admin: boolean;
16
+ };
17
+ export type ApiUser = TokenUser & {
13
18
  first_name: string;
14
19
  last_name: string;
15
20
  full_name: string;
16
- uuid: string;
17
- faculty_status: string;
18
- is_administrator: boolean;
19
- } & Partial<ConsentPreferences>;
20
- export interface ApiUser extends TokenUser {
21
21
  contact_infos: Array<{
22
22
  type: string;
23
23
  value: string;
@@ -34,7 +34,7 @@ export interface ApiUser extends TokenUser {
34
34
  self_reported_role: string;
35
35
  signed_contract_names: string[];
36
36
  using_openstax: boolean;
37
- }
37
+ } & Partial<ConsentPreferences>;
38
38
  export type User = TokenUser | ApiUser;
39
39
  export type AuthProvider = {
40
40
  getAuthToken: () => Promise<string | null>;
@@ -2,8 +2,8 @@ import { ConfigProviderForConfig } from '../../config';
2
2
  import { GenericFetch } from '../../fetch';
3
3
  import { CookieAuthProvider } from '.';
4
4
  type Config = {
5
- cookieName: string;
6
5
  accountsBase: string;
6
+ cookieName: string;
7
7
  };
8
8
  interface Initializer<C> {
9
9
  configSpace?: C;
@@ -1,7 +1,7 @@
1
- import cookie from 'cookie';
2
1
  import { once } from '../..';
3
2
  import { resolveConfigValue } from '../../config';
4
3
  import { ifDefined } from '../../guards';
4
+ import { loadUserData } from './utils/userSubrequest';
5
5
  import { getAuthTokenOrCookie } from '.';
6
6
  export const subrequestAuthProvider = (initializer) => (configProvider) => {
7
7
  const config = configProvider[ifDefined(initializer.configSpace, 'subrequest')];
@@ -23,9 +23,7 @@ export const subrequestAuthProvider = (initializer) => (configProvider) => {
23
23
  if (!token) {
24
24
  return undefined;
25
25
  }
26
- const headers = { cookie: cookie.serialize(resolvedCookieName, token) };
27
- const user = await initializer.fetch((await accountsBase()).replace(/\/+$/, '') + '/api/user', { headers })
28
- .then(response => response.json());
26
+ const user = await loadUserData(initializer.fetch, await accountsBase(), resolvedCookieName, token);
29
27
  if (user) {
30
28
  logger.setContext({ user: user.uuid });
31
29
  }
@@ -0,0 +1,3 @@
1
+ import { ApiUser } from '..';
2
+ import { GenericFetch } from '../../../fetch';
3
+ export declare const loadUserData: (fetch: GenericFetch, accountsBase: string, cookieName: string, token: string) => Promise<ApiUser | undefined>;
@@ -0,0 +1,6 @@
1
+ import cookie from 'cookie';
2
+ export const loadUserData = (fetch, accountsBase, cookieName, token) => {
3
+ const headers = { cookie: cookie.serialize(cookieName, token) };
4
+ return fetch(accountsBase.replace(/\/+$/, '') + '/api/user', { headers })
5
+ .then(response => response.json());
6
+ };
@@ -13,18 +13,6 @@ export declare const isFolderValue: (thing: any) => thing is FolderValue;
13
13
  export interface FileServerAdapter {
14
14
  putFileContent: (source: FileValue, content: string) => Promise<FileValue>;
15
15
  getSignedViewerUrl: (source: FileValue) => Promise<string>;
16
- getPublicViewerUrl: (source: FileValue) => Promise<string>;
17
16
  getFileContent: (source: FileValue) => Promise<Buffer>;
18
- getSignedFileUploadConfig: () => Promise<{
19
- url: string;
20
- payload: {
21
- [key: string]: string;
22
- };
23
- }>;
24
- copyFileTo: (source: FileValue, destinationPath: string) => Promise<FileValue>;
25
- copyFileToDirectory: (source: FileValue, destinationDirectory: string) => Promise<FileValue>;
26
- isTemporaryUpload: (source: FileValue) => boolean;
27
- getFileChecksum: (source: FileValue) => Promise<string>;
28
- filesEqual: (sourceA: FileValue, sourceB: FileValue) => Promise<boolean>;
29
17
  }
30
18
  export declare const isFileOrFolder: (thing: any) => thing is FileValue | FolderValue;
@@ -1,18 +1,16 @@
1
1
  /* cspell:ignore originalname */
2
- import crypto from 'crypto';
3
2
  import fs from 'fs';
4
3
  import https from 'https';
5
4
  import path from 'path';
6
5
  import cors from 'cors';
7
6
  import express from 'express';
8
7
  import multer from 'multer';
9
- import { v4 as uuid } from 'uuid';
10
8
  import { assertString } from '../../assertions';
11
9
  import { resolveConfigValue } from '../../config';
12
10
  import { ifDefined } from '../../guards';
13
- import { memoize } from '../../misc/helpers';
11
+ import { once } from '../../misc/helpers';
14
12
  /* istanbul ignore next */
15
- const startServer = memoize((port, uploadDir) => {
13
+ const startServer = once((port, uploadDir) => {
16
14
  // TODO - re-evaluate the `preservePath` behavior to match whatever s3 does
17
15
  const upload = multer({ dest: uploadDir, preservePath: true });
18
16
  const fileServerApp = express();
@@ -57,9 +55,6 @@ export const localFileServer = (initializer) => (configProvider) => {
57
55
  const getSignedViewerUrl = async (source) => {
58
56
  return `https://${await host}:${await port}/${source.path}`;
59
57
  };
60
- const getPublicViewerUrl = async (source) => {
61
- return `https://${await host}:${await port}/${source.path}`;
62
- };
63
58
  const getFileContent = async (source) => {
64
59
  const filePath = path.join(await fileDir, source.path);
65
60
  return fs.promises.readFile(filePath);
@@ -71,55 +66,9 @@ export const localFileServer = (initializer) => (configProvider) => {
71
66
  await fs.promises.writeFile(filePath, content);
72
67
  return source;
73
68
  };
74
- const getSignedFileUploadConfig = async () => {
75
- const prefix = 'uploads/' + uuid();
76
- return {
77
- url: `https://${await host}:${await port}/`,
78
- payload: {
79
- key: prefix + '/${filename}',
80
- }
81
- };
82
- };
83
- const copyFileTo = async (source, destinationPath) => {
84
- const sourcePath = path.join(await fileDir, source.path);
85
- const destPath = path.join(await fileDir, destinationPath);
86
- const destDirectory = path.dirname(destPath);
87
- await fs.promises.mkdir(destDirectory, { recursive: true });
88
- await fs.promises.copyFile(sourcePath, destPath);
89
- return {
90
- ...source,
91
- path: destinationPath
92
- };
93
- };
94
- const copyFileToDirectory = async (source, destination) => {
95
- const destinationPath = path.join(destination, source.label);
96
- return copyFileTo(source, destinationPath);
97
- };
98
- const isTemporaryUpload = (source) => {
99
- return source.path.indexOf('uploads/') === 0;
100
- };
101
- const getFileChecksum = async (source) => {
102
- const filePath = path.join(await fileDir, source.path);
103
- const fileContent = await fs.promises.readFile(filePath);
104
- return crypto.createHash('md5').update(fileContent).digest('hex');
105
- };
106
- const filesEqual = async (sourceA, sourceB) => {
107
- const [aSum, bSum] = await Promise.all([
108
- getFileChecksum(sourceA),
109
- getFileChecksum(sourceB)
110
- ]);
111
- return aSum === bSum;
112
- };
113
69
  return {
114
70
  getSignedViewerUrl,
115
- getPublicViewerUrl,
116
71
  getFileContent,
117
72
  putFileContent,
118
- getSignedFileUploadConfig,
119
- copyFileTo,
120
- copyFileToDirectory,
121
- isTemporaryUpload,
122
- getFileChecksum,
123
- filesEqual,
124
73
  };
125
74
  };
@@ -4,7 +4,6 @@ import { FileServerAdapter } from '.';
4
4
  export type Config = {
5
5
  bucketName: string;
6
6
  bucketRegion: string;
7
- publicViewerDomain?: string;
8
7
  };
9
8
  interface Initializer<C> {
10
9
  configSpace?: C;
@@ -1,9 +1,6 @@
1
1
  /* cspell:ignore presigner */
2
- import { CopyObjectCommand, GetObjectCommand, HeadObjectCommand, PutObjectCommand, S3Client } from '@aws-sdk/client-s3';
3
- import { createPresignedPost } from '@aws-sdk/s3-presigned-post';
2
+ import { GetObjectCommand, PutObjectCommand, S3Client } from '@aws-sdk/client-s3';
4
3
  import { getSignedUrl } from '@aws-sdk/s3-request-presigner';
5
- import path from 'path';
6
- import { v4 as uuid } from 'uuid';
7
4
  import { once } from '../..';
8
5
  import { assertDefined } from '../../assertions';
9
6
  import { resolveConfigValue } from '../../config';
@@ -12,9 +9,6 @@ export const s3FileServer = (initializer) => (configProvider) => {
12
9
  const config = configProvider[ifDefined(initializer.configSpace, 'deployed')];
13
10
  const bucketName = once(() => resolveConfigValue(config.bucketName));
14
11
  const bucketRegion = once(() => resolveConfigValue(config.bucketRegion));
15
- const publicViewerDomain = once(() => 'publicViewerDomain' in config && config.publicViewerDomain
16
- ? resolveConfigValue(config.publicViewerDomain)
17
- : undefined);
18
12
  const s3Service = once(async () => {
19
13
  var _a, _b;
20
14
  const args = { apiVersion: '2012-08-10', region: await bucketRegion() };
@@ -30,10 +24,6 @@ export const s3FileServer = (initializer) => (configProvider) => {
30
24
  expiresIn: 3600, // 1 hour
31
25
  });
32
26
  };
33
- const getPublicViewerUrl = async (source) => {
34
- const host = assertDefined(await publicViewerDomain(), new Error(`Tried to get public viewer URL for ${source.path} but no publicViewerDomain configured`));
35
- return `https://${host}/${source.path}`;
36
- };
37
27
  const getFileContent = async (source) => {
38
28
  const bucket = await bucketName();
39
29
  const command = new GetObjectCommand({ Bucket: bucket, Key: source.path });
@@ -51,74 +41,9 @@ export const s3FileServer = (initializer) => (configProvider) => {
51
41
  await (await s3Service()).send(command);
52
42
  return source;
53
43
  };
54
- /*
55
- * https://docs.aws.amazon.com/AWSJavaScriptSDK/v3/latest/modules/_aws_sdk_s3_presigned_post.html
56
- * https://docs.aws.amazon.com/AmazonS3/latest/userguide/HTTPPOSTExamples.html
57
- * https://docs.aws.amazon.com/AmazonS3/latest/API/sigv4-post-example.html
58
- */
59
- const getSignedFileUploadConfig = async () => {
60
- const prefix = 'uploads/' + uuid();
61
- const bucket = (await bucketName());
62
- const Conditions = [
63
- { acl: 'private' },
64
- { bucket },
65
- ['starts-with', '$key', prefix]
66
- ];
67
- const defaultFields = {
68
- acl: 'private',
69
- };
70
- const { url, fields } = await createPresignedPost(await s3Service(), {
71
- Bucket: bucket,
72
- Key: prefix + '/${filename}',
73
- Conditions,
74
- Fields: defaultFields,
75
- Expires: 3600, // 1 hour
76
- });
77
- return {
78
- url, payload: fields
79
- };
80
- };
81
- const copyFileTo = async (source, destinationPath) => {
82
- const bucket = (await bucketName());
83
- const destinationPathWithoutLeadingSlash = destinationPath.replace(/^\//, '');
84
- const command = new CopyObjectCommand({
85
- Bucket: bucket,
86
- Key: destinationPathWithoutLeadingSlash,
87
- CopySource: path.join(bucket, source.path),
88
- });
89
- await (await s3Service()).send(command);
90
- return {
91
- ...source,
92
- path: destinationPathWithoutLeadingSlash
93
- };
94
- };
95
- const copyFileToDirectory = async (source, destination) => {
96
- const destinationPath = path.join(destination, source.label);
97
- return copyFileTo(source, destinationPath);
98
- };
99
- const isTemporaryUpload = (source) => {
100
- return source.path.indexOf('uploads/') === 0;
101
- };
102
- const getFileChecksum = async (source) => {
103
- const bucket = (await bucketName());
104
- const command = new HeadObjectCommand({ Bucket: bucket, Key: source.path });
105
- const response = await (await s3Service()).send(command);
106
- return assertDefined(response.ETag);
107
- };
108
- const filesEqual = async (sourceA, sourceB) => {
109
- const [aSum, bSum] = await Promise.all([getFileChecksum(sourceA), getFileChecksum(sourceB)]);
110
- return aSum === bSum;
111
- };
112
44
  return {
113
45
  getFileContent,
114
46
  putFileContent,
115
47
  getSignedViewerUrl,
116
- getPublicViewerUrl,
117
- getSignedFileUploadConfig,
118
- copyFileTo,
119
- copyFileToDirectory,
120
- isTemporaryUpload,
121
- getFileChecksum,
122
- filesEqual,
123
48
  };
124
49
  };
@@ -26,6 +26,10 @@ export const openSearchService = (initializer = {}) => (configProvider) => {
26
26
  maxRetries: 4, // default is 3
27
27
  requestTimeout: 5000, // default is 30000
28
28
  pingTimeout: 2000, // default is 30000
29
+ sniffOnConnectionFault: true,
30
+ sniffOnStart: true,
31
+ resurrectStrategy: 'ping',
32
+ agent: { keepAlive: false },
29
33
  node: await resolveConfigValue(config.node),
30
34
  }));
31
35
  return (indexConfig) => {
@@ -61,9 +65,6 @@ export const openSearchService = (initializer = {}) => (configProvider) => {
61
65
  body: params.body,
62
66
  id: params.id,
63
67
  refresh: true
64
- }, {
65
- requestTimeout: 10000,
66
- maxRetries: 1,
67
68
  });
68
69
  };
69
70
  const bulkIndex = async (items) => {
@@ -75,9 +76,6 @@ export const openSearchService = (initializer = {}) => (configProvider) => {
75
76
  item.body
76
77
  ]),
77
78
  refresh: true
78
- }, {
79
- requestTimeout: 10000,
80
- maxRetries: 1,
81
79
  });
82
80
  };
83
81
  const search = async (options) => {