micro509 0.17.1 → 0.19.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.
- package/CHANGELOG.md +165 -6
- package/dist/crypto/crypto.d.ts +12 -4
- package/dist/crypto/crypto.js +30 -17
- package/dist/crypto/crypto.js.map +1 -1
- package/dist/crypto.d.ts +8 -2
- package/dist/der/der.d.ts +14 -4
- package/dist/der/der.js +19 -19
- package/dist/der/der.js.map +1 -1
- package/dist/der.d.ts +26 -2
- package/dist/der.js +4 -4
- package/dist/index.d.ts +84 -16
- package/dist/index.js +19 -19
- package/dist/internal/asn1/asn1.d.ts +1 -2
- package/dist/internal/asn1/asn1.js +10 -2
- package/dist/internal/asn1/asn1.js.map +1 -1
- package/dist/internal/asn1/ber.js.map +1 -1
- package/dist/internal/asn1/decode-refusal.js.map +1 -1
- package/dist/internal/asn1/der.d.ts +1 -2
- package/dist/internal/asn1/der.js.map +1 -1
- package/dist/internal/asn1/oids.js +71 -353
- package/dist/internal/asn1/oids.js.map +1 -1
- package/dist/internal/asn1/oids.json.js +357 -0
- package/dist/internal/asn1/oids.json.js.map +1 -0
- package/dist/internal/crypto/algorithm-names.js +1 -1
- package/dist/internal/crypto/algorithm-names.js.map +1 -1
- package/dist/internal/crypto/ecdsa.js.map +1 -1
- package/dist/internal/crypto/hash.js.map +1 -1
- package/dist/internal/crypto/pbes2.d.ts +1 -2
- package/dist/internal/crypto/pbes2.js +70 -70
- package/dist/internal/crypto/pbes2.js.map +1 -1
- package/dist/internal/crypto/prime-ec.js +37 -0
- package/dist/internal/crypto/prime-ec.js.map +1 -0
- package/dist/internal/crypto/rsa-pss.js +50 -50
- package/dist/internal/crypto/rsa-pss.js.map +1 -1
- package/dist/internal/crypto/sig-verify.d.ts +41 -2
- package/dist/internal/crypto/sig-verify.js +125 -38
- package/dist/internal/crypto/sig-verify.js.map +1 -1
- package/dist/internal/crypto/signing.d.ts +1 -2
- package/dist/internal/crypto/signing.js +26 -26
- package/dist/internal/crypto/signing.js.map +1 -1
- package/dist/internal/jose/base64url.js.map +1 -1
- package/dist/internal/jose/json-data.js +108 -0
- package/dist/internal/jose/json-data.js.map +1 -0
- package/dist/internal/jose/strict-json.d.ts +1 -2
- package/dist/internal/jose/strict-json.js.map +1 -1
- package/dist/internal/shared/base64.js.map +1 -1
- package/dist/internal/shared/dn.d.ts +1 -2
- package/dist/internal/shared/dn.js +1 -1
- package/dist/internal/shared/dn.js.map +1 -1
- package/dist/internal/shared/idna.js.map +1 -1
- package/dist/internal/shared/ip.d.ts +1 -2
- package/dist/internal/shared/ip.js.map +1 -1
- package/dist/internal/shared/mailbox.js.map +1 -1
- package/dist/internal/shared/punycode.js.map +1 -1
- package/dist/internal/shared/uri-host.js.map +1 -1
- package/dist/internal/verify/name-constraints-engine.js +64 -64
- package/dist/internal/verify/name-constraints-engine.js.map +1 -1
- package/dist/internal/verify/policy-engine.js +1 -1
- package/dist/internal/verify/policy-engine.js.map +1 -1
- package/dist/internal/verify/spki-distrust.js.map +1 -1
- package/dist/internal/verify/verify-path.d.ts +1 -2
- package/dist/internal/verify/verify-path.js +234 -128
- package/dist/internal/verify/verify-path.js.map +1 -1
- package/dist/internal/x509/directory-name.js +10 -10
- package/dist/internal/x509/directory-name.js.map +1 -1
- package/dist/internal/x509/extension-bits.js.map +1 -1
- package/dist/internal/x509/extension-errors.d.ts +1 -2
- package/dist/internal/x509/extension-errors.js.map +1 -1
- package/dist/internal/x509/extension-registry.js +18 -18
- package/dist/internal/x509/extension-registry.js.map +1 -1
- package/dist/internal/x509/general-name-profile.js +9 -9
- package/dist/internal/x509/general-name-profile.js.map +1 -1
- package/dist/internal/x509/general-name.js +32 -32
- package/dist/internal/x509/general-name.js.map +1 -1
- package/dist/internal/x509/name-fields.js +1 -1
- package/dist/internal/x509/name-fields.js.map +1 -1
- package/dist/internal/x509/or-address.js.map +1 -1
- package/dist/jose/base64url.d.ts +4 -0
- package/dist/jose/base64url.js +14 -0
- package/dist/jose/base64url.js.map +1 -0
- package/dist/jose/errors.d.ts +9 -3
- package/dist/jose/errors.js.map +1 -1
- package/dist/jose/jwe.d.ts +64 -0
- package/dist/jose/jwe.js +188 -0
- package/dist/jose/jwe.js.map +1 -0
- package/dist/jose/jwks.d.ts +38 -10
- package/dist/jose/jwks.js +156 -96
- package/dist/jose/jwks.js.map +1 -1
- package/dist/jose/jws.d.ts +8 -6
- package/dist/jose/jws.js +216 -170
- package/dist/jose/jws.js.map +1 -1
- package/dist/jose/jwt.d.ts +8 -2
- package/dist/jose/jwt.js +98 -98
- package/dist/jose/jwt.js.map +1 -1
- package/dist/jose/remote-jwks.d.ts +1 -2
- package/dist/jose/remote-jwks.js +106 -108
- package/dist/jose/remote-jwks.js.map +1 -1
- package/dist/jose.d.ts +15 -4
- package/dist/jose.js +7 -5
- package/dist/kdf/argon2-arithmetic.js.map +1 -1
- package/dist/kdf/argon2-core.js.map +1 -1
- package/dist/kdf/argon2-memory.js.map +1 -1
- package/dist/kdf/argon2-portable.js.map +1 -1
- package/dist/kdf/argon2.d.ts +7 -2
- package/dist/kdf/argon2.js.map +1 -1
- package/dist/kdf.d.ts +6 -0
- package/dist/keys/keys.d.ts +31 -6
- package/dist/keys/keys.js +315 -233
- package/dist/keys/keys.js.map +1 -1
- package/dist/keys.d.ts +11 -2
- package/dist/keys.js +2 -2
- package/dist/pem/pem.d.ts +1 -2
- package/dist/pem/pem.js +40 -25
- package/dist/pem/pem.js.map +1 -1
- package/dist/pem.d.ts +6 -0
- package/dist/pkcs/pfx.d.ts +2 -3
- package/dist/pkcs/pfx.js +142 -142
- package/dist/pkcs/pfx.js.map +1 -1
- package/dist/pkcs/pkcs12-mac.d.ts +1 -2
- package/dist/pkcs/pkcs12-mac.js +122 -122
- package/dist/pkcs/pkcs12-mac.js.map +1 -1
- package/dist/pkcs/pkcs7.d.ts +24 -3
- package/dist/pkcs/pkcs7.js +294 -256
- package/dist/pkcs/pkcs7.js.map +1 -1
- package/dist/pkcs.d.ts +10 -1
- package/dist/pkcs.js +4 -4
- package/dist/result/result.d.ts +1 -2
- package/dist/result/result.js.map +1 -1
- package/dist/result.d.ts +6 -0
- package/dist/revocation/chain.d.ts +69 -16
- package/dist/revocation/chain.js +431 -303
- package/dist/revocation/chain.js.map +1 -1
- package/dist/revocation/crl.d.ts +67 -14
- package/dist/revocation/crl.js +656 -366
- package/dist/revocation/crl.js.map +1 -1
- package/dist/revocation/ocsp.d.ts +78 -24
- package/dist/revocation/ocsp.js +622 -436
- package/dist/revocation/ocsp.js.map +1 -1
- package/dist/revocation/revocation.d.ts +68 -14
- package/dist/revocation/revocation.js +195 -74
- package/dist/revocation/revocation.js.map +1 -1
- package/dist/revocation.d.ts +14 -5
- package/dist/revocation.js +4 -4
- package/dist/ssh/ssh.d.ts +2 -3
- package/dist/ssh/ssh.js +165 -170
- package/dist/ssh/ssh.js.map +1 -1
- package/dist/ssh/wire.d.ts +1 -2
- package/dist/ssh/wire.js +10 -10
- package/dist/ssh/wire.js.map +1 -1
- package/dist/ssh.d.ts +8 -0
- package/dist/verify/identity.d.ts +3 -4
- package/dist/verify/identity.js +33 -33
- package/dist/verify/identity.js.map +1 -1
- package/dist/verify/name-constraints.d.ts +9 -2
- package/dist/verify/policy.d.ts +9 -2
- package/dist/verify/verify.d.ts +85 -34
- package/dist/verify/verify.js +276 -226
- package/dist/verify/verify.js.map +1 -1
- package/dist/verify.d.ts +12 -2
- package/dist/x509/certificate.d.ts +4 -5
- package/dist/x509/certificate.js +40 -40
- package/dist/x509/certificate.js.map +1 -1
- package/dist/x509/csr.d.ts +3 -4
- package/dist/x509/csr.js +15 -15
- package/dist/x509/csr.js.map +1 -1
- package/dist/x509/extensions.d.ts +1 -2
- package/dist/x509/extensions.js +165 -165
- package/dist/x509/extensions.js.map +1 -1
- package/dist/x509/fingerprint.d.ts +1 -2
- package/dist/x509/fingerprint.js.map +1 -1
- package/dist/x509/name-text.d.ts +1 -2
- package/dist/x509/name-text.js.map +1 -1
- package/dist/x509/name.d.ts +1 -2
- package/dist/x509/name.js +15 -15
- package/dist/x509/name.js.map +1 -1
- package/dist/x509/parse.d.ts +9 -6
- package/dist/x509/parse.js +394 -394
- package/dist/x509/parse.js.map +1 -1
- package/dist/x509.d.ts +17 -4
- package/dist/x509.js +8 -8
- package/package.json +32 -33
- package/dist/internal/asn1/oids2.js +0 -75
- package/dist/internal/asn1/oids2.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"or-address.js","names":["VALID","MALFORMED","UNSUPPORTED","valid","checks","result","value","size","isNumericStringContents","decodeString","element","numeric","printable","children","childrenOf","source","values","index","length","left","right","difference","BUILT_IN_STANDARD_ATTRIBUTES","inner","BUILT_IN_STANDARD_ORDER","fields","limits","field","max","names","name","positions","position","attributes","type","rest","attribute","components","component","lines","line","terminalType","decodeIntegerNumber","EXTENSION_ATTRIBUTE_VALUES","wrapped","typeNumber","sorted","standard","optional","domainDefined","extensionAttributes","extra"],"sources":["../../../src/internal/x509/or-address.ts"],"sourcesContent":["/**\n * RFC 5280 Appendix A.1 ORAddress schema validation for x400Address builder\n * input. The module is `DEFINITIONS EXPLICIT TAGS`, so only the fields marked\n * IMPLICIT replace their underlying tag.\n *\n * @module\n */\n\nimport {\n\tchildrenOf,\n\tdecodeIntegerNumber,\n\tdecodeString,\n\tisNumericStringContents,\n} from '#micro509/internal/asn1/asn1';\nimport type { DerElement } from '#micro509/internal/asn1/der';\nimport type { GeneralNameContentCheck } from '#micro509/internal/x509/general-name-profile';\n\nconst VALID: GeneralNameContentCheck = { ok: true };\nconst MALFORMED: GeneralNameContentCheck = { ok: false, reason: 'malformed' };\nconst UNSUPPORTED: GeneralNameContentCheck = { ok: false, reason: 'unsupported' };\n\nconst NUMERIC_STRING = 0x12;\nconst PRINTABLE_STRING = 0x13;\nconst SEQUENCE = 0x30;\nconst SET = 0x31;\n\n/** A string bound in characters, inclusive. */\ninterface Bounds {\n\treadonly min: number;\n\treadonly max: number;\n}\n\nfunction bounds(min: number, max: number): Bounds {\n\treturn { min, max };\n}\n\nfunction check(valid: boolean): GeneralNameContentCheck {\n\treturn valid ? VALID : MALFORMED;\n}\n\nfunction firstFailure(checks: readonly GeneralNameContentCheck[]): GeneralNameContentCheck {\n\treturn checks.find((result) => !result.ok) ?? VALID;\n}\n\nfunction isNumericString(value: Uint8Array, size: Bounds): boolean {\n\treturn value.length >= size.min && value.length <= size.max && isNumericStringContents(value);\n}\n\nfunction isPrintableString(value: Uint8Array, size: Bounds): boolean {\n\tif (value.length < size.min || value.length > size.max) {\n\t\treturn false;\n\t}\n\ttry {\n\t\tdecodeString(PRINTABLE_STRING, value);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/** A universal NumericString or PrintableString element within its CHOICE bounds. */\nfunction isNumericOrPrintable(element: DerElement, numeric: Bounds, printable: Bounds): boolean {\n\treturn element.tag === NUMERIC_STRING\n\t\t? isNumericString(element.value, numeric)\n\t\t: element.tag === PRINTABLE_STRING && isPrintableString(element.value, printable);\n}\n\n/** The single element an explicit tag wraps, or `undefined`. */\nfunction explicitInner(source: Uint8Array, element: DerElement): DerElement | undefined {\n\tconst children = childrenOf(source, element);\n\treturn children.length === 1 ? children[0] : undefined;\n}\n\n/** DER orders SET components by ascending tag and SET OF members by ascending encoding. */\nfunction isAscending(values: readonly number[]): boolean {\n\treturn values.every((value, index) => index === 0 || (values[index - 1] ?? value) < value);\n}\n\nfunction compareEncodings(left: Uint8Array, right: Uint8Array): number {\n\tconst length = Math.min(left.length, right.length);\n\tfor (let index = 0; index < length; index += 1) {\n\t\tconst difference = (left[index] ?? 0) - (right[index] ?? 0);\n\t\tif (difference !== 0) return difference;\n\t}\n\treturn left.length - right.length;\n}\n\nfunction encodingOf(source: Uint8Array, element: DerElement): Uint8Array {\n\treturn source.subarray(element.start - element.headerLength, element.end);\n}\n\n/** RFC 5280 A.1: `CountryName ::= [APPLICATION 1] CHOICE`, also the physical-delivery-country-name CHOICE. */\nfunction checkCountryName(element: DerElement | undefined): GeneralNameContentCheck {\n\treturn check(element !== undefined && isNumericOrPrintable(element, bounds(3, 3), bounds(2, 2)));\n}\n\ntype FieldCheck = (source: Uint8Array, element: DerElement) => GeneralNameContentCheck;\n\n/** BuiltInStandardAttributes fields in schema order, keyed by their encoded tag. */\nconst BUILT_IN_STANDARD_ATTRIBUTES: ReadonlyMap<number, FieldCheck> = new Map<number, FieldCheck>([\n\t[0x61, (source, element) => checkCountryName(explicitInner(source, element))],\n\t[\n\t\t0x62,\n\t\t(source, element) => {\n\t\t\tconst inner = explicitInner(source, element);\n\t\t\treturn check(\n\t\t\t\tinner !== undefined && isNumericOrPrintable(inner, bounds(0, 16), bounds(0, 16)),\n\t\t\t);\n\t\t},\n\t],\n\t[0x80, (_source, element) => check(isNumericString(element.value, bounds(1, 16)))],\n\t[0x81, (_source, element) => check(isPrintableString(element.value, bounds(1, 24)))],\n\t[\n\t\t0xa2,\n\t\t(source, element) => {\n\t\t\tconst inner = explicitInner(source, element);\n\t\t\treturn check(\n\t\t\t\tinner !== undefined && isNumericOrPrintable(inner, bounds(1, 16), bounds(1, 16)),\n\t\t\t);\n\t\t},\n\t],\n\t[0x83, (_source, element) => check(isPrintableString(element.value, bounds(1, 64)))],\n\t[0x84, (_source, element) => check(isNumericString(element.value, bounds(1, 32)))],\n\t[0xa5, checkPersonalName],\n\t[0xa6, checkOrganizationalUnitNames],\n]);\n\nconst BUILT_IN_STANDARD_ORDER: readonly number[] = [...BUILT_IN_STANDARD_ATTRIBUTES.keys()];\n\n/**\n * `PersonalName ::= SET { surname [0], given-name [1] OPTIONAL, initials [2]\n * OPTIONAL, generation-qualifier [3] OPTIONAL }`, each an IMPLICIT\n * PrintableString of 1 to 40, 16, 5 and 3 characters.\n */\nfunction checkPersonalName(source: Uint8Array, element: DerElement): GeneralNameContentCheck {\n\tconst fields = childrenOf(source, element);\n\tconst limits = new Map([\n\t\t[0x80, 40],\n\t\t[0x81, 16],\n\t\t[0x82, 5],\n\t\t[0x83, 3],\n\t]);\n\treturn check(\n\t\tfields[0]?.tag === 0x80 &&\n\t\t\tisAscending(fields.map((field) => field.tag)) &&\n\t\t\tfields.every((field) => {\n\t\t\t\tconst max = limits.get(field.tag);\n\t\t\t\treturn max !== undefined && isPrintableString(field.value, bounds(1, max));\n\t\t\t}),\n\t);\n}\n\n/** `OrganizationalUnitNames ::= SEQUENCE SIZE (1..4) OF PrintableString (SIZE (1..32))`. */\nfunction checkOrganizationalUnitNames(\n\tsource: Uint8Array,\n\telement: DerElement,\n): GeneralNameContentCheck {\n\tconst names = childrenOf(source, element);\n\treturn check(\n\t\tnames.length >= 1 &&\n\t\t\tnames.length <= 4 &&\n\t\t\tnames.every(\n\t\t\t\t(name) => name.tag === PRINTABLE_STRING && isPrintableString(name.value, bounds(1, 32)),\n\t\t\t),\n\t);\n}\n\nfunction checkBuiltInStandardAttributes(\n\tsource: Uint8Array,\n\telement: DerElement,\n): GeneralNameContentCheck {\n\tconst fields = childrenOf(source, element);\n\tconst positions = fields.map((field) => BUILT_IN_STANDARD_ORDER.indexOf(field.tag));\n\tif (positions.some((position) => position < 0) || !isAscending(positions)) {\n\t\treturn MALFORMED;\n\t}\n\treturn firstFailure(\n\t\tfields.map(\n\t\t\t(field) => BUILT_IN_STANDARD_ATTRIBUTES.get(field.tag)?.(source, field) ?? MALFORMED,\n\t\t),\n\t);\n}\n\n/**\n * `BuiltInDomainDefinedAttributes ::= SEQUENCE SIZE (1..4) OF SEQUENCE { type\n * PrintableString (SIZE (1..8)), value PrintableString (SIZE (1..128)) }`.\n */\nfunction checkBuiltInDomainDefinedAttributes(\n\tsource: Uint8Array,\n\telement: DerElement,\n): GeneralNameContentCheck {\n\tconst attributes = childrenOf(source, element);\n\treturn check(\n\t\tattributes.length >= 1 &&\n\t\t\tattributes.length <= 4 &&\n\t\t\tattributes.every((attribute) => {\n\t\t\t\tconst [type, value, ...rest] =\n\t\t\t\t\tattribute.tag === SEQUENCE ? childrenOf(source, attribute) : [];\n\t\t\t\treturn (\n\t\t\t\t\trest.length === 0 &&\n\t\t\t\t\ttype?.tag === PRINTABLE_STRING &&\n\t\t\t\t\tvalue?.tag === PRINTABLE_STRING &&\n\t\t\t\t\tisPrintableString(type.value, bounds(1, 8)) &&\n\t\t\t\t\tisPrintableString(value.value, bounds(1, 128))\n\t\t\t\t);\n\t\t\t}),\n\t);\n}\n\n/**\n * `PDSParameter ::= SET { printable-string PrintableString (SIZE (1..30))\n * OPTIONAL, teletex-string TeletexString OPTIONAL }`. A TeletexString\n * component is unsupported.\n */\nfunction checkPdsParameter(source: Uint8Array, value: DerElement): GeneralNameContentCheck {\n\tif (value.tag !== SET) return MALFORMED;\n\tconst components = childrenOf(source, value);\n\tif (components.some((component) => component.tag === 0x14)) return UNSUPPORTED;\n\treturn check(\n\t\tcomponents.length <= 1 &&\n\t\t\tcomponents.every(\n\t\t\t\t(component) =>\n\t\t\t\t\tcomponent.tag === PRINTABLE_STRING && isPrintableString(component.value, bounds(1, 30)),\n\t\t\t),\n\t);\n}\n\n/**\n * `UnformattedPostalAddress ::= SET { printable-address SEQUENCE SIZE (1..6) OF\n * PrintableString (SIZE (1..30)) OPTIONAL, teletex-string TeletexString\n * OPTIONAL }`. A TeletexString component is unsupported.\n */\nfunction checkUnformattedPostalAddress(\n\tsource: Uint8Array,\n\tvalue: DerElement,\n): GeneralNameContentCheck {\n\tif (value.tag !== SET) return MALFORMED;\n\tconst components = childrenOf(source, value);\n\tif (components.some((component) => component.tag === 0x14)) return UNSUPPORTED;\n\tconst lines = components[0] === undefined ? [] : childrenOf(source, components[0]);\n\treturn check(\n\t\tcomponents.length <= 1 &&\n\t\t\t(components[0] === undefined ||\n\t\t\t\t(components[0].tag === SEQUENCE &&\n\t\t\t\t\tlines.length >= 1 &&\n\t\t\t\t\tlines.length <= 6 &&\n\t\t\t\t\tlines.every(\n\t\t\t\t\t\t(line) => line.tag === PRINTABLE_STRING && isPrintableString(line.value, bounds(1, 30)),\n\t\t\t\t\t))),\n\t);\n}\n\n/** `TerminalType ::= INTEGER (0..ub-integer-options)`, with ub-integer-options 256. */\nfunction checkTerminalType(_source: Uint8Array, value: DerElement): GeneralNameContentCheck {\n\tif (value.tag !== 0x02) return MALFORMED;\n\ttry {\n\t\tconst terminalType = decodeIntegerNumber(value.value);\n\t\treturn check(terminalType >= 0 && terminalType <= 256);\n\t} catch {\n\t\treturn MALFORMED;\n\t}\n}\n\n/**\n * Extension-attribute value schemas by `extension-attribute-type`. Types 2 to 6\n * are TeletexString forms and type 22 is extended-network-address; they and\n * any type RFC 5280 does not define are unsupported.\n */\nconst EXTENSION_ATTRIBUTE_VALUES: ReadonlyMap<number, FieldCheck> = new Map<number, FieldCheck>([\n\t[\n\t\t1,\n\t\t(_source, value) =>\n\t\t\tcheck(value.tag === PRINTABLE_STRING && isPrintableString(value.value, bounds(1, 64))),\n\t],\n\t[\n\t\t7,\n\t\t(_source, value) =>\n\t\t\tcheck(value.tag === PRINTABLE_STRING && isPrintableString(value.value, bounds(1, 16))),\n\t],\n\t[8, (_source, value) => checkCountryName(value)],\n\t[9, (_source, value) => check(isNumericOrPrintable(value, bounds(1, 16), bounds(1, 16)))],\n\t...[10, 11, 12, 13, 14, 15, 17, 18, 19, 20, 21].map((type): [number, FieldCheck] => [\n\t\ttype,\n\t\tcheckPdsParameter,\n\t]),\n\t[16, checkUnformattedPostalAddress],\n\t[23, checkTerminalType],\n]);\n\n/**\n * `ExtensionAttribute ::= SEQUENCE { extension-attribute-type [0] IMPLICIT\n * INTEGER (0..256), extension-attribute-value [1] ANY DEFINED BY\n * extension-attribute-type }`.\n */\nfunction checkExtensionAttribute(source: Uint8Array, element: DerElement): GeneralNameContentCheck {\n\tconst [type, wrapped, ...rest] = element.tag === SEQUENCE ? childrenOf(source, element) : [];\n\tif (type?.tag !== 0x80 || wrapped?.tag !== 0xa1 || rest.length > 0) return MALFORMED;\n\tlet typeNumber: number;\n\ttry {\n\t\ttypeNumber = decodeIntegerNumber(type.value);\n\t} catch {\n\t\treturn MALFORMED;\n\t}\n\tconst value = explicitInner(source, wrapped);\n\tif (typeNumber < 0 || typeNumber > 256 || value === undefined) return MALFORMED;\n\treturn EXTENSION_ATTRIBUTE_VALUES.get(typeNumber)?.(source, value) ?? UNSUPPORTED;\n}\n\n/** `ExtensionAttributes ::= SET SIZE (1..256) OF ExtensionAttribute`, DER-sorted. */\nfunction checkExtensionAttributes(\n\tsource: Uint8Array,\n\telement: DerElement,\n): GeneralNameContentCheck {\n\tconst attributes = childrenOf(source, element);\n\tconst sorted = attributes.every(\n\t\t(attribute, index) =>\n\t\t\tindex === 0 ||\n\t\t\tcompareEncodings(\n\t\t\t\tencodingOf(source, attributes[index - 1] ?? attribute),\n\t\t\t\tencodingOf(source, attribute),\n\t\t\t) <= 0,\n\t);\n\tif (attributes.length < 1 || attributes.length > 256 || !sorted) return MALFORMED;\n\treturn firstFailure(attributes.map((attribute) => checkExtensionAttribute(source, attribute)));\n}\n\n/**\n * `ORAddress ::= SEQUENCE { built-in-standard-attributes, built-in-domain-defined-attributes\n * OPTIONAL, extension-attributes OPTIONAL }`, given the children of the x400Address element.\n */\nexport function checkOrAddressFields(\n\tchildren: readonly DerElement[],\n\tsource: Uint8Array,\n): GeneralNameContentCheck {\n\tconst [standard, ...optional] = children;\n\tconst domainDefined = optional[0]?.tag === SEQUENCE ? optional[0] : undefined;\n\tconst extensions = optional.slice(domainDefined === undefined ? 0 : 1);\n\tconst [extensionAttributes, ...extra] = extensions;\n\tif (\n\t\tstandard?.tag !== SEQUENCE ||\n\t\textra.length > 0 ||\n\t\t(extensionAttributes !== undefined && extensionAttributes.tag !== SET)\n\t) {\n\t\treturn MALFORMED;\n\t}\n\treturn firstFailure([\n\t\tcheckBuiltInStandardAttributes(source, standard),\n\t\tdomainDefined === undefined\n\t\t\t? VALID\n\t\t\t: checkBuiltInDomainDefinedAttributes(source, domainDefined),\n\t\textensionAttributes === undefined\n\t\t\t? VALID\n\t\t\t: checkExtensionAttributes(source, extensionAttributes),\n\t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,KAAKA,IAAa,OAAOvC,MAAU,KAAA,IAAkBL,IAC/D0C,EAA2B,IAAIE,CAAU,CAAC,GAAG9B,GAAQT,CAAK,KAAKJ;AACvE;;AAGA,SAAS,yBACR,GACA,GAC0B;CAC1B,IAAM+B,IAAanB,EAAWC,GAAQL,CAAO,GACvCoC,IAASb,EAAW,OACxB,GAAW,MACXhB,MAAU,KACV,iBACC,WAAWF,GAAQkB,EAAWhB,IAAQ,MAAMmB,CAAS,GACrD,WAAWrB,GAAQqB,CAAS,CAC7B,KAAK,CACP;CAEA,OADIH,EAAW,SAAS,KAAKA,EAAW,SAAS,OAAO,CAACa,IAAe7C,IACjE,aAAagC,EAAW,KAAK,MAAc,wBAAwBlB,GAAQqB,CAAS,CAAC,CAAC;AAC9F;;;;;AAMA,SAAgB,qBACf,GACA,GAC0B;CAC1B,IAAM,CAACW,GAAU,GAAGC,KAAYnC,GAC1BoC,IAAgBD,EAAS,EAAE,EAAE,QAAQ,KAAWA,EAAS,KAAK,KAAA,GAE9D,CAACE,GAAqB,GAAGC,KADZH,EAAS,MAAMC,MAAkB,KAAA,IAAY,IAAI,CACnB;CAQjD,OANCF,GAAU,QAAQ,MAClBI,EAAM,SAAS,KACdD,MAAwB,KAAA,KAAaA,EAAoB,QAAQ,KAE3DjD,IAED,aAAa;EACnB,+BAA+Bc,GAAQgC,CAAQ;EAC/CE,MAAkB,KAAA,IACfjD,IACA,oCAAoCe,GAAQkC,CAAa;EAC5DC,MAAwB,KAAA,IACrBlD,IACA,yBAAyBe,GAAQmC,CAAmB;CACxD,CAAC;AACF"}
|
|
1
|
+
{"version":3,"file":"or-address.js","names":["childrenOf","decodeIntegerNumber","decodeString","isNumericStringContents","VALID","MALFORMED","UNSUPPORTED","min","max","valid","checks","result","value","size","element","numeric","printable","source","children","values","index","left","right","length","difference","BUILT_IN_STANDARD_ATTRIBUTES","inner","_source","BUILT_IN_STANDARD_ORDER","fields","limits","field","names","name","positions","position","attributes","attribute","type","rest","components","component","lines","line","terminalType","EXTENSION_ATTRIBUTE_VALUES","wrapped","typeNumber","sorted","standard","optional","domainDefined","extensionAttributes","extra"],"sources":["../../../src/internal/x509/or-address.ts"],"sourcesContent":["/**\n * RFC 5280 Appendix A.1 ORAddress schema validation for x400Address builder\n * input. The module is `DEFINITIONS EXPLICIT TAGS`, so only the fields marked\n * IMPLICIT replace their underlying tag.\n *\n * @module\n */\n\nimport {\n\tchildrenOf,\n\tdecodeIntegerNumber,\n\tdecodeString,\n\tisNumericStringContents,\n} from '#micro509/internal/asn1/asn1';\nimport type { DerElement } from '#micro509/internal/asn1/der';\nimport type { GeneralNameContentCheck } from '#micro509/internal/x509/general-name-profile';\n\nconst VALID: GeneralNameContentCheck = { ok: true };\nconst MALFORMED: GeneralNameContentCheck = { ok: false, reason: 'malformed' };\nconst UNSUPPORTED: GeneralNameContentCheck = { ok: false, reason: 'unsupported' };\n\nconst NUMERIC_STRING = 0x12;\nconst PRINTABLE_STRING = 0x13;\nconst SEQUENCE = 0x30;\nconst SET = 0x31;\n\n/** A string bound in characters, inclusive. */\ninterface Bounds {\n\treadonly min: number;\n\treadonly max: number;\n}\n\nfunction bounds(min: number, max: number): Bounds {\n\treturn { min, max };\n}\n\nfunction check(valid: boolean): GeneralNameContentCheck {\n\treturn valid ? VALID : MALFORMED;\n}\n\nfunction firstFailure(checks: readonly GeneralNameContentCheck[]): GeneralNameContentCheck {\n\treturn checks.find((result) => !result.ok) ?? VALID;\n}\n\nfunction isNumericString(value: Uint8Array, size: Bounds): boolean {\n\treturn value.length >= size.min && value.length <= size.max && isNumericStringContents(value);\n}\n\nfunction isPrintableString(value: Uint8Array, size: Bounds): boolean {\n\tif (value.length < size.min || value.length > size.max) {\n\t\treturn false;\n\t}\n\ttry {\n\t\tdecodeString(PRINTABLE_STRING, value);\n\t\treturn true;\n\t} catch {\n\t\treturn false;\n\t}\n}\n\n/** A universal NumericString or PrintableString element within its CHOICE bounds. */\nfunction isNumericOrPrintable(element: DerElement, numeric: Bounds, printable: Bounds): boolean {\n\treturn element.tag === NUMERIC_STRING\n\t\t? isNumericString(element.value, numeric)\n\t\t: element.tag === PRINTABLE_STRING && isPrintableString(element.value, printable);\n}\n\n/** The single element an explicit tag wraps, or `undefined`. */\nfunction explicitInner(source: Uint8Array, element: DerElement): DerElement | undefined {\n\tconst children = childrenOf(source, element);\n\treturn children.length === 1 ? children[0] : undefined;\n}\n\n/** DER orders SET components by ascending tag and SET OF members by ascending encoding. */\nfunction isAscending(values: readonly number[]): boolean {\n\treturn values.every((value, index) => index === 0 || (values[index - 1] ?? value) < value);\n}\n\nfunction compareEncodings(left: Uint8Array, right: Uint8Array): number {\n\tconst length = Math.min(left.length, right.length);\n\tfor (let index = 0; index < length; index += 1) {\n\t\tconst difference = (left[index] ?? 0) - (right[index] ?? 0);\n\t\tif (difference !== 0) return difference;\n\t}\n\treturn left.length - right.length;\n}\n\nfunction encodingOf(source: Uint8Array, element: DerElement): Uint8Array {\n\treturn source.subarray(element.start - element.headerLength, element.end);\n}\n\n/** RFC 5280 A.1: `CountryName ::= [APPLICATION 1] CHOICE`, also the physical-delivery-country-name CHOICE. */\nfunction checkCountryName(element: DerElement | undefined): GeneralNameContentCheck {\n\treturn check(element !== undefined && isNumericOrPrintable(element, bounds(3, 3), bounds(2, 2)));\n}\n\ntype FieldCheck = (source: Uint8Array, element: DerElement) => GeneralNameContentCheck;\n\n/** BuiltInStandardAttributes fields in schema order, keyed by their encoded tag. */\nconst BUILT_IN_STANDARD_ATTRIBUTES: ReadonlyMap<number, FieldCheck> = new Map<number, FieldCheck>([\n\t[0x61, (source, element) => checkCountryName(explicitInner(source, element))],\n\t[\n\t\t0x62,\n\t\t(source, element) => {\n\t\t\tconst inner = explicitInner(source, element);\n\t\t\treturn check(\n\t\t\t\tinner !== undefined && isNumericOrPrintable(inner, bounds(0, 16), bounds(0, 16)),\n\t\t\t);\n\t\t},\n\t],\n\t[0x80, (_source, element) => check(isNumericString(element.value, bounds(1, 16)))],\n\t[0x81, (_source, element) => check(isPrintableString(element.value, bounds(1, 24)))],\n\t[\n\t\t0xa2,\n\t\t(source, element) => {\n\t\t\tconst inner = explicitInner(source, element);\n\t\t\treturn check(\n\t\t\t\tinner !== undefined && isNumericOrPrintable(inner, bounds(1, 16), bounds(1, 16)),\n\t\t\t);\n\t\t},\n\t],\n\t[0x83, (_source, element) => check(isPrintableString(element.value, bounds(1, 64)))],\n\t[0x84, (_source, element) => check(isNumericString(element.value, bounds(1, 32)))],\n\t[0xa5, checkPersonalName],\n\t[0xa6, checkOrganizationalUnitNames],\n]);\n\nconst BUILT_IN_STANDARD_ORDER: readonly number[] = [...BUILT_IN_STANDARD_ATTRIBUTES.keys()];\n\n/**\n * `PersonalName ::= SET { surname [0], given-name [1] OPTIONAL, initials [2]\n * OPTIONAL, generation-qualifier [3] OPTIONAL }`, each an IMPLICIT\n * PrintableString of 1 to 40, 16, 5 and 3 characters.\n */\nfunction checkPersonalName(source: Uint8Array, element: DerElement): GeneralNameContentCheck {\n\tconst fields = childrenOf(source, element);\n\tconst limits = new Map([\n\t\t[0x80, 40],\n\t\t[0x81, 16],\n\t\t[0x82, 5],\n\t\t[0x83, 3],\n\t]);\n\treturn check(\n\t\tfields[0]?.tag === 0x80 &&\n\t\t\tisAscending(fields.map((field) => field.tag)) &&\n\t\t\tfields.every((field) => {\n\t\t\t\tconst max = limits.get(field.tag);\n\t\t\t\treturn max !== undefined && isPrintableString(field.value, bounds(1, max));\n\t\t\t}),\n\t);\n}\n\n/** `OrganizationalUnitNames ::= SEQUENCE SIZE (1..4) OF PrintableString (SIZE (1..32))`. */\nfunction checkOrganizationalUnitNames(\n\tsource: Uint8Array,\n\telement: DerElement,\n): GeneralNameContentCheck {\n\tconst names = childrenOf(source, element);\n\treturn check(\n\t\tnames.length >= 1 &&\n\t\t\tnames.length <= 4 &&\n\t\t\tnames.every(\n\t\t\t\t(name) => name.tag === PRINTABLE_STRING && isPrintableString(name.value, bounds(1, 32)),\n\t\t\t),\n\t);\n}\n\nfunction checkBuiltInStandardAttributes(\n\tsource: Uint8Array,\n\telement: DerElement,\n): GeneralNameContentCheck {\n\tconst fields = childrenOf(source, element);\n\tconst positions = fields.map((field) => BUILT_IN_STANDARD_ORDER.indexOf(field.tag));\n\tif (positions.some((position) => position < 0) || !isAscending(positions)) {\n\t\treturn MALFORMED;\n\t}\n\treturn firstFailure(\n\t\tfields.map(\n\t\t\t(field) => BUILT_IN_STANDARD_ATTRIBUTES.get(field.tag)?.(source, field) ?? MALFORMED,\n\t\t),\n\t);\n}\n\n/**\n * `BuiltInDomainDefinedAttributes ::= SEQUENCE SIZE (1..4) OF SEQUENCE { type\n * PrintableString (SIZE (1..8)), value PrintableString (SIZE (1..128)) }`.\n */\nfunction checkBuiltInDomainDefinedAttributes(\n\tsource: Uint8Array,\n\telement: DerElement,\n): GeneralNameContentCheck {\n\tconst attributes = childrenOf(source, element);\n\treturn check(\n\t\tattributes.length >= 1 &&\n\t\t\tattributes.length <= 4 &&\n\t\t\tattributes.every((attribute) => {\n\t\t\t\tconst [type, value, ...rest] =\n\t\t\t\t\tattribute.tag === SEQUENCE ? childrenOf(source, attribute) : [];\n\t\t\t\treturn (\n\t\t\t\t\trest.length === 0 &&\n\t\t\t\t\ttype?.tag === PRINTABLE_STRING &&\n\t\t\t\t\tvalue?.tag === PRINTABLE_STRING &&\n\t\t\t\t\tisPrintableString(type.value, bounds(1, 8)) &&\n\t\t\t\t\tisPrintableString(value.value, bounds(1, 128))\n\t\t\t\t);\n\t\t\t}),\n\t);\n}\n\n/**\n * `PDSParameter ::= SET { printable-string PrintableString (SIZE (1..30))\n * OPTIONAL, teletex-string TeletexString OPTIONAL }`. A TeletexString\n * component is unsupported.\n */\nfunction checkPdsParameter(source: Uint8Array, value: DerElement): GeneralNameContentCheck {\n\tif (value.tag !== SET) return MALFORMED;\n\tconst components = childrenOf(source, value);\n\tif (components.some((component) => component.tag === 0x14)) return UNSUPPORTED;\n\treturn check(\n\t\tcomponents.length <= 1 &&\n\t\t\tcomponents.every(\n\t\t\t\t(component) =>\n\t\t\t\t\tcomponent.tag === PRINTABLE_STRING && isPrintableString(component.value, bounds(1, 30)),\n\t\t\t),\n\t);\n}\n\n/**\n * `UnformattedPostalAddress ::= SET { printable-address SEQUENCE SIZE (1..6) OF\n * PrintableString (SIZE (1..30)) OPTIONAL, teletex-string TeletexString\n * OPTIONAL }`. A TeletexString component is unsupported.\n */\nfunction checkUnformattedPostalAddress(\n\tsource: Uint8Array,\n\tvalue: DerElement,\n): GeneralNameContentCheck {\n\tif (value.tag !== SET) return MALFORMED;\n\tconst components = childrenOf(source, value);\n\tif (components.some((component) => component.tag === 0x14)) return UNSUPPORTED;\n\tconst lines = components[0] === undefined ? [] : childrenOf(source, components[0]);\n\treturn check(\n\t\tcomponents.length <= 1 &&\n\t\t\t(components[0] === undefined ||\n\t\t\t\t(components[0].tag === SEQUENCE &&\n\t\t\t\t\tlines.length >= 1 &&\n\t\t\t\t\tlines.length <= 6 &&\n\t\t\t\t\tlines.every(\n\t\t\t\t\t\t(line) => line.tag === PRINTABLE_STRING && isPrintableString(line.value, bounds(1, 30)),\n\t\t\t\t\t))),\n\t);\n}\n\n/** `TerminalType ::= INTEGER (0..ub-integer-options)`, with ub-integer-options 256. */\nfunction checkTerminalType(_source: Uint8Array, value: DerElement): GeneralNameContentCheck {\n\tif (value.tag !== 0x02) return MALFORMED;\n\ttry {\n\t\tconst terminalType = decodeIntegerNumber(value.value);\n\t\treturn check(terminalType >= 0 && terminalType <= 256);\n\t} catch {\n\t\treturn MALFORMED;\n\t}\n}\n\n/**\n * Extension-attribute value schemas by `extension-attribute-type`. Types 2 to 6\n * are TeletexString forms and type 22 is extended-network-address; they and\n * any type RFC 5280 does not define are unsupported.\n */\nconst EXTENSION_ATTRIBUTE_VALUES: ReadonlyMap<number, FieldCheck> = new Map<number, FieldCheck>([\n\t[\n\t\t1,\n\t\t(_source, value) =>\n\t\t\tcheck(value.tag === PRINTABLE_STRING && isPrintableString(value.value, bounds(1, 64))),\n\t],\n\t[\n\t\t7,\n\t\t(_source, value) =>\n\t\t\tcheck(value.tag === PRINTABLE_STRING && isPrintableString(value.value, bounds(1, 16))),\n\t],\n\t[8, (_source, value) => checkCountryName(value)],\n\t[9, (_source, value) => check(isNumericOrPrintable(value, bounds(1, 16), bounds(1, 16)))],\n\t...[10, 11, 12, 13, 14, 15, 17, 18, 19, 20, 21].map((type): [number, FieldCheck] => [\n\t\ttype,\n\t\tcheckPdsParameter,\n\t]),\n\t[16, checkUnformattedPostalAddress],\n\t[23, checkTerminalType],\n]);\n\n/**\n * `ExtensionAttribute ::= SEQUENCE { extension-attribute-type [0] IMPLICIT\n * INTEGER (0..256), extension-attribute-value [1] ANY DEFINED BY\n * extension-attribute-type }`.\n */\nfunction checkExtensionAttribute(source: Uint8Array, element: DerElement): GeneralNameContentCheck {\n\tconst [type, wrapped, ...rest] = element.tag === SEQUENCE ? childrenOf(source, element) : [];\n\tif (type?.tag !== 0x80 || wrapped?.tag !== 0xa1 || rest.length > 0) return MALFORMED;\n\tlet typeNumber: number;\n\ttry {\n\t\ttypeNumber = decodeIntegerNumber(type.value);\n\t} catch {\n\t\treturn MALFORMED;\n\t}\n\tconst value = explicitInner(source, wrapped);\n\tif (typeNumber < 0 || typeNumber > 256 || value === undefined) return MALFORMED;\n\treturn EXTENSION_ATTRIBUTE_VALUES.get(typeNumber)?.(source, value) ?? UNSUPPORTED;\n}\n\n/** `ExtensionAttributes ::= SET SIZE (1..256) OF ExtensionAttribute`, DER-sorted. */\nfunction checkExtensionAttributes(\n\tsource: Uint8Array,\n\telement: DerElement,\n): GeneralNameContentCheck {\n\tconst attributes = childrenOf(source, element);\n\tconst sorted = attributes.every(\n\t\t(attribute, index) =>\n\t\t\tindex === 0 ||\n\t\t\tcompareEncodings(\n\t\t\t\tencodingOf(source, attributes[index - 1] ?? attribute),\n\t\t\t\tencodingOf(source, attribute),\n\t\t\t) <= 0,\n\t);\n\tif (attributes.length < 1 || attributes.length > 256 || !sorted) return MALFORMED;\n\treturn firstFailure(attributes.map((attribute) => checkExtensionAttribute(source, attribute)));\n}\n\n/**\n * `ORAddress ::= SEQUENCE { built-in-standard-attributes, built-in-domain-defined-attributes\n * OPTIONAL, extension-attributes OPTIONAL }`, given the children of the x400Address element.\n */\nexport function checkOrAddressFields(\n\tchildren: readonly DerElement[],\n\tsource: Uint8Array,\n): GeneralNameContentCheck {\n\tconst [standard, ...optional] = children;\n\tconst domainDefined = optional[0]?.tag === SEQUENCE ? optional[0] : undefined;\n\tconst extensions = optional.slice(domainDefined === undefined ? 0 : 1);\n\tconst [extensionAttributes, ...extra] = extensions;\n\tif (\n\t\tstandard?.tag !== SEQUENCE ||\n\t\textra.length > 0 ||\n\t\t(extensionAttributes !== undefined && extensionAttributes.tag !== SET)\n\t) {\n\t\treturn MALFORMED;\n\t}\n\treturn firstFailure([\n\t\tcheckBuiltInStandardAttributes(source, standard),\n\t\tdomainDefined === undefined\n\t\t\t? VALID\n\t\t\t: checkBuiltInDomainDefinedAttributes(source, domainDefined),\n\t\textensionAttributes === undefined\n\t\t\t? VALID\n\t\t\t: checkExtensionAttributes(source, extensionAttributes),\n\t]);\n}\n"],"mappings":";;;;;;;;;AAiBA,MAAMI,IAAiC,EAAE,IAAI,GAAK,GAC5CC,IAAqC;CAAE,IAAI;CAAO,QAAQ;AAAY,GACtEC,IAAuC;CAAE,IAAI;CAAO,QAAQ;AAAc;AAahF,SAAS,OAAOC,GAAaC,GAAqB;CACjD,OAAO;EAAED;EAAKC;CAAI;AACnB;AAEA,SAAS,MAAMC,GAAyC;CACvD,OAAOA,IAAQL,IAAQC;AACxB;AAEA,SAAS,aAAaK,GAAqE;CAC1F,OAAOA,EAAO,MAAMC,MAAW,CAACA,EAAO,EAAE,KAAKP;AAC/C;AAEA,SAAS,gBAAgBQ,GAAmBC,GAAuB;CAClE,OAAOD,EAAM,UAAUC,EAAK,OAAOD,EAAM,UAAUC,EAAK,OAAOV,EAAwBS,CAAK;AAC7F;AAEA,SA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IACjE,aAAa+B,EAAW,KAAKC,MAAc,wBAAwBpB,GAAQoB,CAAS,CAAC,CAAC;AAC9F;;;;;AAMA,SAAgB,qBACfnB,GACAD,GAC0B;CAC1B,IAAM,CAACgC,GAAU,GAAGC,KAAYhC,GAC1BiC,IAAgBD,EAAS,EAAE,EAAE,QAAQ,KAAWA,EAAS,KAAK,KAAA,GAE9D,CAACE,GAAqB,GAAGC,KADZH,EAAS,MAAMC,MAAkB,KAAA,IAAY,IAAI,CACnB;CAQjD,OANCF,GAAU,QAAQ,MAClBI,EAAM,SAAS,KACdD,MAAwB,KAAA,KAAaA,EAAoB,QAAQ,KAE3D/C,IAED,aAAa;EACnB,+BAA+BY,GAAQgC,CAAQ;EAC/CE,MAAkB,KAAA,IACf/C,IACA,oCAAoCa,GAAQkC,CAAa;EAC5DC,MAAwB,KAAA,IACrBhD,IACA,yBAAyBa,GAAQmC,CAAmB;CACxD,CAAC;AACF"}
|
|
@@ -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,gBAAgBI,GAA2B;CAC1D,OAAOJ,EAAOI,CAAK;AACpB;;AAGA,SAAgB,gBAAgBC,GAAuC;CACtE,OAAOJ,EAAOI,CAAK;AACpB"}
|
package/dist/jose/errors.d.ts
CHANGED
|
@@ -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>;
|
package/dist/jose/errors.js.map
CHANGED
|
@@ -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":";;
|
|
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,YACfC,GACAC,GACAC,GACyB;CACzB,OAAOH,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>>;
|
package/dist/jose/jwe.js
ADDED
|
@@ -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":["getCrypto","base64UrlDecode","base64UrlEncode","snapshotJsonData","isJsonArray","isJsonObject","joseFailure","decodeJsonObject","resolveJoseLimits","validRsaPublicExponent","rethrowIfInvariant","successResult","key","type","algorithm","members","names","seen","name","critical","input","limits","snapshot","source","completed","header","bytes","length","plaintext","crypto","cek","iv","encryptedKey","aes","encrypted","error","segment","maxBytes","decoded","token","segments","protectedSegment","encryptedKeySegment","ivSegment","ciphertextSegment","tagSegment","protectedBytes","object","ciphertext","tag","parsed","encryptedKeyBytes","unwrapFailed","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,SACRY,GACAC,GACuC;CACvC,IACC,EAAED,aAAe,cACjBA,EAAI,SAASC,KACbD,EAAI,UAAU,SAAS,cACvB,CAACA,EAAI,OAAO,SAASC,MAAS,WAAW,YAAY,SAAS,GAE9D,OAAOP,EACN,kBACA,8DACD;CAED,IAAMQ,IAAYF,EAAI;CAyBtB,OAvBC,EAAE,UAAUE,MACZ,OAAOA,EAAU,QAAS,YAC1BA,EAAU,SAAS,QACnB,EAAE,UAAUA,EAAU,SACtBA,EAAU,KAAK,SAAS,YAEjBR,EAAY,kBAAkB,mCAAmC,IAGxE,EAAE,mBAAmBQ,MACrB,OAAOA,EAAU,iBAAkB,YACnC,CAAC,OAAO,cAAcA,EAAU,aAAa,KAC7CA,EAAU,gBAAgB,QAC1BA,EAAU,gBAAgB,QAC1B,EAAE,oBAAoBA,MACtB,EAAEA,EAAU,0BAA0B,eACtC,CAACL,EAAuBK,EAAU,cAAc,IAEzCR,EACN,kBACA,sEACD,IAEMK,EAAc,KAAK,KAAKG,EAAU,gBAAgB,CAAC,CAAC;AAC5D;AAEA,SAAS,cAAcC,GAA0D;CAChF,IAAI,CAAC,OAAO,OAAOA,GAAS,MAAM,GAAG,OAAOJ,EAAc,KAAA,CAAS;CACnE,IAAMK,IAAQD,EAAQ;CACtB,IAAI,CAACX,EAAYY,CAAK,KAAKA,EAAM,WAAW,G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AOK,EAAQ,YAAY3C,EAAI,KAAK,IADnDA;AAErB"}
|
package/dist/jose/jwks.d.ts
CHANGED
|
@@ -35,8 +35,21 @@ export interface RsaJwkEntry extends JwkEntryBase {
|
|
|
35
35
|
/** Base64url public exponent. */
|
|
36
36
|
readonly e: string;
|
|
37
37
|
}
|
|
38
|
+
/** An EC public key entry, with its curve and uncompressed affine coordinates. */
|
|
39
|
+
export interface EcJwkEntry extends JwkEntryBase {
|
|
40
|
+
/** Discriminant. */
|
|
41
|
+
readonly kind: "ec";
|
|
42
|
+
/** The curve identifier, retained even when unsupported. */
|
|
43
|
+
readonly crv: string;
|
|
44
|
+
/** Base64url fixed-width affine x coordinate. */
|
|
45
|
+
readonly x: string;
|
|
46
|
+
/** Base64url fixed-width affine y coordinate. */
|
|
47
|
+
readonly y: string;
|
|
48
|
+
}
|
|
49
|
+
/** Public key entries whose type this module can select. */
|
|
50
|
+
export type SupportedJwkEntry = RsaJwkEntry | EcJwkEntry;
|
|
38
51
|
/**
|
|
39
|
-
* An entry this module never selects: a `kty` other than `RSA`, or an entry with missing or
|
|
52
|
+
* An entry this module never selects: a `kty` other than `RSA` or `EC`, or an entry with missing or
|
|
40
53
|
* wrongly typed members (RFC 7517 §5). Kept so callers can inspect the whole set.
|
|
41
54
|
*/
|
|
42
55
|
export interface UnsupportedJwkEntry extends JwkEntryBase {
|
|
@@ -46,7 +59,7 @@ export interface UnsupportedJwkEntry extends JwkEntryBase {
|
|
|
46
59
|
readonly kty?: string;
|
|
47
60
|
}
|
|
48
61
|
/** One key of a JWK Set. */
|
|
49
|
-
export type JwkEntry =
|
|
62
|
+
export type JwkEntry = SupportedJwkEntry | UnsupportedJwkEntry;
|
|
50
63
|
/** A parsed JWK Set. */
|
|
51
64
|
export interface Jwks {
|
|
52
65
|
/** The keys, in document order. */
|
|
@@ -60,11 +73,21 @@ export type ParseJwksErrorCode = "jwks_malformed" | "limit_exceeded" | "invalid_
|
|
|
60
73
|
* Parses a JWK Set document.
|
|
61
74
|
*
|
|
62
75
|
* The document must be duplicate-free JSON with a `keys` array within `limits`. Keys with a `kty`
|
|
63
|
-
* other than `RSA`, and keys with missing or wrongly typed members, are kept as `unsupported`
|
|
76
|
+
* other than `RSA` or `EC`, and keys with missing or wrongly typed members, are kept as `unsupported`
|
|
64
77
|
* entries and never selected (RFC 7517 §5). A set that is not a duplicate-free object with a
|
|
65
78
|
* `keys` array of objects is `jwks_malformed`.
|
|
66
79
|
*/
|
|
67
80
|
export declare function parseJwks(input: string | Uint8Array, limits?: Partial<JwksLimits>): JoseResult<Jwks, ParseJwksErrorCode>;
|
|
81
|
+
/**
|
|
82
|
+
* Validates already parsed, plain JSON data and owns a detached deep snapshot of it.
|
|
83
|
+
*
|
|
84
|
+
* Prefer {@linkcode parseJwks} for untrusted transport text: an object cannot reveal lost duplicate
|
|
85
|
+
* member names or invalid original UTF-8. No getters or `toJSON` are called. Cycles, non-JSON values,
|
|
86
|
+
* sparse arrays, accessors, symbols and custom prototypes are refused. `maxBytes` bounds the UTF-8
|
|
87
|
+
* size of the compact JSON data spelling, not the original transport bytes. Depth and node limits
|
|
88
|
+
* match the text parser. A changed source object requires a new validation and resolver instance.
|
|
89
|
+
*/
|
|
90
|
+
export declare function validateJwks(value: unknown, limits?: Partial<JwksLimits>): JoseResult<Jwks, ParseJwksErrorCode>;
|
|
68
91
|
/** What {@linkcode selectJwk} matches against. */
|
|
69
92
|
export interface JwkSelector {
|
|
70
93
|
/** The algorithm the token uses. */
|
|
@@ -75,19 +98,24 @@ export interface JwkSelector {
|
|
|
75
98
|
/**
|
|
76
99
|
* Selects the one key of a set that can verify `selector`.
|
|
77
100
|
*
|
|
78
|
-
* Keys are filtered by `kid` (when the token has one), key type, `use`, `key_ops`, `alg` and RSA
|
|
101
|
+
* Keys are filtered by `kid` (when the token has one), key type, `use`, `key_ops`, `alg` and RSA/EC
|
|
79
102
|
* parameters. No match is `key_not_found`, or `key_unsuitable` when `kid` matched only keys that
|
|
80
103
|
* fail the other checks. More than one match is `ambiguous_key`: a token without `kid` therefore
|
|
81
104
|
* resolves only against a set with a single usable key.
|
|
82
105
|
*/
|
|
83
|
-
export declare function selectJwk(jwks: Jwks, selector: JwkSelector): JoseResult<
|
|
84
|
-
/**
|
|
85
|
-
|
|
106
|
+
export declare function selectJwk(jwks: Jwks, selector: JwkSelector): JoseResult<SupportedJwkEntry, Exclude<KeyResolutionErrorCode, "jwks_unavailable" | "aborted">>;
|
|
107
|
+
/**
|
|
108
|
+
* Imports a selected entry as a verify-only key for `algorithm`. The default remains RS256;
|
|
109
|
+
* pass the selected algorithm explicitly for every other RSA hash or ECDSA curve.
|
|
110
|
+
*/
|
|
111
|
+
export declare function importJwkEntry(entry: SupportedJwkEntry, algorithm?: JwsAlgorithm): Promise<JoseResult<CryptoKey, "key_unsuitable">>;
|
|
86
112
|
/**
|
|
87
113
|
* Creates a key resolver over a fixed JWK Set.
|
|
88
114
|
*
|
|
89
115
|
* The resolver selects with {@linkcode selectJwk} and imports each key once, so repeated
|
|
90
|
-
* verifications reuse the same `CryptoKey`.
|
|
116
|
+
* verifications reuse the same `CryptoKey`. Keep one resolver per trusted source/snapshot and
|
|
117
|
+
* replace it when that snapshot changes so removed keys do not survive rotation.
|
|
118
|
+
*
|
|
119
|
+
* @see https://micro509.kjanat.dev/guide/jose-cache for application-owned raw JWKS caches.
|
|
91
120
|
*/
|
|
92
|
-
export declare function createJwksKeyResolver(jwks: Jwks): JwsKeyResolver;
|
|
93
|
-
//# sourceMappingURL=jwks.d.ts.map
|
|
121
|
+
export declare function createJwksKeyResolver(jwks: Jwks): JwsKeyResolver;
|