unjwt 0.6.1 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,31 +1,3 @@
1
- import { L as JWKSet, N as JWKLookupFunction, d as JWSHeaderParameters, f as JWSProtectedHeader, g as JOSEPayload, h as JWSVerifyResult, m as JWSVerifyOptions, nt as JWK_Private, p as JWSSignOptions, rt as JWK_Public, u as JWSAlgorithm, ut as JWK_Symmetric } from "../_chunks/index.mjs";
2
- import { i as isJWTError, n as JWTErrorCauseMap, r as JWTErrorCode, t as JWTError } from "../_chunks/error.mjs";
3
-
4
- //#region src/core/jws.d.ts
5
- /**
6
- * Creates a JWS (JSON Web Signature) in Compact Serialization format.
7
- *
8
- * @param payload The payload to sign. Can be a string, Uint8Array, or an object (which will be JSON stringified).
9
- * @param key The signing key (CryptoKey, JWK, or raw symmetric key as Uint8Array).
10
- * @param options Signing options, including the algorithm (`alg`) and protected header parameters.
11
- * @returns A Promise resolving to the JWS Compact Serialization string.
12
- */
13
- declare function sign(payload: JOSEPayload, key: JWK_Symmetric | JWK_Private, options?: JWSSignOptions): Promise<string>;
14
- declare function sign(payload: JOSEPayload, key: CryptoKey | Uint8Array<ArrayBuffer>, options: JWSSignOptions & {
15
- alg: JWSAlgorithm;
16
- }): Promise<string>;
17
- /**
18
- * Verifies a JWS (JSON Web Signature) in Compact Serialization format.
19
- *
20
- * @param jws The JWS Compact Serialization string.
21
- * @param key The verification key (CryptoKey, JWK, JWKSet, raw symmetric key as Uint8Array, or a function resolving the key or set).
22
- * @param options Verification options, such as allowed algorithms.
23
- * @returns A Promise resolving to an object containing the verified payload and protected header.
24
- * @throws If the JWS is invalid, signature verification fails, or options are not met.
25
- */
26
- declare function verify<T extends JOSEPayload>(jws: string, key: CryptoKey | JWKSet | JWK_Public | JWK_Symmetric | Uint8Array<ArrayBuffer> | JWKLookupFunction, options?: JWSVerifyOptions): Promise<JWSVerifyResult<T>>;
27
- declare function verify(jws: string, key: CryptoKey | JWKSet | JWK_Public | JWK_Symmetric | Uint8Array<ArrayBuffer> | JWKLookupFunction, options: JWSVerifyOptions & {
28
- forceUint8Array: true;
29
- }): Promise<JWSVerifyResult<Uint8Array<ArrayBuffer>>>;
30
- //#endregion
31
- export { JWSAlgorithm, JWSHeaderParameters, JWSProtectedHeader, JWSSignOptions, JWSVerifyOptions, JWSVerifyResult, JWTError, type JWTErrorCauseMap, type JWTErrorCode, isJWTError, sign, verify };
1
+ import { A as JWSMultiSigner, B as JWSVerifyResult, C as JWSAsymmetricPrivateJWK, D as JWSGeneralSignature, E as JWSGeneralSerialization, F as JWSProtectedHeader, G as isJWTError, H as JWTError, I as JWSSignJWK, L as JWSSignOptions, M as JWSMultiVerifyOptions, N as JWSMultiVerifyOutcome, O as JWSHeaderParameters, P as JWSMultiVerifyResult, R as JWSVerifyJWK, S as JWSAlgorithm, T as JWSFlattenedSerialization, U as JWTErrorCauseMap, W as JWTErrorCode, j as JWSMultiVerifyAllOptions, k as JWSMultiSignOptions, w as JWSAsymmetricPublicJWK, z as JWSVerifyOptions } from "../_chunks/index.mjs";
2
+ import { a as verifyMulti, i as signMulti, n as verify, o as verifyMultiAll, r as generalToFlattenedJWS, t as sign } from "../_chunks/jws.mjs";
3
+ export { JWSAlgorithm, JWSAsymmetricPrivateJWK, JWSAsymmetricPublicJWK, JWSFlattenedSerialization, JWSGeneralSerialization, JWSGeneralSignature, JWSHeaderParameters, JWSMultiSignOptions, JWSMultiSigner, JWSMultiVerifyAllOptions, JWSMultiVerifyOptions, JWSMultiVerifyOutcome, JWSMultiVerifyResult, JWSProtectedHeader, JWSSignJWK, JWSSignOptions, JWSVerifyJWK, JWSVerifyOptions, JWSVerifyResult, JWTError, JWTErrorCauseMap, JWTErrorCode, generalToFlattenedJWS, isJWTError, sign, signMulti, verify, verifyMulti, verifyMultiAll };
package/dist/core/jws.mjs CHANGED
@@ -1,104 +1,3 @@
1
- import { A as validateCriticalHeadersJWS, M as JWTError, N as isJWTError, S as computeJwtTimeClaims, T as decodePayloadFromB64UrlSegment, _ as textDecoder, a as base64UrlEncode, b as applyTypCtyDefaults, d as isJWKSet, i as base64UrlDecode, j as validateJwtClaims, u as isJWK, v as textEncoder, y as sanitizeObject } from "../_chunks/utils.mjs";
2
- import { D as verify$1, E as sign$1 } from "../_chunks/_crypto.mjs";
3
- import { getJWKsFromSet, importKey } from "./jwk.mjs";
4
- //#region src/core/jws.ts
5
- async function sign(payload, key, options = {}) {
6
- const { protectedHeader: userHeader } = options;
7
- let { alg } = options;
8
- if (!alg) if (isJWK(key) && key.alg) alg = key.alg;
9
- else throw new TypeError("JWS \"alg\" (Algorithm) must be provided in options");
10
- if (alg === "none") throw new JWTError("\"none\" is not a valid signing algorithm", "ERR_JWS_ALG_NOT_ALLOWED");
11
- const signingKey = await _resolveSigningKey(alg, await importKey(key, alg), "sign");
12
- const protectedHeader = _buildJWSHeader(alg, key, userHeader, payload);
13
- const computedPayload = computeJwtTimeClaims(payload, protectedHeader.typ, options.expiresIn, options.currentDate);
14
- const protectedHeaderEncoded = base64UrlEncode(JSON.stringify(protectedHeader));
15
- let payloadBytes;
16
- if (payload instanceof Uint8Array) payloadBytes = payload;
17
- else if (typeof payload === "string") payloadBytes = textEncoder.encode(payload);
18
- else if (typeof payload === "object" && payload !== null) payloadBytes = textEncoder.encode(JSON.stringify(computedPayload || payload));
19
- else throw new TypeError("Payload must be a string, Uint8Array, or a JSON-serializable object.");
20
- const signingInputString = `${protectedHeaderEncoded}.${protectedHeader.b64 !== false ? base64UrlEncode(payloadBytes) : textDecoder.decode(payloadBytes)}`;
21
- const signingInputBytes = textEncoder.encode(signingInputString);
22
- return `${signingInputString}.${base64UrlEncode(await sign$1(alg, signingKey, signingInputBytes))}`;
23
- }
24
- async function verify(jws, key, options = {}) {
25
- const parts = jws.split(".");
26
- if (parts.length !== 3) throw new JWTError("Invalid JWS: Must contain three parts separated by dots.", "ERR_JWS_INVALID");
27
- const [protectedHeaderEncoded, payloadEncoded, signatureEncoded] = parts;
28
- let protectedHeader;
29
- try {
30
- const protectedHeaderString = base64UrlDecode(protectedHeaderEncoded);
31
- protectedHeader = sanitizeObject(JSON.parse(protectedHeaderString));
32
- } catch {
33
- throw new JWTError("Invalid JWS: Protected header could not be decoded.", "ERR_JWS_INVALID");
34
- }
35
- if (!protectedHeader || typeof protectedHeader !== "object" || !protectedHeader.alg) throw new JWTError("Invalid JWS: Protected header must be an object with an \"alg\" property.", "ERR_JWS_INVALID");
36
- const alg = protectedHeader.alg;
37
- if (options.algorithms && !options.algorithms.includes(alg)) throw new JWTError(`Algorithm not allowed: ${alg}`, "ERR_JWS_ALG_NOT_ALLOWED");
38
- if (options.typ && protectedHeader.typ !== options.typ) throw new JWTError(`Invalid JWS: "typ" (Type) Header Parameter mismatch. Expected "${options.typ}", got "${protectedHeader.typ}".`, "ERR_JWS_INVALID");
39
- let signatureBytes;
40
- try {
41
- signatureBytes = base64UrlDecode(signatureEncoded, false);
42
- } catch {
43
- throw new JWTError("Invalid JWS: Signature could not be decoded.", "ERR_JWS_INVALID");
44
- }
45
- const keyInput = typeof key === "function" ? await key(protectedHeader, jws) : key;
46
- const signingInputBytes = textEncoder.encode(`${protectedHeaderEncoded}.${payloadEncoded}`);
47
- if (isJWKSet(keyInput)) {
48
- const candidates = getJWKsFromSet(keyInput, _buildJWSSetFilter(protectedHeader));
49
- if (candidates.length === 0) throw new JWTError(`No key found in JWK Set${protectedHeader.kid ? ` with kid "${protectedHeader.kid}"` : ""}.`, "ERR_JWK_KEY_NOT_FOUND");
50
- let verified = false;
51
- for (const candidate of candidates) try {
52
- if (await verify$1(alg, await _resolveSigningKey(alg, await importKey(candidate, alg), "verify"), signatureBytes, signingInputBytes)) {
53
- verified = true;
54
- break;
55
- }
56
- } catch {}
57
- if (!verified) throw new JWTError("JWS signature verification failed.", "ERR_JWS_SIGNATURE_INVALID");
58
- } else if (!await verify$1(alg, await _resolveSigningKey(alg, await importKey(keyInput, alg), "verify"), signatureBytes, signingInputBytes)) throw new JWTError("JWS signature verification failed.", "ERR_JWS_SIGNATURE_INVALID");
59
- const useB64 = protectedHeader.b64 !== false;
60
- let payload;
61
- try {
62
- payload = useB64 ? decodePayloadFromB64UrlSegment(payloadEncoded, protectedHeader, options.forceUint8Array) : options.forceUint8Array ? textEncoder.encode(payloadEncoded) : payloadEncoded;
63
- } catch (error_) {
64
- throw new JWTError(`Invalid JWS: Payload decoding failed (${error_ instanceof Error ? error_.message : error_})`, "ERR_JWS_INVALID");
65
- }
66
- validateCriticalHeadersJWS(protectedHeader, options.recognizedHeaders);
67
- if (payload && typeof payload === "object" && options.validateClaims !== false && (options.validateClaims === true || protectedHeader.typ?.toLowerCase().includes("jwt")) && !options.forceUint8Array && !(payload instanceof Uint8Array)) validateJwtClaims(payload, options);
68
- return {
69
- payload,
70
- protectedHeader
71
- };
72
- }
73
- async function _resolveSigningKey(alg, key, usage) {
74
- if (key instanceof Uint8Array) {
75
- const minBytes = Number.parseInt(alg.slice(2), 10) / 8;
76
- if (key.length < minBytes) throw new JWTError(`${alg} requires a key of at least ${minBytes} bytes`, "ERR_JWK_INVALID");
77
- return crypto.subtle.importKey("raw", key, {
78
- name: "HMAC",
79
- hash: `SHA-${alg.slice(-3)}`
80
- }, false, [usage]);
81
- }
82
- if (alg.startsWith("RS") || alg.startsWith("PS")) {
83
- const { modulusLength } = key.algorithm;
84
- if (typeof modulusLength !== "number" || modulusLength < 2048) throw new JWTError(`${alg} requires a key modulusLength of at least 2048 bits`, "ERR_JWK_INVALID");
85
- }
86
- return key;
87
- }
88
- function _buildJWSSetFilter(header) {
89
- const { kid, alg } = header;
90
- return (k) => (!kid || k.kid === kid) && (!k.alg || k.alg === alg);
91
- }
92
- function _buildJWSHeader(alg, key, userHeader, payload) {
93
- const safeHeader = sanitizeObject(userHeader);
94
- const header = {
95
- ...isJWK(key) && key.kid ? { kid: key.kid } : {},
96
- ...safeHeader,
97
- alg
98
- };
99
- applyTypCtyDefaults(header, payload);
100
- if (header.b64 === true) delete header.b64;
101
- return header;
102
- }
103
- //#endregion
104
- export { JWTError, isJWTError, sign, verify };
1
+ import { D as JWTError, O as isJWTError } from "../_chunks/utils.mjs";
2
+ import { a as verifyMulti, i as signMulti, n as verify, o as verifyMultiAll, r as generalToFlattenedJWS, t as sign } from "../_chunks/jws.mjs";
3
+ export { JWTError, generalToFlattenedJWS, isJWTError, sign, signMulti, verify, verifyMulti, verifyMultiAll };
@@ -1,6 +1,19 @@
1
- import { A as JWK, L as JWKSet, ft as JWK_oct, l as StrictOmit, nt as JWK_Private, rt as JWK_Public, t as ExpiresIn, v as JWTClaimValidationOptions, y as JWTClaims } from "../../_chunks/index.mjs";
2
-
3
- //#region src/core/utils/jwt.d.ts
1
+ import { Ct as JWK_EC_Private, Dt as JWK_OKP_Private, Ht as JWK_oct, J as JWTClaimValidationOptions, Lt as JWK_RSA_Private, Mt as JWK_Private, Nt as JWK_Public, Ot as JWK_OKP_Public, Rt as JWK_RSA_Public, S as JWSAlgorithm, Ut as KeyManagementAlgorithm, V as StrictOmit, Y as JWTClaims, n as ExpiresIn, ot as JWK, pt as JWKSet, t as Duration, wt as JWK_EC_Public } from "../../_chunks/index.mjs";
2
+ import { a as textDecoder, c as sanitizeObject, i as base64UrlEncode, l as sanitizeObjectCopy, n as base64Encode, o as textEncoder, r as base64UrlDecode, s as safeJsonParse, t as base64Decode, u as secureRandomBytes } from "../../_chunks/libs/unsecure.mjs";
3
+ /**
4
+ * Infer the set of JWS signing algorithms a key unambiguously supports.
5
+ * Returns `undefined` when inference is not possible — callers must pass
6
+ * `options.algorithms` explicitly (raw bytes, ambiguous JWK, lookup functions, ...).
7
+ */
8
+ declare function inferJWSAllowedAlgorithms(key: unknown): JWSAlgorithm[] | undefined;
9
+ /**
10
+ * Infer the set of JWE key-management algorithms a key unambiguously supports.
11
+ * Returns `undefined` when inference is not possible — callers must pass
12
+ * `options.algorithms` explicitly.
13
+ *
14
+ * Passwords (`string` / `Uint8Array`) infer to the three PBES2 variants.
15
+ */
16
+ declare function inferJWEAllowedAlgorithms(key: unknown): KeyManagementAlgorithm[] | undefined;
4
17
  /**
5
18
  * Apply default typ/cty semantics shared by JWS & JWE.
6
19
  * - If typ is undefined and payload is a non-Uint8Array object, set typ="JWT".
@@ -15,33 +28,57 @@ declare function isJWTContent(header: {
15
28
  typ?: string;
16
29
  cty?: string;
17
30
  } | undefined): boolean;
31
+ /** Parse a decoded string as JSON when it looks like a JSON object or array, otherwise return the string verbatim. */
32
+ declare function decodeMaybeJWTString<T = unknown>(decodedString: string): T | string;
33
+ /** Decode raw payload bytes honoring `forceUint8Array`. */
34
+ declare function decodePayloadFromBytes<T = unknown>(bytes: Uint8Array<ArrayBuffer>, forceUint8Array?: boolean): T | Uint8Array<ArrayBuffer> | string;
35
+ /** Decode a Base64URL-encoded payload segment honoring `forceUint8Array`. */
36
+ declare function decodePayloadFromB64UrlSegment<T = unknown>(payloadEncoded: string, forceUint8Array?: boolean): T | Uint8Array<ArrayBuffer> | string;
37
+ /** Convert plaintext input to bytes, shared by JWS & JWE when preparing payload. */
38
+ declare function getPlaintextBytes(payload: string | Uint8Array<ArrayBuffer> | Record<string, unknown>): Uint8Array<ArrayBuffer>;
18
39
  /**
19
- * Given a decoded string and JOSE headers, return an object if JSON, otherwise the string.
20
- */
21
- declare function decodeMaybeJWTString<T = unknown>(decodedString: string, header: {
22
- typ?: string;
23
- cty?: string;
24
- } | undefined): T | string;
25
- /**
26
- * Decode a payload that is represented as raw bytes into T | string, honoring forceUint8Array and headers.
40
+ * Parse a {@link Duration} (integer seconds or shorthand string like `"10m"`)
41
+ * into a positive integer number of seconds. Used for `expiresIn`-style inputs
42
+ * where `0` / negatives are invalid.
43
+ *
44
+ * For inputs that legitimately permit `0` (e.g. `notBeforeIn: 0`), compute the
45
+ * bounds at the call site instead.
27
46
  */
28
- declare function decodePayloadFromBytes<T = unknown>(bytes: Uint8Array<ArrayBuffer>, header: {
29
- typ?: string;
30
- cty?: string;
31
- } | undefined, forceUint8Array?: boolean): T | Uint8Array<ArrayBuffer> | string;
47
+ declare function computeDurationInSeconds(duration: Duration): number;
48
+ /** @deprecated Renamed to {@link computeDurationInSeconds} in v0.7.0. */
49
+ declare const computeExpiresInSeconds: (expiresIn: ExpiresIn) => number;
50
+ /** @deprecated Renamed to {@link computeDurationInSeconds} in v0.7.0. */
51
+ declare const computeMaxTokenAgeSeconds: (expiresIn: ExpiresIn) => number;
52
+ /** Options for {@link computeJwtTimeClaims}. */
53
+ interface ComputeJwtTimeClaimsOptions {
54
+ /** Reference moment for `iat` (and for `expiresIn` / `notBeforeIn` math). Defaults to `new Date()`. */
55
+ currentDate?: Date;
56
+ /** Duration until `exp`, relative to `currentDate`. Mutually exclusive with `expiresAt`. */
57
+ expiresIn?: ExpiresIn;
58
+ /** Absolute moment for `exp`. Mutually exclusive with `expiresIn`. */
59
+ expiresAt?: Date;
60
+ /**
61
+ * Duration from `iat` before which the JWT must not be accepted.
62
+ * `0` is allowed and means `nbf = iat` (explicit temporal floor at sign time).
63
+ * Mutually exclusive with `notBeforeAt`.
64
+ */
65
+ notBeforeIn?: ExpiresIn;
66
+ /** Absolute moment for `nbf` (RFC 7519 §4.1.5). Mutually exclusive with `notBeforeIn`. */
67
+ notBeforeAt?: Date;
68
+ }
32
69
  /**
33
- * Decode a payload that is a Base64URL segment into T | string | Uint8Array based on flags and headers.
70
+ * Compute `iat` + optional `exp` / `nbf` for any JSON-object payload.
71
+ *
72
+ * Returns a shallow-cloned payload with the time claims added, or `undefined`
73
+ * when no hint applies (no expiry/nbf provided, non-object payload, or the
74
+ * payload already carries the corresponding claim).
75
+ *
76
+ * `expiresIn` / `expiresAt` and `notBeforeIn` / `notBeforeAt` are each mutually
77
+ * exclusive pairs — passing both within a pair throws `ERR_JWT_CLAIM_INVALID`.
78
+ * Invalid `Date` inputs (NaN `.getTime()`) and negative `notBeforeIn` durations
79
+ * also throw.
34
80
  */
35
- declare function decodePayloadFromB64UrlSegment<T = unknown>(payloadEncoded: string, header: {
36
- typ?: string;
37
- cty?: string;
38
- } | undefined, forceUint8Array?: boolean): T | Uint8Array<ArrayBuffer> | string;
39
- /** Convert plaintext input to bytes, shared by JWS & JWE when preparing payload. */
40
- declare function getPlaintextBytes(payload: string | Uint8Array<ArrayBuffer> | Record<string, unknown>): Uint8Array<ArrayBuffer>;
41
- declare function computeExpiresInSeconds(expiresIn: ExpiresIn): number;
42
- declare const computeMaxTokenAgeSeconds: (expiresIn: ExpiresIn) => number;
43
- /** Optionally compute iat/exp when signing JWTs. */
44
- declare function computeJwtTimeClaims(payload: unknown, headerTyp: string | undefined, expiresIn?: ExpiresIn, currentDate?: Date): JWTClaims | undefined;
81
+ declare function computeJwtTimeClaims(payload: unknown, options?: ComputeJwtTimeClaimsOptions): JWTClaims | undefined;
45
82
  /** Validate JWT claims under JWS verification rules (or custom JWE implementations). */
46
83
  declare function validateJwtClaims(jwtClaims: JWTClaims, options?: JWTClaimValidationOptions): void;
47
84
  /** Validate critical headers in JWS semantics. */
@@ -52,58 +89,54 @@ declare function validateCriticalHeadersJWS(protectedHeader: {
52
89
  declare function validateCriticalHeadersJWE(protectedHeader: {
53
90
  crit?: string[];
54
91
  } & Record<string, any>, recognizedHeaders?: string[]): void;
55
- //#endregion
56
- //#region src/core/utils/sanitize.d.ts
57
- /**
58
- * Originally derived from unsecure@0.0.4
59
- * Licensed under the MIT License.
60
- *
61
- * Source: https://github.com/sandros94/unsecure/blob/913ed5580c551153a19154b4916c67a8efb2be85/src/sanitize.ts
62
- */
63
- /**
64
- * Returns a deep structural copy of `obj` with prototype-pollution vectors
65
- * stripped at every level (`__proto__`, `prototype`, `constructor`).
66
- *
67
- * The input is never modified. Arrays are copied element-by-element;
68
- * nested objects are recursed with a WeakSet cycle guard.
69
- */
70
- declare function sanitizeObject<T extends Record<string, unknown> | undefined>(obj: T): T;
71
- //#endregion
72
- //#region src/core/utils/index.d.ts
73
- declare const textEncoder: TextEncoder;
74
- declare const textDecoder: TextDecoder;
75
- declare function base64Encode(data: Uint8Array<ArrayBuffer> | string): string;
76
- declare function base64UrlEncode(data: Uint8Array<ArrayBuffer> | string): string;
77
- declare function base64Decode(str: string | undefined): string;
78
- declare function base64Decode<T extends boolean | undefined>(str?: string | undefined, toString?: T): T extends false ? Uint8Array<ArrayBuffer> : string;
79
- declare function base64UrlDecode(str: string | undefined): string;
80
- declare function base64UrlDecode<T extends boolean | undefined>(str?: string | undefined, toString?: T): T extends false ? Uint8Array<ArrayBuffer> : string;
81
- declare function randomBytes(length: Readonly<number>): Uint8Array<ArrayBuffer>;
82
- /**
83
- * Concatenates multiple Uint8Arrays
84
- * @param arrays Arrays to concatenate
85
- * @returns Concatenated array
86
- */
92
+ /** Concatenate multiple `Uint8Array`s into a single contiguous buffer. */
87
93
  declare function concatUint8Arrays(...arrays: Readonly<Uint8Array<ArrayBuffer>[]>): Uint8Array<ArrayBuffer>;
94
+ /** Wrap a value in an array; returns the array unchanged if already an array. */
88
95
  declare function maybeArray<T>(item: T | T[]): T[];
96
+ /** Type guard for {@link JWK} — checks for an object with a string `kty`. */
89
97
  declare function isJWK(key: any): key is JWK;
98
+ /** Type guard for {@link JWKSet} — checks for an object with a `keys` array. */
90
99
  declare function isJWKSet(key: any): key is JWKSet;
100
+ /** Asserts that `key` is a `CryptoKey`; throws `TypeError` otherwise. */
91
101
  declare function assertCryptoKey(key: unknown): asserts key is CryptoKey;
102
+ /**
103
+ * Type guard for `CryptoKey`. Uses `Symbol.toStringTag` instead of `instanceof`
104
+ * so it works across worker / realm boundaries where `CryptoKey` identities differ.
105
+ */
92
106
  declare function isCryptoKey(key: unknown): key is CryptoKey;
107
+ /** Type guard for `CryptoKeyPair` — both `publicKey` and `privateKey` must be CryptoKeys. */
93
108
  declare const isCryptoKeyPair: (key: any) => key is CryptoKeyPair;
94
- /** Returns true if the JWK is a symmetric (oct) key. */
95
- declare function isSymmetricJWK(key: unknown): key is Extract<JWK, JWK_oct>;
96
- /** Returns true if the JWK is an asymmetric (RSA, EC, OKP) key. */
109
+ /**
110
+ * Returns true if the JWK is a symmetric (oct) key.
111
+ *
112
+ * The `T` inference preserves the caller's narrowed alg type — passing a
113
+ * `JWK_oct<"HS256">` refines to `JWK_oct<"HS256">`, not `JWK_oct<string>`.
114
+ */
115
+ declare function isSymmetricJWK<T>(key: T): key is Extract<T, JWK_oct>;
116
+ declare function isSymmetricJWK(key: unknown): key is JWK_oct;
117
+ /**
118
+ * Returns true if the JWK is an asymmetric (RSA, EC, OKP) key.
119
+ *
120
+ * The `T` inference preserves the caller's narrowed alg type — passing a
121
+ * `JWK_EC<"ES256">` refines to `JWK_EC<"ES256">`, not `JWK_EC<string>`,
122
+ * and so on for RSA and OKP.
123
+ */
124
+ declare function isAsymmetricJWK<T>(key: T): key is Exclude<T, JWK_oct>;
97
125
  declare function isAsymmetricJWK(key: unknown): key is Exclude<JWK, JWK_oct>;
98
126
  /**
99
127
  * Type guard that checks if the provided JWK contains private key material.
100
128
  * It relies purely on the presence of private components (e.g. "d"), not on the alg value.
129
+ *
130
+ * Preserves narrow alg types from the caller.
101
131
  */
132
+ declare function isPrivateJWK<T>(key: T): key is Extract<T, JWK_EC_Private | JWK_OKP_Private | JWK_RSA_Private>;
102
133
  declare function isPrivateJWK(key: unknown): key is JWK_Private;
103
134
  /**
104
135
  * Type guard that checks if the provided JWK is a public (asymmetric) key.
105
136
  * This checks for the presence of public components and absence of private material.
137
+ *
138
+ * Preserves narrow alg types from the caller.
106
139
  */
140
+ declare function isPublicJWK<T>(key: T): key is Exclude<Extract<T, JWK_EC_Public | JWK_OKP_Public | JWK_RSA_Public>, JWK_Private>;
107
141
  declare function isPublicJWK(key: unknown): key is JWK_Public;
108
- //#endregion
109
- export { StrictOmit, applyTypCtyDefaults, assertCryptoKey, base64Decode, base64Encode, base64UrlDecode, base64UrlEncode, computeExpiresInSeconds, computeJwtTimeClaims, computeMaxTokenAgeSeconds, concatUint8Arrays, decodeMaybeJWTString, decodePayloadFromB64UrlSegment, decodePayloadFromBytes, getPlaintextBytes, isAsymmetricJWK, isCryptoKey, isCryptoKeyPair, isJWK, isJWKSet, isJWTContent, isPrivateJWK, isPublicJWK, isSymmetricJWK, maybeArray, randomBytes, sanitizeObject, textDecoder, textEncoder, validateCriticalHeadersJWE, validateCriticalHeadersJWS, validateJwtClaims };
142
+ export { ComputeJwtTimeClaimsOptions, StrictOmit, applyTypCtyDefaults, assertCryptoKey, base64Decode, base64Encode, base64UrlDecode, base64UrlEncode, computeDurationInSeconds, computeExpiresInSeconds, computeJwtTimeClaims, computeMaxTokenAgeSeconds, concatUint8Arrays, decodeMaybeJWTString, decodePayloadFromB64UrlSegment, decodePayloadFromBytes, getPlaintextBytes, inferJWEAllowedAlgorithms, inferJWSAllowedAlgorithms, isAsymmetricJWK, isCryptoKey, isCryptoKeyPair, isJWK, isJWKSet, isJWTContent, isPrivateJWK, isPublicJWK, isSymmetricJWK, maybeArray, safeJsonParse, sanitizeObject, sanitizeObjectCopy, secureRandomBytes, textDecoder, textEncoder, validateCriticalHeadersJWE, validateCriticalHeadersJWS, validateJwtClaims };
@@ -1,2 +1,3 @@
1
- import { A as validateCriticalHeadersJWS, C as computeMaxTokenAgeSeconds, D as getPlaintextBytes, E as decodePayloadFromBytes, O as isJWTContent, S as computeJwtTimeClaims, T as decodePayloadFromB64UrlSegment, _ as textDecoder, a as base64UrlEncode, b as applyTypCtyDefaults, c as isCryptoKey, d as isJWKSet, f as isPrivateJWK, g as randomBytes, h as maybeArray, i as base64UrlDecode, j as validateJwtClaims, k as validateCriticalHeadersJWE, l as isCryptoKeyPair, m as isSymmetricJWK, n as base64Decode, o as concatUint8Arrays, p as isPublicJWK, r as base64Encode, s as isAsymmetricJWK, t as assertCryptoKey, u as isJWK, v as textEncoder, w as decodeMaybeJWTString, x as computeExpiresInSeconds, y as sanitizeObject } from "../../_chunks/utils.mjs";
2
- export { applyTypCtyDefaults, assertCryptoKey, base64Decode, base64Encode, base64UrlDecode, base64UrlEncode, computeExpiresInSeconds, computeJwtTimeClaims, computeMaxTokenAgeSeconds, concatUint8Arrays, decodeMaybeJWTString, decodePayloadFromB64UrlSegment, decodePayloadFromBytes, getPlaintextBytes, isAsymmetricJWK, isCryptoKey, isCryptoKeyPair, isJWK, isJWKSet, isJWTContent, isPrivateJWK, isPublicJWK, isSymmetricJWK, maybeArray, randomBytes, sanitizeObject, textDecoder, textEncoder, validateCriticalHeadersJWE, validateCriticalHeadersJWS, validateJwtClaims };
1
+ import { C as validateCriticalHeadersJWS, E as inferJWSAllowedAlgorithms, S as validateCriticalHeadersJWE, T as inferJWEAllowedAlgorithms, _ as decodeMaybeJWTString, a as isCryptoKeyPair, b as getPlaintextBytes, c as isPrivateJWK, d as maybeArray, f as applyTypCtyDefaults, g as computeMaxTokenAgeSeconds, h as computeJwtTimeClaims, i as isCryptoKey, l as isPublicJWK, m as computeExpiresInSeconds, n as concatUint8Arrays, o as isJWK, p as computeDurationInSeconds, r as isAsymmetricJWK, s as isJWKSet, t as assertCryptoKey, u as isSymmetricJWK, v as decodePayloadFromB64UrlSegment, w as validateJwtClaims, x as isJWTContent, y as decodePayloadFromBytes } from "../../_chunks/utils.mjs";
2
+ import { a as base64UrlEncode, c as safeJsonParse, i as base64UrlDecode, l as sanitizeObject, n as base64Decode, o as textDecoder, r as base64Encode, s as textEncoder, t as secureRandomBytes, u as sanitizeObjectCopy } from "../../_chunks/libs/unsecure.mjs";
3
+ export { applyTypCtyDefaults, assertCryptoKey, base64Decode, base64Encode, base64UrlDecode, base64UrlEncode, computeDurationInSeconds, computeExpiresInSeconds, computeJwtTimeClaims, computeMaxTokenAgeSeconds, concatUint8Arrays, decodeMaybeJWTString, decodePayloadFromB64UrlSegment, decodePayloadFromBytes, getPlaintextBytes, inferJWEAllowedAlgorithms, inferJWSAllowedAlgorithms, isAsymmetricJWK, isCryptoKey, isCryptoKeyPair, isJWK, isJWKSet, isJWTContent, isPrivateJWK, isPublicJWK, isSymmetricJWK, maybeArray, safeJsonParse, sanitizeObject, sanitizeObjectCopy, secureRandomBytes, textDecoder, textEncoder, validateCriticalHeadersJWE, validateCriticalHeadersJWS, validateJwtClaims };
package/dist/index.d.mts CHANGED
@@ -1,7 +1,6 @@
1
- import { $ as JWK_OKP_SIGN, A as JWK, B as JWK_AES_GCM_KW, C as DeriveKeyOptions, D as GenerateKeyAlgorithm, E as GenerateJWKReturn, F as JWKPEMAlgorithm, G as JWK_ECDH_ES, H as JWK_Asymmetric, I as JWKParameters, J as JWK_EC_Public, K as JWK_ECDSA, L as JWKSet, M as JWKCacheAdapter, N as JWKLookupFunction, O as GenerateKeyOptions, P as JWKLookupFunctionHeader, Q as JWK_OKP_Public, R as JWK_AES_CBC_HMAC, S as ContentEncryptionAlgorithm, T as GenerateJWKOptions, U as JWK_Asymmetric_Algorithm, V as JWK_AES_KW, W as JWK_EC, X as JWK_OKP, Y as JWK_HMAC, Z as JWK_OKP_Private, _ as JWT, a as JWEEncryptOptions, at as JWK_RSA_ENC, b as JoseHeaderParameters, c as JWEProtectedHeader, ct as JWK_RSA_Public, d as JWSHeaderParameters, dt as JWK_Symmetric_Algorithm, et as JWK_PBES2, f as JWSProtectedHeader, ft as JWK_oct, g as JOSEPayload, gt as WrapKeyResult, h as JWSVerifyResult, ht as WrapKeyOptions, i as JWEDecryptResult, it as JWK_RSA, j as JWKAlgorithm, k as GenerateKeyReturn, lt as JWK_RSA_SIGN, m as JWSVerifyOptions, mt as UnwrapKeyOptions, n as MaxTokenAge, nt as JWK_Private, o as JWEHeaderParameters, ot as JWK_RSA_PSS, p as JWSSignOptions, pt as KeyManagementAlgorithm, q as JWK_EC_Private, r as JWEDecryptOptions, rt as JWK_Public, s as JWEKeyManagementHeaderParameters, st as JWK_RSA_Private, t as ExpiresIn, tt as JWK_Pair, u as JWSAlgorithm, ut as JWK_Symmetric, v as JWTClaimValidationOptions, w as DeriveKeyReturn, x as CompositeKey, y as JWTClaims, z as JWK_AES_GCM } from "./_chunks/index.mjs";
2
- import { i as isJWTError, n as JWTErrorCauseMap, r as JWTErrorCode, t as JWTError } from "./_chunks/error.mjs";
3
- import { decrypt, encrypt } from "./core/jwe.mjs";
4
- import { WeakMapJWKCache, clearJWKCache, configureJWKCache, deriveJWKFromPassword, deriveKeyFromPassword, deriveSharedSecret, exportKey, exportToPEM, generateJWK, generateKey, getJWKFromSet, getJWKsFromSet, importFromPEM, importKey, unwrapKey, wrapKey } from "./core/jwk.mjs";
5
- import { sign, verify } from "./core/jws.mjs";
6
- import { assertCryptoKey, base64Decode, base64Encode, base64UrlDecode, base64UrlEncode, computeExpiresInSeconds, computeMaxTokenAgeSeconds, concatUint8Arrays, isAsymmetricJWK, isCryptoKey, isCryptoKeyPair, isJWK, isJWKSet, isPrivateJWK, isPublicJWK, isSymmetricJWK, maybeArray, randomBytes, sanitizeObject, textDecoder, textEncoder, validateJwtClaims } from "./core/utils/index.mjs";
7
- export { CompositeKey, ContentEncryptionAlgorithm, DeriveKeyOptions, DeriveKeyReturn, ExpiresIn, GenerateJWKOptions, GenerateJWKReturn, GenerateKeyAlgorithm, GenerateKeyOptions, GenerateKeyReturn, JOSEPayload, JWEDecryptOptions, JWEDecryptResult, JWEEncryptOptions, JWEHeaderParameters, JWEKeyManagementHeaderParameters, JWEProtectedHeader, JWK, JWKAlgorithm, JWKCacheAdapter, JWKLookupFunction, JWKLookupFunctionHeader, JWKPEMAlgorithm, JWKParameters, JWKSet, JWK_AES_CBC_HMAC, JWK_AES_GCM, JWK_AES_GCM_KW, JWK_AES_KW, JWK_Asymmetric, JWK_Asymmetric_Algorithm, JWK_EC, JWK_ECDH_ES, JWK_ECDSA, JWK_EC_Private, JWK_EC_Public, JWK_HMAC, JWK_OKP, JWK_OKP_Private, JWK_OKP_Public, JWK_OKP_SIGN, JWK_PBES2, JWK_Pair, JWK_Private, JWK_Public, JWK_RSA, JWK_RSA_ENC, JWK_RSA_PSS, JWK_RSA_Private, JWK_RSA_Public, JWK_RSA_SIGN, JWK_Symmetric, JWK_Symmetric_Algorithm, JWK_oct, JWSAlgorithm, JWSHeaderParameters, JWSProtectedHeader, JWSSignOptions, JWSVerifyOptions, JWSVerifyResult, JWT, JWTClaimValidationOptions, JWTClaims, JWTError, type JWTErrorCauseMap, type JWTErrorCode, JoseHeaderParameters, KeyManagementAlgorithm, MaxTokenAge, UnwrapKeyOptions, WeakMapJWKCache, WrapKeyOptions, WrapKeyResult, assertCryptoKey, base64Decode, base64Encode, base64UrlDecode, base64UrlEncode, clearJWKCache, computeExpiresInSeconds, computeMaxTokenAgeSeconds, concatUint8Arrays, configureJWKCache, decrypt, deriveJWKFromPassword, deriveKeyFromPassword, deriveSharedSecret, encrypt, exportKey, exportToPEM, generateJWK, generateKey, getJWKFromSet, getJWKsFromSet, importFromPEM, importKey, isAsymmetricJWK, isCryptoKey, isCryptoKeyPair, isJWK, isJWKSet, isJWTError, isPrivateJWK, isPublicJWK, isSymmetricJWK, maybeArray, randomBytes, sanitizeObject, sign, textDecoder, textEncoder, unwrapKey, validateJwtClaims, verify, wrapKey };
1
+ import { $ as DeriveKeyOptions, A as JWSMultiSigner, At as JWK_PBES2, B as JWSVerifyResult, Bt as JWK_Symmetric, C as JWSAsymmetricPrivateJWK, Ct as JWK_EC_Private, D as JWSGeneralSignature, Dt as JWK_OKP_Private, E as JWSGeneralSerialization, Et as JWK_OKP, F as JWSProtectedHeader, Ft as JWK_RSA_ENC, G as isJWTError, Gt as UnwrappingKeyFor, H as JWTError, Ht as JWK_oct, I as JWSSignJWK, It as JWK_RSA_PSS, J as JWTClaimValidationOptions, Jt as WrappingKeyFor, K as JOSEPayload, Kt as WrapKeyOptions, L as JWSSignOptions, Lt as JWK_RSA_Private, M as JWSMultiVerifyOptions, Mt as JWK_Private, N as JWSMultiVerifyOutcome, Nt as JWK_Public, O as JWSHeaderParameters, Ot as JWK_OKP_Public, P as JWSMultiVerifyResult, Pt as JWK_RSA, Q as ContentEncryptionAlgorithm, R as JWSVerifyJWK, Rt as JWK_RSA_Public, S as JWSAlgorithm, St as JWK_ECDSA, T as JWSFlattenedSerialization, Tt as JWK_HMAC, U as JWTErrorCauseMap, Ut as KeyManagementAlgorithm, Vt as JWK_Symmetric_Algorithm, W as JWTErrorCode, Wt as UnwrapKeyOptions, X as JoseHeaderParameters, Y as JWTClaims, Z as CompositeKey, _ as JWEMultiDecryptOptions, _t as JWK_AES_KW, a as JWEAsymmetricPrivateJWK, at as GenerateKeyReturn, b as JWEMultiRecipient, bt as JWK_EC, c as JWEDecryptOptions, ct as JWKCacheAdapter, d as JWEEncryptOptions, dt as JWKPEMAlgorithm, et as DeriveKeyReturn, f as JWEFlattenedSerialization, ft as JWKParameters, g as JWEKeyManagementHeaderParameters, gt as JWK_AES_GCM_KW, h as JWEHeaderParameters, ht as JWK_AES_GCM, i as NotBeforeIn, it as GenerateKeyOptions, j as JWSMultiVerifyAllOptions, jt as JWK_Pair, k as JWSMultiSignOptions, kt as JWK_OKP_SIGN, l as JWEDecryptResult, lt as JWKLookupFunction, m as JWEGeneralSerialization, mt as JWK_AES_CBC_HMAC, n as ExpiresIn, nt as GenerateJWKReturn, o as JWEAsymmetricPublicJWK, ot as JWK, p as JWEGeneralRecipient, pt as JWKSet, q as JWT, qt as WrapKeyResult, r as MaxTokenAge, rt as GenerateKeyAlgorithm, s as JWEDecryptJWK, st as JWKAlgorithm, t as Duration, tt as GenerateJWKOptions, u as JWEEncryptJWK, ut as JWKLookupFunctionHeader, v as JWEMultiDecryptResult, vt as JWK_Asymmetric, w as JWSAsymmetricPublicJWK, wt as JWK_EC_Public, x as JWEProtectedHeader, xt as JWK_ECDH_ES, y as JWEMultiEncryptOptions, yt as JWK_Asymmetric_Algorithm, z as JWSVerifyOptions, zt as JWK_RSA_SIGN } from "./_chunks/index.mjs";
2
+ import { WeakMapJWKCache, clearJWKCache, configureJWKCache, deriveJWKFromPassword, deriveKeyFromPassword, deriveSharedSecret, exportKey, exportPEM, exportToPEM, generateJWK, generateKey, getJWKFromSet, getJWKsFromSet, importFromPEM, importKey, importPEM, unwrapKey, wrapKey } from "./core/jwk.mjs";
3
+ import { a as generalToFlattened, i as encryptMulti, n as encrypt, r as decryptMulti, t as decrypt } from "./_chunks/jwe.mjs";
4
+ import { a as verifyMulti, i as signMulti, n as verify, o as verifyMultiAll, r as generalToFlattenedJWS, t as sign } from "./_chunks/jws.mjs";
5
+ import { assertCryptoKey, computeDurationInSeconds, computeExpiresInSeconds, computeMaxTokenAgeSeconds, isAsymmetricJWK, isCryptoKey, isCryptoKeyPair, isJWK, isJWKSet, isPrivateJWK, isPublicJWK, isSymmetricJWK, validateJwtClaims } from "./core/utils/index.mjs";
6
+ export { CompositeKey, ContentEncryptionAlgorithm, DeriveKeyOptions, DeriveKeyReturn, Duration, ExpiresIn, GenerateJWKOptions, GenerateJWKReturn, GenerateKeyAlgorithm, GenerateKeyOptions, GenerateKeyReturn, JOSEPayload, JWEAsymmetricPrivateJWK, JWEAsymmetricPublicJWK, JWEDecryptJWK, JWEDecryptOptions, JWEDecryptResult, JWEEncryptJWK, JWEEncryptOptions, JWEFlattenedSerialization, JWEGeneralRecipient, JWEGeneralSerialization, JWEHeaderParameters, JWEKeyManagementHeaderParameters, JWEMultiDecryptOptions, JWEMultiDecryptResult, JWEMultiEncryptOptions, JWEMultiRecipient, JWEProtectedHeader, JWK, JWKAlgorithm, JWKCacheAdapter, JWKLookupFunction, JWKLookupFunctionHeader, JWKPEMAlgorithm, JWKParameters, JWKSet, JWK_AES_CBC_HMAC, JWK_AES_GCM, JWK_AES_GCM_KW, JWK_AES_KW, JWK_Asymmetric, JWK_Asymmetric_Algorithm, JWK_EC, JWK_ECDH_ES, JWK_ECDSA, JWK_EC_Private, JWK_EC_Public, JWK_HMAC, JWK_OKP, JWK_OKP_Private, JWK_OKP_Public, JWK_OKP_SIGN, JWK_PBES2, JWK_Pair, JWK_Private, JWK_Public, JWK_RSA, JWK_RSA_ENC, JWK_RSA_PSS, JWK_RSA_Private, JWK_RSA_Public, JWK_RSA_SIGN, JWK_Symmetric, JWK_Symmetric_Algorithm, JWK_oct, JWSAlgorithm, JWSAsymmetricPrivateJWK, JWSAsymmetricPublicJWK, JWSFlattenedSerialization, JWSGeneralSerialization, JWSGeneralSignature, JWSHeaderParameters, JWSMultiSignOptions, JWSMultiSigner, JWSMultiVerifyAllOptions, JWSMultiVerifyOptions, JWSMultiVerifyOutcome, JWSMultiVerifyResult, JWSProtectedHeader, JWSSignJWK, JWSSignOptions, JWSVerifyJWK, JWSVerifyOptions, JWSVerifyResult, JWT, JWTClaimValidationOptions, JWTClaims, JWTError, type JWTErrorCauseMap, type JWTErrorCode, JoseHeaderParameters, KeyManagementAlgorithm, MaxTokenAge, NotBeforeIn, UnwrapKeyOptions, UnwrappingKeyFor, WeakMapJWKCache, WrapKeyOptions, WrapKeyResult, WrappingKeyFor, assertCryptoKey, clearJWKCache, computeDurationInSeconds, computeExpiresInSeconds, computeMaxTokenAgeSeconds, configureJWKCache, decrypt, decryptMulti, deriveJWKFromPassword, deriveKeyFromPassword, deriveSharedSecret, encrypt, encryptMulti, exportKey, exportPEM, exportToPEM, generalToFlattened, generalToFlattenedJWS, generateJWK, generateKey, getJWKFromSet, getJWKsFromSet, importFromPEM, importKey, importPEM, isAsymmetricJWK, isCryptoKey, isCryptoKeyPair, isJWK, isJWKSet, isJWTError, isPrivateJWK, isPublicJWK, isSymmetricJWK, sign, signMulti, unwrapKey, validateJwtClaims, verify, verifyMulti, verifyMultiAll, wrapKey };
package/dist/index.mjs CHANGED
@@ -1,5 +1,5 @@
1
- import { C as computeMaxTokenAgeSeconds, M as JWTError, N as isJWTError, _ as textDecoder, a as base64UrlEncode, c as isCryptoKey, d as isJWKSet, f as isPrivateJWK, g as randomBytes, h as maybeArray, i as base64UrlDecode, j as validateJwtClaims, l as isCryptoKeyPair, m as isSymmetricJWK, n as base64Decode, o as concatUint8Arrays, p as isPublicJWK, r as base64Encode, s as isAsymmetricJWK, t as assertCryptoKey, u as isJWK, v as textEncoder, x as computeExpiresInSeconds, y as sanitizeObject } from "./_chunks/utils.mjs";
2
- import { WeakMapJWKCache, clearJWKCache, configureJWKCache, deriveJWKFromPassword, deriveKeyFromPassword, deriveSharedSecret, exportKey, exportToPEM, generateJWK, generateKey, getJWKFromSet, getJWKsFromSet, importFromPEM, importKey, unwrapKey, wrapKey } from "./core/jwk.mjs";
3
- import { sign, verify } from "./core/jws.mjs";
4
- import { decrypt, encrypt } from "./core/jwe.mjs";
5
- export { JWTError, WeakMapJWKCache, assertCryptoKey, base64Decode, base64Encode, base64UrlDecode, base64UrlEncode, clearJWKCache, computeExpiresInSeconds, computeMaxTokenAgeSeconds, concatUint8Arrays, configureJWKCache, decrypt, deriveJWKFromPassword, deriveKeyFromPassword, deriveSharedSecret, encrypt, exportKey, exportToPEM, generateJWK, generateKey, getJWKFromSet, getJWKsFromSet, importFromPEM, importKey, isAsymmetricJWK, isCryptoKey, isCryptoKeyPair, isJWK, isJWKSet, isJWTError, isPrivateJWK, isPublicJWK, isSymmetricJWK, maybeArray, randomBytes, sanitizeObject, sign, textDecoder, textEncoder, unwrapKey, validateJwtClaims, verify, wrapKey };
1
+ import { D as JWTError, O as isJWTError, a as isCryptoKeyPair, c as isPrivateJWK, g as computeMaxTokenAgeSeconds, i as isCryptoKey, l as isPublicJWK, m as computeExpiresInSeconds, o as isJWK, p as computeDurationInSeconds, r as isAsymmetricJWK, s as isJWKSet, t as assertCryptoKey, u as isSymmetricJWK, w as validateJwtClaims } from "./_chunks/utils.mjs";
2
+ import { _ as unwrapKey, a as deriveKeyFromPassword, c as exportPEM, d as generateKey, f as getJWKFromSet, g as importPEM, h as importKey, i as deriveJWKFromPassword, l as exportToPEM, m as importFromPEM, n as clearJWKCache, o as deriveSharedSecret, p as getJWKsFromSet, r as configureJWKCache, s as exportKey, t as WeakMapJWKCache, u as generateJWK, v as wrapKey } from "./_chunks/jwk.mjs";
3
+ import { a as verifyMulti, i as signMulti, n as verify, o as verifyMultiAll, r as generalToFlattenedJWS, t as sign } from "./_chunks/jws.mjs";
4
+ import { a as generalToFlattened, i as encryptMulti, n as encrypt, r as decryptMulti, t as decrypt } from "./_chunks/jwe.mjs";
5
+ export { JWTError, WeakMapJWKCache, assertCryptoKey, clearJWKCache, computeDurationInSeconds, computeExpiresInSeconds, computeMaxTokenAgeSeconds, configureJWKCache, decrypt, decryptMulti, deriveJWKFromPassword, deriveKeyFromPassword, deriveSharedSecret, encrypt, encryptMulti, exportKey, exportPEM, exportToPEM, generalToFlattened, generalToFlattenedJWS, generateJWK, generateKey, getJWKFromSet, getJWKsFromSet, importFromPEM, importKey, importPEM, isAsymmetricJWK, isCryptoKey, isCryptoKeyPair, isJWK, isJWKSet, isJWTError, isPrivateJWK, isPublicJWK, isSymmetricJWK, sign, signMulti, unwrapKey, validateJwtClaims, verify, verifyMulti, verifyMultiAll, wrapKey };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "unjwt",
3
- "version": "0.6.1",
3
+ "version": "0.7.1",
4
4
  "description": "Low-level JWT utilities",
5
5
  "license": "MIT",
6
6
  "author": {
@@ -55,30 +55,31 @@
55
55
  },
56
56
  "devDependencies": {
57
57
  "@types/node": "^24",
58
- "@types/supertest": "^6.0.3",
59
- "@typescript/native-preview": "7.0.0-dev.20260306.1",
60
- "@vitest/coverage-v8": "^4.0.15",
58
+ "@types/supertest": "^7.2.0",
59
+ "@typescript/native-preview": "7.0.0-dev.20260421.2",
60
+ "@vitest/coverage-v8": "^4.1.5",
61
61
  "automd": "^0.4.3",
62
62
  "changelogen": "^0.6.2",
63
- "cookie-esv1": "npm:cookie-es@^1.2.2",
64
- "cookie-esv2": "npm:cookie-es@^2.0.0",
65
- "h3v1": "npm:h3@^1.15.10",
66
- "h3v2": "npm:h3@^2.0.1-rc.19",
67
- "jose": "^6.2.0",
68
- "nano-staged": "^0.9.0",
69
- "obuild": "^0.4.32",
70
- "oxfmt": "^0.43.0",
71
- "oxlint": "^1.51.0",
72
- "rolldown": "1.0.0-rc.12",
63
+ "cookie-esv1": "npm:cookie-es@^1.2.3",
64
+ "cookie-esv3": "npm:cookie-es@^3.1.1",
65
+ "h3v1": "npm:h3@^1.15.11",
66
+ "h3v2": "npm:h3@^2.0.1-rc.20",
67
+ "jose": "^6.2.2",
68
+ "nano-staged": "^1.0.2",
69
+ "obuild": "^0.4.33",
70
+ "oxfmt": "^0.46.0",
71
+ "oxlint": "^1.61.0",
72
+ "rolldown": "1.0.0-rc.17",
73
73
  "simple-git-hooks": "^2.13.1",
74
74
  "supertest": "^7.2.2",
75
- "typescript": "^5.9.3",
76
- "vitest": "^4.0.18"
75
+ "typescript": "^6.0.3",
76
+ "unsecure": "^0.2.2",
77
+ "vitest": "^4.1.5"
77
78
  },
78
79
  "peerDependencies": {
79
- "cookie-es": "^1.2.2 || ^2.0.0",
80
- "h3": "^1.15.4 || >=2.0.1-rc.18 || ^2.0.1",
81
- "rou3": "^0.7.10"
80
+ "cookie-es": "^1.2.3 || ^3.1.1",
81
+ "h3": "^1.15.4 || >=2.0.1-rc.20 || ^2.0.1",
82
+ "rou3": "^0.8.1"
82
83
  },
83
84
  "peerDependenciesMeta": {
84
85
  "cookie-es": {
@@ -91,6 +92,9 @@
91
92
  "optional": true
92
93
  }
93
94
  },
95
+ "resolutions": {
96
+ "unjwt": "link:."
97
+ },
94
98
  "simple-git-hooks": {
95
99
  "pre-commit": "./node_modules/.bin/nano-staged"
96
100
  },
@@ -106,6 +110,7 @@
106
110
  "lint": "oxlint . && oxfmt --check .",
107
111
  "fmt": "automd && oxlint --fix . && oxfmt .",
108
112
  "release": "pnpm test && pnpm prepack && changelogen --release --push",
113
+ "stub": "obuild --stub",
109
114
  "test": "vitest run --slowTestThreshold=1000",
110
115
  "test:coverage": "vitest run --coverage --slowTestThreshold=1000",
111
116
  "typecheck": "tsgo --noEmit",
@@ -1,67 +0,0 @@
1
- //#region src/core/error.d.ts
2
- /**
3
- * All known error codes thrown by unjwt.
4
- *
5
- * Code naming follows the JOSE spec hierarchy:
6
- * ERR_JWT_* — RFC 7519 JSON Web Token claim validation
7
- * ERR_JWS_* — RFC 7515 JSON Web Signature
8
- * ERR_JWE_* — RFC 7516 JSON Web Encryption
9
- * ERR_JWK_* — RFC 7517 JSON Web Key
10
- */
11
- type JWTErrorCode = "ERR_JWT_EXPIRED" | "ERR_JWT_NBF" | "ERR_JWT_CLAIM_INVALID" | "ERR_JWT_CLAIM_MISSING" | "ERR_JWS_INVALID" | "ERR_JWS_SIGNATURE_INVALID" | "ERR_JWS_ALG_NOT_ALLOWED" | "ERR_JWE_INVALID" | "ERR_JWE_DECRYPTION_FAILED" | "ERR_JWE_ALG_NOT_ALLOWED" | "ERR_JWK_INVALID" | "ERR_JWK_KEY_NOT_FOUND" | (string & {});
12
- /**
13
- * Maps known error codes to their structured `cause` shapes.
14
- * Only codes that carry decoded context beyond the message appear here.
15
- * Extend this interface when new structured causes are introduced.
16
- */
17
- interface JWTErrorCauseMap {
18
- /** Decoded claims available at the point the lifetime check failed. */
19
- ERR_JWT_EXPIRED: {
20
- jti?: string;
21
- iat?: number;
22
- exp?: number;
23
- };
24
- }
25
- /**
26
- * Base error class for all unjwt errors. Every error thrown by the library is
27
- * an instance of `JWTError`, so a single `instanceof` check is sufficient to
28
- * distinguish library errors from other thrown values. Use the `code` property
29
- * (or the `isJWTError` type guard) to narrow to a specific error condition.
30
- *
31
- * @example
32
- * import { JWTError, isJWTError } from "unjwt/jws";
33
- *
34
- * try {
35
- * await verify(token, key);
36
- * } catch (err) {
37
- * if (isJWTError(err, "ERR_JWT_EXPIRED")) {
38
- * console.log(err.cause.jti); // string | undefined
39
- * }
40
- * }
41
- */
42
- declare class JWTError<TCode extends JWTErrorCode = JWTErrorCode> extends Error {
43
- readonly code: TCode;
44
- override readonly cause?: unknown;
45
- constructor(message: string, code: TCode, cause?: unknown);
46
- }
47
- /**
48
- * Type guard that narrows `error` to `JWTError`.
49
- *
50
- * When called with a code that is a key of `JWTErrorCauseMap`, the return
51
- * type is additionally narrowed to include the structured `cause` shape for
52
- * that code. When called with any other `JWTErrorCode`, `code` is narrowed
53
- * but `cause` remains `unknown`. When called without a code, narrows only to
54
- * `JWTError`.
55
- *
56
- * @example
57
- * if (isJWTError(err, "ERR_JWT_EXPIRED")) {
58
- * err.cause.jti // string | undefined ✓
59
- * }
60
- */
61
- declare function isJWTError<T extends keyof JWTErrorCauseMap>(error: unknown, code: T): error is JWTError<T> & {
62
- cause: JWTErrorCauseMap[T];
63
- };
64
- declare function isJWTError<T extends JWTErrorCode>(error: unknown, code: T): error is JWTError<T>;
65
- declare function isJWTError(error: unknown): error is JWTError;
66
- //#endregion
67
- export { isJWTError as i, JWTErrorCauseMap as n, JWTErrorCode as r, JWTError as t };