unjwt 0.2.1 → 0.4.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/dist/index.mjs CHANGED
@@ -1,141 +1,5 @@
1
- import { subtle } from 'unjwt/crypto';
2
-
3
- const DEFAULT_SIGNATURE_METHOD = "HMAC";
4
- const DEFAULT_HASH_METHODS = "SHA-256";
5
- const textEncoder = new TextEncoder();
6
- async function createSignature(key, algorithm, data) {
7
- const encoded = textEncoder.encode(data);
8
- const signature = await subtle.sign(algorithm, key, encoded);
9
- return encodeToBase64Url(signature);
10
- }
11
- async function importKey(options) {
12
- const {
13
- secret,
14
- usage = "sign",
15
- name = DEFAULT_SIGNATURE_METHOD,
16
- hash = DEFAULT_HASH_METHODS
17
- } = { ...options };
18
- const encodedKey = textEncoder.encode(secret);
19
- return await subtle.importKey(
20
- "raw",
21
- encodedKey,
22
- { name, hash },
23
- false,
24
- [usage]
25
- );
26
- }
27
- function encodeToBase64Url(input) {
28
- let data;
29
- if (typeof input === "string")
30
- data = textEncoder.encode(input);
31
- else if (input instanceof ArrayBuffer)
32
- data = new Uint8Array(input);
33
- else
34
- data = textEncoder.encode(JSON.stringify(input));
35
- const base64 = btoa(String.fromCodePoint(...data));
36
- return base64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
37
- }
38
- function decodeFromBase64Url(base64Url) {
39
- const base64 = base64Url.replace(/-/g, "+").replace(/_/g, "/");
40
- return atob(base64);
41
- }
42
- function decodeFromBase64UrlToBuffer(base64Url) {
43
- const bytes = decodeFromBase64Url(base64Url);
44
- const buffer = Uint8Array.from(bytes, (c) => c.codePointAt(0));
45
- return buffer.buffer;
46
- }
47
-
48
- function decodeJWT(token) {
49
- try {
50
- return _decodeJWT(token);
51
- } catch {
52
- }
53
- }
54
- function _decodeJWT(token) {
55
- const parts = String(token).split(".");
56
- if (parts.length !== 3)
57
- throw new Error("Invalid token format");
58
- const [, payload] = parts;
59
- return JSON.parse(decodeFromBase64Url(payload));
60
- }
61
-
62
- const headerAlgMap = {
63
- HMAC: "HS",
64
- RSA: "RS",
65
- ECDSA: "ES"
66
- };
67
- async function signJWT(options) {
68
- const {
69
- payload = {},
70
- secret,
71
- issuer,
72
- audience,
73
- expires = 30,
74
- signatureMethod = DEFAULT_SIGNATURE_METHOD,
75
- hashMethod = DEFAULT_HASH_METHODS
76
- } = { ...options };
77
- const key = await importKey({
78
- secret,
79
- name: signatureMethod,
80
- hash: hashMethod
81
- });
82
- const header = {
83
- typ: "JWT",
84
- alg: `${headerAlgMap[signatureMethod]}${hashMethod.split("-")[1]}`
85
- };
86
- const iat = Math.floor(Date.now() / 1e3);
87
- const exp = iat + expires * 24 * 60 * 60;
88
- const jwtPayload = {
89
- ...payload,
90
- iss: issuer,
91
- aud: audience,
92
- iat,
93
- exp
94
- };
95
- const signature = await createSignature(
96
- key,
97
- signatureMethod,
98
- `${encodeToBase64Url(header)}.${encodeToBase64Url(jwtPayload)}`
99
- );
100
- return `${encodeToBase64Url(header)}.${encodeToBase64Url(
101
- jwtPayload
102
- )}.${signature}`;
103
- }
104
-
105
- async function verifyJWT(options) {
106
- const {
107
- token,
108
- secret,
109
- issuer,
110
- audience,
111
- leeway = 60,
112
- signatureMethod = DEFAULT_SIGNATURE_METHOD,
113
- hashMethod = DEFAULT_HASH_METHODS
114
- } = { ...options };
115
- const [header, payload, signature] = String(token).split(".");
116
- const key = await importKey({
117
- secret,
118
- usage: "verify",
119
- name: signatureMethod,
120
- hash: hashMethod
121
- });
122
- const isValid = await subtle.verify(
123
- signatureMethod,
124
- key,
125
- decodeFromBase64UrlToBuffer(signature),
126
- textEncoder.encode(`${header}.${payload}`)
127
- );
128
- if (!isValid)
129
- throw new Error("Invalid JWT signature");
130
- let decodedPayload;
131
- try {
132
- decodedPayload = JSON.parse(decodeFromBase64Url(payload));
133
- } catch {
134
- throw new Error("Invalid JWT payload");
135
- }
136
- const now = Math.floor(Date.now() / 1e3);
137
- if (issuer !== decodedPayload.iss || (Array.isArray(decodedPayload.aud) ? !decodedPayload.aud.includes(audience) : audience !== decodedPayload.aud) || decodedPayload.exp && now > decodedPayload.exp + leeway || decodedPayload.nbf && now < decodedPayload.nbf - leeway)
138
- throw new Error("Invalid JWT claims");
139
- }
140
-
141
- export { _decodeJWT, decodeJWT, signJWT, verifyJWT };
1
+ export { j as jwe } from './shared/unjwt._GivNhs2.mjs';
2
+ export { j as jwk } from './shared/unjwt.C9ELsKeK.mjs';
3
+ export { j as jws } from './shared/unjwt.KOd0vXyx.mjs';
4
+ import './shared/unjwt.DPTwlVpK.mjs';
5
+ import './shared/unjwt.DD0p18Gd.mjs';
package/dist/jwe.d.mts ADDED
@@ -0,0 +1,3 @@
1
+ export { J as JWE_DEFAULTS, s as seal, u as unseal } from './shared/unjwt.Dr-mxtq9.mjs';
2
+ import './shared/unjwt.4uzJv0cA.mjs';
3
+ import './shared/unjwt.zb2wBNCJ.mjs';
package/dist/jwe.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ export { J as JWE_DEFAULTS, s as seal, u as unseal } from './shared/unjwt.DGsIvgyn.js';
2
+ import './shared/unjwt.ChP7VhqI.js';
3
+ import './shared/unjwt.zb2wBNCJ.js';
package/dist/jwe.mjs ADDED
@@ -0,0 +1,3 @@
1
+ import './shared/unjwt.DPTwlVpK.mjs';
2
+ import './shared/unjwt.DD0p18Gd.mjs';
3
+ export { J as JWE_DEFAULTS, s as seal, u as unseal } from './shared/unjwt._GivNhs2.mjs';
package/dist/jwk.d.mts ADDED
@@ -0,0 +1,2 @@
1
+ import './shared/unjwt.zb2wBNCJ.mjs';
2
+ export { e as exportKey, g as generateKey, i as importKey } from './shared/unjwt.A7HKFx3n.mjs';
package/dist/jwk.d.ts ADDED
@@ -0,0 +1,2 @@
1
+ import './shared/unjwt.zb2wBNCJ.js';
2
+ export { e as exportKey, g as generateKey, i as importKey } from './shared/unjwt.CVUxLNoy.js';
package/dist/jwk.mjs ADDED
@@ -0,0 +1,2 @@
1
+ import './shared/unjwt.DPTwlVpK.mjs';
2
+ export { e as exportKey, g as generateKey, i as importKey } from './shared/unjwt.C9ELsKeK.mjs';
package/dist/jws.d.mts ADDED
@@ -0,0 +1,3 @@
1
+ import './shared/unjwt.zb2wBNCJ.mjs';
2
+ export { J as JWS_DEFAULTS, s as sign, v as verify } from './shared/unjwt.BdjvpIUY.mjs';
3
+ import './shared/unjwt.4uzJv0cA.mjs';
package/dist/jws.d.ts ADDED
@@ -0,0 +1,3 @@
1
+ import './shared/unjwt.zb2wBNCJ.js';
2
+ export { J as JWS_DEFAULTS, s as sign, v as verify } from './shared/unjwt.BmjmfFWo.js';
3
+ import './shared/unjwt.ChP7VhqI.js';
package/dist/jws.mjs ADDED
@@ -0,0 +1,4 @@
1
+ import './shared/unjwt.DPTwlVpK.mjs';
2
+ import './shared/unjwt.DD0p18Gd.mjs';
3
+ import './shared/unjwt.C9ELsKeK.mjs';
4
+ export { J as JWS_DEFAULTS, s as sign, v as verify } from './shared/unjwt.KOd0vXyx.mjs';
@@ -0,0 +1,110 @@
1
+ import { J as JWK } from './unjwt.zb2wBNCJ.mjs';
2
+
3
+ /** Header Parameters common to JWE and JWS */
4
+ interface JoseHeaderParameters {
5
+ /** "kid" (Key ID) Header Parameter */
6
+ kid?: string;
7
+ /** "x5t" (X.509 Certificate SHA-1 Thumbprint) Header Parameter */
8
+ x5t?: string;
9
+ /** "x5c" (X.509 Certificate Chain) Header Parameter */
10
+ x5c?: string[];
11
+ /** "x5u" (X.509 URL) Header Parameter */
12
+ x5u?: string;
13
+ /** "jku" (JWK Set URL) Header Parameter */
14
+ jku?: string;
15
+ /** "jwk" (JSON Web Key) Header Parameter */
16
+ jwk?: Pick<JWK, "kty" | "crv" | "x" | "y" | "e" | "n">;
17
+ /** "typ" (Type) Header Parameter */
18
+ typ?: string;
19
+ /** "cty" (Content Type) Header Parameter */
20
+ cty?: string;
21
+ /** "crit" (Critical) Header Parameter */
22
+ crit?: string[];
23
+ /** Any other JWS/JWE Header member. */
24
+ [propName: string]: unknown;
25
+ }
26
+
27
+ /**
28
+ * Supported key wrapping algorithms
29
+ */
30
+ declare const KEY_WRAPPING_ALGORITHMS: Readonly<{
31
+ "PBES2-HS256+A128KW": {
32
+ hash: string;
33
+ keyLength: number;
34
+ };
35
+ "PBES2-HS384+A192KW": {
36
+ hash: string;
37
+ keyLength: number;
38
+ };
39
+ "PBES2-HS512+A256KW": {
40
+ hash: string;
41
+ keyLength: number;
42
+ };
43
+ }>;
44
+ /**
45
+ * Supported JWS symmetric algorithms
46
+ */
47
+ declare const JWS_SYMMETRIC_ALGORITHMS: Readonly<{
48
+ HS256: {
49
+ hash: string;
50
+ };
51
+ HS384: {
52
+ hash: string;
53
+ };
54
+ HS512: {
55
+ hash: string;
56
+ };
57
+ }>;
58
+ /**
59
+ * Supported content encryption algorithms
60
+ */
61
+ declare const CONTENT_ENCRYPTION_ALGORITHMS: Readonly<{
62
+ A128GCM: {
63
+ type: string;
64
+ keyLength: number;
65
+ tagLength: number;
66
+ ivLength: number;
67
+ };
68
+ A192GCM: {
69
+ type: string;
70
+ keyLength: number;
71
+ tagLength: number;
72
+ ivLength: number;
73
+ };
74
+ A256GCM: {
75
+ type: string;
76
+ keyLength: number;
77
+ tagLength: number;
78
+ ivLength: number;
79
+ };
80
+ "A128CBC-HS256": {
81
+ type: string;
82
+ keyLength: number;
83
+ encKeyLength: number;
84
+ macKeyLength: number;
85
+ tagLength: number;
86
+ ivLength: number;
87
+ macAlgorithm: string;
88
+ };
89
+ "A192CBC-HS384": {
90
+ type: string;
91
+ keyLength: number;
92
+ encKeyLength: number;
93
+ macKeyLength: number;
94
+ tagLength: number;
95
+ ivLength: number;
96
+ macAlgorithm: string;
97
+ };
98
+ "A256CBC-HS512": {
99
+ type: string;
100
+ keyLength: number;
101
+ encKeyLength: number;
102
+ macKeyLength: number;
103
+ tagLength: number;
104
+ ivLength: number;
105
+ macAlgorithm: string;
106
+ };
107
+ }>;
108
+
109
+ export { CONTENT_ENCRYPTION_ALGORITHMS as C, KEY_WRAPPING_ALGORITHMS as K, JWS_SYMMETRIC_ALGORITHMS as a };
110
+ export type { JoseHeaderParameters as J };
@@ -0,0 +1,52 @@
1
+ import { J as JWK } from './unjwt.zb2wBNCJ.mjs';
2
+
3
+ /**
4
+ * Generates a new cryptographic key as a JWK object.
5
+ * Currently supports symmetric keys ('oct'). Future versions will support asymmetric keys.
6
+ *
7
+ * @param type The type of key to generate. Currently only 'oct' (symmetric) is supported.
8
+ * For 'oct': requires `length` option.
9
+ * Future types like 'RSA' or 'EC' will require different options.
10
+ * @param options Generation options specific to the key type.
11
+ * @param options.length For 'oct' keys: Key length in bits (e.g., 128, 192, 256, 512).
12
+ * @param options.alg Optional JWA algorithm identifier (e.g., "HS256", "A128KW") to include in the JWK.
13
+ *
14
+ * @returns Promise resolving to the generated key as a JWK object.
15
+ * @throws Error if the key type or options are invalid/unsupported.
16
+ */
17
+ declare function generateKey(type: "oct", length: 128 | 192 | 256 | 512, jwk?: Omit<JWK, "kty" | "k">): Promise<JWK>;
18
+ /**
19
+ * Exports a CryptoKey to its JWK representation.
20
+ * Supports symmetric ('oct') keys. Future versions will support asymmetric keys.
21
+ *
22
+ * @param key The CryptoKey to export. Must be extractable.
23
+ *
24
+ * @returns Promise resolving to the JWK representation.
25
+ * @throws Error if the key is not extractable or its type is unsupported for export.
26
+ */
27
+ declare function exportKey(key: CryptoKey): Promise<JWK>;
28
+ /**
29
+ * Imports a symmetric key from various formats (JWK, raw bytes, string) into a CryptoKey.
30
+ *
31
+ * @param key The key material (JWK object, Uint8Array, or string).
32
+ * @param algorithm The Web Crypto AlgorithmIdentifier to import the key for (e.g., HmacImportParams, AesKeyAlgorithm).
33
+ * @param extractable Whether the imported key should be extractable.
34
+ * @param keyUsages The allowed key usages for the imported CryptoKey.
35
+ *
36
+ * @returns Promise resolving to the imported CryptoKey.
37
+ * @throws Error if the key format is invalid or unsupported for symmetric import.
38
+ */
39
+ declare function importKey(key: JWK | string | Uint8Array, algorithm: AlgorithmIdentifier | HmacImportParams | AesKeyAlgorithm, extractable: boolean, keyUsages: KeyUsage[]): Promise<CryptoKey>;
40
+
41
+ declare const jwk_exportKey: typeof exportKey;
42
+ declare const jwk_generateKey: typeof generateKey;
43
+ declare const jwk_importKey: typeof importKey;
44
+ declare namespace jwk {
45
+ export {
46
+ jwk_exportKey as exportKey,
47
+ jwk_generateKey as generateKey,
48
+ jwk_importKey as importKey,
49
+ };
50
+ }
51
+
52
+ export { exportKey as e, generateKey as g, importKey as i, jwk as j };
@@ -0,0 +1,79 @@
1
+ import { J as JWK } from './unjwt.zb2wBNCJ.mjs';
2
+ import { a as JWS_SYMMETRIC_ALGORITHMS, J as JoseHeaderParameters } from './unjwt.4uzJv0cA.mjs';
3
+
4
+ /** Supported JWS Symmetric Algorithm types */
5
+ type JWSSymmetricAlgorithm = keyof typeof JWS_SYMMETRIC_ALGORITHMS;
6
+ /** Supported JWS Algorithm types */
7
+ type JWSAlgorithm = JWSSymmetricAlgorithm;
8
+ /** Recognized JWS Header Parameters, any other Header Members may also be present. */
9
+ interface JWSHeaderParameters extends JoseHeaderParameters {
10
+ /** JWS "alg" (Algorithm) Header Parameter */
11
+ alg?: JWSAlgorithm;
12
+ /**
13
+ * This JWS Extension Header Parameter modifies the JWS Payload representation and the JWS Signing
14
+ * Input computation as per {@link https://www.rfc-editor.org/rfc/rfc7797 RFC7797}.
15
+ */
16
+ b64?: boolean;
17
+ }
18
+ /**
19
+ * JWS (JSON Web Signature) options for signing
20
+ */
21
+ interface JWSSignOptions {
22
+ /**
23
+ * Additional protected header parameters
24
+ */
25
+ protectedHeader?: JWSHeaderParameters;
26
+ }
27
+
28
+ /** The default JWS algorithm. */
29
+ declare const JWS_DEFAULTS: Readonly<{
30
+ alg: JWSSymmetricAlgorithm;
31
+ }>;
32
+ /**
33
+ * Signs data using JWS with a symmetric key (HMAC).
34
+ * @param payload The data to sign.
35
+ * @param secret The symmetric secret key.
36
+ * @param options Optional parameters for signing.
37
+ * @returns Promise resolving to the compact JWS token.
38
+ */
39
+ declare function sign(payload: string | Uint8Array, secret: JWK | string | Uint8Array, options?: JWSSignOptions): Promise<string>;
40
+ /**
41
+ * Verifies a JWS token signed with a symmetric key (HMAC).
42
+ * @param token The JWS token string in compact serialization format.
43
+ * @param secret The symmetric secret key used for signing.
44
+ * @returns Promise resolving to the verified payload as a string.
45
+ */
46
+ declare function verify(token: string, secret: JWK | string | Uint8Array): Promise<string>;
47
+ /**
48
+ * Verifies a JWS token signed with a symmetric key (HMAC).
49
+ * @param token The JWS token string in compact serialization format.
50
+ * @param secret The symmetric secret key used for signing.
51
+ * @param options Verification options.
52
+ * @returns Promise resolving to the verified payload as a string.
53
+ */
54
+ declare function verify(token: string, secret: JWK | string | Uint8Array, options: {
55
+ textOutput: true;
56
+ }): Promise<string>;
57
+ /**
58
+ * Verifies a JWS token signed with a symmetric key (HMAC).
59
+ * @param token The JWS token string in compact serialization format.
60
+ * @param secret The symmetric secret key used for signing.
61
+ * @param options Verification options.
62
+ * @returns Promise resolving to the verified payload as a Uint8Array.
63
+ */
64
+ declare function verify(token: string, secret: JWK | string | Uint8Array, options: {
65
+ textOutput: false;
66
+ }): Promise<Uint8Array>;
67
+
68
+ declare const jws_JWS_DEFAULTS: typeof JWS_DEFAULTS;
69
+ declare const jws_sign: typeof sign;
70
+ declare const jws_verify: typeof verify;
71
+ declare namespace jws {
72
+ export {
73
+ jws_JWS_DEFAULTS as JWS_DEFAULTS,
74
+ jws_sign as sign,
75
+ jws_verify as verify,
76
+ };
77
+ }
78
+
79
+ export { JWS_DEFAULTS as J, jws as j, sign as s, verify as v };
@@ -0,0 +1,79 @@
1
+ import { J as JWK } from './unjwt.zb2wBNCJ.js';
2
+ import { a as JWS_SYMMETRIC_ALGORITHMS, J as JoseHeaderParameters } from './unjwt.ChP7VhqI.js';
3
+
4
+ /** Supported JWS Symmetric Algorithm types */
5
+ type JWSSymmetricAlgorithm = keyof typeof JWS_SYMMETRIC_ALGORITHMS;
6
+ /** Supported JWS Algorithm types */
7
+ type JWSAlgorithm = JWSSymmetricAlgorithm;
8
+ /** Recognized JWS Header Parameters, any other Header Members may also be present. */
9
+ interface JWSHeaderParameters extends JoseHeaderParameters {
10
+ /** JWS "alg" (Algorithm) Header Parameter */
11
+ alg?: JWSAlgorithm;
12
+ /**
13
+ * This JWS Extension Header Parameter modifies the JWS Payload representation and the JWS Signing
14
+ * Input computation as per {@link https://www.rfc-editor.org/rfc/rfc7797 RFC7797}.
15
+ */
16
+ b64?: boolean;
17
+ }
18
+ /**
19
+ * JWS (JSON Web Signature) options for signing
20
+ */
21
+ interface JWSSignOptions {
22
+ /**
23
+ * Additional protected header parameters
24
+ */
25
+ protectedHeader?: JWSHeaderParameters;
26
+ }
27
+
28
+ /** The default JWS algorithm. */
29
+ declare const JWS_DEFAULTS: Readonly<{
30
+ alg: JWSSymmetricAlgorithm;
31
+ }>;
32
+ /**
33
+ * Signs data using JWS with a symmetric key (HMAC).
34
+ * @param payload The data to sign.
35
+ * @param secret The symmetric secret key.
36
+ * @param options Optional parameters for signing.
37
+ * @returns Promise resolving to the compact JWS token.
38
+ */
39
+ declare function sign(payload: string | Uint8Array, secret: JWK | string | Uint8Array, options?: JWSSignOptions): Promise<string>;
40
+ /**
41
+ * Verifies a JWS token signed with a symmetric key (HMAC).
42
+ * @param token The JWS token string in compact serialization format.
43
+ * @param secret The symmetric secret key used for signing.
44
+ * @returns Promise resolving to the verified payload as a string.
45
+ */
46
+ declare function verify(token: string, secret: JWK | string | Uint8Array): Promise<string>;
47
+ /**
48
+ * Verifies a JWS token signed with a symmetric key (HMAC).
49
+ * @param token The JWS token string in compact serialization format.
50
+ * @param secret The symmetric secret key used for signing.
51
+ * @param options Verification options.
52
+ * @returns Promise resolving to the verified payload as a string.
53
+ */
54
+ declare function verify(token: string, secret: JWK | string | Uint8Array, options: {
55
+ textOutput: true;
56
+ }): Promise<string>;
57
+ /**
58
+ * Verifies a JWS token signed with a symmetric key (HMAC).
59
+ * @param token The JWS token string in compact serialization format.
60
+ * @param secret The symmetric secret key used for signing.
61
+ * @param options Verification options.
62
+ * @returns Promise resolving to the verified payload as a Uint8Array.
63
+ */
64
+ declare function verify(token: string, secret: JWK | string | Uint8Array, options: {
65
+ textOutput: false;
66
+ }): Promise<Uint8Array>;
67
+
68
+ declare const jws_JWS_DEFAULTS: typeof JWS_DEFAULTS;
69
+ declare const jws_sign: typeof sign;
70
+ declare const jws_verify: typeof verify;
71
+ declare namespace jws {
72
+ export {
73
+ jws_JWS_DEFAULTS as JWS_DEFAULTS,
74
+ jws_sign as sign,
75
+ jws_verify as verify,
76
+ };
77
+ }
78
+
79
+ export { JWS_DEFAULTS as J, jws as j, sign as s, verify as v };
@@ -0,0 +1,120 @@
1
+ import { r as randomBytes, b as base64UrlEncode, t as textEncoder } from './unjwt.DPTwlVpK.mjs';
2
+
3
+ async function generateKey(type, length, options) {
4
+ switch (type) {
5
+ case "oct": {
6
+ if (!length || typeof length !== "number" || ![128, 192, 256, 512].includes(length)) {
7
+ throw new Error(
8
+ "Invalid options for 'oct' key generation. 'length' (128, 192, 256, or 512) is required."
9
+ );
10
+ }
11
+ const keyBytes = randomBytes(length / 8);
12
+ const jwk = {
13
+ ext: true,
14
+ // Default extractable
15
+ ...options,
16
+ // TODO: do we want to allow this level of control?
17
+ kty: "oct",
18
+ k: base64UrlEncode(keyBytes)
19
+ };
20
+ return jwk;
21
+ }
22
+ // Add cases for 'RSA', 'EC'
23
+ default: {
24
+ throw new Error(`Unsupported key type for generation: ${type}`);
25
+ }
26
+ }
27
+ }
28
+ async function exportKey(key) {
29
+ if (!key.extractable) {
30
+ throw new Error("Key must be extractable to export to JWK format.");
31
+ }
32
+ if (key.type === "secret") {
33
+ try {
34
+ const jwk2 = await crypto.subtle.exportKey("jwk", key);
35
+ if (jwk2.kty === "oct" && typeof jwk2.k === "string") {
36
+ const finalJwk = {
37
+ ...jwk2,
38
+ kty: "oct",
39
+ key_ops: jwk2.key_ops || key.usages,
40
+ ext: jwk2.ext ?? key.extractable
41
+ };
42
+ if (!finalJwk.alg && key.algorithm.name === "HMAC") {
43
+ finalJwk.alg = `HS${key.algorithm.hash.name.split("-")[1]}`;
44
+ } else if (!finalJwk.alg) {
45
+ finalJwk.alg = key.algorithm.name;
46
+ }
47
+ return finalJwk;
48
+ }
49
+ } catch {
50
+ }
51
+ const rawKey = await crypto.subtle.exportKey("raw", key);
52
+ const jwk = {
53
+ kty: "oct",
54
+ k: base64UrlEncode(new Uint8Array(rawKey)),
55
+ // Infer JWA algorithm name
56
+ alg: key.algorithm.name === "HMAC" ? `HS${key.algorithm.hash.name.split("-")[1]}` : key.algorithm.name,
57
+ // Use algorithm name directly (e.g., AES-KW)
58
+ key_ops: key.usages,
59
+ ext: key.extractable
60
+ };
61
+ return jwk;
62
+ } else if (key.type === "public" || key.type === "private") {
63
+ try {
64
+ const jwk = await crypto.subtle.exportKey("jwk", key);
65
+ return jwk;
66
+ } catch (error) {
67
+ throw new Error(`Failed to export asymmetric key to JWK: ${error}`);
68
+ }
69
+ } else {
70
+ throw new Error(`Unsupported CryptoKey type for export: ${key.type}`);
71
+ }
72
+ }
73
+ async function importKey(key, algorithm, extractable, keyUsages) {
74
+ if (typeof key === "string") {
75
+ const keyData = textEncoder.encode(key);
76
+ return crypto.subtle.importKey(
77
+ "raw",
78
+ keyData,
79
+ algorithm,
80
+ extractable,
81
+ keyUsages
82
+ );
83
+ } else if (key instanceof Uint8Array) {
84
+ const keyData = key;
85
+ return crypto.subtle.importKey(
86
+ "raw",
87
+ keyData,
88
+ algorithm,
89
+ extractable,
90
+ keyUsages
91
+ );
92
+ } else if (typeof key === "object" && key !== null && key.kty === "oct") {
93
+ if (typeof key.k !== "string") {
94
+ throw new TypeError(
95
+ "Symmetric JWK must contain the 'k' parameter as a string"
96
+ );
97
+ }
98
+ const keyData = key;
99
+ return crypto.subtle.importKey(
100
+ "jwk",
101
+ keyData,
102
+ algorithm,
103
+ extractable,
104
+ keyUsages
105
+ );
106
+ } else {
107
+ throw new Error(
108
+ "Invalid key format. Expected symmetric JWK (oct), Uint8Array, or string."
109
+ );
110
+ }
111
+ }
112
+
113
+ const jwk = {
114
+ __proto__: null,
115
+ exportKey: exportKey,
116
+ generateKey: generateKey,
117
+ importKey: importKey
118
+ };
119
+
120
+ export { exportKey as e, generateKey as g, importKey as i, jwk as j };
@@ -0,0 +1,52 @@
1
+ import { J as JWK } from './unjwt.zb2wBNCJ.js';
2
+
3
+ /**
4
+ * Generates a new cryptographic key as a JWK object.
5
+ * Currently supports symmetric keys ('oct'). Future versions will support asymmetric keys.
6
+ *
7
+ * @param type The type of key to generate. Currently only 'oct' (symmetric) is supported.
8
+ * For 'oct': requires `length` option.
9
+ * Future types like 'RSA' or 'EC' will require different options.
10
+ * @param options Generation options specific to the key type.
11
+ * @param options.length For 'oct' keys: Key length in bits (e.g., 128, 192, 256, 512).
12
+ * @param options.alg Optional JWA algorithm identifier (e.g., "HS256", "A128KW") to include in the JWK.
13
+ *
14
+ * @returns Promise resolving to the generated key as a JWK object.
15
+ * @throws Error if the key type or options are invalid/unsupported.
16
+ */
17
+ declare function generateKey(type: "oct", length: 128 | 192 | 256 | 512, jwk?: Omit<JWK, "kty" | "k">): Promise<JWK>;
18
+ /**
19
+ * Exports a CryptoKey to its JWK representation.
20
+ * Supports symmetric ('oct') keys. Future versions will support asymmetric keys.
21
+ *
22
+ * @param key The CryptoKey to export. Must be extractable.
23
+ *
24
+ * @returns Promise resolving to the JWK representation.
25
+ * @throws Error if the key is not extractable or its type is unsupported for export.
26
+ */
27
+ declare function exportKey(key: CryptoKey): Promise<JWK>;
28
+ /**
29
+ * Imports a symmetric key from various formats (JWK, raw bytes, string) into a CryptoKey.
30
+ *
31
+ * @param key The key material (JWK object, Uint8Array, or string).
32
+ * @param algorithm The Web Crypto AlgorithmIdentifier to import the key for (e.g., HmacImportParams, AesKeyAlgorithm).
33
+ * @param extractable Whether the imported key should be extractable.
34
+ * @param keyUsages The allowed key usages for the imported CryptoKey.
35
+ *
36
+ * @returns Promise resolving to the imported CryptoKey.
37
+ * @throws Error if the key format is invalid or unsupported for symmetric import.
38
+ */
39
+ declare function importKey(key: JWK | string | Uint8Array, algorithm: AlgorithmIdentifier | HmacImportParams | AesKeyAlgorithm, extractable: boolean, keyUsages: KeyUsage[]): Promise<CryptoKey>;
40
+
41
+ declare const jwk_exportKey: typeof exportKey;
42
+ declare const jwk_generateKey: typeof generateKey;
43
+ declare const jwk_importKey: typeof importKey;
44
+ declare namespace jwk {
45
+ export {
46
+ jwk_exportKey as exportKey,
47
+ jwk_generateKey as generateKey,
48
+ jwk_importKey as importKey,
49
+ };
50
+ }
51
+
52
+ export { exportKey as e, generateKey as g, importKey as i, jwk as j };