micro509 0.17.1 → 0.18.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 (126) hide show
  1. package/CHANGELOG.md +78 -6
  2. package/dist/crypto/crypto.d.ts +2 -3
  3. package/dist/crypto.d.ts +6 -0
  4. package/dist/der/der.d.ts +14 -4
  5. package/dist/der/der.js +19 -19
  6. package/dist/der.d.ts +26 -2
  7. package/dist/der.js +4 -4
  8. package/dist/index.d.ts +82 -15
  9. package/dist/index.js +19 -19
  10. package/dist/internal/asn1/asn1.d.ts +1 -2
  11. package/dist/internal/asn1/der.d.ts +1 -2
  12. package/dist/internal/asn1/oids.js +71 -353
  13. package/dist/internal/asn1/oids.js.map +1 -1
  14. package/dist/internal/asn1/oids.json.js +357 -0
  15. package/dist/internal/asn1/oids.json.js.map +1 -0
  16. package/dist/internal/crypto/algorithm-names.js +1 -1
  17. package/dist/internal/crypto/pbes2.d.ts +1 -2
  18. package/dist/internal/crypto/pbes2.js +70 -70
  19. package/dist/internal/crypto/prime-ec.js +37 -0
  20. package/dist/internal/crypto/prime-ec.js.map +1 -0
  21. package/dist/internal/crypto/rsa-pss.js +50 -50
  22. package/dist/internal/crypto/sig-verify.d.ts +1 -2
  23. package/dist/internal/crypto/sig-verify.js +60 -60
  24. package/dist/internal/crypto/signing.d.ts +1 -2
  25. package/dist/internal/crypto/signing.js +26 -26
  26. package/dist/internal/jose/json-data.js +108 -0
  27. package/dist/internal/jose/json-data.js.map +1 -0
  28. package/dist/internal/jose/strict-json.d.ts +1 -2
  29. package/dist/internal/shared/dn.d.ts +1 -2
  30. package/dist/internal/shared/dn.js +1 -1
  31. package/dist/internal/shared/ip.d.ts +1 -2
  32. package/dist/internal/verify/name-constraints-engine.js +64 -64
  33. package/dist/internal/verify/policy-engine.js +1 -1
  34. package/dist/internal/verify/verify-path.d.ts +1 -2
  35. package/dist/internal/verify/verify-path.js +19 -19
  36. package/dist/internal/x509/directory-name.js +10 -10
  37. package/dist/internal/x509/extension-errors.d.ts +1 -2
  38. package/dist/internal/x509/extension-registry.js +18 -18
  39. package/dist/internal/x509/general-name-profile.js +9 -9
  40. package/dist/internal/x509/general-name.js +32 -32
  41. package/dist/internal/x509/name-fields.js +1 -1
  42. package/dist/jose/base64url.d.ts +4 -0
  43. package/dist/jose/base64url.js +14 -0
  44. package/dist/jose/base64url.js.map +1 -0
  45. package/dist/jose/errors.d.ts +9 -3
  46. package/dist/jose/errors.js.map +1 -1
  47. package/dist/jose/jwe.d.ts +64 -0
  48. package/dist/jose/jwe.js +188 -0
  49. package/dist/jose/jwe.js.map +1 -0
  50. package/dist/jose/jwks.d.ts +38 -10
  51. package/dist/jose/jwks.js +156 -96
  52. package/dist/jose/jwks.js.map +1 -1
  53. package/dist/jose/jws.d.ts +8 -6
  54. package/dist/jose/jws.js +216 -170
  55. package/dist/jose/jws.js.map +1 -1
  56. package/dist/jose/jwt.d.ts +8 -2
  57. package/dist/jose/jwt.js +98 -98
  58. package/dist/jose/remote-jwks.d.ts +1 -2
  59. package/dist/jose/remote-jwks.js +106 -108
  60. package/dist/jose/remote-jwks.js.map +1 -1
  61. package/dist/jose.d.ts +15 -4
  62. package/dist/jose.js +7 -5
  63. package/dist/kdf/argon2.d.ts +7 -2
  64. package/dist/kdf.d.ts +6 -0
  65. package/dist/keys/keys.d.ts +31 -6
  66. package/dist/keys/keys.js +315 -233
  67. package/dist/keys/keys.js.map +1 -1
  68. package/dist/keys.d.ts +11 -2
  69. package/dist/keys.js +2 -2
  70. package/dist/pem/pem.d.ts +1 -2
  71. package/dist/pem/pem.js +40 -25
  72. package/dist/pem/pem.js.map +1 -1
  73. package/dist/pem.d.ts +6 -0
  74. package/dist/pkcs/pfx.d.ts +2 -3
  75. package/dist/pkcs/pfx.js +142 -142
  76. package/dist/pkcs/pkcs12-mac.d.ts +1 -2
  77. package/dist/pkcs/pkcs12-mac.js +122 -122
  78. package/dist/pkcs/pkcs7.d.ts +14 -3
  79. package/dist/pkcs/pkcs7.js +268 -248
  80. package/dist/pkcs/pkcs7.js.map +1 -1
  81. package/dist/pkcs.d.ts +10 -1
  82. package/dist/pkcs.js +4 -4
  83. package/dist/result/result.d.ts +1 -2
  84. package/dist/result.d.ts +6 -0
  85. package/dist/revocation/chain.d.ts +2 -3
  86. package/dist/revocation/chain.js +52 -52
  87. package/dist/revocation/crl.d.ts +2 -3
  88. package/dist/revocation/crl.js +319 -319
  89. package/dist/revocation/crl.js.map +1 -1
  90. package/dist/revocation/ocsp.d.ts +2 -3
  91. package/dist/revocation/ocsp.js +395 -395
  92. package/dist/revocation/revocation.d.ts +2 -3
  93. package/dist/revocation/revocation.js +22 -22
  94. package/dist/revocation.d.ts +12 -3
  95. package/dist/revocation.js +4 -4
  96. package/dist/ssh/ssh.d.ts +2 -3
  97. package/dist/ssh/ssh.js +165 -170
  98. package/dist/ssh/ssh.js.map +1 -1
  99. package/dist/ssh/wire.d.ts +1 -2
  100. package/dist/ssh/wire.js +10 -10
  101. package/dist/ssh.d.ts +8 -0
  102. package/dist/verify/identity.d.ts +1 -2
  103. package/dist/verify/identity.js +31 -31
  104. package/dist/verify/name-constraints.d.ts +9 -2
  105. package/dist/verify/policy.d.ts +9 -2
  106. package/dist/verify/verify.d.ts +3 -4
  107. package/dist/verify/verify.js +121 -121
  108. package/dist/verify.d.ts +9 -0
  109. package/dist/x509/certificate.d.ts +4 -5
  110. package/dist/x509/certificate.js +40 -40
  111. package/dist/x509/csr.d.ts +3 -4
  112. package/dist/x509/csr.js +15 -15
  113. package/dist/x509/extensions.d.ts +1 -2
  114. package/dist/x509/extensions.js +165 -165
  115. package/dist/x509/extensions.js.map +1 -1
  116. package/dist/x509/fingerprint.d.ts +1 -2
  117. package/dist/x509/name-text.d.ts +1 -2
  118. package/dist/x509/name.d.ts +1 -2
  119. package/dist/x509/name.js +15 -15
  120. package/dist/x509/parse.d.ts +3 -4
  121. package/dist/x509/parse.js +423 -423
  122. package/dist/x509.d.ts +17 -4
  123. package/dist/x509.js +8 -8
  124. package/package.json +22 -23
  125. package/dist/internal/asn1/oids2.js +0 -75
  126. package/dist/internal/asn1/oids2.js.map +0 -1
@@ -1,9 +1,9 @@
1
1
  import { DECODE_REFUSAL_CODES as e } from "../../result/result.js";
2
- import { rethrowDecodeRefusal as t } from "../asn1/decode-refusal.js";
3
- import { childrenOf as n, decodeObjectIdentifier as r, decodeString as i, toHex as a } from "../asn1/asn1.js";
4
- import { OIDS as o } from "../asn1/oids2.js";
5
- import { readDirectoryNameTlv as s } from "./directory-name.js";
6
- import { decodeIpAddress as c } from "../shared/ip.js";
2
+ import { childrenOf as t, decodeObjectIdentifier as n, decodeString as r, toHex as i } from "../asn1/asn1.js";
3
+ import { rethrowDecodeRefusal as a } from "../asn1/decode-refusal.js";
4
+ import { OIDS as o } from "../asn1/oids.js";
5
+ import { decodeIpAddress as s } from "../shared/ip.js";
6
+ import { readDirectoryNameTlv as c } from "./directory-name.js";
7
7
  // src/internal/x509/general-name.ts
8
8
  /**
9
9
  * The canonical RFC 5280 §4.2.1.6 GeneralName decoder, shared by certificate
@@ -13,8 +13,8 @@ import { decodeIpAddress as c } from "../shared/ip.js";
13
13
  * @module
14
14
  */
15
15
  /** Decode a SEQUENCE OF GeneralName. */
16
- function parseGeneralNames(e, t) {
17
- let r = n(e, t);
16
+ function parseGeneralNames(e, n) {
17
+ let r = t(e, n);
18
18
  if (r.length === 0) throw Error("GeneralNames must not be empty");
19
19
  for (let e of r) if ((e.tag & 192) != 128) throw Error("GeneralNames must contain GeneralName entries");
20
20
  return r.map((t) => parseGeneralName(e, t));
@@ -27,7 +27,7 @@ function parseGeneralNames(e, t) {
27
27
  */
28
28
  function requireNonEmptyIa5(e, t) {
29
29
  if (e.value.length === 0) throw Error(`GeneralName ${t} must not be empty`);
30
- return i(22, e.value);
30
+ return r(22, e.value);
31
31
  }
32
32
  /** Decode a single GeneralName from its implicit context tag. */
33
33
  function parseGeneralName(e, t) {
@@ -47,7 +47,7 @@ function parseGeneralName(e, t) {
47
47
  };
48
48
  case 135: return {
49
49
  type: "ip",
50
- value: c(t.value)
50
+ value: s(t.value)
51
51
  };
52
52
  case 163: return {
53
53
  type: "x400Address",
@@ -55,7 +55,7 @@ function parseGeneralName(e, t) {
55
55
  };
56
56
  case 164: return {
57
57
  type: "directoryName",
58
- derHex: a(s(t))
58
+ derHex: i(c(t))
59
59
  };
60
60
  case 165: return {
61
61
  type: "ediPartyName",
@@ -63,7 +63,7 @@ function parseGeneralName(e, t) {
63
63
  };
64
64
  case 136: return {
65
65
  type: "registeredID",
66
- value: r(t.value)
66
+ value: n(t.value)
67
67
  };
68
68
  default: throw Error(`Invalid GeneralName tag: ${t.tag}`);
69
69
  }
@@ -75,34 +75,34 @@ function parseGeneralName(e, t) {
75
75
  * replaces OtherName's SEQUENCE tag: the type-id and `value [0] EXPLICIT` are
76
76
  * the direct children, with no inner SEQUENCE.
77
77
  */
78
- function readOtherName(e, t) {
79
- let i = n(e, t), a = i[0], o = i[1];
78
+ function readOtherName(e, r) {
79
+ let i = t(e, r), a = i[0], o = i[1];
80
80
  if (i.length !== 2 || a === void 0 || o === void 0 || a.tag !== 6 || o.tag !== 160) throw Error("Malformed otherName");
81
- let s = n(e, o), c = s[0];
81
+ let s = t(e, o), c = s[0];
82
82
  if (s.length !== 1 || c === void 0) throw Error("otherName value [0] must wrap exactly one element");
83
83
  return {
84
- typeId: r(a.value),
84
+ typeId: n(a.value),
85
85
  value: c
86
86
  };
87
87
  }
88
88
  /** RFC 4985 §2: `SRVName ::= IA5String (SIZE (1..MAX))`. */
89
89
  function decodeSrvName(e) {
90
90
  if (e.tag !== 22 || e.value.length === 0) throw Error("SRV-ID otherName must wrap a non-empty IA5String");
91
- return i(e.tag, e.value);
91
+ return r(e.tag, e.value);
92
92
  }
93
93
  /** The DER of an otherName value element. */
94
94
  function otherNameValueDer(e, t) {
95
95
  return e.slice(t.start - t.headerLength, t.end);
96
96
  }
97
97
  /** [MS-WCCE] §2.2.2.7.5: a user principal name is a UTF8String. */
98
- function decodeUpn(n) {
99
- if (n.tag === 12 && n.value.length !== 0) try {
98
+ function decodeUpn(t) {
99
+ if (t.tag === 12 && t.value.length !== 0) try {
100
100
  return {
101
101
  type: "upn",
102
- value: i(n.tag, n.value)
102
+ value: r(t.tag, t.value)
103
103
  };
104
- } catch (n) {
105
- t(n, e);
104
+ } catch (t) {
105
+ a(t, e);
106
106
  return;
107
107
  }
108
108
  }
@@ -120,17 +120,17 @@ function decodeInt32(e) {
120
120
  if (!(t === void 0 || n === void 0 || t.length > 4 || r !== void 0 && (n === 0 && r < 128 || n === 255 && r >= 128))) return t.slice(1).reduce((e, t) => e * 256 + t, n >= 128 ? n - 256 : n);
121
121
  }
122
122
  /** The single element under an EXPLICIT context tag. */
123
- function explicitChild(e, t, r) {
124
- if (t?.tag !== r) return;
125
- let i = n(e, t);
123
+ function explicitChild(e, n, r) {
124
+ if (n?.tag !== r) return;
125
+ let i = t(e, n);
126
126
  return i.length === 1 ? i[0] : void 0;
127
127
  }
128
128
  /**
129
129
  * RFC 4556 §3.2.2 KRB5PrincipalName with RFC 4120's PrincipalName, Realm and
130
130
  * KerberosString, all EXPLICIT-tagged. A realm holds no NUL (RFC 4120 §5.2.2).
131
131
  */
132
- function decodeKrb5PrincipalName(e, t) {
133
- let r = t.tag === 48 ? n(e, t) : [], i = decodeKerberosString(explicitChild(e, r[0], 160)), a = explicitChild(e, r[1], 161), o = a?.tag === 48 ? n(e, a) : [], s = decodeInt32(explicitChild(e, o[0], 160)), c = explicitChild(e, o[1], 161), l = c?.tag === 48 ? n(e, c).map(decodeKerberosString) : [void 0];
132
+ function decodeKrb5PrincipalName(e, n) {
133
+ let r = n.tag === 48 ? t(e, n) : [], i = decodeKerberosString(explicitChild(e, r[0], 160)), a = explicitChild(e, r[1], 161), o = a?.tag === 48 ? t(e, a) : [], s = decodeInt32(explicitChild(e, o[0], 160)), c = explicitChild(e, o[1], 161), l = c?.tag === 48 ? t(e, c).map(decodeKerberosString) : [void 0];
134
134
  if (r.length !== 2 || o.length !== 2 || i === void 0 || i.includes("\0") || s === void 0) return;
135
135
  let u = l.filter((e) => e !== void 0);
136
136
  return u.length === l.length ? {
@@ -159,22 +159,22 @@ function typedOtherName(e, t, n) {
159
159
  * payload throws.
160
160
  */
161
161
  function parseOtherName(e, t) {
162
- let { typeId: n, value: r } = readOtherName(e, t);
162
+ let { typeId: n, value: i } = readOtherName(e, t);
163
163
  switch (n) {
164
164
  case o.idOnDnsSrv: return {
165
165
  type: "srv",
166
- value: decodeSrvName(r)
166
+ value: decodeSrvName(i)
167
167
  };
168
168
  case o.idOnSmtpUtf8Mailbox:
169
- if (r.tag !== 12 || r.value.length === 0) throw Error("SmtpUTF8Mailbox otherName must wrap a non-empty UTF8String");
169
+ if (i.tag !== 12 || i.value.length === 0) throw Error("SmtpUTF8Mailbox otherName must wrap a non-empty UTF8String");
170
170
  return {
171
171
  type: "smtpUtf8Mailbox",
172
- value: i(r.tag, r.value)
172
+ value: r(i.tag, i.value)
173
173
  };
174
- default: return typedOtherName(n, e, r) ?? {
174
+ default: return typedOtherName(n, e, i) ?? {
175
175
  type: "otherName",
176
176
  typeId: n,
177
- value: otherNameValueDer(e, r)
177
+ value: otherNameValueDer(e, i)
178
178
  };
179
179
  }
180
180
  }
@@ -1,5 +1,5 @@
1
1
  import { ia5String as e, printableString as t, utf8String as n } from "../asn1/der.js";
2
- import { OIDS as r } from "../asn1/oids2.js";
2
+ import { OIDS as r } from "../asn1/oids.js";
3
3
  // src/internal/x509/name-fields.ts
4
4
  /**
5
5
  * Distinguished-name field metadata.
@@ -0,0 +1,4 @@
1
+ /** Encodes bytes as canonical unpadded base64url; does not encode text. */
2
+ export declare function base64UrlEncode(bytes: Uint8Array): string;
3
+ /** Decodes canonical unpadded base64url, or returns `undefined` for invalid/noncanonical input. Empty input yields empty bytes. */
4
+ export declare function base64UrlDecode(value: string): Uint8Array | undefined;
@@ -0,0 +1,14 @@
1
+ import { base64UrlDecode as e, base64UrlEncode as t } from "../internal/jose/base64url.js";
2
+ // src/jose/base64url.ts
3
+ /** Public byte-oriented JOSE base64url codecs. @module */
4
+ /** Encodes bytes as canonical unpadded base64url; does not encode text. */
5
+ function base64UrlEncode(e) {
6
+ return t(e);
7
+ }
8
+ /** Decodes canonical unpadded base64url, or returns `undefined` for invalid/noncanonical input. Empty input yields empty bytes. */
9
+ function base64UrlDecode(t) {
10
+ return e(t);
11
+ }
12
+ export { base64UrlDecode, base64UrlEncode };
13
+
14
+ //# sourceMappingURL=base64url.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"base64url.js","names":["encode","decode","base64UrlDecode$1","base64UrlEncode$1","bytes","value"],"sources":["../../src/jose/base64url.ts"],"sourcesContent":["/** Public byte-oriented JOSE base64url codecs. @module */\nimport {\n\tbase64UrlDecode as decode,\n\tbase64UrlEncode as encode,\n} from '#micro509/internal/jose/base64url';\n\n/** Encodes bytes as canonical unpadded base64url; does not encode text. */\nexport function base64UrlEncode(bytes: Uint8Array): string {\n\treturn encode(bytes);\n}\n\n/** Decodes canonical unpadded base64url, or returns `undefined` for invalid/noncanonical input. Empty input yields empty bytes. */\nexport function base64UrlDecode(value: string): Uint8Array | undefined {\n\treturn decode(value);\n}\n"],"mappings":";;;;AAOA,SAAgB,gBAAgB,GAA2B;CAC1D,OAAOA,EAAOI,CAAK;AACpB;;AAGA,SAAgB,gBAAgB,GAAuC;CACtE,OAAOH,EAAOI,CAAK;AACpB"}
@@ -1,3 +1,8 @@
1
+ /**
2
+ * Typed failures shared by the JOSE parsing, verification and key-resolution APIs.
3
+ *
4
+ * @module
5
+ */
1
6
  import { ErrorResult, Micro509Error } from "../result/result.js";
2
7
  /** Reasons a compact serialization is refused before any signature is checked. */
3
8
  export type JwsParseErrorCode = "token_too_large" | "malformed_token" | "invalid_encoding" | "invalid_utf8" | "invalid_json" | "duplicate_member" | "limit_exceeded" | "invalid_header" | "unsupported_critical_header" | "unsupported_unencoded_payload" | "unsupported_nested_jwt" | "invalid_payload";
@@ -11,8 +16,10 @@ export type JwtClaimsErrorCode = "missing_claim" | "invalid_claim" | "issuer_mis
11
16
  export type VerifyJwsErrorCode = JwsParseErrorCode | KeyResolutionErrorCode | JwsPolicyErrorCode;
12
17
  /** Failure codes of {@linkcode verifyJwt}. */
13
18
  export type VerifyJwtErrorCode = VerifyJwsErrorCode | JwtClaimsErrorCode;
19
+ /** Failures for the compact JWE profile. */
20
+ export type JweErrorCode = "invalid_options" | "token_too_large" | "malformed_token" | "invalid_encoding" | "invalid_utf8" | "invalid_json" | "duplicate_member" | "limit_exceeded" | "invalid_header" | "algorithm_not_allowed" | "encryption_not_allowed" | "key_unsuitable" | "unsupported_critical_header" | "unsupported_compression" | "encryption_failed" | "decryption_failed";
14
21
  /** Every code a JOSE API reports. */
15
- export type JoseErrorCode = VerifyJwtErrorCode;
22
+ export type JoseErrorCode = VerifyJwtErrorCode | JweErrorCode;
16
23
  /**
17
24
  * Structured context for a failure. Holds names and short identifiers only, never token
18
25
  * segments, claim values or key material.
@@ -40,5 +47,4 @@ export type JoseErrorResult<TCode extends string = JoseErrorCode> = ErrorResult<
40
47
  export type JoseResult<TValue, TCode extends string = JoseErrorCode> = {
41
48
  readonly ok: true;
42
49
  readonly value: TValue;
43
- } | JoseErrorResult<TCode>;
44
- //# sourceMappingURL=errors.d.ts.map
50
+ } | JoseErrorResult<TCode>;
@@ -1 +1 @@
1
- {"version":3,"file":"errors.js","names":["failureResult","code","message","details"],"sources":["../../src/jose/errors.ts"],"sourcesContent":["/**\n * Typed failures shared by the JOSE parsing, verification and key-resolution APIs.\n *\n * @module\n */\n\nimport type { ErrorResult, Micro509Error } from '#micro509/result/result';\nimport { failureResult } from '#micro509/result/result';\n\n/** Longest `kid` echoed into {@linkcode JoseErrorDetails}. */\nconst MAX_REPORTED_KID_LENGTH = 64;\n\n/** Reasons a compact serialization is refused before any signature is checked. */\nexport type JwsParseErrorCode =\n\t| 'token_too_large'\n\t| 'malformed_token'\n\t| 'invalid_encoding'\n\t| 'invalid_utf8'\n\t| 'invalid_json'\n\t| 'duplicate_member'\n\t| 'limit_exceeded'\n\t| 'invalid_header'\n\t| 'unsupported_critical_header'\n\t| 'unsupported_unencoded_payload'\n\t| 'unsupported_nested_jwt'\n\t| 'invalid_payload';\n\n/** Reasons a signing key cannot be resolved for a token. */\nexport type KeyResolutionErrorCode =\n\t| 'key_not_found'\n\t| 'ambiguous_key'\n\t| 'key_unsuitable'\n\t| 'key_resolution_failed'\n\t| 'jwks_unavailable'\n\t| 'jwks_malformed'\n\t| 'aborted';\n\n/** Reasons a well-formed token is refused by the verification policy or its signature. */\nexport type JwsPolicyErrorCode =\n\t| 'invalid_options'\n\t| 'unsigned_token'\n\t| 'algorithm_not_allowed'\n\t| 'token_type_mismatch'\n\t| 'invalid_signature';\n\n/** Reasons a signature-verified token fails the claims policy. */\nexport type JwtClaimsErrorCode =\n\t| 'missing_claim'\n\t| 'invalid_claim'\n\t| 'issuer_mismatch'\n\t| 'audience_mismatch'\n\t| 'expired'\n\t| 'not_yet_valid'\n\t| 'issued_in_future'\n\t| 'token_too_old';\n\n/** Failure codes of {@linkcode verifyCompactJws}. */\nexport type VerifyJwsErrorCode = JwsParseErrorCode | KeyResolutionErrorCode | JwsPolicyErrorCode;\n\n/** Failure codes of {@linkcode verifyJwt}. */\nexport type VerifyJwtErrorCode = VerifyJwsErrorCode | JwtClaimsErrorCode;\n\n/** Every code a JOSE API reports. */\nexport type JoseErrorCode = VerifyJwtErrorCode;\n\n/**\n * Structured context for a failure. Holds names and short identifiers only, never token\n * segments, claim values or key material.\n */\nexport interface JoseErrorDetails {\n\t/** The `alg` header value the token carried. */\n\treadonly alg?: string;\n\t/** The `kid` header value the token carried, truncated to 64 characters. */\n\treadonly kid?: string;\n\t/** The claim name a claims failure concerns. */\n\treadonly claim?: string;\n\t/** The critical header names that were refused. */\n\treadonly crit?: readonly string[];\n\t/** The HTTP status a JWKS endpoint answered with. */\n\treadonly status?: number;\n}\n\n/** Failure payload of the JOSE APIs. */\nexport interface JoseFailure<TCode extends string = JoseErrorCode>\n\textends Micro509Error<TCode, JoseErrorDetails> {\n\t/** Always `false` for failures. */\n\treadonly ok: false;\n}\n\n/** A flattened failed result carrying a {@linkcode JoseFailure}. */\nexport type JoseErrorResult<TCode extends string = JoseErrorCode> = ErrorResult<\n\tTCode,\n\tJoseErrorDetails,\n\tJoseFailure<TCode>\n>;\n\n/** Success-or-failure result of a JOSE API. */\nexport type JoseResult<TValue, TCode extends string = JoseErrorCode> =\n\t| { readonly ok: true; readonly value: TValue }\n\t| JoseErrorResult<TCode>;\n\n/** Builds a failed result, truncating any reported `kid`. */\nexport function joseFailure<TCode extends JoseErrorCode>(\n\tcode: TCode,\n\tmessage: string,\n\tdetails?: JoseErrorDetails,\n): JoseErrorResult<TCode> {\n\treturn failureResult(\n\t\tcode,\n\t\tmessage,\n\t\tdetails?.kid === undefined\n\t\t\t? details\n\t\t\t: { ...details, kid: details.kid.slice(0, MAX_REPORTED_KID_LENGTH) },\n\t);\n}\n"],"mappings":";;AAsGA,SAAgB,YACf,GACA,GACA,GACyB;CACzB,OAAOA,EACNC,GACAC,GACAC,GAAS,QAAQ,KAAA,IACdA,IACA;EAAE,GAAGA;EAAS,KAAKA,EAAQ,IAAI,MAAM,GAAG,EAAuB;CAAE,CACrE;AACD"}
1
+ {"version":3,"file":"errors.js","names":["failureResult","code","message","details"],"sources":["../../src/jose/errors.ts"],"sourcesContent":["/**\n * Typed failures shared by the JOSE parsing, verification and key-resolution APIs.\n *\n * @module\n */\n\nimport type { ErrorResult, Micro509Error } from '#micro509/result/result';\nimport { failureResult } from '#micro509/result/result';\n\n/** Longest `kid` echoed into {@linkcode JoseErrorDetails}. */\nconst MAX_REPORTED_KID_LENGTH = 64;\n\n/** Reasons a compact serialization is refused before any signature is checked. */\nexport type JwsParseErrorCode =\n\t| 'token_too_large'\n\t| 'malformed_token'\n\t| 'invalid_encoding'\n\t| 'invalid_utf8'\n\t| 'invalid_json'\n\t| 'duplicate_member'\n\t| 'limit_exceeded'\n\t| 'invalid_header'\n\t| 'unsupported_critical_header'\n\t| 'unsupported_unencoded_payload'\n\t| 'unsupported_nested_jwt'\n\t| 'invalid_payload';\n\n/** Reasons a signing key cannot be resolved for a token. */\nexport type KeyResolutionErrorCode =\n\t| 'key_not_found'\n\t| 'ambiguous_key'\n\t| 'key_unsuitable'\n\t| 'key_resolution_failed'\n\t| 'jwks_unavailable'\n\t| 'jwks_malformed'\n\t| 'aborted';\n\n/** Reasons a well-formed token is refused by the verification policy or its signature. */\nexport type JwsPolicyErrorCode =\n\t| 'invalid_options'\n\t| 'unsigned_token'\n\t| 'algorithm_not_allowed'\n\t| 'token_type_mismatch'\n\t| 'invalid_signature';\n\n/** Reasons a signature-verified token fails the claims policy. */\nexport type JwtClaimsErrorCode =\n\t| 'missing_claim'\n\t| 'invalid_claim'\n\t| 'issuer_mismatch'\n\t| 'audience_mismatch'\n\t| 'expired'\n\t| 'not_yet_valid'\n\t| 'issued_in_future'\n\t| 'token_too_old';\n\n/** Failure codes of {@linkcode verifyCompactJws}. */\nexport type VerifyJwsErrorCode = JwsParseErrorCode | KeyResolutionErrorCode | JwsPolicyErrorCode;\n\n/** Failure codes of {@linkcode verifyJwt}. */\nexport type VerifyJwtErrorCode = VerifyJwsErrorCode | JwtClaimsErrorCode;\n\n/** Failures for the compact JWE profile. */\nexport type JweErrorCode =\n\t| 'invalid_options'\n\t| 'token_too_large'\n\t| 'malformed_token'\n\t| 'invalid_encoding'\n\t| 'invalid_utf8'\n\t| 'invalid_json'\n\t| 'duplicate_member'\n\t| 'limit_exceeded'\n\t| 'invalid_header'\n\t| 'algorithm_not_allowed'\n\t| 'encryption_not_allowed'\n\t| 'key_unsuitable'\n\t| 'unsupported_critical_header'\n\t| 'unsupported_compression'\n\t| 'encryption_failed'\n\t| 'decryption_failed';\n\n/** Every code a JOSE API reports. */\nexport type JoseErrorCode = VerifyJwtErrorCode | JweErrorCode;\n\n/**\n * Structured context for a failure. Holds names and short identifiers only, never token\n * segments, claim values or key material.\n */\nexport interface JoseErrorDetails {\n\t/** The `alg` header value the token carried. */\n\treadonly alg?: string;\n\t/** The `kid` header value the token carried, truncated to 64 characters. */\n\treadonly kid?: string;\n\t/** The claim name a claims failure concerns. */\n\treadonly claim?: string;\n\t/** The critical header names that were refused. */\n\treadonly crit?: readonly string[];\n\t/** The HTTP status a JWKS endpoint answered with. */\n\treadonly status?: number;\n}\n\n/** Failure payload of the JOSE APIs. */\nexport interface JoseFailure<TCode extends string = JoseErrorCode>\n\textends Micro509Error<TCode, JoseErrorDetails> {\n\t/** Always `false` for failures. */\n\treadonly ok: false;\n}\n\n/** A flattened failed result carrying a {@linkcode JoseFailure}. */\nexport type JoseErrorResult<TCode extends string = JoseErrorCode> = ErrorResult<\n\tTCode,\n\tJoseErrorDetails,\n\tJoseFailure<TCode>\n>;\n\n/** Success-or-failure result of a JOSE API. */\nexport type JoseResult<TValue, TCode extends string = JoseErrorCode> =\n\t| { readonly ok: true; readonly value: TValue }\n\t| JoseErrorResult<TCode>;\n\n/** Builds a failed result, truncating any reported `kid`. */\nexport function joseFailure<TCode extends JoseErrorCode>(\n\tcode: TCode,\n\tmessage: string,\n\tdetails?: JoseErrorDetails,\n): JoseErrorResult<TCode> {\n\treturn failureResult(\n\t\tcode,\n\t\tmessage,\n\t\tdetails?.kid === undefined\n\t\t\t? details\n\t\t\t: { ...details, kid: details.kid.slice(0, MAX_REPORTED_KID_LENGTH) },\n\t);\n}\n"],"mappings":";;AAyHA,SAAgB,YACf,GACA,GACA,GACyB;CACzB,OAAOA,EACNC,GACAC,GACAC,GAAS,QAAQ,KAAA,IACdA,IACA;EAAE,GAAGA;EAAS,KAAKA,EAAQ,IAAI,MAAM,GAAG,EAAuB;CAAE,CACrE;AACD"}
@@ -0,0 +1,64 @@
1
+ import { JsonObject } from "../internal/jose/strict-json.js";
2
+ import { JoseResult, JweErrorCode } from "./errors.js";
3
+ import { JoseLimits } from "./jws.js";
4
+ /** Implemented key-management algorithm; SHA-512 and MGF1-SHA-512 with empty OAEP label. */
5
+ export type JweAlgorithm = "RSA-OAEP-512";
6
+ /** Implemented content encryption: 256-bit AES-GCM, 96-bit IV, 128-bit tag. */
7
+ export type JweEncryption = "A256GCM";
8
+ /** A compact JWE protected header, with every noncritical member retained. */
9
+ export interface JweHeader {
10
+ /** Key-management algorithm. */
11
+ readonly alg: string;
12
+ /** Content-encryption algorithm. */
13
+ readonly enc: string;
14
+ /** All protected members. No unprotected header exists in this serialization. */
15
+ readonly members: JsonObject;
16
+ }
17
+ /** Input to {@linkcode encryptCompactJwe}. */
18
+ export interface EncryptJweInput {
19
+ /** An RSA-OAEP/SHA-512 public key with `encrypt` usage, 2048–8192 bits. */
20
+ readonly publicKey: CryptoKey;
21
+ /** Payload bytes; text encoding is the caller's decision. */
22
+ readonly plaintext: Uint8Array;
23
+ /** Explicit key-management algorithm. */
24
+ readonly algorithm: JweAlgorithm;
25
+ /** Explicit content-encryption algorithm. */
26
+ readonly encryption: JweEncryption;
27
+ /** Additional protected JSON data. `alg` and `enc`, if supplied, must agree. No default `typ`. */
28
+ readonly header?: JsonObject;
29
+ /** Existing JOSE bounds; `maxPayloadBytes` also bounds plaintext/ciphertext and `maxSignatureBytes` bounds the encrypted CEK. */
30
+ readonly limits?: Partial<JoseLimits>;
31
+ }
32
+ /** Input policy for {@linkcode decryptCompactJwe}; neither allowlist is inferred from the token. */
33
+ export interface DecryptJweOptions {
34
+ /** An RSA-OAEP/SHA-512 private key with `decrypt` usage, 2048–8192 bits. */
35
+ readonly privateKey: CryptoKey;
36
+ /** Accepted key-management algorithms for this application. */
37
+ readonly keyManagementAlgorithms: readonly [JweAlgorithm, ...JweAlgorithm[]];
38
+ /** Accepted content-encryption algorithms for this application. */
39
+ readonly contentEncryptionAlgorithms: readonly [JweEncryption, ...JweEncryption[]];
40
+ /** Bounds with the same meaning as {@linkcode EncryptJweInput.limits}. */
41
+ readonly limits?: Partial<JoseLimits>;
42
+ }
43
+ /** Authenticated plaintext. Encryption does not establish sender identity: anyone with the public key can encrypt. */
44
+ export interface DecryptedJwe {
45
+ /** GCM authentication succeeded under the supplied key. */
46
+ readonly authenticated: true;
47
+ /** Plaintext bytes; never an implicit JSON or nested JWT decode. */
48
+ readonly plaintext: Uint8Array;
49
+ /** Authenticated protected header. */
50
+ readonly header: JweHeader;
51
+ }
52
+ /**
53
+ * Encrypts one compact JWE for the limited RSA-OAEP-512/A256GCM profile (RFC 7516 §5.1).
54
+ * Generates a fresh 32-byte CEK and 12-byte IV; no externally supplied IV, compression or external AAD.
55
+ * The protected header's ORIGINAL base64url segment is the ASCII AAD (RFC 7516 §5.1 step 14).
56
+ */
57
+ export declare function encryptCompactJwe(input: EncryptJweInput): Promise<JoseResult<string, JweErrorCode>>;
58
+ /**
59
+ * Decrypts with explicit application allowlists, bounded parsing and the supplied private key.
60
+ * RSA unwrap, wrong CEK length, wrong key and GCM authentication failures share `decryption_failed`.
61
+ * A wrong RSA ciphertext length skips RSA and follows the dummy-CEK/GCM path. This reduces oracle
62
+ * information; JavaScript and provider implementations are not promised to be constant-time.
63
+ */
64
+ export declare function decryptCompactJwe(token: string, options: DecryptJweOptions): Promise<JoseResult<DecryptedJwe, JweErrorCode>>;
@@ -0,0 +1,188 @@
1
+ import { getCrypto as e } from "../internal/crypto/webcrypto.js";
2
+ import { base64UrlDecode as t, base64UrlEncode as n } from "../internal/jose/base64url.js";
3
+ import { snapshotJsonData as r } from "../internal/jose/json-data.js";
4
+ import { isJsonArray as i, isJsonObject as a } from "../internal/jose/strict-json.js";
5
+ import { joseFailure as o } from "./errors.js";
6
+ import { decodeJsonObject as s, resolveJoseLimits as c, validRsaPublicExponent as l } from "./jws.js";
7
+ import { rethrowIfInvariant as u, successResult as d } from "../result/result.js";
8
+ function checkKey(e, t) {
9
+ if (!(e instanceof CryptoKey) || e.type !== t || e.algorithm.name !== "RSA-OAEP" || !e.usages.includes(t === "public" ? "encrypt" : "decrypt")) return o("key_unsuitable", "JWE requires an RSA-OAEP key with the correct type and usage");
10
+ let n = e.algorithm;
11
+ return !("hash" in n) || typeof n.hash != "object" || n.hash === null || !("name" in n.hash) || n.hash.name !== "SHA-512" ? o("key_unsuitable", "JWE RSA-OAEP-512 requires SHA-512") : !("modulusLength" in n) || typeof n.modulusLength != "number" || !Number.isSafeInteger(n.modulusLength) || n.modulusLength < 2048 || n.modulusLength > 8192 || !("publicExponent" in n) || !(n.publicExponent instanceof Uint8Array) || !l(n.publicExponent) ? o("key_unsuitable", "JWE RSA keys require a 2048–8192 bit modulus and a suitable exponent") : d(Math.ceil(n.modulusLength / 8));
12
+ }
13
+ function checkCritical(e) {
14
+ if (!Object.hasOwn(e, "crit")) return d(void 0);
15
+ let t = e.crit;
16
+ if (!i(t) || t.length === 0) return o("invalid_header", "JWE crit must be a nonempty array");
17
+ let n = /* @__PURE__ */ new Set();
18
+ for (let r of t) {
19
+ if (typeof r != "string" || r.length === 0 || n.has(r) || !Object.hasOwn(e, r)) return o("invalid_header", "JWE crit has a repeated, absent or invalid member");
20
+ n.add(r);
21
+ }
22
+ return o("unsupported_critical_header", "JWE critical extensions are not supported");
23
+ }
24
+ function headerFromMembers(e) {
25
+ if (typeof e.alg != "string" || e.alg.length === 0 || typeof e.enc != "string" || e.enc.length === 0) return o("invalid_header", "JWE requires string alg and enc");
26
+ for (let t of [
27
+ "typ",
28
+ "cty",
29
+ "kid"
30
+ ]) if (Object.hasOwn(e, t) && typeof e[t] != "string") return o("invalid_header", `JWE ${t} must be a string`);
31
+ let t = checkCritical(e);
32
+ return t.ok ? Object.hasOwn(e, "zip") ? o("unsupported_compression", "JWE compression is not supported") : d({
33
+ alg: e.alg,
34
+ enc: e.enc,
35
+ members: e
36
+ }) : t;
37
+ }
38
+ function encryptionHeader(e, t) {
39
+ if (e.algorithm !== "RSA-OAEP-512") return o("algorithm_not_allowed", "Unsupported JWE key-management algorithm");
40
+ if (e.encryption !== "A256GCM") return o("encryption_not_allowed", "Unsupported JWE content-encryption algorithm");
41
+ let i = r(e.header === void 0 ? {} : e.header, {
42
+ maxBytes: t.maxHeaderBytes,
43
+ maxDepth: t.maxJsonDepth,
44
+ maxNodes: t.maxJsonNodes
45
+ });
46
+ if (!i.ok) return o(i.code, "JWE header must be bounded plain JSON data");
47
+ if (!a(i.value)) return o("invalid_header", "JWE header must be an object");
48
+ let s = i.value;
49
+ if (Object.hasOwn(s, "alg") && s.alg !== e.algorithm || Object.hasOwn(s, "enc") && s.enc !== e.encryption) return o("invalid_header", "JWE header conflicts with the requested algorithms");
50
+ let c = {
51
+ ...s,
52
+ alg: e.algorithm,
53
+ enc: e.encryption
54
+ }, l = r(c, {
55
+ maxBytes: t.maxHeaderBytes,
56
+ maxDepth: t.maxJsonDepth,
57
+ maxNodes: t.maxJsonNodes
58
+ });
59
+ if (!l.ok) return o(l.code, "JWE completed header exceeds its JSON bounds");
60
+ let u = headerFromMembers(c);
61
+ if (!u.ok) return u;
62
+ let f = new TextEncoder().encode(JSON.stringify(c));
63
+ return f.length > t.maxHeaderBytes ? o("limit_exceeded", "JWE header exceeds maxHeaderBytes") : d(n(f));
64
+ }
65
+ function encodedLength(e) {
66
+ return Math.ceil(e * 4 / 3);
67
+ }
68
+ /**
69
+ * Encrypts one compact JWE for the limited RSA-OAEP-512/A256GCM profile (RFC 7516 §5.1).
70
+ * Generates a fresh 32-byte CEK and 12-byte IV; no externally supplied IV, compression or external AAD.
71
+ * The protected header's ORIGINAL base64url segment is the ASCII AAD (RFC 7516 §5.1 step 14).
72
+ */
73
+ async function encryptCompactJwe(t) {
74
+ if (typeof t != "object" || !t || !(t.plaintext instanceof Uint8Array)) return o("invalid_options", "JWE input requires plaintext bytes");
75
+ let r = c(t.limits);
76
+ if (!r.ok) return r;
77
+ if (t.plaintext.length > r.value.maxPayloadBytes) return o("limit_exceeded", "JWE plaintext exceeds maxPayloadBytes");
78
+ let i = encryptionHeader(t, r.value);
79
+ if (!i.ok) return i;
80
+ let a = checkKey(t.publicKey, "public");
81
+ if (!a.ok) return a;
82
+ if (a.value > r.value.maxSignatureBytes) return o("limit_exceeded", "JWE encrypted key exceeds maxSignatureBytes");
83
+ if (i.value.length + encodedLength(a.value) + encodedLength(12) + encodedLength(t.plaintext.length) + encodedLength(16) + 4 > r.value.maxTokenLength) return o("token_too_large", "JWE exceeds maxTokenLength");
84
+ let s = new Uint8Array(t.plaintext), l = e(), f = l.getRandomValues(/* @__PURE__ */ new Uint8Array(32)), p = l.getRandomValues(/* @__PURE__ */ new Uint8Array(12));
85
+ try {
86
+ let e = new Uint8Array(await l.subtle.encrypt({ name: "RSA-OAEP" }, t.publicKey, f)), r = await l.subtle.importKey("raw", f, { name: "AES-GCM" }, !1, ["encrypt"]), a = new Uint8Array(await l.subtle.encrypt({
87
+ name: "AES-GCM",
88
+ iv: p,
89
+ additionalData: new TextEncoder().encode(i.value),
90
+ tagLength: 128
91
+ }, r, s));
92
+ return d([
93
+ i.value,
94
+ n(e),
95
+ n(p),
96
+ n(a.subarray(0, a.length - 16)),
97
+ n(a.subarray(a.length - 16))
98
+ ].join("."));
99
+ } catch (e) {
100
+ return u(e), o("encryption_failed", "JWE encryption failed");
101
+ } finally {
102
+ f.fill(0), s.fill(0);
103
+ }
104
+ }
105
+ function decodeSegment(e, n) {
106
+ if (e.length > encodedLength(n)) return o("limit_exceeded", "JWE segment exceeds its byte limit");
107
+ let r = t(e);
108
+ return r === void 0 ? o("invalid_encoding", "JWE segment is not canonical base64url") : r.length > n ? o("limit_exceeded", "JWE segment exceeds its byte limit") : d(r);
109
+ }
110
+ function parse(e, t) {
111
+ if (typeof e != "string") return o("malformed_token", "JWE must be a string");
112
+ if (e.length > t.maxTokenLength) return o("token_too_large", "JWE exceeds maxTokenLength");
113
+ let n = e.split("."), [r, i, a, c, l] = n;
114
+ if (n.length !== 5 || !r || i === void 0 || !a || c === void 0 || !l) return o("malformed_token", "JWE requires five compact segments");
115
+ let u = decodeSegment(r, t.maxHeaderBytes);
116
+ if (!u.ok) return u;
117
+ let f = s(u.value, t, "header", "invalid_header", "JWE");
118
+ if (!f.ok) return f;
119
+ let p = headerFromMembers(f.value);
120
+ if (!p.ok) return p;
121
+ let m = decodeSegment(i, t.maxSignatureBytes);
122
+ if (!m.ok) return m;
123
+ let h = decodeSegment(a, 12);
124
+ if (!h.ok) return h;
125
+ let g = decodeSegment(c, t.maxPayloadBytes);
126
+ if (!g.ok) return g;
127
+ let _ = decodeSegment(l, 16);
128
+ return _.ok ? h.value.length !== 12 || _.value.length !== 16 ? o("malformed_token", "JWE requires a 12-byte IV and 16-byte tag") : d({
129
+ header: p.value,
130
+ aad: new TextEncoder().encode(r),
131
+ encryptedKey: m.value,
132
+ iv: h.value,
133
+ ciphertext: g.value,
134
+ tag: _.value
135
+ }) : _;
136
+ }
137
+ function decryptionFailure() {
138
+ return o("decryption_failed", "JWE decryption failed");
139
+ }
140
+ /** Uniform CEK/tag refusal, with dummy CEK on unwrap failure (RFC 7516 §11.5). */
141
+ async function decryptPayload(t, n, r) {
142
+ let i = e(), a = i.getRandomValues(/* @__PURE__ */ new Uint8Array(32)), o = t.encryptedKey.length !== r;
143
+ try {
144
+ if (!o) try {
145
+ let e = new Uint8Array(await i.subtle.decrypt({ name: "RSA-OAEP" }, n, new Uint8Array(t.encryptedKey)));
146
+ e.length === 32 ? (a.fill(0), a = e) : (e.fill(0), o = !0);
147
+ } catch (e) {
148
+ u(e), o = !0;
149
+ }
150
+ let e = await i.subtle.importKey("raw", a, { name: "AES-GCM" }, !1, ["decrypt"]), r = new Uint8Array(t.ciphertext.length + 16);
151
+ r.set(t.ciphertext), r.set(t.tag, t.ciphertext.length);
152
+ let s = new Uint8Array(await i.subtle.decrypt({
153
+ name: "AES-GCM",
154
+ iv: new Uint8Array(t.iv),
155
+ additionalData: new Uint8Array(t.aad),
156
+ tagLength: 128
157
+ }, e, r));
158
+ return o ? (s.fill(0), decryptionFailure()) : d({
159
+ authenticated: !0,
160
+ plaintext: s,
161
+ header: t.header
162
+ });
163
+ } catch (e) {
164
+ return u(e), decryptionFailure();
165
+ } finally {
166
+ a.fill(0);
167
+ }
168
+ }
169
+ /**
170
+ * Decrypts with explicit application allowlists, bounded parsing and the supplied private key.
171
+ * RSA unwrap, wrong CEK length, wrong key and GCM authentication failures share `decryption_failed`.
172
+ * A wrong RSA ciphertext length skips RSA and follows the dummy-CEK/GCM path. This reduces oracle
173
+ * information; JavaScript and provider implementations are not promised to be constant-time.
174
+ */
175
+ async function decryptCompactJwe(e, t) {
176
+ if (typeof t != "object" || !t || !Array.isArray(t.keyManagementAlgorithms) || t.keyManagementAlgorithms.length === 0 || t.keyManagementAlgorithms.some((e) => e !== "RSA-OAEP-512") || !Array.isArray(t.contentEncryptionAlgorithms) || t.contentEncryptionAlgorithms.length === 0 || t.contentEncryptionAlgorithms.some((e) => e !== "A256GCM")) return o("invalid_options", "JWE requires nonempty supported alg and enc allowlists");
177
+ let n = c(t.limits);
178
+ if (!n.ok) return n;
179
+ let r = parse(e, n.value);
180
+ if (!r.ok) return r;
181
+ if (!t.keyManagementAlgorithms.some((e) => e === r.value.header.alg)) return o("algorithm_not_allowed", "JWE key-management algorithm is not allowed");
182
+ if (!t.contentEncryptionAlgorithms.some((e) => e === r.value.header.enc)) return o("encryption_not_allowed", "JWE content-encryption algorithm is not allowed");
183
+ let i = checkKey(t.privateKey, "private");
184
+ return i.ok ? await decryptPayload(r.value, t.privateKey, i.value) : i;
185
+ }
186
+ export { decryptCompactJwe, encryptCompactJwe };
187
+
188
+ //# sourceMappingURL=jwe.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"jwe.js","names":["key","type","joseFailure","algorithm","validRsaPublicExponent","successResult","members","names","isJsonArray","seen","name","critical","input","snapshot","snapshotJsonData","limits","isJsonObject","source","completed","header","bytes","base64UrlEncode","length","resolveJoseLimits","plaintext","crypto","getCrypto","cek","iv","encryptedKey","aes","encrypted","error","rethrowIfInvariant","segment","maxBytes","decoded","base64UrlDecode","token","segments","protectedSegment","encryptedKeySegment","ivSegment","ciphertextSegment","tagSegment","protectedBytes","object","decodeJsonObject","ciphertext","tag","unwrapFailed","parsed","encryptedKeyBytes","candidate","ciphertextAndTag","options","alg","enc"],"sources":["../../src/jose/jwe.ts"],"sourcesContent":["/** Compact JWE: RSA-OAEP-512 key management and A256GCM content encryption. @module */\n\nimport { getCrypto } from '#micro509/internal/crypto/webcrypto';\nimport { base64UrlDecode, base64UrlEncode } from '#micro509/internal/jose/base64url';\nimport { snapshotJsonData } from '#micro509/internal/jose/json-data';\nimport type { JsonObject } from '#micro509/internal/jose/strict-json';\nimport { isJsonArray, isJsonObject } from '#micro509/internal/jose/strict-json';\nimport type { JoseResult, JweErrorCode } from '#micro509/jose/errors';\nimport { joseFailure } from '#micro509/jose/errors';\nimport type { JoseLimits } from '#micro509/jose/jws';\nimport { decodeJsonObject, resolveJoseLimits, validRsaPublicExponent } from '#micro509/jose/jws';\nimport { rethrowIfInvariant, successResult } from '#micro509/result/result';\n\n/** Implemented key-management algorithm; SHA-512 and MGF1-SHA-512 with empty OAEP label. */\nexport type JweAlgorithm = 'RSA-OAEP-512';\n/** Implemented content encryption: 256-bit AES-GCM, 96-bit IV, 128-bit tag. */\nexport type JweEncryption = 'A256GCM';\n\n/** A compact JWE protected header, with every noncritical member retained. */\nexport interface JweHeader {\n\t/** Key-management algorithm. */\n\treadonly alg: string;\n\t/** Content-encryption algorithm. */\n\treadonly enc: string;\n\t/** All protected members. No unprotected header exists in this serialization. */\n\treadonly members: JsonObject;\n}\n\n/** Input to {@linkcode encryptCompactJwe}. */\nexport interface EncryptJweInput {\n\t/** An RSA-OAEP/SHA-512 public key with `encrypt` usage, 2048–8192 bits. */\n\treadonly publicKey: CryptoKey;\n\t/** Payload bytes; text encoding is the caller's decision. */\n\treadonly plaintext: Uint8Array;\n\t/** Explicit key-management algorithm. */\n\treadonly algorithm: JweAlgorithm;\n\t/** Explicit content-encryption algorithm. */\n\treadonly encryption: JweEncryption;\n\t/** Additional protected JSON data. `alg` and `enc`, if supplied, must agree. No default `typ`. */\n\treadonly header?: JsonObject;\n\t/** Existing JOSE bounds; `maxPayloadBytes` also bounds plaintext/ciphertext and `maxSignatureBytes` bounds the encrypted CEK. */\n\treadonly limits?: Partial<JoseLimits>;\n}\n\n/** Input policy for {@linkcode decryptCompactJwe}; neither allowlist is inferred from the token. */\nexport interface DecryptJweOptions {\n\t/** An RSA-OAEP/SHA-512 private key with `decrypt` usage, 2048–8192 bits. */\n\treadonly privateKey: CryptoKey;\n\t/** Accepted key-management algorithms for this application. */\n\treadonly keyManagementAlgorithms: readonly [JweAlgorithm, ...JweAlgorithm[]];\n\t/** Accepted content-encryption algorithms for this application. */\n\treadonly contentEncryptionAlgorithms: readonly [JweEncryption, ...JweEncryption[]];\n\t/** Bounds with the same meaning as {@linkcode EncryptJweInput.limits}. */\n\treadonly limits?: Partial<JoseLimits>;\n}\n\n/** Authenticated plaintext. Encryption does not establish sender identity: anyone with the public key can encrypt. */\nexport interface DecryptedJwe {\n\t/** GCM authentication succeeded under the supplied key. */\n\treadonly authenticated: true;\n\t/** Plaintext bytes; never an implicit JSON or nested JWT decode. */\n\treadonly plaintext: Uint8Array;\n\t/** Authenticated protected header. */\n\treadonly header: JweHeader;\n}\n\nconst CEK_BYTES = 32;\nconst IV_BYTES = 12;\nconst TAG_BYTES = 16;\n\nfunction checkKey(\n\tkey: CryptoKey,\n\ttype: 'public' | 'private',\n): JoseResult<number, 'key_unsuitable'> {\n\tif (\n\t\t!(key instanceof CryptoKey) ||\n\t\tkey.type !== type ||\n\t\tkey.algorithm.name !== 'RSA-OAEP' ||\n\t\t!key.usages.includes(type === 'public' ? 'encrypt' : 'decrypt')\n\t) {\n\t\treturn joseFailure(\n\t\t\t'key_unsuitable',\n\t\t\t'JWE requires an RSA-OAEP key with the correct type and usage',\n\t\t);\n\t}\n\tconst algorithm = key.algorithm;\n\tif (\n\t\t!('hash' in algorithm) ||\n\t\ttypeof algorithm.hash !== 'object' ||\n\t\talgorithm.hash === null ||\n\t\t!('name' in algorithm.hash) ||\n\t\talgorithm.hash.name !== 'SHA-512'\n\t) {\n\t\treturn joseFailure('key_unsuitable', 'JWE RSA-OAEP-512 requires SHA-512');\n\t}\n\tif (\n\t\t!('modulusLength' in algorithm) ||\n\t\ttypeof algorithm.modulusLength !== 'number' ||\n\t\t!Number.isSafeInteger(algorithm.modulusLength) ||\n\t\talgorithm.modulusLength < 2048 ||\n\t\talgorithm.modulusLength > 8192 ||\n\t\t!('publicExponent' in algorithm) ||\n\t\t!(algorithm.publicExponent instanceof Uint8Array) ||\n\t\t!validRsaPublicExponent(algorithm.publicExponent)\n\t) {\n\t\treturn joseFailure(\n\t\t\t'key_unsuitable',\n\t\t\t'JWE RSA keys require a 2048–8192 bit modulus and a suitable exponent',\n\t\t);\n\t}\n\treturn successResult(Math.ceil(algorithm.modulusLength / 8));\n}\n\nfunction checkCritical(members: JsonObject): JoseResult<undefined, JweErrorCode> {\n\tif (!Object.hasOwn(members, 'crit')) return successResult(undefined);\n\tconst names = members.crit;\n\tif (!isJsonArray(names) || names.length === 0)\n\t\treturn joseFailure('invalid_header', 'JWE crit must be a nonempty array');\n\tconst seen = new Set<string>();\n\tfor (const name of names) {\n\t\tif (\n\t\t\ttypeof name !== 'string' ||\n\t\t\tname.length === 0 ||\n\t\t\tseen.has(name) ||\n\t\t\t!Object.hasOwn(members, name)\n\t\t)\n\t\t\treturn joseFailure('invalid_header', 'JWE crit has a repeated, absent or invalid member');\n\t\tseen.add(name);\n\t}\n\treturn joseFailure('unsupported_critical_header', 'JWE critical extensions are not supported');\n}\n\nfunction headerFromMembers(members: JsonObject): JoseResult<JweHeader, JweErrorCode> {\n\tif (\n\t\ttypeof members.alg !== 'string' ||\n\t\tmembers.alg.length === 0 ||\n\t\ttypeof members.enc !== 'string' ||\n\t\tmembers.enc.length === 0\n\t)\n\t\treturn joseFailure('invalid_header', 'JWE requires string alg and enc');\n\tfor (const name of ['typ', 'cty', 'kid']) {\n\t\tif (Object.hasOwn(members, name) && typeof members[name] !== 'string')\n\t\t\treturn joseFailure('invalid_header', `JWE ${name} must be a string`);\n\t}\n\tconst critical = checkCritical(members);\n\tif (!critical.ok) return critical;\n\tif (Object.hasOwn(members, 'zip'))\n\t\treturn joseFailure('unsupported_compression', 'JWE compression is not supported');\n\treturn successResult({ alg: members.alg, enc: members.enc, members });\n}\n\nfunction encryptionHeader(\n\tinput: EncryptJweInput,\n\tlimits: JoseLimits,\n): JoseResult<string, JweErrorCode> {\n\tif (input.algorithm !== 'RSA-OAEP-512')\n\t\treturn joseFailure('algorithm_not_allowed', 'Unsupported JWE key-management algorithm');\n\tif (input.encryption !== 'A256GCM')\n\t\treturn joseFailure('encryption_not_allowed', 'Unsupported JWE content-encryption algorithm');\n\tconst snapshot = snapshotJsonData(input.header === undefined ? {} : input.header, {\n\t\tmaxBytes: limits.maxHeaderBytes,\n\t\tmaxDepth: limits.maxJsonDepth,\n\t\tmaxNodes: limits.maxJsonNodes,\n\t});\n\tif (!snapshot.ok) return joseFailure(snapshot.code, 'JWE header must be bounded plain JSON data');\n\tif (!isJsonObject(snapshot.value))\n\t\treturn joseFailure('invalid_header', 'JWE header must be an object');\n\tconst source = snapshot.value;\n\tif (\n\t\t(Object.hasOwn(source, 'alg') && source.alg !== input.algorithm) ||\n\t\t(Object.hasOwn(source, 'enc') && source.enc !== input.encryption)\n\t)\n\t\treturn joseFailure('invalid_header', 'JWE header conflicts with the requested algorithms');\n\tconst members = { ...source, alg: input.algorithm, enc: input.encryption };\n\tconst completed = snapshotJsonData(members, {\n\t\tmaxBytes: limits.maxHeaderBytes,\n\t\tmaxDepth: limits.maxJsonDepth,\n\t\tmaxNodes: limits.maxJsonNodes,\n\t});\n\tif (!completed.ok)\n\t\treturn joseFailure(completed.code, 'JWE completed header exceeds its JSON bounds');\n\tconst header = headerFromMembers(members);\n\tif (!header.ok) return header;\n\tconst bytes = new TextEncoder().encode(JSON.stringify(members));\n\tif (bytes.length > limits.maxHeaderBytes)\n\t\treturn joseFailure('limit_exceeded', 'JWE header exceeds maxHeaderBytes');\n\treturn successResult(base64UrlEncode(bytes));\n}\n\nfunction encodedLength(length: number): number {\n\treturn Math.ceil((length * 4) / 3);\n}\n\n/**\n * Encrypts one compact JWE for the limited RSA-OAEP-512/A256GCM profile (RFC 7516 §5.1).\n * Generates a fresh 32-byte CEK and 12-byte IV; no externally supplied IV, compression or external AAD.\n * The protected header's ORIGINAL base64url segment is the ASCII AAD (RFC 7516 §5.1 step 14).\n */\nexport async function encryptCompactJwe(\n\tinput: EncryptJweInput,\n): Promise<JoseResult<string, JweErrorCode>> {\n\tif (typeof input !== 'object' || input === null || !(input.plaintext instanceof Uint8Array))\n\t\treturn joseFailure('invalid_options', 'JWE input requires plaintext bytes');\n\tconst limits = resolveJoseLimits(input.limits);\n\tif (!limits.ok) return limits;\n\tif (input.plaintext.length > limits.value.maxPayloadBytes)\n\t\treturn joseFailure('limit_exceeded', 'JWE plaintext exceeds maxPayloadBytes');\n\tconst header = encryptionHeader(input, limits.value);\n\tif (!header.ok) return header;\n\tconst key = checkKey(input.publicKey, 'public');\n\tif (!key.ok) return key;\n\tif (key.value > limits.value.maxSignatureBytes)\n\t\treturn joseFailure('limit_exceeded', 'JWE encrypted key exceeds maxSignatureBytes');\n\tif (\n\t\theader.value.length +\n\t\t\tencodedLength(key.value) +\n\t\t\tencodedLength(IV_BYTES) +\n\t\t\tencodedLength(input.plaintext.length) +\n\t\t\tencodedLength(TAG_BYTES) +\n\t\t\t4 >\n\t\tlimits.value.maxTokenLength\n\t)\n\t\treturn joseFailure('token_too_large', 'JWE exceeds maxTokenLength');\n\tconst plaintext = new Uint8Array(input.plaintext);\n\tconst crypto = getCrypto();\n\tconst cek = crypto.getRandomValues(new Uint8Array(CEK_BYTES));\n\tconst iv = crypto.getRandomValues(new Uint8Array(IV_BYTES));\n\ttry {\n\t\tconst encryptedKey = new Uint8Array(\n\t\t\tawait crypto.subtle.encrypt({ name: 'RSA-OAEP' }, input.publicKey, cek),\n\t\t);\n\t\tconst aes = await crypto.subtle.importKey('raw', cek, { name: 'AES-GCM' }, false, ['encrypt']);\n\t\tconst encrypted = new Uint8Array(\n\t\t\tawait crypto.subtle.encrypt(\n\t\t\t\t{\n\t\t\t\t\tname: 'AES-GCM',\n\t\t\t\t\tiv,\n\t\t\t\t\tadditionalData: new TextEncoder().encode(header.value),\n\t\t\t\t\ttagLength: 128,\n\t\t\t\t},\n\t\t\t\taes,\n\t\t\t\tplaintext,\n\t\t\t),\n\t\t);\n\t\treturn successResult(\n\t\t\t[\n\t\t\t\theader.value,\n\t\t\t\tbase64UrlEncode(encryptedKey),\n\t\t\t\tbase64UrlEncode(iv),\n\t\t\t\tbase64UrlEncode(encrypted.subarray(0, encrypted.length - TAG_BYTES)),\n\t\t\t\tbase64UrlEncode(encrypted.subarray(encrypted.length - TAG_BYTES)),\n\t\t\t].join('.'),\n\t\t);\n\t} catch (error) {\n\t\trethrowIfInvariant(error);\n\t\treturn joseFailure('encryption_failed', 'JWE encryption failed');\n\t} finally {\n\t\tcek.fill(0);\n\t\tplaintext.fill(0);\n\t}\n}\n\ninterface ParsedJwe {\n\treadonly header: JweHeader;\n\treadonly aad: Uint8Array;\n\treadonly encryptedKey: Uint8Array;\n\treadonly iv: Uint8Array;\n\treadonly ciphertext: Uint8Array;\n\treadonly tag: Uint8Array;\n}\n\nfunction decodeSegment(segment: string, maxBytes: number): JoseResult<Uint8Array, JweErrorCode> {\n\tif (segment.length > encodedLength(maxBytes))\n\t\treturn joseFailure('limit_exceeded', 'JWE segment exceeds its byte limit');\n\tconst decoded = base64UrlDecode(segment);\n\tif (decoded === undefined)\n\t\treturn joseFailure('invalid_encoding', 'JWE segment is not canonical base64url');\n\tif (decoded.length > maxBytes)\n\t\treturn joseFailure('limit_exceeded', 'JWE segment exceeds its byte limit');\n\treturn successResult(decoded);\n}\nfunction parse(token: string, limits: JoseLimits): JoseResult<ParsedJwe, JweErrorCode> {\n\tif (typeof token !== 'string') return joseFailure('malformed_token', 'JWE must be a string');\n\tif (token.length > limits.maxTokenLength)\n\t\treturn joseFailure('token_too_large', 'JWE exceeds maxTokenLength');\n\tconst segments = token.split('.');\n\tconst [protectedSegment, encryptedKeySegment, ivSegment, ciphertextSegment, tagSegment] =\n\t\tsegments;\n\tif (\n\t\tsegments.length !== 5 ||\n\t\t!protectedSegment ||\n\t\tencryptedKeySegment === undefined ||\n\t\t!ivSegment ||\n\t\tciphertextSegment === undefined ||\n\t\t!tagSegment\n\t)\n\t\treturn joseFailure('malformed_token', 'JWE requires five compact segments');\n\tconst protectedBytes = decodeSegment(protectedSegment, limits.maxHeaderBytes);\n\tif (!protectedBytes.ok) return protectedBytes;\n\tconst object = decodeJsonObject(protectedBytes.value, limits, 'header', 'invalid_header', 'JWE');\n\tif (!object.ok) return object;\n\tconst header = headerFromMembers(object.value);\n\tif (!header.ok) return header;\n\tconst encryptedKey = decodeSegment(encryptedKeySegment, limits.maxSignatureBytes);\n\tif (!encryptedKey.ok) return encryptedKey;\n\tconst iv = decodeSegment(ivSegment, IV_BYTES);\n\tif (!iv.ok) return iv;\n\tconst ciphertext = decodeSegment(ciphertextSegment, limits.maxPayloadBytes);\n\tif (!ciphertext.ok) return ciphertext;\n\tconst tag = decodeSegment(tagSegment, TAG_BYTES);\n\tif (!tag.ok) return tag;\n\tif (iv.value.length !== IV_BYTES || tag.value.length !== TAG_BYTES)\n\t\treturn joseFailure('malformed_token', 'JWE requires a 12-byte IV and 16-byte tag');\n\treturn successResult({\n\t\theader: header.value,\n\t\taad: new TextEncoder().encode(protectedSegment),\n\t\tencryptedKey: encryptedKey.value,\n\t\tiv: iv.value,\n\t\tciphertext: ciphertext.value,\n\t\ttag: tag.value,\n\t});\n}\nfunction decryptionFailure(): JoseResult<never, 'decryption_failed'> {\n\treturn joseFailure('decryption_failed', 'JWE decryption failed');\n}\n\n/** Uniform CEK/tag refusal, with dummy CEK on unwrap failure (RFC 7516 §11.5). */\nasync function decryptPayload(\n\tparsed: ParsedJwe,\n\tkey: CryptoKey,\n\tencryptedKeyBytes: number,\n): Promise<JoseResult<DecryptedJwe, JweErrorCode>> {\n\tconst crypto = getCrypto();\n\tlet cek = crypto.getRandomValues(new Uint8Array(CEK_BYTES));\n\tlet unwrapFailed = parsed.encryptedKey.length !== encryptedKeyBytes;\n\ttry {\n\t\tif (!unwrapFailed) {\n\t\t\ttry {\n\t\t\t\tconst candidate = new Uint8Array(\n\t\t\t\t\tawait crypto.subtle.decrypt(\n\t\t\t\t\t\t{ name: 'RSA-OAEP' },\n\t\t\t\t\t\tkey,\n\t\t\t\t\t\tnew Uint8Array(parsed.encryptedKey),\n\t\t\t\t\t),\n\t\t\t\t);\n\t\t\t\tif (candidate.length !== CEK_BYTES) {\n\t\t\t\t\tcandidate.fill(0);\n\t\t\t\t\tunwrapFailed = true;\n\t\t\t\t} else {\n\t\t\t\t\tcek.fill(0);\n\t\t\t\t\tcek = candidate;\n\t\t\t\t}\n\t\t\t} catch (error) {\n\t\t\t\trethrowIfInvariant(error);\n\t\t\t\tunwrapFailed = true;\n\t\t\t}\n\t\t}\n\t\tconst aes = await crypto.subtle.importKey('raw', cek, { name: 'AES-GCM' }, false, ['decrypt']);\n\t\tconst ciphertextAndTag = new Uint8Array(parsed.ciphertext.length + TAG_BYTES);\n\t\tciphertextAndTag.set(parsed.ciphertext);\n\t\tciphertextAndTag.set(parsed.tag, parsed.ciphertext.length);\n\t\tconst plaintext = new Uint8Array(\n\t\t\tawait crypto.subtle.decrypt(\n\t\t\t\t{\n\t\t\t\t\tname: 'AES-GCM',\n\t\t\t\t\tiv: new Uint8Array(parsed.iv),\n\t\t\t\t\tadditionalData: new Uint8Array(parsed.aad),\n\t\t\t\t\ttagLength: 128,\n\t\t\t\t},\n\t\t\t\taes,\n\t\t\t\tciphertextAndTag,\n\t\t\t),\n\t\t);\n\t\tif (unwrapFailed) {\n\t\t\tplaintext.fill(0);\n\t\t\treturn decryptionFailure();\n\t\t}\n\t\treturn successResult({ authenticated: true, plaintext, header: parsed.header });\n\t} catch (error) {\n\t\trethrowIfInvariant(error);\n\t\treturn decryptionFailure();\n\t} finally {\n\t\tcek.fill(0);\n\t}\n}\n\n/**\n * Decrypts with explicit application allowlists, bounded parsing and the supplied private key.\n * RSA unwrap, wrong CEK length, wrong key and GCM authentication failures share `decryption_failed`.\n * A wrong RSA ciphertext length skips RSA and follows the dummy-CEK/GCM path. This reduces oracle\n * information; JavaScript and provider implementations are not promised to be constant-time.\n */\nexport async function decryptCompactJwe(\n\ttoken: string,\n\toptions: DecryptJweOptions,\n): Promise<JoseResult<DecryptedJwe, JweErrorCode>> {\n\tif (\n\t\ttypeof options !== 'object' ||\n\t\toptions === null ||\n\t\t!Array.isArray(options.keyManagementAlgorithms) ||\n\t\toptions.keyManagementAlgorithms.length === 0 ||\n\t\toptions.keyManagementAlgorithms.some((alg) => alg !== 'RSA-OAEP-512') ||\n\t\t!Array.isArray(options.contentEncryptionAlgorithms) ||\n\t\toptions.contentEncryptionAlgorithms.length === 0 ||\n\t\toptions.contentEncryptionAlgorithms.some((enc) => enc !== 'A256GCM')\n\t)\n\t\treturn joseFailure('invalid_options', 'JWE requires nonempty supported alg and enc allowlists');\n\tconst limits = resolveJoseLimits(options.limits);\n\tif (!limits.ok) return limits;\n\tconst parsed = parse(token, limits.value);\n\tif (!parsed.ok) return parsed;\n\tif (!options.keyManagementAlgorithms.some((alg) => alg === parsed.value.header.alg))\n\t\treturn joseFailure('algorithm_not_allowed', 'JWE key-management algorithm is not allowed');\n\tif (!options.contentEncryptionAlgorithms.some((enc) => enc === parsed.value.header.enc))\n\t\treturn joseFailure('encryption_not_allowed', 'JWE content-encryption algorithm is not allowed');\n\tconst key = checkKey(options.privateKey, 'private');\n\tif (!key.ok) return key;\n\treturn await decryptPayload(parsed.value, options.privateKey, key.value);\n}\n"],"mappings":";;;;;;;AAsEA,SAAS,SACR,GACA,GACuC;CACvC,IACC,EAAEA,aAAe,cACjBA,EAAI,SAASC,KACbD,EAAI,UAAU,SAAS,cACvB,CAACA,EAAI,OA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