@openstax/ts-utils 1.38.3 → 1.39.1

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.
@@ -3,6 +3,7 @@ import { VerifyConfig } from 'http-message-signatures';
3
3
  import { JWK } from 'node-jose';
4
4
  import { ConfigProviderForConfig } from '../../config';
5
5
  type Config = {
6
+ apiHost: string;
6
7
  bypassSignatureVerification: string;
7
8
  };
8
9
  interface Initializer<C> {
@@ -5,6 +5,7 @@ exports.createHttpMessageVerifier = void 0;
5
5
  const crypto_1 = require("crypto");
6
6
  const http_message_signatures_1 = require("http-message-signatures");
7
7
  const jwks_rsa_1 = require("jwks-rsa");
8
+ const structured_headers_1 = require("structured-headers");
8
9
  const assertions_1 = require("../../assertions");
9
10
  const config_1 = require("../../config");
10
11
  const errors_1 = require("../../errors");
@@ -12,6 +13,7 @@ const helpers_1 = require("../../misc/helpers");
12
13
  const jwks_1 = require("../../misc/jwks");
13
14
  const createHttpMessageVerifier = ({ configSpace, fetcher }) => (configProvider) => {
14
15
  const config = configProvider[configSpace !== null && configSpace !== void 0 ? configSpace : 'verifier'];
16
+ const getApiHost = (0, helpers_1.once)(async () => await (0, config_1.resolveConfigValue)(config.apiHost));
15
17
  const getBypassSignatureVerification = (0, helpers_1.once)(async () => (await (0, config_1.resolveConfigValue)(config.bypassSignatureVerification)) === 'true');
16
18
  return ({ request }) => ({
17
19
  verify: async ({ configOverride, signatureAgentVerifier }) => {
@@ -30,9 +32,25 @@ const createHttpMessageVerifier = ({ configSpace, fetcher }) => (configProvider)
30
32
  // but we do not bother matching the Signature-Agent names with the Signature names
31
33
  // as that would be awkward with the packages we use
32
34
  const signatureAgentString = (_a = headers['signature-agent']) !== null && _a !== void 0 ? _a : '';
33
- const signatureAgentMatches = [...signatureAgentString.matchAll(/([^=]+)="([^"]+)"/g)];
34
- const signatureAgents = signatureAgentMatches.length == 0 ?
35
- [signatureAgentString] : [...new Set(signatureAgentMatches.map((match) => match[2]))];
35
+ let rawValues;
36
+ // Try parsing as RFC 8941 Item first (e.g., "https://url" or bare token)
37
+ try {
38
+ rawValues = [(0, structured_headers_1.parseItem)(signatureAgentString)];
39
+ }
40
+ catch {
41
+ // If item parsing fails, try parsing as a Dictionary (e.g., sig="https://url")
42
+ rawValues = Array.from((0, structured_headers_1.parseDictionary)(signatureAgentString).values());
43
+ }
44
+ // Convert values to strings (handle Token, string, and reject others) and deduplicate
45
+ const signatureAgents = [...new Set(rawValues.map(([bareItem]) => {
46
+ if (bareItem instanceof structured_headers_1.Token) {
47
+ return bareItem.toString();
48
+ }
49
+ return (0, assertions_1.assertString)(bareItem, new errors_1.InvalidRequestError('Signature-Agent values must be strings or tokens'));
50
+ }))];
51
+ if (signatureAgents.length === 0) {
52
+ throw new errors_1.InvalidRequestError('Signature-Agent header is required');
53
+ }
36
54
  const keys = (await Promise.all(signatureAgents.map(async (signatureAgent) => {
37
55
  if (!await signatureAgentVerifier(signatureAgent)) {
38
56
  throw new errors_1.InvalidRequestError('Signature-Agent verification failed');
@@ -44,8 +62,7 @@ const createHttpMessageVerifier = ({ configSpace, fetcher }) => (configProvider)
44
62
  body,
45
63
  headers,
46
64
  method: requestContext.http.method,
47
- // Node's request.url is really just the path and querystring
48
- url: requestContext.http.path,
65
+ url: `${await getApiHost()}${requestContext.http.path}${request.rawQueryString ? `?${request.rawQueryString}` : ''}`,
49
66
  };
50
67
  if (!await http_message_signatures_1.httpbis.verifyMessage({
51
68
  all: true,
@@ -78,14 +95,37 @@ const createHttpMessageVerifier = ({ configSpace, fetcher }) => (configProvider)
78
95
  // For example, if a GET request uses configOverride to make content-digest not required
79
96
  if (!headers['content-digest'])
80
97
  return true;
81
- const match = headers['content-digest'].match(/^(sha-256|sha-512)=:([^:]+):/);
82
- if (!match)
98
+ let contentDigest;
99
+ try {
100
+ contentDigest = (0, structured_headers_1.parseDictionary)(headers['content-digest']);
101
+ }
102
+ catch {
83
103
  throw new errors_1.InvalidRequestError('Unsupported Content-Digest header format');
84
- const contentDigestAlg = match[1];
85
- const contentDigestHash = match[2];
86
- const calculatedContentDigestHash = (0, crypto_1.createHash)(contentDigestAlg).update((0, assertions_1.assertString)(body)).digest('base64');
87
- if (calculatedContentDigestHash !== contentDigestHash.replace(/:/g, '')) {
88
- throw new errors_1.InvalidRequestError('Calculated Content-Digest value did not match header');
104
+ }
105
+ if (contentDigest.size === 0) {
106
+ throw new errors_1.InvalidRequestError('Content-Digest header is required');
107
+ }
108
+ // Map Content-Digest algorithm names to Node's crypto algorithm names
109
+ const algorithmMap = {
110
+ 'sha-256': 'sha256',
111
+ 'sha-512': 'sha512',
112
+ };
113
+ for (const [algorithm, value] of contentDigest.entries()) {
114
+ const [bareItem] = value;
115
+ // Convert ByteSequence to string, or assert it's already a string
116
+ const hashValue = bareItem instanceof structured_headers_1.ByteSequence
117
+ ? bareItem.toBase64()
118
+ : (0, assertions_1.assertString)(bareItem, new errors_1.InvalidRequestError('Content-Digest values must be strings'));
119
+ const cryptoAlgorithm = algorithmMap[algorithm];
120
+ if (!cryptoAlgorithm) {
121
+ throw new errors_1.InvalidRequestError(`Unsupported Content-Digest algorithm: ${algorithm}`);
122
+ }
123
+ // Calculate the hash
124
+ const calculatedHash = (0, crypto_1.createHash)(cryptoAlgorithm).update((0, assertions_1.assertString)(body, new errors_1.InvalidRequestError('Request body is required when Content-Digest is present'))).digest('base64');
125
+ // Compare with the provided hash
126
+ if (calculatedHash !== hashValue) {
127
+ throw new errors_1.InvalidRequestError(`Calculated Content-Digest value did not match header for algorithm ${algorithm}`);
128
+ }
89
129
  }
90
130
  return true;
91
131
  },
@@ -1,5 +1,6 @@
1
- import { User } from '../authProvider';
2
1
  import { EagerXapiStatement, UXapiStatement, XapiStatement } from '.';
3
2
  export declare const addStatementDefaultFields: (statement: (Pick<XapiStatement, "object" | "verb" | "context" | "result"> & {
4
3
  id?: string;
5
- }) | UXapiStatement, user: User) => EagerXapiStatement;
4
+ }) | UXapiStatement, user: {
5
+ uuid: string;
6
+ }) => EagerXapiStatement;
@@ -79,7 +79,7 @@ export declare const putAttemptStatement: (gateway: LrsGateway, activity: {
79
79
  export declare const createAttemptActivityStatement: (attemptStatement: UXapiStatement, verb: UXapiStatement["verb"], result?: UXapiStatement["result"]) => Pick<UXapiStatement, "object" | "verb" | "context" | "result">;
80
80
  export declare const putAttemptActivityStatement: (gateway: LrsGateway, attemptStatement: UXapiStatement, verb: UXapiStatement["verb"], result?: UXapiStatement["result"]) => Promise<import(".").EagerXapiStatement>;
81
81
  export declare const createCompletedStatement: (attemptStatement: UXapiStatement, result?: UXapiStatement["result"]) => Pick<UXapiStatement, "object" | "verb" | "context" | "result">;
82
- export declare const putCompletedStatement: (gateway: LrsGateway, attemptStatement: UXapiStatement, result: UXapiStatement["result"]) => Promise<import(".").EagerXapiStatement>;
82
+ export declare const putCompletedStatement: (gateway: LrsGateway, attemptStatement: UXapiStatement, result: UXapiStatement["result"], user?: string) => Promise<import(".").EagerXapiStatement>;
83
83
  export declare const createCompletedPendingScoringStatement: (attemptStatement: UXapiStatement) => Pick<UXapiStatement, "object" | "verb" | "context" | "result">;
84
84
  export declare const putCompletedPendingScoringStatement: (gateway: LrsGateway, attemptStatement: UXapiStatement) => Promise<import(".").EagerXapiStatement>;
85
85
  export declare const createScoredStatement: (attemptStatement: UXapiStatement, result: UXapiStatement["result"]) => Pick<UXapiStatement, "object" | "verb" | "context" | "result">;
@@ -311,8 +311,8 @@ const createCompletedStatement = (attemptStatement, result) => {
311
311
  };
312
312
  };
313
313
  exports.createCompletedStatement = createCompletedStatement;
314
- const putCompletedStatement = async (gateway, attemptStatement, result) => {
315
- return (await gateway.putXapiStatements([(0, exports.createCompletedStatement)(attemptStatement, result)]))[0];
314
+ const putCompletedStatement = async (gateway, attemptStatement, result, user) => {
315
+ return (await gateway.putXapiStatements([(0, exports.createCompletedStatement)(attemptStatement, result)], user))[0];
316
316
  };
317
317
  exports.putCompletedStatement = putCompletedStatement;
318
318
  // pending score statement for when the open written response has been graded.
@@ -84,7 +84,7 @@ export declare const lrsGateway: <C extends string = "lrs">(initializer: Initial
84
84
  }) => {
85
85
  putXapiStatements: (statements: Array<(Pick<XapiStatement, "object" | "verb" | "context" | "result"> & {
86
86
  id?: string;
87
- }) | UXapiStatement>) => Promise<EagerXapiStatement[]>;
87
+ }) | UXapiStatement>, user?: string) => Promise<EagerXapiStatement[]>;
88
88
  getXapiStatements: (params: {
89
89
  verb?: string;
90
90
  activity?: string;
@@ -56,9 +56,11 @@ const lrsGateway = (initializer) => (configProvider) => {
56
56
  status: [502]
57
57
  });
58
58
  // Note: This method actually uses POST
59
- const putXapiStatements = async (statements) => {
60
- const user = (0, assertions_1.assertDefined)(await authProvider.getUser(), new errors_1.UnauthorizedError);
61
- const statementsWithDefaults = statements.map(statement => (0, addStatementDefaultFields_1.addStatementDefaultFields)(statement, user));
59
+ const putXapiStatements = async (statements, user) => {
60
+ const userObj = user
61
+ ? { uuid: user }
62
+ : (0, assertions_1.assertDefined)(await authProvider.getUser(), new errors_1.UnauthorizedError);
63
+ const statementsWithDefaults = statements.map(statement => (0, addStatementDefaultFields_1.addStatementDefaultFields)(statement, userObj));
62
64
  const response = await fetcher((await lrsHost()).replace(/\/+$/, '') + '/data/xAPI/statements', {
63
65
  body: JSON.stringify(statementsWithDefaults),
64
66
  headers: {