wirejs-deploy-amplify-basic 0.0.15-alpha → 0.0.16-alpha

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,1812 +0,0 @@
1
- // ../../packages/create-wirejs-app/packages/wirejs-resources/lib/services/file.js
2
- import process from "process";
3
- import fs from "fs";
4
- import path from "path";
5
-
6
- // ../../packages/create-wirejs-app/packages/wirejs-resources/lib/resource.js
7
- var Resource = class {
8
- /**
9
- * @type {Resource | string}
10
- */
11
- scope;
12
- /**
13
- * @type {string}
14
- */
15
- id;
16
- /**
17
- *
18
- * @param {Resource | string} scope
19
- * @param {string} id
20
- */
21
- constructor(scope, id) {
22
- this.scope = scope;
23
- this.id = id;
24
- }
25
- get absoluteId() {
26
- const sanitizedId = encodeURIComponent(this.id);
27
- if (typeof this.scope === "string") {
28
- return `${encodeURIComponent(this.scope)}/${sanitizedId}`;
29
- } else if (typeof this.scope?.id === "string") {
30
- return `${this.scope.absoluteId}/${sanitizedId}`;
31
- } else {
32
- throw new Error("Resources must defined within a scope. Provide either a namespace string or parent resource.");
33
- }
34
- }
35
- };
36
-
37
- // ../../packages/create-wirejs-app/packages/wirejs-resources/lib/services/file.js
38
- var CWD = process.cwd();
39
- var ALREADY_EXISTS_CODE = "EEXIST";
40
- var FileService = class extends Resource {
41
- /**
42
- * @param {Resource | string} scope
43
- * @param {string} id
44
- */
45
- constructor(scope, id) {
46
- super(scope, id);
47
- }
48
- /**
49
- * @param {string} filename
50
- * @returns
51
- */
52
- #fullNameFor(filename) {
53
- const sanitizedId = this.absoluteId.replace("~", "-").replace(/\.+/g, ".");
54
- const sanitizedName = filename.replace("~", "-").replace(/\.+/g, ".");
55
- return path.join(CWD, "temp", "wirejs-services", sanitizedId, sanitizedName);
56
- }
57
- /**
58
- * @param {string} filename
59
- * @param {BufferEncoding} [encoding]
60
- * @return {Promise<string>} file data as a string
61
- */
62
- async read(filename, encoding = "utf8") {
63
- return fs.promises.readFile(this.#fullNameFor(filename), { encoding });
64
- }
65
- /**
66
- *
67
- * @param {string} filename
68
- * @param {string} data
69
- * @param {{
70
- * onlyIfNotExists?: boolean;
71
- * }} [options]
72
- */
73
- async write(filename, data, { onlyIfNotExists = false } = {}) {
74
- const fullname = this.#fullNameFor(filename);
75
- const flag = onlyIfNotExists ? "wx" : "w";
76
- await fs.promises.mkdir(path.dirname(fullname), { recursive: true });
77
- return fs.promises.writeFile(fullname, data, { flag });
78
- }
79
- /**
80
- *
81
- * @param {string} filename
82
- */
83
- async delete(filename) {
84
- return fs.promises.unlink(this.#fullNameFor(filename));
85
- }
86
- /**
87
- *
88
- * @param {{
89
- * prefix?: string
90
- * }} [options]
91
- */
92
- async *list({ prefix = "" } = {}) {
93
- const all = await fs.promises.readdir(CWD, { recursive: true });
94
- for (const name of all) {
95
- if (prefix === void 0 || name.startsWith(prefix)) yield name;
96
- }
97
- }
98
- isAlreadyExistsError(error) {
99
- return error.code === ALREADY_EXISTS_CODE;
100
- }
101
- };
102
-
103
- // ../../packages/create-wirejs-app/packages/wirejs-resources/lib/services/authentication.js
104
- import { scrypt, randomBytes } from "crypto";
105
-
106
- // ../../packages/create-wirejs-app/node_modules/jose/dist/node/esm/runtime/base64url.js
107
- import { Buffer as Buffer2 } from "node:buffer";
108
-
109
- // ../../packages/create-wirejs-app/node_modules/jose/dist/node/esm/lib/buffer_utils.js
110
- var encoder = new TextEncoder();
111
- var decoder = new TextDecoder();
112
- var MAX_INT32 = 2 ** 32;
113
- function concat(...buffers) {
114
- const size = buffers.reduce((acc, { length }) => acc + length, 0);
115
- const buf = new Uint8Array(size);
116
- let i = 0;
117
- for (const buffer of buffers) {
118
- buf.set(buffer, i);
119
- i += buffer.length;
120
- }
121
- return buf;
122
- }
123
-
124
- // ../../packages/create-wirejs-app/node_modules/jose/dist/node/esm/runtime/base64url.js
125
- function normalize(input) {
126
- let encoded = input;
127
- if (encoded instanceof Uint8Array) {
128
- encoded = decoder.decode(encoded);
129
- }
130
- return encoded;
131
- }
132
- var encode = (input) => Buffer2.from(input).toString("base64url");
133
- var decode = (input) => new Uint8Array(Buffer2.from(normalize(input), "base64url"));
134
-
135
- // ../../packages/create-wirejs-app/node_modules/jose/dist/node/esm/util/errors.js
136
- var JOSEError = class extends Error {
137
- static code = "ERR_JOSE_GENERIC";
138
- code = "ERR_JOSE_GENERIC";
139
- constructor(message2, options) {
140
- super(message2, options);
141
- this.name = this.constructor.name;
142
- Error.captureStackTrace?.(this, this.constructor);
143
- }
144
- };
145
- var JWTClaimValidationFailed = class extends JOSEError {
146
- static code = "ERR_JWT_CLAIM_VALIDATION_FAILED";
147
- code = "ERR_JWT_CLAIM_VALIDATION_FAILED";
148
- claim;
149
- reason;
150
- payload;
151
- constructor(message2, payload, claim = "unspecified", reason = "unspecified") {
152
- super(message2, { cause: { claim, reason, payload } });
153
- this.claim = claim;
154
- this.reason = reason;
155
- this.payload = payload;
156
- }
157
- };
158
- var JWTExpired = class extends JOSEError {
159
- static code = "ERR_JWT_EXPIRED";
160
- code = "ERR_JWT_EXPIRED";
161
- claim;
162
- reason;
163
- payload;
164
- constructor(message2, payload, claim = "unspecified", reason = "unspecified") {
165
- super(message2, { cause: { claim, reason, payload } });
166
- this.claim = claim;
167
- this.reason = reason;
168
- this.payload = payload;
169
- }
170
- };
171
- var JOSEAlgNotAllowed = class extends JOSEError {
172
- static code = "ERR_JOSE_ALG_NOT_ALLOWED";
173
- code = "ERR_JOSE_ALG_NOT_ALLOWED";
174
- };
175
- var JOSENotSupported = class extends JOSEError {
176
- static code = "ERR_JOSE_NOT_SUPPORTED";
177
- code = "ERR_JOSE_NOT_SUPPORTED";
178
- };
179
- var JWSInvalid = class extends JOSEError {
180
- static code = "ERR_JWS_INVALID";
181
- code = "ERR_JWS_INVALID";
182
- };
183
- var JWTInvalid = class extends JOSEError {
184
- static code = "ERR_JWT_INVALID";
185
- code = "ERR_JWT_INVALID";
186
- };
187
- var JWSSignatureVerificationFailed = class extends JOSEError {
188
- static code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
189
- code = "ERR_JWS_SIGNATURE_VERIFICATION_FAILED";
190
- constructor(message2 = "signature verification failed", options) {
191
- super(message2, options);
192
- }
193
- };
194
-
195
- // ../../packages/create-wirejs-app/node_modules/jose/dist/node/esm/runtime/is_key_object.js
196
- import * as util from "node:util";
197
- var is_key_object_default = (obj) => util.types.isKeyObject(obj);
198
-
199
- // ../../packages/create-wirejs-app/node_modules/jose/dist/node/esm/runtime/webcrypto.js
200
- import * as crypto from "node:crypto";
201
- import * as util2 from "node:util";
202
- var webcrypto2 = crypto.webcrypto;
203
- var webcrypto_default = webcrypto2;
204
- var isCryptoKey = (key) => util2.types.isCryptoKey(key);
205
-
206
- // ../../packages/create-wirejs-app/node_modules/jose/dist/node/esm/lib/crypto_key.js
207
- function unusable(name, prop = "algorithm.name") {
208
- return new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);
209
- }
210
- function isAlgorithm(algorithm, name) {
211
- return algorithm.name === name;
212
- }
213
- function getHashLength(hash2) {
214
- return parseInt(hash2.name.slice(4), 10);
215
- }
216
- function getNamedCurve(alg) {
217
- switch (alg) {
218
- case "ES256":
219
- return "P-256";
220
- case "ES384":
221
- return "P-384";
222
- case "ES512":
223
- return "P-521";
224
- default:
225
- throw new Error("unreachable");
226
- }
227
- }
228
- function checkUsage(key, usages) {
229
- if (usages.length && !usages.some((expected) => key.usages.includes(expected))) {
230
- let msg = "CryptoKey does not support this operation, its usages must include ";
231
- if (usages.length > 2) {
232
- const last = usages.pop();
233
- msg += `one of ${usages.join(", ")}, or ${last}.`;
234
- } else if (usages.length === 2) {
235
- msg += `one of ${usages[0]} or ${usages[1]}.`;
236
- } else {
237
- msg += `${usages[0]}.`;
238
- }
239
- throw new TypeError(msg);
240
- }
241
- }
242
- function checkSigCryptoKey(key, alg, ...usages) {
243
- switch (alg) {
244
- case "HS256":
245
- case "HS384":
246
- case "HS512": {
247
- if (!isAlgorithm(key.algorithm, "HMAC"))
248
- throw unusable("HMAC");
249
- const expected = parseInt(alg.slice(2), 10);
250
- const actual = getHashLength(key.algorithm.hash);
251
- if (actual !== expected)
252
- throw unusable(`SHA-${expected}`, "algorithm.hash");
253
- break;
254
- }
255
- case "RS256":
256
- case "RS384":
257
- case "RS512": {
258
- if (!isAlgorithm(key.algorithm, "RSASSA-PKCS1-v1_5"))
259
- throw unusable("RSASSA-PKCS1-v1_5");
260
- const expected = parseInt(alg.slice(2), 10);
261
- const actual = getHashLength(key.algorithm.hash);
262
- if (actual !== expected)
263
- throw unusable(`SHA-${expected}`, "algorithm.hash");
264
- break;
265
- }
266
- case "PS256":
267
- case "PS384":
268
- case "PS512": {
269
- if (!isAlgorithm(key.algorithm, "RSA-PSS"))
270
- throw unusable("RSA-PSS");
271
- const expected = parseInt(alg.slice(2), 10);
272
- const actual = getHashLength(key.algorithm.hash);
273
- if (actual !== expected)
274
- throw unusable(`SHA-${expected}`, "algorithm.hash");
275
- break;
276
- }
277
- case "EdDSA": {
278
- if (key.algorithm.name !== "Ed25519" && key.algorithm.name !== "Ed448") {
279
- throw unusable("Ed25519 or Ed448");
280
- }
281
- break;
282
- }
283
- case "ES256":
284
- case "ES384":
285
- case "ES512": {
286
- if (!isAlgorithm(key.algorithm, "ECDSA"))
287
- throw unusable("ECDSA");
288
- const expected = getNamedCurve(alg);
289
- const actual = key.algorithm.namedCurve;
290
- if (actual !== expected)
291
- throw unusable(expected, "algorithm.namedCurve");
292
- break;
293
- }
294
- default:
295
- throw new TypeError("CryptoKey does not support this operation");
296
- }
297
- checkUsage(key, usages);
298
- }
299
-
300
- // ../../packages/create-wirejs-app/node_modules/jose/dist/node/esm/lib/invalid_key_input.js
301
- function message(msg, actual, ...types4) {
302
- types4 = types4.filter(Boolean);
303
- if (types4.length > 2) {
304
- const last = types4.pop();
305
- msg += `one of type ${types4.join(", ")}, or ${last}.`;
306
- } else if (types4.length === 2) {
307
- msg += `one of type ${types4[0]} or ${types4[1]}.`;
308
- } else {
309
- msg += `of type ${types4[0]}.`;
310
- }
311
- if (actual == null) {
312
- msg += ` Received ${actual}`;
313
- } else if (typeof actual === "function" && actual.name) {
314
- msg += ` Received function ${actual.name}`;
315
- } else if (typeof actual === "object" && actual != null) {
316
- if (actual.constructor?.name) {
317
- msg += ` Received an instance of ${actual.constructor.name}`;
318
- }
319
- }
320
- return msg;
321
- }
322
- var invalid_key_input_default = (actual, ...types4) => {
323
- return message("Key must be ", actual, ...types4);
324
- };
325
- function withAlg(alg, actual, ...types4) {
326
- return message(`Key for the ${alg} algorithm must be `, actual, ...types4);
327
- }
328
-
329
- // ../../packages/create-wirejs-app/node_modules/jose/dist/node/esm/runtime/is_key_like.js
330
- var is_key_like_default = (key) => is_key_object_default(key) || isCryptoKey(key);
331
- var types3 = ["KeyObject"];
332
- if (globalThis.CryptoKey || webcrypto_default?.CryptoKey) {
333
- types3.push("CryptoKey");
334
- }
335
-
336
- // ../../packages/create-wirejs-app/node_modules/jose/dist/node/esm/lib/is_disjoint.js
337
- var isDisjoint = (...headers) => {
338
- const sources = headers.filter(Boolean);
339
- if (sources.length === 0 || sources.length === 1) {
340
- return true;
341
- }
342
- let acc;
343
- for (const header of sources) {
344
- const parameters = Object.keys(header);
345
- if (!acc || acc.size === 0) {
346
- acc = new Set(parameters);
347
- continue;
348
- }
349
- for (const parameter of parameters) {
350
- if (acc.has(parameter)) {
351
- return false;
352
- }
353
- acc.add(parameter);
354
- }
355
- }
356
- return true;
357
- };
358
- var is_disjoint_default = isDisjoint;
359
-
360
- // ../../packages/create-wirejs-app/node_modules/jose/dist/node/esm/lib/is_object.js
361
- function isObjectLike(value) {
362
- return typeof value === "object" && value !== null;
363
- }
364
- function isObject(input) {
365
- if (!isObjectLike(input) || Object.prototype.toString.call(input) !== "[object Object]") {
366
- return false;
367
- }
368
- if (Object.getPrototypeOf(input) === null) {
369
- return true;
370
- }
371
- let proto = input;
372
- while (Object.getPrototypeOf(proto) !== null) {
373
- proto = Object.getPrototypeOf(proto);
374
- }
375
- return Object.getPrototypeOf(input) === proto;
376
- }
377
-
378
- // ../../packages/create-wirejs-app/node_modules/jose/dist/node/esm/runtime/get_named_curve.js
379
- import { KeyObject } from "node:crypto";
380
-
381
- // ../../packages/create-wirejs-app/node_modules/jose/dist/node/esm/lib/is_jwk.js
382
- function isJWK(key) {
383
- return isObject(key) && typeof key.kty === "string";
384
- }
385
- function isPrivateJWK(key) {
386
- return key.kty !== "oct" && typeof key.d === "string";
387
- }
388
- function isPublicJWK(key) {
389
- return key.kty !== "oct" && typeof key.d === "undefined";
390
- }
391
- function isSecretJWK(key) {
392
- return isJWK(key) && key.kty === "oct" && typeof key.k === "string";
393
- }
394
-
395
- // ../../packages/create-wirejs-app/node_modules/jose/dist/node/esm/runtime/get_named_curve.js
396
- var namedCurveToJOSE = (namedCurve) => {
397
- switch (namedCurve) {
398
- case "prime256v1":
399
- return "P-256";
400
- case "secp384r1":
401
- return "P-384";
402
- case "secp521r1":
403
- return "P-521";
404
- case "secp256k1":
405
- return "secp256k1";
406
- default:
407
- throw new JOSENotSupported("Unsupported key curve for this operation");
408
- }
409
- };
410
- var getNamedCurve2 = (kee, raw) => {
411
- let key;
412
- if (isCryptoKey(kee)) {
413
- key = KeyObject.from(kee);
414
- } else if (is_key_object_default(kee)) {
415
- key = kee;
416
- } else if (isJWK(kee)) {
417
- return kee.crv;
418
- } else {
419
- throw new TypeError(invalid_key_input_default(kee, ...types3));
420
- }
421
- if (key.type === "secret") {
422
- throw new TypeError('only "private" or "public" type keys can be used for this operation');
423
- }
424
- switch (key.asymmetricKeyType) {
425
- case "ed25519":
426
- case "ed448":
427
- return `Ed${key.asymmetricKeyType.slice(2)}`;
428
- case "x25519":
429
- case "x448":
430
- return `X${key.asymmetricKeyType.slice(1)}`;
431
- case "ec": {
432
- const namedCurve = key.asymmetricKeyDetails.namedCurve;
433
- if (raw) {
434
- return namedCurve;
435
- }
436
- return namedCurveToJOSE(namedCurve);
437
- }
438
- default:
439
- throw new TypeError("Invalid asymmetric key type for this operation");
440
- }
441
- };
442
- var get_named_curve_default = getNamedCurve2;
443
-
444
- // ../../packages/create-wirejs-app/node_modules/jose/dist/node/esm/runtime/check_key_length.js
445
- import { KeyObject as KeyObject2 } from "node:crypto";
446
- var check_key_length_default = (key, alg) => {
447
- let modulusLength;
448
- try {
449
- if (key instanceof KeyObject2) {
450
- modulusLength = key.asymmetricKeyDetails?.modulusLength;
451
- } else {
452
- modulusLength = Buffer.from(key.n, "base64url").byteLength << 3;
453
- }
454
- } catch {
455
- }
456
- if (typeof modulusLength !== "number" || modulusLength < 2048) {
457
- throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);
458
- }
459
- };
460
-
461
- // ../../packages/create-wirejs-app/node_modules/jose/dist/node/esm/runtime/jwk_to_key.js
462
- import { createPrivateKey, createPublicKey } from "node:crypto";
463
- var parse = (key) => {
464
- if (key.d) {
465
- return createPrivateKey({ format: "jwk", key });
466
- }
467
- return createPublicKey({ format: "jwk", key });
468
- };
469
- var jwk_to_key_default = parse;
470
-
471
- // ../../packages/create-wirejs-app/node_modules/jose/dist/node/esm/key/import.js
472
- async function importJWK(jwk, alg) {
473
- if (!isObject(jwk)) {
474
- throw new TypeError("JWK must be an object");
475
- }
476
- alg ||= jwk.alg;
477
- switch (jwk.kty) {
478
- case "oct":
479
- if (typeof jwk.k !== "string" || !jwk.k) {
480
- throw new TypeError('missing "k" (Key Value) Parameter value');
481
- }
482
- return decode(jwk.k);
483
- case "RSA":
484
- if (jwk.oth !== void 0) {
485
- throw new JOSENotSupported('RSA JWK "oth" (Other Primes Info) Parameter value is not supported');
486
- }
487
- case "EC":
488
- case "OKP":
489
- return jwk_to_key_default({ ...jwk, alg });
490
- default:
491
- throw new JOSENotSupported('Unsupported "kty" (Key Type) Parameter value');
492
- }
493
- }
494
-
495
- // ../../packages/create-wirejs-app/node_modules/jose/dist/node/esm/lib/check_key_type.js
496
- var tag = (key) => key?.[Symbol.toStringTag];
497
- var jwkMatchesOp = (alg, key, usage) => {
498
- if (key.use !== void 0 && key.use !== "sig") {
499
- throw new TypeError("Invalid key for this operation, when present its use must be sig");
500
- }
501
- if (key.key_ops !== void 0 && key.key_ops.includes?.(usage) !== true) {
502
- throw new TypeError(`Invalid key for this operation, when present its key_ops must include ${usage}`);
503
- }
504
- if (key.alg !== void 0 && key.alg !== alg) {
505
- throw new TypeError(`Invalid key for this operation, when present its alg must be ${alg}`);
506
- }
507
- return true;
508
- };
509
- var symmetricTypeCheck = (alg, key, usage, allowJwk) => {
510
- if (key instanceof Uint8Array)
511
- return;
512
- if (allowJwk && isJWK(key)) {
513
- if (isSecretJWK(key) && jwkMatchesOp(alg, key, usage))
514
- return;
515
- throw new TypeError(`JSON Web Key for symmetric algorithms must have JWK "kty" (Key Type) equal to "oct" and the JWK "k" (Key Value) present`);
516
- }
517
- if (!is_key_like_default(key)) {
518
- throw new TypeError(withAlg(alg, key, ...types3, "Uint8Array", allowJwk ? "JSON Web Key" : null));
519
- }
520
- if (key.type !== "secret") {
521
- throw new TypeError(`${tag(key)} instances for symmetric algorithms must be of type "secret"`);
522
- }
523
- };
524
- var asymmetricTypeCheck = (alg, key, usage, allowJwk) => {
525
- if (allowJwk && isJWK(key)) {
526
- switch (usage) {
527
- case "sign":
528
- if (isPrivateJWK(key) && jwkMatchesOp(alg, key, usage))
529
- return;
530
- throw new TypeError(`JSON Web Key for this operation be a private JWK`);
531
- case "verify":
532
- if (isPublicJWK(key) && jwkMatchesOp(alg, key, usage))
533
- return;
534
- throw new TypeError(`JSON Web Key for this operation be a public JWK`);
535
- }
536
- }
537
- if (!is_key_like_default(key)) {
538
- throw new TypeError(withAlg(alg, key, ...types3, allowJwk ? "JSON Web Key" : null));
539
- }
540
- if (key.type === "secret") {
541
- throw new TypeError(`${tag(key)} instances for asymmetric algorithms must not be of type "secret"`);
542
- }
543
- if (usage === "sign" && key.type === "public") {
544
- throw new TypeError(`${tag(key)} instances for asymmetric algorithm signing must be of type "private"`);
545
- }
546
- if (usage === "decrypt" && key.type === "public") {
547
- throw new TypeError(`${tag(key)} instances for asymmetric algorithm decryption must be of type "private"`);
548
- }
549
- if (key.algorithm && usage === "verify" && key.type === "private") {
550
- throw new TypeError(`${tag(key)} instances for asymmetric algorithm verifying must be of type "public"`);
551
- }
552
- if (key.algorithm && usage === "encrypt" && key.type === "private") {
553
- throw new TypeError(`${tag(key)} instances for asymmetric algorithm encryption must be of type "public"`);
554
- }
555
- };
556
- function checkKeyType(allowJwk, alg, key, usage) {
557
- const symmetric = alg.startsWith("HS") || alg === "dir" || alg.startsWith("PBES2") || /^A\d{3}(?:GCM)?KW$/.test(alg);
558
- if (symmetric) {
559
- symmetricTypeCheck(alg, key, usage, allowJwk);
560
- } else {
561
- asymmetricTypeCheck(alg, key, usage, allowJwk);
562
- }
563
- }
564
- var check_key_type_default = checkKeyType.bind(void 0, false);
565
- var checkKeyTypeWithJwk = checkKeyType.bind(void 0, true);
566
-
567
- // ../../packages/create-wirejs-app/node_modules/jose/dist/node/esm/lib/validate_crit.js
568
- function validateCrit(Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader) {
569
- if (joseHeader.crit !== void 0 && protectedHeader?.crit === void 0) {
570
- throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected');
571
- }
572
- if (!protectedHeader || protectedHeader.crit === void 0) {
573
- return /* @__PURE__ */ new Set();
574
- }
575
- if (!Array.isArray(protectedHeader.crit) || protectedHeader.crit.length === 0 || protectedHeader.crit.some((input) => typeof input !== "string" || input.length === 0)) {
576
- throw new Err('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');
577
- }
578
- let recognized;
579
- if (recognizedOption !== void 0) {
580
- recognized = new Map([...Object.entries(recognizedOption), ...recognizedDefault.entries()]);
581
- } else {
582
- recognized = recognizedDefault;
583
- }
584
- for (const parameter of protectedHeader.crit) {
585
- if (!recognized.has(parameter)) {
586
- throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`);
587
- }
588
- if (joseHeader[parameter] === void 0) {
589
- throw new Err(`Extension Header Parameter "${parameter}" is missing`);
590
- }
591
- if (recognized.get(parameter) && protectedHeader[parameter] === void 0) {
592
- throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`);
593
- }
594
- }
595
- return new Set(protectedHeader.crit);
596
- }
597
- var validate_crit_default = validateCrit;
598
-
599
- // ../../packages/create-wirejs-app/node_modules/jose/dist/node/esm/lib/validate_algorithms.js
600
- var validateAlgorithms = (option, algorithms) => {
601
- if (algorithms !== void 0 && (!Array.isArray(algorithms) || algorithms.some((s) => typeof s !== "string"))) {
602
- throw new TypeError(`"${option}" option must be an array of strings`);
603
- }
604
- if (!algorithms) {
605
- return void 0;
606
- }
607
- return new Set(algorithms);
608
- };
609
- var validate_algorithms_default = validateAlgorithms;
610
-
611
- // ../../packages/create-wirejs-app/node_modules/jose/dist/node/esm/runtime/verify.js
612
- import * as crypto3 from "node:crypto";
613
- import { promisify as promisify2 } from "node:util";
614
-
615
- // ../../packages/create-wirejs-app/node_modules/jose/dist/node/esm/runtime/dsa_digest.js
616
- function dsaDigest(alg) {
617
- switch (alg) {
618
- case "PS256":
619
- case "RS256":
620
- case "ES256":
621
- case "ES256K":
622
- return "sha256";
623
- case "PS384":
624
- case "RS384":
625
- case "ES384":
626
- return "sha384";
627
- case "PS512":
628
- case "RS512":
629
- case "ES512":
630
- return "sha512";
631
- case "EdDSA":
632
- return void 0;
633
- default:
634
- throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
635
- }
636
- }
637
-
638
- // ../../packages/create-wirejs-app/node_modules/jose/dist/node/esm/runtime/node_key.js
639
- import { constants, KeyObject as KeyObject3 } from "node:crypto";
640
- var ecCurveAlgMap = /* @__PURE__ */ new Map([
641
- ["ES256", "P-256"],
642
- ["ES256K", "secp256k1"],
643
- ["ES384", "P-384"],
644
- ["ES512", "P-521"]
645
- ]);
646
- function keyForCrypto(alg, key) {
647
- let asymmetricKeyType;
648
- let asymmetricKeyDetails;
649
- let isJWK2;
650
- if (key instanceof KeyObject3) {
651
- asymmetricKeyType = key.asymmetricKeyType;
652
- asymmetricKeyDetails = key.asymmetricKeyDetails;
653
- } else {
654
- isJWK2 = true;
655
- switch (key.kty) {
656
- case "RSA":
657
- asymmetricKeyType = "rsa";
658
- break;
659
- case "EC":
660
- asymmetricKeyType = "ec";
661
- break;
662
- case "OKP": {
663
- if (key.crv === "Ed25519") {
664
- asymmetricKeyType = "ed25519";
665
- break;
666
- }
667
- if (key.crv === "Ed448") {
668
- asymmetricKeyType = "ed448";
669
- break;
670
- }
671
- throw new TypeError("Invalid key for this operation, its crv must be Ed25519 or Ed448");
672
- }
673
- default:
674
- throw new TypeError("Invalid key for this operation, its kty must be RSA, OKP, or EC");
675
- }
676
- }
677
- let options;
678
- switch (alg) {
679
- case "EdDSA":
680
- if (!["ed25519", "ed448"].includes(asymmetricKeyType)) {
681
- throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ed25519 or ed448");
682
- }
683
- break;
684
- case "RS256":
685
- case "RS384":
686
- case "RS512":
687
- if (asymmetricKeyType !== "rsa") {
688
- throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa");
689
- }
690
- check_key_length_default(key, alg);
691
- break;
692
- case "PS256":
693
- case "PS384":
694
- case "PS512":
695
- if (asymmetricKeyType === "rsa-pss") {
696
- const { hashAlgorithm, mgf1HashAlgorithm, saltLength } = asymmetricKeyDetails;
697
- const length = parseInt(alg.slice(-3), 10);
698
- if (hashAlgorithm !== void 0 && (hashAlgorithm !== `sha${length}` || mgf1HashAlgorithm !== hashAlgorithm)) {
699
- throw new TypeError(`Invalid key for this operation, its RSA-PSS parameters do not meet the requirements of "alg" ${alg}`);
700
- }
701
- if (saltLength !== void 0 && saltLength > length >> 3) {
702
- throw new TypeError(`Invalid key for this operation, its RSA-PSS parameter saltLength does not meet the requirements of "alg" ${alg}`);
703
- }
704
- } else if (asymmetricKeyType !== "rsa") {
705
- throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be rsa or rsa-pss");
706
- }
707
- check_key_length_default(key, alg);
708
- options = {
709
- padding: constants.RSA_PKCS1_PSS_PADDING,
710
- saltLength: constants.RSA_PSS_SALTLEN_DIGEST
711
- };
712
- break;
713
- case "ES256":
714
- case "ES256K":
715
- case "ES384":
716
- case "ES512": {
717
- if (asymmetricKeyType !== "ec") {
718
- throw new TypeError("Invalid key for this operation, its asymmetricKeyType must be ec");
719
- }
720
- const actual = get_named_curve_default(key);
721
- const expected = ecCurveAlgMap.get(alg);
722
- if (actual !== expected) {
723
- throw new TypeError(`Invalid key curve for the algorithm, its curve must be ${expected}, got ${actual}`);
724
- }
725
- options = { dsaEncoding: "ieee-p1363" };
726
- break;
727
- }
728
- default:
729
- throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
730
- }
731
- if (isJWK2) {
732
- return { format: "jwk", key, ...options };
733
- }
734
- return options ? { ...options, key } : key;
735
- }
736
-
737
- // ../../packages/create-wirejs-app/node_modules/jose/dist/node/esm/runtime/sign.js
738
- import * as crypto2 from "node:crypto";
739
- import { promisify } from "node:util";
740
-
741
- // ../../packages/create-wirejs-app/node_modules/jose/dist/node/esm/runtime/hmac_digest.js
742
- function hmacDigest(alg) {
743
- switch (alg) {
744
- case "HS256":
745
- return "sha256";
746
- case "HS384":
747
- return "sha384";
748
- case "HS512":
749
- return "sha512";
750
- default:
751
- throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
752
- }
753
- }
754
-
755
- // ../../packages/create-wirejs-app/node_modules/jose/dist/node/esm/runtime/get_sign_verify_key.js
756
- import { KeyObject as KeyObject4, createSecretKey } from "node:crypto";
757
- function getSignVerifyKey(alg, key, usage) {
758
- if (key instanceof Uint8Array) {
759
- if (!alg.startsWith("HS")) {
760
- throw new TypeError(invalid_key_input_default(key, ...types3));
761
- }
762
- return createSecretKey(key);
763
- }
764
- if (key instanceof KeyObject4) {
765
- return key;
766
- }
767
- if (isCryptoKey(key)) {
768
- checkSigCryptoKey(key, alg, usage);
769
- return KeyObject4.from(key);
770
- }
771
- if (isJWK(key)) {
772
- if (alg.startsWith("HS")) {
773
- return createSecretKey(Buffer.from(key.k, "base64url"));
774
- }
775
- return key;
776
- }
777
- throw new TypeError(invalid_key_input_default(key, ...types3, "Uint8Array", "JSON Web Key"));
778
- }
779
-
780
- // ../../packages/create-wirejs-app/node_modules/jose/dist/node/esm/runtime/sign.js
781
- var oneShotSign = promisify(crypto2.sign);
782
- var sign2 = async (alg, key, data) => {
783
- const k = getSignVerifyKey(alg, key, "sign");
784
- if (alg.startsWith("HS")) {
785
- const hmac = crypto2.createHmac(hmacDigest(alg), k);
786
- hmac.update(data);
787
- return hmac.digest();
788
- }
789
- return oneShotSign(dsaDigest(alg), data, keyForCrypto(alg, k));
790
- };
791
- var sign_default = sign2;
792
-
793
- // ../../packages/create-wirejs-app/node_modules/jose/dist/node/esm/runtime/verify.js
794
- var oneShotVerify = promisify2(crypto3.verify);
795
- var verify2 = async (alg, key, signature, data) => {
796
- const k = getSignVerifyKey(alg, key, "verify");
797
- if (alg.startsWith("HS")) {
798
- const expected = await sign_default(alg, k, data);
799
- const actual = signature;
800
- try {
801
- return crypto3.timingSafeEqual(actual, expected);
802
- } catch {
803
- return false;
804
- }
805
- }
806
- const algorithm = dsaDigest(alg);
807
- const keyInput = keyForCrypto(alg, k);
808
- try {
809
- return await oneShotVerify(algorithm, data, keyInput, signature);
810
- } catch {
811
- return false;
812
- }
813
- };
814
- var verify_default = verify2;
815
-
816
- // ../../packages/create-wirejs-app/node_modules/jose/dist/node/esm/jws/flattened/verify.js
817
- async function flattenedVerify(jws, key, options) {
818
- if (!isObject(jws)) {
819
- throw new JWSInvalid("Flattened JWS must be an object");
820
- }
821
- if (jws.protected === void 0 && jws.header === void 0) {
822
- throw new JWSInvalid('Flattened JWS must have either of the "protected" or "header" members');
823
- }
824
- if (jws.protected !== void 0 && typeof jws.protected !== "string") {
825
- throw new JWSInvalid("JWS Protected Header incorrect type");
826
- }
827
- if (jws.payload === void 0) {
828
- throw new JWSInvalid("JWS Payload missing");
829
- }
830
- if (typeof jws.signature !== "string") {
831
- throw new JWSInvalid("JWS Signature missing or incorrect type");
832
- }
833
- if (jws.header !== void 0 && !isObject(jws.header)) {
834
- throw new JWSInvalid("JWS Unprotected Header incorrect type");
835
- }
836
- let parsedProt = {};
837
- if (jws.protected) {
838
- try {
839
- const protectedHeader = decode(jws.protected);
840
- parsedProt = JSON.parse(decoder.decode(protectedHeader));
841
- } catch {
842
- throw new JWSInvalid("JWS Protected Header is invalid");
843
- }
844
- }
845
- if (!is_disjoint_default(parsedProt, jws.header)) {
846
- throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
847
- }
848
- const joseHeader = {
849
- ...parsedProt,
850
- ...jws.header
851
- };
852
- const extensions = validate_crit_default(JWSInvalid, /* @__PURE__ */ new Map([["b64", true]]), options?.crit, parsedProt, joseHeader);
853
- let b64 = true;
854
- if (extensions.has("b64")) {
855
- b64 = parsedProt.b64;
856
- if (typeof b64 !== "boolean") {
857
- throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');
858
- }
859
- }
860
- const { alg } = joseHeader;
861
- if (typeof alg !== "string" || !alg) {
862
- throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');
863
- }
864
- const algorithms = options && validate_algorithms_default("algorithms", options.algorithms);
865
- if (algorithms && !algorithms.has(alg)) {
866
- throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed');
867
- }
868
- if (b64) {
869
- if (typeof jws.payload !== "string") {
870
- throw new JWSInvalid("JWS Payload must be a string");
871
- }
872
- } else if (typeof jws.payload !== "string" && !(jws.payload instanceof Uint8Array)) {
873
- throw new JWSInvalid("JWS Payload must be a string or an Uint8Array instance");
874
- }
875
- let resolvedKey = false;
876
- if (typeof key === "function") {
877
- key = await key(parsedProt, jws);
878
- resolvedKey = true;
879
- checkKeyTypeWithJwk(alg, key, "verify");
880
- if (isJWK(key)) {
881
- key = await importJWK(key, alg);
882
- }
883
- } else {
884
- checkKeyTypeWithJwk(alg, key, "verify");
885
- }
886
- const data = concat(encoder.encode(jws.protected ?? ""), encoder.encode("."), typeof jws.payload === "string" ? encoder.encode(jws.payload) : jws.payload);
887
- let signature;
888
- try {
889
- signature = decode(jws.signature);
890
- } catch {
891
- throw new JWSInvalid("Failed to base64url decode the signature");
892
- }
893
- const verified = await verify_default(alg, key, signature, data);
894
- if (!verified) {
895
- throw new JWSSignatureVerificationFailed();
896
- }
897
- let payload;
898
- if (b64) {
899
- try {
900
- payload = decode(jws.payload);
901
- } catch {
902
- throw new JWSInvalid("Failed to base64url decode the payload");
903
- }
904
- } else if (typeof jws.payload === "string") {
905
- payload = encoder.encode(jws.payload);
906
- } else {
907
- payload = jws.payload;
908
- }
909
- const result = { payload };
910
- if (jws.protected !== void 0) {
911
- result.protectedHeader = parsedProt;
912
- }
913
- if (jws.header !== void 0) {
914
- result.unprotectedHeader = jws.header;
915
- }
916
- if (resolvedKey) {
917
- return { ...result, key };
918
- }
919
- return result;
920
- }
921
-
922
- // ../../packages/create-wirejs-app/node_modules/jose/dist/node/esm/jws/compact/verify.js
923
- async function compactVerify(jws, key, options) {
924
- if (jws instanceof Uint8Array) {
925
- jws = decoder.decode(jws);
926
- }
927
- if (typeof jws !== "string") {
928
- throw new JWSInvalid("Compact JWS must be a string or Uint8Array");
929
- }
930
- const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split(".");
931
- if (length !== 3) {
932
- throw new JWSInvalid("Invalid Compact JWS");
933
- }
934
- const verified = await flattenedVerify({ payload, protected: protectedHeader, signature }, key, options);
935
- const result = { payload: verified.payload, protectedHeader: verified.protectedHeader };
936
- if (typeof key === "function") {
937
- return { ...result, key: verified.key };
938
- }
939
- return result;
940
- }
941
-
942
- // ../../packages/create-wirejs-app/node_modules/jose/dist/node/esm/lib/epoch.js
943
- var epoch_default = (date) => Math.floor(date.getTime() / 1e3);
944
-
945
- // ../../packages/create-wirejs-app/node_modules/jose/dist/node/esm/lib/secs.js
946
- var minute = 60;
947
- var hour = minute * 60;
948
- var day = hour * 24;
949
- var week = day * 7;
950
- var year = day * 365.25;
951
- var REGEX = /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;
952
- var secs_default = (str) => {
953
- const matched = REGEX.exec(str);
954
- if (!matched || matched[4] && matched[1]) {
955
- throw new TypeError("Invalid time period format");
956
- }
957
- const value = parseFloat(matched[2]);
958
- const unit = matched[3].toLowerCase();
959
- let numericDate;
960
- switch (unit) {
961
- case "sec":
962
- case "secs":
963
- case "second":
964
- case "seconds":
965
- case "s":
966
- numericDate = Math.round(value);
967
- break;
968
- case "minute":
969
- case "minutes":
970
- case "min":
971
- case "mins":
972
- case "m":
973
- numericDate = Math.round(value * minute);
974
- break;
975
- case "hour":
976
- case "hours":
977
- case "hr":
978
- case "hrs":
979
- case "h":
980
- numericDate = Math.round(value * hour);
981
- break;
982
- case "day":
983
- case "days":
984
- case "d":
985
- numericDate = Math.round(value * day);
986
- break;
987
- case "week":
988
- case "weeks":
989
- case "w":
990
- numericDate = Math.round(value * week);
991
- break;
992
- default:
993
- numericDate = Math.round(value * year);
994
- break;
995
- }
996
- if (matched[1] === "-" || matched[4] === "ago") {
997
- return -numericDate;
998
- }
999
- return numericDate;
1000
- };
1001
-
1002
- // ../../packages/create-wirejs-app/node_modules/jose/dist/node/esm/lib/jwt_claims_set.js
1003
- var normalizeTyp = (value) => value.toLowerCase().replace(/^application\//, "");
1004
- var checkAudiencePresence = (audPayload, audOption) => {
1005
- if (typeof audPayload === "string") {
1006
- return audOption.includes(audPayload);
1007
- }
1008
- if (Array.isArray(audPayload)) {
1009
- return audOption.some(Set.prototype.has.bind(new Set(audPayload)));
1010
- }
1011
- return false;
1012
- };
1013
- var jwt_claims_set_default = (protectedHeader, encodedPayload, options = {}) => {
1014
- let payload;
1015
- try {
1016
- payload = JSON.parse(decoder.decode(encodedPayload));
1017
- } catch {
1018
- }
1019
- if (!isObject(payload)) {
1020
- throw new JWTInvalid("JWT Claims Set must be a top-level JSON object");
1021
- }
1022
- const { typ } = options;
1023
- if (typ && (typeof protectedHeader.typ !== "string" || normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) {
1024
- throw new JWTClaimValidationFailed('unexpected "typ" JWT header value', payload, "typ", "check_failed");
1025
- }
1026
- const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options;
1027
- const presenceCheck = [...requiredClaims];
1028
- if (maxTokenAge !== void 0)
1029
- presenceCheck.push("iat");
1030
- if (audience !== void 0)
1031
- presenceCheck.push("aud");
1032
- if (subject !== void 0)
1033
- presenceCheck.push("sub");
1034
- if (issuer !== void 0)
1035
- presenceCheck.push("iss");
1036
- for (const claim of new Set(presenceCheck.reverse())) {
1037
- if (!(claim in payload)) {
1038
- throw new JWTClaimValidationFailed(`missing required "${claim}" claim`, payload, claim, "missing");
1039
- }
1040
- }
1041
- if (issuer && !(Array.isArray(issuer) ? issuer : [issuer]).includes(payload.iss)) {
1042
- throw new JWTClaimValidationFailed('unexpected "iss" claim value', payload, "iss", "check_failed");
1043
- }
1044
- if (subject && payload.sub !== subject) {
1045
- throw new JWTClaimValidationFailed('unexpected "sub" claim value', payload, "sub", "check_failed");
1046
- }
1047
- if (audience && !checkAudiencePresence(payload.aud, typeof audience === "string" ? [audience] : audience)) {
1048
- throw new JWTClaimValidationFailed('unexpected "aud" claim value', payload, "aud", "check_failed");
1049
- }
1050
- let tolerance;
1051
- switch (typeof options.clockTolerance) {
1052
- case "string":
1053
- tolerance = secs_default(options.clockTolerance);
1054
- break;
1055
- case "number":
1056
- tolerance = options.clockTolerance;
1057
- break;
1058
- case "undefined":
1059
- tolerance = 0;
1060
- break;
1061
- default:
1062
- throw new TypeError("Invalid clockTolerance option type");
1063
- }
1064
- const { currentDate } = options;
1065
- const now = epoch_default(currentDate || /* @__PURE__ */ new Date());
1066
- if ((payload.iat !== void 0 || maxTokenAge) && typeof payload.iat !== "number") {
1067
- throw new JWTClaimValidationFailed('"iat" claim must be a number', payload, "iat", "invalid");
1068
- }
1069
- if (payload.nbf !== void 0) {
1070
- if (typeof payload.nbf !== "number") {
1071
- throw new JWTClaimValidationFailed('"nbf" claim must be a number', payload, "nbf", "invalid");
1072
- }
1073
- if (payload.nbf > now + tolerance) {
1074
- throw new JWTClaimValidationFailed('"nbf" claim timestamp check failed', payload, "nbf", "check_failed");
1075
- }
1076
- }
1077
- if (payload.exp !== void 0) {
1078
- if (typeof payload.exp !== "number") {
1079
- throw new JWTClaimValidationFailed('"exp" claim must be a number', payload, "exp", "invalid");
1080
- }
1081
- if (payload.exp <= now - tolerance) {
1082
- throw new JWTExpired('"exp" claim timestamp check failed', payload, "exp", "check_failed");
1083
- }
1084
- }
1085
- if (maxTokenAge) {
1086
- const age = now - payload.iat;
1087
- const max = typeof maxTokenAge === "number" ? maxTokenAge : secs_default(maxTokenAge);
1088
- if (age - tolerance > max) {
1089
- throw new JWTExpired('"iat" claim timestamp check failed (too far in the past)', payload, "iat", "check_failed");
1090
- }
1091
- if (age < 0 - tolerance) {
1092
- throw new JWTClaimValidationFailed('"iat" claim timestamp check failed (it should be in the past)', payload, "iat", "check_failed");
1093
- }
1094
- }
1095
- return payload;
1096
- };
1097
-
1098
- // ../../packages/create-wirejs-app/node_modules/jose/dist/node/esm/jwt/verify.js
1099
- async function jwtVerify(jwt, key, options) {
1100
- const verified = await compactVerify(jwt, key, options);
1101
- if (verified.protectedHeader.crit?.includes("b64") && verified.protectedHeader.b64 === false) {
1102
- throw new JWTInvalid("JWTs MUST NOT use unencoded payload");
1103
- }
1104
- const payload = jwt_claims_set_default(verified.protectedHeader, verified.payload, options);
1105
- const result = { payload, protectedHeader: verified.protectedHeader };
1106
- if (typeof key === "function") {
1107
- return { ...result, key: verified.key };
1108
- }
1109
- return result;
1110
- }
1111
-
1112
- // ../../packages/create-wirejs-app/node_modules/jose/dist/node/esm/jws/flattened/sign.js
1113
- var FlattenedSign = class {
1114
- _payload;
1115
- _protectedHeader;
1116
- _unprotectedHeader;
1117
- constructor(payload) {
1118
- if (!(payload instanceof Uint8Array)) {
1119
- throw new TypeError("payload must be an instance of Uint8Array");
1120
- }
1121
- this._payload = payload;
1122
- }
1123
- setProtectedHeader(protectedHeader) {
1124
- if (this._protectedHeader) {
1125
- throw new TypeError("setProtectedHeader can only be called once");
1126
- }
1127
- this._protectedHeader = protectedHeader;
1128
- return this;
1129
- }
1130
- setUnprotectedHeader(unprotectedHeader) {
1131
- if (this._unprotectedHeader) {
1132
- throw new TypeError("setUnprotectedHeader can only be called once");
1133
- }
1134
- this._unprotectedHeader = unprotectedHeader;
1135
- return this;
1136
- }
1137
- async sign(key, options) {
1138
- if (!this._protectedHeader && !this._unprotectedHeader) {
1139
- throw new JWSInvalid("either setProtectedHeader or setUnprotectedHeader must be called before #sign()");
1140
- }
1141
- if (!is_disjoint_default(this._protectedHeader, this._unprotectedHeader)) {
1142
- throw new JWSInvalid("JWS Protected and JWS Unprotected Header Parameter names must be disjoint");
1143
- }
1144
- const joseHeader = {
1145
- ...this._protectedHeader,
1146
- ...this._unprotectedHeader
1147
- };
1148
- const extensions = validate_crit_default(JWSInvalid, /* @__PURE__ */ new Map([["b64", true]]), options?.crit, this._protectedHeader, joseHeader);
1149
- let b64 = true;
1150
- if (extensions.has("b64")) {
1151
- b64 = this._protectedHeader.b64;
1152
- if (typeof b64 !== "boolean") {
1153
- throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');
1154
- }
1155
- }
1156
- const { alg } = joseHeader;
1157
- if (typeof alg !== "string" || !alg) {
1158
- throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');
1159
- }
1160
- checkKeyTypeWithJwk(alg, key, "sign");
1161
- let payload = this._payload;
1162
- if (b64) {
1163
- payload = encoder.encode(encode(payload));
1164
- }
1165
- let protectedHeader;
1166
- if (this._protectedHeader) {
1167
- protectedHeader = encoder.encode(encode(JSON.stringify(this._protectedHeader)));
1168
- } else {
1169
- protectedHeader = encoder.encode("");
1170
- }
1171
- const data = concat(protectedHeader, encoder.encode("."), payload);
1172
- const signature = await sign_default(alg, key, data);
1173
- const jws = {
1174
- signature: encode(signature),
1175
- payload: ""
1176
- };
1177
- if (b64) {
1178
- jws.payload = decoder.decode(payload);
1179
- }
1180
- if (this._unprotectedHeader) {
1181
- jws.header = this._unprotectedHeader;
1182
- }
1183
- if (this._protectedHeader) {
1184
- jws.protected = decoder.decode(protectedHeader);
1185
- }
1186
- return jws;
1187
- }
1188
- };
1189
-
1190
- // ../../packages/create-wirejs-app/node_modules/jose/dist/node/esm/jws/compact/sign.js
1191
- var CompactSign = class {
1192
- _flattened;
1193
- constructor(payload) {
1194
- this._flattened = new FlattenedSign(payload);
1195
- }
1196
- setProtectedHeader(protectedHeader) {
1197
- this._flattened.setProtectedHeader(protectedHeader);
1198
- return this;
1199
- }
1200
- async sign(key, options) {
1201
- const jws = await this._flattened.sign(key, options);
1202
- if (jws.payload === void 0) {
1203
- throw new TypeError("use the flattened module for creating JWS with b64: false");
1204
- }
1205
- return `${jws.protected}.${jws.payload}.${jws.signature}`;
1206
- }
1207
- };
1208
-
1209
- // ../../packages/create-wirejs-app/node_modules/jose/dist/node/esm/jwt/produce.js
1210
- function validateInput(label, input) {
1211
- if (!Number.isFinite(input)) {
1212
- throw new TypeError(`Invalid ${label} input`);
1213
- }
1214
- return input;
1215
- }
1216
- var ProduceJWT = class {
1217
- _payload;
1218
- constructor(payload = {}) {
1219
- if (!isObject(payload)) {
1220
- throw new TypeError("JWT Claims Set MUST be an object");
1221
- }
1222
- this._payload = payload;
1223
- }
1224
- setIssuer(issuer) {
1225
- this._payload = { ...this._payload, iss: issuer };
1226
- return this;
1227
- }
1228
- setSubject(subject) {
1229
- this._payload = { ...this._payload, sub: subject };
1230
- return this;
1231
- }
1232
- setAudience(audience) {
1233
- this._payload = { ...this._payload, aud: audience };
1234
- return this;
1235
- }
1236
- setJti(jwtId) {
1237
- this._payload = { ...this._payload, jti: jwtId };
1238
- return this;
1239
- }
1240
- setNotBefore(input) {
1241
- if (typeof input === "number") {
1242
- this._payload = { ...this._payload, nbf: validateInput("setNotBefore", input) };
1243
- } else if (input instanceof Date) {
1244
- this._payload = { ...this._payload, nbf: validateInput("setNotBefore", epoch_default(input)) };
1245
- } else {
1246
- this._payload = { ...this._payload, nbf: epoch_default(/* @__PURE__ */ new Date()) + secs_default(input) };
1247
- }
1248
- return this;
1249
- }
1250
- setExpirationTime(input) {
1251
- if (typeof input === "number") {
1252
- this._payload = { ...this._payload, exp: validateInput("setExpirationTime", input) };
1253
- } else if (input instanceof Date) {
1254
- this._payload = { ...this._payload, exp: validateInput("setExpirationTime", epoch_default(input)) };
1255
- } else {
1256
- this._payload = { ...this._payload, exp: epoch_default(/* @__PURE__ */ new Date()) + secs_default(input) };
1257
- }
1258
- return this;
1259
- }
1260
- setIssuedAt(input) {
1261
- if (typeof input === "undefined") {
1262
- this._payload = { ...this._payload, iat: epoch_default(/* @__PURE__ */ new Date()) };
1263
- } else if (input instanceof Date) {
1264
- this._payload = { ...this._payload, iat: validateInput("setIssuedAt", epoch_default(input)) };
1265
- } else if (typeof input === "string") {
1266
- this._payload = {
1267
- ...this._payload,
1268
- iat: validateInput("setIssuedAt", epoch_default(/* @__PURE__ */ new Date()) + secs_default(input))
1269
- };
1270
- } else {
1271
- this._payload = { ...this._payload, iat: validateInput("setIssuedAt", input) };
1272
- }
1273
- return this;
1274
- }
1275
- };
1276
-
1277
- // ../../packages/create-wirejs-app/node_modules/jose/dist/node/esm/jwt/sign.js
1278
- var SignJWT = class extends ProduceJWT {
1279
- _protectedHeader;
1280
- setProtectedHeader(protectedHeader) {
1281
- this._protectedHeader = protectedHeader;
1282
- return this;
1283
- }
1284
- async sign(key, options) {
1285
- const sig = new CompactSign(encoder.encode(JSON.stringify(this._payload)));
1286
- sig.setProtectedHeader(this._protectedHeader);
1287
- if (Array.isArray(this._protectedHeader?.crit) && this._protectedHeader.crit.includes("b64") && this._protectedHeader.b64 === false) {
1288
- throw new JWTInvalid("JWTs MUST NOT use unencoded payload");
1289
- }
1290
- return sig.sign(key, options);
1291
- }
1292
- };
1293
-
1294
- // ../../packages/create-wirejs-app/packages/wirejs-resources/lib/resources/secret.js
1295
- import crypto4 from "crypto";
1296
-
1297
- // ../../packages/create-wirejs-app/packages/wirejs-resources/lib/overrides.js
1298
- var overrides = {};
1299
-
1300
- // ../../packages/create-wirejs-app/packages/wirejs-resources/lib/resources/secret.js
1301
- var FILENAME = "secret";
1302
- var Secret = class extends Resource {
1303
- /**
1304
- * @type {FileService}
1305
- */
1306
- #fileService;
1307
- /**
1308
- * @type {Promise<any>}
1309
- */
1310
- #initPromise;
1311
- /**
1312
- * @param {Resource | string}
1313
- * @param {string} id
1314
- */
1315
- constructor(scope, id) {
1316
- super(scope, id);
1317
- this.#fileService = new (overrides.FileService || FileService)(this, "files");
1318
- }
1319
- #initialize() {
1320
- this.#initPromise = this.#initPromise || this.#fileService.write(
1321
- FILENAME,
1322
- JSON.stringify(crypto4.randomBytes(64).toString("base64url")),
1323
- { onlyIfNotExists: true }
1324
- ).catch((error) => {
1325
- if (!this.#fileService.isAlreadyExistsError(error)) throw error;
1326
- });
1327
- return this.#initPromise;
1328
- }
1329
- /**
1330
- * @returns {any}
1331
- */
1332
- async read() {
1333
- await this.#initialize();
1334
- return JSON.parse(await this.#fileService.read(FILENAME));
1335
- }
1336
- /**
1337
- * @param {any} data
1338
- */
1339
- async write(data) {
1340
- await this.#initialize();
1341
- await this.#fileService.write(FILENAME, JSON.stringify(data));
1342
- }
1343
- };
1344
-
1345
- // ../../packages/create-wirejs-app/packages/wirejs-resources/lib/adapters/cookie-jar.js
1346
- var CookieJar = class {
1347
- /**
1348
- * @type {Record<string, Cookie>}
1349
- */
1350
- #cookies = {};
1351
- /**
1352
- * The list of cookies that have been set with `set()` which need to be
1353
- * sent to the client.
1354
- *
1355
- * @type {Set<string>}
1356
- */
1357
- #setCookies = /* @__PURE__ */ new Set();
1358
- /**
1359
- * Initialize
1360
- *
1361
- * @param {string | undefined} cookie
1362
- */
1363
- constructor(cookie) {
1364
- this.#cookies = Object.fromEntries(
1365
- (cookie || "").split(/;/g).map((c) => {
1366
- const [k, v] = c.split("=").map((p) => decodeURIComponent(p.trim()));
1367
- return [k, {
1368
- name: k,
1369
- value: v
1370
- }];
1371
- })
1372
- );
1373
- }
1374
- /**
1375
- * @param {Cookie} cookie
1376
- */
1377
- set(cookie) {
1378
- this.#cookies[cookie.name] = { ...cookie };
1379
- this.#setCookies.add(cookie.name);
1380
- }
1381
- /**
1382
- *
1383
- * @param {string} name
1384
- * @returns {Cookie | undefined}
1385
- */
1386
- get(name) {
1387
- return this.#cookies[name] ? { ...this.#cookies[name] } : void 0;
1388
- }
1389
- /**
1390
- *
1391
- * @param {string} name
1392
- */
1393
- delete(name) {
1394
- if (this.#cookies[name]) {
1395
- this.#cookies[name].value = "-- deleted --";
1396
- this.#cookies[name].maxAge = 0;
1397
- this.#setCookies.add(name);
1398
- }
1399
- }
1400
- /**
1401
- * Gets a copy of all cookies.
1402
- *
1403
- * Changes made to this copy are not reflected
1404
- *
1405
- * @returns {Record<string, string>}
1406
- */
1407
- getAll() {
1408
- const all = {};
1409
- for (const cookie of Object.values(this.#cookies)) {
1410
- all[cookie.name] = cookie.value;
1411
- }
1412
- return all;
1413
- }
1414
- getSetCookies() {
1415
- const all = [];
1416
- for (const name of this.#setCookies) {
1417
- all.push({ ...this.#cookies[name] });
1418
- }
1419
- return all;
1420
- }
1421
- };
1422
-
1423
- // ../../packages/create-wirejs-app/packages/wirejs-resources/lib/adapters/context.js
1424
- var contextWrappers = /* @__PURE__ */ new Set();
1425
- function withContext(contextWrapper, path2 = []) {
1426
- const fnOrNs = new Proxy(function() {
1427
- }, {
1428
- apply(_target, _thisArg, args) {
1429
- const [context, ...remainingArgs] = args;
1430
- let functionOrNamespaceObject = contextWrapper(context);
1431
- console.log({ context, args, functionOrNamespaceObject, path: path2 });
1432
- for (const k of path2) {
1433
- functionOrNamespaceObject = functionOrNamespaceObject[k];
1434
- }
1435
- return functionOrNamespaceObject(...remainingArgs);
1436
- },
1437
- get(_target, prop) {
1438
- return withContext(contextWrapper, [...path2, prop]);
1439
- }
1440
- });
1441
- contextWrappers.add(fnOrNs);
1442
- return fnOrNs;
1443
- }
1444
- function requiresContext(fnOrNS) {
1445
- return contextWrappers.has(fnOrNS);
1446
- }
1447
- var Context = class {
1448
- /**
1449
- * @type {CookieJar} cookies
1450
- */
1451
- cookies;
1452
- /**
1453
- * @type {URL} location
1454
- */
1455
- location;
1456
- /**
1457
- * @param {{
1458
- * cookies: CookieJar;
1459
- * location: URL;
1460
- * }}
1461
- */
1462
- constructor({ cookies, location }) {
1463
- this.cookies = cookies;
1464
- this.location = location;
1465
- }
1466
- };
1467
-
1468
- // ../../packages/create-wirejs-app/packages/wirejs-resources/lib/services/authentication.js
1469
- function hash(password, salt) {
1470
- return new Promise((resolve, reject) => {
1471
- const finalSalt = salt || randomBytes(16).toString("hex");
1472
- scrypt(password, finalSalt, 64, (err, key) => {
1473
- if (err) {
1474
- reject(err);
1475
- } else {
1476
- resolve(`${finalSalt}$${key.toString("hex")}`);
1477
- }
1478
- });
1479
- });
1480
- }
1481
- async function verifyHash(password, passwordHash) {
1482
- const [saltPart, _hashPart] = passwordHash.split("$");
1483
- const rehashed = await hash(password, saltPart);
1484
- return rehashed === passwordHash;
1485
- }
1486
- var ONE_WEEK = 7 * 24 * 60 * 60;
1487
- var AuthenticationService = class extends Resource {
1488
- #duration;
1489
- #keepalive;
1490
- #cookieName;
1491
- /**
1492
- * @type {Secret}
1493
- */
1494
- #rawSigningSecret;
1495
- /**
1496
- * @type {Promise<Uint8Array<ArrayBufferLike>> | undefined}
1497
- */
1498
- #signingSecret;
1499
- #users;
1500
- /**
1501
- *
1502
- * @param {Resource | string} scope
1503
- * @param {string} id
1504
- * @param {AuthenticationServiceOptions} [options]
1505
- */
1506
- constructor(scope, id, { duration, keepalive, cookie } = {}) {
1507
- super(scope, id);
1508
- this.#duration = duration || ONE_WEEK;
1509
- this.#keepalive = !!keepalive;
1510
- this.#cookieName = cookie ?? "identity";
1511
- this.#rawSigningSecret = new (overrides.Secret || Secret)(this, "jwt-signing-secret");
1512
- const fileService = new (overrides.FileService || FileService)(this, "files");
1513
- this.#users = {
1514
- id,
1515
- /**
1516
- *
1517
- * @param {string} username
1518
- */
1519
- async get(username) {
1520
- try {
1521
- const data = await fileService.read(this.filenameFor(username));
1522
- return JSON.parse(data);
1523
- } catch {
1524
- return void 0;
1525
- }
1526
- },
1527
- /**
1528
- * @param {string} username
1529
- * @param {User} user
1530
- */
1531
- async set(username, details) {
1532
- await fileService.write(this.filenameFor(username), JSON.stringify(details));
1533
- },
1534
- /**
1535
- * @param {string} username
1536
- */
1537
- async has(username) {
1538
- const user = await this.get(username);
1539
- return !!user;
1540
- },
1541
- /**
1542
- * @param {string} username
1543
- * @returns
1544
- */
1545
- filenameFor(username) {
1546
- return `${username}.json`;
1547
- }
1548
- };
1549
- }
1550
- async getSigningSecret() {
1551
- const secretAsString = await this.#rawSigningSecret.read();
1552
- return new TextEncoder().encode(secretAsString);
1553
- }
1554
- /**
1555
- * @type {Promise<Uint8Array<ArrayBufferLike>>}
1556
- */
1557
- get signingSecret() {
1558
- if (!this.#signingSecret) {
1559
- this.#signingSecret = this.getSigningSecret();
1560
- }
1561
- return this.#signingSecret;
1562
- }
1563
- /**
1564
- * @param {CookieJar} cookies
1565
- * @returns {Promise<AuthenticationBaseState>}
1566
- */
1567
- async getBaseState(cookies) {
1568
- let idCookie, idPayload, user;
1569
- try {
1570
- idCookie = cookies.get(this.#cookieName)?.value;
1571
- idPayload = idCookie ? await jwtVerify(idCookie, await this.signingSecret) : void 0;
1572
- user = idPayload ? idPayload.payload.sub : void 0;
1573
- } catch (err) {
1574
- console.error(err);
1575
- }
1576
- if (user) {
1577
- return {
1578
- state: "authenticated",
1579
- user
1580
- };
1581
- } else {
1582
- return {
1583
- state: "unauthenticated",
1584
- user: void 0
1585
- };
1586
- }
1587
- }
1588
- /**
1589
- * @param {CookieJar} cookies
1590
- * @returns {Promise<AuthenticationState>}
1591
- */
1592
- async getState(cookies) {
1593
- const state = await this.getBaseState(cookies);
1594
- if (state.state === "authenticated") {
1595
- if (this.#keepalive) this.setBaseState(state);
1596
- return {
1597
- state,
1598
- actions: {
1599
- changepassword: {
1600
- name: "Change Password",
1601
- inputs: {
1602
- existingPassword: {
1603
- label: "Old Password",
1604
- type: "password"
1605
- },
1606
- newPassword: {
1607
- label: "New Password",
1608
- type: "password"
1609
- }
1610
- },
1611
- buttons: ["Change Password"]
1612
- },
1613
- signout: {
1614
- name: "Sign out"
1615
- }
1616
- }
1617
- };
1618
- } else {
1619
- return {
1620
- state,
1621
- actions: {
1622
- signin: {
1623
- name: "Sign In",
1624
- inputs: {
1625
- username: {
1626
- label: "Username",
1627
- type: "text"
1628
- },
1629
- password: {
1630
- label: "Password",
1631
- type: "password"
1632
- }
1633
- },
1634
- buttons: ["Sign In"]
1635
- },
1636
- signup: {
1637
- name: "Sign Up",
1638
- inputs: {
1639
- username: {
1640
- label: "Username",
1641
- type: "text"
1642
- },
1643
- password: {
1644
- label: "Password",
1645
- type: "password"
1646
- }
1647
- },
1648
- buttons: ["Sign Up"]
1649
- }
1650
- }
1651
- };
1652
- }
1653
- }
1654
- /**
1655
- *
1656
- * @param {CookieJar} cookies
1657
- * @param {string | undefined} [user]
1658
- */
1659
- async setBaseState(cookies, user) {
1660
- if (!user) {
1661
- cookies.delete(this.#cookieName);
1662
- } else {
1663
- const jwt = await new SignJWT({}).setProtectedHeader({ alg: "HS256" }).setIssuedAt().setSubject(user).setExpirationTime(`${this.#duration}s`).sign(await this.signingSecret);
1664
- cookies.set({
1665
- name: this.#cookieName,
1666
- value: jwt,
1667
- httpOnly: true,
1668
- secure: true,
1669
- maxAge: this.#duration
1670
- });
1671
- }
1672
- }
1673
- /**
1674
- *
1675
- * @param {Record<string, string>} input
1676
- * @param {string[]} fields
1677
- * @returns {AuthenticationError[] | undefined}
1678
- */
1679
- missingFieldErrors(input, fields) {
1680
- const errors = [];
1681
- for (const field of fields) {
1682
- if (!input[field]) errors.push({
1683
- field,
1684
- message: "Field is required."
1685
- });
1686
- }
1687
- return errors.length > 0 ? errors : void 0;
1688
- }
1689
- /**
1690
- * @param {CookieJar} cookies
1691
- * @param {PerformActionParameter} params
1692
- * @returns {Promise<AuthenticationState | { errors: AuthenticationError[] }>}
1693
- */
1694
- async setState(cookies, { key, inputs, verb: _verb }) {
1695
- if (key === "signout") {
1696
- await this.setBaseState(cookies, void 0);
1697
- return this.getState(cookies);
1698
- } else if (key === "signup") {
1699
- const errors = this.missingFieldErrors(inputs, ["username", "password"]);
1700
- if (errors) {
1701
- return { errors };
1702
- } else if (await this.#users.has(inputs.username)) {
1703
- return {
1704
- errors: [{
1705
- field: "username",
1706
- message: "User already exists."
1707
- }]
1708
- };
1709
- } else {
1710
- await this.#users.set(inputs.username, {
1711
- id: inputs.username,
1712
- password: await hash(inputs.password)
1713
- });
1714
- await this.setBaseState(cookies, inputs.username);
1715
- return this.getState(cookies);
1716
- }
1717
- } else if (key === "signin") {
1718
- const user = await this.#users.get(inputs.username);
1719
- if (!user) {
1720
- return {
1721
- errors: [{
1722
- field: "username",
1723
- message: `User doesn't exist.`
1724
- }]
1725
- };
1726
- } else if (await verifyHash(inputs.password, user.password)) {
1727
- await this.setBaseState(cookies, inputs.username);
1728
- return this.getState(cookies);
1729
- } else {
1730
- return {
1731
- errors: [{
1732
- field: "password",
1733
- message: "Incorrect password."
1734
- }]
1735
- };
1736
- }
1737
- } else if (key === "changepassword") {
1738
- const state = await this.getBaseState(cookies);
1739
- const user = await this.#users.get(state.user);
1740
- if (!user) {
1741
- return {
1742
- errors: [{
1743
- field: "username",
1744
- message: `You're not signed in as a recognized user.`
1745
- }]
1746
- };
1747
- } else if (await verifyHash(inputs.existingPassword, user.password)) {
1748
- await this.#users.set(user.id, {
1749
- ...user,
1750
- password: await hash(inputs.newPassword)
1751
- });
1752
- return {
1753
- message: "Password updated.",
1754
- ...await this.getState(cookies)
1755
- };
1756
- } else {
1757
- return {
1758
- errors: [{
1759
- field: "existingPassword",
1760
- message: "The provided existing password is incorrect."
1761
- }]
1762
- };
1763
- }
1764
- } else {
1765
- return {
1766
- errors: [{
1767
- message: "Unrecognized authentication action."
1768
- }]
1769
- };
1770
- }
1771
- }
1772
- buildApi() {
1773
- return withContext((context) => ({
1774
- getState: () => this.getState(context.cookies),
1775
- /**
1776
- *
1777
- * @param {Parameters<typeof this['setState']>[1]} options
1778
- * @returns
1779
- */
1780
- setState: (options) => this.setState(context.cookies, options)
1781
- }));
1782
- }
1783
- };
1784
-
1785
- // ../../packages/create-wirejs-app/packages/wirejs-deploy-amplify-basic/wirejs-resources-overrides/index.js
1786
- var FileService2 = class extends Resource {
1787
- constructor(scope, id) {
1788
- super(scope, id);
1789
- addResource("FileService", { absoluteId: this.absoluteId });
1790
- }
1791
- async write(...args) {
1792
- console.log('"writing secret" ... :/ ... ');
1793
- }
1794
- };
1795
- overrides.FileService = FileService2;
1796
- globalThis.wirejsResources = [];
1797
- function addResource(type, options) {
1798
- wirejsResources.push({
1799
- type,
1800
- options
1801
- });
1802
- }
1803
- export {
1804
- AuthenticationService,
1805
- Context,
1806
- CookieJar,
1807
- FileService2 as FileService,
1808
- Resource,
1809
- overrides,
1810
- requiresContext,
1811
- withContext
1812
- };