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.
@@ -0,0 +1,213 @@
1
+ import { t as textEncoder, r as randomBytes, b as base64UrlEncode, a as textDecoder, c as base64UrlDecode, d as concatUint8Arrays } from './unjwt.DPTwlVpK.mjs';
2
+ import { l as lookupAlgorithm, K as KEY_WRAPPING_ALGORITHMS, C as CONTENT_ENCRYPTION_ALGORITHMS } from './unjwt.DD0p18Gd.mjs';
3
+
4
+ const JWE_DEFAULTS = /* @__PURE__ */ Object.freeze({
5
+ saltSize: 16,
6
+ iterations: 2048,
7
+ alg: "PBES2-HS256+A128KW",
8
+ enc: "A256GCM"
9
+ });
10
+ async function seal(data, password, options = {}) {
11
+ const protectedHeader = options.protectedHeader || {};
12
+ const iterations = protectedHeader.p2c || options.iterations || JWE_DEFAULTS.iterations;
13
+ const saltSize = options.saltSize || JWE_DEFAULTS.saltSize;
14
+ const alg = protectedHeader.alg || JWE_DEFAULTS.alg;
15
+ const enc = protectedHeader.enc || JWE_DEFAULTS.enc;
16
+ validateKeyWrappingAlgorithm(alg);
17
+ const encConfig = validateContentEncryptionAlgorithm(enc);
18
+ const plaintext = typeof data === "string" ? textEncoder.encode(data) : data;
19
+ const saltInput = randomBytes(saltSize);
20
+ const header = {
21
+ alg,
22
+ enc,
23
+ p2s: base64UrlEncode(saltInput),
24
+ p2c: iterations,
25
+ ...protectedHeader
26
+ };
27
+ const encodedHeader = base64UrlEncode(
28
+ textEncoder.encode(JSON.stringify(header))
29
+ );
30
+ const derivedKey = await deriveKeyFromPassword(
31
+ password,
32
+ saltInput,
33
+ iterations,
34
+ alg
35
+ );
36
+ const {
37
+ wrappedKey,
38
+ rawCek: _,
39
+ cek
40
+ } = await generateAndWrapCEK(derivedKey, encConfig);
41
+ const iv = randomBytes(encConfig.ivLength);
42
+ let ciphertext;
43
+ let tag;
44
+ if (encConfig.type === "gcm") {
45
+ const result = await encryptGCM(
46
+ plaintext,
47
+ cek,
48
+ iv,
49
+ textEncoder.encode(encodedHeader),
50
+ encConfig
51
+ );
52
+ ciphertext = result.ciphertext;
53
+ tag = result.tag;
54
+ } else {
55
+ throw new Error(`Unsupported encryption type: ${encConfig.type}`);
56
+ }
57
+ return [
58
+ encodedHeader,
59
+ base64UrlEncode(new Uint8Array(wrappedKey)),
60
+ base64UrlEncode(iv),
61
+ base64UrlEncode(ciphertext),
62
+ base64UrlEncode(tag)
63
+ ].join(".");
64
+ }
65
+ async function unseal(token, password, options = {}) {
66
+ if (!token) {
67
+ throw new Error("Missing JWE token");
68
+ }
69
+ const textOutput = options.textOutput !== false;
70
+ const [
71
+ encodedHeader,
72
+ encryptedKey,
73
+ encodedIv,
74
+ encodedCiphertext,
75
+ encodedTag
76
+ ] = token.split(".");
77
+ const header = JSON.parse(textDecoder.decode(base64UrlDecode(encodedHeader)));
78
+ const alg = header.alg;
79
+ const enc = header.enc;
80
+ validateKeyWrappingAlgorithm(alg);
81
+ const encConfig = validateContentEncryptionAlgorithm(enc);
82
+ const iterations = header.p2c;
83
+ const saltInput = base64UrlDecode(header.p2s);
84
+ const derivedKey = await deriveKeyFromPassword(
85
+ password,
86
+ saltInput,
87
+ iterations,
88
+ alg
89
+ );
90
+ const wrappedKey = base64UrlDecode(encryptedKey);
91
+ const iv = base64UrlDecode(encodedIv);
92
+ const ciphertext = base64UrlDecode(encodedCiphertext);
93
+ const tag = base64UrlDecode(encodedTag);
94
+ const cek = await unwrapCEK(wrappedKey, derivedKey, encConfig);
95
+ let decrypted;
96
+ if (encConfig.type === "gcm") {
97
+ decrypted = await decryptGCM(
98
+ ciphertext,
99
+ tag,
100
+ cek,
101
+ iv,
102
+ textEncoder.encode(encodedHeader)
103
+ );
104
+ } else {
105
+ throw new Error(`Unsupported encryption type: ${encConfig.type}`);
106
+ }
107
+ return textOutput ? textDecoder.decode(decrypted) : decrypted;
108
+ }
109
+ async function deriveKeyFromPassword(password, saltInput, iterations, alg) {
110
+ if (!password) {
111
+ throw new Error("Missing password");
112
+ }
113
+ const algConfig = validateKeyWrappingAlgorithm(alg);
114
+ const baseKey = await crypto.subtle.importKey(
115
+ "raw",
116
+ typeof password === "string" ? textEncoder.encode(password) : password,
117
+ { name: "PBKDF2" },
118
+ false,
119
+ ["deriveKey"]
120
+ );
121
+ const salt = concatUint8Arrays(
122
+ textEncoder.encode(alg),
123
+ new Uint8Array([0]),
124
+ saltInput
125
+ );
126
+ return crypto.subtle.deriveKey(
127
+ {
128
+ name: "PBKDF2",
129
+ hash: algConfig.hash,
130
+ salt,
131
+ iterations
132
+ },
133
+ baseKey,
134
+ { name: "AES-KW", length: algConfig.keyLength },
135
+ false,
136
+ ["wrapKey", "unwrapKey"]
137
+ );
138
+ }
139
+ function validateKeyWrappingAlgorithm(alg) {
140
+ return lookupAlgorithm(alg, KEY_WRAPPING_ALGORITHMS, "key wrapping");
141
+ }
142
+ function validateContentEncryptionAlgorithm(enc) {
143
+ return lookupAlgorithm(
144
+ enc,
145
+ CONTENT_ENCRYPTION_ALGORITHMS,
146
+ "content encryption"
147
+ );
148
+ }
149
+ async function generateAndWrapCEK(derivedKey, encConfig) {
150
+ if (encConfig.type === "gcm") {
151
+ const cek = await crypto.subtle.generateKey(
152
+ { name: "AES-GCM", length: encConfig.keyLength },
153
+ true,
154
+ ["encrypt", "decrypt", "wrapKey", "unwrapKey"]
155
+ );
156
+ const wrappedKey = await crypto.subtle.wrapKey("raw", cek, derivedKey, {
157
+ name: "AES-KW"
158
+ });
159
+ return { wrappedKey, rawCek: null, cek };
160
+ }
161
+ throw new Error(`Unsupported encryption type: ${encConfig.type}`);
162
+ }
163
+ async function unwrapCEK(wrappedKey, derivedKey, encConfig) {
164
+ if (encConfig.type === "gcm") {
165
+ return crypto.subtle.unwrapKey(
166
+ "raw",
167
+ wrappedKey,
168
+ derivedKey,
169
+ { name: "AES-KW" },
170
+ { name: "AES-GCM", length: encConfig.keyLength },
171
+ false,
172
+ ["decrypt"]
173
+ );
174
+ }
175
+ throw new Error(`Unsupported encryption type: ${encConfig.type}`);
176
+ }
177
+ async function encryptGCM(plaintext, cek, iv, aad, encConfig) {
178
+ const ciphertext = await crypto.subtle.encrypt(
179
+ {
180
+ name: "AES-GCM",
181
+ iv,
182
+ additionalData: aad
183
+ },
184
+ cek,
185
+ plaintext
186
+ );
187
+ const encrypted = new Uint8Array(ciphertext);
188
+ const tag = encrypted.slice(-encConfig.tagLength);
189
+ const ciphertextOutput = encrypted.slice(0, -encConfig.tagLength);
190
+ return { ciphertext: ciphertextOutput, tag };
191
+ }
192
+ async function decryptGCM(ciphertext, tag, cek, iv, aad) {
193
+ const encryptedData = concatUint8Arrays(ciphertext, tag);
194
+ const decrypted = await crypto.subtle.decrypt(
195
+ {
196
+ name: "AES-GCM",
197
+ iv,
198
+ additionalData: aad
199
+ },
200
+ cek,
201
+ encryptedData
202
+ );
203
+ return new Uint8Array(decrypted);
204
+ }
205
+
206
+ const jwe = {
207
+ __proto__: null,
208
+ JWE_DEFAULTS: JWE_DEFAULTS,
209
+ seal: seal,
210
+ unseal: unseal
211
+ };
212
+
213
+ export { JWE_DEFAULTS as J, jwe as j, seal as s, unseal as u };
@@ -0,0 +1,82 @@
1
+ /**
2
+ Based on https://github.com/panva/jose/tree/v6.0.10
3
+ Copyright (c) 2018 Filip Skokan.
4
+ https://github.com/panva/jose/blob/v6.0.10/LICENSE.md
5
+ */
6
+ /** Generic JSON Web Key Parameters. */
7
+ interface JWKParameters {
8
+ /** JWK "kty" (Key Type) Parameter */
9
+ kty?: string;
10
+ /**
11
+ * JWK "alg" (Algorithm) Parameter
12
+ *
13
+ * @see {@link https://github.com/panva/jose/issues/210 Algorithm Key Requirements}
14
+ */
15
+ alg?: string;
16
+ /** JWK "key_ops" (Key Operations) Parameter */
17
+ key_ops?: string[];
18
+ /** JWK "ext" (Extractable) Parameter */
19
+ ext?: boolean;
20
+ /** JWK "use" (Public Key Use) Parameter */
21
+ use?: string;
22
+ /** JWK "x5c" (X.509 Certificate Chain) Parameter */
23
+ x5c?: string[];
24
+ /** JWK "x5t" (X.509 Certificate SHA-1 Thumbprint) Parameter */
25
+ x5t?: string;
26
+ /** JWK "x5t#S256" (X.509 Certificate SHA-256 Thumbprint) Parameter */
27
+ "x5t#S256"?: string;
28
+ /** JWK "x5u" (X.509 URL) Parameter */
29
+ x5u?: string;
30
+ /** JWK "kid" (Key ID) Parameter */
31
+ kid?: string;
32
+ }
33
+ /**
34
+ * JSON Web Key ({@link https://www.rfc-editor.org/rfc/rfc7517 JWK}). "RSA", "EC", "OKP", and "oct"
35
+ * key types are supported.
36
+ *
37
+ * @see {@link JWK_OKP_Public}
38
+ * @see {@link JWK_OKP_Private}
39
+ * @see {@link JWK_EC_Public}
40
+ * @see {@link JWK_EC_Private}
41
+ * @see {@link JWK_RSA_Public}
42
+ * @see {@link JWK_RSA_Private}
43
+ * @see {@link JWK_oct}
44
+ */
45
+ interface JWK extends JWKParameters {
46
+ /**
47
+ * - EC JWK "crv" (Curve) Parameter
48
+ * - OKP JWK "crv" (The Subtype of Key Pair) Parameter
49
+ */
50
+ crv?: string;
51
+ /**
52
+ * - Private RSA JWK "d" (Private Exponent) Parameter
53
+ * - Private EC JWK "d" (ECC Private Key) Parameter
54
+ * - Private OKP JWK "d" (The Private Key) Parameter
55
+ */
56
+ d?: string;
57
+ /** Private RSA JWK "dp" (First Factor CRT Exponent) Parameter */
58
+ dp?: string;
59
+ /** Private RSA JWK "dq" (Second Factor CRT Exponent) Parameter */
60
+ dq?: string;
61
+ /** RSA JWK "e" (Exponent) Parameter */
62
+ e?: string;
63
+ /** Oct JWK "k" (Key Value) Parameter */
64
+ k?: string;
65
+ /** RSA JWK "n" (Modulus) Parameter */
66
+ n?: string;
67
+ /** Private RSA JWK "p" (First Prime Factor) Parameter */
68
+ p?: string;
69
+ /** Private RSA JWK "q" (Second Prime Factor) Parameter */
70
+ q?: string;
71
+ /** Private RSA JWK "qi" (First CRT Coefficient) Parameter */
72
+ qi?: string;
73
+ /**
74
+ * - EC JWK "x" (X Coordinate) Parameter
75
+ * - OKP JWK "x" (The public key) Parameter
76
+ */
77
+ x?: string;
78
+ /** EC JWK "y" (Y Coordinate) Parameter */
79
+ y?: string;
80
+ }
81
+
82
+ export type { JWK as J };
@@ -0,0 +1,82 @@
1
+ /**
2
+ Based on https://github.com/panva/jose/tree/v6.0.10
3
+ Copyright (c) 2018 Filip Skokan.
4
+ https://github.com/panva/jose/blob/v6.0.10/LICENSE.md
5
+ */
6
+ /** Generic JSON Web Key Parameters. */
7
+ interface JWKParameters {
8
+ /** JWK "kty" (Key Type) Parameter */
9
+ kty?: string;
10
+ /**
11
+ * JWK "alg" (Algorithm) Parameter
12
+ *
13
+ * @see {@link https://github.com/panva/jose/issues/210 Algorithm Key Requirements}
14
+ */
15
+ alg?: string;
16
+ /** JWK "key_ops" (Key Operations) Parameter */
17
+ key_ops?: string[];
18
+ /** JWK "ext" (Extractable) Parameter */
19
+ ext?: boolean;
20
+ /** JWK "use" (Public Key Use) Parameter */
21
+ use?: string;
22
+ /** JWK "x5c" (X.509 Certificate Chain) Parameter */
23
+ x5c?: string[];
24
+ /** JWK "x5t" (X.509 Certificate SHA-1 Thumbprint) Parameter */
25
+ x5t?: string;
26
+ /** JWK "x5t#S256" (X.509 Certificate SHA-256 Thumbprint) Parameter */
27
+ "x5t#S256"?: string;
28
+ /** JWK "x5u" (X.509 URL) Parameter */
29
+ x5u?: string;
30
+ /** JWK "kid" (Key ID) Parameter */
31
+ kid?: string;
32
+ }
33
+ /**
34
+ * JSON Web Key ({@link https://www.rfc-editor.org/rfc/rfc7517 JWK}). "RSA", "EC", "OKP", and "oct"
35
+ * key types are supported.
36
+ *
37
+ * @see {@link JWK_OKP_Public}
38
+ * @see {@link JWK_OKP_Private}
39
+ * @see {@link JWK_EC_Public}
40
+ * @see {@link JWK_EC_Private}
41
+ * @see {@link JWK_RSA_Public}
42
+ * @see {@link JWK_RSA_Private}
43
+ * @see {@link JWK_oct}
44
+ */
45
+ interface JWK extends JWKParameters {
46
+ /**
47
+ * - EC JWK "crv" (Curve) Parameter
48
+ * - OKP JWK "crv" (The Subtype of Key Pair) Parameter
49
+ */
50
+ crv?: string;
51
+ /**
52
+ * - Private RSA JWK "d" (Private Exponent) Parameter
53
+ * - Private EC JWK "d" (ECC Private Key) Parameter
54
+ * - Private OKP JWK "d" (The Private Key) Parameter
55
+ */
56
+ d?: string;
57
+ /** Private RSA JWK "dp" (First Factor CRT Exponent) Parameter */
58
+ dp?: string;
59
+ /** Private RSA JWK "dq" (Second Factor CRT Exponent) Parameter */
60
+ dq?: string;
61
+ /** RSA JWK "e" (Exponent) Parameter */
62
+ e?: string;
63
+ /** Oct JWK "k" (Key Value) Parameter */
64
+ k?: string;
65
+ /** RSA JWK "n" (Modulus) Parameter */
66
+ n?: string;
67
+ /** Private RSA JWK "p" (First Prime Factor) Parameter */
68
+ p?: string;
69
+ /** Private RSA JWK "q" (Second Prime Factor) Parameter */
70
+ q?: string;
71
+ /** Private RSA JWK "qi" (First CRT Coefficient) Parameter */
72
+ qi?: string;
73
+ /**
74
+ * - EC JWK "x" (X Coordinate) Parameter
75
+ * - OKP JWK "x" (The public key) Parameter
76
+ */
77
+ x?: string;
78
+ /** EC JWK "y" (Y Coordinate) Parameter */
79
+ y?: string;
80
+ }
81
+
82
+ export type { JWK as J };
package/package.json CHANGED
@@ -1,70 +1,60 @@
1
1
  {
2
2
  "name": "unjwt",
3
- "type": "module",
4
- "version": "0.2.1",
5
- "packageManager": "pnpm@8.6.12",
6
- "description": "Easy creation and verification of JSON Web Tokens (JWT)",
7
- "author": "Johann Schopplich <pkg@johannschopplich.com>",
3
+ "version": "0.4.0",
4
+ "description": "Low-level JWT utilities",
5
+ "repository": "sandros94/unjwt",
8
6
  "license": "MIT",
9
- "homepage": "https://github.com/johannschopplich/unjwt#readme",
10
- "repository": {
11
- "type": "git",
12
- "url": "git+https://github.com/johannschopplich/unjwt.git"
13
- },
14
- "bugs": {
15
- "url": "https://github.com/johannschopplich/unjwt/issues"
16
- },
17
- "keywords": [
18
- "cloudflare",
19
- "jwt",
20
- "serverless",
21
- "token",
22
- "worker"
23
- ],
24
7
  "sideEffects": false,
8
+ "type": "module",
9
+ "author": {
10
+ "name": "Sandro Circi",
11
+ "email": "sandro.circi@digitoolmedia.com"
12
+ },
25
13
  "exports": {
26
14
  ".": {
27
- "types": "./dist/index.d.ts",
28
- "import": "./dist/index.mjs"
15
+ "types": "./dist/index.d.mts",
16
+ "default": "./dist/index.mjs"
17
+ },
18
+ "./jwe": {
19
+ "types": "./dist/jwe.d.mts",
20
+ "default": "./dist/jwe.mjs"
29
21
  },
30
- "./crypto": {
31
- "browser": "./dist/crypto/web.mjs",
32
- "bun": "./dist/crypto/web.mjs",
33
- "deno": "./dist/crypto/web.mjs",
34
- "edge-light": "./dist/crypto/web.mjs",
35
- "edge-routine": "./dist/crypto/web.mjs",
36
- "lagon": "./dist/crypto/web.mjs",
37
- "netlify": "./dist/crypto/web.mjs",
38
- "react-native": "./dist/crypto/web.mjs",
39
- "wintercg": "./dist/crypto/web.mjs",
40
- "worker": "./dist/crypto/web.mjs",
41
- "workerd": "./dist/crypto/web.mjs",
42
- "node": {
43
- "types": "./dist/crypto/node.d.ts",
44
- "import": "./dist/crypto/node.mjs"
45
- },
46
- "types": "./dist/crypto/web.d.ts",
47
- "import": "./dist/crypto/web.mjs"
22
+ "./jwk": {
23
+ "types": "./dist/jwk.d.mts",
24
+ "default": "./dist/jwk.mjs"
25
+ },
26
+ "./jws": {
27
+ "types": "./dist/jws.d.mts",
28
+ "default": "./dist/jws.mjs"
48
29
  }
49
30
  },
50
- "types": "./dist/index.d.ts",
31
+ "main": "./dist/index.mjs",
32
+ "module": "./dist/index.mjs",
33
+ "types": "./dist/index.d.mts",
51
34
  "files": [
52
35
  "dist"
53
36
  ],
54
37
  "scripts": {
55
38
  "build": "unbuild",
56
- "dev": "unbuild --stub",
57
- "lint": "eslint .",
58
- "lint:fix": "eslint . --fix",
59
- "release": "bumpp --commit --push --tag",
60
- "test:types": "tsc --noEmit"
39
+ "dev": "vitest dev",
40
+ "lint": "eslint . && prettier -c .",
41
+ "lint:fix": "automd && eslint . --fix && prettier -w .",
42
+ "prepack": "pnpm build",
43
+ "release": "pnpm test && pnpm prepack && changelogen --release --push --publish",
44
+ "test": "pnpm lint && pnpm test:types && vitest run --coverage",
45
+ "test:types": "tsc --noEmit --skipLibCheck"
61
46
  },
62
47
  "devDependencies": {
63
- "@antfu/eslint-config": "^0.40.2",
64
- "@types/node": "^20.5.0",
65
- "bumpp": "^9.1.1",
66
- "eslint": "^8.47.0",
67
- "typescript": "^5.1.6",
68
- "unbuild": "^2.0.0-rc.0"
69
- }
48
+ "@types/node": "^22.13.13",
49
+ "@vitest/coverage-v8": "^3.0.9",
50
+ "automd": "^0.4.0",
51
+ "changelogen": "^0.6.1",
52
+ "eslint": "^9.23.0",
53
+ "eslint-config-unjs": "^0.4.2",
54
+ "prettier": "^3.5.3",
55
+ "typescript": "^5.8.2",
56
+ "unbuild": "^3.5.0",
57
+ "vitest": "^3.0.9"
58
+ },
59
+ "packageManager": "pnpm@10.7.0"
70
60
  }
@@ -1,5 +0,0 @@
1
- declare const subtle: Crypto['subtle'];
2
- declare const randomUUID: Crypto['randomUUID'];
3
- declare const getRandomValues: Crypto['getRandomValues'];
4
-
5
- export { getRandomValues, randomUUID, subtle };
@@ -1,5 +0,0 @@
1
- declare const subtle: Crypto['subtle'];
2
- declare const randomUUID: Crypto['randomUUID'];
3
- declare const getRandomValues: Crypto['getRandomValues'];
4
-
5
- export { getRandomValues, randomUUID, subtle };
@@ -1,11 +0,0 @@
1
- import nodeCrypto from 'node:crypto';
2
-
3
- const subtle = nodeCrypto.webcrypto?.subtle || {};
4
- const randomUUID = () => {
5
- return nodeCrypto.randomUUID();
6
- };
7
- const getRandomValues = (array) => {
8
- return nodeCrypto.webcrypto.getRandomValues(array);
9
- };
10
-
11
- export { getRandomValues, randomUUID, subtle };
@@ -1,5 +0,0 @@
1
- declare const subtle: Crypto['subtle'];
2
- declare const randomUUID: Crypto['randomUUID'];
3
- declare const getRandomValues: Crypto['getRandomValues'];
4
-
5
- export { getRandomValues, randomUUID, subtle };
@@ -1,5 +0,0 @@
1
- declare const subtle: Crypto['subtle'];
2
- declare const randomUUID: Crypto['randomUUID'];
3
- declare const getRandomValues: Crypto['getRandomValues'];
4
-
5
- export { getRandomValues, randomUUID, subtle };
@@ -1,10 +0,0 @@
1
- const webCrypto = globalThis.crypto;
2
- const subtle = webCrypto.subtle;
3
- const randomUUID = () => {
4
- return webCrypto.randomUUID();
5
- };
6
- const getRandomValues = (array) => {
7
- return webCrypto.getRandomValues(array);
8
- };
9
-
10
- export { getRandomValues, randomUUID, subtle };