repocairn 0.1.6 → 0.1.7

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 (62) hide show
  1. package/node_modules/fast-uri/index.js +201 -48
  2. package/node_modules/fast-uri/lib/schemes.js +9 -4
  3. package/node_modules/fast-uri/lib/utils.js +388 -91
  4. package/node_modules/fast-uri/package.json +1 -1
  5. package/node_modules/fast-uri/test/component-safe-serialization.test.js +105 -0
  6. package/node_modules/fast-uri/test/equal.test.js +31 -3
  7. package/node_modules/fast-uri/test/fixtures/uri-js-parse.json +2 -0
  8. package/node_modules/fast-uri/test/ipv6-canonical.test.js +34 -0
  9. package/node_modules/fast-uri/test/ipv6-validation.test.js +90 -0
  10. package/node_modules/fast-uri/test/malformed-percent.test.js +77 -0
  11. package/node_modules/fast-uri/test/malformed-urn.test.js +61 -0
  12. package/node_modules/fast-uri/test/parse.test.js +7 -3
  13. package/node_modules/fast-uri/test/query-fragment-normalization.test.js +33 -0
  14. package/node_modules/fast-uri/test/reserved-path-normalization.test.js +109 -0
  15. package/node_modules/fast-uri/test/scheme-validation.test.js +124 -0
  16. package/node_modules/fast-uri/test/security-normalization.test.js +101 -0
  17. package/node_modules/fast-uri/test/security.test.js +75 -3
  18. package/node_modules/fast-uri/test/urn-full-input.test.js +29 -0
  19. package/node_modules/fast-uri/test/websocket-query-preservation.test.js +24 -0
  20. package/node_modules/jose/dist/types/jwks/remote.d.ts +4 -4
  21. package/node_modules/jose/dist/types/jws/general/verify.d.ts +3 -3
  22. package/node_modules/jose/dist/types/jwt/encrypt.d.ts +8 -14
  23. package/node_modules/jose/dist/types/jwt/sign.d.ts +8 -14
  24. package/node_modules/jose/dist/types/jwt/unsecured.d.ts +9 -15
  25. package/node_modules/jose/dist/webapi/jwe/compact/encrypt.js +30 -8
  26. package/node_modules/jose/dist/webapi/jwe/flattened/decrypt.js +8 -4
  27. package/node_modules/jose/dist/webapi/jwe/flattened/encrypt.js +6 -13
  28. package/node_modules/jose/dist/webapi/jwe/general/decrypt.js +19 -19
  29. package/node_modules/jose/dist/webapi/jwe/general/encrypt.js +27 -20
  30. package/node_modules/jose/dist/webapi/jwk/embedded.js +15 -1
  31. package/node_modules/jose/dist/webapi/jwk/thumbprint.js +11 -5
  32. package/node_modules/jose/dist/webapi/jwks/local.js +45 -53
  33. package/node_modules/jose/dist/webapi/jwks/remote.js +82 -103
  34. package/node_modules/jose/dist/webapi/jws/compact/sign.js +10 -9
  35. package/node_modules/jose/dist/webapi/jws/flattened/sign.js +2 -1
  36. package/node_modules/jose/dist/webapi/jws/flattened/verify.js +8 -7
  37. package/node_modules/jose/dist/webapi/jws/general/sign.js +5 -3
  38. package/node_modules/jose/dist/webapi/jws/general/verify.js +51 -21
  39. package/node_modules/jose/dist/webapi/jwt/decrypt.js +7 -9
  40. package/node_modules/jose/dist/webapi/jwt/encrypt.js +21 -50
  41. package/node_modules/jose/dist/webapi/jwt/sign.js +8 -41
  42. package/node_modules/jose/dist/webapi/jwt/unsecured.js +21 -42
  43. package/node_modules/jose/dist/webapi/key/generate_key_pair.js +6 -2
  44. package/node_modules/jose/dist/webapi/key/generate_secret.js +7 -6
  45. package/node_modules/jose/dist/webapi/key/import.js +16 -12
  46. package/node_modules/jose/dist/webapi/lib/asn1.js +7 -2
  47. package/node_modules/jose/dist/webapi/lib/content_encryption.js +7 -15
  48. package/node_modules/jose/dist/webapi/lib/deflate.js +8 -0
  49. package/node_modules/jose/dist/webapi/lib/helpers.js +1 -1
  50. package/node_modules/jose/dist/webapi/lib/jwe_decrypt.js +85 -28
  51. package/node_modules/jose/dist/webapi/lib/jwe_encrypt.js +40 -12
  52. package/node_modules/jose/dist/webapi/lib/jwk_metadata.js +20 -0
  53. package/node_modules/jose/dist/webapi/lib/jws_sign.js +47 -36
  54. package/node_modules/jose/dist/webapi/lib/jws_verify.js +77 -45
  55. package/node_modules/jose/dist/webapi/lib/jwt_claims_set.js +82 -47
  56. package/node_modules/jose/dist/webapi/lib/key.js +24 -9
  57. package/node_modules/jose/dist/webapi/lib/key_management.js +10 -4
  58. package/node_modules/jose/dist/webapi/lib/key_options.js +6 -0
  59. package/node_modules/jose/dist/webapi/lib/options.js +26 -0
  60. package/node_modules/jose/dist/webapi/lib/type_checks.js +11 -13
  61. package/node_modules/jose/package.json +1 -1
  62. package/package.json +1 -1
@@ -1,41 +1,71 @@
1
- import { prepareVerify, verifySignature, verifyResult } from '../../lib/jws_verify.js';
1
+ import { encodeJsonUnencodedPayload, parseProtectedHeader, prepareVerify, snapshotJws, verifySignature, verifyResult, } from '../../lib/jws_verify.js';
2
2
  import { JWSInvalid, JWSSignatureVerificationFailed } from '../../util/errors.js';
3
3
  import { isObject } from '../../lib/type_checks.js';
4
+ function snapshotSignature(signature, payload) {
5
+ try {
6
+ const jws = snapshotJws(signature, [payload]);
7
+ const { protected: encodedProtected, header, signature: encodedSignature } = jws;
8
+ if (encodedProtected === undefined && header === undefined)
9
+ return undefined;
10
+ if (encodedProtected !== undefined && typeof encodedProtected !== 'string')
11
+ return undefined;
12
+ if (typeof encodedSignature !== 'string')
13
+ return undefined;
14
+ if (header !== undefined && !isObject(header))
15
+ return undefined;
16
+ const protectedHeader = parseProtectedHeader(encodedProtected);
17
+ const { b64, crit } = protectedHeader;
18
+ return [
19
+ jws,
20
+ protectedHeader,
21
+ Array.isArray(crit) && crit.includes('b64')
22
+ ? typeof b64 === 'boolean'
23
+ ? b64
24
+ ? 1
25
+ : 2
26
+ : 0
27
+ : 1,
28
+ ];
29
+ }
30
+ catch {
31
+ return undefined;
32
+ }
33
+ }
4
34
  export async function generalVerify(jws, key, options) {
5
35
  if (!isObject(jws)) {
6
36
  throw new JWSInvalid('General JWS must be an object');
7
37
  }
8
- const { signatures, payload } = jws;
9
- if (!Array.isArray(signatures) || !signatures.every(isObject)) {
38
+ const { signatures, payload: inputPayload } = jws;
39
+ if (!Array.isArray(signatures)) {
40
+ throw new JWSInvalid('JWS Signatures missing or incorrect type');
41
+ }
42
+ const signatureEntries = Array.from(signatures);
43
+ if (!signatureEntries.every(isObject)) {
10
44
  throw new JWSInvalid('JWS Signatures missing or incorrect type');
11
45
  }
12
46
  let shared;
13
47
  try {
14
- if (payload === undefined)
48
+ if (inputPayload === undefined)
15
49
  throw new Error();
16
50
  shared = prepareVerify(options);
17
51
  }
18
52
  catch {
19
53
  throw new JWSSignatureVerificationFailed();
20
54
  }
21
- for (const signature of signatures) {
55
+ const payload = inputPayload instanceof Uint8Array ? new Uint8Array(inputPayload) : inputPayload;
56
+ const candidates = signatureEntries
57
+ .map((signature) => snapshotSignature(signature, payload))
58
+ .filter((candidate) => candidate !== undefined);
59
+ let modes = 0;
60
+ for (const [, , mode] of candidates) {
61
+ modes |= mode;
62
+ if (modes === 3) {
63
+ throw new JWSInvalid('inconsistent use of JWS Unencoded Payload (RFC7797)');
64
+ }
65
+ }
66
+ for (const candidate of candidates) {
22
67
  try {
23
- const { protected: encodedProtected, header, signature: encodedSignature } = signature;
24
- if (encodedProtected === undefined && header === undefined)
25
- throw new Error();
26
- if (encodedProtected !== undefined && typeof encodedProtected !== 'string') {
27
- throw new Error();
28
- }
29
- if (typeof encodedSignature !== 'string')
30
- throw new Error();
31
- if (header !== undefined && !isObject(header))
32
- throw new Error();
33
- return verifyResult(signature, await verifySignature({
34
- header,
35
- payload,
36
- protected: encodedProtected,
37
- signature: encodedSignature,
38
- }, shared, key));
68
+ return verifyResult(candidate[0], await verifySignature(candidate[0], shared, key, encodeJsonUnencodedPayload, candidate[1]));
39
69
  }
40
70
  catch {
41
71
  }
@@ -5,15 +5,13 @@ export async function jwtDecrypt(jwt, key, options) {
5
5
  const decrypted = await decryptCompact(jwt, prepareDecrypt(options), key);
6
6
  const protectedHeader = decrypted[1];
7
7
  const payload = validateClaimsSet(protectedHeader, decrypted[0], options);
8
- if (protectedHeader.iss !== undefined && protectedHeader.iss !== payload.iss) {
9
- throw new JWTClaimValidationFailed('replicated "iss" claim header parameter mismatch', payload, 'iss', 'mismatch');
10
- }
11
- if (protectedHeader.sub !== undefined && protectedHeader.sub !== payload.sub) {
12
- throw new JWTClaimValidationFailed('replicated "sub" claim header parameter mismatch', payload, 'sub', 'mismatch');
13
- }
14
- if (protectedHeader.aud !== undefined &&
15
- JSON.stringify(protectedHeader.aud) !== JSON.stringify(payload.aud)) {
16
- throw new JWTClaimValidationFailed('replicated "aud" claim header parameter mismatch', payload, 'aud', 'mismatch');
8
+ for (const claim of ['iss', 'sub', 'aud']) {
9
+ if (protectedHeader[claim] !== undefined &&
10
+ (claim === 'aud'
11
+ ? JSON.stringify(protectedHeader.aud) !== JSON.stringify(payload.aud)
12
+ : protectedHeader[claim] !== payload[claim])) {
13
+ throw new JWTClaimValidationFailed(`replicated "${claim}" claim header parameter mismatch`, payload, claim, 'mismatch');
14
+ }
17
15
  }
18
16
  const result = { payload, protectedHeader };
19
17
  if (typeof key === 'function') {
@@ -1,7 +1,8 @@
1
- import { CompactEncrypt } from '../jwe/compact/encrypt.js';
2
- import { JWTClaimsBuilder } from '../lib/jwt_claims_set.js';
1
+ import { createJWE } from '../lib/jwe_encrypt.js';
2
+ import { JWTClaimsBuilder, jwtClaim, jwtData } from '../lib/jwt_claims_set.js';
3
3
  import { assertNotSet } from '../lib/helpers.js';
4
- export class EncryptJWT {
4
+ const EncryptJWT_base = JWTClaimsBuilder;
5
+ export class EncryptJWT extends EncryptJWT_base {
5
6
  #cek;
6
7
  #iv;
7
8
  #keyManagementParameters;
@@ -9,38 +10,6 @@ export class EncryptJWT {
9
10
  #replicateIssuerAsHeader;
10
11
  #replicateSubjectAsHeader;
11
12
  #replicateAudienceAsHeader;
12
- #jwt;
13
- constructor(payload = {}) {
14
- this.#jwt = new JWTClaimsBuilder(payload);
15
- }
16
- setIssuer(issuer) {
17
- this.#jwt.iss = issuer;
18
- return this;
19
- }
20
- setSubject(subject) {
21
- this.#jwt.sub = subject;
22
- return this;
23
- }
24
- setAudience(audience) {
25
- this.#jwt.aud = audience;
26
- return this;
27
- }
28
- setJti(jwtId) {
29
- this.#jwt.jti = jwtId;
30
- return this;
31
- }
32
- setNotBefore(input) {
33
- this.#jwt.nbf = input;
34
- return this;
35
- }
36
- setExpirationTime(input) {
37
- this.#jwt.exp = input;
38
- return this;
39
- }
40
- setIssuedAt(input) {
41
- this.#jwt.iat = input;
42
- return this;
43
- }
44
13
  setProtectedHeader(protectedHeader) {
45
14
  assertNotSet(this.#protectedHeader, 'setProtectedHeader');
46
15
  this.#protectedHeader = protectedHeader;
@@ -74,28 +43,30 @@ export class EncryptJWT {
74
43
  return this;
75
44
  }
76
45
  async encrypt(key, options) {
77
- const enc = new CompactEncrypt(this.#jwt.data());
46
+ const plaintext = jwtData(this);
78
47
  if (this.#protectedHeader &&
79
48
  (this.#replicateIssuerAsHeader ||
80
49
  this.#replicateSubjectAsHeader ||
81
50
  this.#replicateAudienceAsHeader)) {
82
51
  this.#protectedHeader = {
83
52
  ...this.#protectedHeader,
84
- iss: this.#replicateIssuerAsHeader ? this.#jwt.iss : undefined,
85
- sub: this.#replicateSubjectAsHeader ? this.#jwt.sub : undefined,
86
- aud: this.#replicateAudienceAsHeader ? this.#jwt.aud : undefined,
53
+ iss: this.#replicateIssuerAsHeader ? jwtClaim(this, 'iss') : undefined,
54
+ sub: this.#replicateSubjectAsHeader ? jwtClaim(this, 'sub') : undefined,
55
+ aud: this.#replicateAudienceAsHeader ? jwtClaim(this, 'aud') : undefined,
87
56
  };
88
57
  }
89
- enc.setProtectedHeader(this.#protectedHeader);
90
- if (this.#iv) {
91
- enc.setInitializationVector(this.#iv);
92
- }
93
- if (this.#cek) {
94
- enc.setContentEncryptionKey(this.#cek);
95
- }
96
- if (this.#keyManagementParameters) {
97
- enc.setKeyManagementParameters(this.#keyManagementParameters);
98
- }
99
- return enc.encrypt(key, options);
58
+ const jwe = await createJWE([
59
+ plaintext,
60
+ this.#protectedHeader,
61
+ undefined,
62
+ undefined,
63
+ undefined,
64
+ this.#cek,
65
+ this.#iv,
66
+ this.#keyManagementParameters,
67
+ undefined,
68
+ false,
69
+ ], key, options);
70
+ return [jwe.protected, jwe.encrypted_key, jwe.iv, jwe.ciphertext, jwe.tag].join('.');
100
71
  }
101
72
  }
@@ -1,51 +1,18 @@
1
- import { CompactSign } from '../jws/compact/sign.js';
2
- import { unencodedPayload } from '../lib/jws_sign.js';
1
+ import { createCompactSignature } from '../lib/jws_sign.js';
3
2
  import { JWTInvalid } from '../util/errors.js';
4
- import { JWTClaimsBuilder } from '../lib/jwt_claims_set.js';
5
- export class SignJWT {
3
+ import { JWTClaimsBuilder, jwtData } from '../lib/jwt_claims_set.js';
4
+ import { assertNotSet } from '../lib/helpers.js';
5
+ const SignJWT_base = JWTClaimsBuilder;
6
+ export class SignJWT extends SignJWT_base {
6
7
  #protectedHeader;
7
- #jwt;
8
- constructor(payload = {}) {
9
- this.#jwt = new JWTClaimsBuilder(payload);
10
- }
11
- setIssuer(issuer) {
12
- this.#jwt.iss = issuer;
13
- return this;
14
- }
15
- setSubject(subject) {
16
- this.#jwt.sub = subject;
17
- return this;
18
- }
19
- setAudience(audience) {
20
- this.#jwt.aud = audience;
21
- return this;
22
- }
23
- setJti(jwtId) {
24
- this.#jwt.jti = jwtId;
25
- return this;
26
- }
27
- setNotBefore(input) {
28
- this.#jwt.nbf = input;
29
- return this;
30
- }
31
- setExpirationTime(input) {
32
- this.#jwt.exp = input;
33
- return this;
34
- }
35
- setIssuedAt(input) {
36
- this.#jwt.iat = input;
37
- return this;
38
- }
39
8
  setProtectedHeader(protectedHeader) {
9
+ assertNotSet(this.#protectedHeader, 'setProtectedHeader');
40
10
  this.#protectedHeader = protectedHeader;
41
11
  return this;
42
12
  }
43
13
  async sign(key, options) {
44
- const sig = new CompactSign(this.#jwt.data());
45
- sig.setProtectedHeader(this.#protectedHeader);
46
- if (unencodedPayload(this.#protectedHeader)) {
14
+ return createCompactSignature(jwtData(this), this.#protectedHeader, options?.crit, key, () => {
47
15
  throw new JWTInvalid('JWTs MUST NOT use unencoded payload');
48
- }
49
- return sig.sign(key, options);
16
+ });
50
17
  }
51
18
  }
@@ -1,46 +1,15 @@
1
1
  import * as b64u from '../util/base64url.js';
2
- import { strictDecoder } from '../lib/buffer_utils.js';
3
- import { decodeBase64url } from '../lib/helpers.js';
4
- import { JWTInvalid } from '../util/errors.js';
5
- import { validateClaimsSet, JWTClaimsBuilder } from '../lib/jwt_claims_set.js';
6
- export class UnsecuredJWT {
7
- #jwt;
8
- constructor(payload = {}) {
9
- this.#jwt = new JWTClaimsBuilder(payload);
10
- }
2
+ import { decodeBase64url, parseJoseHeader } from '../lib/helpers.js';
3
+ import { JWSInvalid, JWTInvalid } from '../util/errors.js';
4
+ import { validateClaimsSet, JWTClaimsBuilder, jwtData } from '../lib/jwt_claims_set.js';
5
+ import { JWS_RECOGNIZED, validateB64, validateCrit } from '../lib/options.js';
6
+ const UnsecuredJWT_base = JWTClaimsBuilder;
7
+ export class UnsecuredJWT extends UnsecuredJWT_base {
11
8
  encode() {
12
9
  const header = b64u.encode(JSON.stringify({ alg: 'none' }));
13
- const payload = b64u.encode(this.#jwt.data());
10
+ const payload = b64u.encode(jwtData(this));
14
11
  return `${header}.${payload}.`;
15
12
  }
16
- setIssuer(issuer) {
17
- this.#jwt.iss = issuer;
18
- return this;
19
- }
20
- setSubject(subject) {
21
- this.#jwt.sub = subject;
22
- return this;
23
- }
24
- setAudience(audience) {
25
- this.#jwt.aud = audience;
26
- return this;
27
- }
28
- setJti(jwtId) {
29
- this.#jwt.jti = jwtId;
30
- return this;
31
- }
32
- setNotBefore(input) {
33
- this.#jwt.nbf = input;
34
- return this;
35
- }
36
- setExpirationTime(input) {
37
- this.#jwt.exp = input;
38
- return this;
39
- }
40
- setIssuedAt(input) {
41
- this.#jwt.iat = input;
42
- return this;
43
- }
44
13
  static decode(jwt, options) {
45
14
  if (typeof jwt !== 'string') {
46
15
  throw new JWTInvalid('Unsecured JWT must be a string');
@@ -50,14 +19,24 @@ export class UnsecuredJWT {
50
19
  throw new JWTInvalid('Invalid Unsecured JWT');
51
20
  }
52
21
  let header;
22
+ let b64;
53
23
  try {
54
- header = JSON.parse(strictDecoder.decode(b64u.decode(encodedHeader)));
55
- if (header.alg !== 'none')
56
- throw new Error();
24
+ header = parseJoseHeader(encodedHeader, JWSInvalid, 'JWS Protected Header is invalid');
25
+ const extensions = validateCrit(JWSInvalid, JWS_RECOGNIZED, undefined, header, header);
26
+ b64 = validateB64(header, extensions);
57
27
  }
58
- catch {
28
+ catch (cause) {
29
+ if (!(cause instanceof JWSInvalid)) {
30
+ throw cause;
31
+ }
32
+ throw new JWTInvalid('Invalid Unsecured JWT', { cause });
33
+ }
34
+ if (header.alg !== 'none') {
59
35
  throw new JWTInvalid('Invalid Unsecured JWT');
60
36
  }
37
+ if (!b64) {
38
+ throw new JWTInvalid('JWTs MUST NOT use unencoded payload');
39
+ }
61
40
  const payload = validateClaimsSet(header, decodeBase64url(encodedPayload, 'payload', JWTInvalid), options);
62
41
  return { payload, header };
63
42
  }
@@ -1,13 +1,17 @@
1
1
  import { JOSENotSupported } from '../util/errors.js';
2
+ import { validateExtractableOption } from '../lib/key_options.js';
2
3
  import { keyAlgorithm, unsupportedAlg, algArgument } from '../lib/key_algorithm.js';
3
4
  function getModulusLengthOption(options) {
4
5
  const modulusLength = options?.modulusLength ?? 2048;
5
- if (typeof modulusLength !== 'number' || modulusLength < 2048) {
6
+ if (typeof modulusLength !== 'number' ||
7
+ !Number.isInteger(modulusLength) ||
8
+ modulusLength < 2048) {
6
9
  throw new JOSENotSupported('Invalid or unsupported modulusLength option provided, 2048 bits or larger keys must be used');
7
10
  }
8
11
  return modulusLength;
9
12
  }
10
13
  export async function generateKeyPair(alg, options) {
14
+ const extractable = validateExtractableOption(options?.extractable);
11
15
  const entry = keyAlgorithm(alg, algArgument);
12
16
  if (entry.secret) {
13
17
  unsupportedAlg(algArgument);
@@ -41,7 +45,7 @@ export async function generateKeyPair(alg, options) {
41
45
  }
42
46
  : entry.subtle;
43
47
  }
44
- return crypto.subtle.generateKey(algorithm, options?.extractable ?? false, [
48
+ return crypto.subtle.generateKey(algorithm, extractable ?? false, [
45
49
  ...entry.usages[1],
46
50
  ...entry.usages[0],
47
51
  ]);
@@ -1,5 +1,7 @@
1
1
  import { unsupportedAlg, algArgument } from '../lib/key_algorithm.js';
2
+ import { validateExtractableOption } from '../lib/key_options.js';
2
3
  export async function generateSecret(alg, options) {
4
+ const extractable = validateExtractableOption(options?.extractable);
3
5
  let length;
4
6
  let algorithm;
5
7
  let keyUsages;
@@ -7,19 +9,18 @@ export async function generateSecret(alg, options) {
7
9
  case 'HS256':
8
10
  case 'HS384':
9
11
  case 'HS512':
10
- length = parseInt(alg.slice(-3), 10);
12
+ length = +alg.slice(-3);
11
13
  algorithm = { name: 'HMAC', hash: `SHA-${length}`, length };
12
14
  keyUsages = ['sign', 'verify'];
13
15
  break;
14
16
  case 'A128CBC-HS256':
15
17
  case 'A192CBC-HS384':
16
18
  case 'A256CBC-HS512':
17
- length = parseInt(alg.slice(-3), 10);
18
- return crypto.getRandomValues(new Uint8Array(length >> 3));
19
+ return crypto.getRandomValues(new Uint8Array(+alg.slice(-3) >> 3));
19
20
  case 'A128KW':
20
21
  case 'A192KW':
21
22
  case 'A256KW':
22
- length = parseInt(alg.slice(1, 4), 10);
23
+ length = +alg.slice(1, 4);
23
24
  algorithm = { name: 'AES-KW', length };
24
25
  keyUsages = ['wrapKey', 'unwrapKey'];
25
26
  break;
@@ -29,12 +30,12 @@ export async function generateSecret(alg, options) {
29
30
  case 'A128GCM':
30
31
  case 'A192GCM':
31
32
  case 'A256GCM':
32
- length = parseInt(alg.slice(1, 4), 10);
33
+ length = +alg.slice(1, 4);
33
34
  algorithm = { name: 'AES-GCM', length };
34
35
  keyUsages = ['encrypt', 'decrypt'];
35
36
  break;
36
37
  default:
37
38
  unsupportedAlg(algArgument);
38
39
  }
39
- return crypto.subtle.generateKey(algorithm, options?.extractable ?? false, keyUsages);
40
+ return crypto.subtle.generateKey(algorithm, extractable ?? false, keyUsages);
40
41
  }
@@ -4,6 +4,8 @@ import { jwkToKey } from '../lib/jwk_to_key.js';
4
4
  import { keyAlgorithm } from '../lib/key_algorithm.js';
5
5
  import { JOSENotSupported } from '../util/errors.js';
6
6
  import { isObject } from '../lib/type_checks.js';
7
+ import { validateExtractableOption } from '../lib/key_options.js';
8
+ import { normalizeJwk } from '../lib/jwk_metadata.js';
7
9
  export async function importSPKI(spki, alg, options) {
8
10
  if (typeof spki !== 'string' || spki.indexOf('-----BEGIN PUBLIC KEY-----') !== 0) {
9
11
  throw new TypeError('"spki" must be SPKI formatted string');
@@ -26,31 +28,33 @@ export async function importJWK(jwk, alg, options) {
26
28
  if (!isObject(jwk)) {
27
29
  throw new TypeError('JWK must be an object');
28
30
  }
29
- alg ??= jwk.alg;
30
- const ext = options?.extractable ?? jwk.ext;
31
- if (jwk.kty !== 'oct' && !alg) {
31
+ const normalized = normalizeJwk(jwk);
32
+ const extractable = validateExtractableOption(options?.extractable);
33
+ const { alg: jwkAlg } = normalized;
34
+ alg ??= jwkAlg;
35
+ const ext = extractable ?? normalized.ext;
36
+ if (normalized.kty !== 'oct' && !alg) {
32
37
  throw new TypeError('"alg" argument is required when "jwk.alg" is not present');
33
38
  }
34
- switch (jwk.kty) {
39
+ switch (normalized.kty) {
35
40
  case 'oct':
36
- if (typeof jwk.k !== 'string' || !jwk.k) {
41
+ if (typeof normalized.k !== 'string') {
37
42
  throw new TypeError('missing "k" (Key Value) Parameter value');
38
43
  }
39
- return decodeBase64URL(jwk.k);
40
- case 'RSA':
41
- return jwkToKey(keyAlgorithm(alg), { ...jwk, alg, ext });
44
+ return decodeBase64URL(normalized.k);
42
45
  case 'AKP': {
43
- if (typeof jwk.alg !== 'string' || !jwk.alg) {
46
+ if (typeof jwkAlg !== 'string' || !jwkAlg) {
44
47
  throw new TypeError('missing "alg" (Algorithm) Parameter value');
45
48
  }
46
- if (alg !== undefined && alg !== jwk.alg) {
49
+ if (alg !== jwkAlg) {
47
50
  throw new TypeError('JWK alg and alg option value mismatch');
48
51
  }
49
- return jwkToKey(keyAlgorithm(jwk.alg), { ...jwk, ext });
52
+ return jwkToKey(keyAlgorithm(alg), { ...normalized, ext });
50
53
  }
54
+ case 'RSA':
51
55
  case 'EC':
52
56
  case 'OKP':
53
- return jwkToKey(keyAlgorithm(alg), { ...jwk, alg, ext });
57
+ return jwkToKey(keyAlgorithm(alg), { ...normalized, alg, ext });
54
58
  default:
55
59
  throw new JOSENotSupported('Unsupported "kty" (Key Type) Parameter value');
56
60
  }
@@ -3,6 +3,7 @@ import { encodeBase64, decodeBase64 } from '../lib/base64.js';
3
3
  import { JOSENotSupported } from '../util/errors.js';
4
4
  import { keyAlgorithm, unsupportedAlg, algArgument } from './key_algorithm.js';
5
5
  import { isCryptoKey, isKeyObject } from './is_key_like.js';
6
+ import { validateExtractableOption } from './key_options.js';
6
7
  const formatPEM = (b64, descriptor) => {
7
8
  const newlined = (b64.match(/.{1,64}/g) || []).join('\n');
8
9
  return `-----BEGIN ${descriptor}-----\n${newlined}\n-----END ${descriptor}-----`;
@@ -112,6 +113,7 @@ const parseECAlgorithmIdentifier = (state) => {
112
113
  throw new Error('Unsupported named curve');
113
114
  };
114
115
  const genericImport = async (keyFormat, keyData, alg, options) => {
116
+ const extractable = validateExtractableOption(options?.extractable);
115
117
  const entry = keyAlgorithm(alg, algArgument);
116
118
  if (entry.secret) {
117
119
  unsupportedAlg(algArgument);
@@ -131,7 +133,7 @@ const genericImport = async (keyFormat, keyData, alg, options) => {
131
133
  else {
132
134
  algorithm = entry.subtle;
133
135
  }
134
- return crypto.subtle.importKey(keyFormat, keyData, algorithm, options?.extractable ?? isPublic, entry.usages[isPublic ? 0 : 1]);
136
+ return crypto.subtle.importKey(keyFormat, keyData, algorithm, extractable ?? isPublic, entry.usages[isPublic ? 0 : 1]);
135
137
  };
136
138
  const processPEMData = (pem, pattern) => {
137
139
  return decodeBase64(pem.replace(pattern, ''));
@@ -147,7 +149,10 @@ export const fromSPKI = (pem, alg, options) => {
147
149
  function spkiFromX509(buf) {
148
150
  const state = createASN1State(buf);
149
151
  expectTag(state, 0x30, 'Invalid certificate structure');
150
- parseLength(state);
152
+ const certificateLength = parseLength(state);
153
+ if (certificateLength < 0 || state.pos + certificateLength > state.data.length) {
154
+ throw new Error('Unexpected end of ASN.1 input');
155
+ }
151
156
  expectTag(state, 0x30, 'Invalid tbsCertificate structure');
152
157
  parseLength(state);
153
158
  if (buf[state.pos] === 0xa0) {
@@ -51,25 +51,14 @@ async function cbcDecrypt(enc, cek, ciphertext, iv, tag, aad) {
51
51
  const [encKey, macKey, keySize] = await cbcKeySetup(enc, cek, 'decrypt');
52
52
  const macData = concat(aad, iv, ciphertext, uint64be(aad.length * 8));
53
53
  const expectedTag = await cbcHmacTag(macKey, macData, keySize);
54
- let macCheckPassed;
55
54
  try {
56
- macCheckPassed = await timingSafeEqual(tag, expectedTag);
55
+ if (await timingSafeEqual(tag, expectedTag)) {
56
+ return new Uint8Array(await crypto.subtle.decrypt({ iv: iv, name: 'AES-CBC' }, encKey, ciphertext));
57
+ }
57
58
  }
58
59
  catch {
59
60
  }
60
- if (!macCheckPassed) {
61
- throw new JWEDecryptionFailed();
62
- }
63
- let plaintext;
64
- try {
65
- plaintext = new Uint8Array(await crypto.subtle.decrypt({ iv: iv, name: 'AES-CBC' }, encKey, ciphertext));
66
- }
67
- catch {
68
- }
69
- if (!plaintext) {
70
- throw new JWEDecryptionFailed();
71
- }
72
- return plaintext;
61
+ throw new JWEDecryptionFailed();
73
62
  }
74
63
  async function gcmEncrypt(enc, plaintext, cek, iv, aad) {
75
64
  const encKey = cek instanceof Uint8Array
@@ -132,6 +121,9 @@ export async function decrypt(enc, cek, ciphertext, iv, tag, aad) {
132
121
  if (!tag) {
133
122
  throw new JWEInvalid('JWE Authentication Tag missing');
134
123
  }
124
+ if (!enc.cbc && tag.length !== 16) {
125
+ throw new JWEInvalid('Invalid Authentication Tag length');
126
+ }
135
127
  checkIvLength(enc, iv);
136
128
  if (cek instanceof Uint8Array) {
137
129
  checkCekLength(cek, enc.cekBits);
@@ -1,5 +1,13 @@
1
1
  import { JOSENotSupported, JWEInvalid } from '../util/errors.js';
2
2
  import { concat } from './buffer_utils.js';
3
+ export function validateZip(joseHeader, protectedHeader) {
4
+ if (joseHeader.zip !== undefined && joseHeader.zip !== 'DEF') {
5
+ throw new JOSENotSupported('Unsupported JWE "zip" (Compression Algorithm) Header Parameter value.');
6
+ }
7
+ if (joseHeader.zip !== undefined && !protectedHeader?.zip) {
8
+ throw new JWEInvalid('JWE "zip" (Compression Algorithm) Header Parameter MUST be in a protected header.');
9
+ }
10
+ }
3
11
  function supported(name) {
4
12
  if (typeof globalThis[name] === 'undefined') {
5
13
  throw new JOSENotSupported(`JWE "zip" (Compression Algorithm) Header Parameter requires the ${name} API.`);
@@ -3,7 +3,7 @@ import { encode, strictDecoder } from './buffer_utils.js';
3
3
  import { isObject } from './type_checks.js';
4
4
  export const unprotected = Symbol();
5
5
  export function assertNotSet(value, name) {
6
- if (value) {
6
+ if (value !== undefined) {
7
7
  throw new TypeError(`${name} can only be called once`);
8
8
  }
9
9
  }