@rio.js/enterprise 1.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/README.md +89 -0
- package/dist/adapter-factory-BTRALCLD-kJBwe70v.mjs +836 -0
- package/dist/better-auth-CStoaWiq.d.mts +10 -0
- package/dist/better-auth-CqfhQJYE.mjs +558 -0
- package/dist/better-auth.d.mts +2 -0
- package/dist/better-auth.mjs +17 -0
- package/dist/bun-sqlite-dialect-2R9nCsVF-DFs6tpGr.mjs +155 -0
- package/dist/client--1_AEBPu-8Ae9icC9.mjs +125 -0
- package/dist/client.d.mts +17 -0
- package/dist/client.mjs +381 -0
- package/dist/db-BVXTgOd3.mjs +681 -0
- package/dist/db-BadqSwVl.d.mts +9542 -0
- package/dist/db-schema.final-DWleoQm0.mjs +785 -0
- package/dist/db.d.mts +2 -0
- package/dist/db.mjs +3 -0
- package/dist/dialect-C6_pK3V9-CPJHWkYR.mjs +72 -0
- package/dist/dist-CygcgJYk.mjs +422 -0
- package/dist/env-DwlNAN_D-C1zHd0cf-Cdlw8sNp.mjs +289 -0
- package/dist/esm-C5TuvtGn.mjs +15816 -0
- package/dist/index.d.mts +6 -0
- package/dist/index.mjs +17 -0
- package/dist/init-D8lwWc90.mjs +27 -0
- package/dist/json-oFuWgANh-O1U6k3bL.mjs +3811 -0
- package/dist/kysely-adapter-D_seG51p.mjs +297 -0
- package/dist/memory-adapter-CY-oDozb.mjs +215 -0
- package/dist/misc-CbURQDlR-sLtUwwQY.mjs +7 -0
- package/dist/node-sqlite-dialect-CdC7L-ji-QLbJGmDc.mjs +155 -0
- package/dist/parser-bL7W2mQ0-YdTgjtji.mjs +140 -0
- package/dist/plugins-BNFht2HW.mjs +23358 -0
- package/dist/plugins.d.mts +1 -0
- package/dist/plugins.mjs +13 -0
- package/dist/react--VZQu7s1.mjs +560 -0
- package/dist/react.d.mts +1 -0
- package/dist/react.mjs +6 -0
- package/dist/server.d.mts +10 -0
- package/dist/server.mjs +45 -0
- package/dist/social-providers-DNfE9Ak7-Be5zMAEe.mjs +2920 -0
- package/dist/social-providers.d.mts +1 -0
- package/dist/social-providers.mjs +6 -0
- package/dist/verify-CN5Qc0e-.mjs +1183 -0
- package/package.json +98 -0
|
@@ -0,0 +1,3811 @@
|
|
|
1
|
+
import { f as logger, g as BetterAuthError } from "./env-DwlNAN_D-C1zHd0cf-Cdlw8sNp.mjs";
|
|
2
|
+
import { B as uint32be, C as JOSENotSupported, E as JWKInvalid, F as decode, H as base64, I as encode, L as concat, M as JWTClaimValidationFailed, P as JWTInvalid, R as decoder, T as JWEInvalid, U as base64Url, V as uint64be, _ as isKeyLike, a as subtleAlgorithm, b as checkEncCryptoKey, c as isJWK, d as importJWK, f as checkKeyLength, g as isCryptoKey, h as assertCryptoKey, i as getSigKey, j as JWSInvalid, l as validateAlgorithms, m as isDisjoint, n as JWTClaimsBuilder, o as checkKeyType, p as isObject, r as validateClaimsSet, s as normalizeKey, t as jwtVerify, u as validateCrit, v as isKeyObject, w as JWEDecryptionFailed, x as JOSEAlgNotAllowed, y as invalidKeyInput, z as encode$1 } from "./verify-CN5Qc0e-.mjs";
|
|
3
|
+
import { APIError } from "better-call";
|
|
4
|
+
import * as z$2 from "zod";
|
|
5
|
+
|
|
6
|
+
//#region ../better-auth/dist/context-BcO8kAU0-Crm4egyw.mjs
|
|
7
|
+
const AsyncLocalStoragePromise = import(
|
|
8
|
+
/* @vite-ignore */
|
|
9
|
+
/* webpackIgnore: true */
|
|
10
|
+
"node:async_hooks"
|
|
11
|
+
).then((mod) => mod.AsyncLocalStorage).catch((err) => {
|
|
12
|
+
if ("AsyncLocalStorage" in globalThis) return globalThis.AsyncLocalStorage;
|
|
13
|
+
console.warn("[better-auth] Warning: AsyncLocalStorage is not available in this environment. Some features may not work as expected.");
|
|
14
|
+
console.warn("[better-auth] Please read more about this warning at https://better-auth.com/docs/installation#mount-handler");
|
|
15
|
+
console.warn("[better-auth] If you are using Cloudflare Workers, please see: https://developers.cloudflare.com/workers/configuration/compatibility-flags/#nodejs-compatibility-flag");
|
|
16
|
+
throw err;
|
|
17
|
+
});
|
|
18
|
+
async function getAsyncLocalStorage() {
|
|
19
|
+
return AsyncLocalStoragePromise;
|
|
20
|
+
}
|
|
21
|
+
let currentContextAsyncStorage$1 = null;
|
|
22
|
+
const ensureAsyncStorage$3 = async () => {
|
|
23
|
+
if (!currentContextAsyncStorage$1) currentContextAsyncStorage$1 = new (await (getAsyncLocalStorage()))();
|
|
24
|
+
return currentContextAsyncStorage$1;
|
|
25
|
+
};
|
|
26
|
+
async function getCurrentAuthContext() {
|
|
27
|
+
const context = (await ensureAsyncStorage$3()).getStore();
|
|
28
|
+
if (!context) throw new Error("No auth context found. Please make sure you are calling this function within a `runWithEndpointContext` callback.");
|
|
29
|
+
return context;
|
|
30
|
+
}
|
|
31
|
+
async function runWithEndpointContext(context, fn) {
|
|
32
|
+
return (await ensureAsyncStorage$3()).run(context, fn);
|
|
33
|
+
}
|
|
34
|
+
let requestStateAsyncStorage = null;
|
|
35
|
+
const ensureAsyncStorage$2 = async () => {
|
|
36
|
+
if (!requestStateAsyncStorage) requestStateAsyncStorage = new (await (getAsyncLocalStorage()))();
|
|
37
|
+
return requestStateAsyncStorage;
|
|
38
|
+
};
|
|
39
|
+
async function hasRequestState() {
|
|
40
|
+
return (await ensureAsyncStorage$2()).getStore() !== void 0;
|
|
41
|
+
}
|
|
42
|
+
async function getCurrentRequestState() {
|
|
43
|
+
const store = (await ensureAsyncStorage$2()).getStore();
|
|
44
|
+
if (!store) throw new Error("No request state found. Please make sure you are calling this function within a `runWithRequestState` callback.");
|
|
45
|
+
return store;
|
|
46
|
+
}
|
|
47
|
+
async function runWithRequestState(store, fn) {
|
|
48
|
+
return (await ensureAsyncStorage$2()).run(store, fn);
|
|
49
|
+
}
|
|
50
|
+
function defineRequestState(initFn) {
|
|
51
|
+
const ref = Object.freeze({});
|
|
52
|
+
return {
|
|
53
|
+
get ref() {
|
|
54
|
+
return ref;
|
|
55
|
+
},
|
|
56
|
+
async get() {
|
|
57
|
+
const store = await getCurrentRequestState();
|
|
58
|
+
if (!store.has(ref)) {
|
|
59
|
+
const initialValue = await initFn();
|
|
60
|
+
store.set(ref, initialValue);
|
|
61
|
+
return initialValue;
|
|
62
|
+
}
|
|
63
|
+
return store.get(ref);
|
|
64
|
+
},
|
|
65
|
+
async set(value) {
|
|
66
|
+
(await getCurrentRequestState()).set(ref, value);
|
|
67
|
+
}
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
let currentAdapterAsyncStorage = null;
|
|
71
|
+
const ensureAsyncStorage$1 = async () => {
|
|
72
|
+
if (!currentAdapterAsyncStorage) currentAdapterAsyncStorage = new (await (getAsyncLocalStorage()))();
|
|
73
|
+
return currentAdapterAsyncStorage;
|
|
74
|
+
};
|
|
75
|
+
const getCurrentAdapter = async (fallback) => {
|
|
76
|
+
return ensureAsyncStorage$1().then((als) => {
|
|
77
|
+
return als.getStore() || fallback;
|
|
78
|
+
}).catch(() => {
|
|
79
|
+
return fallback;
|
|
80
|
+
});
|
|
81
|
+
};
|
|
82
|
+
async function getCurrentTransactionAdapter() {
|
|
83
|
+
return getCurrentAdapter((await getCurrentAuthContext()).context.adapter);
|
|
84
|
+
}
|
|
85
|
+
const runWithAdapter = async (adapter, fn) => {
|
|
86
|
+
let called = true;
|
|
87
|
+
return ensureAsyncStorage$1().then((als) => {
|
|
88
|
+
called = true;
|
|
89
|
+
return als.run(adapter, fn);
|
|
90
|
+
}).catch((err) => {
|
|
91
|
+
if (!called) return fn();
|
|
92
|
+
throw err;
|
|
93
|
+
});
|
|
94
|
+
};
|
|
95
|
+
const runWithTransaction = async (adapter, fn) => {
|
|
96
|
+
let called = true;
|
|
97
|
+
return ensureAsyncStorage$1().then((als) => {
|
|
98
|
+
called = true;
|
|
99
|
+
return adapter.transaction(async (trx) => {
|
|
100
|
+
return als.run(trx, fn);
|
|
101
|
+
});
|
|
102
|
+
}).catch((err) => {
|
|
103
|
+
if (!called) return fn();
|
|
104
|
+
throw err;
|
|
105
|
+
});
|
|
106
|
+
};
|
|
107
|
+
let currentContextAsyncStorage = null;
|
|
108
|
+
const ensureAsyncStorage = async () => {
|
|
109
|
+
if (!currentContextAsyncStorage) currentContextAsyncStorage = new (await (getAsyncLocalStorage()))();
|
|
110
|
+
return currentContextAsyncStorage;
|
|
111
|
+
};
|
|
112
|
+
async function getCurrentGraphContext(graphAdapter) {
|
|
113
|
+
const context = (await ensureAsyncStorage()).getStore();
|
|
114
|
+
if (context) return context;
|
|
115
|
+
if (graphAdapter) return graphAdapter;
|
|
116
|
+
throw new Error("No graph context found. Please make sure you are calling this function within a `runWithEndpointContext` callback.");
|
|
117
|
+
}
|
|
118
|
+
async function runWithGraphContext(adapter, fn) {
|
|
119
|
+
const als = await ensureAsyncStorage();
|
|
120
|
+
const transactionAdapter = adapter.transaction();
|
|
121
|
+
console.log("running with graph id", transactionAdapter.id);
|
|
122
|
+
const result = await als.run(transactionAdapter, fn);
|
|
123
|
+
console.log("committing graph transaction", transactionAdapter.id);
|
|
124
|
+
await transactionAdapter.commit();
|
|
125
|
+
return result;
|
|
126
|
+
}
|
|
127
|
+
function withTransaction(endpoint) {
|
|
128
|
+
return async (ctx) => {
|
|
129
|
+
return await runWithTransaction(ctx.context.adapter, async () => {
|
|
130
|
+
return await runWithGraphContext(ctx.context.graphAdapter, async () => {
|
|
131
|
+
return await endpoint(ctx);
|
|
132
|
+
});
|
|
133
|
+
});
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
function runWithGraphTransaction(dbAdapter, graphAdapter, fn) {
|
|
137
|
+
console.log("running with graph transaction", dbAdapter.id, graphAdapter.id);
|
|
138
|
+
return runWithTransaction(dbAdapter, async () => {
|
|
139
|
+
return await runWithGraphContext(graphAdapter, fn);
|
|
140
|
+
});
|
|
141
|
+
}
|
|
142
|
+
async function authorize(ctx, subjectType, subjectId, permissionName, objectType, objectId, message) {
|
|
143
|
+
const graphAdapter = await getCurrentGraphContext(ctx.context.graphAdapter);
|
|
144
|
+
if (ctx.context.options.graph?.enabled) {
|
|
145
|
+
if (!await graphAdapter.check(subjectType, subjectId, permissionName, objectType, objectId)) throw new APIError("FORBIDDEN", { message });
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
//#endregion
|
|
150
|
+
//#region ../../node_modules/.pnpm/jose@6.1.2/node_modules/jose/dist/webapi/lib/iv.js
|
|
151
|
+
function bitLength(alg$1) {
|
|
152
|
+
switch (alg$1) {
|
|
153
|
+
case "A128GCM":
|
|
154
|
+
case "A128GCMKW":
|
|
155
|
+
case "A192GCM":
|
|
156
|
+
case "A192GCMKW":
|
|
157
|
+
case "A256GCM":
|
|
158
|
+
case "A256GCMKW": return 96;
|
|
159
|
+
case "A128CBC-HS256":
|
|
160
|
+
case "A192CBC-HS384":
|
|
161
|
+
case "A256CBC-HS512": return 128;
|
|
162
|
+
default: throw new JOSENotSupported(`Unsupported JWE Algorithm: ${alg$1}`);
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
const generateIv = (alg$1) => crypto.getRandomValues(new Uint8Array(bitLength(alg$1) >> 3));
|
|
166
|
+
|
|
167
|
+
//#endregion
|
|
168
|
+
//#region ../../node_modules/.pnpm/jose@6.1.2/node_modules/jose/dist/webapi/lib/check_iv_length.js
|
|
169
|
+
function checkIvLength(enc$1, iv) {
|
|
170
|
+
if (iv.length << 3 !== bitLength(enc$1)) throw new JWEInvalid("Invalid Initialization Vector length");
|
|
171
|
+
}
|
|
172
|
+
|
|
173
|
+
//#endregion
|
|
174
|
+
//#region ../../node_modules/.pnpm/jose@6.1.2/node_modules/jose/dist/webapi/lib/check_cek_length.js
|
|
175
|
+
function checkCekLength(cek, expected) {
|
|
176
|
+
const actual = cek.byteLength << 3;
|
|
177
|
+
if (actual !== expected) throw new JWEInvalid(`Invalid Content Encryption Key length. Expected ${expected} bits, got ${actual} bits`);
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
//#endregion
|
|
181
|
+
//#region ../../node_modules/.pnpm/jose@6.1.2/node_modules/jose/dist/webapi/lib/decrypt.js
|
|
182
|
+
async function timingSafeEqual(a, b) {
|
|
183
|
+
if (!(a instanceof Uint8Array)) throw new TypeError("First argument must be a buffer");
|
|
184
|
+
if (!(b instanceof Uint8Array)) throw new TypeError("Second argument must be a buffer");
|
|
185
|
+
const algorithm = {
|
|
186
|
+
name: "HMAC",
|
|
187
|
+
hash: "SHA-256"
|
|
188
|
+
};
|
|
189
|
+
const key = await crypto.subtle.generateKey(algorithm, false, ["sign"]);
|
|
190
|
+
const aHmac = new Uint8Array(await crypto.subtle.sign(algorithm, key, a));
|
|
191
|
+
const bHmac = new Uint8Array(await crypto.subtle.sign(algorithm, key, b));
|
|
192
|
+
let out = 0;
|
|
193
|
+
let i = -1;
|
|
194
|
+
while (++i < 32) out |= aHmac[i] ^ bHmac[i];
|
|
195
|
+
return out === 0;
|
|
196
|
+
}
|
|
197
|
+
async function cbcDecrypt(enc$1, cek, ciphertext, iv, tag, aad) {
|
|
198
|
+
if (!(cek instanceof Uint8Array)) throw new TypeError(invalidKeyInput(cek, "Uint8Array"));
|
|
199
|
+
const keySize = parseInt(enc$1.slice(1, 4), 10);
|
|
200
|
+
const encKey = await crypto.subtle.importKey("raw", cek.subarray(keySize >> 3), "AES-CBC", false, ["decrypt"]);
|
|
201
|
+
const macKey = await crypto.subtle.importKey("raw", cek.subarray(0, keySize >> 3), {
|
|
202
|
+
hash: `SHA-${keySize << 1}`,
|
|
203
|
+
name: "HMAC"
|
|
204
|
+
}, false, ["sign"]);
|
|
205
|
+
const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3));
|
|
206
|
+
const expectedTag = new Uint8Array((await crypto.subtle.sign("HMAC", macKey, macData)).slice(0, keySize >> 3));
|
|
207
|
+
let macCheckPassed;
|
|
208
|
+
try {
|
|
209
|
+
macCheckPassed = await timingSafeEqual(tag, expectedTag);
|
|
210
|
+
} catch {}
|
|
211
|
+
if (!macCheckPassed) throw new JWEDecryptionFailed();
|
|
212
|
+
let plaintext;
|
|
213
|
+
try {
|
|
214
|
+
plaintext = new Uint8Array(await crypto.subtle.decrypt({
|
|
215
|
+
iv,
|
|
216
|
+
name: "AES-CBC"
|
|
217
|
+
}, encKey, ciphertext));
|
|
218
|
+
} catch {}
|
|
219
|
+
if (!plaintext) throw new JWEDecryptionFailed();
|
|
220
|
+
return plaintext;
|
|
221
|
+
}
|
|
222
|
+
async function gcmDecrypt(enc$1, cek, ciphertext, iv, tag, aad) {
|
|
223
|
+
let encKey;
|
|
224
|
+
if (cek instanceof Uint8Array) encKey = await crypto.subtle.importKey("raw", cek, "AES-GCM", false, ["decrypt"]);
|
|
225
|
+
else {
|
|
226
|
+
checkEncCryptoKey(cek, enc$1, "decrypt");
|
|
227
|
+
encKey = cek;
|
|
228
|
+
}
|
|
229
|
+
try {
|
|
230
|
+
return new Uint8Array(await crypto.subtle.decrypt({
|
|
231
|
+
additionalData: aad,
|
|
232
|
+
iv,
|
|
233
|
+
name: "AES-GCM",
|
|
234
|
+
tagLength: 128
|
|
235
|
+
}, encKey, concat(ciphertext, tag)));
|
|
236
|
+
} catch {
|
|
237
|
+
throw new JWEDecryptionFailed();
|
|
238
|
+
}
|
|
239
|
+
}
|
|
240
|
+
async function decrypt(enc$1, cek, ciphertext, iv, tag, aad) {
|
|
241
|
+
if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) throw new TypeError(invalidKeyInput(cek, "CryptoKey", "KeyObject", "Uint8Array", "JSON Web Key"));
|
|
242
|
+
if (!iv) throw new JWEInvalid("JWE Initialization Vector missing");
|
|
243
|
+
if (!tag) throw new JWEInvalid("JWE Authentication Tag missing");
|
|
244
|
+
checkIvLength(enc$1, iv);
|
|
245
|
+
switch (enc$1) {
|
|
246
|
+
case "A128CBC-HS256":
|
|
247
|
+
case "A192CBC-HS384":
|
|
248
|
+
case "A256CBC-HS512":
|
|
249
|
+
if (cek instanceof Uint8Array) checkCekLength(cek, parseInt(enc$1.slice(-3), 10));
|
|
250
|
+
return cbcDecrypt(enc$1, cek, ciphertext, iv, tag, aad);
|
|
251
|
+
case "A128GCM":
|
|
252
|
+
case "A192GCM":
|
|
253
|
+
case "A256GCM":
|
|
254
|
+
if (cek instanceof Uint8Array) checkCekLength(cek, parseInt(enc$1.slice(1, 4), 10));
|
|
255
|
+
return gcmDecrypt(enc$1, cek, ciphertext, iv, tag, aad);
|
|
256
|
+
default: throw new JOSENotSupported("Unsupported JWE Content Encryption Algorithm");
|
|
257
|
+
}
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
//#endregion
|
|
261
|
+
//#region ../../node_modules/.pnpm/jose@6.1.2/node_modules/jose/dist/webapi/lib/aeskw.js
|
|
262
|
+
function checkKeySize(key, alg$1) {
|
|
263
|
+
if (key.algorithm.length !== parseInt(alg$1.slice(1, 4), 10)) throw new TypeError(`Invalid key size for alg: ${alg$1}`);
|
|
264
|
+
}
|
|
265
|
+
function getCryptoKey$1(key, alg$1, usage) {
|
|
266
|
+
if (key instanceof Uint8Array) return crypto.subtle.importKey("raw", key, "AES-KW", true, [usage]);
|
|
267
|
+
checkEncCryptoKey(key, alg$1, usage);
|
|
268
|
+
return key;
|
|
269
|
+
}
|
|
270
|
+
async function wrap$2(alg$1, key, cek) {
|
|
271
|
+
const cryptoKey = await getCryptoKey$1(key, alg$1, "wrapKey");
|
|
272
|
+
checkKeySize(cryptoKey, alg$1);
|
|
273
|
+
const cryptoKeyCek = await crypto.subtle.importKey("raw", cek, {
|
|
274
|
+
hash: "SHA-256",
|
|
275
|
+
name: "HMAC"
|
|
276
|
+
}, true, ["sign"]);
|
|
277
|
+
return new Uint8Array(await crypto.subtle.wrapKey("raw", cryptoKeyCek, cryptoKey, "AES-KW"));
|
|
278
|
+
}
|
|
279
|
+
async function unwrap$2(alg$1, key, encryptedKey) {
|
|
280
|
+
const cryptoKey = await getCryptoKey$1(key, alg$1, "unwrapKey");
|
|
281
|
+
checkKeySize(cryptoKey, alg$1);
|
|
282
|
+
const cryptoKeyCek = await crypto.subtle.unwrapKey("raw", encryptedKey, cryptoKey, "AES-KW", {
|
|
283
|
+
hash: "SHA-256",
|
|
284
|
+
name: "HMAC"
|
|
285
|
+
}, true, ["sign"]);
|
|
286
|
+
return new Uint8Array(await crypto.subtle.exportKey("raw", cryptoKeyCek));
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
//#endregion
|
|
290
|
+
//#region ../../node_modules/.pnpm/jose@6.1.2/node_modules/jose/dist/webapi/lib/digest.js
|
|
291
|
+
async function digest(algorithm, data) {
|
|
292
|
+
const subtleDigest = `SHA-${algorithm.slice(-3)}`;
|
|
293
|
+
return new Uint8Array(await crypto.subtle.digest(subtleDigest, data));
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
//#endregion
|
|
297
|
+
//#region ../../node_modules/.pnpm/jose@6.1.2/node_modules/jose/dist/webapi/lib/ecdhes.js
|
|
298
|
+
function lengthAndInput(input) {
|
|
299
|
+
return concat(uint32be(input.length), input);
|
|
300
|
+
}
|
|
301
|
+
async function concatKdf(Z, L, OtherInfo) {
|
|
302
|
+
const dkLen = L >> 3;
|
|
303
|
+
const hashLen = 32;
|
|
304
|
+
const reps = Math.ceil(dkLen / hashLen);
|
|
305
|
+
const dk = new Uint8Array(reps * hashLen);
|
|
306
|
+
for (let i = 1; i <= reps; i++) {
|
|
307
|
+
const hashInput = new Uint8Array(4 + Z.length + OtherInfo.length);
|
|
308
|
+
hashInput.set(uint32be(i), 0);
|
|
309
|
+
hashInput.set(Z, 4);
|
|
310
|
+
hashInput.set(OtherInfo, 4 + Z.length);
|
|
311
|
+
const hashResult = await digest("sha256", hashInput);
|
|
312
|
+
dk.set(hashResult, (i - 1) * hashLen);
|
|
313
|
+
}
|
|
314
|
+
return dk.slice(0, dkLen);
|
|
315
|
+
}
|
|
316
|
+
async function deriveKey$1(publicKey, privateKey, algorithm, keyLength, apu = new Uint8Array(), apv = new Uint8Array()) {
|
|
317
|
+
checkEncCryptoKey(publicKey, "ECDH");
|
|
318
|
+
checkEncCryptoKey(privateKey, "ECDH", "deriveBits");
|
|
319
|
+
const otherInfo = concat(lengthAndInput(encode$1(algorithm)), lengthAndInput(apu), lengthAndInput(apv), uint32be(keyLength), new Uint8Array());
|
|
320
|
+
return concatKdf(new Uint8Array(await crypto.subtle.deriveBits({
|
|
321
|
+
name: publicKey.algorithm.name,
|
|
322
|
+
public: publicKey
|
|
323
|
+
}, privateKey, getEcdhBitLength(publicKey))), keyLength, otherInfo);
|
|
324
|
+
}
|
|
325
|
+
function getEcdhBitLength(publicKey) {
|
|
326
|
+
if (publicKey.algorithm.name === "X25519") return 256;
|
|
327
|
+
return Math.ceil(parseInt(publicKey.algorithm.namedCurve.slice(-3), 10) / 8) << 3;
|
|
328
|
+
}
|
|
329
|
+
function allowed(key) {
|
|
330
|
+
switch (key.algorithm.namedCurve) {
|
|
331
|
+
case "P-256":
|
|
332
|
+
case "P-384":
|
|
333
|
+
case "P-521": return true;
|
|
334
|
+
default: return key.algorithm.name === "X25519";
|
|
335
|
+
}
|
|
336
|
+
}
|
|
337
|
+
|
|
338
|
+
//#endregion
|
|
339
|
+
//#region ../../node_modules/.pnpm/jose@6.1.2/node_modules/jose/dist/webapi/lib/pbes2kw.js
|
|
340
|
+
function getCryptoKey(key, alg$1) {
|
|
341
|
+
if (key instanceof Uint8Array) return crypto.subtle.importKey("raw", key, "PBKDF2", false, ["deriveBits"]);
|
|
342
|
+
checkEncCryptoKey(key, alg$1, "deriveBits");
|
|
343
|
+
return key;
|
|
344
|
+
}
|
|
345
|
+
const concatSalt = (alg$1, p2sInput) => concat(encode$1(alg$1), Uint8Array.of(0), p2sInput);
|
|
346
|
+
async function deriveKey(p2s, alg$1, p2c, key) {
|
|
347
|
+
if (!(p2s instanceof Uint8Array) || p2s.length < 8) throw new JWEInvalid("PBES2 Salt Input must be 8 or more octets");
|
|
348
|
+
const salt = concatSalt(alg$1, p2s);
|
|
349
|
+
const keylen = parseInt(alg$1.slice(13, 16), 10);
|
|
350
|
+
const subtleAlg = {
|
|
351
|
+
hash: `SHA-${alg$1.slice(8, 11)}`,
|
|
352
|
+
iterations: p2c,
|
|
353
|
+
name: "PBKDF2",
|
|
354
|
+
salt
|
|
355
|
+
};
|
|
356
|
+
const cryptoKey = await getCryptoKey(key, alg$1);
|
|
357
|
+
return new Uint8Array(await crypto.subtle.deriveBits(subtleAlg, cryptoKey, keylen));
|
|
358
|
+
}
|
|
359
|
+
async function wrap$1(alg$1, key, cek, p2c = 2048, p2s = crypto.getRandomValues(new Uint8Array(16))) {
|
|
360
|
+
const derived = await deriveKey(p2s, alg$1, p2c, key);
|
|
361
|
+
return {
|
|
362
|
+
encryptedKey: await wrap$2(alg$1.slice(-6), derived, cek),
|
|
363
|
+
p2c,
|
|
364
|
+
p2s: encode(p2s)
|
|
365
|
+
};
|
|
366
|
+
}
|
|
367
|
+
async function unwrap$1(alg$1, key, encryptedKey, p2c, p2s) {
|
|
368
|
+
const derived = await deriveKey(p2s, alg$1, p2c, key);
|
|
369
|
+
return unwrap$2(alg$1.slice(-6), derived, encryptedKey);
|
|
370
|
+
}
|
|
371
|
+
|
|
372
|
+
//#endregion
|
|
373
|
+
//#region ../../node_modules/.pnpm/jose@6.1.2/node_modules/jose/dist/webapi/lib/rsaes.js
|
|
374
|
+
const subtleAlgorithm$1 = (alg$1) => {
|
|
375
|
+
switch (alg$1) {
|
|
376
|
+
case "RSA-OAEP":
|
|
377
|
+
case "RSA-OAEP-256":
|
|
378
|
+
case "RSA-OAEP-384":
|
|
379
|
+
case "RSA-OAEP-512": return "RSA-OAEP";
|
|
380
|
+
default: throw new JOSENotSupported(`alg ${alg$1} is not supported either by JOSE or your javascript runtime`);
|
|
381
|
+
}
|
|
382
|
+
};
|
|
383
|
+
async function encrypt$1(alg$1, key, cek) {
|
|
384
|
+
checkEncCryptoKey(key, alg$1, "encrypt");
|
|
385
|
+
checkKeyLength(alg$1, key);
|
|
386
|
+
return new Uint8Array(await crypto.subtle.encrypt(subtleAlgorithm$1(alg$1), key, cek));
|
|
387
|
+
}
|
|
388
|
+
async function decrypt$1(alg$1, key, encryptedKey) {
|
|
389
|
+
checkEncCryptoKey(key, alg$1, "decrypt");
|
|
390
|
+
checkKeyLength(alg$1, key);
|
|
391
|
+
return new Uint8Array(await crypto.subtle.decrypt(subtleAlgorithm$1(alg$1), key, encryptedKey));
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
//#endregion
|
|
395
|
+
//#region ../../node_modules/.pnpm/jose@6.1.2/node_modules/jose/dist/webapi/lib/cek.js
|
|
396
|
+
function cekLength(alg$1) {
|
|
397
|
+
switch (alg$1) {
|
|
398
|
+
case "A128GCM": return 128;
|
|
399
|
+
case "A192GCM": return 192;
|
|
400
|
+
case "A256GCM":
|
|
401
|
+
case "A128CBC-HS256": return 256;
|
|
402
|
+
case "A192CBC-HS384": return 384;
|
|
403
|
+
case "A256CBC-HS512": return 512;
|
|
404
|
+
default: throw new JOSENotSupported(`Unsupported JWE Algorithm: ${alg$1}`);
|
|
405
|
+
}
|
|
406
|
+
}
|
|
407
|
+
const generateCek = (alg$1) => crypto.getRandomValues(new Uint8Array(cekLength(alg$1) >> 3));
|
|
408
|
+
|
|
409
|
+
//#endregion
|
|
410
|
+
//#region ../../node_modules/.pnpm/jose@6.1.2/node_modules/jose/dist/webapi/lib/encrypt.js
|
|
411
|
+
async function cbcEncrypt(enc$1, plaintext, cek, iv, aad) {
|
|
412
|
+
if (!(cek instanceof Uint8Array)) throw new TypeError(invalidKeyInput(cek, "Uint8Array"));
|
|
413
|
+
const keySize = parseInt(enc$1.slice(1, 4), 10);
|
|
414
|
+
const encKey = await crypto.subtle.importKey("raw", cek.subarray(keySize >> 3), "AES-CBC", false, ["encrypt"]);
|
|
415
|
+
const macKey = await crypto.subtle.importKey("raw", cek.subarray(0, keySize >> 3), {
|
|
416
|
+
hash: `SHA-${keySize << 1}`,
|
|
417
|
+
name: "HMAC"
|
|
418
|
+
}, false, ["sign"]);
|
|
419
|
+
const ciphertext = new Uint8Array(await crypto.subtle.encrypt({
|
|
420
|
+
iv,
|
|
421
|
+
name: "AES-CBC"
|
|
422
|
+
}, encKey, plaintext));
|
|
423
|
+
const macData = concat(aad, iv, ciphertext, uint64be(aad.length << 3));
|
|
424
|
+
return {
|
|
425
|
+
ciphertext,
|
|
426
|
+
tag: new Uint8Array((await crypto.subtle.sign("HMAC", macKey, macData)).slice(0, keySize >> 3)),
|
|
427
|
+
iv
|
|
428
|
+
};
|
|
429
|
+
}
|
|
430
|
+
async function gcmEncrypt(enc$1, plaintext, cek, iv, aad) {
|
|
431
|
+
let encKey;
|
|
432
|
+
if (cek instanceof Uint8Array) encKey = await crypto.subtle.importKey("raw", cek, "AES-GCM", false, ["encrypt"]);
|
|
433
|
+
else {
|
|
434
|
+
checkEncCryptoKey(cek, enc$1, "encrypt");
|
|
435
|
+
encKey = cek;
|
|
436
|
+
}
|
|
437
|
+
const encrypted = new Uint8Array(await crypto.subtle.encrypt({
|
|
438
|
+
additionalData: aad,
|
|
439
|
+
iv,
|
|
440
|
+
name: "AES-GCM",
|
|
441
|
+
tagLength: 128
|
|
442
|
+
}, encKey, plaintext));
|
|
443
|
+
const tag = encrypted.slice(-16);
|
|
444
|
+
return {
|
|
445
|
+
ciphertext: encrypted.slice(0, -16),
|
|
446
|
+
tag,
|
|
447
|
+
iv
|
|
448
|
+
};
|
|
449
|
+
}
|
|
450
|
+
async function encrypt(enc$1, plaintext, cek, iv, aad) {
|
|
451
|
+
if (!isCryptoKey(cek) && !(cek instanceof Uint8Array)) throw new TypeError(invalidKeyInput(cek, "CryptoKey", "KeyObject", "Uint8Array", "JSON Web Key"));
|
|
452
|
+
if (iv) checkIvLength(enc$1, iv);
|
|
453
|
+
else iv = generateIv(enc$1);
|
|
454
|
+
switch (enc$1) {
|
|
455
|
+
case "A128CBC-HS256":
|
|
456
|
+
case "A192CBC-HS384":
|
|
457
|
+
case "A256CBC-HS512":
|
|
458
|
+
if (cek instanceof Uint8Array) checkCekLength(cek, parseInt(enc$1.slice(-3), 10));
|
|
459
|
+
return cbcEncrypt(enc$1, plaintext, cek, iv, aad);
|
|
460
|
+
case "A128GCM":
|
|
461
|
+
case "A192GCM":
|
|
462
|
+
case "A256GCM":
|
|
463
|
+
if (cek instanceof Uint8Array) checkCekLength(cek, parseInt(enc$1.slice(1, 4), 10));
|
|
464
|
+
return gcmEncrypt(enc$1, plaintext, cek, iv, aad);
|
|
465
|
+
default: throw new JOSENotSupported("Unsupported JWE Content Encryption Algorithm");
|
|
466
|
+
}
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
//#endregion
|
|
470
|
+
//#region ../../node_modules/.pnpm/jose@6.1.2/node_modules/jose/dist/webapi/lib/aesgcmkw.js
|
|
471
|
+
async function wrap(alg$1, key, cek, iv) {
|
|
472
|
+
const wrapped = await encrypt(alg$1.slice(0, 7), cek, key, iv, new Uint8Array());
|
|
473
|
+
return {
|
|
474
|
+
encryptedKey: wrapped.ciphertext,
|
|
475
|
+
iv: encode(wrapped.iv),
|
|
476
|
+
tag: encode(wrapped.tag)
|
|
477
|
+
};
|
|
478
|
+
}
|
|
479
|
+
async function unwrap(alg$1, key, encryptedKey, iv, tag) {
|
|
480
|
+
return decrypt(alg$1.slice(0, 7), key, encryptedKey, iv, tag, new Uint8Array());
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
//#endregion
|
|
484
|
+
//#region ../../node_modules/.pnpm/jose@6.1.2/node_modules/jose/dist/webapi/lib/decrypt_key_management.js
|
|
485
|
+
async function decryptKeyManagement(alg$1, key, encryptedKey, joseHeader, options) {
|
|
486
|
+
switch (alg$1) {
|
|
487
|
+
case "dir":
|
|
488
|
+
if (encryptedKey !== void 0) throw new JWEInvalid("Encountered unexpected JWE Encrypted Key");
|
|
489
|
+
return key;
|
|
490
|
+
case "ECDH-ES": if (encryptedKey !== void 0) throw new JWEInvalid("Encountered unexpected JWE Encrypted Key");
|
|
491
|
+
case "ECDH-ES+A128KW":
|
|
492
|
+
case "ECDH-ES+A192KW":
|
|
493
|
+
case "ECDH-ES+A256KW": {
|
|
494
|
+
if (!isObject(joseHeader.epk)) throw new JWEInvalid(`JOSE Header "epk" (Ephemeral Public Key) missing or invalid`);
|
|
495
|
+
assertCryptoKey(key);
|
|
496
|
+
if (!allowed(key)) throw new JOSENotSupported("ECDH with the provided key is not allowed or not supported by your javascript runtime");
|
|
497
|
+
const epk = await importJWK(joseHeader.epk, alg$1);
|
|
498
|
+
assertCryptoKey(epk);
|
|
499
|
+
let partyUInfo;
|
|
500
|
+
let partyVInfo;
|
|
501
|
+
if (joseHeader.apu !== void 0) {
|
|
502
|
+
if (typeof joseHeader.apu !== "string") throw new JWEInvalid(`JOSE Header "apu" (Agreement PartyUInfo) invalid`);
|
|
503
|
+
try {
|
|
504
|
+
partyUInfo = decode(joseHeader.apu);
|
|
505
|
+
} catch {
|
|
506
|
+
throw new JWEInvalid("Failed to base64url decode the apu");
|
|
507
|
+
}
|
|
508
|
+
}
|
|
509
|
+
if (joseHeader.apv !== void 0) {
|
|
510
|
+
if (typeof joseHeader.apv !== "string") throw new JWEInvalid(`JOSE Header "apv" (Agreement PartyVInfo) invalid`);
|
|
511
|
+
try {
|
|
512
|
+
partyVInfo = decode(joseHeader.apv);
|
|
513
|
+
} catch {
|
|
514
|
+
throw new JWEInvalid("Failed to base64url decode the apv");
|
|
515
|
+
}
|
|
516
|
+
}
|
|
517
|
+
const sharedSecret = await deriveKey$1(epk, key, alg$1 === "ECDH-ES" ? joseHeader.enc : alg$1, alg$1 === "ECDH-ES" ? cekLength(joseHeader.enc) : parseInt(alg$1.slice(-5, -2), 10), partyUInfo, partyVInfo);
|
|
518
|
+
if (alg$1 === "ECDH-ES") return sharedSecret;
|
|
519
|
+
if (encryptedKey === void 0) throw new JWEInvalid("JWE Encrypted Key missing");
|
|
520
|
+
return unwrap$2(alg$1.slice(-6), sharedSecret, encryptedKey);
|
|
521
|
+
}
|
|
522
|
+
case "RSA-OAEP":
|
|
523
|
+
case "RSA-OAEP-256":
|
|
524
|
+
case "RSA-OAEP-384":
|
|
525
|
+
case "RSA-OAEP-512":
|
|
526
|
+
if (encryptedKey === void 0) throw new JWEInvalid("JWE Encrypted Key missing");
|
|
527
|
+
assertCryptoKey(key);
|
|
528
|
+
return decrypt$1(alg$1, key, encryptedKey);
|
|
529
|
+
case "PBES2-HS256+A128KW":
|
|
530
|
+
case "PBES2-HS384+A192KW":
|
|
531
|
+
case "PBES2-HS512+A256KW": {
|
|
532
|
+
if (encryptedKey === void 0) throw new JWEInvalid("JWE Encrypted Key missing");
|
|
533
|
+
if (typeof joseHeader.p2c !== "number") throw new JWEInvalid(`JOSE Header "p2c" (PBES2 Count) missing or invalid`);
|
|
534
|
+
const p2cLimit = options?.maxPBES2Count || 1e4;
|
|
535
|
+
if (joseHeader.p2c > p2cLimit) throw new JWEInvalid(`JOSE Header "p2c" (PBES2 Count) out is of acceptable bounds`);
|
|
536
|
+
if (typeof joseHeader.p2s !== "string") throw new JWEInvalid(`JOSE Header "p2s" (PBES2 Salt) missing or invalid`);
|
|
537
|
+
let p2s;
|
|
538
|
+
try {
|
|
539
|
+
p2s = decode(joseHeader.p2s);
|
|
540
|
+
} catch {
|
|
541
|
+
throw new JWEInvalid("Failed to base64url decode the p2s");
|
|
542
|
+
}
|
|
543
|
+
return unwrap$1(alg$1, key, encryptedKey, joseHeader.p2c, p2s);
|
|
544
|
+
}
|
|
545
|
+
case "A128KW":
|
|
546
|
+
case "A192KW":
|
|
547
|
+
case "A256KW":
|
|
548
|
+
if (encryptedKey === void 0) throw new JWEInvalid("JWE Encrypted Key missing");
|
|
549
|
+
return unwrap$2(alg$1, key, encryptedKey);
|
|
550
|
+
case "A128GCMKW":
|
|
551
|
+
case "A192GCMKW":
|
|
552
|
+
case "A256GCMKW": {
|
|
553
|
+
if (encryptedKey === void 0) throw new JWEInvalid("JWE Encrypted Key missing");
|
|
554
|
+
if (typeof joseHeader.iv !== "string") throw new JWEInvalid(`JOSE Header "iv" (Initialization Vector) missing or invalid`);
|
|
555
|
+
if (typeof joseHeader.tag !== "string") throw new JWEInvalid(`JOSE Header "tag" (Authentication Tag) missing or invalid`);
|
|
556
|
+
let iv;
|
|
557
|
+
try {
|
|
558
|
+
iv = decode(joseHeader.iv);
|
|
559
|
+
} catch {
|
|
560
|
+
throw new JWEInvalid("Failed to base64url decode the iv");
|
|
561
|
+
}
|
|
562
|
+
let tag;
|
|
563
|
+
try {
|
|
564
|
+
tag = decode(joseHeader.tag);
|
|
565
|
+
} catch {
|
|
566
|
+
throw new JWEInvalid("Failed to base64url decode the tag");
|
|
567
|
+
}
|
|
568
|
+
return unwrap(alg$1, key, encryptedKey, iv, tag);
|
|
569
|
+
}
|
|
570
|
+
default: throw new JOSENotSupported("Invalid or unsupported \"alg\" (JWE Algorithm) header value");
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
//#endregion
|
|
575
|
+
//#region ../../node_modules/.pnpm/jose@6.1.2/node_modules/jose/dist/webapi/jwe/flattened/decrypt.js
|
|
576
|
+
async function flattenedDecrypt(jwe, key, options) {
|
|
577
|
+
if (!isObject(jwe)) throw new JWEInvalid("Flattened JWE must be an object");
|
|
578
|
+
if (jwe.protected === void 0 && jwe.header === void 0 && jwe.unprotected === void 0) throw new JWEInvalid("JOSE Header missing");
|
|
579
|
+
if (jwe.iv !== void 0 && typeof jwe.iv !== "string") throw new JWEInvalid("JWE Initialization Vector incorrect type");
|
|
580
|
+
if (typeof jwe.ciphertext !== "string") throw new JWEInvalid("JWE Ciphertext missing or incorrect type");
|
|
581
|
+
if (jwe.tag !== void 0 && typeof jwe.tag !== "string") throw new JWEInvalid("JWE Authentication Tag incorrect type");
|
|
582
|
+
if (jwe.protected !== void 0 && typeof jwe.protected !== "string") throw new JWEInvalid("JWE Protected Header incorrect type");
|
|
583
|
+
if (jwe.encrypted_key !== void 0 && typeof jwe.encrypted_key !== "string") throw new JWEInvalid("JWE Encrypted Key incorrect type");
|
|
584
|
+
if (jwe.aad !== void 0 && typeof jwe.aad !== "string") throw new JWEInvalid("JWE AAD incorrect type");
|
|
585
|
+
if (jwe.header !== void 0 && !isObject(jwe.header)) throw new JWEInvalid("JWE Shared Unprotected Header incorrect type");
|
|
586
|
+
if (jwe.unprotected !== void 0 && !isObject(jwe.unprotected)) throw new JWEInvalid("JWE Per-Recipient Unprotected Header incorrect type");
|
|
587
|
+
let parsedProt;
|
|
588
|
+
if (jwe.protected) try {
|
|
589
|
+
const protectedHeader$1 = decode(jwe.protected);
|
|
590
|
+
parsedProt = JSON.parse(decoder.decode(protectedHeader$1));
|
|
591
|
+
} catch {
|
|
592
|
+
throw new JWEInvalid("JWE Protected Header is invalid");
|
|
593
|
+
}
|
|
594
|
+
if (!isDisjoint(parsedProt, jwe.header, jwe.unprotected)) throw new JWEInvalid("JWE Protected, JWE Unprotected Header, and JWE Per-Recipient Unprotected Header Parameter names must be disjoint");
|
|
595
|
+
const joseHeader = {
|
|
596
|
+
...parsedProt,
|
|
597
|
+
...jwe.header,
|
|
598
|
+
...jwe.unprotected
|
|
599
|
+
};
|
|
600
|
+
validateCrit(JWEInvalid, /* @__PURE__ */ new Map(), options?.crit, parsedProt, joseHeader);
|
|
601
|
+
if (joseHeader.zip !== void 0) throw new JOSENotSupported("JWE \"zip\" (Compression Algorithm) Header Parameter is not supported.");
|
|
602
|
+
const { alg: alg$1, enc: enc$1 } = joseHeader;
|
|
603
|
+
if (typeof alg$1 !== "string" || !alg$1) throw new JWEInvalid("missing JWE Algorithm (alg) in JWE Header");
|
|
604
|
+
if (typeof enc$1 !== "string" || !enc$1) throw new JWEInvalid("missing JWE Encryption Algorithm (enc) in JWE Header");
|
|
605
|
+
const keyManagementAlgorithms = options && validateAlgorithms("keyManagementAlgorithms", options.keyManagementAlgorithms);
|
|
606
|
+
const contentEncryptionAlgorithms = options && validateAlgorithms("contentEncryptionAlgorithms", options.contentEncryptionAlgorithms);
|
|
607
|
+
if (keyManagementAlgorithms && !keyManagementAlgorithms.has(alg$1) || !keyManagementAlgorithms && alg$1.startsWith("PBES2")) throw new JOSEAlgNotAllowed("\"alg\" (Algorithm) Header Parameter value not allowed");
|
|
608
|
+
if (contentEncryptionAlgorithms && !contentEncryptionAlgorithms.has(enc$1)) throw new JOSEAlgNotAllowed("\"enc\" (Encryption Algorithm) Header Parameter value not allowed");
|
|
609
|
+
let encryptedKey;
|
|
610
|
+
if (jwe.encrypted_key !== void 0) try {
|
|
611
|
+
encryptedKey = decode(jwe.encrypted_key);
|
|
612
|
+
} catch {
|
|
613
|
+
throw new JWEInvalid("Failed to base64url decode the encrypted_key");
|
|
614
|
+
}
|
|
615
|
+
let resolvedKey = false;
|
|
616
|
+
if (typeof key === "function") {
|
|
617
|
+
key = await key(parsedProt, jwe);
|
|
618
|
+
resolvedKey = true;
|
|
619
|
+
}
|
|
620
|
+
checkKeyType(alg$1 === "dir" ? enc$1 : alg$1, key, "decrypt");
|
|
621
|
+
const k = await normalizeKey(key, alg$1);
|
|
622
|
+
let cek;
|
|
623
|
+
try {
|
|
624
|
+
cek = await decryptKeyManagement(alg$1, k, encryptedKey, joseHeader, options);
|
|
625
|
+
} catch (err) {
|
|
626
|
+
if (err instanceof TypeError || err instanceof JWEInvalid || err instanceof JOSENotSupported) throw err;
|
|
627
|
+
cek = generateCek(enc$1);
|
|
628
|
+
}
|
|
629
|
+
let iv;
|
|
630
|
+
let tag;
|
|
631
|
+
if (jwe.iv !== void 0) try {
|
|
632
|
+
iv = decode(jwe.iv);
|
|
633
|
+
} catch {
|
|
634
|
+
throw new JWEInvalid("Failed to base64url decode the iv");
|
|
635
|
+
}
|
|
636
|
+
if (jwe.tag !== void 0) try {
|
|
637
|
+
tag = decode(jwe.tag);
|
|
638
|
+
} catch {
|
|
639
|
+
throw new JWEInvalid("Failed to base64url decode the tag");
|
|
640
|
+
}
|
|
641
|
+
const protectedHeader = jwe.protected !== void 0 ? encode$1(jwe.protected) : new Uint8Array();
|
|
642
|
+
let additionalData;
|
|
643
|
+
if (jwe.aad !== void 0) additionalData = concat(protectedHeader, encode$1("."), encode$1(jwe.aad));
|
|
644
|
+
else additionalData = protectedHeader;
|
|
645
|
+
let ciphertext;
|
|
646
|
+
try {
|
|
647
|
+
ciphertext = decode(jwe.ciphertext);
|
|
648
|
+
} catch {
|
|
649
|
+
throw new JWEInvalid("Failed to base64url decode the ciphertext");
|
|
650
|
+
}
|
|
651
|
+
const result = { plaintext: await decrypt(enc$1, cek, ciphertext, iv, tag, additionalData) };
|
|
652
|
+
if (jwe.protected !== void 0) result.protectedHeader = parsedProt;
|
|
653
|
+
if (jwe.aad !== void 0) try {
|
|
654
|
+
result.additionalAuthenticatedData = decode(jwe.aad);
|
|
655
|
+
} catch {
|
|
656
|
+
throw new JWEInvalid("Failed to base64url decode the aad");
|
|
657
|
+
}
|
|
658
|
+
if (jwe.unprotected !== void 0) result.sharedUnprotectedHeader = jwe.unprotected;
|
|
659
|
+
if (jwe.header !== void 0) result.unprotectedHeader = jwe.header;
|
|
660
|
+
if (resolvedKey) return {
|
|
661
|
+
...result,
|
|
662
|
+
key: k
|
|
663
|
+
};
|
|
664
|
+
return result;
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
//#endregion
|
|
668
|
+
//#region ../../node_modules/.pnpm/jose@6.1.2/node_modules/jose/dist/webapi/jwe/compact/decrypt.js
|
|
669
|
+
async function compactDecrypt(jwe, key, options) {
|
|
670
|
+
if (jwe instanceof Uint8Array) jwe = decoder.decode(jwe);
|
|
671
|
+
if (typeof jwe !== "string") throw new JWEInvalid("Compact JWE must be a string or Uint8Array");
|
|
672
|
+
const { 0: protectedHeader, 1: encryptedKey, 2: iv, 3: ciphertext, 4: tag, length } = jwe.split(".");
|
|
673
|
+
if (length !== 5) throw new JWEInvalid("Invalid Compact JWE");
|
|
674
|
+
const decrypted = await flattenedDecrypt({
|
|
675
|
+
ciphertext,
|
|
676
|
+
iv: iv || void 0,
|
|
677
|
+
protected: protectedHeader,
|
|
678
|
+
tag: tag || void 0,
|
|
679
|
+
encrypted_key: encryptedKey || void 0
|
|
680
|
+
}, key, options);
|
|
681
|
+
const result = {
|
|
682
|
+
plaintext: decrypted.plaintext,
|
|
683
|
+
protectedHeader: decrypted.protectedHeader
|
|
684
|
+
};
|
|
685
|
+
if (typeof key === "function") return {
|
|
686
|
+
...result,
|
|
687
|
+
key: decrypted.key
|
|
688
|
+
};
|
|
689
|
+
return result;
|
|
690
|
+
}
|
|
691
|
+
|
|
692
|
+
//#endregion
|
|
693
|
+
//#region ../../node_modules/.pnpm/jose@6.1.2/node_modules/jose/dist/webapi/lib/private_symbols.js
|
|
694
|
+
const unprotected = Symbol();
|
|
695
|
+
|
|
696
|
+
//#endregion
|
|
697
|
+
//#region ../../node_modules/.pnpm/jose@6.1.2/node_modules/jose/dist/webapi/lib/key_to_jwk.js
|
|
698
|
+
async function keyToJWK(key) {
|
|
699
|
+
if (isKeyObject(key)) if (key.type === "secret") key = key.export();
|
|
700
|
+
else return key.export({ format: "jwk" });
|
|
701
|
+
if (key instanceof Uint8Array) return {
|
|
702
|
+
kty: "oct",
|
|
703
|
+
k: encode(key)
|
|
704
|
+
};
|
|
705
|
+
if (!isCryptoKey(key)) throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "Uint8Array"));
|
|
706
|
+
if (!key.extractable) throw new TypeError("non-extractable CryptoKey cannot be exported as a JWK");
|
|
707
|
+
const { ext, key_ops, alg: alg$1, use, ...jwk } = await crypto.subtle.exportKey("jwk", key);
|
|
708
|
+
if (jwk.kty === "AKP") jwk.alg = alg$1;
|
|
709
|
+
return jwk;
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
//#endregion
|
|
713
|
+
//#region ../../node_modules/.pnpm/jose@6.1.2/node_modules/jose/dist/webapi/key/export.js
|
|
714
|
+
async function exportJWK(key) {
|
|
715
|
+
return keyToJWK(key);
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
//#endregion
|
|
719
|
+
//#region ../../node_modules/.pnpm/jose@6.1.2/node_modules/jose/dist/webapi/lib/encrypt_key_management.js
|
|
720
|
+
async function encryptKeyManagement(alg$1, enc$1, key, providedCek, providedParameters = {}) {
|
|
721
|
+
let encryptedKey;
|
|
722
|
+
let parameters;
|
|
723
|
+
let cek;
|
|
724
|
+
switch (alg$1) {
|
|
725
|
+
case "dir":
|
|
726
|
+
cek = key;
|
|
727
|
+
break;
|
|
728
|
+
case "ECDH-ES":
|
|
729
|
+
case "ECDH-ES+A128KW":
|
|
730
|
+
case "ECDH-ES+A192KW":
|
|
731
|
+
case "ECDH-ES+A256KW": {
|
|
732
|
+
assertCryptoKey(key);
|
|
733
|
+
if (!allowed(key)) throw new JOSENotSupported("ECDH with the provided key is not allowed or not supported by your javascript runtime");
|
|
734
|
+
const { apu, apv } = providedParameters;
|
|
735
|
+
let ephemeralKey;
|
|
736
|
+
if (providedParameters.epk) ephemeralKey = await normalizeKey(providedParameters.epk, alg$1);
|
|
737
|
+
else ephemeralKey = (await crypto.subtle.generateKey(key.algorithm, true, ["deriveBits"])).privateKey;
|
|
738
|
+
const { x, y, crv, kty } = await exportJWK(ephemeralKey);
|
|
739
|
+
const sharedSecret = await deriveKey$1(key, ephemeralKey, alg$1 === "ECDH-ES" ? enc$1 : alg$1, alg$1 === "ECDH-ES" ? cekLength(enc$1) : parseInt(alg$1.slice(-5, -2), 10), apu, apv);
|
|
740
|
+
parameters = { epk: {
|
|
741
|
+
x,
|
|
742
|
+
crv,
|
|
743
|
+
kty
|
|
744
|
+
} };
|
|
745
|
+
if (kty === "EC") parameters.epk.y = y;
|
|
746
|
+
if (apu) parameters.apu = encode(apu);
|
|
747
|
+
if (apv) parameters.apv = encode(apv);
|
|
748
|
+
if (alg$1 === "ECDH-ES") {
|
|
749
|
+
cek = sharedSecret;
|
|
750
|
+
break;
|
|
751
|
+
}
|
|
752
|
+
cek = providedCek || generateCek(enc$1);
|
|
753
|
+
const kwAlg = alg$1.slice(-6);
|
|
754
|
+
encryptedKey = await wrap$2(kwAlg, sharedSecret, cek);
|
|
755
|
+
break;
|
|
756
|
+
}
|
|
757
|
+
case "RSA-OAEP":
|
|
758
|
+
case "RSA-OAEP-256":
|
|
759
|
+
case "RSA-OAEP-384":
|
|
760
|
+
case "RSA-OAEP-512":
|
|
761
|
+
cek = providedCek || generateCek(enc$1);
|
|
762
|
+
assertCryptoKey(key);
|
|
763
|
+
encryptedKey = await encrypt$1(alg$1, key, cek);
|
|
764
|
+
break;
|
|
765
|
+
case "PBES2-HS256+A128KW":
|
|
766
|
+
case "PBES2-HS384+A192KW":
|
|
767
|
+
case "PBES2-HS512+A256KW": {
|
|
768
|
+
cek = providedCek || generateCek(enc$1);
|
|
769
|
+
const { p2c, p2s } = providedParameters;
|
|
770
|
+
({encryptedKey, ...parameters} = await wrap$1(alg$1, key, cek, p2c, p2s));
|
|
771
|
+
break;
|
|
772
|
+
}
|
|
773
|
+
case "A128KW":
|
|
774
|
+
case "A192KW":
|
|
775
|
+
case "A256KW":
|
|
776
|
+
cek = providedCek || generateCek(enc$1);
|
|
777
|
+
encryptedKey = await wrap$2(alg$1, key, cek);
|
|
778
|
+
break;
|
|
779
|
+
case "A128GCMKW":
|
|
780
|
+
case "A192GCMKW":
|
|
781
|
+
case "A256GCMKW": {
|
|
782
|
+
cek = providedCek || generateCek(enc$1);
|
|
783
|
+
const { iv } = providedParameters;
|
|
784
|
+
({encryptedKey, ...parameters} = await wrap(alg$1, key, cek, iv));
|
|
785
|
+
break;
|
|
786
|
+
}
|
|
787
|
+
default: throw new JOSENotSupported("Invalid or unsupported \"alg\" (JWE Algorithm) header value");
|
|
788
|
+
}
|
|
789
|
+
return {
|
|
790
|
+
cek,
|
|
791
|
+
encryptedKey,
|
|
792
|
+
parameters
|
|
793
|
+
};
|
|
794
|
+
}
|
|
795
|
+
|
|
796
|
+
//#endregion
|
|
797
|
+
//#region ../../node_modules/.pnpm/jose@6.1.2/node_modules/jose/dist/webapi/jwe/flattened/encrypt.js
|
|
798
|
+
var FlattenedEncrypt = class {
|
|
799
|
+
#plaintext;
|
|
800
|
+
#protectedHeader;
|
|
801
|
+
#sharedUnprotectedHeader;
|
|
802
|
+
#unprotectedHeader;
|
|
803
|
+
#aad;
|
|
804
|
+
#cek;
|
|
805
|
+
#iv;
|
|
806
|
+
#keyManagementParameters;
|
|
807
|
+
constructor(plaintext) {
|
|
808
|
+
if (!(plaintext instanceof Uint8Array)) throw new TypeError("plaintext must be an instance of Uint8Array");
|
|
809
|
+
this.#plaintext = plaintext;
|
|
810
|
+
}
|
|
811
|
+
setKeyManagementParameters(parameters) {
|
|
812
|
+
if (this.#keyManagementParameters) throw new TypeError("setKeyManagementParameters can only be called once");
|
|
813
|
+
this.#keyManagementParameters = parameters;
|
|
814
|
+
return this;
|
|
815
|
+
}
|
|
816
|
+
setProtectedHeader(protectedHeader) {
|
|
817
|
+
if (this.#protectedHeader) throw new TypeError("setProtectedHeader can only be called once");
|
|
818
|
+
this.#protectedHeader = protectedHeader;
|
|
819
|
+
return this;
|
|
820
|
+
}
|
|
821
|
+
setSharedUnprotectedHeader(sharedUnprotectedHeader) {
|
|
822
|
+
if (this.#sharedUnprotectedHeader) throw new TypeError("setSharedUnprotectedHeader can only be called once");
|
|
823
|
+
this.#sharedUnprotectedHeader = sharedUnprotectedHeader;
|
|
824
|
+
return this;
|
|
825
|
+
}
|
|
826
|
+
setUnprotectedHeader(unprotectedHeader) {
|
|
827
|
+
if (this.#unprotectedHeader) throw new TypeError("setUnprotectedHeader can only be called once");
|
|
828
|
+
this.#unprotectedHeader = unprotectedHeader;
|
|
829
|
+
return this;
|
|
830
|
+
}
|
|
831
|
+
setAdditionalAuthenticatedData(aad) {
|
|
832
|
+
this.#aad = aad;
|
|
833
|
+
return this;
|
|
834
|
+
}
|
|
835
|
+
setContentEncryptionKey(cek) {
|
|
836
|
+
if (this.#cek) throw new TypeError("setContentEncryptionKey can only be called once");
|
|
837
|
+
this.#cek = cek;
|
|
838
|
+
return this;
|
|
839
|
+
}
|
|
840
|
+
setInitializationVector(iv) {
|
|
841
|
+
if (this.#iv) throw new TypeError("setInitializationVector can only be called once");
|
|
842
|
+
this.#iv = iv;
|
|
843
|
+
return this;
|
|
844
|
+
}
|
|
845
|
+
async encrypt(key, options) {
|
|
846
|
+
if (!this.#protectedHeader && !this.#unprotectedHeader && !this.#sharedUnprotectedHeader) throw new JWEInvalid("either setProtectedHeader, setUnprotectedHeader, or sharedUnprotectedHeader must be called before #encrypt()");
|
|
847
|
+
if (!isDisjoint(this.#protectedHeader, this.#unprotectedHeader, this.#sharedUnprotectedHeader)) throw new JWEInvalid("JWE Protected, JWE Shared Unprotected and JWE Per-Recipient Header Parameter names must be disjoint");
|
|
848
|
+
const joseHeader = {
|
|
849
|
+
...this.#protectedHeader,
|
|
850
|
+
...this.#unprotectedHeader,
|
|
851
|
+
...this.#sharedUnprotectedHeader
|
|
852
|
+
};
|
|
853
|
+
validateCrit(JWEInvalid, /* @__PURE__ */ new Map(), options?.crit, this.#protectedHeader, joseHeader);
|
|
854
|
+
if (joseHeader.zip !== void 0) throw new JOSENotSupported("JWE \"zip\" (Compression Algorithm) Header Parameter is not supported.");
|
|
855
|
+
const { alg: alg$1, enc: enc$1 } = joseHeader;
|
|
856
|
+
if (typeof alg$1 !== "string" || !alg$1) throw new JWEInvalid("JWE \"alg\" (Algorithm) Header Parameter missing or invalid");
|
|
857
|
+
if (typeof enc$1 !== "string" || !enc$1) throw new JWEInvalid("JWE \"enc\" (Encryption Algorithm) Header Parameter missing or invalid");
|
|
858
|
+
let encryptedKey;
|
|
859
|
+
if (this.#cek && (alg$1 === "dir" || alg$1 === "ECDH-ES")) throw new TypeError(`setContentEncryptionKey cannot be called with JWE "alg" (Algorithm) Header ${alg$1}`);
|
|
860
|
+
checkKeyType(alg$1 === "dir" ? enc$1 : alg$1, key, "encrypt");
|
|
861
|
+
let cek;
|
|
862
|
+
{
|
|
863
|
+
let parameters;
|
|
864
|
+
const k = await normalizeKey(key, alg$1);
|
|
865
|
+
({cek, encryptedKey, parameters} = await encryptKeyManagement(alg$1, enc$1, k, this.#cek, this.#keyManagementParameters));
|
|
866
|
+
if (parameters) if (options && unprotected in options) if (!this.#unprotectedHeader) this.setUnprotectedHeader(parameters);
|
|
867
|
+
else this.#unprotectedHeader = {
|
|
868
|
+
...this.#unprotectedHeader,
|
|
869
|
+
...parameters
|
|
870
|
+
};
|
|
871
|
+
else if (!this.#protectedHeader) this.setProtectedHeader(parameters);
|
|
872
|
+
else this.#protectedHeader = {
|
|
873
|
+
...this.#protectedHeader,
|
|
874
|
+
...parameters
|
|
875
|
+
};
|
|
876
|
+
}
|
|
877
|
+
let additionalData;
|
|
878
|
+
let protectedHeaderS;
|
|
879
|
+
let protectedHeaderB;
|
|
880
|
+
let aadMember;
|
|
881
|
+
if (this.#protectedHeader) {
|
|
882
|
+
protectedHeaderS = encode(JSON.stringify(this.#protectedHeader));
|
|
883
|
+
protectedHeaderB = encode$1(protectedHeaderS);
|
|
884
|
+
} else {
|
|
885
|
+
protectedHeaderS = "";
|
|
886
|
+
protectedHeaderB = new Uint8Array();
|
|
887
|
+
}
|
|
888
|
+
if (this.#aad) {
|
|
889
|
+
aadMember = encode(this.#aad);
|
|
890
|
+
const aadMemberBytes = encode$1(aadMember);
|
|
891
|
+
additionalData = concat(protectedHeaderB, encode$1("."), aadMemberBytes);
|
|
892
|
+
} else additionalData = protectedHeaderB;
|
|
893
|
+
const { ciphertext, tag, iv } = await encrypt(enc$1, this.#plaintext, cek, this.#iv, additionalData);
|
|
894
|
+
const jwe = { ciphertext: encode(ciphertext) };
|
|
895
|
+
if (iv) jwe.iv = encode(iv);
|
|
896
|
+
if (tag) jwe.tag = encode(tag);
|
|
897
|
+
if (encryptedKey) jwe.encrypted_key = encode(encryptedKey);
|
|
898
|
+
if (aadMember) jwe.aad = aadMember;
|
|
899
|
+
if (this.#protectedHeader) jwe.protected = protectedHeaderS;
|
|
900
|
+
if (this.#sharedUnprotectedHeader) jwe.unprotected = this.#sharedUnprotectedHeader;
|
|
901
|
+
if (this.#unprotectedHeader) jwe.header = this.#unprotectedHeader;
|
|
902
|
+
return jwe;
|
|
903
|
+
}
|
|
904
|
+
};
|
|
905
|
+
|
|
906
|
+
//#endregion
|
|
907
|
+
//#region ../../node_modules/.pnpm/jose@6.1.2/node_modules/jose/dist/webapi/jwt/decrypt.js
|
|
908
|
+
async function jwtDecrypt(jwt, key, options) {
|
|
909
|
+
const decrypted = await compactDecrypt(jwt, key, options);
|
|
910
|
+
const payload = validateClaimsSet(decrypted.protectedHeader, decrypted.plaintext, options);
|
|
911
|
+
const { protectedHeader } = decrypted;
|
|
912
|
+
if (protectedHeader.iss !== void 0 && protectedHeader.iss !== payload.iss) throw new JWTClaimValidationFailed("replicated \"iss\" claim header parameter mismatch", payload, "iss", "mismatch");
|
|
913
|
+
if (protectedHeader.sub !== void 0 && protectedHeader.sub !== payload.sub) throw new JWTClaimValidationFailed("replicated \"sub\" claim header parameter mismatch", payload, "sub", "mismatch");
|
|
914
|
+
if (protectedHeader.aud !== void 0 && JSON.stringify(protectedHeader.aud) !== JSON.stringify(payload.aud)) throw new JWTClaimValidationFailed("replicated \"aud\" claim header parameter mismatch", payload, "aud", "mismatch");
|
|
915
|
+
const result = {
|
|
916
|
+
payload,
|
|
917
|
+
protectedHeader
|
|
918
|
+
};
|
|
919
|
+
if (typeof key === "function") return {
|
|
920
|
+
...result,
|
|
921
|
+
key: decrypted.key
|
|
922
|
+
};
|
|
923
|
+
return result;
|
|
924
|
+
}
|
|
925
|
+
|
|
926
|
+
//#endregion
|
|
927
|
+
//#region ../../node_modules/.pnpm/jose@6.1.2/node_modules/jose/dist/webapi/jwe/compact/encrypt.js
|
|
928
|
+
var CompactEncrypt = class {
|
|
929
|
+
#flattened;
|
|
930
|
+
constructor(plaintext) {
|
|
931
|
+
this.#flattened = new FlattenedEncrypt(plaintext);
|
|
932
|
+
}
|
|
933
|
+
setContentEncryptionKey(cek) {
|
|
934
|
+
this.#flattened.setContentEncryptionKey(cek);
|
|
935
|
+
return this;
|
|
936
|
+
}
|
|
937
|
+
setInitializationVector(iv) {
|
|
938
|
+
this.#flattened.setInitializationVector(iv);
|
|
939
|
+
return this;
|
|
940
|
+
}
|
|
941
|
+
setProtectedHeader(protectedHeader) {
|
|
942
|
+
this.#flattened.setProtectedHeader(protectedHeader);
|
|
943
|
+
return this;
|
|
944
|
+
}
|
|
945
|
+
setKeyManagementParameters(parameters) {
|
|
946
|
+
this.#flattened.setKeyManagementParameters(parameters);
|
|
947
|
+
return this;
|
|
948
|
+
}
|
|
949
|
+
async encrypt(key, options) {
|
|
950
|
+
const jwe = await this.#flattened.encrypt(key, options);
|
|
951
|
+
return [
|
|
952
|
+
jwe.protected,
|
|
953
|
+
jwe.encrypted_key,
|
|
954
|
+
jwe.iv,
|
|
955
|
+
jwe.ciphertext,
|
|
956
|
+
jwe.tag
|
|
957
|
+
].join(".");
|
|
958
|
+
}
|
|
959
|
+
};
|
|
960
|
+
|
|
961
|
+
//#endregion
|
|
962
|
+
//#region ../../node_modules/.pnpm/jose@6.1.2/node_modules/jose/dist/webapi/lib/sign.js
|
|
963
|
+
async function sign(alg$1, key, data) {
|
|
964
|
+
const cryptoKey = await getSigKey(alg$1, key, "sign");
|
|
965
|
+
checkKeyLength(alg$1, cryptoKey);
|
|
966
|
+
const signature = await crypto.subtle.sign(subtleAlgorithm(alg$1, cryptoKey.algorithm), cryptoKey, data);
|
|
967
|
+
return new Uint8Array(signature);
|
|
968
|
+
}
|
|
969
|
+
|
|
970
|
+
//#endregion
|
|
971
|
+
//#region ../../node_modules/.pnpm/jose@6.1.2/node_modules/jose/dist/webapi/jws/flattened/sign.js
|
|
972
|
+
var FlattenedSign = class {
|
|
973
|
+
#payload;
|
|
974
|
+
#protectedHeader;
|
|
975
|
+
#unprotectedHeader;
|
|
976
|
+
constructor(payload) {
|
|
977
|
+
if (!(payload instanceof Uint8Array)) throw new TypeError("payload must be an instance of Uint8Array");
|
|
978
|
+
this.#payload = payload;
|
|
979
|
+
}
|
|
980
|
+
setProtectedHeader(protectedHeader) {
|
|
981
|
+
if (this.#protectedHeader) throw new TypeError("setProtectedHeader can only be called once");
|
|
982
|
+
this.#protectedHeader = protectedHeader;
|
|
983
|
+
return this;
|
|
984
|
+
}
|
|
985
|
+
setUnprotectedHeader(unprotectedHeader) {
|
|
986
|
+
if (this.#unprotectedHeader) throw new TypeError("setUnprotectedHeader can only be called once");
|
|
987
|
+
this.#unprotectedHeader = unprotectedHeader;
|
|
988
|
+
return this;
|
|
989
|
+
}
|
|
990
|
+
async sign(key, options) {
|
|
991
|
+
if (!this.#protectedHeader && !this.#unprotectedHeader) throw new JWSInvalid("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");
|
|
992
|
+
if (!isDisjoint(this.#protectedHeader, this.#unprotectedHeader)) throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
|
|
993
|
+
const joseHeader = {
|
|
994
|
+
...this.#protectedHeader,
|
|
995
|
+
...this.#unprotectedHeader
|
|
996
|
+
};
|
|
997
|
+
const extensions = validateCrit(JWSInvalid, new Map([["b64", true]]), options?.crit, this.#protectedHeader, joseHeader);
|
|
998
|
+
let b64 = true;
|
|
999
|
+
if (extensions.has("b64")) {
|
|
1000
|
+
b64 = this.#protectedHeader.b64;
|
|
1001
|
+
if (typeof b64 !== "boolean") throw new JWSInvalid("The \"b64\" (base64url-encode payload) Header Parameter must be a boolean");
|
|
1002
|
+
}
|
|
1003
|
+
const { alg: alg$1 } = joseHeader;
|
|
1004
|
+
if (typeof alg$1 !== "string" || !alg$1) throw new JWSInvalid("JWS \"alg\" (Algorithm) Header Parameter missing or invalid");
|
|
1005
|
+
checkKeyType(alg$1, key, "sign");
|
|
1006
|
+
let payloadS;
|
|
1007
|
+
let payloadB;
|
|
1008
|
+
if (b64) {
|
|
1009
|
+
payloadS = encode(this.#payload);
|
|
1010
|
+
payloadB = encode$1(payloadS);
|
|
1011
|
+
} else {
|
|
1012
|
+
payloadB = this.#payload;
|
|
1013
|
+
payloadS = "";
|
|
1014
|
+
}
|
|
1015
|
+
let protectedHeaderString;
|
|
1016
|
+
let protectedHeaderBytes;
|
|
1017
|
+
if (this.#protectedHeader) {
|
|
1018
|
+
protectedHeaderString = encode(JSON.stringify(this.#protectedHeader));
|
|
1019
|
+
protectedHeaderBytes = encode$1(protectedHeaderString);
|
|
1020
|
+
} else {
|
|
1021
|
+
protectedHeaderString = "";
|
|
1022
|
+
protectedHeaderBytes = new Uint8Array();
|
|
1023
|
+
}
|
|
1024
|
+
const data = concat(protectedHeaderBytes, encode$1("."), payloadB);
|
|
1025
|
+
const jws = {
|
|
1026
|
+
signature: encode(await sign(alg$1, await normalizeKey(key, alg$1), data)),
|
|
1027
|
+
payload: payloadS
|
|
1028
|
+
};
|
|
1029
|
+
if (this.#unprotectedHeader) jws.header = this.#unprotectedHeader;
|
|
1030
|
+
if (this.#protectedHeader) jws.protected = protectedHeaderString;
|
|
1031
|
+
return jws;
|
|
1032
|
+
}
|
|
1033
|
+
};
|
|
1034
|
+
|
|
1035
|
+
//#endregion
|
|
1036
|
+
//#region ../../node_modules/.pnpm/jose@6.1.2/node_modules/jose/dist/webapi/jws/compact/sign.js
|
|
1037
|
+
var CompactSign = class {
|
|
1038
|
+
#flattened;
|
|
1039
|
+
constructor(payload) {
|
|
1040
|
+
this.#flattened = new FlattenedSign(payload);
|
|
1041
|
+
}
|
|
1042
|
+
setProtectedHeader(protectedHeader) {
|
|
1043
|
+
this.#flattened.setProtectedHeader(protectedHeader);
|
|
1044
|
+
return this;
|
|
1045
|
+
}
|
|
1046
|
+
async sign(key, options) {
|
|
1047
|
+
const jws = await this.#flattened.sign(key, options);
|
|
1048
|
+
if (jws.payload === void 0) throw new TypeError("use the flattened module for creating JWS with b64: false");
|
|
1049
|
+
return `${jws.protected}.${jws.payload}.${jws.signature}`;
|
|
1050
|
+
}
|
|
1051
|
+
};
|
|
1052
|
+
|
|
1053
|
+
//#endregion
|
|
1054
|
+
//#region ../../node_modules/.pnpm/jose@6.1.2/node_modules/jose/dist/webapi/jwt/sign.js
|
|
1055
|
+
var SignJWT = class {
|
|
1056
|
+
#protectedHeader;
|
|
1057
|
+
#jwt;
|
|
1058
|
+
constructor(payload = {}) {
|
|
1059
|
+
this.#jwt = new JWTClaimsBuilder(payload);
|
|
1060
|
+
}
|
|
1061
|
+
setIssuer(issuer) {
|
|
1062
|
+
this.#jwt.iss = issuer;
|
|
1063
|
+
return this;
|
|
1064
|
+
}
|
|
1065
|
+
setSubject(subject) {
|
|
1066
|
+
this.#jwt.sub = subject;
|
|
1067
|
+
return this;
|
|
1068
|
+
}
|
|
1069
|
+
setAudience(audience) {
|
|
1070
|
+
this.#jwt.aud = audience;
|
|
1071
|
+
return this;
|
|
1072
|
+
}
|
|
1073
|
+
setJti(jwtId) {
|
|
1074
|
+
this.#jwt.jti = jwtId;
|
|
1075
|
+
return this;
|
|
1076
|
+
}
|
|
1077
|
+
setNotBefore(input) {
|
|
1078
|
+
this.#jwt.nbf = input;
|
|
1079
|
+
return this;
|
|
1080
|
+
}
|
|
1081
|
+
setExpirationTime(input) {
|
|
1082
|
+
this.#jwt.exp = input;
|
|
1083
|
+
return this;
|
|
1084
|
+
}
|
|
1085
|
+
setIssuedAt(input) {
|
|
1086
|
+
this.#jwt.iat = input;
|
|
1087
|
+
return this;
|
|
1088
|
+
}
|
|
1089
|
+
setProtectedHeader(protectedHeader) {
|
|
1090
|
+
this.#protectedHeader = protectedHeader;
|
|
1091
|
+
return this;
|
|
1092
|
+
}
|
|
1093
|
+
async sign(key, options) {
|
|
1094
|
+
const sig = new CompactSign(this.#jwt.data());
|
|
1095
|
+
sig.setProtectedHeader(this.#protectedHeader);
|
|
1096
|
+
if (Array.isArray(this.#protectedHeader?.crit) && this.#protectedHeader.crit.includes("b64") && this.#protectedHeader.b64 === false) throw new JWTInvalid("JWTs MUST NOT use unencoded payload");
|
|
1097
|
+
return sig.sign(key, options);
|
|
1098
|
+
}
|
|
1099
|
+
};
|
|
1100
|
+
|
|
1101
|
+
//#endregion
|
|
1102
|
+
//#region ../../node_modules/.pnpm/jose@6.1.2/node_modules/jose/dist/webapi/jwt/encrypt.js
|
|
1103
|
+
var EncryptJWT = class {
|
|
1104
|
+
#cek;
|
|
1105
|
+
#iv;
|
|
1106
|
+
#keyManagementParameters;
|
|
1107
|
+
#protectedHeader;
|
|
1108
|
+
#replicateIssuerAsHeader;
|
|
1109
|
+
#replicateSubjectAsHeader;
|
|
1110
|
+
#replicateAudienceAsHeader;
|
|
1111
|
+
#jwt;
|
|
1112
|
+
constructor(payload = {}) {
|
|
1113
|
+
this.#jwt = new JWTClaimsBuilder(payload);
|
|
1114
|
+
}
|
|
1115
|
+
setIssuer(issuer) {
|
|
1116
|
+
this.#jwt.iss = issuer;
|
|
1117
|
+
return this;
|
|
1118
|
+
}
|
|
1119
|
+
setSubject(subject) {
|
|
1120
|
+
this.#jwt.sub = subject;
|
|
1121
|
+
return this;
|
|
1122
|
+
}
|
|
1123
|
+
setAudience(audience) {
|
|
1124
|
+
this.#jwt.aud = audience;
|
|
1125
|
+
return this;
|
|
1126
|
+
}
|
|
1127
|
+
setJti(jwtId) {
|
|
1128
|
+
this.#jwt.jti = jwtId;
|
|
1129
|
+
return this;
|
|
1130
|
+
}
|
|
1131
|
+
setNotBefore(input) {
|
|
1132
|
+
this.#jwt.nbf = input;
|
|
1133
|
+
return this;
|
|
1134
|
+
}
|
|
1135
|
+
setExpirationTime(input) {
|
|
1136
|
+
this.#jwt.exp = input;
|
|
1137
|
+
return this;
|
|
1138
|
+
}
|
|
1139
|
+
setIssuedAt(input) {
|
|
1140
|
+
this.#jwt.iat = input;
|
|
1141
|
+
return this;
|
|
1142
|
+
}
|
|
1143
|
+
setProtectedHeader(protectedHeader) {
|
|
1144
|
+
if (this.#protectedHeader) throw new TypeError("setProtectedHeader can only be called once");
|
|
1145
|
+
this.#protectedHeader = protectedHeader;
|
|
1146
|
+
return this;
|
|
1147
|
+
}
|
|
1148
|
+
setKeyManagementParameters(parameters) {
|
|
1149
|
+
if (this.#keyManagementParameters) throw new TypeError("setKeyManagementParameters can only be called once");
|
|
1150
|
+
this.#keyManagementParameters = parameters;
|
|
1151
|
+
return this;
|
|
1152
|
+
}
|
|
1153
|
+
setContentEncryptionKey(cek) {
|
|
1154
|
+
if (this.#cek) throw new TypeError("setContentEncryptionKey can only be called once");
|
|
1155
|
+
this.#cek = cek;
|
|
1156
|
+
return this;
|
|
1157
|
+
}
|
|
1158
|
+
setInitializationVector(iv) {
|
|
1159
|
+
if (this.#iv) throw new TypeError("setInitializationVector can only be called once");
|
|
1160
|
+
this.#iv = iv;
|
|
1161
|
+
return this;
|
|
1162
|
+
}
|
|
1163
|
+
replicateIssuerAsHeader() {
|
|
1164
|
+
this.#replicateIssuerAsHeader = true;
|
|
1165
|
+
return this;
|
|
1166
|
+
}
|
|
1167
|
+
replicateSubjectAsHeader() {
|
|
1168
|
+
this.#replicateSubjectAsHeader = true;
|
|
1169
|
+
return this;
|
|
1170
|
+
}
|
|
1171
|
+
replicateAudienceAsHeader() {
|
|
1172
|
+
this.#replicateAudienceAsHeader = true;
|
|
1173
|
+
return this;
|
|
1174
|
+
}
|
|
1175
|
+
async encrypt(key, options) {
|
|
1176
|
+
const enc$1 = new CompactEncrypt(this.#jwt.data());
|
|
1177
|
+
if (this.#protectedHeader && (this.#replicateIssuerAsHeader || this.#replicateSubjectAsHeader || this.#replicateAudienceAsHeader)) this.#protectedHeader = {
|
|
1178
|
+
...this.#protectedHeader,
|
|
1179
|
+
iss: this.#replicateIssuerAsHeader ? this.#jwt.iss : void 0,
|
|
1180
|
+
sub: this.#replicateSubjectAsHeader ? this.#jwt.sub : void 0,
|
|
1181
|
+
aud: this.#replicateAudienceAsHeader ? this.#jwt.aud : void 0
|
|
1182
|
+
};
|
|
1183
|
+
enc$1.setProtectedHeader(this.#protectedHeader);
|
|
1184
|
+
if (this.#iv) enc$1.setInitializationVector(this.#iv);
|
|
1185
|
+
if (this.#cek) enc$1.setContentEncryptionKey(this.#cek);
|
|
1186
|
+
if (this.#keyManagementParameters) enc$1.setKeyManagementParameters(this.#keyManagementParameters);
|
|
1187
|
+
return enc$1.encrypt(key, options);
|
|
1188
|
+
}
|
|
1189
|
+
};
|
|
1190
|
+
|
|
1191
|
+
//#endregion
|
|
1192
|
+
//#region ../../node_modules/.pnpm/jose@6.1.2/node_modules/jose/dist/webapi/jwk/thumbprint.js
|
|
1193
|
+
const check = (value, description) => {
|
|
1194
|
+
if (typeof value !== "string" || !value) throw new JWKInvalid(`${description} missing or invalid`);
|
|
1195
|
+
};
|
|
1196
|
+
async function calculateJwkThumbprint(key, digestAlgorithm) {
|
|
1197
|
+
let jwk;
|
|
1198
|
+
if (isJWK(key)) jwk = key;
|
|
1199
|
+
else if (isKeyLike(key)) jwk = await exportJWK(key);
|
|
1200
|
+
else throw new TypeError(invalidKeyInput(key, "CryptoKey", "KeyObject", "JSON Web Key"));
|
|
1201
|
+
digestAlgorithm ??= "sha256";
|
|
1202
|
+
if (digestAlgorithm !== "sha256" && digestAlgorithm !== "sha384" && digestAlgorithm !== "sha512") throw new TypeError("digestAlgorithm must one of \"sha256\", \"sha384\", or \"sha512\"");
|
|
1203
|
+
let components;
|
|
1204
|
+
switch (jwk.kty) {
|
|
1205
|
+
case "AKP":
|
|
1206
|
+
check(jwk.alg, "\"alg\" (Algorithm) Parameter");
|
|
1207
|
+
check(jwk.pub, "\"pub\" (Public key) Parameter");
|
|
1208
|
+
components = {
|
|
1209
|
+
alg: jwk.alg,
|
|
1210
|
+
kty: jwk.kty,
|
|
1211
|
+
pub: jwk.pub
|
|
1212
|
+
};
|
|
1213
|
+
break;
|
|
1214
|
+
case "EC":
|
|
1215
|
+
check(jwk.crv, "\"crv\" (Curve) Parameter");
|
|
1216
|
+
check(jwk.x, "\"x\" (X Coordinate) Parameter");
|
|
1217
|
+
check(jwk.y, "\"y\" (Y Coordinate) Parameter");
|
|
1218
|
+
components = {
|
|
1219
|
+
crv: jwk.crv,
|
|
1220
|
+
kty: jwk.kty,
|
|
1221
|
+
x: jwk.x,
|
|
1222
|
+
y: jwk.y
|
|
1223
|
+
};
|
|
1224
|
+
break;
|
|
1225
|
+
case "OKP":
|
|
1226
|
+
check(jwk.crv, "\"crv\" (Subtype of Key Pair) Parameter");
|
|
1227
|
+
check(jwk.x, "\"x\" (Public Key) Parameter");
|
|
1228
|
+
components = {
|
|
1229
|
+
crv: jwk.crv,
|
|
1230
|
+
kty: jwk.kty,
|
|
1231
|
+
x: jwk.x
|
|
1232
|
+
};
|
|
1233
|
+
break;
|
|
1234
|
+
case "RSA":
|
|
1235
|
+
check(jwk.e, "\"e\" (Exponent) Parameter");
|
|
1236
|
+
check(jwk.n, "\"n\" (Modulus) Parameter");
|
|
1237
|
+
components = {
|
|
1238
|
+
e: jwk.e,
|
|
1239
|
+
kty: jwk.kty,
|
|
1240
|
+
n: jwk.n
|
|
1241
|
+
};
|
|
1242
|
+
break;
|
|
1243
|
+
case "oct":
|
|
1244
|
+
check(jwk.k, "\"k\" (Key Value) Parameter");
|
|
1245
|
+
components = {
|
|
1246
|
+
k: jwk.k,
|
|
1247
|
+
kty: jwk.kty
|
|
1248
|
+
};
|
|
1249
|
+
break;
|
|
1250
|
+
default: throw new JOSENotSupported("\"kty\" (Key Type) Parameter missing or unsupported");
|
|
1251
|
+
}
|
|
1252
|
+
const data = encode$1(JSON.stringify(components));
|
|
1253
|
+
return encode(await digest(digestAlgorithm, data));
|
|
1254
|
+
}
|
|
1255
|
+
|
|
1256
|
+
//#endregion
|
|
1257
|
+
//#region ../../node_modules/.pnpm/@noble+hashes@2.0.1/node_modules/@noble/hashes/utils.js
|
|
1258
|
+
/**
|
|
1259
|
+
* Utilities for hex, bytes, CSPRNG.
|
|
1260
|
+
* @module
|
|
1261
|
+
*/
|
|
1262
|
+
/*! noble-hashes - MIT License (c) 2022 Paul Miller (paulmillr.com) */
|
|
1263
|
+
/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */
|
|
1264
|
+
function isBytes$1(a) {
|
|
1265
|
+
return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
|
|
1266
|
+
}
|
|
1267
|
+
/** Asserts something is positive integer. */
|
|
1268
|
+
function anumber(n, title = "") {
|
|
1269
|
+
if (!Number.isSafeInteger(n) || n < 0) {
|
|
1270
|
+
const prefix = title && `"${title}" `;
|
|
1271
|
+
throw new Error(`${prefix}expected integer >= 0, got ${n}`);
|
|
1272
|
+
}
|
|
1273
|
+
}
|
|
1274
|
+
/** Asserts something is Uint8Array. */
|
|
1275
|
+
function abytes$1(value, length, title = "") {
|
|
1276
|
+
const bytes = isBytes$1(value);
|
|
1277
|
+
const len = value?.length;
|
|
1278
|
+
const needsLen = length !== void 0;
|
|
1279
|
+
if (!bytes || needsLen && len !== length) {
|
|
1280
|
+
const prefix = title && `"${title}" `;
|
|
1281
|
+
const ofLen = needsLen ? ` of length ${length}` : "";
|
|
1282
|
+
const got = bytes ? `length=${len}` : `type=${typeof value}`;
|
|
1283
|
+
throw new Error(prefix + "expected Uint8Array" + ofLen + ", got " + got);
|
|
1284
|
+
}
|
|
1285
|
+
return value;
|
|
1286
|
+
}
|
|
1287
|
+
/** Asserts something is hash */
|
|
1288
|
+
function ahash(h) {
|
|
1289
|
+
if (typeof h !== "function" || typeof h.create !== "function") throw new Error("Hash must wrapped by utils.createHasher");
|
|
1290
|
+
anumber(h.outputLen);
|
|
1291
|
+
anumber(h.blockLen);
|
|
1292
|
+
}
|
|
1293
|
+
/** Asserts a hash instance has not been destroyed / finished */
|
|
1294
|
+
function aexists$1(instance, checkFinished = true) {
|
|
1295
|
+
if (instance.destroyed) throw new Error("Hash instance has been destroyed");
|
|
1296
|
+
if (checkFinished && instance.finished) throw new Error("Hash#digest() has already been called");
|
|
1297
|
+
}
|
|
1298
|
+
/** Asserts output is properly-sized byte array */
|
|
1299
|
+
function aoutput$1(out, instance) {
|
|
1300
|
+
abytes$1(out, void 0, "digestInto() output");
|
|
1301
|
+
const min = instance.outputLen;
|
|
1302
|
+
if (out.length < min) throw new Error("\"digestInto() output\" expected to be of length >=" + min);
|
|
1303
|
+
}
|
|
1304
|
+
/** Cast u8 / u16 / u32 to u32. */
|
|
1305
|
+
function u32(arr) {
|
|
1306
|
+
return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
|
|
1307
|
+
}
|
|
1308
|
+
/** Zeroize a byte array. Warning: JS provides no guarantees. */
|
|
1309
|
+
function clean(...arrays) {
|
|
1310
|
+
for (let i = 0; i < arrays.length; i++) arrays[i].fill(0);
|
|
1311
|
+
}
|
|
1312
|
+
/** Create DataView of an array for easy byte-level manipulation. */
|
|
1313
|
+
function createView(arr) {
|
|
1314
|
+
return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
|
|
1315
|
+
}
|
|
1316
|
+
/** The rotate right (circular right shift) operation for uint32 */
|
|
1317
|
+
function rotr(word, shift) {
|
|
1318
|
+
return word << 32 - shift | word >>> shift;
|
|
1319
|
+
}
|
|
1320
|
+
/** The rotate left (circular left shift) operation for uint32 */
|
|
1321
|
+
function rotl(word, shift) {
|
|
1322
|
+
return word << shift | word >>> 32 - shift >>> 0;
|
|
1323
|
+
}
|
|
1324
|
+
/** Is current platform little-endian? Most are. Big-Endian platform: IBM */
|
|
1325
|
+
const isLE$1 = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)();
|
|
1326
|
+
/** The byte swap operation for uint32 */
|
|
1327
|
+
function byteSwap(word) {
|
|
1328
|
+
return word << 24 & 4278190080 | word << 8 & 16711680 | word >>> 8 & 65280 | word >>> 24 & 255;
|
|
1329
|
+
}
|
|
1330
|
+
/** In place byte swap for Uint32Array */
|
|
1331
|
+
function byteSwap32(arr) {
|
|
1332
|
+
for (let i = 0; i < arr.length; i++) arr[i] = byteSwap(arr[i]);
|
|
1333
|
+
return arr;
|
|
1334
|
+
}
|
|
1335
|
+
const swap32IfBE = isLE$1 ? (u) => u : byteSwap32;
|
|
1336
|
+
const hasHexBuiltin$1 = /* @__PURE__ */ (() => typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function")();
|
|
1337
|
+
const asciis$1 = {
|
|
1338
|
+
_0: 48,
|
|
1339
|
+
_9: 57,
|
|
1340
|
+
A: 65,
|
|
1341
|
+
F: 70,
|
|
1342
|
+
a: 97,
|
|
1343
|
+
f: 102
|
|
1344
|
+
};
|
|
1345
|
+
function asciiToBase16$1(ch) {
|
|
1346
|
+
if (ch >= asciis$1._0 && ch <= asciis$1._9) return ch - asciis$1._0;
|
|
1347
|
+
if (ch >= asciis$1.A && ch <= asciis$1.F) return ch - (asciis$1.A - 10);
|
|
1348
|
+
if (ch >= asciis$1.a && ch <= asciis$1.f) return ch - (asciis$1.a - 10);
|
|
1349
|
+
}
|
|
1350
|
+
/**
|
|
1351
|
+
* Convert hex string to byte array. Uses built-in function, when available.
|
|
1352
|
+
* @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
|
|
1353
|
+
*/
|
|
1354
|
+
function hexToBytes$1(hex$1) {
|
|
1355
|
+
if (typeof hex$1 !== "string") throw new Error("hex string expected, got " + typeof hex$1);
|
|
1356
|
+
if (hasHexBuiltin$1) return Uint8Array.fromHex(hex$1);
|
|
1357
|
+
const hl = hex$1.length;
|
|
1358
|
+
const al = hl / 2;
|
|
1359
|
+
if (hl % 2) throw new Error("hex string expected, got unpadded hex of length " + hl);
|
|
1360
|
+
const array = new Uint8Array(al);
|
|
1361
|
+
for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
|
|
1362
|
+
const n1 = asciiToBase16$1(hex$1.charCodeAt(hi));
|
|
1363
|
+
const n2 = asciiToBase16$1(hex$1.charCodeAt(hi + 1));
|
|
1364
|
+
if (n1 === void 0 || n2 === void 0) {
|
|
1365
|
+
const char = hex$1[hi] + hex$1[hi + 1];
|
|
1366
|
+
throw new Error("hex string expected, got non-hex character \"" + char + "\" at index " + hi);
|
|
1367
|
+
}
|
|
1368
|
+
array[ai] = n1 * 16 + n2;
|
|
1369
|
+
}
|
|
1370
|
+
return array;
|
|
1371
|
+
}
|
|
1372
|
+
/**
|
|
1373
|
+
* There is no setImmediate in browser and setTimeout is slow.
|
|
1374
|
+
* Call of async fn will return Promise, which will be fullfiled only on
|
|
1375
|
+
* next scheduler queue processing step and this is exactly what we need.
|
|
1376
|
+
*/
|
|
1377
|
+
const nextTick = async () => {};
|
|
1378
|
+
/** Returns control to thread each 'tick' ms to avoid blocking. */
|
|
1379
|
+
async function asyncLoop(iters, tick, cb) {
|
|
1380
|
+
let ts = Date.now();
|
|
1381
|
+
for (let i = 0; i < iters; i++) {
|
|
1382
|
+
cb(i);
|
|
1383
|
+
const diff = Date.now() - ts;
|
|
1384
|
+
if (diff >= 0 && diff < tick) continue;
|
|
1385
|
+
await /* @__PURE__ */ nextTick();
|
|
1386
|
+
ts += diff;
|
|
1387
|
+
}
|
|
1388
|
+
}
|
|
1389
|
+
/**
|
|
1390
|
+
* Converts string to bytes using UTF8 encoding.
|
|
1391
|
+
* Built-in doesn't validate input to be string: we do the check.
|
|
1392
|
+
* @example utf8ToBytes('abc') // Uint8Array.from([97, 98, 99])
|
|
1393
|
+
*/
|
|
1394
|
+
function utf8ToBytes$1(str) {
|
|
1395
|
+
if (typeof str !== "string") throw new Error("string expected");
|
|
1396
|
+
return new Uint8Array(new TextEncoder().encode(str));
|
|
1397
|
+
}
|
|
1398
|
+
/**
|
|
1399
|
+
* Helper for KDFs: consumes uint8array or string.
|
|
1400
|
+
* When string is passed, does utf8 decoding, using TextDecoder.
|
|
1401
|
+
*/
|
|
1402
|
+
function kdfInputToBytes(data, errorTitle = "") {
|
|
1403
|
+
if (typeof data === "string") return utf8ToBytes$1(data);
|
|
1404
|
+
return abytes$1(data, void 0, errorTitle);
|
|
1405
|
+
}
|
|
1406
|
+
/** Merges default options and passed options. */
|
|
1407
|
+
function checkOpts(defaults, opts) {
|
|
1408
|
+
if (opts !== void 0 && {}.toString.call(opts) !== "[object Object]") throw new Error("options must be object or undefined");
|
|
1409
|
+
return Object.assign(defaults, opts);
|
|
1410
|
+
}
|
|
1411
|
+
/** Creates function with outputLen, blockLen, create properties from a class constructor. */
|
|
1412
|
+
function createHasher(hashCons, info$1 = {}) {
|
|
1413
|
+
const hashC = (msg, opts) => hashCons(opts).update(msg).digest();
|
|
1414
|
+
const tmp = hashCons(void 0);
|
|
1415
|
+
hashC.outputLen = tmp.outputLen;
|
|
1416
|
+
hashC.blockLen = tmp.blockLen;
|
|
1417
|
+
hashC.create = (opts) => hashCons(opts);
|
|
1418
|
+
Object.assign(hashC, info$1);
|
|
1419
|
+
return Object.freeze(hashC);
|
|
1420
|
+
}
|
|
1421
|
+
/** Creates OID opts for NIST hashes, with prefix 06 09 60 86 48 01 65 03 04 02. */
|
|
1422
|
+
const oidNist = (suffix) => ({ oid: Uint8Array.from([
|
|
1423
|
+
6,
|
|
1424
|
+
9,
|
|
1425
|
+
96,
|
|
1426
|
+
134,
|
|
1427
|
+
72,
|
|
1428
|
+
1,
|
|
1429
|
+
101,
|
|
1430
|
+
3,
|
|
1431
|
+
4,
|
|
1432
|
+
2,
|
|
1433
|
+
suffix
|
|
1434
|
+
]) });
|
|
1435
|
+
|
|
1436
|
+
//#endregion
|
|
1437
|
+
//#region ../../node_modules/.pnpm/@noble+hashes@2.0.1/node_modules/@noble/hashes/hmac.js
|
|
1438
|
+
/**
|
|
1439
|
+
* HMAC: RFC2104 message authentication code.
|
|
1440
|
+
* @module
|
|
1441
|
+
*/
|
|
1442
|
+
/** Internal class for HMAC. */
|
|
1443
|
+
var _HMAC = class {
|
|
1444
|
+
oHash;
|
|
1445
|
+
iHash;
|
|
1446
|
+
blockLen;
|
|
1447
|
+
outputLen;
|
|
1448
|
+
finished = false;
|
|
1449
|
+
destroyed = false;
|
|
1450
|
+
constructor(hash, key) {
|
|
1451
|
+
ahash(hash);
|
|
1452
|
+
abytes$1(key, void 0, "key");
|
|
1453
|
+
this.iHash = hash.create();
|
|
1454
|
+
if (typeof this.iHash.update !== "function") throw new Error("Expected instance of class which extends utils.Hash");
|
|
1455
|
+
this.blockLen = this.iHash.blockLen;
|
|
1456
|
+
this.outputLen = this.iHash.outputLen;
|
|
1457
|
+
const blockLen = this.blockLen;
|
|
1458
|
+
const pad = new Uint8Array(blockLen);
|
|
1459
|
+
pad.set(key.length > blockLen ? hash.create().update(key).digest() : key);
|
|
1460
|
+
for (let i = 0; i < pad.length; i++) pad[i] ^= 54;
|
|
1461
|
+
this.iHash.update(pad);
|
|
1462
|
+
this.oHash = hash.create();
|
|
1463
|
+
for (let i = 0; i < pad.length; i++) pad[i] ^= 106;
|
|
1464
|
+
this.oHash.update(pad);
|
|
1465
|
+
clean(pad);
|
|
1466
|
+
}
|
|
1467
|
+
update(buf) {
|
|
1468
|
+
aexists$1(this);
|
|
1469
|
+
this.iHash.update(buf);
|
|
1470
|
+
return this;
|
|
1471
|
+
}
|
|
1472
|
+
digestInto(out) {
|
|
1473
|
+
aexists$1(this);
|
|
1474
|
+
abytes$1(out, this.outputLen, "output");
|
|
1475
|
+
this.finished = true;
|
|
1476
|
+
this.iHash.digestInto(out);
|
|
1477
|
+
this.oHash.update(out);
|
|
1478
|
+
this.oHash.digestInto(out);
|
|
1479
|
+
this.destroy();
|
|
1480
|
+
}
|
|
1481
|
+
digest() {
|
|
1482
|
+
const out = new Uint8Array(this.oHash.outputLen);
|
|
1483
|
+
this.digestInto(out);
|
|
1484
|
+
return out;
|
|
1485
|
+
}
|
|
1486
|
+
_cloneInto(to) {
|
|
1487
|
+
to ||= Object.create(Object.getPrototypeOf(this), {});
|
|
1488
|
+
const { oHash, iHash, finished, destroyed, blockLen, outputLen } = this;
|
|
1489
|
+
to = to;
|
|
1490
|
+
to.finished = finished;
|
|
1491
|
+
to.destroyed = destroyed;
|
|
1492
|
+
to.blockLen = blockLen;
|
|
1493
|
+
to.outputLen = outputLen;
|
|
1494
|
+
to.oHash = oHash._cloneInto(to.oHash);
|
|
1495
|
+
to.iHash = iHash._cloneInto(to.iHash);
|
|
1496
|
+
return to;
|
|
1497
|
+
}
|
|
1498
|
+
clone() {
|
|
1499
|
+
return this._cloneInto();
|
|
1500
|
+
}
|
|
1501
|
+
destroy() {
|
|
1502
|
+
this.destroyed = true;
|
|
1503
|
+
this.oHash.destroy();
|
|
1504
|
+
this.iHash.destroy();
|
|
1505
|
+
}
|
|
1506
|
+
};
|
|
1507
|
+
/**
|
|
1508
|
+
* HMAC: RFC2104 message authentication code.
|
|
1509
|
+
* @param hash - function that would be used e.g. sha256
|
|
1510
|
+
* @param key - message key
|
|
1511
|
+
* @param message - message data
|
|
1512
|
+
* @example
|
|
1513
|
+
* import { hmac } from '@noble/hashes/hmac';
|
|
1514
|
+
* import { sha256 } from '@noble/hashes/sha2';
|
|
1515
|
+
* const mac1 = hmac(sha256, 'key', 'message');
|
|
1516
|
+
*/
|
|
1517
|
+
const hmac = (hash, key, message) => new _HMAC(hash, key).update(message).digest();
|
|
1518
|
+
hmac.create = (hash, key) => new _HMAC(hash, key);
|
|
1519
|
+
|
|
1520
|
+
//#endregion
|
|
1521
|
+
//#region ../../node_modules/.pnpm/@noble+hashes@2.0.1/node_modules/@noble/hashes/hkdf.js
|
|
1522
|
+
/**
|
|
1523
|
+
* HKDF (RFC 5869): extract + expand in one step.
|
|
1524
|
+
* See https://soatok.blog/2021/11/17/understanding-hkdf/.
|
|
1525
|
+
* @module
|
|
1526
|
+
*/
|
|
1527
|
+
/**
|
|
1528
|
+
* HKDF-extract from spec. Less important part. `HKDF-Extract(IKM, salt) -> PRK`
|
|
1529
|
+
* Arguments position differs from spec (IKM is first one, since it is not optional)
|
|
1530
|
+
* @param hash - hash function that would be used (e.g. sha256)
|
|
1531
|
+
* @param ikm - input keying material, the initial key
|
|
1532
|
+
* @param salt - optional salt value (a non-secret random value)
|
|
1533
|
+
*/
|
|
1534
|
+
function extract(hash, ikm, salt) {
|
|
1535
|
+
ahash(hash);
|
|
1536
|
+
if (salt === void 0) salt = new Uint8Array(hash.outputLen);
|
|
1537
|
+
return hmac(hash, salt, ikm);
|
|
1538
|
+
}
|
|
1539
|
+
const HKDF_COUNTER = /* @__PURE__ */ Uint8Array.of(0);
|
|
1540
|
+
const EMPTY_BUFFER = /* @__PURE__ */ Uint8Array.of();
|
|
1541
|
+
/**
|
|
1542
|
+
* HKDF-expand from the spec. The most important part. `HKDF-Expand(PRK, info, L) -> OKM`
|
|
1543
|
+
* @param hash - hash function that would be used (e.g. sha256)
|
|
1544
|
+
* @param prk - a pseudorandom key of at least HashLen octets (usually, the output from the extract step)
|
|
1545
|
+
* @param info - optional context and application specific information (can be a zero-length string)
|
|
1546
|
+
* @param length - length of output keying material in bytes
|
|
1547
|
+
*/
|
|
1548
|
+
function expand(hash, prk, info$1, length = 32) {
|
|
1549
|
+
ahash(hash);
|
|
1550
|
+
anumber(length, "length");
|
|
1551
|
+
const olen = hash.outputLen;
|
|
1552
|
+
if (length > 255 * olen) throw new Error("Length must be <= 255*HashLen");
|
|
1553
|
+
const blocks = Math.ceil(length / olen);
|
|
1554
|
+
if (info$1 === void 0) info$1 = EMPTY_BUFFER;
|
|
1555
|
+
else abytes$1(info$1, void 0, "info");
|
|
1556
|
+
const okm = new Uint8Array(blocks * olen);
|
|
1557
|
+
const HMAC = hmac.create(hash, prk);
|
|
1558
|
+
const HMACTmp = HMAC._cloneInto();
|
|
1559
|
+
const T = new Uint8Array(HMAC.outputLen);
|
|
1560
|
+
for (let counter = 0; counter < blocks; counter++) {
|
|
1561
|
+
HKDF_COUNTER[0] = counter + 1;
|
|
1562
|
+
HMACTmp.update(counter === 0 ? EMPTY_BUFFER : T).update(info$1).update(HKDF_COUNTER).digestInto(T);
|
|
1563
|
+
okm.set(T, olen * counter);
|
|
1564
|
+
HMAC._cloneInto(HMACTmp);
|
|
1565
|
+
}
|
|
1566
|
+
HMAC.destroy();
|
|
1567
|
+
HMACTmp.destroy();
|
|
1568
|
+
clean(T, HKDF_COUNTER);
|
|
1569
|
+
return okm.slice(0, length);
|
|
1570
|
+
}
|
|
1571
|
+
/**
|
|
1572
|
+
* HKDF (RFC 5869): derive keys from an initial input.
|
|
1573
|
+
* Combines hkdf_extract + hkdf_expand in one step
|
|
1574
|
+
* @param hash - hash function that would be used (e.g. sha256)
|
|
1575
|
+
* @param ikm - input keying material, the initial key
|
|
1576
|
+
* @param salt - optional salt value (a non-secret random value)
|
|
1577
|
+
* @param info - optional context and application specific information (can be a zero-length string)
|
|
1578
|
+
* @param length - length of output keying material in bytes
|
|
1579
|
+
* @example
|
|
1580
|
+
* import { hkdf } from '@noble/hashes/hkdf';
|
|
1581
|
+
* import { sha256 } from '@noble/hashes/sha2';
|
|
1582
|
+
* import { randomBytes } from '@noble/hashes/utils';
|
|
1583
|
+
* const inputKey = randomBytes(32);
|
|
1584
|
+
* const salt = randomBytes(32);
|
|
1585
|
+
* const info = 'application-key';
|
|
1586
|
+
* const hk1 = hkdf(sha256, inputKey, salt, info, 32);
|
|
1587
|
+
*/
|
|
1588
|
+
const hkdf = (hash, ikm, salt, info$1, length) => expand(hash, extract(hash, ikm, salt), info$1, length);
|
|
1589
|
+
|
|
1590
|
+
//#endregion
|
|
1591
|
+
//#region ../../node_modules/.pnpm/@noble+hashes@2.0.1/node_modules/@noble/hashes/_md.js
|
|
1592
|
+
/**
|
|
1593
|
+
* Internal Merkle-Damgard hash utils.
|
|
1594
|
+
* @module
|
|
1595
|
+
*/
|
|
1596
|
+
/** Choice: a ? b : c */
|
|
1597
|
+
function Chi(a, b, c) {
|
|
1598
|
+
return a & b ^ ~a & c;
|
|
1599
|
+
}
|
|
1600
|
+
/** Majority function, true if any two inputs is true. */
|
|
1601
|
+
function Maj(a, b, c) {
|
|
1602
|
+
return a & b ^ a & c ^ b & c;
|
|
1603
|
+
}
|
|
1604
|
+
/**
|
|
1605
|
+
* Merkle-Damgard hash construction base class.
|
|
1606
|
+
* Could be used to create MD5, RIPEMD, SHA1, SHA2.
|
|
1607
|
+
*/
|
|
1608
|
+
var HashMD = class {
|
|
1609
|
+
blockLen;
|
|
1610
|
+
outputLen;
|
|
1611
|
+
padOffset;
|
|
1612
|
+
isLE;
|
|
1613
|
+
buffer;
|
|
1614
|
+
view;
|
|
1615
|
+
finished = false;
|
|
1616
|
+
length = 0;
|
|
1617
|
+
pos = 0;
|
|
1618
|
+
destroyed = false;
|
|
1619
|
+
constructor(blockLen, outputLen, padOffset, isLE$2) {
|
|
1620
|
+
this.blockLen = blockLen;
|
|
1621
|
+
this.outputLen = outputLen;
|
|
1622
|
+
this.padOffset = padOffset;
|
|
1623
|
+
this.isLE = isLE$2;
|
|
1624
|
+
this.buffer = new Uint8Array(blockLen);
|
|
1625
|
+
this.view = createView(this.buffer);
|
|
1626
|
+
}
|
|
1627
|
+
update(data) {
|
|
1628
|
+
aexists$1(this);
|
|
1629
|
+
abytes$1(data);
|
|
1630
|
+
const { view, buffer, blockLen } = this;
|
|
1631
|
+
const len = data.length;
|
|
1632
|
+
for (let pos = 0; pos < len;) {
|
|
1633
|
+
const take = Math.min(blockLen - this.pos, len - pos);
|
|
1634
|
+
if (take === blockLen) {
|
|
1635
|
+
const dataView = createView(data);
|
|
1636
|
+
for (; blockLen <= len - pos; pos += blockLen) this.process(dataView, pos);
|
|
1637
|
+
continue;
|
|
1638
|
+
}
|
|
1639
|
+
buffer.set(data.subarray(pos, pos + take), this.pos);
|
|
1640
|
+
this.pos += take;
|
|
1641
|
+
pos += take;
|
|
1642
|
+
if (this.pos === blockLen) {
|
|
1643
|
+
this.process(view, 0);
|
|
1644
|
+
this.pos = 0;
|
|
1645
|
+
}
|
|
1646
|
+
}
|
|
1647
|
+
this.length += data.length;
|
|
1648
|
+
this.roundClean();
|
|
1649
|
+
return this;
|
|
1650
|
+
}
|
|
1651
|
+
digestInto(out) {
|
|
1652
|
+
aexists$1(this);
|
|
1653
|
+
aoutput$1(out, this);
|
|
1654
|
+
this.finished = true;
|
|
1655
|
+
const { buffer, view, blockLen, isLE: isLE$2 } = this;
|
|
1656
|
+
let { pos } = this;
|
|
1657
|
+
buffer[pos++] = 128;
|
|
1658
|
+
clean(this.buffer.subarray(pos));
|
|
1659
|
+
if (this.padOffset > blockLen - pos) {
|
|
1660
|
+
this.process(view, 0);
|
|
1661
|
+
pos = 0;
|
|
1662
|
+
}
|
|
1663
|
+
for (let i = pos; i < blockLen; i++) buffer[i] = 0;
|
|
1664
|
+
view.setBigUint64(blockLen - 8, BigInt(this.length * 8), isLE$2);
|
|
1665
|
+
this.process(view, 0);
|
|
1666
|
+
const oview = createView(out);
|
|
1667
|
+
const len = this.outputLen;
|
|
1668
|
+
if (len % 4) throw new Error("_sha2: outputLen must be aligned to 32bit");
|
|
1669
|
+
const outLen = len / 4;
|
|
1670
|
+
const state = this.get();
|
|
1671
|
+
if (outLen > state.length) throw new Error("_sha2: outputLen bigger than state");
|
|
1672
|
+
for (let i = 0; i < outLen; i++) oview.setUint32(4 * i, state[i], isLE$2);
|
|
1673
|
+
}
|
|
1674
|
+
digest() {
|
|
1675
|
+
const { buffer, outputLen } = this;
|
|
1676
|
+
this.digestInto(buffer);
|
|
1677
|
+
const res = buffer.slice(0, outputLen);
|
|
1678
|
+
this.destroy();
|
|
1679
|
+
return res;
|
|
1680
|
+
}
|
|
1681
|
+
_cloneInto(to) {
|
|
1682
|
+
to ||= new this.constructor();
|
|
1683
|
+
to.set(...this.get());
|
|
1684
|
+
const { blockLen, buffer, length, finished, destroyed, pos } = this;
|
|
1685
|
+
to.destroyed = destroyed;
|
|
1686
|
+
to.finished = finished;
|
|
1687
|
+
to.length = length;
|
|
1688
|
+
to.pos = pos;
|
|
1689
|
+
if (length % blockLen) to.buffer.set(buffer);
|
|
1690
|
+
return to;
|
|
1691
|
+
}
|
|
1692
|
+
clone() {
|
|
1693
|
+
return this._cloneInto();
|
|
1694
|
+
}
|
|
1695
|
+
};
|
|
1696
|
+
/**
|
|
1697
|
+
* Initial SHA-2 state: fractional parts of square roots of first 16 primes 2..53.
|
|
1698
|
+
* Check out `test/misc/sha2-gen-iv.js` for recomputation guide.
|
|
1699
|
+
*/
|
|
1700
|
+
/** Initial SHA256 state. Bits 0..32 of frac part of sqrt of primes 2..19 */
|
|
1701
|
+
const SHA256_IV = /* @__PURE__ */ Uint32Array.from([
|
|
1702
|
+
1779033703,
|
|
1703
|
+
3144134277,
|
|
1704
|
+
1013904242,
|
|
1705
|
+
2773480762,
|
|
1706
|
+
1359893119,
|
|
1707
|
+
2600822924,
|
|
1708
|
+
528734635,
|
|
1709
|
+
1541459225
|
|
1710
|
+
]);
|
|
1711
|
+
|
|
1712
|
+
//#endregion
|
|
1713
|
+
//#region ../../node_modules/.pnpm/@noble+hashes@2.0.1/node_modules/@noble/hashes/_u64.js
|
|
1714
|
+
/**
|
|
1715
|
+
* Internal helpers for u64. BigUint64Array is too slow as per 2025, so we implement it using Uint32Array.
|
|
1716
|
+
* @todo re-check https://issues.chromium.org/issues/42212588
|
|
1717
|
+
* @module
|
|
1718
|
+
*/
|
|
1719
|
+
const U32_MASK64 = /* @__PURE__ */ BigInt(2 ** 32 - 1);
|
|
1720
|
+
const _32n = /* @__PURE__ */ BigInt(32);
|
|
1721
|
+
function fromBig(n, le = false) {
|
|
1722
|
+
if (le) return {
|
|
1723
|
+
h: Number(n & U32_MASK64),
|
|
1724
|
+
l: Number(n >> _32n & U32_MASK64)
|
|
1725
|
+
};
|
|
1726
|
+
return {
|
|
1727
|
+
h: Number(n >> _32n & U32_MASK64) | 0,
|
|
1728
|
+
l: Number(n & U32_MASK64) | 0
|
|
1729
|
+
};
|
|
1730
|
+
}
|
|
1731
|
+
function split(lst, le = false) {
|
|
1732
|
+
const len = lst.length;
|
|
1733
|
+
let Ah = new Uint32Array(len);
|
|
1734
|
+
let Al = new Uint32Array(len);
|
|
1735
|
+
for (let i = 0; i < len; i++) {
|
|
1736
|
+
const { h, l } = fromBig(lst[i], le);
|
|
1737
|
+
[Ah[i], Al[i]] = [h, l];
|
|
1738
|
+
}
|
|
1739
|
+
return [Ah, Al];
|
|
1740
|
+
}
|
|
1741
|
+
const rotlSH = (h, l, s) => h << s | l >>> 32 - s;
|
|
1742
|
+
const rotlSL = (h, l, s) => l << s | h >>> 32 - s;
|
|
1743
|
+
const rotlBH = (h, l, s) => l << s - 32 | h >>> 64 - s;
|
|
1744
|
+
const rotlBL = (h, l, s) => h << s - 32 | l >>> 64 - s;
|
|
1745
|
+
|
|
1746
|
+
//#endregion
|
|
1747
|
+
//#region ../../node_modules/.pnpm/@noble+hashes@2.0.1/node_modules/@noble/hashes/sha2.js
|
|
1748
|
+
/**
|
|
1749
|
+
* SHA2 hash function. A.k.a. sha256, sha384, sha512, sha512_224, sha512_256.
|
|
1750
|
+
* SHA256 is the fastest hash implementable in JS, even faster than Blake3.
|
|
1751
|
+
* Check out [RFC 4634](https://www.rfc-editor.org/rfc/rfc4634) and
|
|
1752
|
+
* [FIPS 180-4](https://nvlpubs.nist.gov/nistpubs/FIPS/NIST.FIPS.180-4.pdf).
|
|
1753
|
+
* @module
|
|
1754
|
+
*/
|
|
1755
|
+
/**
|
|
1756
|
+
* Round constants:
|
|
1757
|
+
* First 32 bits of fractional parts of the cube roots of the first 64 primes 2..311)
|
|
1758
|
+
*/
|
|
1759
|
+
const SHA256_K = /* @__PURE__ */ Uint32Array.from([
|
|
1760
|
+
1116352408,
|
|
1761
|
+
1899447441,
|
|
1762
|
+
3049323471,
|
|
1763
|
+
3921009573,
|
|
1764
|
+
961987163,
|
|
1765
|
+
1508970993,
|
|
1766
|
+
2453635748,
|
|
1767
|
+
2870763221,
|
|
1768
|
+
3624381080,
|
|
1769
|
+
310598401,
|
|
1770
|
+
607225278,
|
|
1771
|
+
1426881987,
|
|
1772
|
+
1925078388,
|
|
1773
|
+
2162078206,
|
|
1774
|
+
2614888103,
|
|
1775
|
+
3248222580,
|
|
1776
|
+
3835390401,
|
|
1777
|
+
4022224774,
|
|
1778
|
+
264347078,
|
|
1779
|
+
604807628,
|
|
1780
|
+
770255983,
|
|
1781
|
+
1249150122,
|
|
1782
|
+
1555081692,
|
|
1783
|
+
1996064986,
|
|
1784
|
+
2554220882,
|
|
1785
|
+
2821834349,
|
|
1786
|
+
2952996808,
|
|
1787
|
+
3210313671,
|
|
1788
|
+
3336571891,
|
|
1789
|
+
3584528711,
|
|
1790
|
+
113926993,
|
|
1791
|
+
338241895,
|
|
1792
|
+
666307205,
|
|
1793
|
+
773529912,
|
|
1794
|
+
1294757372,
|
|
1795
|
+
1396182291,
|
|
1796
|
+
1695183700,
|
|
1797
|
+
1986661051,
|
|
1798
|
+
2177026350,
|
|
1799
|
+
2456956037,
|
|
1800
|
+
2730485921,
|
|
1801
|
+
2820302411,
|
|
1802
|
+
3259730800,
|
|
1803
|
+
3345764771,
|
|
1804
|
+
3516065817,
|
|
1805
|
+
3600352804,
|
|
1806
|
+
4094571909,
|
|
1807
|
+
275423344,
|
|
1808
|
+
430227734,
|
|
1809
|
+
506948616,
|
|
1810
|
+
659060556,
|
|
1811
|
+
883997877,
|
|
1812
|
+
958139571,
|
|
1813
|
+
1322822218,
|
|
1814
|
+
1537002063,
|
|
1815
|
+
1747873779,
|
|
1816
|
+
1955562222,
|
|
1817
|
+
2024104815,
|
|
1818
|
+
2227730452,
|
|
1819
|
+
2361852424,
|
|
1820
|
+
2428436474,
|
|
1821
|
+
2756734187,
|
|
1822
|
+
3204031479,
|
|
1823
|
+
3329325298
|
|
1824
|
+
]);
|
|
1825
|
+
/** Reusable temporary buffer. "W" comes straight from spec. */
|
|
1826
|
+
const SHA256_W = /* @__PURE__ */ new Uint32Array(64);
|
|
1827
|
+
/** Internal 32-byte base SHA2 hash class. */
|
|
1828
|
+
var SHA2_32B = class extends HashMD {
|
|
1829
|
+
constructor(outputLen) {
|
|
1830
|
+
super(64, outputLen, 8, false);
|
|
1831
|
+
}
|
|
1832
|
+
get() {
|
|
1833
|
+
const { A, B, C, D, E, F, G, H } = this;
|
|
1834
|
+
return [
|
|
1835
|
+
A,
|
|
1836
|
+
B,
|
|
1837
|
+
C,
|
|
1838
|
+
D,
|
|
1839
|
+
E,
|
|
1840
|
+
F,
|
|
1841
|
+
G,
|
|
1842
|
+
H
|
|
1843
|
+
];
|
|
1844
|
+
}
|
|
1845
|
+
set(A, B, C, D, E, F, G, H) {
|
|
1846
|
+
this.A = A | 0;
|
|
1847
|
+
this.B = B | 0;
|
|
1848
|
+
this.C = C | 0;
|
|
1849
|
+
this.D = D | 0;
|
|
1850
|
+
this.E = E | 0;
|
|
1851
|
+
this.F = F | 0;
|
|
1852
|
+
this.G = G | 0;
|
|
1853
|
+
this.H = H | 0;
|
|
1854
|
+
}
|
|
1855
|
+
process(view, offset) {
|
|
1856
|
+
for (let i = 0; i < 16; i++, offset += 4) SHA256_W[i] = view.getUint32(offset, false);
|
|
1857
|
+
for (let i = 16; i < 64; i++) {
|
|
1858
|
+
const W15 = SHA256_W[i - 15];
|
|
1859
|
+
const W2 = SHA256_W[i - 2];
|
|
1860
|
+
const s0 = rotr(W15, 7) ^ rotr(W15, 18) ^ W15 >>> 3;
|
|
1861
|
+
SHA256_W[i] = (rotr(W2, 17) ^ rotr(W2, 19) ^ W2 >>> 10) + SHA256_W[i - 7] + s0 + SHA256_W[i - 16] | 0;
|
|
1862
|
+
}
|
|
1863
|
+
let { A, B, C, D, E, F, G, H } = this;
|
|
1864
|
+
for (let i = 0; i < 64; i++) {
|
|
1865
|
+
const sigma1 = rotr(E, 6) ^ rotr(E, 11) ^ rotr(E, 25);
|
|
1866
|
+
const T1 = H + sigma1 + Chi(E, F, G) + SHA256_K[i] + SHA256_W[i] | 0;
|
|
1867
|
+
const T2 = (rotr(A, 2) ^ rotr(A, 13) ^ rotr(A, 22)) + Maj(A, B, C) | 0;
|
|
1868
|
+
H = G;
|
|
1869
|
+
G = F;
|
|
1870
|
+
F = E;
|
|
1871
|
+
E = D + T1 | 0;
|
|
1872
|
+
D = C;
|
|
1873
|
+
C = B;
|
|
1874
|
+
B = A;
|
|
1875
|
+
A = T1 + T2 | 0;
|
|
1876
|
+
}
|
|
1877
|
+
A = A + this.A | 0;
|
|
1878
|
+
B = B + this.B | 0;
|
|
1879
|
+
C = C + this.C | 0;
|
|
1880
|
+
D = D + this.D | 0;
|
|
1881
|
+
E = E + this.E | 0;
|
|
1882
|
+
F = F + this.F | 0;
|
|
1883
|
+
G = G + this.G | 0;
|
|
1884
|
+
H = H + this.H | 0;
|
|
1885
|
+
this.set(A, B, C, D, E, F, G, H);
|
|
1886
|
+
}
|
|
1887
|
+
roundClean() {
|
|
1888
|
+
clean(SHA256_W);
|
|
1889
|
+
}
|
|
1890
|
+
destroy() {
|
|
1891
|
+
this.set(0, 0, 0, 0, 0, 0, 0, 0);
|
|
1892
|
+
clean(this.buffer);
|
|
1893
|
+
}
|
|
1894
|
+
};
|
|
1895
|
+
/** Internal SHA2-256 hash class. */
|
|
1896
|
+
var _SHA256 = class extends SHA2_32B {
|
|
1897
|
+
A = SHA256_IV[0] | 0;
|
|
1898
|
+
B = SHA256_IV[1] | 0;
|
|
1899
|
+
C = SHA256_IV[2] | 0;
|
|
1900
|
+
D = SHA256_IV[3] | 0;
|
|
1901
|
+
E = SHA256_IV[4] | 0;
|
|
1902
|
+
F = SHA256_IV[5] | 0;
|
|
1903
|
+
G = SHA256_IV[6] | 0;
|
|
1904
|
+
H = SHA256_IV[7] | 0;
|
|
1905
|
+
constructor() {
|
|
1906
|
+
super(32);
|
|
1907
|
+
}
|
|
1908
|
+
};
|
|
1909
|
+
/**
|
|
1910
|
+
* SHA2-256 hash function from RFC 4634. In JS it's the fastest: even faster than Blake3. Some info:
|
|
1911
|
+
*
|
|
1912
|
+
* - Trying 2^128 hashes would get 50% chance of collision, using birthday attack.
|
|
1913
|
+
* - BTC network is doing 2^70 hashes/sec (2^95 hashes/year) as per 2025.
|
|
1914
|
+
* - Each sha256 hash is executing 2^18 bit operations.
|
|
1915
|
+
* - Good 2024 ASICs can do 200Th/sec with 3500 watts of power, corresponding to 2^36 hashes/joule.
|
|
1916
|
+
*/
|
|
1917
|
+
const sha256 = /* @__PURE__ */ createHasher(() => new _SHA256(), /* @__PURE__ */ oidNist(1));
|
|
1918
|
+
|
|
1919
|
+
//#endregion
|
|
1920
|
+
//#region ../better-auth/dist/hex-Bu7BHRzh.mjs
|
|
1921
|
+
function getWebcryptoSubtle() {
|
|
1922
|
+
const cr = typeof globalThis !== "undefined" && globalThis.crypto;
|
|
1923
|
+
if (cr && typeof cr.subtle === "object" && cr.subtle != null) return cr.subtle;
|
|
1924
|
+
throw new Error("crypto.subtle must be defined");
|
|
1925
|
+
}
|
|
1926
|
+
async function signJWT(payload, secret, expiresIn = 3600) {
|
|
1927
|
+
return await new SignJWT(payload).setProtectedHeader({ alg: "HS256" }).setIssuedAt().setExpirationTime(Math.floor(Date.now() / 1e3) + expiresIn).sign(new TextEncoder().encode(secret));
|
|
1928
|
+
}
|
|
1929
|
+
async function verifyJWT(token, secret) {
|
|
1930
|
+
try {
|
|
1931
|
+
return (await jwtVerify(token, new TextEncoder().encode(secret))).payload;
|
|
1932
|
+
} catch (error) {
|
|
1933
|
+
return null;
|
|
1934
|
+
}
|
|
1935
|
+
}
|
|
1936
|
+
const info = new Uint8Array([
|
|
1937
|
+
66,
|
|
1938
|
+
101,
|
|
1939
|
+
116,
|
|
1940
|
+
116,
|
|
1941
|
+
101,
|
|
1942
|
+
114,
|
|
1943
|
+
65,
|
|
1944
|
+
117,
|
|
1945
|
+
116,
|
|
1946
|
+
104,
|
|
1947
|
+
46,
|
|
1948
|
+
106,
|
|
1949
|
+
115,
|
|
1950
|
+
32,
|
|
1951
|
+
71,
|
|
1952
|
+
101,
|
|
1953
|
+
110,
|
|
1954
|
+
101,
|
|
1955
|
+
114,
|
|
1956
|
+
97,
|
|
1957
|
+
116,
|
|
1958
|
+
101,
|
|
1959
|
+
100,
|
|
1960
|
+
32,
|
|
1961
|
+
69,
|
|
1962
|
+
110,
|
|
1963
|
+
99,
|
|
1964
|
+
114,
|
|
1965
|
+
121,
|
|
1966
|
+
112,
|
|
1967
|
+
116,
|
|
1968
|
+
105,
|
|
1969
|
+
111,
|
|
1970
|
+
110,
|
|
1971
|
+
32,
|
|
1972
|
+
75,
|
|
1973
|
+
101,
|
|
1974
|
+
121
|
|
1975
|
+
]);
|
|
1976
|
+
const now = () => Date.now() / 1e3 | 0;
|
|
1977
|
+
const alg = "dir";
|
|
1978
|
+
const enc = "A256CBC-HS512";
|
|
1979
|
+
async function symmetricEncodeJWT(payload, secret, salt, expiresIn = 3600) {
|
|
1980
|
+
const encryptionSecret = hkdf(sha256, new TextEncoder().encode(secret), new TextEncoder().encode(salt), info, 64);
|
|
1981
|
+
const thumbprint = await calculateJwkThumbprint({
|
|
1982
|
+
kty: "oct",
|
|
1983
|
+
k: encode(encryptionSecret)
|
|
1984
|
+
}, "sha256");
|
|
1985
|
+
return await new EncryptJWT(payload).setProtectedHeader({
|
|
1986
|
+
alg,
|
|
1987
|
+
enc,
|
|
1988
|
+
kid: thumbprint
|
|
1989
|
+
}).setIssuedAt().setExpirationTime(now() + expiresIn).setJti(crypto.randomUUID()).encrypt(encryptionSecret);
|
|
1990
|
+
}
|
|
1991
|
+
async function symmetricDecodeJWT(token, secret, salt) {
|
|
1992
|
+
if (!token) return null;
|
|
1993
|
+
try {
|
|
1994
|
+
const { payload } = await jwtDecrypt(token, async ({ kid }) => {
|
|
1995
|
+
const encryptionSecret = hkdf(sha256, new TextEncoder().encode(secret), new TextEncoder().encode(salt), info, 64);
|
|
1996
|
+
if (kid === void 0) return encryptionSecret;
|
|
1997
|
+
if (kid === await calculateJwkThumbprint({
|
|
1998
|
+
kty: "oct",
|
|
1999
|
+
k: encode(encryptionSecret)
|
|
2000
|
+
}, "sha256")) return encryptionSecret;
|
|
2001
|
+
throw new Error("no matching decryption secret");
|
|
2002
|
+
}, {
|
|
2003
|
+
clockTolerance: 15,
|
|
2004
|
+
keyManagementAlgorithms: [alg],
|
|
2005
|
+
contentEncryptionAlgorithms: [enc, "A256GCM"]
|
|
2006
|
+
});
|
|
2007
|
+
return payload;
|
|
2008
|
+
} catch (error) {
|
|
2009
|
+
return null;
|
|
2010
|
+
}
|
|
2011
|
+
}
|
|
2012
|
+
const hexadecimal = "0123456789abcdef";
|
|
2013
|
+
const hex = {
|
|
2014
|
+
encode: (data) => {
|
|
2015
|
+
if (typeof data === "string") data = new TextEncoder().encode(data);
|
|
2016
|
+
if (data.byteLength === 0) return "";
|
|
2017
|
+
const buffer = new Uint8Array(data);
|
|
2018
|
+
let result = "";
|
|
2019
|
+
for (const byte of buffer) result += byte.toString(16).padStart(2, "0");
|
|
2020
|
+
return result;
|
|
2021
|
+
},
|
|
2022
|
+
decode: (data) => {
|
|
2023
|
+
if (!data) return "";
|
|
2024
|
+
if (typeof data === "string") {
|
|
2025
|
+
if (data.length % 2 !== 0) throw new Error("Invalid hexadecimal string");
|
|
2026
|
+
if (!(/* @__PURE__ */ new RegExp(`^[${hexadecimal}]+$`)).test(data)) throw new Error("Invalid hexadecimal string");
|
|
2027
|
+
const result = new Uint8Array(data.length / 2);
|
|
2028
|
+
for (let i = 0; i < data.length; i += 2) result[i / 2] = parseInt(data.slice(i, i + 2), 16);
|
|
2029
|
+
return new TextDecoder().decode(result);
|
|
2030
|
+
}
|
|
2031
|
+
return new TextDecoder().decode(data);
|
|
2032
|
+
}
|
|
2033
|
+
};
|
|
2034
|
+
|
|
2035
|
+
//#endregion
|
|
2036
|
+
//#region ../../node_modules/.pnpm/@noble+ciphers@2.0.1/node_modules/@noble/ciphers/utils.js
|
|
2037
|
+
/**
|
|
2038
|
+
* Utilities for hex, bytes, CSPRNG.
|
|
2039
|
+
* @module
|
|
2040
|
+
*/
|
|
2041
|
+
/*! noble-ciphers - MIT License (c) 2023 Paul Miller (paulmillr.com) */
|
|
2042
|
+
/** Checks if something is Uint8Array. Be careful: nodejs Buffer will return true. */
|
|
2043
|
+
function isBytes(a) {
|
|
2044
|
+
return a instanceof Uint8Array || ArrayBuffer.isView(a) && a.constructor.name === "Uint8Array";
|
|
2045
|
+
}
|
|
2046
|
+
/** Asserts something is boolean. */
|
|
2047
|
+
function abool(b) {
|
|
2048
|
+
if (typeof b !== "boolean") throw new Error(`boolean expected, not ${b}`);
|
|
2049
|
+
}
|
|
2050
|
+
/** Asserts something is positive integer. */
|
|
2051
|
+
function anumber$1(n) {
|
|
2052
|
+
if (!Number.isSafeInteger(n) || n < 0) throw new Error("positive integer expected, got " + n);
|
|
2053
|
+
}
|
|
2054
|
+
/** Asserts something is Uint8Array. */
|
|
2055
|
+
function abytes(value, length, title = "") {
|
|
2056
|
+
const bytes = isBytes(value);
|
|
2057
|
+
const len = value?.length;
|
|
2058
|
+
const needsLen = length !== void 0;
|
|
2059
|
+
if (!bytes || needsLen && len !== length) {
|
|
2060
|
+
const prefix = title && `"${title}" `;
|
|
2061
|
+
const ofLen = needsLen ? ` of length ${length}` : "";
|
|
2062
|
+
const got = bytes ? `length=${len}` : `type=${typeof value}`;
|
|
2063
|
+
throw new Error(prefix + "expected Uint8Array" + ofLen + ", got " + got);
|
|
2064
|
+
}
|
|
2065
|
+
return value;
|
|
2066
|
+
}
|
|
2067
|
+
/** Asserts a hash instance has not been destroyed / finished */
|
|
2068
|
+
function aexists(instance, checkFinished = true) {
|
|
2069
|
+
if (instance.destroyed) throw new Error("Hash instance has been destroyed");
|
|
2070
|
+
if (checkFinished && instance.finished) throw new Error("Hash#digest() has already been called");
|
|
2071
|
+
}
|
|
2072
|
+
/** Asserts output is properly-sized byte array */
|
|
2073
|
+
function aoutput(out, instance) {
|
|
2074
|
+
abytes(out, void 0, "output");
|
|
2075
|
+
const min = instance.outputLen;
|
|
2076
|
+
if (out.length < min) throw new Error("digestInto() expects output buffer of length at least " + min);
|
|
2077
|
+
}
|
|
2078
|
+
/** Cast u8 / u16 / u32 to u32. */
|
|
2079
|
+
function u32$1(arr) {
|
|
2080
|
+
return new Uint32Array(arr.buffer, arr.byteOffset, Math.floor(arr.byteLength / 4));
|
|
2081
|
+
}
|
|
2082
|
+
/** Zeroize a byte array. Warning: JS provides no guarantees. */
|
|
2083
|
+
function clean$1(...arrays) {
|
|
2084
|
+
for (let i = 0; i < arrays.length; i++) arrays[i].fill(0);
|
|
2085
|
+
}
|
|
2086
|
+
/** Create DataView of an array for easy byte-level manipulation. */
|
|
2087
|
+
function createView$1(arr) {
|
|
2088
|
+
return new DataView(arr.buffer, arr.byteOffset, arr.byteLength);
|
|
2089
|
+
}
|
|
2090
|
+
/** Is current platform little-endian? Most are. Big-Endian platform: IBM */
|
|
2091
|
+
const isLE = /* @__PURE__ */ (() => new Uint8Array(new Uint32Array([287454020]).buffer)[0] === 68)();
|
|
2092
|
+
const hasHexBuiltin = /* @__PURE__ */ (() => typeof Uint8Array.from([]).toHex === "function" && typeof Uint8Array.fromHex === "function")();
|
|
2093
|
+
const hexes = /* @__PURE__ */ Array.from({ length: 256 }, (_, i) => i.toString(16).padStart(2, "0"));
|
|
2094
|
+
/**
|
|
2095
|
+
* Convert byte array to hex string. Uses built-in function, when available.
|
|
2096
|
+
* @example bytesToHex(Uint8Array.from([0xca, 0xfe, 0x01, 0x23])) // 'cafe0123'
|
|
2097
|
+
*/
|
|
2098
|
+
function bytesToHex(bytes) {
|
|
2099
|
+
abytes(bytes);
|
|
2100
|
+
if (hasHexBuiltin) return bytes.toHex();
|
|
2101
|
+
let hex$1 = "";
|
|
2102
|
+
for (let i = 0; i < bytes.length; i++) hex$1 += hexes[bytes[i]];
|
|
2103
|
+
return hex$1;
|
|
2104
|
+
}
|
|
2105
|
+
const asciis = {
|
|
2106
|
+
_0: 48,
|
|
2107
|
+
_9: 57,
|
|
2108
|
+
A: 65,
|
|
2109
|
+
F: 70,
|
|
2110
|
+
a: 97,
|
|
2111
|
+
f: 102
|
|
2112
|
+
};
|
|
2113
|
+
function asciiToBase16(ch) {
|
|
2114
|
+
if (ch >= asciis._0 && ch <= asciis._9) return ch - asciis._0;
|
|
2115
|
+
if (ch >= asciis.A && ch <= asciis.F) return ch - (asciis.A - 10);
|
|
2116
|
+
if (ch >= asciis.a && ch <= asciis.f) return ch - (asciis.a - 10);
|
|
2117
|
+
}
|
|
2118
|
+
/**
|
|
2119
|
+
* Convert hex string to byte array. Uses built-in function, when available.
|
|
2120
|
+
* @example hexToBytes('cafe0123') // Uint8Array.from([0xca, 0xfe, 0x01, 0x23])
|
|
2121
|
+
*/
|
|
2122
|
+
function hexToBytes(hex$1) {
|
|
2123
|
+
if (typeof hex$1 !== "string") throw new Error("hex string expected, got " + typeof hex$1);
|
|
2124
|
+
if (hasHexBuiltin) return Uint8Array.fromHex(hex$1);
|
|
2125
|
+
const hl = hex$1.length;
|
|
2126
|
+
const al = hl / 2;
|
|
2127
|
+
if (hl % 2) throw new Error("hex string expected, got unpadded hex of length " + hl);
|
|
2128
|
+
const array = new Uint8Array(al);
|
|
2129
|
+
for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {
|
|
2130
|
+
const n1 = asciiToBase16(hex$1.charCodeAt(hi));
|
|
2131
|
+
const n2 = asciiToBase16(hex$1.charCodeAt(hi + 1));
|
|
2132
|
+
if (n1 === void 0 || n2 === void 0) {
|
|
2133
|
+
const char = hex$1[hi] + hex$1[hi + 1];
|
|
2134
|
+
throw new Error("hex string expected, got non-hex character \"" + char + "\" at index " + hi);
|
|
2135
|
+
}
|
|
2136
|
+
array[ai] = n1 * 16 + n2;
|
|
2137
|
+
}
|
|
2138
|
+
return array;
|
|
2139
|
+
}
|
|
2140
|
+
/**
|
|
2141
|
+
* Converts string to bytes using UTF8 encoding.
|
|
2142
|
+
* @example utf8ToBytes('abc') // new Uint8Array([97, 98, 99])
|
|
2143
|
+
*/
|
|
2144
|
+
function utf8ToBytes(str) {
|
|
2145
|
+
if (typeof str !== "string") throw new Error("string expected");
|
|
2146
|
+
return new Uint8Array(new TextEncoder().encode(str));
|
|
2147
|
+
}
|
|
2148
|
+
/**
|
|
2149
|
+
* Copies several Uint8Arrays into one.
|
|
2150
|
+
*/
|
|
2151
|
+
function concatBytes(...arrays) {
|
|
2152
|
+
let sum = 0;
|
|
2153
|
+
for (let i = 0; i < arrays.length; i++) {
|
|
2154
|
+
const a = arrays[i];
|
|
2155
|
+
abytes(a);
|
|
2156
|
+
sum += a.length;
|
|
2157
|
+
}
|
|
2158
|
+
const res = new Uint8Array(sum);
|
|
2159
|
+
for (let i = 0, pad = 0; i < arrays.length; i++) {
|
|
2160
|
+
const a = arrays[i];
|
|
2161
|
+
res.set(a, pad);
|
|
2162
|
+
pad += a.length;
|
|
2163
|
+
}
|
|
2164
|
+
return res;
|
|
2165
|
+
}
|
|
2166
|
+
function checkOpts$1(defaults, opts) {
|
|
2167
|
+
if (opts == null || typeof opts !== "object") throw new Error("options must be defined");
|
|
2168
|
+
return Object.assign(defaults, opts);
|
|
2169
|
+
}
|
|
2170
|
+
/** Compares 2 uint8array-s in kinda constant time. */
|
|
2171
|
+
function equalBytes(a, b) {
|
|
2172
|
+
if (a.length !== b.length) return false;
|
|
2173
|
+
let diff = 0;
|
|
2174
|
+
for (let i = 0; i < a.length; i++) diff |= a[i] ^ b[i];
|
|
2175
|
+
return diff === 0;
|
|
2176
|
+
}
|
|
2177
|
+
/**
|
|
2178
|
+
* Wraps a cipher: validates args, ensures encrypt() can only be called once.
|
|
2179
|
+
* @__NO_SIDE_EFFECTS__
|
|
2180
|
+
*/
|
|
2181
|
+
const wrapCipher = (params, constructor) => {
|
|
2182
|
+
function wrappedCipher(key, ...args) {
|
|
2183
|
+
abytes(key, void 0, "key");
|
|
2184
|
+
if (!isLE) throw new Error("Non little-endian hardware is not yet supported");
|
|
2185
|
+
if (params.nonceLength !== void 0) {
|
|
2186
|
+
const nonce = args[0];
|
|
2187
|
+
abytes(nonce, params.varSizeNonce ? void 0 : params.nonceLength, "nonce");
|
|
2188
|
+
}
|
|
2189
|
+
const tagl = params.tagLength;
|
|
2190
|
+
if (tagl && args[1] !== void 0) abytes(args[1], void 0, "AAD");
|
|
2191
|
+
const cipher = constructor(key, ...args);
|
|
2192
|
+
const checkOutput = (fnLength, output) => {
|
|
2193
|
+
if (output !== void 0) {
|
|
2194
|
+
if (fnLength !== 2) throw new Error("cipher output not supported");
|
|
2195
|
+
abytes(output, void 0, "output");
|
|
2196
|
+
}
|
|
2197
|
+
};
|
|
2198
|
+
let called = false;
|
|
2199
|
+
return {
|
|
2200
|
+
encrypt(data, output) {
|
|
2201
|
+
if (called) throw new Error("cannot encrypt() twice with same key + nonce");
|
|
2202
|
+
called = true;
|
|
2203
|
+
abytes(data);
|
|
2204
|
+
checkOutput(cipher.encrypt.length, output);
|
|
2205
|
+
return cipher.encrypt(data, output);
|
|
2206
|
+
},
|
|
2207
|
+
decrypt(data, output) {
|
|
2208
|
+
abytes(data);
|
|
2209
|
+
if (tagl && data.length < tagl) throw new Error("\"ciphertext\" expected length bigger than tagLength=" + tagl);
|
|
2210
|
+
checkOutput(cipher.decrypt.length, output);
|
|
2211
|
+
return cipher.decrypt(data, output);
|
|
2212
|
+
}
|
|
2213
|
+
};
|
|
2214
|
+
}
|
|
2215
|
+
Object.assign(wrappedCipher, params);
|
|
2216
|
+
return wrappedCipher;
|
|
2217
|
+
};
|
|
2218
|
+
/**
|
|
2219
|
+
* By default, returns u8a of length.
|
|
2220
|
+
* When out is available, it checks it for validity and uses it.
|
|
2221
|
+
*/
|
|
2222
|
+
function getOutput(expectedLength, out, onlyAligned = true) {
|
|
2223
|
+
if (out === void 0) return new Uint8Array(expectedLength);
|
|
2224
|
+
if (out.length !== expectedLength) throw new Error("\"output\" expected Uint8Array of length " + expectedLength + ", got: " + out.length);
|
|
2225
|
+
if (onlyAligned && !isAligned32$1(out)) throw new Error("invalid output, must be aligned");
|
|
2226
|
+
return out;
|
|
2227
|
+
}
|
|
2228
|
+
function u64Lengths(dataLength, aadLength, isLE$2) {
|
|
2229
|
+
abool(isLE$2);
|
|
2230
|
+
const num = new Uint8Array(16);
|
|
2231
|
+
const view = createView$1(num);
|
|
2232
|
+
view.setBigUint64(0, BigInt(aadLength), isLE$2);
|
|
2233
|
+
view.setBigUint64(8, BigInt(dataLength), isLE$2);
|
|
2234
|
+
return num;
|
|
2235
|
+
}
|
|
2236
|
+
function isAligned32$1(bytes) {
|
|
2237
|
+
return bytes.byteOffset % 4 === 0;
|
|
2238
|
+
}
|
|
2239
|
+
function copyBytes(bytes) {
|
|
2240
|
+
return Uint8Array.from(bytes);
|
|
2241
|
+
}
|
|
2242
|
+
/** Cryptographically secure PRNG. Uses internal OS-level `crypto.getRandomValues`. */
|
|
2243
|
+
function randomBytes(bytesLength = 32) {
|
|
2244
|
+
const cr = typeof globalThis === "object" ? globalThis.crypto : null;
|
|
2245
|
+
if (typeof cr?.getRandomValues !== "function") throw new Error("crypto.getRandomValues must be defined");
|
|
2246
|
+
return cr.getRandomValues(new Uint8Array(bytesLength));
|
|
2247
|
+
}
|
|
2248
|
+
/**
|
|
2249
|
+
* Uses CSPRG for nonce, nonce injected in ciphertext.
|
|
2250
|
+
* For `encrypt`, a `nonceBytes`-length buffer is fetched from CSPRNG and
|
|
2251
|
+
* prepended to encrypted ciphertext. For `decrypt`, first `nonceBytes` of ciphertext
|
|
2252
|
+
* are treated as nonce.
|
|
2253
|
+
*
|
|
2254
|
+
* NOTE: Under the same key, using random nonces (e.g. `managedNonce`) with AES-GCM and ChaCha
|
|
2255
|
+
* should be limited to `2**23` (8M) messages to get a collision chance of `2**-50`. Stretching to * `2**32` (4B) messages, chance would become `2**-33` - still negligible, but creeping up.
|
|
2256
|
+
* @example
|
|
2257
|
+
* const gcm = managedNonce(aes.gcm);
|
|
2258
|
+
* const ciphr = gcm(key).encrypt(data);
|
|
2259
|
+
* const plain = gcm(key).decrypt(ciph);
|
|
2260
|
+
*/
|
|
2261
|
+
function managedNonce(fn, randomBytes_ = randomBytes) {
|
|
2262
|
+
const { nonceLength } = fn;
|
|
2263
|
+
anumber$1(nonceLength);
|
|
2264
|
+
const addNonce = (nonce, ciphertext) => {
|
|
2265
|
+
const out = concatBytes(nonce, ciphertext);
|
|
2266
|
+
ciphertext.fill(0);
|
|
2267
|
+
return out;
|
|
2268
|
+
};
|
|
2269
|
+
return ((key, ...args) => ({
|
|
2270
|
+
encrypt(plaintext) {
|
|
2271
|
+
abytes(plaintext);
|
|
2272
|
+
const nonce = randomBytes_(nonceLength);
|
|
2273
|
+
const encrypted = fn(key, nonce, ...args).encrypt(plaintext);
|
|
2274
|
+
if (encrypted instanceof Promise) return encrypted.then((ct) => addNonce(nonce, ct));
|
|
2275
|
+
return addNonce(nonce, encrypted);
|
|
2276
|
+
},
|
|
2277
|
+
decrypt(ciphertext) {
|
|
2278
|
+
abytes(ciphertext);
|
|
2279
|
+
const nonce = ciphertext.subarray(0, nonceLength);
|
|
2280
|
+
const decrypted = ciphertext.subarray(nonceLength);
|
|
2281
|
+
return fn(key, nonce, ...args).decrypt(decrypted);
|
|
2282
|
+
}
|
|
2283
|
+
}));
|
|
2284
|
+
}
|
|
2285
|
+
|
|
2286
|
+
//#endregion
|
|
2287
|
+
//#region ../../node_modules/.pnpm/@noble+ciphers@2.0.1/node_modules/@noble/ciphers/_arx.js
|
|
2288
|
+
/**
|
|
2289
|
+
* Basic utils for ARX (add-rotate-xor) salsa and chacha ciphers.
|
|
2290
|
+
|
|
2291
|
+
RFC8439 requires multi-step cipher stream, where
|
|
2292
|
+
authKey starts with counter: 0, actual msg with counter: 1.
|
|
2293
|
+
|
|
2294
|
+
For this, we need a way to re-use nonce / counter:
|
|
2295
|
+
|
|
2296
|
+
const counter = new Uint8Array(4);
|
|
2297
|
+
chacha(..., counter, ...); // counter is now 1
|
|
2298
|
+
chacha(..., counter, ...); // counter is now 2
|
|
2299
|
+
|
|
2300
|
+
This is complicated:
|
|
2301
|
+
|
|
2302
|
+
- 32-bit counters are enough, no need for 64-bit: max ArrayBuffer size in JS is 4GB
|
|
2303
|
+
- Original papers don't allow mutating counters
|
|
2304
|
+
- Counter overflow is undefined [^1]
|
|
2305
|
+
- Idea A: allow providing (nonce | counter) instead of just nonce, re-use it
|
|
2306
|
+
- Caveat: Cannot be re-used through all cases:
|
|
2307
|
+
- * chacha has (counter | nonce)
|
|
2308
|
+
- * xchacha has (nonce16 | counter | nonce16)
|
|
2309
|
+
- Idea B: separate nonce / counter and provide separate API for counter re-use
|
|
2310
|
+
- Caveat: there are different counter sizes depending on an algorithm.
|
|
2311
|
+
- salsa & chacha also differ in structures of key & sigma:
|
|
2312
|
+
salsa20: s[0] | k(4) | s[1] | nonce(2) | cnt(2) | s[2] | k(4) | s[3]
|
|
2313
|
+
chacha: s(4) | k(8) | cnt(1) | nonce(3)
|
|
2314
|
+
chacha20orig: s(4) | k(8) | cnt(2) | nonce(2)
|
|
2315
|
+
- Idea C: helper method such as `setSalsaState(key, nonce, sigma, data)`
|
|
2316
|
+
- Caveat: we can't re-use counter array
|
|
2317
|
+
|
|
2318
|
+
xchacha [^2] uses the subkey and remaining 8 byte nonce with ChaCha20 as normal
|
|
2319
|
+
(prefixed by 4 NUL bytes, since [RFC8439] specifies a 12-byte nonce).
|
|
2320
|
+
|
|
2321
|
+
[^1]: https://mailarchive.ietf.org/arch/msg/cfrg/gsOnTJzcbgG6OqD8Sc0GO5aR_tU/
|
|
2322
|
+
[^2]: https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha#appendix-A.2
|
|
2323
|
+
|
|
2324
|
+
* @module
|
|
2325
|
+
*/
|
|
2326
|
+
const encodeStr = (str) => Uint8Array.from(str.split(""), (c) => c.charCodeAt(0));
|
|
2327
|
+
const sigma16 = encodeStr("expand 16-byte k");
|
|
2328
|
+
const sigma32 = encodeStr("expand 32-byte k");
|
|
2329
|
+
const sigma16_32 = u32$1(sigma16);
|
|
2330
|
+
const sigma32_32 = u32$1(sigma32);
|
|
2331
|
+
/** Rotate left. */
|
|
2332
|
+
function rotl$1(a, b) {
|
|
2333
|
+
return a << b | a >>> 32 - b;
|
|
2334
|
+
}
|
|
2335
|
+
function isAligned32(b) {
|
|
2336
|
+
return b.byteOffset % 4 === 0;
|
|
2337
|
+
}
|
|
2338
|
+
const BLOCK_LEN = 64;
|
|
2339
|
+
const BLOCK_LEN32 = 16;
|
|
2340
|
+
const MAX_COUNTER = 2 ** 32 - 1;
|
|
2341
|
+
const U32_EMPTY = Uint32Array.of();
|
|
2342
|
+
function runCipher(core, sigma, key, nonce, data, output, counter, rounds) {
|
|
2343
|
+
const len = data.length;
|
|
2344
|
+
const block = new Uint8Array(BLOCK_LEN);
|
|
2345
|
+
const b32 = u32$1(block);
|
|
2346
|
+
const isAligned = isAligned32(data) && isAligned32(output);
|
|
2347
|
+
const d32 = isAligned ? u32$1(data) : U32_EMPTY;
|
|
2348
|
+
const o32 = isAligned ? u32$1(output) : U32_EMPTY;
|
|
2349
|
+
for (let pos = 0; pos < len; counter++) {
|
|
2350
|
+
core(sigma, key, nonce, b32, counter, rounds);
|
|
2351
|
+
if (counter >= MAX_COUNTER) throw new Error("arx: counter overflow");
|
|
2352
|
+
const take = Math.min(BLOCK_LEN, len - pos);
|
|
2353
|
+
if (isAligned && take === BLOCK_LEN) {
|
|
2354
|
+
const pos32 = pos / 4;
|
|
2355
|
+
if (pos % 4 !== 0) throw new Error("arx: invalid block position");
|
|
2356
|
+
for (let j = 0, posj; j < BLOCK_LEN32; j++) {
|
|
2357
|
+
posj = pos32 + j;
|
|
2358
|
+
o32[posj] = d32[posj] ^ b32[j];
|
|
2359
|
+
}
|
|
2360
|
+
pos += BLOCK_LEN;
|
|
2361
|
+
continue;
|
|
2362
|
+
}
|
|
2363
|
+
for (let j = 0, posj; j < take; j++) {
|
|
2364
|
+
posj = pos + j;
|
|
2365
|
+
output[posj] = data[posj] ^ block[j];
|
|
2366
|
+
}
|
|
2367
|
+
pos += take;
|
|
2368
|
+
}
|
|
2369
|
+
}
|
|
2370
|
+
/** Creates ARX-like (ChaCha, Salsa) cipher stream from core function. */
|
|
2371
|
+
function createCipher(core, opts) {
|
|
2372
|
+
const { allowShortKeys, extendNonceFn, counterLength, counterRight, rounds } = checkOpts$1({
|
|
2373
|
+
allowShortKeys: false,
|
|
2374
|
+
counterLength: 8,
|
|
2375
|
+
counterRight: false,
|
|
2376
|
+
rounds: 20
|
|
2377
|
+
}, opts);
|
|
2378
|
+
if (typeof core !== "function") throw new Error("core must be a function");
|
|
2379
|
+
anumber$1(counterLength);
|
|
2380
|
+
anumber$1(rounds);
|
|
2381
|
+
abool(counterRight);
|
|
2382
|
+
abool(allowShortKeys);
|
|
2383
|
+
return (key, nonce, data, output, counter = 0) => {
|
|
2384
|
+
abytes(key, void 0, "key");
|
|
2385
|
+
abytes(nonce, void 0, "nonce");
|
|
2386
|
+
abytes(data, void 0, "data");
|
|
2387
|
+
const len = data.length;
|
|
2388
|
+
if (output === void 0) output = new Uint8Array(len);
|
|
2389
|
+
abytes(output, void 0, "output");
|
|
2390
|
+
anumber$1(counter);
|
|
2391
|
+
if (counter < 0 || counter >= MAX_COUNTER) throw new Error("arx: counter overflow");
|
|
2392
|
+
if (output.length < len) throw new Error(`arx: output (${output.length}) is shorter than data (${len})`);
|
|
2393
|
+
const toClean = [];
|
|
2394
|
+
let l = key.length;
|
|
2395
|
+
let k;
|
|
2396
|
+
let sigma;
|
|
2397
|
+
if (l === 32) {
|
|
2398
|
+
toClean.push(k = copyBytes(key));
|
|
2399
|
+
sigma = sigma32_32;
|
|
2400
|
+
} else if (l === 16 && allowShortKeys) {
|
|
2401
|
+
k = new Uint8Array(32);
|
|
2402
|
+
k.set(key);
|
|
2403
|
+
k.set(key, 16);
|
|
2404
|
+
sigma = sigma16_32;
|
|
2405
|
+
toClean.push(k);
|
|
2406
|
+
} else {
|
|
2407
|
+
abytes(key, 32, "arx key");
|
|
2408
|
+
throw new Error("invalid key size");
|
|
2409
|
+
}
|
|
2410
|
+
if (!isAligned32(nonce)) toClean.push(nonce = copyBytes(nonce));
|
|
2411
|
+
const k32 = u32$1(k);
|
|
2412
|
+
if (extendNonceFn) {
|
|
2413
|
+
if (nonce.length !== 24) throw new Error(`arx: extended nonce must be 24 bytes`);
|
|
2414
|
+
extendNonceFn(sigma, k32, u32$1(nonce.subarray(0, 16)), k32);
|
|
2415
|
+
nonce = nonce.subarray(16);
|
|
2416
|
+
}
|
|
2417
|
+
const nonceNcLen = 16 - counterLength;
|
|
2418
|
+
if (nonceNcLen !== nonce.length) throw new Error(`arx: nonce must be ${nonceNcLen} or 16 bytes`);
|
|
2419
|
+
if (nonceNcLen !== 12) {
|
|
2420
|
+
const nc = new Uint8Array(12);
|
|
2421
|
+
nc.set(nonce, counterRight ? 0 : 12 - nonce.length);
|
|
2422
|
+
nonce = nc;
|
|
2423
|
+
toClean.push(nonce);
|
|
2424
|
+
}
|
|
2425
|
+
const n32 = u32$1(nonce);
|
|
2426
|
+
runCipher(core, sigma, k32, n32, data, output, counter, rounds);
|
|
2427
|
+
clean$1(...toClean);
|
|
2428
|
+
return output;
|
|
2429
|
+
};
|
|
2430
|
+
}
|
|
2431
|
+
|
|
2432
|
+
//#endregion
|
|
2433
|
+
//#region ../../node_modules/.pnpm/@noble+ciphers@2.0.1/node_modules/@noble/ciphers/_poly1305.js
|
|
2434
|
+
/**
|
|
2435
|
+
* Poly1305 ([PDF](https://cr.yp.to/mac/poly1305-20050329.pdf),
|
|
2436
|
+
* [wiki](https://en.wikipedia.org/wiki/Poly1305))
|
|
2437
|
+
* is a fast and parallel secret-key message-authentication code suitable for
|
|
2438
|
+
* a wide variety of applications. It was standardized in
|
|
2439
|
+
* [RFC 8439](https://www.rfc-editor.org/rfc/rfc8439) and is now used in TLS 1.3.
|
|
2440
|
+
*
|
|
2441
|
+
* Polynomial MACs are not perfect for every situation:
|
|
2442
|
+
* they lack Random Key Robustness: the MAC can be forged, and can't be used in PAKE schemes.
|
|
2443
|
+
* See [invisible salamanders attack](https://keymaterial.net/2020/09/07/invisible-salamanders-in-aes-gcm-siv/).
|
|
2444
|
+
* To combat invisible salamanders, `hash(key)` can be included in ciphertext,
|
|
2445
|
+
* however, this would violate ciphertext indistinguishability:
|
|
2446
|
+
* an attacker would know which key was used - so `HKDF(key, i)`
|
|
2447
|
+
* could be used instead.
|
|
2448
|
+
*
|
|
2449
|
+
* Check out [original website](https://cr.yp.to/mac.html).
|
|
2450
|
+
* Based on Public Domain [poly1305-donna](https://github.com/floodyberry/poly1305-donna).
|
|
2451
|
+
* @module
|
|
2452
|
+
*/
|
|
2453
|
+
function u8to16(a, i) {
|
|
2454
|
+
return a[i++] & 255 | (a[i++] & 255) << 8;
|
|
2455
|
+
}
|
|
2456
|
+
/** Poly1305 class. Prefer poly1305() function instead. */
|
|
2457
|
+
var Poly1305 = class {
|
|
2458
|
+
blockLen = 16;
|
|
2459
|
+
outputLen = 16;
|
|
2460
|
+
buffer = new Uint8Array(16);
|
|
2461
|
+
r = new Uint16Array(10);
|
|
2462
|
+
h = new Uint16Array(10);
|
|
2463
|
+
pad = new Uint16Array(8);
|
|
2464
|
+
pos = 0;
|
|
2465
|
+
finished = false;
|
|
2466
|
+
constructor(key) {
|
|
2467
|
+
key = copyBytes(abytes(key, 32, "key"));
|
|
2468
|
+
const t0 = u8to16(key, 0);
|
|
2469
|
+
const t1 = u8to16(key, 2);
|
|
2470
|
+
const t2 = u8to16(key, 4);
|
|
2471
|
+
const t3 = u8to16(key, 6);
|
|
2472
|
+
const t4 = u8to16(key, 8);
|
|
2473
|
+
const t5 = u8to16(key, 10);
|
|
2474
|
+
const t6 = u8to16(key, 12);
|
|
2475
|
+
const t7 = u8to16(key, 14);
|
|
2476
|
+
this.r[0] = t0 & 8191;
|
|
2477
|
+
this.r[1] = (t0 >>> 13 | t1 << 3) & 8191;
|
|
2478
|
+
this.r[2] = (t1 >>> 10 | t2 << 6) & 7939;
|
|
2479
|
+
this.r[3] = (t2 >>> 7 | t3 << 9) & 8191;
|
|
2480
|
+
this.r[4] = (t3 >>> 4 | t4 << 12) & 255;
|
|
2481
|
+
this.r[5] = t4 >>> 1 & 8190;
|
|
2482
|
+
this.r[6] = (t4 >>> 14 | t5 << 2) & 8191;
|
|
2483
|
+
this.r[7] = (t5 >>> 11 | t6 << 5) & 8065;
|
|
2484
|
+
this.r[8] = (t6 >>> 8 | t7 << 8) & 8191;
|
|
2485
|
+
this.r[9] = t7 >>> 5 & 127;
|
|
2486
|
+
for (let i = 0; i < 8; i++) this.pad[i] = u8to16(key, 16 + 2 * i);
|
|
2487
|
+
}
|
|
2488
|
+
process(data, offset, isLast = false) {
|
|
2489
|
+
const hibit = isLast ? 0 : 2048;
|
|
2490
|
+
const { h, r } = this;
|
|
2491
|
+
const r0 = r[0];
|
|
2492
|
+
const r1 = r[1];
|
|
2493
|
+
const r2 = r[2];
|
|
2494
|
+
const r3 = r[3];
|
|
2495
|
+
const r4 = r[4];
|
|
2496
|
+
const r5 = r[5];
|
|
2497
|
+
const r6 = r[6];
|
|
2498
|
+
const r7 = r[7];
|
|
2499
|
+
const r8 = r[8];
|
|
2500
|
+
const r9 = r[9];
|
|
2501
|
+
const t0 = u8to16(data, offset + 0);
|
|
2502
|
+
const t1 = u8to16(data, offset + 2);
|
|
2503
|
+
const t2 = u8to16(data, offset + 4);
|
|
2504
|
+
const t3 = u8to16(data, offset + 6);
|
|
2505
|
+
const t4 = u8to16(data, offset + 8);
|
|
2506
|
+
const t5 = u8to16(data, offset + 10);
|
|
2507
|
+
const t6 = u8to16(data, offset + 12);
|
|
2508
|
+
const t7 = u8to16(data, offset + 14);
|
|
2509
|
+
let h0 = h[0] + (t0 & 8191);
|
|
2510
|
+
let h1 = h[1] + ((t0 >>> 13 | t1 << 3) & 8191);
|
|
2511
|
+
let h2 = h[2] + ((t1 >>> 10 | t2 << 6) & 8191);
|
|
2512
|
+
let h3 = h[3] + ((t2 >>> 7 | t3 << 9) & 8191);
|
|
2513
|
+
let h4 = h[4] + ((t3 >>> 4 | t4 << 12) & 8191);
|
|
2514
|
+
let h5 = h[5] + (t4 >>> 1 & 8191);
|
|
2515
|
+
let h6 = h[6] + ((t4 >>> 14 | t5 << 2) & 8191);
|
|
2516
|
+
let h7 = h[7] + ((t5 >>> 11 | t6 << 5) & 8191);
|
|
2517
|
+
let h8 = h[8] + ((t6 >>> 8 | t7 << 8) & 8191);
|
|
2518
|
+
let h9 = h[9] + (t7 >>> 5 | hibit);
|
|
2519
|
+
let c = 0;
|
|
2520
|
+
let d0 = c + h0 * r0 + h1 * (5 * r9) + h2 * (5 * r8) + h3 * (5 * r7) + h4 * (5 * r6);
|
|
2521
|
+
c = d0 >>> 13;
|
|
2522
|
+
d0 &= 8191;
|
|
2523
|
+
d0 += h5 * (5 * r5) + h6 * (5 * r4) + h7 * (5 * r3) + h8 * (5 * r2) + h9 * (5 * r1);
|
|
2524
|
+
c += d0 >>> 13;
|
|
2525
|
+
d0 &= 8191;
|
|
2526
|
+
let d1 = c + h0 * r1 + h1 * r0 + h2 * (5 * r9) + h3 * (5 * r8) + h4 * (5 * r7);
|
|
2527
|
+
c = d1 >>> 13;
|
|
2528
|
+
d1 &= 8191;
|
|
2529
|
+
d1 += h5 * (5 * r6) + h6 * (5 * r5) + h7 * (5 * r4) + h8 * (5 * r3) + h9 * (5 * r2);
|
|
2530
|
+
c += d1 >>> 13;
|
|
2531
|
+
d1 &= 8191;
|
|
2532
|
+
let d2 = c + h0 * r2 + h1 * r1 + h2 * r0 + h3 * (5 * r9) + h4 * (5 * r8);
|
|
2533
|
+
c = d2 >>> 13;
|
|
2534
|
+
d2 &= 8191;
|
|
2535
|
+
d2 += h5 * (5 * r7) + h6 * (5 * r6) + h7 * (5 * r5) + h8 * (5 * r4) + h9 * (5 * r3);
|
|
2536
|
+
c += d2 >>> 13;
|
|
2537
|
+
d2 &= 8191;
|
|
2538
|
+
let d3 = c + h0 * r3 + h1 * r2 + h2 * r1 + h3 * r0 + h4 * (5 * r9);
|
|
2539
|
+
c = d3 >>> 13;
|
|
2540
|
+
d3 &= 8191;
|
|
2541
|
+
d3 += h5 * (5 * r8) + h6 * (5 * r7) + h7 * (5 * r6) + h8 * (5 * r5) + h9 * (5 * r4);
|
|
2542
|
+
c += d3 >>> 13;
|
|
2543
|
+
d3 &= 8191;
|
|
2544
|
+
let d4 = c + h0 * r4 + h1 * r3 + h2 * r2 + h3 * r1 + h4 * r0;
|
|
2545
|
+
c = d4 >>> 13;
|
|
2546
|
+
d4 &= 8191;
|
|
2547
|
+
d4 += h5 * (5 * r9) + h6 * (5 * r8) + h7 * (5 * r7) + h8 * (5 * r6) + h9 * (5 * r5);
|
|
2548
|
+
c += d4 >>> 13;
|
|
2549
|
+
d4 &= 8191;
|
|
2550
|
+
let d5 = c + h0 * r5 + h1 * r4 + h2 * r3 + h3 * r2 + h4 * r1;
|
|
2551
|
+
c = d5 >>> 13;
|
|
2552
|
+
d5 &= 8191;
|
|
2553
|
+
d5 += h5 * r0 + h6 * (5 * r9) + h7 * (5 * r8) + h8 * (5 * r7) + h9 * (5 * r6);
|
|
2554
|
+
c += d5 >>> 13;
|
|
2555
|
+
d5 &= 8191;
|
|
2556
|
+
let d6 = c + h0 * r6 + h1 * r5 + h2 * r4 + h3 * r3 + h4 * r2;
|
|
2557
|
+
c = d6 >>> 13;
|
|
2558
|
+
d6 &= 8191;
|
|
2559
|
+
d6 += h5 * r1 + h6 * r0 + h7 * (5 * r9) + h8 * (5 * r8) + h9 * (5 * r7);
|
|
2560
|
+
c += d6 >>> 13;
|
|
2561
|
+
d6 &= 8191;
|
|
2562
|
+
let d7 = c + h0 * r7 + h1 * r6 + h2 * r5 + h3 * r4 + h4 * r3;
|
|
2563
|
+
c = d7 >>> 13;
|
|
2564
|
+
d7 &= 8191;
|
|
2565
|
+
d7 += h5 * r2 + h6 * r1 + h7 * r0 + h8 * (5 * r9) + h9 * (5 * r8);
|
|
2566
|
+
c += d7 >>> 13;
|
|
2567
|
+
d7 &= 8191;
|
|
2568
|
+
let d8 = c + h0 * r8 + h1 * r7 + h2 * r6 + h3 * r5 + h4 * r4;
|
|
2569
|
+
c = d8 >>> 13;
|
|
2570
|
+
d8 &= 8191;
|
|
2571
|
+
d8 += h5 * r3 + h6 * r2 + h7 * r1 + h8 * r0 + h9 * (5 * r9);
|
|
2572
|
+
c += d8 >>> 13;
|
|
2573
|
+
d8 &= 8191;
|
|
2574
|
+
let d9 = c + h0 * r9 + h1 * r8 + h2 * r7 + h3 * r6 + h4 * r5;
|
|
2575
|
+
c = d9 >>> 13;
|
|
2576
|
+
d9 &= 8191;
|
|
2577
|
+
d9 += h5 * r4 + h6 * r3 + h7 * r2 + h8 * r1 + h9 * r0;
|
|
2578
|
+
c += d9 >>> 13;
|
|
2579
|
+
d9 &= 8191;
|
|
2580
|
+
c = (c << 2) + c | 0;
|
|
2581
|
+
c = c + d0 | 0;
|
|
2582
|
+
d0 = c & 8191;
|
|
2583
|
+
c = c >>> 13;
|
|
2584
|
+
d1 += c;
|
|
2585
|
+
h[0] = d0;
|
|
2586
|
+
h[1] = d1;
|
|
2587
|
+
h[2] = d2;
|
|
2588
|
+
h[3] = d3;
|
|
2589
|
+
h[4] = d4;
|
|
2590
|
+
h[5] = d5;
|
|
2591
|
+
h[6] = d6;
|
|
2592
|
+
h[7] = d7;
|
|
2593
|
+
h[8] = d8;
|
|
2594
|
+
h[9] = d9;
|
|
2595
|
+
}
|
|
2596
|
+
finalize() {
|
|
2597
|
+
const { h, pad } = this;
|
|
2598
|
+
const g = new Uint16Array(10);
|
|
2599
|
+
let c = h[1] >>> 13;
|
|
2600
|
+
h[1] &= 8191;
|
|
2601
|
+
for (let i = 2; i < 10; i++) {
|
|
2602
|
+
h[i] += c;
|
|
2603
|
+
c = h[i] >>> 13;
|
|
2604
|
+
h[i] &= 8191;
|
|
2605
|
+
}
|
|
2606
|
+
h[0] += c * 5;
|
|
2607
|
+
c = h[0] >>> 13;
|
|
2608
|
+
h[0] &= 8191;
|
|
2609
|
+
h[1] += c;
|
|
2610
|
+
c = h[1] >>> 13;
|
|
2611
|
+
h[1] &= 8191;
|
|
2612
|
+
h[2] += c;
|
|
2613
|
+
g[0] = h[0] + 5;
|
|
2614
|
+
c = g[0] >>> 13;
|
|
2615
|
+
g[0] &= 8191;
|
|
2616
|
+
for (let i = 1; i < 10; i++) {
|
|
2617
|
+
g[i] = h[i] + c;
|
|
2618
|
+
c = g[i] >>> 13;
|
|
2619
|
+
g[i] &= 8191;
|
|
2620
|
+
}
|
|
2621
|
+
g[9] -= 8192;
|
|
2622
|
+
let mask = (c ^ 1) - 1;
|
|
2623
|
+
for (let i = 0; i < 10; i++) g[i] &= mask;
|
|
2624
|
+
mask = ~mask;
|
|
2625
|
+
for (let i = 0; i < 10; i++) h[i] = h[i] & mask | g[i];
|
|
2626
|
+
h[0] = (h[0] | h[1] << 13) & 65535;
|
|
2627
|
+
h[1] = (h[1] >>> 3 | h[2] << 10) & 65535;
|
|
2628
|
+
h[2] = (h[2] >>> 6 | h[3] << 7) & 65535;
|
|
2629
|
+
h[3] = (h[3] >>> 9 | h[4] << 4) & 65535;
|
|
2630
|
+
h[4] = (h[4] >>> 12 | h[5] << 1 | h[6] << 14) & 65535;
|
|
2631
|
+
h[5] = (h[6] >>> 2 | h[7] << 11) & 65535;
|
|
2632
|
+
h[6] = (h[7] >>> 5 | h[8] << 8) & 65535;
|
|
2633
|
+
h[7] = (h[8] >>> 8 | h[9] << 5) & 65535;
|
|
2634
|
+
let f = h[0] + pad[0];
|
|
2635
|
+
h[0] = f & 65535;
|
|
2636
|
+
for (let i = 1; i < 8; i++) {
|
|
2637
|
+
f = (h[i] + pad[i] | 0) + (f >>> 16) | 0;
|
|
2638
|
+
h[i] = f & 65535;
|
|
2639
|
+
}
|
|
2640
|
+
clean$1(g);
|
|
2641
|
+
}
|
|
2642
|
+
update(data) {
|
|
2643
|
+
aexists(this);
|
|
2644
|
+
abytes(data);
|
|
2645
|
+
data = copyBytes(data);
|
|
2646
|
+
const { buffer, blockLen } = this;
|
|
2647
|
+
const len = data.length;
|
|
2648
|
+
for (let pos = 0; pos < len;) {
|
|
2649
|
+
const take = Math.min(blockLen - this.pos, len - pos);
|
|
2650
|
+
if (take === blockLen) {
|
|
2651
|
+
for (; blockLen <= len - pos; pos += blockLen) this.process(data, pos);
|
|
2652
|
+
continue;
|
|
2653
|
+
}
|
|
2654
|
+
buffer.set(data.subarray(pos, pos + take), this.pos);
|
|
2655
|
+
this.pos += take;
|
|
2656
|
+
pos += take;
|
|
2657
|
+
if (this.pos === blockLen) {
|
|
2658
|
+
this.process(buffer, 0, false);
|
|
2659
|
+
this.pos = 0;
|
|
2660
|
+
}
|
|
2661
|
+
}
|
|
2662
|
+
return this;
|
|
2663
|
+
}
|
|
2664
|
+
destroy() {
|
|
2665
|
+
clean$1(this.h, this.r, this.buffer, this.pad);
|
|
2666
|
+
}
|
|
2667
|
+
digestInto(out) {
|
|
2668
|
+
aexists(this);
|
|
2669
|
+
aoutput(out, this);
|
|
2670
|
+
this.finished = true;
|
|
2671
|
+
const { buffer, h } = this;
|
|
2672
|
+
let { pos } = this;
|
|
2673
|
+
if (pos) {
|
|
2674
|
+
buffer[pos++] = 1;
|
|
2675
|
+
for (; pos < 16; pos++) buffer[pos] = 0;
|
|
2676
|
+
this.process(buffer, 0, true);
|
|
2677
|
+
}
|
|
2678
|
+
this.finalize();
|
|
2679
|
+
let opos = 0;
|
|
2680
|
+
for (let i = 0; i < 8; i++) {
|
|
2681
|
+
out[opos++] = h[i] >>> 0;
|
|
2682
|
+
out[opos++] = h[i] >>> 8;
|
|
2683
|
+
}
|
|
2684
|
+
return out;
|
|
2685
|
+
}
|
|
2686
|
+
digest() {
|
|
2687
|
+
const { buffer, outputLen } = this;
|
|
2688
|
+
this.digestInto(buffer);
|
|
2689
|
+
const res = buffer.slice(0, outputLen);
|
|
2690
|
+
this.destroy();
|
|
2691
|
+
return res;
|
|
2692
|
+
}
|
|
2693
|
+
};
|
|
2694
|
+
function wrapConstructorWithKey(hashCons) {
|
|
2695
|
+
const hashC = (msg, key) => hashCons(key).update(msg).digest();
|
|
2696
|
+
const tmp = hashCons(new Uint8Array(32));
|
|
2697
|
+
hashC.outputLen = tmp.outputLen;
|
|
2698
|
+
hashC.blockLen = tmp.blockLen;
|
|
2699
|
+
hashC.create = (key) => hashCons(key);
|
|
2700
|
+
return hashC;
|
|
2701
|
+
}
|
|
2702
|
+
/** Poly1305 MAC from RFC 8439. */
|
|
2703
|
+
const poly1305 = (() => wrapConstructorWithKey((key) => new Poly1305(key)))();
|
|
2704
|
+
|
|
2705
|
+
//#endregion
|
|
2706
|
+
//#region ../../node_modules/.pnpm/@noble+ciphers@2.0.1/node_modules/@noble/ciphers/chacha.js
|
|
2707
|
+
/**
|
|
2708
|
+
* ChaCha stream cipher, released
|
|
2709
|
+
* in 2008. Developed after Salsa20, ChaCha aims to increase diffusion per round.
|
|
2710
|
+
* It was standardized in [RFC 8439](https://www.rfc-editor.org/rfc/rfc8439) and
|
|
2711
|
+
* is now used in TLS 1.3.
|
|
2712
|
+
*
|
|
2713
|
+
* [XChaCha20](https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha)
|
|
2714
|
+
* extended-nonce variant is also provided. Similar to XSalsa, it's safe to use with
|
|
2715
|
+
* randomly-generated nonces.
|
|
2716
|
+
*
|
|
2717
|
+
* Check out [PDF](http://cr.yp.to/chacha/chacha-20080128.pdf) and
|
|
2718
|
+
* [wiki](https://en.wikipedia.org/wiki/Salsa20) and
|
|
2719
|
+
* [website](https://cr.yp.to/chacha.html).
|
|
2720
|
+
*
|
|
2721
|
+
* @module
|
|
2722
|
+
*/
|
|
2723
|
+
/** Identical to `chachaCore_small`. Unused. */
|
|
2724
|
+
function chachaCore(s, k, n, out, cnt, rounds = 20) {
|
|
2725
|
+
let y00 = s[0], y01 = s[1], y02 = s[2], y03 = s[3], y04 = k[0], y05 = k[1], y06 = k[2], y07 = k[3], y08 = k[4], y09 = k[5], y10 = k[6], y11 = k[7], y12 = cnt, y13 = n[0], y14 = n[1], y15 = n[2];
|
|
2726
|
+
let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15;
|
|
2727
|
+
for (let r = 0; r < rounds; r += 2) {
|
|
2728
|
+
x00 = x00 + x04 | 0;
|
|
2729
|
+
x12 = rotl$1(x12 ^ x00, 16);
|
|
2730
|
+
x08 = x08 + x12 | 0;
|
|
2731
|
+
x04 = rotl$1(x04 ^ x08, 12);
|
|
2732
|
+
x00 = x00 + x04 | 0;
|
|
2733
|
+
x12 = rotl$1(x12 ^ x00, 8);
|
|
2734
|
+
x08 = x08 + x12 | 0;
|
|
2735
|
+
x04 = rotl$1(x04 ^ x08, 7);
|
|
2736
|
+
x01 = x01 + x05 | 0;
|
|
2737
|
+
x13 = rotl$1(x13 ^ x01, 16);
|
|
2738
|
+
x09 = x09 + x13 | 0;
|
|
2739
|
+
x05 = rotl$1(x05 ^ x09, 12);
|
|
2740
|
+
x01 = x01 + x05 | 0;
|
|
2741
|
+
x13 = rotl$1(x13 ^ x01, 8);
|
|
2742
|
+
x09 = x09 + x13 | 0;
|
|
2743
|
+
x05 = rotl$1(x05 ^ x09, 7);
|
|
2744
|
+
x02 = x02 + x06 | 0;
|
|
2745
|
+
x14 = rotl$1(x14 ^ x02, 16);
|
|
2746
|
+
x10 = x10 + x14 | 0;
|
|
2747
|
+
x06 = rotl$1(x06 ^ x10, 12);
|
|
2748
|
+
x02 = x02 + x06 | 0;
|
|
2749
|
+
x14 = rotl$1(x14 ^ x02, 8);
|
|
2750
|
+
x10 = x10 + x14 | 0;
|
|
2751
|
+
x06 = rotl$1(x06 ^ x10, 7);
|
|
2752
|
+
x03 = x03 + x07 | 0;
|
|
2753
|
+
x15 = rotl$1(x15 ^ x03, 16);
|
|
2754
|
+
x11 = x11 + x15 | 0;
|
|
2755
|
+
x07 = rotl$1(x07 ^ x11, 12);
|
|
2756
|
+
x03 = x03 + x07 | 0;
|
|
2757
|
+
x15 = rotl$1(x15 ^ x03, 8);
|
|
2758
|
+
x11 = x11 + x15 | 0;
|
|
2759
|
+
x07 = rotl$1(x07 ^ x11, 7);
|
|
2760
|
+
x00 = x00 + x05 | 0;
|
|
2761
|
+
x15 = rotl$1(x15 ^ x00, 16);
|
|
2762
|
+
x10 = x10 + x15 | 0;
|
|
2763
|
+
x05 = rotl$1(x05 ^ x10, 12);
|
|
2764
|
+
x00 = x00 + x05 | 0;
|
|
2765
|
+
x15 = rotl$1(x15 ^ x00, 8);
|
|
2766
|
+
x10 = x10 + x15 | 0;
|
|
2767
|
+
x05 = rotl$1(x05 ^ x10, 7);
|
|
2768
|
+
x01 = x01 + x06 | 0;
|
|
2769
|
+
x12 = rotl$1(x12 ^ x01, 16);
|
|
2770
|
+
x11 = x11 + x12 | 0;
|
|
2771
|
+
x06 = rotl$1(x06 ^ x11, 12);
|
|
2772
|
+
x01 = x01 + x06 | 0;
|
|
2773
|
+
x12 = rotl$1(x12 ^ x01, 8);
|
|
2774
|
+
x11 = x11 + x12 | 0;
|
|
2775
|
+
x06 = rotl$1(x06 ^ x11, 7);
|
|
2776
|
+
x02 = x02 + x07 | 0;
|
|
2777
|
+
x13 = rotl$1(x13 ^ x02, 16);
|
|
2778
|
+
x08 = x08 + x13 | 0;
|
|
2779
|
+
x07 = rotl$1(x07 ^ x08, 12);
|
|
2780
|
+
x02 = x02 + x07 | 0;
|
|
2781
|
+
x13 = rotl$1(x13 ^ x02, 8);
|
|
2782
|
+
x08 = x08 + x13 | 0;
|
|
2783
|
+
x07 = rotl$1(x07 ^ x08, 7);
|
|
2784
|
+
x03 = x03 + x04 | 0;
|
|
2785
|
+
x14 = rotl$1(x14 ^ x03, 16);
|
|
2786
|
+
x09 = x09 + x14 | 0;
|
|
2787
|
+
x04 = rotl$1(x04 ^ x09, 12);
|
|
2788
|
+
x03 = x03 + x04 | 0;
|
|
2789
|
+
x14 = rotl$1(x14 ^ x03, 8);
|
|
2790
|
+
x09 = x09 + x14 | 0;
|
|
2791
|
+
x04 = rotl$1(x04 ^ x09, 7);
|
|
2792
|
+
}
|
|
2793
|
+
let oi = 0;
|
|
2794
|
+
out[oi++] = y00 + x00 | 0;
|
|
2795
|
+
out[oi++] = y01 + x01 | 0;
|
|
2796
|
+
out[oi++] = y02 + x02 | 0;
|
|
2797
|
+
out[oi++] = y03 + x03 | 0;
|
|
2798
|
+
out[oi++] = y04 + x04 | 0;
|
|
2799
|
+
out[oi++] = y05 + x05 | 0;
|
|
2800
|
+
out[oi++] = y06 + x06 | 0;
|
|
2801
|
+
out[oi++] = y07 + x07 | 0;
|
|
2802
|
+
out[oi++] = y08 + x08 | 0;
|
|
2803
|
+
out[oi++] = y09 + x09 | 0;
|
|
2804
|
+
out[oi++] = y10 + x10 | 0;
|
|
2805
|
+
out[oi++] = y11 + x11 | 0;
|
|
2806
|
+
out[oi++] = y12 + x12 | 0;
|
|
2807
|
+
out[oi++] = y13 + x13 | 0;
|
|
2808
|
+
out[oi++] = y14 + x14 | 0;
|
|
2809
|
+
out[oi++] = y15 + x15 | 0;
|
|
2810
|
+
}
|
|
2811
|
+
/**
|
|
2812
|
+
* hchacha hashes key and nonce into key' and nonce' for xchacha20.
|
|
2813
|
+
* Identical to `hchacha_small`.
|
|
2814
|
+
* Need to find a way to merge it with `chachaCore` without 25% performance hit.
|
|
2815
|
+
*/
|
|
2816
|
+
function hchacha(s, k, i, out) {
|
|
2817
|
+
let x00 = s[0], x01 = s[1], x02 = s[2], x03 = s[3], x04 = k[0], x05 = k[1], x06 = k[2], x07 = k[3], x08 = k[4], x09 = k[5], x10 = k[6], x11 = k[7], x12 = i[0], x13 = i[1], x14 = i[2], x15 = i[3];
|
|
2818
|
+
for (let r = 0; r < 20; r += 2) {
|
|
2819
|
+
x00 = x00 + x04 | 0;
|
|
2820
|
+
x12 = rotl$1(x12 ^ x00, 16);
|
|
2821
|
+
x08 = x08 + x12 | 0;
|
|
2822
|
+
x04 = rotl$1(x04 ^ x08, 12);
|
|
2823
|
+
x00 = x00 + x04 | 0;
|
|
2824
|
+
x12 = rotl$1(x12 ^ x00, 8);
|
|
2825
|
+
x08 = x08 + x12 | 0;
|
|
2826
|
+
x04 = rotl$1(x04 ^ x08, 7);
|
|
2827
|
+
x01 = x01 + x05 | 0;
|
|
2828
|
+
x13 = rotl$1(x13 ^ x01, 16);
|
|
2829
|
+
x09 = x09 + x13 | 0;
|
|
2830
|
+
x05 = rotl$1(x05 ^ x09, 12);
|
|
2831
|
+
x01 = x01 + x05 | 0;
|
|
2832
|
+
x13 = rotl$1(x13 ^ x01, 8);
|
|
2833
|
+
x09 = x09 + x13 | 0;
|
|
2834
|
+
x05 = rotl$1(x05 ^ x09, 7);
|
|
2835
|
+
x02 = x02 + x06 | 0;
|
|
2836
|
+
x14 = rotl$1(x14 ^ x02, 16);
|
|
2837
|
+
x10 = x10 + x14 | 0;
|
|
2838
|
+
x06 = rotl$1(x06 ^ x10, 12);
|
|
2839
|
+
x02 = x02 + x06 | 0;
|
|
2840
|
+
x14 = rotl$1(x14 ^ x02, 8);
|
|
2841
|
+
x10 = x10 + x14 | 0;
|
|
2842
|
+
x06 = rotl$1(x06 ^ x10, 7);
|
|
2843
|
+
x03 = x03 + x07 | 0;
|
|
2844
|
+
x15 = rotl$1(x15 ^ x03, 16);
|
|
2845
|
+
x11 = x11 + x15 | 0;
|
|
2846
|
+
x07 = rotl$1(x07 ^ x11, 12);
|
|
2847
|
+
x03 = x03 + x07 | 0;
|
|
2848
|
+
x15 = rotl$1(x15 ^ x03, 8);
|
|
2849
|
+
x11 = x11 + x15 | 0;
|
|
2850
|
+
x07 = rotl$1(x07 ^ x11, 7);
|
|
2851
|
+
x00 = x00 + x05 | 0;
|
|
2852
|
+
x15 = rotl$1(x15 ^ x00, 16);
|
|
2853
|
+
x10 = x10 + x15 | 0;
|
|
2854
|
+
x05 = rotl$1(x05 ^ x10, 12);
|
|
2855
|
+
x00 = x00 + x05 | 0;
|
|
2856
|
+
x15 = rotl$1(x15 ^ x00, 8);
|
|
2857
|
+
x10 = x10 + x15 | 0;
|
|
2858
|
+
x05 = rotl$1(x05 ^ x10, 7);
|
|
2859
|
+
x01 = x01 + x06 | 0;
|
|
2860
|
+
x12 = rotl$1(x12 ^ x01, 16);
|
|
2861
|
+
x11 = x11 + x12 | 0;
|
|
2862
|
+
x06 = rotl$1(x06 ^ x11, 12);
|
|
2863
|
+
x01 = x01 + x06 | 0;
|
|
2864
|
+
x12 = rotl$1(x12 ^ x01, 8);
|
|
2865
|
+
x11 = x11 + x12 | 0;
|
|
2866
|
+
x06 = rotl$1(x06 ^ x11, 7);
|
|
2867
|
+
x02 = x02 + x07 | 0;
|
|
2868
|
+
x13 = rotl$1(x13 ^ x02, 16);
|
|
2869
|
+
x08 = x08 + x13 | 0;
|
|
2870
|
+
x07 = rotl$1(x07 ^ x08, 12);
|
|
2871
|
+
x02 = x02 + x07 | 0;
|
|
2872
|
+
x13 = rotl$1(x13 ^ x02, 8);
|
|
2873
|
+
x08 = x08 + x13 | 0;
|
|
2874
|
+
x07 = rotl$1(x07 ^ x08, 7);
|
|
2875
|
+
x03 = x03 + x04 | 0;
|
|
2876
|
+
x14 = rotl$1(x14 ^ x03, 16);
|
|
2877
|
+
x09 = x09 + x14 | 0;
|
|
2878
|
+
x04 = rotl$1(x04 ^ x09, 12);
|
|
2879
|
+
x03 = x03 + x04 | 0;
|
|
2880
|
+
x14 = rotl$1(x14 ^ x03, 8);
|
|
2881
|
+
x09 = x09 + x14 | 0;
|
|
2882
|
+
x04 = rotl$1(x04 ^ x09, 7);
|
|
2883
|
+
}
|
|
2884
|
+
let oi = 0;
|
|
2885
|
+
out[oi++] = x00;
|
|
2886
|
+
out[oi++] = x01;
|
|
2887
|
+
out[oi++] = x02;
|
|
2888
|
+
out[oi++] = x03;
|
|
2889
|
+
out[oi++] = x12;
|
|
2890
|
+
out[oi++] = x13;
|
|
2891
|
+
out[oi++] = x14;
|
|
2892
|
+
out[oi++] = x15;
|
|
2893
|
+
}
|
|
2894
|
+
/**
|
|
2895
|
+
* ChaCha stream cipher. Conforms to RFC 8439 (IETF, TLS). 12-byte nonce, 4-byte counter.
|
|
2896
|
+
* With smaller nonce, it's not safe to make it random (CSPRNG), due to collision chance.
|
|
2897
|
+
*/
|
|
2898
|
+
const chacha20 = /* @__PURE__ */ createCipher(chachaCore, {
|
|
2899
|
+
counterRight: false,
|
|
2900
|
+
counterLength: 4,
|
|
2901
|
+
allowShortKeys: false
|
|
2902
|
+
});
|
|
2903
|
+
/**
|
|
2904
|
+
* XChaCha eXtended-nonce ChaCha. With 24-byte nonce, it's safe to make it random (CSPRNG).
|
|
2905
|
+
* See [IRTF draft](https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha).
|
|
2906
|
+
*/
|
|
2907
|
+
const xchacha20 = /* @__PURE__ */ createCipher(chachaCore, {
|
|
2908
|
+
counterRight: false,
|
|
2909
|
+
counterLength: 8,
|
|
2910
|
+
extendNonceFn: hchacha,
|
|
2911
|
+
allowShortKeys: false
|
|
2912
|
+
});
|
|
2913
|
+
const ZEROS16 = /* @__PURE__ */ new Uint8Array(16);
|
|
2914
|
+
const updatePadded = (h, msg) => {
|
|
2915
|
+
h.update(msg);
|
|
2916
|
+
const leftover = msg.length % 16;
|
|
2917
|
+
if (leftover) h.update(ZEROS16.subarray(leftover));
|
|
2918
|
+
};
|
|
2919
|
+
const ZEROS32 = /* @__PURE__ */ new Uint8Array(32);
|
|
2920
|
+
function computeTag(fn, key, nonce, ciphertext, AAD) {
|
|
2921
|
+
if (AAD !== void 0) abytes(AAD, void 0, "AAD");
|
|
2922
|
+
const authKey = fn(key, nonce, ZEROS32);
|
|
2923
|
+
const lengths = u64Lengths(ciphertext.length, AAD ? AAD.length : 0, true);
|
|
2924
|
+
const h = poly1305.create(authKey);
|
|
2925
|
+
if (AAD) updatePadded(h, AAD);
|
|
2926
|
+
updatePadded(h, ciphertext);
|
|
2927
|
+
h.update(lengths);
|
|
2928
|
+
const res = h.digest();
|
|
2929
|
+
clean$1(authKey, lengths);
|
|
2930
|
+
return res;
|
|
2931
|
+
}
|
|
2932
|
+
/**
|
|
2933
|
+
* AEAD algorithm from RFC 8439.
|
|
2934
|
+
* Salsa20 and chacha (RFC 8439) use poly1305 differently.
|
|
2935
|
+
* We could have composed them, but it's hard because of authKey:
|
|
2936
|
+
* In salsa20, authKey changes position in salsa stream.
|
|
2937
|
+
* In chacha, authKey can't be computed inside computeTag, it modifies the counter.
|
|
2938
|
+
*/
|
|
2939
|
+
const _poly1305_aead = (xorStream) => (key, nonce, AAD) => {
|
|
2940
|
+
const tagLength = 16;
|
|
2941
|
+
return {
|
|
2942
|
+
encrypt(plaintext, output) {
|
|
2943
|
+
const plength = plaintext.length;
|
|
2944
|
+
output = getOutput(plength + tagLength, output, false);
|
|
2945
|
+
output.set(plaintext);
|
|
2946
|
+
const oPlain = output.subarray(0, -tagLength);
|
|
2947
|
+
xorStream(key, nonce, oPlain, oPlain, 1);
|
|
2948
|
+
const tag = computeTag(xorStream, key, nonce, oPlain, AAD);
|
|
2949
|
+
output.set(tag, plength);
|
|
2950
|
+
clean$1(tag);
|
|
2951
|
+
return output;
|
|
2952
|
+
},
|
|
2953
|
+
decrypt(ciphertext, output) {
|
|
2954
|
+
output = getOutput(ciphertext.length - tagLength, output, false);
|
|
2955
|
+
const data = ciphertext.subarray(0, -tagLength);
|
|
2956
|
+
const passedTag = ciphertext.subarray(-tagLength);
|
|
2957
|
+
const tag = computeTag(xorStream, key, nonce, data, AAD);
|
|
2958
|
+
if (!equalBytes(passedTag, tag)) throw new Error("invalid tag");
|
|
2959
|
+
output.set(ciphertext.subarray(0, -tagLength));
|
|
2960
|
+
xorStream(key, nonce, output, output, 1);
|
|
2961
|
+
clean$1(tag);
|
|
2962
|
+
return output;
|
|
2963
|
+
}
|
|
2964
|
+
};
|
|
2965
|
+
};
|
|
2966
|
+
/**
|
|
2967
|
+
* ChaCha20-Poly1305 from RFC 8439.
|
|
2968
|
+
*
|
|
2969
|
+
* Unsafe to use random nonces under the same key, due to collision chance.
|
|
2970
|
+
* Prefer XChaCha instead.
|
|
2971
|
+
*/
|
|
2972
|
+
const chacha20poly1305 = /* @__PURE__ */ wrapCipher({
|
|
2973
|
+
blockSize: 64,
|
|
2974
|
+
nonceLength: 12,
|
|
2975
|
+
tagLength: 16
|
|
2976
|
+
}, _poly1305_aead(chacha20));
|
|
2977
|
+
/**
|
|
2978
|
+
* XChaCha20-Poly1305 extended-nonce chacha.
|
|
2979
|
+
*
|
|
2980
|
+
* Can be safely used with random nonces (CSPRNG).
|
|
2981
|
+
* See [IRTF draft](https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-xchacha).
|
|
2982
|
+
*/
|
|
2983
|
+
const xchacha20poly1305 = /* @__PURE__ */ wrapCipher({
|
|
2984
|
+
blockSize: 64,
|
|
2985
|
+
nonceLength: 24,
|
|
2986
|
+
tagLength: 16
|
|
2987
|
+
}, _poly1305_aead(xchacha20));
|
|
2988
|
+
|
|
2989
|
+
//#endregion
|
|
2990
|
+
//#region ../../node_modules/.pnpm/@noble+hashes@2.0.1/node_modules/@noble/hashes/pbkdf2.js
|
|
2991
|
+
/**
|
|
2992
|
+
* PBKDF (RFC 2898). Can be used to create a key from password and salt.
|
|
2993
|
+
* @module
|
|
2994
|
+
*/
|
|
2995
|
+
function pbkdf2Init(hash, _password, _salt, _opts) {
|
|
2996
|
+
ahash(hash);
|
|
2997
|
+
const { c, dkLen, asyncTick } = checkOpts({
|
|
2998
|
+
dkLen: 32,
|
|
2999
|
+
asyncTick: 10
|
|
3000
|
+
}, _opts);
|
|
3001
|
+
anumber(c, "c");
|
|
3002
|
+
anumber(dkLen, "dkLen");
|
|
3003
|
+
anumber(asyncTick, "asyncTick");
|
|
3004
|
+
if (c < 1) throw new Error("iterations (c) must be >= 1");
|
|
3005
|
+
const password = kdfInputToBytes(_password, "password");
|
|
3006
|
+
const salt = kdfInputToBytes(_salt, "salt");
|
|
3007
|
+
const DK = new Uint8Array(dkLen);
|
|
3008
|
+
const PRF = hmac.create(hash, password);
|
|
3009
|
+
return {
|
|
3010
|
+
c,
|
|
3011
|
+
dkLen,
|
|
3012
|
+
asyncTick,
|
|
3013
|
+
DK,
|
|
3014
|
+
PRF,
|
|
3015
|
+
PRFSalt: PRF._cloneInto().update(salt)
|
|
3016
|
+
};
|
|
3017
|
+
}
|
|
3018
|
+
function pbkdf2Output(PRF, PRFSalt, DK, prfW, u) {
|
|
3019
|
+
PRF.destroy();
|
|
3020
|
+
PRFSalt.destroy();
|
|
3021
|
+
if (prfW) prfW.destroy();
|
|
3022
|
+
clean(u);
|
|
3023
|
+
return DK;
|
|
3024
|
+
}
|
|
3025
|
+
/**
|
|
3026
|
+
* PBKDF2-HMAC: RFC 2898 key derivation function
|
|
3027
|
+
* @param hash - hash function that would be used e.g. sha256
|
|
3028
|
+
* @param password - password from which a derived key is generated
|
|
3029
|
+
* @param salt - cryptographic salt
|
|
3030
|
+
* @param opts - {c, dkLen} where c is work factor and dkLen is output message size
|
|
3031
|
+
* @example
|
|
3032
|
+
* const key = pbkdf2(sha256, 'password', 'salt', { dkLen: 32, c: Math.pow(2, 18) });
|
|
3033
|
+
*/
|
|
3034
|
+
function pbkdf2(hash, password, salt, opts) {
|
|
3035
|
+
const { c, dkLen, DK, PRF, PRFSalt } = pbkdf2Init(hash, password, salt, opts);
|
|
3036
|
+
let prfW;
|
|
3037
|
+
const arr = new Uint8Array(4);
|
|
3038
|
+
const view = createView(arr);
|
|
3039
|
+
const u = new Uint8Array(PRF.outputLen);
|
|
3040
|
+
for (let ti = 1, pos = 0; pos < dkLen; ti++, pos += PRF.outputLen) {
|
|
3041
|
+
const Ti = DK.subarray(pos, pos + PRF.outputLen);
|
|
3042
|
+
view.setInt32(0, ti, false);
|
|
3043
|
+
(prfW = PRFSalt._cloneInto(prfW)).update(arr).digestInto(u);
|
|
3044
|
+
Ti.set(u.subarray(0, Ti.length));
|
|
3045
|
+
for (let ui = 1; ui < c; ui++) {
|
|
3046
|
+
PRF._cloneInto(prfW).update(u).digestInto(u);
|
|
3047
|
+
for (let i = 0; i < Ti.length; i++) Ti[i] ^= u[i];
|
|
3048
|
+
}
|
|
3049
|
+
}
|
|
3050
|
+
return pbkdf2Output(PRF, PRFSalt, DK, prfW, u);
|
|
3051
|
+
}
|
|
3052
|
+
|
|
3053
|
+
//#endregion
|
|
3054
|
+
//#region ../../node_modules/.pnpm/@noble+hashes@2.0.1/node_modules/@noble/hashes/scrypt.js
|
|
3055
|
+
/**
|
|
3056
|
+
* RFC 7914 Scrypt KDF. Can be used to create a key from password and salt.
|
|
3057
|
+
* @module
|
|
3058
|
+
*/
|
|
3059
|
+
function XorAndSalsa(prev, pi, input, ii, out, oi) {
|
|
3060
|
+
let y00 = prev[pi++] ^ input[ii++], y01 = prev[pi++] ^ input[ii++];
|
|
3061
|
+
let y02 = prev[pi++] ^ input[ii++], y03 = prev[pi++] ^ input[ii++];
|
|
3062
|
+
let y04 = prev[pi++] ^ input[ii++], y05 = prev[pi++] ^ input[ii++];
|
|
3063
|
+
let y06 = prev[pi++] ^ input[ii++], y07 = prev[pi++] ^ input[ii++];
|
|
3064
|
+
let y08 = prev[pi++] ^ input[ii++], y09 = prev[pi++] ^ input[ii++];
|
|
3065
|
+
let y10 = prev[pi++] ^ input[ii++], y11 = prev[pi++] ^ input[ii++];
|
|
3066
|
+
let y12 = prev[pi++] ^ input[ii++], y13 = prev[pi++] ^ input[ii++];
|
|
3067
|
+
let y14 = prev[pi++] ^ input[ii++], y15 = prev[pi++] ^ input[ii++];
|
|
3068
|
+
let x00 = y00, x01 = y01, x02 = y02, x03 = y03, x04 = y04, x05 = y05, x06 = y06, x07 = y07, x08 = y08, x09 = y09, x10 = y10, x11 = y11, x12 = y12, x13 = y13, x14 = y14, x15 = y15;
|
|
3069
|
+
for (let i = 0; i < 8; i += 2) {
|
|
3070
|
+
x04 ^= rotl(x00 + x12 | 0, 7);
|
|
3071
|
+
x08 ^= rotl(x04 + x00 | 0, 9);
|
|
3072
|
+
x12 ^= rotl(x08 + x04 | 0, 13);
|
|
3073
|
+
x00 ^= rotl(x12 + x08 | 0, 18);
|
|
3074
|
+
x09 ^= rotl(x05 + x01 | 0, 7);
|
|
3075
|
+
x13 ^= rotl(x09 + x05 | 0, 9);
|
|
3076
|
+
x01 ^= rotl(x13 + x09 | 0, 13);
|
|
3077
|
+
x05 ^= rotl(x01 + x13 | 0, 18);
|
|
3078
|
+
x14 ^= rotl(x10 + x06 | 0, 7);
|
|
3079
|
+
x02 ^= rotl(x14 + x10 | 0, 9);
|
|
3080
|
+
x06 ^= rotl(x02 + x14 | 0, 13);
|
|
3081
|
+
x10 ^= rotl(x06 + x02 | 0, 18);
|
|
3082
|
+
x03 ^= rotl(x15 + x11 | 0, 7);
|
|
3083
|
+
x07 ^= rotl(x03 + x15 | 0, 9);
|
|
3084
|
+
x11 ^= rotl(x07 + x03 | 0, 13);
|
|
3085
|
+
x15 ^= rotl(x11 + x07 | 0, 18);
|
|
3086
|
+
x01 ^= rotl(x00 + x03 | 0, 7);
|
|
3087
|
+
x02 ^= rotl(x01 + x00 | 0, 9);
|
|
3088
|
+
x03 ^= rotl(x02 + x01 | 0, 13);
|
|
3089
|
+
x00 ^= rotl(x03 + x02 | 0, 18);
|
|
3090
|
+
x06 ^= rotl(x05 + x04 | 0, 7);
|
|
3091
|
+
x07 ^= rotl(x06 + x05 | 0, 9);
|
|
3092
|
+
x04 ^= rotl(x07 + x06 | 0, 13);
|
|
3093
|
+
x05 ^= rotl(x04 + x07 | 0, 18);
|
|
3094
|
+
x11 ^= rotl(x10 + x09 | 0, 7);
|
|
3095
|
+
x08 ^= rotl(x11 + x10 | 0, 9);
|
|
3096
|
+
x09 ^= rotl(x08 + x11 | 0, 13);
|
|
3097
|
+
x10 ^= rotl(x09 + x08 | 0, 18);
|
|
3098
|
+
x12 ^= rotl(x15 + x14 | 0, 7);
|
|
3099
|
+
x13 ^= rotl(x12 + x15 | 0, 9);
|
|
3100
|
+
x14 ^= rotl(x13 + x12 | 0, 13);
|
|
3101
|
+
x15 ^= rotl(x14 + x13 | 0, 18);
|
|
3102
|
+
}
|
|
3103
|
+
out[oi++] = y00 + x00 | 0;
|
|
3104
|
+
out[oi++] = y01 + x01 | 0;
|
|
3105
|
+
out[oi++] = y02 + x02 | 0;
|
|
3106
|
+
out[oi++] = y03 + x03 | 0;
|
|
3107
|
+
out[oi++] = y04 + x04 | 0;
|
|
3108
|
+
out[oi++] = y05 + x05 | 0;
|
|
3109
|
+
out[oi++] = y06 + x06 | 0;
|
|
3110
|
+
out[oi++] = y07 + x07 | 0;
|
|
3111
|
+
out[oi++] = y08 + x08 | 0;
|
|
3112
|
+
out[oi++] = y09 + x09 | 0;
|
|
3113
|
+
out[oi++] = y10 + x10 | 0;
|
|
3114
|
+
out[oi++] = y11 + x11 | 0;
|
|
3115
|
+
out[oi++] = y12 + x12 | 0;
|
|
3116
|
+
out[oi++] = y13 + x13 | 0;
|
|
3117
|
+
out[oi++] = y14 + x14 | 0;
|
|
3118
|
+
out[oi++] = y15 + x15 | 0;
|
|
3119
|
+
}
|
|
3120
|
+
function BlockMix(input, ii, out, oi, r) {
|
|
3121
|
+
let head = oi + 0;
|
|
3122
|
+
let tail = oi + 16 * r;
|
|
3123
|
+
for (let i = 0; i < 16; i++) out[tail + i] = input[ii + (2 * r - 1) * 16 + i];
|
|
3124
|
+
for (let i = 0; i < r; i++, head += 16, ii += 16) {
|
|
3125
|
+
XorAndSalsa(out, tail, input, ii, out, head);
|
|
3126
|
+
if (i > 0) tail += 16;
|
|
3127
|
+
XorAndSalsa(out, head, input, ii += 16, out, tail);
|
|
3128
|
+
}
|
|
3129
|
+
}
|
|
3130
|
+
function scryptInit(password, salt, _opts) {
|
|
3131
|
+
const { N, r, p, dkLen, asyncTick, maxmem, onProgress } = checkOpts({
|
|
3132
|
+
dkLen: 32,
|
|
3133
|
+
asyncTick: 10,
|
|
3134
|
+
maxmem: 1024 ** 3 + 1024
|
|
3135
|
+
}, _opts);
|
|
3136
|
+
anumber(N, "N");
|
|
3137
|
+
anumber(r, "r");
|
|
3138
|
+
anumber(p, "p");
|
|
3139
|
+
anumber(dkLen, "dkLen");
|
|
3140
|
+
anumber(asyncTick, "asyncTick");
|
|
3141
|
+
anumber(maxmem, "maxmem");
|
|
3142
|
+
if (onProgress !== void 0 && typeof onProgress !== "function") throw new Error("progressCb must be a function");
|
|
3143
|
+
const blockSize = 128 * r;
|
|
3144
|
+
const blockSize32 = blockSize / 4;
|
|
3145
|
+
const pow32 = Math.pow(2, 32);
|
|
3146
|
+
if (N <= 1 || (N & N - 1) !== 0 || N > pow32) throw new Error("\"N\" expected a power of 2, and 2^1 <= N <= 2^32");
|
|
3147
|
+
if (p < 1 || p > (pow32 - 1) * 32 / blockSize) throw new Error("\"p\" expected integer 1..((2^32 - 1) * 32) / (128 * r)");
|
|
3148
|
+
if (dkLen < 1 || dkLen > (pow32 - 1) * 32) throw new Error("\"dkLen\" expected integer 1..(2^32 - 1) * 32");
|
|
3149
|
+
if (blockSize * (N + p) > maxmem) throw new Error("\"maxmem\" limit was hit, expected 128*r*(N+p) <= \"maxmem\"=" + maxmem);
|
|
3150
|
+
const B = pbkdf2(sha256, password, salt, {
|
|
3151
|
+
c: 1,
|
|
3152
|
+
dkLen: blockSize * p
|
|
3153
|
+
});
|
|
3154
|
+
const B32 = u32(B);
|
|
3155
|
+
const V = u32(new Uint8Array(blockSize * N));
|
|
3156
|
+
const tmp = u32(new Uint8Array(blockSize));
|
|
3157
|
+
let blockMixCb = () => {};
|
|
3158
|
+
if (onProgress) {
|
|
3159
|
+
const totalBlockMix = 2 * N * p;
|
|
3160
|
+
const callbackPer = Math.max(Math.floor(totalBlockMix / 1e4), 1);
|
|
3161
|
+
let blockMixCnt = 0;
|
|
3162
|
+
blockMixCb = () => {
|
|
3163
|
+
blockMixCnt++;
|
|
3164
|
+
if (onProgress && (!(blockMixCnt % callbackPer) || blockMixCnt === totalBlockMix)) onProgress(blockMixCnt / totalBlockMix);
|
|
3165
|
+
};
|
|
3166
|
+
}
|
|
3167
|
+
return {
|
|
3168
|
+
N,
|
|
3169
|
+
r,
|
|
3170
|
+
p,
|
|
3171
|
+
dkLen,
|
|
3172
|
+
blockSize32,
|
|
3173
|
+
V,
|
|
3174
|
+
B32,
|
|
3175
|
+
B,
|
|
3176
|
+
tmp,
|
|
3177
|
+
blockMixCb,
|
|
3178
|
+
asyncTick
|
|
3179
|
+
};
|
|
3180
|
+
}
|
|
3181
|
+
function scryptOutput(password, dkLen, B, V, tmp) {
|
|
3182
|
+
const res = pbkdf2(sha256, password, B, {
|
|
3183
|
+
c: 1,
|
|
3184
|
+
dkLen
|
|
3185
|
+
});
|
|
3186
|
+
clean(B, V, tmp);
|
|
3187
|
+
return res;
|
|
3188
|
+
}
|
|
3189
|
+
/**
|
|
3190
|
+
* Scrypt KDF from RFC 7914. Async version. See {@link ScryptOpts}.
|
|
3191
|
+
* @example
|
|
3192
|
+
* await scryptAsync('password', 'salt', { N: 2**18, r: 8, p: 1, dkLen: 32 });
|
|
3193
|
+
*/
|
|
3194
|
+
async function scryptAsync(password, salt, opts) {
|
|
3195
|
+
const { N, r, p, dkLen, blockSize32, V, B32, B, tmp, blockMixCb, asyncTick } = scryptInit(password, salt, opts);
|
|
3196
|
+
swap32IfBE(B32);
|
|
3197
|
+
for (let pi = 0; pi < p; pi++) {
|
|
3198
|
+
const Pi = blockSize32 * pi;
|
|
3199
|
+
for (let i = 0; i < blockSize32; i++) V[i] = B32[Pi + i];
|
|
3200
|
+
let pos = 0;
|
|
3201
|
+
await asyncLoop(N - 1, asyncTick, () => {
|
|
3202
|
+
BlockMix(V, pos, V, pos += blockSize32, r);
|
|
3203
|
+
blockMixCb();
|
|
3204
|
+
});
|
|
3205
|
+
BlockMix(V, (N - 1) * blockSize32, B32, Pi, r);
|
|
3206
|
+
blockMixCb();
|
|
3207
|
+
await asyncLoop(N, asyncTick, () => {
|
|
3208
|
+
const j = (B32[Pi + blockSize32 - 16] & N - 1) >>> 0;
|
|
3209
|
+
for (let k = 0; k < blockSize32; k++) tmp[k] = B32[Pi + k] ^ V[j * blockSize32 + k];
|
|
3210
|
+
BlockMix(tmp, 0, B32, Pi, r);
|
|
3211
|
+
blockMixCb();
|
|
3212
|
+
});
|
|
3213
|
+
}
|
|
3214
|
+
swap32IfBE(B32);
|
|
3215
|
+
return scryptOutput(password, dkLen, B, V, tmp);
|
|
3216
|
+
}
|
|
3217
|
+
|
|
3218
|
+
//#endregion
|
|
3219
|
+
//#region ../better-auth/dist/crypto-BVDG04BB.mjs
|
|
3220
|
+
function createHash(algorithm, encoding) {
|
|
3221
|
+
return { digest: async (input) => {
|
|
3222
|
+
const encoder = new TextEncoder();
|
|
3223
|
+
const data = typeof input === "string" ? encoder.encode(input) : input;
|
|
3224
|
+
const hashBuffer = await getWebcryptoSubtle().digest(algorithm, data);
|
|
3225
|
+
if (encoding === "hex") return Array.from(new Uint8Array(hashBuffer)).map((b) => b.toString(16).padStart(2, "0")).join("");
|
|
3226
|
+
if (encoding === "base64" || encoding === "base64url" || encoding === "base64urlnopad") {
|
|
3227
|
+
if (encoding.includes("url")) return base64Url.encode(hashBuffer, { padding: encoding !== "base64urlnopad" });
|
|
3228
|
+
return base64.encode(hashBuffer);
|
|
3229
|
+
}
|
|
3230
|
+
return hashBuffer;
|
|
3231
|
+
} };
|
|
3232
|
+
}
|
|
3233
|
+
/**
|
|
3234
|
+
* Compare two buffers in constant time.
|
|
3235
|
+
*/
|
|
3236
|
+
function constantTimeEqual(a, b) {
|
|
3237
|
+
if (typeof a === "string") a = new TextEncoder().encode(a);
|
|
3238
|
+
if (typeof b === "string") b = new TextEncoder().encode(b);
|
|
3239
|
+
const aBuffer = new Uint8Array(a);
|
|
3240
|
+
const bBuffer = new Uint8Array(b);
|
|
3241
|
+
let c = aBuffer.length ^ bBuffer.length;
|
|
3242
|
+
const length = Math.max(aBuffer.length, bBuffer.length);
|
|
3243
|
+
for (let i = 0; i < length; i++) c |= (i < aBuffer.length ? aBuffer[i] : 0) ^ (i < bBuffer.length ? bBuffer[i] : 0);
|
|
3244
|
+
return c === 0;
|
|
3245
|
+
}
|
|
3246
|
+
const config = {
|
|
3247
|
+
N: 16384,
|
|
3248
|
+
r: 16,
|
|
3249
|
+
p: 1,
|
|
3250
|
+
dkLen: 64
|
|
3251
|
+
};
|
|
3252
|
+
async function generateKey(password, salt) {
|
|
3253
|
+
return await scryptAsync(password.normalize("NFKC"), salt, {
|
|
3254
|
+
N: config.N,
|
|
3255
|
+
p: config.p,
|
|
3256
|
+
r: config.r,
|
|
3257
|
+
dkLen: config.dkLen,
|
|
3258
|
+
maxmem: 128 * config.N * config.r * 2
|
|
3259
|
+
});
|
|
3260
|
+
}
|
|
3261
|
+
const hashPassword = async (password) => {
|
|
3262
|
+
const salt = hex.encode(crypto.getRandomValues(new Uint8Array(16)));
|
|
3263
|
+
const key = await generateKey(password, salt);
|
|
3264
|
+
return `${salt}:${hex.encode(key)}`;
|
|
3265
|
+
};
|
|
3266
|
+
const verifyPassword = async ({ hash, password }) => {
|
|
3267
|
+
const [salt, key] = hash.split(":");
|
|
3268
|
+
if (!salt || !key) throw new BetterAuthError("Invalid password hash");
|
|
3269
|
+
return constantTimeEqual(await generateKey(password, salt), hexToBytes$1(key));
|
|
3270
|
+
};
|
|
3271
|
+
function expandAlphabet(alphabet) {
|
|
3272
|
+
switch (alphabet) {
|
|
3273
|
+
case "a-z": return "abcdefghijklmnopqrstuvwxyz";
|
|
3274
|
+
case "A-Z": return "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
|
|
3275
|
+
case "0-9": return "0123456789";
|
|
3276
|
+
case "-_": return "-_";
|
|
3277
|
+
default: throw new Error(`Unsupported alphabet: ${alphabet}`);
|
|
3278
|
+
}
|
|
3279
|
+
}
|
|
3280
|
+
function createRandomStringGenerator(...baseAlphabets) {
|
|
3281
|
+
const baseCharSet = baseAlphabets.map(expandAlphabet).join("");
|
|
3282
|
+
if (baseCharSet.length === 0) throw new Error("No valid characters provided for random string generation.");
|
|
3283
|
+
const baseCharSetLength = baseCharSet.length;
|
|
3284
|
+
return (length, ...alphabets) => {
|
|
3285
|
+
if (length <= 0) throw new Error("Length must be a positive integer.");
|
|
3286
|
+
let charSet = baseCharSet;
|
|
3287
|
+
let charSetLength = baseCharSetLength;
|
|
3288
|
+
if (alphabets.length > 0) {
|
|
3289
|
+
charSet = alphabets.map(expandAlphabet).join("");
|
|
3290
|
+
charSetLength = charSet.length;
|
|
3291
|
+
}
|
|
3292
|
+
const maxValid = Math.floor(256 / charSetLength) * charSetLength;
|
|
3293
|
+
const buf = new Uint8Array(length * 2);
|
|
3294
|
+
const bufLength = buf.length;
|
|
3295
|
+
let result = "";
|
|
3296
|
+
let bufIndex = bufLength;
|
|
3297
|
+
let rand;
|
|
3298
|
+
while (result.length < length) {
|
|
3299
|
+
if (bufIndex >= bufLength) {
|
|
3300
|
+
crypto.getRandomValues(buf);
|
|
3301
|
+
bufIndex = 0;
|
|
3302
|
+
}
|
|
3303
|
+
rand = buf[bufIndex++];
|
|
3304
|
+
if (rand < maxValid) result += charSet[rand % charSetLength];
|
|
3305
|
+
}
|
|
3306
|
+
return result;
|
|
3307
|
+
};
|
|
3308
|
+
}
|
|
3309
|
+
const generateRandomString = createRandomStringGenerator("a-z", "0-9", "A-Z", "-_");
|
|
3310
|
+
const symmetricEncrypt = async ({ key, data }) => {
|
|
3311
|
+
const keyAsBytes = await createHash("SHA-256").digest(key);
|
|
3312
|
+
const dataAsBytes = utf8ToBytes(data);
|
|
3313
|
+
return bytesToHex(managedNonce(xchacha20poly1305)(new Uint8Array(keyAsBytes)).encrypt(dataAsBytes));
|
|
3314
|
+
};
|
|
3315
|
+
const symmetricDecrypt = async ({ key, data }) => {
|
|
3316
|
+
const keyAsBytes = await createHash("SHA-256").digest(key);
|
|
3317
|
+
const dataAsBytes = hexToBytes(data);
|
|
3318
|
+
const chacha = managedNonce(xchacha20poly1305)(new Uint8Array(keyAsBytes));
|
|
3319
|
+
return new TextDecoder().decode(chacha.decrypt(dataAsBytes));
|
|
3320
|
+
};
|
|
3321
|
+
|
|
3322
|
+
//#endregion
|
|
3323
|
+
//#region ../better-auth/dist/utils-BqZRXR74.mjs
|
|
3324
|
+
const { get: getOAuthState, set: setOAuthState } = defineRequestState(() => null);
|
|
3325
|
+
async function generateState(c, link, additionalData) {
|
|
3326
|
+
const callbackURL = c.body?.callbackURL || c.context.options.baseURL;
|
|
3327
|
+
if (!callbackURL) throw new APIError("BAD_REQUEST", { message: "callbackURL is required" });
|
|
3328
|
+
const codeVerifier = generateRandomString(128);
|
|
3329
|
+
const state = generateRandomString(32);
|
|
3330
|
+
const storeStateStrategy = c.context.oauthConfig?.storeStateStrategy || "cookie";
|
|
3331
|
+
const stateData = {
|
|
3332
|
+
...additionalData ? additionalData : {},
|
|
3333
|
+
callbackURL,
|
|
3334
|
+
codeVerifier,
|
|
3335
|
+
errorURL: c.body?.errorCallbackURL,
|
|
3336
|
+
newUserURL: c.body?.newUserCallbackURL,
|
|
3337
|
+
link,
|
|
3338
|
+
expiresAt: Date.now() + 600 * 1e3,
|
|
3339
|
+
requestSignUp: c.body?.requestSignUp
|
|
3340
|
+
};
|
|
3341
|
+
await setOAuthState(stateData);
|
|
3342
|
+
if (storeStateStrategy === "cookie") {
|
|
3343
|
+
const encryptedData = await symmetricEncrypt({
|
|
3344
|
+
key: c.context.secret,
|
|
3345
|
+
data: JSON.stringify(stateData)
|
|
3346
|
+
});
|
|
3347
|
+
const stateCookie$1 = c.context.createAuthCookie("oauth_state", { maxAge: 600 * 1e3 });
|
|
3348
|
+
c.setCookie(stateCookie$1.name, encryptedData, stateCookie$1.attributes);
|
|
3349
|
+
return {
|
|
3350
|
+
state,
|
|
3351
|
+
codeVerifier
|
|
3352
|
+
};
|
|
3353
|
+
}
|
|
3354
|
+
const stateCookie = c.context.createAuthCookie("state", { maxAge: 300 * 1e3 });
|
|
3355
|
+
await c.setSignedCookie(stateCookie.name, state, c.context.secret, stateCookie.attributes);
|
|
3356
|
+
const expiresAt = /* @__PURE__ */ new Date();
|
|
3357
|
+
expiresAt.setMinutes(expiresAt.getMinutes() + 10);
|
|
3358
|
+
const verification = await c.context.internalAdapter.createVerificationValue({
|
|
3359
|
+
value: JSON.stringify(stateData),
|
|
3360
|
+
identifier: state,
|
|
3361
|
+
expiresAt
|
|
3362
|
+
});
|
|
3363
|
+
if (!verification) {
|
|
3364
|
+
c.context.logger.error("Unable to create verification. Make sure the database adapter is properly working and there is a verification table in the database");
|
|
3365
|
+
throw new APIError("INTERNAL_SERVER_ERROR", { message: "Unable to create verification" });
|
|
3366
|
+
}
|
|
3367
|
+
return {
|
|
3368
|
+
state: verification.identifier,
|
|
3369
|
+
codeVerifier
|
|
3370
|
+
};
|
|
3371
|
+
}
|
|
3372
|
+
async function parseState(c) {
|
|
3373
|
+
const state = c.query.state || c.body.state;
|
|
3374
|
+
const storeStateStrategy = c.context.oauthConfig.storeStateStrategy || "cookie";
|
|
3375
|
+
const stateDataSchema = z$2.looseObject({
|
|
3376
|
+
callbackURL: z$2.string(),
|
|
3377
|
+
codeVerifier: z$2.string(),
|
|
3378
|
+
errorURL: z$2.string().optional(),
|
|
3379
|
+
newUserURL: z$2.string().optional(),
|
|
3380
|
+
expiresAt: z$2.number(),
|
|
3381
|
+
link: z$2.object({
|
|
3382
|
+
email: z$2.string(),
|
|
3383
|
+
userId: z$2.coerce.string()
|
|
3384
|
+
}).optional(),
|
|
3385
|
+
requestSignUp: z$2.boolean().optional()
|
|
3386
|
+
});
|
|
3387
|
+
let parsedData;
|
|
3388
|
+
if (storeStateStrategy === "cookie") {
|
|
3389
|
+
const stateCookie = c.context.createAuthCookie("oauth_state");
|
|
3390
|
+
const encryptedData = c.getCookie(stateCookie.name);
|
|
3391
|
+
if (!encryptedData) {
|
|
3392
|
+
c.context.logger.error("State Mismatch. OAuth state cookie not found", { state });
|
|
3393
|
+
const errorURL = c.context.options.onAPIError?.errorURL || `${c.context.baseURL}/error`;
|
|
3394
|
+
throw c.redirect(`${errorURL}?error=please_restart_the_process`);
|
|
3395
|
+
}
|
|
3396
|
+
try {
|
|
3397
|
+
const decryptedData = await symmetricDecrypt({
|
|
3398
|
+
key: c.context.secret,
|
|
3399
|
+
data: encryptedData
|
|
3400
|
+
});
|
|
3401
|
+
parsedData = stateDataSchema.parse(JSON.parse(decryptedData));
|
|
3402
|
+
} catch (error) {
|
|
3403
|
+
c.context.logger.error("Failed to decrypt or parse OAuth state cookie", { error });
|
|
3404
|
+
const errorURL = c.context.options.onAPIError?.errorURL || `${c.context.baseURL}/error`;
|
|
3405
|
+
throw c.redirect(`${errorURL}?error=please_restart_the_process`);
|
|
3406
|
+
}
|
|
3407
|
+
c.setCookie(stateCookie.name, "", { maxAge: 0 });
|
|
3408
|
+
} else {
|
|
3409
|
+
const data = await c.context.internalAdapter.findVerificationValue(state);
|
|
3410
|
+
if (!data) {
|
|
3411
|
+
c.context.logger.error("State Mismatch. Verification not found", { state });
|
|
3412
|
+
const errorURL = c.context.options.onAPIError?.errorURL || `${c.context.baseURL}/error`;
|
|
3413
|
+
throw c.redirect(`${errorURL}?error=please_restart_the_process`);
|
|
3414
|
+
}
|
|
3415
|
+
parsedData = stateDataSchema.parse(JSON.parse(data.value));
|
|
3416
|
+
const stateCookie = c.context.createAuthCookie("state");
|
|
3417
|
+
const stateCookieValue = await c.getSignedCookie(stateCookie.name, c.context.secret);
|
|
3418
|
+
if (!c.context.oauthConfig?.skipStateCookieCheck && (!stateCookieValue || stateCookieValue !== state)) {
|
|
3419
|
+
const errorURL = c.context.options.onAPIError?.errorURL || `${c.context.baseURL}/error`;
|
|
3420
|
+
throw c.redirect(`${errorURL}?error=state_mismatch`);
|
|
3421
|
+
}
|
|
3422
|
+
c.setCookie(stateCookie.name, "", { maxAge: 0 });
|
|
3423
|
+
await c.context.internalAdapter.deleteVerificationValue(data.id);
|
|
3424
|
+
}
|
|
3425
|
+
if (!parsedData.errorURL) parsedData.errorURL = c.context.options.onAPIError?.errorURL || `${c.context.baseURL}/error`;
|
|
3426
|
+
if (parsedData.expiresAt < Date.now()) {
|
|
3427
|
+
const errorURL = c.context.options.onAPIError?.errorURL || `${c.context.baseURL}/error`;
|
|
3428
|
+
throw c.redirect(`${errorURL}?error=please_restart_the_process`);
|
|
3429
|
+
}
|
|
3430
|
+
if (parsedData) await setOAuthState(parsedData);
|
|
3431
|
+
return parsedData;
|
|
3432
|
+
}
|
|
3433
|
+
const HIDE_METADATA = { isAction: false };
|
|
3434
|
+
const generateId = (size) => {
|
|
3435
|
+
return createRandomStringGenerator("a-z", "A-Z", "0-9")(size || 32);
|
|
3436
|
+
};
|
|
3437
|
+
|
|
3438
|
+
//#endregion
|
|
3439
|
+
//#region ../better-auth/dist/get-model-name-DGZmxvj1.mjs
|
|
3440
|
+
const getAuthTables = (options) => {
|
|
3441
|
+
const pluginSchema = (options.plugins ?? []).reduce((acc, plugin) => {
|
|
3442
|
+
const schema = plugin.schema;
|
|
3443
|
+
if (!schema) return acc;
|
|
3444
|
+
for (const [key, value] of Object.entries(schema)) acc[key] = {
|
|
3445
|
+
fields: {
|
|
3446
|
+
...acc[key]?.fields,
|
|
3447
|
+
...value.fields
|
|
3448
|
+
},
|
|
3449
|
+
modelName: value.modelName || key
|
|
3450
|
+
};
|
|
3451
|
+
return acc;
|
|
3452
|
+
}, {});
|
|
3453
|
+
const shouldAddRateLimitTable = options.rateLimit?.storage === "database";
|
|
3454
|
+
const rateLimitTable = { rateLimit: {
|
|
3455
|
+
modelName: options.rateLimit?.modelName || "rateLimit",
|
|
3456
|
+
fields: {
|
|
3457
|
+
key: {
|
|
3458
|
+
type: "string",
|
|
3459
|
+
fieldName: options.rateLimit?.fields?.key || "key"
|
|
3460
|
+
},
|
|
3461
|
+
count: {
|
|
3462
|
+
type: "number",
|
|
3463
|
+
fieldName: options.rateLimit?.fields?.count || "count"
|
|
3464
|
+
},
|
|
3465
|
+
lastRequest: {
|
|
3466
|
+
type: "number",
|
|
3467
|
+
bigint: true,
|
|
3468
|
+
fieldName: options.rateLimit?.fields?.lastRequest || "lastRequest"
|
|
3469
|
+
}
|
|
3470
|
+
}
|
|
3471
|
+
} };
|
|
3472
|
+
const { user, session, account, ...pluginTables } = pluginSchema;
|
|
3473
|
+
const sessionTable = { session: {
|
|
3474
|
+
modelName: options.session?.modelName || "session",
|
|
3475
|
+
fields: {
|
|
3476
|
+
expiresAt: {
|
|
3477
|
+
type: "date",
|
|
3478
|
+
required: true,
|
|
3479
|
+
fieldName: options.session?.fields?.expiresAt || "expiresAt"
|
|
3480
|
+
},
|
|
3481
|
+
token: {
|
|
3482
|
+
type: "string",
|
|
3483
|
+
required: true,
|
|
3484
|
+
fieldName: options.session?.fields?.token || "token",
|
|
3485
|
+
unique: true
|
|
3486
|
+
},
|
|
3487
|
+
createdAt: {
|
|
3488
|
+
type: "date",
|
|
3489
|
+
required: true,
|
|
3490
|
+
fieldName: options.session?.fields?.createdAt || "createdAt",
|
|
3491
|
+
defaultValue: () => /* @__PURE__ */ new Date()
|
|
3492
|
+
},
|
|
3493
|
+
updatedAt: {
|
|
3494
|
+
type: "date",
|
|
3495
|
+
required: true,
|
|
3496
|
+
fieldName: options.session?.fields?.updatedAt || "updatedAt",
|
|
3497
|
+
onUpdate: () => /* @__PURE__ */ new Date()
|
|
3498
|
+
},
|
|
3499
|
+
ipAddress: {
|
|
3500
|
+
type: "string",
|
|
3501
|
+
required: false,
|
|
3502
|
+
fieldName: options.session?.fields?.ipAddress || "ipAddress"
|
|
3503
|
+
},
|
|
3504
|
+
userAgent: {
|
|
3505
|
+
type: "string",
|
|
3506
|
+
required: false,
|
|
3507
|
+
fieldName: options.session?.fields?.userAgent || "userAgent"
|
|
3508
|
+
},
|
|
3509
|
+
userId: {
|
|
3510
|
+
type: "string",
|
|
3511
|
+
fieldName: options.session?.fields?.userId || "userId",
|
|
3512
|
+
references: {
|
|
3513
|
+
model: options.user?.modelName || "user",
|
|
3514
|
+
field: "id",
|
|
3515
|
+
onDelete: "cascade"
|
|
3516
|
+
},
|
|
3517
|
+
required: true,
|
|
3518
|
+
index: true
|
|
3519
|
+
},
|
|
3520
|
+
...session?.fields,
|
|
3521
|
+
...options.session?.additionalFields
|
|
3522
|
+
},
|
|
3523
|
+
order: 2
|
|
3524
|
+
} };
|
|
3525
|
+
return {
|
|
3526
|
+
user: {
|
|
3527
|
+
modelName: options.user?.modelName || "user",
|
|
3528
|
+
fields: {
|
|
3529
|
+
name: {
|
|
3530
|
+
type: "string",
|
|
3531
|
+
required: true,
|
|
3532
|
+
fieldName: options.user?.fields?.name || "name",
|
|
3533
|
+
sortable: true
|
|
3534
|
+
},
|
|
3535
|
+
email: {
|
|
3536
|
+
type: "string",
|
|
3537
|
+
unique: true,
|
|
3538
|
+
required: true,
|
|
3539
|
+
fieldName: options.user?.fields?.email || "email",
|
|
3540
|
+
sortable: true
|
|
3541
|
+
},
|
|
3542
|
+
emailVerified: {
|
|
3543
|
+
type: "boolean",
|
|
3544
|
+
defaultValue: false,
|
|
3545
|
+
required: true,
|
|
3546
|
+
fieldName: options.user?.fields?.emailVerified || "emailVerified",
|
|
3547
|
+
input: false
|
|
3548
|
+
},
|
|
3549
|
+
image: {
|
|
3550
|
+
type: "string",
|
|
3551
|
+
required: false,
|
|
3552
|
+
fieldName: options.user?.fields?.image || "image"
|
|
3553
|
+
},
|
|
3554
|
+
createdAt: {
|
|
3555
|
+
type: "date",
|
|
3556
|
+
defaultValue: () => /* @__PURE__ */ new Date(),
|
|
3557
|
+
required: true,
|
|
3558
|
+
fieldName: options.user?.fields?.createdAt || "createdAt"
|
|
3559
|
+
},
|
|
3560
|
+
updatedAt: {
|
|
3561
|
+
type: "date",
|
|
3562
|
+
defaultValue: () => /* @__PURE__ */ new Date(),
|
|
3563
|
+
onUpdate: () => /* @__PURE__ */ new Date(),
|
|
3564
|
+
required: true,
|
|
3565
|
+
fieldName: options.user?.fields?.updatedAt || "updatedAt"
|
|
3566
|
+
},
|
|
3567
|
+
...user?.fields,
|
|
3568
|
+
...options.user?.additionalFields
|
|
3569
|
+
},
|
|
3570
|
+
order: 1
|
|
3571
|
+
},
|
|
3572
|
+
...!options.secondaryStorage || options.session?.storeSessionInDatabase ? sessionTable : {},
|
|
3573
|
+
account: {
|
|
3574
|
+
modelName: options.account?.modelName || "account",
|
|
3575
|
+
fields: {
|
|
3576
|
+
accountId: {
|
|
3577
|
+
type: "string",
|
|
3578
|
+
required: true,
|
|
3579
|
+
fieldName: options.account?.fields?.accountId || "accountId"
|
|
3580
|
+
},
|
|
3581
|
+
providerId: {
|
|
3582
|
+
type: "string",
|
|
3583
|
+
required: true,
|
|
3584
|
+
fieldName: options.account?.fields?.providerId || "providerId"
|
|
3585
|
+
},
|
|
3586
|
+
userId: {
|
|
3587
|
+
type: "string",
|
|
3588
|
+
references: {
|
|
3589
|
+
model: options.user?.modelName || "user",
|
|
3590
|
+
field: "id",
|
|
3591
|
+
onDelete: "cascade"
|
|
3592
|
+
},
|
|
3593
|
+
required: true,
|
|
3594
|
+
fieldName: options.account?.fields?.userId || "userId",
|
|
3595
|
+
index: true
|
|
3596
|
+
},
|
|
3597
|
+
accessToken: {
|
|
3598
|
+
type: "string",
|
|
3599
|
+
required: false,
|
|
3600
|
+
fieldName: options.account?.fields?.accessToken || "accessToken"
|
|
3601
|
+
},
|
|
3602
|
+
refreshToken: {
|
|
3603
|
+
type: "string",
|
|
3604
|
+
required: false,
|
|
3605
|
+
fieldName: options.account?.fields?.refreshToken || "refreshToken"
|
|
3606
|
+
},
|
|
3607
|
+
idToken: {
|
|
3608
|
+
type: "string",
|
|
3609
|
+
required: false,
|
|
3610
|
+
fieldName: options.account?.fields?.idToken || "idToken"
|
|
3611
|
+
},
|
|
3612
|
+
accessTokenExpiresAt: {
|
|
3613
|
+
type: "date",
|
|
3614
|
+
required: false,
|
|
3615
|
+
fieldName: options.account?.fields?.accessTokenExpiresAt || "accessTokenExpiresAt"
|
|
3616
|
+
},
|
|
3617
|
+
refreshTokenExpiresAt: {
|
|
3618
|
+
type: "date",
|
|
3619
|
+
required: false,
|
|
3620
|
+
fieldName: options.account?.fields?.refreshTokenExpiresAt || "refreshTokenExpiresAt"
|
|
3621
|
+
},
|
|
3622
|
+
scope: {
|
|
3623
|
+
type: "string",
|
|
3624
|
+
required: false,
|
|
3625
|
+
fieldName: options.account?.fields?.scope || "scope"
|
|
3626
|
+
},
|
|
3627
|
+
password: {
|
|
3628
|
+
type: "string",
|
|
3629
|
+
required: false,
|
|
3630
|
+
fieldName: options.account?.fields?.password || "password"
|
|
3631
|
+
},
|
|
3632
|
+
createdAt: {
|
|
3633
|
+
type: "date",
|
|
3634
|
+
required: true,
|
|
3635
|
+
fieldName: options.account?.fields?.createdAt || "createdAt",
|
|
3636
|
+
defaultValue: () => /* @__PURE__ */ new Date()
|
|
3637
|
+
},
|
|
3638
|
+
updatedAt: {
|
|
3639
|
+
type: "date",
|
|
3640
|
+
required: true,
|
|
3641
|
+
fieldName: options.account?.fields?.updatedAt || "updatedAt",
|
|
3642
|
+
onUpdate: () => /* @__PURE__ */ new Date()
|
|
3643
|
+
},
|
|
3644
|
+
...account?.fields,
|
|
3645
|
+
...options.account?.additionalFields
|
|
3646
|
+
},
|
|
3647
|
+
order: 3
|
|
3648
|
+
},
|
|
3649
|
+
verification: {
|
|
3650
|
+
modelName: options.verification?.modelName || "verification",
|
|
3651
|
+
fields: {
|
|
3652
|
+
identifier: {
|
|
3653
|
+
type: "string",
|
|
3654
|
+
required: true,
|
|
3655
|
+
fieldName: options.verification?.fields?.identifier || "identifier",
|
|
3656
|
+
index: true
|
|
3657
|
+
},
|
|
3658
|
+
value: {
|
|
3659
|
+
type: "string",
|
|
3660
|
+
required: true,
|
|
3661
|
+
fieldName: options.verification?.fields?.value || "value"
|
|
3662
|
+
},
|
|
3663
|
+
expiresAt: {
|
|
3664
|
+
type: "date",
|
|
3665
|
+
required: true,
|
|
3666
|
+
fieldName: options.verification?.fields?.expiresAt || "expiresAt"
|
|
3667
|
+
},
|
|
3668
|
+
createdAt: {
|
|
3669
|
+
type: "date",
|
|
3670
|
+
required: true,
|
|
3671
|
+
defaultValue: () => /* @__PURE__ */ new Date(),
|
|
3672
|
+
fieldName: options.verification?.fields?.createdAt || "createdAt"
|
|
3673
|
+
},
|
|
3674
|
+
updatedAt: {
|
|
3675
|
+
type: "date",
|
|
3676
|
+
required: true,
|
|
3677
|
+
defaultValue: () => /* @__PURE__ */ new Date(),
|
|
3678
|
+
onUpdate: () => /* @__PURE__ */ new Date(),
|
|
3679
|
+
fieldName: options.verification?.fields?.updatedAt || "updatedAt"
|
|
3680
|
+
}
|
|
3681
|
+
},
|
|
3682
|
+
order: 4
|
|
3683
|
+
},
|
|
3684
|
+
...pluginTables,
|
|
3685
|
+
...shouldAddRateLimitTable ? rateLimitTable : {}
|
|
3686
|
+
};
|
|
3687
|
+
};
|
|
3688
|
+
const initGetDefaultModelName = ({ usePlural, schema }) => {
|
|
3689
|
+
/**
|
|
3690
|
+
* This function helps us get the default model name from the schema defined by devs.
|
|
3691
|
+
* Often times, the user will be using the `modelName` which could had been customized by the users.
|
|
3692
|
+
* This function helps us get the actual model name useful to match against the schema. (eg: schema[model])
|
|
3693
|
+
*
|
|
3694
|
+
* If it's still unclear what this does:
|
|
3695
|
+
*
|
|
3696
|
+
* 1. User can define a custom modelName.
|
|
3697
|
+
* 2. When using a custom modelName, doing something like `schema[model]` will not work.
|
|
3698
|
+
* 3. Using this function helps us get the actual model name based on the user's defined custom modelName.
|
|
3699
|
+
*/
|
|
3700
|
+
const getDefaultModelName = (model) => {
|
|
3701
|
+
if (usePlural && model.charAt(model.length - 1) === "s") {
|
|
3702
|
+
let pluralessModel = model.slice(0, -1);
|
|
3703
|
+
let m$1 = schema[pluralessModel] ? pluralessModel : void 0;
|
|
3704
|
+
if (!m$1) m$1 = Object.entries(schema).find(([_, f]) => f.modelName === pluralessModel)?.[0];
|
|
3705
|
+
if (m$1) return m$1;
|
|
3706
|
+
}
|
|
3707
|
+
let m = schema[model] ? model : void 0;
|
|
3708
|
+
if (!m) m = Object.entries(schema).find(([_, f]) => f.modelName === model)?.[0];
|
|
3709
|
+
if (!m) throw new BetterAuthError(`Model "${model}" not found in schema`);
|
|
3710
|
+
return m;
|
|
3711
|
+
};
|
|
3712
|
+
return getDefaultModelName;
|
|
3713
|
+
};
|
|
3714
|
+
const initGetDefaultFieldName = ({ schema, usePlural }) => {
|
|
3715
|
+
const getDefaultModelName = initGetDefaultModelName({
|
|
3716
|
+
schema,
|
|
3717
|
+
usePlural
|
|
3718
|
+
});
|
|
3719
|
+
/**
|
|
3720
|
+
* This function helps us get the default field name from the schema defined by devs.
|
|
3721
|
+
* Often times, the user will be using the `fieldName` which could had been customized by the users.
|
|
3722
|
+
* This function helps us get the actual field name useful to match against the schema. (eg: schema[model].fields[field])
|
|
3723
|
+
*
|
|
3724
|
+
* If it's still unclear what this does:
|
|
3725
|
+
*
|
|
3726
|
+
* 1. User can define a custom fieldName.
|
|
3727
|
+
* 2. When using a custom fieldName, doing something like `schema[model].fields[field]` will not work.
|
|
3728
|
+
*/
|
|
3729
|
+
const getDefaultFieldName = ({ field, model: unsafeModel }) => {
|
|
3730
|
+
if (field === "id" || field === "_id") return "id";
|
|
3731
|
+
const model = getDefaultModelName(unsafeModel);
|
|
3732
|
+
let f = schema[model]?.fields[field];
|
|
3733
|
+
if (!f) {
|
|
3734
|
+
const result = Object.entries(schema[model].fields).find(([_, f$1]) => f$1.fieldName === field);
|
|
3735
|
+
if (result) {
|
|
3736
|
+
f = result[1];
|
|
3737
|
+
field = result[0];
|
|
3738
|
+
}
|
|
3739
|
+
}
|
|
3740
|
+
if (!f) throw new BetterAuthError(`Field ${field} not found in model ${model}`);
|
|
3741
|
+
return field;
|
|
3742
|
+
};
|
|
3743
|
+
return getDefaultFieldName;
|
|
3744
|
+
};
|
|
3745
|
+
const initGetFieldName = ({ schema, usePlural }) => {
|
|
3746
|
+
const getDefaultModelName = initGetDefaultModelName({
|
|
3747
|
+
schema,
|
|
3748
|
+
usePlural
|
|
3749
|
+
});
|
|
3750
|
+
const getDefaultFieldName = initGetDefaultFieldName({
|
|
3751
|
+
schema,
|
|
3752
|
+
usePlural
|
|
3753
|
+
});
|
|
3754
|
+
/**
|
|
3755
|
+
* Get the field name which is expected to be saved in the database based on the user's schema.
|
|
3756
|
+
*
|
|
3757
|
+
* This function is useful if you need to save the field name to the database.
|
|
3758
|
+
*
|
|
3759
|
+
* For example, if the user has defined a custom field name for the `user` model, then you can use this function to get the actual field name from the schema.
|
|
3760
|
+
*/
|
|
3761
|
+
function getFieldName({ model: modelName, field: fieldName }) {
|
|
3762
|
+
const model = getDefaultModelName(modelName);
|
|
3763
|
+
const field = getDefaultFieldName({
|
|
3764
|
+
model,
|
|
3765
|
+
field: fieldName
|
|
3766
|
+
});
|
|
3767
|
+
return schema[model]?.fields[field]?.fieldName || field;
|
|
3768
|
+
}
|
|
3769
|
+
return getFieldName;
|
|
3770
|
+
};
|
|
3771
|
+
const initGetModelName = ({ usePlural, schema }) => {
|
|
3772
|
+
const getDefaultModelName = initGetDefaultModelName({
|
|
3773
|
+
schema,
|
|
3774
|
+
usePlural
|
|
3775
|
+
});
|
|
3776
|
+
/**
|
|
3777
|
+
* Users can overwrite the default model of some tables. This function helps find the correct model name.
|
|
3778
|
+
* Furthermore, if the user passes `usePlural` as true in their adapter config,
|
|
3779
|
+
* then we should return the model name ending with an `s`.
|
|
3780
|
+
*/
|
|
3781
|
+
const getModelName = (model) => {
|
|
3782
|
+
const defaultModelKey = getDefaultModelName(model);
|
|
3783
|
+
if (schema && schema[defaultModelKey] && schema[defaultModelKey].modelName !== model) return usePlural ? `${schema[defaultModelKey].modelName}s` : schema[defaultModelKey].modelName;
|
|
3784
|
+
return usePlural ? `${model}s` : model;
|
|
3785
|
+
};
|
|
3786
|
+
return getModelName;
|
|
3787
|
+
};
|
|
3788
|
+
|
|
3789
|
+
//#endregion
|
|
3790
|
+
//#region ../better-auth/dist/json-oFuWgANh.mjs
|
|
3791
|
+
function safeJSONParse(data) {
|
|
3792
|
+
function reviver(_, value) {
|
|
3793
|
+
if (typeof value === "string") {
|
|
3794
|
+
if (/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?Z$/.test(value)) {
|
|
3795
|
+
const date = new Date(value);
|
|
3796
|
+
if (!isNaN(date.getTime())) return date;
|
|
3797
|
+
}
|
|
3798
|
+
}
|
|
3799
|
+
return value;
|
|
3800
|
+
}
|
|
3801
|
+
try {
|
|
3802
|
+
if (typeof data !== "string") return data;
|
|
3803
|
+
return JSON.parse(data, reviver);
|
|
3804
|
+
} catch (e) {
|
|
3805
|
+
logger.error("Error parsing JSON", { error: e });
|
|
3806
|
+
return null;
|
|
3807
|
+
}
|
|
3808
|
+
}
|
|
3809
|
+
|
|
3810
|
+
//#endregion
|
|
3811
|
+
export { abytes$1 as A, exportJWK as B, symmetricEncodeJWT as C, rotlSH as D, rotlBL as E, createHasher as F, getCurrentTransactionAdapter as G, getCurrentAdapter as H, swap32IfBE as I, runWithEndpointContext as J, hasRequestState as K, u32 as L, anumber as M, aoutput$1 as N, rotlSL as O, clean as P, utf8ToBytes$1 as R, symmetricDecodeJWT as S, rotlBH as T, getCurrentAuthContext as U, authorize as V, getCurrentGraphContext as W, runWithRequestState as X, runWithGraphTransaction as Y, withTransaction as Z, symmetricEncrypt as _, initGetFieldName as a, hex as b, generateId as c, constantTimeEqual as d, createHash as f, symmetricDecrypt as g, hashPassword as h, initGetDefaultModelName as i, aexists$1 as j, split as k, generateState as l, generateRandomString as m, getAuthTables as n, initGetModelName as o, createRandomStringGenerator as p, runWithAdapter as q, initGetDefaultFieldName as r, HIDE_METADATA as s, safeJSONParse as t, parseState as u, verifyPassword as v, verifyJWT as w, signJWT as x, getWebcryptoSubtle as y, SignJWT as z };
|