@hot-updater/js 0.12.7 → 0.13.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/getUpdateInfo.d.ts +1 -1
- package/dist/index.cjs +1272 -48
- package/dist/index.d.ts +2 -0
- package/dist/index.js +1267 -47
- package/dist/verifyJwtSignedUrl.d.ts +36 -0
- package/dist/verifyJwtSignedUrl.spec.d.ts +1 -0
- package/dist/withJwtSignedUrl.d.ts +19 -0
- package/dist/withJwtSignedUrl.spec.d.ts +1 -0
- package/package.json +5 -4
package/dist/index.js
CHANGED
|
@@ -1344,15 +1344,6 @@ function __webpack_require__(moduleId) {
|
|
|
1344
1344
|
(()=>{
|
|
1345
1345
|
__webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
|
|
1346
1346
|
})();
|
|
1347
|
-
const isNullable = (value)=>null == value;
|
|
1348
|
-
const checkForRollback = (bundles, currentBundleId)=>{
|
|
1349
|
-
if (currentBundleId === __WEBPACK_EXTERNAL_MODULE__hot_updater_core_132f924c__.NIL_UUID) return false;
|
|
1350
|
-
if (0 === bundles.length) return true;
|
|
1351
|
-
const enabled = bundles.find((item)=>item.id === currentBundleId)?.enabled;
|
|
1352
|
-
const availableOldVersion = bundles.find((item)=>item.id.localeCompare(currentBundleId) < 0 && item.enabled)?.enabled;
|
|
1353
|
-
if (isNullable(enabled)) return Boolean(availableOldVersion);
|
|
1354
|
-
return !enabled;
|
|
1355
|
-
};
|
|
1356
1347
|
var semver = __webpack_require__("../../node_modules/.pnpm/semver@7.6.3/node_modules/semver/index.js");
|
|
1357
1348
|
var semver_default = /*#__PURE__*/ __webpack_require__.n(semver);
|
|
1358
1349
|
const semverSatisfies = (targetAppVersion, currentVersion)=>{
|
|
@@ -1360,51 +1351,1280 @@ const semverSatisfies = (targetAppVersion, currentVersion)=>{
|
|
|
1360
1351
|
if (!currentCoerce) return false;
|
|
1361
1352
|
return semver_default().satisfies(currentCoerce.version, targetAppVersion);
|
|
1362
1353
|
};
|
|
1363
|
-
const
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
|
|
1372
|
-
|
|
1373
|
-
|
|
1374
|
-
|
|
1375
|
-
|
|
1354
|
+
const INIT_BUNDLE_ROLLBACK_UPDATE_INFO = {
|
|
1355
|
+
message: null,
|
|
1356
|
+
id: __WEBPACK_EXTERNAL_MODULE__hot_updater_core_132f924c__.NIL_UUID,
|
|
1357
|
+
shouldForceUpdate: true,
|
|
1358
|
+
status: "ROLLBACK"
|
|
1359
|
+
};
|
|
1360
|
+
const makeResponse = (bundle, status)=>({
|
|
1361
|
+
id: bundle.id,
|
|
1362
|
+
message: bundle.message,
|
|
1363
|
+
shouldForceUpdate: "ROLLBACK" === status ? true : bundle.shouldForceUpdate,
|
|
1364
|
+
status
|
|
1365
|
+
});
|
|
1366
|
+
const getUpdateInfo = async (bundles, { platform, bundleId, appVersion, minBundleId = __WEBPACK_EXTERNAL_MODULE__hot_updater_core_132f924c__.NIL_UUID, channel = "production" })=>{
|
|
1367
|
+
const candidateBundles = [];
|
|
1368
|
+
for (const b of bundles)if (!(b.platform !== platform || b.channel !== channel || !semverSatisfies(b.targetAppVersion, appVersion) || !b.enabled || minBundleId && b.id.localeCompare(minBundleId) < 0)) candidateBundles.push(b);
|
|
1369
|
+
if (0 === candidateBundles.length) {
|
|
1370
|
+
if (bundleId === __WEBPACK_EXTERNAL_MODULE__hot_updater_core_132f924c__.NIL_UUID || minBundleId && bundleId.localeCompare(minBundleId) <= 0) return null;
|
|
1371
|
+
return INIT_BUNDLE_ROLLBACK_UPDATE_INFO;
|
|
1372
|
+
}
|
|
1373
|
+
let latestCandidate = null;
|
|
1374
|
+
let updateCandidate = null;
|
|
1375
|
+
let rollbackCandidate = null;
|
|
1376
|
+
let currentBundle;
|
|
1377
|
+
for (const b of candidateBundles){
|
|
1378
|
+
if (!latestCandidate || b.id.localeCompare(latestCandidate.id) > 0) latestCandidate = b;
|
|
1379
|
+
if (b.id === bundleId) currentBundle = b;
|
|
1380
|
+
else if (bundleId !== __WEBPACK_EXTERNAL_MODULE__hot_updater_core_132f924c__.NIL_UUID) {
|
|
1381
|
+
if (b.id.localeCompare(bundleId) > 0) {
|
|
1382
|
+
if (!updateCandidate || b.id.localeCompare(updateCandidate.id) > 0) updateCandidate = b;
|
|
1383
|
+
} else if (b.id.localeCompare(bundleId) < 0) {
|
|
1384
|
+
if (!rollbackCandidate || b.id.localeCompare(rollbackCandidate.id) > 0) rollbackCandidate = b;
|
|
1385
|
+
}
|
|
1386
|
+
}
|
|
1387
|
+
}
|
|
1388
|
+
if (bundleId === __WEBPACK_EXTERNAL_MODULE__hot_updater_core_132f924c__.NIL_UUID) {
|
|
1389
|
+
if (latestCandidate && latestCandidate.id.localeCompare(bundleId) > 0) return makeResponse(latestCandidate, "UPDATE");
|
|
1376
1390
|
return null;
|
|
1377
1391
|
}
|
|
1378
|
-
if (
|
|
1379
|
-
if (
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1392
|
+
if (currentBundle) {
|
|
1393
|
+
if (latestCandidate && latestCandidate.id.localeCompare(currentBundle.id) > 0) return makeResponse(latestCandidate, "UPDATE");
|
|
1394
|
+
return null;
|
|
1395
|
+
}
|
|
1396
|
+
if (updateCandidate) return makeResponse(updateCandidate, "UPDATE");
|
|
1397
|
+
if (rollbackCandidate) return makeResponse(rollbackCandidate, "ROLLBACK");
|
|
1398
|
+
if (minBundleId && bundleId.localeCompare(minBundleId) <= 0) return null;
|
|
1399
|
+
return INIT_BUNDLE_ROLLBACK_UPDATE_INFO;
|
|
1400
|
+
};
|
|
1401
|
+
const filterCompatibleAppVersions = (targetAppVersionList, currentVersion)=>{
|
|
1402
|
+
const compatibleAppVersionList = targetAppVersionList.filter((version)=>semverSatisfies(version, currentVersion));
|
|
1403
|
+
return compatibleAppVersionList.sort((a, b)=>b.localeCompare(a));
|
|
1404
|
+
};
|
|
1405
|
+
const encoder = new TextEncoder();
|
|
1406
|
+
const decoder = new TextDecoder();
|
|
1407
|
+
function concat(...buffers) {
|
|
1408
|
+
const size = buffers.reduce((acc, { length })=>acc + length, 0);
|
|
1409
|
+
const buf = new Uint8Array(size);
|
|
1410
|
+
let i = 0;
|
|
1411
|
+
for (const buffer of buffers){
|
|
1412
|
+
buf.set(buffer, i);
|
|
1413
|
+
i += buffer.length;
|
|
1414
|
+
}
|
|
1415
|
+
return buf;
|
|
1416
|
+
}
|
|
1417
|
+
function encodeBase64(input) {
|
|
1418
|
+
if (Uint8Array.prototype.toBase64) return input.toBase64();
|
|
1419
|
+
const CHUNK_SIZE = 0x8000;
|
|
1420
|
+
const arr = [];
|
|
1421
|
+
for(let i = 0; i < input.length; i += CHUNK_SIZE)arr.push(String.fromCharCode.apply(null, input.subarray(i, i + CHUNK_SIZE)));
|
|
1422
|
+
return btoa(arr.join(''));
|
|
1423
|
+
}
|
|
1424
|
+
function decodeBase64(encoded) {
|
|
1425
|
+
if (Uint8Array.fromBase64) return Uint8Array.fromBase64(encoded);
|
|
1426
|
+
const binary = atob(encoded);
|
|
1427
|
+
const bytes = new Uint8Array(binary.length);
|
|
1428
|
+
for(let i = 0; i < binary.length; i++)bytes[i] = binary.charCodeAt(i);
|
|
1429
|
+
return bytes;
|
|
1430
|
+
}
|
|
1431
|
+
function decode(input) {
|
|
1432
|
+
if (Uint8Array.fromBase64) return Uint8Array.fromBase64('string' == typeof input ? input : decoder.decode(input), {
|
|
1433
|
+
alphabet: 'base64url'
|
|
1434
|
+
});
|
|
1435
|
+
let encoded = input;
|
|
1436
|
+
if (encoded instanceof Uint8Array) encoded = decoder.decode(encoded);
|
|
1437
|
+
encoded = encoded.replace(/-/g, '+').replace(/_/g, '/').replace(/\s/g, '');
|
|
1438
|
+
try {
|
|
1439
|
+
return decodeBase64(encoded);
|
|
1440
|
+
} catch {
|
|
1441
|
+
throw new TypeError('The input to be decoded is not correctly encoded.');
|
|
1442
|
+
}
|
|
1443
|
+
}
|
|
1444
|
+
function encode(input) {
|
|
1445
|
+
let unencoded = input;
|
|
1446
|
+
if ('string' == typeof unencoded) unencoded = encoder.encode(unencoded);
|
|
1447
|
+
if (Uint8Array.prototype.toBase64) return unencoded.toBase64({
|
|
1448
|
+
alphabet: 'base64url',
|
|
1449
|
+
omitPadding: true
|
|
1450
|
+
});
|
|
1451
|
+
return encodeBase64(unencoded).replace(/=/g, '').replace(/\+/g, '-').replace(/\//g, '_');
|
|
1452
|
+
}
|
|
1453
|
+
class JOSEError extends Error {
|
|
1454
|
+
static code = 'ERR_JOSE_GENERIC';
|
|
1455
|
+
code = 'ERR_JOSE_GENERIC';
|
|
1456
|
+
constructor(message, options){
|
|
1457
|
+
super(message, options);
|
|
1458
|
+
this.name = this.constructor.name;
|
|
1459
|
+
Error.captureStackTrace?.(this, this.constructor);
|
|
1460
|
+
}
|
|
1461
|
+
}
|
|
1462
|
+
class JWTClaimValidationFailed extends JOSEError {
|
|
1463
|
+
static code = 'ERR_JWT_CLAIM_VALIDATION_FAILED';
|
|
1464
|
+
code = 'ERR_JWT_CLAIM_VALIDATION_FAILED';
|
|
1465
|
+
claim;
|
|
1466
|
+
reason;
|
|
1467
|
+
payload;
|
|
1468
|
+
constructor(message, payload, claim = 'unspecified', reason = 'unspecified'){
|
|
1469
|
+
super(message, {
|
|
1470
|
+
cause: {
|
|
1471
|
+
claim,
|
|
1472
|
+
reason,
|
|
1473
|
+
payload
|
|
1474
|
+
}
|
|
1475
|
+
});
|
|
1476
|
+
this.claim = claim;
|
|
1477
|
+
this.reason = reason;
|
|
1478
|
+
this.payload = payload;
|
|
1479
|
+
}
|
|
1480
|
+
}
|
|
1481
|
+
class JWTExpired extends JOSEError {
|
|
1482
|
+
static code = 'ERR_JWT_EXPIRED';
|
|
1483
|
+
code = 'ERR_JWT_EXPIRED';
|
|
1484
|
+
claim;
|
|
1485
|
+
reason;
|
|
1486
|
+
payload;
|
|
1487
|
+
constructor(message, payload, claim = 'unspecified', reason = 'unspecified'){
|
|
1488
|
+
super(message, {
|
|
1489
|
+
cause: {
|
|
1490
|
+
claim,
|
|
1491
|
+
reason,
|
|
1492
|
+
payload
|
|
1493
|
+
}
|
|
1494
|
+
});
|
|
1495
|
+
this.claim = claim;
|
|
1496
|
+
this.reason = reason;
|
|
1497
|
+
this.payload = payload;
|
|
1498
|
+
}
|
|
1499
|
+
}
|
|
1500
|
+
class JOSEAlgNotAllowed extends JOSEError {
|
|
1501
|
+
static code = 'ERR_JOSE_ALG_NOT_ALLOWED';
|
|
1502
|
+
code = 'ERR_JOSE_ALG_NOT_ALLOWED';
|
|
1503
|
+
}
|
|
1504
|
+
class JOSENotSupported extends JOSEError {
|
|
1505
|
+
static code = 'ERR_JOSE_NOT_SUPPORTED';
|
|
1506
|
+
code = 'ERR_JOSE_NOT_SUPPORTED';
|
|
1507
|
+
}
|
|
1508
|
+
class JWSInvalid extends JOSEError {
|
|
1509
|
+
static code = 'ERR_JWS_INVALID';
|
|
1510
|
+
code = 'ERR_JWS_INVALID';
|
|
1511
|
+
}
|
|
1512
|
+
class JWTInvalid extends JOSEError {
|
|
1513
|
+
static code = 'ERR_JWT_INVALID';
|
|
1514
|
+
code = 'ERR_JWT_INVALID';
|
|
1515
|
+
}
|
|
1516
|
+
class JWKSMultipleMatchingKeys extends JOSEError {
|
|
1517
|
+
[Symbol.asyncIterator];
|
|
1518
|
+
static code = 'ERR_JWKS_MULTIPLE_MATCHING_KEYS';
|
|
1519
|
+
code = 'ERR_JWKS_MULTIPLE_MATCHING_KEYS';
|
|
1520
|
+
constructor(message = 'multiple matching keys found in the JSON Web Key Set', options){
|
|
1521
|
+
super(message, options);
|
|
1522
|
+
}
|
|
1523
|
+
}
|
|
1524
|
+
class JWSSignatureVerificationFailed extends JOSEError {
|
|
1525
|
+
static code = 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED';
|
|
1526
|
+
code = 'ERR_JWS_SIGNATURE_VERIFICATION_FAILED';
|
|
1527
|
+
constructor(message = 'signature verification failed', options){
|
|
1528
|
+
super(message, options);
|
|
1529
|
+
}
|
|
1530
|
+
}
|
|
1531
|
+
const subtle_dsa = (alg, algorithm)=>{
|
|
1532
|
+
const hash = `SHA-${alg.slice(-3)}`;
|
|
1533
|
+
switch(alg){
|
|
1534
|
+
case 'HS256':
|
|
1535
|
+
case 'HS384':
|
|
1536
|
+
case 'HS512':
|
|
1537
|
+
return {
|
|
1538
|
+
hash,
|
|
1539
|
+
name: 'HMAC'
|
|
1540
|
+
};
|
|
1541
|
+
case 'PS256':
|
|
1542
|
+
case 'PS384':
|
|
1543
|
+
case 'PS512':
|
|
1544
|
+
return {
|
|
1545
|
+
hash,
|
|
1546
|
+
name: 'RSA-PSS',
|
|
1547
|
+
saltLength: parseInt(alg.slice(-3), 10) >> 3
|
|
1387
1548
|
};
|
|
1549
|
+
case 'RS256':
|
|
1550
|
+
case 'RS384':
|
|
1551
|
+
case 'RS512':
|
|
1388
1552
|
return {
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
fileUrl: latestBundle.fileUrl,
|
|
1392
|
-
fileHash: latestBundle.fileHash,
|
|
1393
|
-
status: "ROLLBACK"
|
|
1553
|
+
hash,
|
|
1554
|
+
name: 'RSASSA-PKCS1-v1_5'
|
|
1394
1555
|
};
|
|
1556
|
+
case 'ES256':
|
|
1557
|
+
case 'ES384':
|
|
1558
|
+
case 'ES512':
|
|
1559
|
+
return {
|
|
1560
|
+
hash,
|
|
1561
|
+
name: 'ECDSA',
|
|
1562
|
+
namedCurve: algorithm.namedCurve
|
|
1563
|
+
};
|
|
1564
|
+
case 'Ed25519':
|
|
1565
|
+
case 'EdDSA':
|
|
1566
|
+
return {
|
|
1567
|
+
name: 'Ed25519'
|
|
1568
|
+
};
|
|
1569
|
+
default:
|
|
1570
|
+
throw new JOSENotSupported(`alg ${alg} is not supported either by JOSE or your javascript runtime`);
|
|
1571
|
+
}
|
|
1572
|
+
};
|
|
1573
|
+
const check_key_length = (alg, key)=>{
|
|
1574
|
+
if (alg.startsWith('RS') || alg.startsWith('PS')) {
|
|
1575
|
+
const { modulusLength } = key.algorithm;
|
|
1576
|
+
if ('number' != typeof modulusLength || modulusLength < 2048) throw new TypeError(`${alg} requires key modulusLength to be 2048 bits or larger`);
|
|
1577
|
+
}
|
|
1578
|
+
};
|
|
1579
|
+
function unusable(name, prop = 'algorithm.name') {
|
|
1580
|
+
return new TypeError(`CryptoKey does not support this operation, its ${prop} must be ${name}`);
|
|
1581
|
+
}
|
|
1582
|
+
function isAlgorithm(algorithm, name) {
|
|
1583
|
+
return algorithm.name === name;
|
|
1584
|
+
}
|
|
1585
|
+
function getHashLength(hash) {
|
|
1586
|
+
return parseInt(hash.name.slice(4), 10);
|
|
1587
|
+
}
|
|
1588
|
+
function getNamedCurve(alg) {
|
|
1589
|
+
switch(alg){
|
|
1590
|
+
case 'ES256':
|
|
1591
|
+
return 'P-256';
|
|
1592
|
+
case 'ES384':
|
|
1593
|
+
return 'P-384';
|
|
1594
|
+
case 'ES512':
|
|
1595
|
+
return 'P-521';
|
|
1596
|
+
default:
|
|
1597
|
+
throw new Error('unreachable');
|
|
1598
|
+
}
|
|
1599
|
+
}
|
|
1600
|
+
function checkUsage(key, usage) {
|
|
1601
|
+
if (usage && !key.usages.includes(usage)) throw new TypeError(`CryptoKey does not support this operation, its usages must include ${usage}.`);
|
|
1602
|
+
}
|
|
1603
|
+
function checkSigCryptoKey(key, alg, usage) {
|
|
1604
|
+
switch(alg){
|
|
1605
|
+
case 'HS256':
|
|
1606
|
+
case 'HS384':
|
|
1607
|
+
case 'HS512':
|
|
1608
|
+
{
|
|
1609
|
+
if (!isAlgorithm(key.algorithm, 'HMAC')) throw unusable('HMAC');
|
|
1610
|
+
const expected = parseInt(alg.slice(2), 10);
|
|
1611
|
+
const actual = getHashLength(key.algorithm.hash);
|
|
1612
|
+
if (actual !== expected) throw unusable(`SHA-${expected}`, 'algorithm.hash');
|
|
1613
|
+
break;
|
|
1614
|
+
}
|
|
1615
|
+
case 'RS256':
|
|
1616
|
+
case 'RS384':
|
|
1617
|
+
case 'RS512':
|
|
1618
|
+
{
|
|
1619
|
+
if (!isAlgorithm(key.algorithm, 'RSASSA-PKCS1-v1_5')) throw unusable('RSASSA-PKCS1-v1_5');
|
|
1620
|
+
const expected = parseInt(alg.slice(2), 10);
|
|
1621
|
+
const actual = getHashLength(key.algorithm.hash);
|
|
1622
|
+
if (actual !== expected) throw unusable(`SHA-${expected}`, 'algorithm.hash');
|
|
1623
|
+
break;
|
|
1624
|
+
}
|
|
1625
|
+
case 'PS256':
|
|
1626
|
+
case 'PS384':
|
|
1627
|
+
case 'PS512':
|
|
1628
|
+
{
|
|
1629
|
+
if (!isAlgorithm(key.algorithm, 'RSA-PSS')) throw unusable('RSA-PSS');
|
|
1630
|
+
const expected = parseInt(alg.slice(2), 10);
|
|
1631
|
+
const actual = getHashLength(key.algorithm.hash);
|
|
1632
|
+
if (actual !== expected) throw unusable(`SHA-${expected}`, 'algorithm.hash');
|
|
1633
|
+
break;
|
|
1634
|
+
}
|
|
1635
|
+
case 'Ed25519':
|
|
1636
|
+
case 'EdDSA':
|
|
1637
|
+
if (!isAlgorithm(key.algorithm, 'Ed25519')) throw unusable('Ed25519');
|
|
1638
|
+
break;
|
|
1639
|
+
case 'ES256':
|
|
1640
|
+
case 'ES384':
|
|
1641
|
+
case 'ES512':
|
|
1642
|
+
{
|
|
1643
|
+
if (!isAlgorithm(key.algorithm, 'ECDSA')) throw unusable('ECDSA');
|
|
1644
|
+
const expected = getNamedCurve(alg);
|
|
1645
|
+
const actual = key.algorithm.namedCurve;
|
|
1646
|
+
if (actual !== expected) throw unusable(expected, 'algorithm.namedCurve');
|
|
1647
|
+
break;
|
|
1648
|
+
}
|
|
1649
|
+
default:
|
|
1650
|
+
throw new TypeError('CryptoKey does not support this operation');
|
|
1651
|
+
}
|
|
1652
|
+
checkUsage(key, usage);
|
|
1653
|
+
}
|
|
1654
|
+
function invalid_key_input_message(msg, actual, ...types) {
|
|
1655
|
+
types = types.filter(Boolean);
|
|
1656
|
+
if (types.length > 2) {
|
|
1657
|
+
const last = types.pop();
|
|
1658
|
+
msg += `one of type ${types.join(', ')}, or ${last}.`;
|
|
1659
|
+
} else if (2 === types.length) msg += `one of type ${types[0]} or ${types[1]}.`;
|
|
1660
|
+
else msg += `of type ${types[0]}.`;
|
|
1661
|
+
if (null == actual) msg += ` Received ${actual}`;
|
|
1662
|
+
else if ('function' == typeof actual && actual.name) msg += ` Received function ${actual.name}`;
|
|
1663
|
+
else if ('object' == typeof actual && null != actual) {
|
|
1664
|
+
if (actual.constructor?.name) msg += ` Received an instance of ${actual.constructor.name}`;
|
|
1665
|
+
}
|
|
1666
|
+
return msg;
|
|
1667
|
+
}
|
|
1668
|
+
const invalid_key_input = (actual, ...types)=>invalid_key_input_message('Key must be ', actual, ...types);
|
|
1669
|
+
function withAlg(alg, actual, ...types) {
|
|
1670
|
+
return invalid_key_input_message(`Key for the ${alg} algorithm must be `, actual, ...types);
|
|
1671
|
+
}
|
|
1672
|
+
const get_sign_verify_key = async (alg, key, usage)=>{
|
|
1673
|
+
if (key instanceof Uint8Array) {
|
|
1674
|
+
if (!alg.startsWith('HS')) throw new TypeError(invalid_key_input(key, 'CryptoKey', 'KeyObject', 'JSON Web Key'));
|
|
1675
|
+
return crypto.subtle.importKey('raw', key, {
|
|
1676
|
+
hash: `SHA-${alg.slice(-3)}`,
|
|
1677
|
+
name: 'HMAC'
|
|
1678
|
+
}, false, [
|
|
1679
|
+
usage
|
|
1680
|
+
]);
|
|
1681
|
+
}
|
|
1682
|
+
checkSigCryptoKey(key, alg, usage);
|
|
1683
|
+
return key;
|
|
1684
|
+
};
|
|
1685
|
+
const sign = async (alg, key, data)=>{
|
|
1686
|
+
const cryptoKey = await get_sign_verify_key(alg, key, 'sign');
|
|
1687
|
+
check_key_length(alg, cryptoKey);
|
|
1688
|
+
const signature = await crypto.subtle.sign(subtle_dsa(alg, cryptoKey.algorithm), cryptoKey, data);
|
|
1689
|
+
return new Uint8Array(signature);
|
|
1690
|
+
};
|
|
1691
|
+
const is_disjoint = (...headers)=>{
|
|
1692
|
+
const sources = headers.filter(Boolean);
|
|
1693
|
+
if (0 === sources.length || 1 === sources.length) return true;
|
|
1694
|
+
let acc;
|
|
1695
|
+
for (const header of sources){
|
|
1696
|
+
const parameters = Object.keys(header);
|
|
1697
|
+
if (!acc || 0 === acc.size) {
|
|
1698
|
+
acc = new Set(parameters);
|
|
1699
|
+
continue;
|
|
1700
|
+
}
|
|
1701
|
+
for (const parameter of parameters){
|
|
1702
|
+
if (acc.has(parameter)) return false;
|
|
1703
|
+
acc.add(parameter);
|
|
1704
|
+
}
|
|
1705
|
+
}
|
|
1706
|
+
return true;
|
|
1707
|
+
};
|
|
1708
|
+
function isCryptoKey(key) {
|
|
1709
|
+
return key?.[Symbol.toStringTag] === 'CryptoKey';
|
|
1710
|
+
}
|
|
1711
|
+
function isKeyObject(key) {
|
|
1712
|
+
return key?.[Symbol.toStringTag] === 'KeyObject';
|
|
1713
|
+
}
|
|
1714
|
+
const is_key_like = (key)=>isCryptoKey(key) || isKeyObject(key);
|
|
1715
|
+
function isObjectLike(value) {
|
|
1716
|
+
return 'object' == typeof value && null !== value;
|
|
1717
|
+
}
|
|
1718
|
+
const is_object = (input)=>{
|
|
1719
|
+
if (!isObjectLike(input) || '[object Object]' !== Object.prototype.toString.call(input)) return false;
|
|
1720
|
+
if (null === Object.getPrototypeOf(input)) return true;
|
|
1721
|
+
let proto = input;
|
|
1722
|
+
while(null !== Object.getPrototypeOf(proto))proto = Object.getPrototypeOf(proto);
|
|
1723
|
+
return Object.getPrototypeOf(input) === proto;
|
|
1724
|
+
};
|
|
1725
|
+
function isJWK(key) {
|
|
1726
|
+
return is_object(key) && 'string' == typeof key.kty;
|
|
1727
|
+
}
|
|
1728
|
+
function isPrivateJWK(key) {
|
|
1729
|
+
return 'oct' !== key.kty && 'string' == typeof key.d;
|
|
1730
|
+
}
|
|
1731
|
+
function isPublicJWK(key) {
|
|
1732
|
+
return 'oct' !== key.kty && void 0 === key.d;
|
|
1733
|
+
}
|
|
1734
|
+
function isSecretJWK(key) {
|
|
1735
|
+
return 'oct' === key.kty && 'string' == typeof key.k;
|
|
1736
|
+
}
|
|
1737
|
+
const tag = (key)=>key?.[Symbol.toStringTag];
|
|
1738
|
+
const jwkMatchesOp = (alg, key, usage)=>{
|
|
1739
|
+
if (void 0 !== key.use) {
|
|
1740
|
+
let expected;
|
|
1741
|
+
switch(usage){
|
|
1742
|
+
case 'sign':
|
|
1743
|
+
case 'verify':
|
|
1744
|
+
expected = 'sig';
|
|
1745
|
+
break;
|
|
1746
|
+
case 'encrypt':
|
|
1747
|
+
case 'decrypt':
|
|
1748
|
+
expected = 'enc';
|
|
1749
|
+
break;
|
|
1395
1750
|
}
|
|
1751
|
+
if (key.use !== expected) throw new TypeError(`Invalid key for this operation, its "use" must be "${expected}" when present`);
|
|
1752
|
+
}
|
|
1753
|
+
if (void 0 !== key.alg && key.alg !== alg) throw new TypeError(`Invalid key for this operation, its "alg" must be "${alg}" when present`);
|
|
1754
|
+
if (Array.isArray(key.key_ops)) {
|
|
1755
|
+
let expectedKeyOp;
|
|
1756
|
+
switch(true){
|
|
1757
|
+
case 'sign' === usage || 'verify' === usage:
|
|
1758
|
+
case 'dir' === alg:
|
|
1759
|
+
case alg.includes('CBC-HS'):
|
|
1760
|
+
expectedKeyOp = usage;
|
|
1761
|
+
break;
|
|
1762
|
+
case alg.startsWith('PBES2'):
|
|
1763
|
+
expectedKeyOp = 'deriveBits';
|
|
1764
|
+
break;
|
|
1765
|
+
case /^A\d{3}(?:GCM)?(?:KW)?$/.test(alg):
|
|
1766
|
+
expectedKeyOp = !alg.includes('GCM') && alg.endsWith('KW') ? 'encrypt' === usage ? 'wrapKey' : 'unwrapKey' : usage;
|
|
1767
|
+
break;
|
|
1768
|
+
case 'encrypt' === usage && alg.startsWith('RSA'):
|
|
1769
|
+
expectedKeyOp = 'wrapKey';
|
|
1770
|
+
break;
|
|
1771
|
+
case 'decrypt' === usage:
|
|
1772
|
+
expectedKeyOp = alg.startsWith('RSA') ? 'unwrapKey' : 'deriveBits';
|
|
1773
|
+
break;
|
|
1774
|
+
}
|
|
1775
|
+
if (expectedKeyOp && key.key_ops?.includes?.(expectedKeyOp) === false) throw new TypeError(`Invalid key for this operation, its "key_ops" must include "${expectedKeyOp}" when present`);
|
|
1776
|
+
}
|
|
1777
|
+
return true;
|
|
1778
|
+
};
|
|
1779
|
+
const symmetricTypeCheck = (alg, key, usage)=>{
|
|
1780
|
+
if (key instanceof Uint8Array) return;
|
|
1781
|
+
if (isJWK(key)) {
|
|
1782
|
+
if (isSecretJWK(key) && jwkMatchesOp(alg, key, usage)) return;
|
|
1783
|
+
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');
|
|
1396
1784
|
}
|
|
1397
|
-
if (
|
|
1398
|
-
|
|
1399
|
-
|
|
1400
|
-
|
|
1401
|
-
|
|
1402
|
-
|
|
1785
|
+
if (!is_key_like(key)) throw new TypeError(withAlg(alg, key, 'CryptoKey', 'KeyObject', 'JSON Web Key', 'Uint8Array'));
|
|
1786
|
+
if ('secret' !== key.type) throw new TypeError(`${tag(key)} instances for symmetric algorithms must be of type "secret"`);
|
|
1787
|
+
};
|
|
1788
|
+
const asymmetricTypeCheck = (alg, key, usage)=>{
|
|
1789
|
+
if (isJWK(key)) switch(usage){
|
|
1790
|
+
case 'decrypt':
|
|
1791
|
+
case 'sign':
|
|
1792
|
+
if (isPrivateJWK(key) && jwkMatchesOp(alg, key, usage)) return;
|
|
1793
|
+
throw new TypeError("JSON Web Key for this operation be a private JWK");
|
|
1794
|
+
case 'encrypt':
|
|
1795
|
+
case 'verify':
|
|
1796
|
+
if (isPublicJWK(key) && jwkMatchesOp(alg, key, usage)) return;
|
|
1797
|
+
throw new TypeError("JSON Web Key for this operation be a public JWK");
|
|
1798
|
+
}
|
|
1799
|
+
if (!is_key_like(key)) throw new TypeError(withAlg(alg, key, 'CryptoKey', 'KeyObject', 'JSON Web Key'));
|
|
1800
|
+
if ('secret' === key.type) throw new TypeError(`${tag(key)} instances for asymmetric algorithms must not be of type "secret"`);
|
|
1801
|
+
if ('public' === key.type) switch(usage){
|
|
1802
|
+
case 'sign':
|
|
1803
|
+
throw new TypeError(`${tag(key)} instances for asymmetric algorithm signing must be of type "private"`);
|
|
1804
|
+
case 'decrypt':
|
|
1805
|
+
throw new TypeError(`${tag(key)} instances for asymmetric algorithm decryption must be of type "private"`);
|
|
1806
|
+
default:
|
|
1807
|
+
break;
|
|
1808
|
+
}
|
|
1809
|
+
if ('private' === key.type) switch(usage){
|
|
1810
|
+
case 'verify':
|
|
1811
|
+
throw new TypeError(`${tag(key)} instances for asymmetric algorithm verifying must be of type "public"`);
|
|
1812
|
+
case 'encrypt':
|
|
1813
|
+
throw new TypeError(`${tag(key)} instances for asymmetric algorithm encryption must be of type "public"`);
|
|
1814
|
+
default:
|
|
1815
|
+
break;
|
|
1816
|
+
}
|
|
1817
|
+
};
|
|
1818
|
+
const check_key_type = (alg, key, usage)=>{
|
|
1819
|
+
const symmetric = alg.startsWith('HS') || 'dir' === alg || alg.startsWith('PBES2') || /^A(?:128|192|256)(?:GCM)?(?:KW)?$/.test(alg) || /^A(?:128|192|256)CBC-HS(?:256|384|512)$/.test(alg);
|
|
1820
|
+
if (symmetric) symmetricTypeCheck(alg, key, usage);
|
|
1821
|
+
else asymmetricTypeCheck(alg, key, usage);
|
|
1822
|
+
};
|
|
1823
|
+
const validate_crit = (Err, recognizedDefault, recognizedOption, protectedHeader, joseHeader)=>{
|
|
1824
|
+
if (void 0 !== joseHeader.crit && protectedHeader?.crit === void 0) throw new Err('"crit" (Critical) Header Parameter MUST be integrity protected');
|
|
1825
|
+
if (!protectedHeader || void 0 === protectedHeader.crit) return new Set();
|
|
1826
|
+
if (!Array.isArray(protectedHeader.crit) || 0 === protectedHeader.crit.length || protectedHeader.crit.some((input)=>'string' != typeof input || 0 === input.length)) throw new Err('"crit" (Critical) Header Parameter MUST be an array of non-empty strings when present');
|
|
1827
|
+
let recognized;
|
|
1828
|
+
recognized = void 0 !== recognizedOption ? new Map([
|
|
1829
|
+
...Object.entries(recognizedOption),
|
|
1830
|
+
...recognizedDefault.entries()
|
|
1831
|
+
]) : recognizedDefault;
|
|
1832
|
+
for (const parameter of protectedHeader.crit){
|
|
1833
|
+
if (!recognized.has(parameter)) throw new JOSENotSupported(`Extension Header Parameter "${parameter}" is not recognized`);
|
|
1834
|
+
if (void 0 === joseHeader[parameter]) throw new Err(`Extension Header Parameter "${parameter}" is missing`);
|
|
1835
|
+
if (recognized.get(parameter) && void 0 === protectedHeader[parameter]) throw new Err(`Extension Header Parameter "${parameter}" MUST be integrity protected`);
|
|
1836
|
+
}
|
|
1837
|
+
return new Set(protectedHeader.crit);
|
|
1838
|
+
};
|
|
1839
|
+
function subtleMapping(jwk) {
|
|
1840
|
+
let algorithm;
|
|
1841
|
+
let keyUsages;
|
|
1842
|
+
switch(jwk.kty){
|
|
1843
|
+
case 'RSA':
|
|
1844
|
+
switch(jwk.alg){
|
|
1845
|
+
case 'PS256':
|
|
1846
|
+
case 'PS384':
|
|
1847
|
+
case 'PS512':
|
|
1848
|
+
algorithm = {
|
|
1849
|
+
name: 'RSA-PSS',
|
|
1850
|
+
hash: `SHA-${jwk.alg.slice(-3)}`
|
|
1851
|
+
};
|
|
1852
|
+
keyUsages = jwk.d ? [
|
|
1853
|
+
'sign'
|
|
1854
|
+
] : [
|
|
1855
|
+
'verify'
|
|
1856
|
+
];
|
|
1857
|
+
break;
|
|
1858
|
+
case 'RS256':
|
|
1859
|
+
case 'RS384':
|
|
1860
|
+
case 'RS512':
|
|
1861
|
+
algorithm = {
|
|
1862
|
+
name: 'RSASSA-PKCS1-v1_5',
|
|
1863
|
+
hash: `SHA-${jwk.alg.slice(-3)}`
|
|
1864
|
+
};
|
|
1865
|
+
keyUsages = jwk.d ? [
|
|
1866
|
+
'sign'
|
|
1867
|
+
] : [
|
|
1868
|
+
'verify'
|
|
1869
|
+
];
|
|
1870
|
+
break;
|
|
1871
|
+
case 'RSA-OAEP':
|
|
1872
|
+
case 'RSA-OAEP-256':
|
|
1873
|
+
case 'RSA-OAEP-384':
|
|
1874
|
+
case 'RSA-OAEP-512':
|
|
1875
|
+
algorithm = {
|
|
1876
|
+
name: 'RSA-OAEP',
|
|
1877
|
+
hash: `SHA-${parseInt(jwk.alg.slice(-3), 10) || 1}`
|
|
1878
|
+
};
|
|
1879
|
+
keyUsages = jwk.d ? [
|
|
1880
|
+
'decrypt',
|
|
1881
|
+
'unwrapKey'
|
|
1882
|
+
] : [
|
|
1883
|
+
'encrypt',
|
|
1884
|
+
'wrapKey'
|
|
1885
|
+
];
|
|
1886
|
+
break;
|
|
1887
|
+
default:
|
|
1888
|
+
throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
|
|
1889
|
+
}
|
|
1890
|
+
break;
|
|
1891
|
+
case 'EC':
|
|
1892
|
+
switch(jwk.alg){
|
|
1893
|
+
case 'ES256':
|
|
1894
|
+
algorithm = {
|
|
1895
|
+
name: 'ECDSA',
|
|
1896
|
+
namedCurve: 'P-256'
|
|
1897
|
+
};
|
|
1898
|
+
keyUsages = jwk.d ? [
|
|
1899
|
+
'sign'
|
|
1900
|
+
] : [
|
|
1901
|
+
'verify'
|
|
1902
|
+
];
|
|
1903
|
+
break;
|
|
1904
|
+
case 'ES384':
|
|
1905
|
+
algorithm = {
|
|
1906
|
+
name: 'ECDSA',
|
|
1907
|
+
namedCurve: 'P-384'
|
|
1908
|
+
};
|
|
1909
|
+
keyUsages = jwk.d ? [
|
|
1910
|
+
'sign'
|
|
1911
|
+
] : [
|
|
1912
|
+
'verify'
|
|
1913
|
+
];
|
|
1914
|
+
break;
|
|
1915
|
+
case 'ES512':
|
|
1916
|
+
algorithm = {
|
|
1917
|
+
name: 'ECDSA',
|
|
1918
|
+
namedCurve: 'P-521'
|
|
1919
|
+
};
|
|
1920
|
+
keyUsages = jwk.d ? [
|
|
1921
|
+
'sign'
|
|
1922
|
+
] : [
|
|
1923
|
+
'verify'
|
|
1924
|
+
];
|
|
1925
|
+
break;
|
|
1926
|
+
case 'ECDH-ES':
|
|
1927
|
+
case 'ECDH-ES+A128KW':
|
|
1928
|
+
case 'ECDH-ES+A192KW':
|
|
1929
|
+
case 'ECDH-ES+A256KW':
|
|
1930
|
+
algorithm = {
|
|
1931
|
+
name: 'ECDH',
|
|
1932
|
+
namedCurve: jwk.crv
|
|
1933
|
+
};
|
|
1934
|
+
keyUsages = jwk.d ? [
|
|
1935
|
+
'deriveBits'
|
|
1936
|
+
] : [];
|
|
1937
|
+
break;
|
|
1938
|
+
default:
|
|
1939
|
+
throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
|
|
1940
|
+
}
|
|
1941
|
+
break;
|
|
1942
|
+
case 'OKP':
|
|
1943
|
+
switch(jwk.alg){
|
|
1944
|
+
case 'Ed25519':
|
|
1945
|
+
case 'EdDSA':
|
|
1946
|
+
algorithm = {
|
|
1947
|
+
name: 'Ed25519'
|
|
1948
|
+
};
|
|
1949
|
+
keyUsages = jwk.d ? [
|
|
1950
|
+
'sign'
|
|
1951
|
+
] : [
|
|
1952
|
+
'verify'
|
|
1953
|
+
];
|
|
1954
|
+
break;
|
|
1955
|
+
case 'ECDH-ES':
|
|
1956
|
+
case 'ECDH-ES+A128KW':
|
|
1957
|
+
case 'ECDH-ES+A192KW':
|
|
1958
|
+
case 'ECDH-ES+A256KW':
|
|
1959
|
+
algorithm = {
|
|
1960
|
+
name: jwk.crv
|
|
1961
|
+
};
|
|
1962
|
+
keyUsages = jwk.d ? [
|
|
1963
|
+
'deriveBits'
|
|
1964
|
+
] : [];
|
|
1965
|
+
break;
|
|
1966
|
+
default:
|
|
1967
|
+
throw new JOSENotSupported('Invalid or unsupported JWK "alg" (Algorithm) Parameter value');
|
|
1968
|
+
}
|
|
1969
|
+
break;
|
|
1970
|
+
default:
|
|
1971
|
+
throw new JOSENotSupported('Invalid or unsupported JWK "kty" (Key Type) Parameter value');
|
|
1972
|
+
}
|
|
1973
|
+
return {
|
|
1974
|
+
algorithm,
|
|
1975
|
+
keyUsages
|
|
1403
1976
|
};
|
|
1404
|
-
|
|
1977
|
+
}
|
|
1978
|
+
const jwk_to_key = async (jwk)=>{
|
|
1979
|
+
if (!jwk.alg) throw new TypeError('"alg" argument is required when "jwk.alg" is not present');
|
|
1980
|
+
const { algorithm, keyUsages } = subtleMapping(jwk);
|
|
1981
|
+
const keyData = {
|
|
1982
|
+
...jwk
|
|
1983
|
+
};
|
|
1984
|
+
delete keyData.alg;
|
|
1985
|
+
delete keyData.use;
|
|
1986
|
+
return crypto.subtle.importKey('jwk', keyData, algorithm, jwk.ext ?? !jwk.d, jwk.key_ops ?? keyUsages);
|
|
1405
1987
|
};
|
|
1406
|
-
|
|
1407
|
-
|
|
1408
|
-
|
|
1988
|
+
let cache;
|
|
1989
|
+
const handleJWK = async (key, jwk, alg, freeze = false)=>{
|
|
1990
|
+
cache ||= new WeakMap();
|
|
1991
|
+
let cached = cache.get(key);
|
|
1992
|
+
if (cached?.[alg]) return cached[alg];
|
|
1993
|
+
const cryptoKey = await jwk_to_key({
|
|
1994
|
+
...jwk,
|
|
1995
|
+
alg
|
|
1996
|
+
});
|
|
1997
|
+
if (freeze) Object.freeze(key);
|
|
1998
|
+
if (cached) cached[alg] = cryptoKey;
|
|
1999
|
+
else cache.set(key, {
|
|
2000
|
+
[alg]: cryptoKey
|
|
2001
|
+
});
|
|
2002
|
+
return cryptoKey;
|
|
2003
|
+
};
|
|
2004
|
+
const handleKeyObject = (keyObject, alg)=>{
|
|
2005
|
+
cache ||= new WeakMap();
|
|
2006
|
+
let cached = cache.get(keyObject);
|
|
2007
|
+
if (cached?.[alg]) return cached[alg];
|
|
2008
|
+
const isPublic = 'public' === keyObject.type;
|
|
2009
|
+
const extractable = !!isPublic;
|
|
2010
|
+
let cryptoKey;
|
|
2011
|
+
if ('x25519' === keyObject.asymmetricKeyType) {
|
|
2012
|
+
switch(alg){
|
|
2013
|
+
case 'ECDH-ES':
|
|
2014
|
+
case 'ECDH-ES+A128KW':
|
|
2015
|
+
case 'ECDH-ES+A192KW':
|
|
2016
|
+
case 'ECDH-ES+A256KW':
|
|
2017
|
+
break;
|
|
2018
|
+
default:
|
|
2019
|
+
throw new TypeError('given KeyObject instance cannot be used for this algorithm');
|
|
2020
|
+
}
|
|
2021
|
+
cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, isPublic ? [] : [
|
|
2022
|
+
'deriveBits'
|
|
2023
|
+
]);
|
|
2024
|
+
}
|
|
2025
|
+
if ('ed25519' === keyObject.asymmetricKeyType) {
|
|
2026
|
+
if ('EdDSA' !== alg && 'Ed25519' !== alg) throw new TypeError('given KeyObject instance cannot be used for this algorithm');
|
|
2027
|
+
cryptoKey = keyObject.toCryptoKey(keyObject.asymmetricKeyType, extractable, [
|
|
2028
|
+
isPublic ? 'verify' : 'sign'
|
|
2029
|
+
]);
|
|
2030
|
+
}
|
|
2031
|
+
if ('rsa' === keyObject.asymmetricKeyType) {
|
|
2032
|
+
let hash;
|
|
2033
|
+
switch(alg){
|
|
2034
|
+
case 'RSA-OAEP':
|
|
2035
|
+
hash = 'SHA-1';
|
|
2036
|
+
break;
|
|
2037
|
+
case 'RS256':
|
|
2038
|
+
case 'PS256':
|
|
2039
|
+
case 'RSA-OAEP-256':
|
|
2040
|
+
hash = 'SHA-256';
|
|
2041
|
+
break;
|
|
2042
|
+
case 'RS384':
|
|
2043
|
+
case 'PS384':
|
|
2044
|
+
case 'RSA-OAEP-384':
|
|
2045
|
+
hash = 'SHA-384';
|
|
2046
|
+
break;
|
|
2047
|
+
case 'RS512':
|
|
2048
|
+
case 'PS512':
|
|
2049
|
+
case 'RSA-OAEP-512':
|
|
2050
|
+
hash = 'SHA-512';
|
|
2051
|
+
break;
|
|
2052
|
+
default:
|
|
2053
|
+
throw new TypeError('given KeyObject instance cannot be used for this algorithm');
|
|
2054
|
+
}
|
|
2055
|
+
if (alg.startsWith('RSA-OAEP')) return keyObject.toCryptoKey({
|
|
2056
|
+
name: 'RSA-OAEP',
|
|
2057
|
+
hash
|
|
2058
|
+
}, extractable, isPublic ? [
|
|
2059
|
+
'encrypt'
|
|
2060
|
+
] : [
|
|
2061
|
+
'decrypt'
|
|
2062
|
+
]);
|
|
2063
|
+
cryptoKey = keyObject.toCryptoKey({
|
|
2064
|
+
name: alg.startsWith('PS') ? 'RSA-PSS' : 'RSASSA-PKCS1-v1_5',
|
|
2065
|
+
hash
|
|
2066
|
+
}, extractable, [
|
|
2067
|
+
isPublic ? 'verify' : 'sign'
|
|
2068
|
+
]);
|
|
2069
|
+
}
|
|
2070
|
+
if ('ec' === keyObject.asymmetricKeyType) {
|
|
2071
|
+
const nist = new Map([
|
|
2072
|
+
[
|
|
2073
|
+
'prime256v1',
|
|
2074
|
+
'P-256'
|
|
2075
|
+
],
|
|
2076
|
+
[
|
|
2077
|
+
'secp384r1',
|
|
2078
|
+
'P-384'
|
|
2079
|
+
],
|
|
2080
|
+
[
|
|
2081
|
+
'secp521r1',
|
|
2082
|
+
'P-521'
|
|
2083
|
+
]
|
|
2084
|
+
]);
|
|
2085
|
+
const namedCurve = nist.get(keyObject.asymmetricKeyDetails?.namedCurve);
|
|
2086
|
+
if (!namedCurve) throw new TypeError('given KeyObject instance cannot be used for this algorithm');
|
|
2087
|
+
if ('ES256' === alg && 'P-256' === namedCurve) cryptoKey = keyObject.toCryptoKey({
|
|
2088
|
+
name: 'ECDSA',
|
|
2089
|
+
namedCurve
|
|
2090
|
+
}, extractable, [
|
|
2091
|
+
isPublic ? 'verify' : 'sign'
|
|
2092
|
+
]);
|
|
2093
|
+
if ('ES384' === alg && 'P-384' === namedCurve) cryptoKey = keyObject.toCryptoKey({
|
|
2094
|
+
name: 'ECDSA',
|
|
2095
|
+
namedCurve
|
|
2096
|
+
}, extractable, [
|
|
2097
|
+
isPublic ? 'verify' : 'sign'
|
|
2098
|
+
]);
|
|
2099
|
+
if ('ES512' === alg && 'P-521' === namedCurve) cryptoKey = keyObject.toCryptoKey({
|
|
2100
|
+
name: 'ECDSA',
|
|
2101
|
+
namedCurve
|
|
2102
|
+
}, extractable, [
|
|
2103
|
+
isPublic ? 'verify' : 'sign'
|
|
2104
|
+
]);
|
|
2105
|
+
if (alg.startsWith('ECDH-ES')) cryptoKey = keyObject.toCryptoKey({
|
|
2106
|
+
name: 'ECDH',
|
|
2107
|
+
namedCurve
|
|
2108
|
+
}, extractable, isPublic ? [] : [
|
|
2109
|
+
'deriveBits'
|
|
2110
|
+
]);
|
|
2111
|
+
}
|
|
2112
|
+
if (!cryptoKey) throw new TypeError('given KeyObject instance cannot be used for this algorithm');
|
|
2113
|
+
if (cached) cached[alg] = cryptoKey;
|
|
2114
|
+
else cache.set(keyObject, {
|
|
2115
|
+
[alg]: cryptoKey
|
|
2116
|
+
});
|
|
2117
|
+
return cryptoKey;
|
|
2118
|
+
};
|
|
2119
|
+
const normalize_key = async (key, alg)=>{
|
|
2120
|
+
if (key instanceof Uint8Array) return key;
|
|
2121
|
+
if (isCryptoKey(key)) return key;
|
|
2122
|
+
if (isKeyObject(key)) {
|
|
2123
|
+
if ('secret' === key.type) return key.export();
|
|
2124
|
+
if ('toCryptoKey' in key && 'function' == typeof key.toCryptoKey) try {
|
|
2125
|
+
return handleKeyObject(key, alg);
|
|
2126
|
+
} catch (err) {
|
|
2127
|
+
if (err instanceof TypeError) throw err;
|
|
2128
|
+
}
|
|
2129
|
+
let jwk = key.export({
|
|
2130
|
+
format: 'jwk'
|
|
2131
|
+
});
|
|
2132
|
+
return handleJWK(key, jwk, alg);
|
|
2133
|
+
}
|
|
2134
|
+
if (isJWK(key)) {
|
|
2135
|
+
if (key.k) return decode(key.k);
|
|
2136
|
+
return handleJWK(key, key, alg, true);
|
|
2137
|
+
}
|
|
2138
|
+
throw new Error('unreachable');
|
|
2139
|
+
};
|
|
2140
|
+
class FlattenedSign {
|
|
2141
|
+
#payload;
|
|
2142
|
+
#protectedHeader;
|
|
2143
|
+
#unprotectedHeader;
|
|
2144
|
+
constructor(payload){
|
|
2145
|
+
if (!(payload instanceof Uint8Array)) throw new TypeError('payload must be an instance of Uint8Array');
|
|
2146
|
+
this.#payload = payload;
|
|
2147
|
+
}
|
|
2148
|
+
setProtectedHeader(protectedHeader) {
|
|
2149
|
+
if (this.#protectedHeader) throw new TypeError('setProtectedHeader can only be called once');
|
|
2150
|
+
this.#protectedHeader = protectedHeader;
|
|
2151
|
+
return this;
|
|
2152
|
+
}
|
|
2153
|
+
setUnprotectedHeader(unprotectedHeader) {
|
|
2154
|
+
if (this.#unprotectedHeader) throw new TypeError('setUnprotectedHeader can only be called once');
|
|
2155
|
+
this.#unprotectedHeader = unprotectedHeader;
|
|
2156
|
+
return this;
|
|
2157
|
+
}
|
|
2158
|
+
async sign(key, options) {
|
|
2159
|
+
if (!this.#protectedHeader && !this.#unprotectedHeader) throw new JWSInvalid('either setProtectedHeader or setUnprotectedHeader must be called before #sign()');
|
|
2160
|
+
if (!is_disjoint(this.#protectedHeader, this.#unprotectedHeader)) throw new JWSInvalid('JWS Protected and JWS Unprotected Header Parameter names must be disjoint');
|
|
2161
|
+
const joseHeader = {
|
|
2162
|
+
...this.#protectedHeader,
|
|
2163
|
+
...this.#unprotectedHeader
|
|
2164
|
+
};
|
|
2165
|
+
const extensions = validate_crit(JWSInvalid, new Map([
|
|
2166
|
+
[
|
|
2167
|
+
'b64',
|
|
2168
|
+
true
|
|
2169
|
+
]
|
|
2170
|
+
]), options?.crit, this.#protectedHeader, joseHeader);
|
|
2171
|
+
let b64 = true;
|
|
2172
|
+
if (extensions.has('b64')) {
|
|
2173
|
+
b64 = this.#protectedHeader.b64;
|
|
2174
|
+
if ('boolean' != typeof b64) throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');
|
|
2175
|
+
}
|
|
2176
|
+
const { alg } = joseHeader;
|
|
2177
|
+
if ('string' != typeof alg || !alg) throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');
|
|
2178
|
+
check_key_type(alg, key, 'sign');
|
|
2179
|
+
let payload = this.#payload;
|
|
2180
|
+
if (b64) payload = encoder.encode(encode(payload));
|
|
2181
|
+
let protectedHeader;
|
|
2182
|
+
protectedHeader = this.#protectedHeader ? encoder.encode(encode(JSON.stringify(this.#protectedHeader))) : encoder.encode('');
|
|
2183
|
+
const data = concat(protectedHeader, encoder.encode('.'), payload);
|
|
2184
|
+
const k = await normalize_key(key, alg);
|
|
2185
|
+
const signature = await sign(alg, k, data);
|
|
2186
|
+
const jws = {
|
|
2187
|
+
signature: encode(signature),
|
|
2188
|
+
payload: ''
|
|
2189
|
+
};
|
|
2190
|
+
if (b64) jws.payload = decoder.decode(payload);
|
|
2191
|
+
if (this.#unprotectedHeader) jws.header = this.#unprotectedHeader;
|
|
2192
|
+
if (this.#protectedHeader) jws.protected = decoder.decode(protectedHeader);
|
|
2193
|
+
return jws;
|
|
2194
|
+
}
|
|
2195
|
+
}
|
|
2196
|
+
class CompactSign {
|
|
2197
|
+
#flattened;
|
|
2198
|
+
constructor(payload){
|
|
2199
|
+
this.#flattened = new FlattenedSign(payload);
|
|
2200
|
+
}
|
|
2201
|
+
setProtectedHeader(protectedHeader) {
|
|
2202
|
+
this.#flattened.setProtectedHeader(protectedHeader);
|
|
2203
|
+
return this;
|
|
2204
|
+
}
|
|
2205
|
+
async sign(key, options) {
|
|
2206
|
+
const jws = await this.#flattened.sign(key, options);
|
|
2207
|
+
if (void 0 === jws.payload) throw new TypeError('use the flattened module for creating JWS with b64: false');
|
|
2208
|
+
return `${jws.protected}.${jws.payload}.${jws.signature}`;
|
|
2209
|
+
}
|
|
2210
|
+
}
|
|
2211
|
+
const epoch = (date)=>Math.floor(date.getTime() / 1000);
|
|
2212
|
+
const minute = 60;
|
|
2213
|
+
const hour = 60 * minute;
|
|
2214
|
+
const day = 24 * hour;
|
|
2215
|
+
const week = 7 * day;
|
|
2216
|
+
const year = 365.25 * day;
|
|
2217
|
+
const REGEX = /^(\+|\-)? ?(\d+|\d+\.\d+) ?(seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)(?: (ago|from now))?$/i;
|
|
2218
|
+
const secs = (str)=>{
|
|
2219
|
+
const matched = REGEX.exec(str);
|
|
2220
|
+
if (!matched || matched[4] && matched[1]) throw new TypeError('Invalid time period format');
|
|
2221
|
+
const value = parseFloat(matched[2]);
|
|
2222
|
+
const unit = matched[3].toLowerCase();
|
|
2223
|
+
let numericDate;
|
|
2224
|
+
switch(unit){
|
|
2225
|
+
case 'sec':
|
|
2226
|
+
case 'secs':
|
|
2227
|
+
case 'second':
|
|
2228
|
+
case 'seconds':
|
|
2229
|
+
case 's':
|
|
2230
|
+
numericDate = Math.round(value);
|
|
2231
|
+
break;
|
|
2232
|
+
case 'minute':
|
|
2233
|
+
case 'minutes':
|
|
2234
|
+
case 'min':
|
|
2235
|
+
case 'mins':
|
|
2236
|
+
case 'm':
|
|
2237
|
+
numericDate = Math.round(value * minute);
|
|
2238
|
+
break;
|
|
2239
|
+
case 'hour':
|
|
2240
|
+
case 'hours':
|
|
2241
|
+
case 'hr':
|
|
2242
|
+
case 'hrs':
|
|
2243
|
+
case 'h':
|
|
2244
|
+
numericDate = Math.round(value * hour);
|
|
2245
|
+
break;
|
|
2246
|
+
case 'day':
|
|
2247
|
+
case 'days':
|
|
2248
|
+
case 'd':
|
|
2249
|
+
numericDate = Math.round(value * day);
|
|
2250
|
+
break;
|
|
2251
|
+
case 'week':
|
|
2252
|
+
case 'weeks':
|
|
2253
|
+
case 'w':
|
|
2254
|
+
numericDate = Math.round(value * week);
|
|
2255
|
+
break;
|
|
2256
|
+
default:
|
|
2257
|
+
numericDate = Math.round(value * year);
|
|
2258
|
+
break;
|
|
2259
|
+
}
|
|
2260
|
+
if ('-' === matched[1] || 'ago' === matched[4]) return -numericDate;
|
|
2261
|
+
return numericDate;
|
|
2262
|
+
};
|
|
2263
|
+
function validateInput(label, input) {
|
|
2264
|
+
if (!Number.isFinite(input)) throw new TypeError(`Invalid ${label} input`);
|
|
2265
|
+
return input;
|
|
2266
|
+
}
|
|
2267
|
+
const normalizeTyp = (value)=>value.toLowerCase().replace(/^application\//, '');
|
|
2268
|
+
const checkAudiencePresence = (audPayload, audOption)=>{
|
|
2269
|
+
if ('string' == typeof audPayload) return audOption.includes(audPayload);
|
|
2270
|
+
if (Array.isArray(audPayload)) return audOption.some(Set.prototype.has.bind(new Set(audPayload)));
|
|
2271
|
+
return false;
|
|
2272
|
+
};
|
|
2273
|
+
function validateClaimsSet(protectedHeader, encodedPayload, options = {}) {
|
|
2274
|
+
let payload;
|
|
2275
|
+
try {
|
|
2276
|
+
payload = JSON.parse(decoder.decode(encodedPayload));
|
|
2277
|
+
} catch {}
|
|
2278
|
+
if (!is_object(payload)) throw new JWTInvalid('JWT Claims Set must be a top-level JSON object');
|
|
2279
|
+
const { typ } = options;
|
|
2280
|
+
if (typ && ('string' != typeof protectedHeader.typ || normalizeTyp(protectedHeader.typ) !== normalizeTyp(typ))) throw new JWTClaimValidationFailed('unexpected "typ" JWT header value', payload, 'typ', 'check_failed');
|
|
2281
|
+
const { requiredClaims = [], issuer, subject, audience, maxTokenAge } = options;
|
|
2282
|
+
const presenceCheck = [
|
|
2283
|
+
...requiredClaims
|
|
2284
|
+
];
|
|
2285
|
+
if (void 0 !== maxTokenAge) presenceCheck.push('iat');
|
|
2286
|
+
if (void 0 !== audience) presenceCheck.push('aud');
|
|
2287
|
+
if (void 0 !== subject) presenceCheck.push('sub');
|
|
2288
|
+
if (void 0 !== issuer) presenceCheck.push('iss');
|
|
2289
|
+
for (const claim of new Set(presenceCheck.reverse()))if (!(claim in payload)) throw new JWTClaimValidationFailed(`missing required "${claim}" claim`, payload, claim, 'missing');
|
|
2290
|
+
if (issuer && !(Array.isArray(issuer) ? issuer : [
|
|
2291
|
+
issuer
|
|
2292
|
+
]).includes(payload.iss)) throw new JWTClaimValidationFailed('unexpected "iss" claim value', payload, 'iss', 'check_failed');
|
|
2293
|
+
if (subject && payload.sub !== subject) throw new JWTClaimValidationFailed('unexpected "sub" claim value', payload, 'sub', 'check_failed');
|
|
2294
|
+
if (audience && !checkAudiencePresence(payload.aud, 'string' == typeof audience ? [
|
|
2295
|
+
audience
|
|
2296
|
+
] : audience)) throw new JWTClaimValidationFailed('unexpected "aud" claim value', payload, 'aud', 'check_failed');
|
|
2297
|
+
let tolerance;
|
|
2298
|
+
switch(typeof options.clockTolerance){
|
|
2299
|
+
case 'string':
|
|
2300
|
+
tolerance = secs(options.clockTolerance);
|
|
2301
|
+
break;
|
|
2302
|
+
case 'number':
|
|
2303
|
+
tolerance = options.clockTolerance;
|
|
2304
|
+
break;
|
|
2305
|
+
case 'undefined':
|
|
2306
|
+
tolerance = 0;
|
|
2307
|
+
break;
|
|
2308
|
+
default:
|
|
2309
|
+
throw new TypeError('Invalid clockTolerance option type');
|
|
2310
|
+
}
|
|
2311
|
+
const { currentDate } = options;
|
|
2312
|
+
const now = epoch(currentDate || new Date());
|
|
2313
|
+
if ((void 0 !== payload.iat || maxTokenAge) && 'number' != typeof payload.iat) throw new JWTClaimValidationFailed('"iat" claim must be a number', payload, 'iat', 'invalid');
|
|
2314
|
+
if (void 0 !== payload.nbf) {
|
|
2315
|
+
if ('number' != typeof payload.nbf) throw new JWTClaimValidationFailed('"nbf" claim must be a number', payload, 'nbf', 'invalid');
|
|
2316
|
+
if (payload.nbf > now + tolerance) throw new JWTClaimValidationFailed('"nbf" claim timestamp check failed', payload, 'nbf', 'check_failed');
|
|
2317
|
+
}
|
|
2318
|
+
if (void 0 !== payload.exp) {
|
|
2319
|
+
if ('number' != typeof payload.exp) throw new JWTClaimValidationFailed('"exp" claim must be a number', payload, 'exp', 'invalid');
|
|
2320
|
+
if (payload.exp <= now - tolerance) throw new JWTExpired('"exp" claim timestamp check failed', payload, 'exp', 'check_failed');
|
|
2321
|
+
}
|
|
2322
|
+
if (maxTokenAge) {
|
|
2323
|
+
const age = now - payload.iat;
|
|
2324
|
+
const max = 'number' == typeof maxTokenAge ? maxTokenAge : secs(maxTokenAge);
|
|
2325
|
+
if (age - tolerance > max) throw new JWTExpired('"iat" claim timestamp check failed (too far in the past)', payload, 'iat', 'check_failed');
|
|
2326
|
+
if (age < 0 - tolerance) throw new JWTClaimValidationFailed('"iat" claim timestamp check failed (it should be in the past)', payload, 'iat', 'check_failed');
|
|
2327
|
+
}
|
|
2328
|
+
return payload;
|
|
2329
|
+
}
|
|
2330
|
+
class JWTClaimsBuilder {
|
|
2331
|
+
#payload;
|
|
2332
|
+
constructor(payload){
|
|
2333
|
+
if (!is_object(payload)) throw new TypeError('JWT Claims Set MUST be an object');
|
|
2334
|
+
this.#payload = structuredClone(payload);
|
|
2335
|
+
}
|
|
2336
|
+
data() {
|
|
2337
|
+
return encoder.encode(JSON.stringify(this.#payload));
|
|
2338
|
+
}
|
|
2339
|
+
get iss() {
|
|
2340
|
+
return this.#payload.iss;
|
|
2341
|
+
}
|
|
2342
|
+
set iss(value) {
|
|
2343
|
+
this.#payload.iss = value;
|
|
2344
|
+
}
|
|
2345
|
+
get sub() {
|
|
2346
|
+
return this.#payload.sub;
|
|
2347
|
+
}
|
|
2348
|
+
set sub(value) {
|
|
2349
|
+
this.#payload.sub = value;
|
|
2350
|
+
}
|
|
2351
|
+
get aud() {
|
|
2352
|
+
return this.#payload.aud;
|
|
2353
|
+
}
|
|
2354
|
+
set aud(value) {
|
|
2355
|
+
this.#payload.aud = value;
|
|
2356
|
+
}
|
|
2357
|
+
set jti(value) {
|
|
2358
|
+
this.#payload.jti = value;
|
|
2359
|
+
}
|
|
2360
|
+
set nbf(value) {
|
|
2361
|
+
if ('number' == typeof value) this.#payload.nbf = validateInput('setNotBefore', value);
|
|
2362
|
+
else if (value instanceof Date) this.#payload.nbf = validateInput('setNotBefore', epoch(value));
|
|
2363
|
+
else this.#payload.nbf = epoch(new Date()) + secs(value);
|
|
2364
|
+
}
|
|
2365
|
+
set exp(value) {
|
|
2366
|
+
if ('number' == typeof value) this.#payload.exp = validateInput('setExpirationTime', value);
|
|
2367
|
+
else if (value instanceof Date) this.#payload.exp = validateInput('setExpirationTime', epoch(value));
|
|
2368
|
+
else this.#payload.exp = epoch(new Date()) + secs(value);
|
|
2369
|
+
}
|
|
2370
|
+
set iat(value) {
|
|
2371
|
+
if (void 0 === value) this.#payload.iat = epoch(new Date());
|
|
2372
|
+
else if (value instanceof Date) this.#payload.iat = validateInput('setIssuedAt', epoch(value));
|
|
2373
|
+
else if ('string' == typeof value) this.#payload.iat = validateInput('setIssuedAt', epoch(new Date()) + secs(value));
|
|
2374
|
+
else this.#payload.iat = validateInput('setIssuedAt', value);
|
|
2375
|
+
}
|
|
2376
|
+
}
|
|
2377
|
+
class SignJWT {
|
|
2378
|
+
#protectedHeader;
|
|
2379
|
+
#jwt;
|
|
2380
|
+
constructor(payload = {}){
|
|
2381
|
+
this.#jwt = new JWTClaimsBuilder(payload);
|
|
2382
|
+
}
|
|
2383
|
+
setIssuer(issuer) {
|
|
2384
|
+
this.#jwt.iss = issuer;
|
|
2385
|
+
return this;
|
|
2386
|
+
}
|
|
2387
|
+
setSubject(subject) {
|
|
2388
|
+
this.#jwt.sub = subject;
|
|
2389
|
+
return this;
|
|
2390
|
+
}
|
|
2391
|
+
setAudience(audience) {
|
|
2392
|
+
this.#jwt.aud = audience;
|
|
2393
|
+
return this;
|
|
2394
|
+
}
|
|
2395
|
+
setJti(jwtId) {
|
|
2396
|
+
this.#jwt.jti = jwtId;
|
|
2397
|
+
return this;
|
|
2398
|
+
}
|
|
2399
|
+
setNotBefore(input) {
|
|
2400
|
+
this.#jwt.nbf = input;
|
|
2401
|
+
return this;
|
|
2402
|
+
}
|
|
2403
|
+
setExpirationTime(input) {
|
|
2404
|
+
this.#jwt.exp = input;
|
|
2405
|
+
return this;
|
|
2406
|
+
}
|
|
2407
|
+
setIssuedAt(input) {
|
|
2408
|
+
this.#jwt.iat = input;
|
|
2409
|
+
return this;
|
|
2410
|
+
}
|
|
2411
|
+
setProtectedHeader(protectedHeader) {
|
|
2412
|
+
this.#protectedHeader = protectedHeader;
|
|
2413
|
+
return this;
|
|
2414
|
+
}
|
|
2415
|
+
async sign(key, options) {
|
|
2416
|
+
const sig = new CompactSign(this.#jwt.data());
|
|
2417
|
+
sig.setProtectedHeader(this.#protectedHeader);
|
|
2418
|
+
if (Array.isArray(this.#protectedHeader?.crit) && this.#protectedHeader.crit.includes('b64') && false === this.#protectedHeader.b64) throw new JWTInvalid('JWTs MUST NOT use unencoded payload');
|
|
2419
|
+
return sig.sign(key, options);
|
|
2420
|
+
}
|
|
2421
|
+
}
|
|
2422
|
+
const withJwtSignedUrl = async ({ data, reqUrl, jwtSecret })=>{
|
|
2423
|
+
if (!data) return null;
|
|
2424
|
+
if (data.id === __WEBPACK_EXTERNAL_MODULE__hot_updater_core_132f924c__.NIL_UUID) return {
|
|
2425
|
+
...data,
|
|
2426
|
+
fileUrl: null
|
|
2427
|
+
};
|
|
2428
|
+
const key = `${data.id}/bundle.zip`;
|
|
2429
|
+
const token = await signToken(key, jwtSecret);
|
|
2430
|
+
const url = new URL(reqUrl);
|
|
2431
|
+
url.pathname = `/${key}`;
|
|
2432
|
+
url.searchParams.set("token", token);
|
|
2433
|
+
return {
|
|
2434
|
+
...data,
|
|
2435
|
+
fileUrl: url.toString()
|
|
2436
|
+
};
|
|
2437
|
+
};
|
|
2438
|
+
const signToken = async (key, jwtSecret)=>{
|
|
2439
|
+
const secretKey = new TextEncoder().encode(jwtSecret);
|
|
2440
|
+
const token = await new SignJWT({
|
|
2441
|
+
key
|
|
2442
|
+
}).setProtectedHeader({
|
|
2443
|
+
alg: "HS256"
|
|
2444
|
+
}).setExpirationTime("60s").sign(secretKey);
|
|
2445
|
+
return token;
|
|
2446
|
+
};
|
|
2447
|
+
const verify = async (alg, key, signature, data)=>{
|
|
2448
|
+
const cryptoKey = await get_sign_verify_key(alg, key, 'verify');
|
|
2449
|
+
check_key_length(alg, cryptoKey);
|
|
2450
|
+
const algorithm = subtle_dsa(alg, cryptoKey.algorithm);
|
|
2451
|
+
try {
|
|
2452
|
+
return await crypto.subtle.verify(algorithm, cryptoKey, signature, data);
|
|
2453
|
+
} catch {
|
|
2454
|
+
return false;
|
|
2455
|
+
}
|
|
2456
|
+
};
|
|
2457
|
+
const validate_algorithms = (option, algorithms)=>{
|
|
2458
|
+
if (void 0 !== algorithms && (!Array.isArray(algorithms) || algorithms.some((s)=>'string' != typeof s))) throw new TypeError(`"${option}" option must be an array of strings`);
|
|
2459
|
+
if (!algorithms) return;
|
|
2460
|
+
return new Set(algorithms);
|
|
2461
|
+
};
|
|
2462
|
+
async function flattenedVerify(jws, key, options) {
|
|
2463
|
+
if (!is_object(jws)) throw new JWSInvalid('Flattened JWS must be an object');
|
|
2464
|
+
if (void 0 === jws.protected && void 0 === jws.header) throw new JWSInvalid('Flattened JWS must have either of the "protected" or "header" members');
|
|
2465
|
+
if (void 0 !== jws.protected && 'string' != typeof jws.protected) throw new JWSInvalid('JWS Protected Header incorrect type');
|
|
2466
|
+
if (void 0 === jws.payload) throw new JWSInvalid('JWS Payload missing');
|
|
2467
|
+
if ('string' != typeof jws.signature) throw new JWSInvalid('JWS Signature missing or incorrect type');
|
|
2468
|
+
if (void 0 !== jws.header && !is_object(jws.header)) throw new JWSInvalid('JWS Unprotected Header incorrect type');
|
|
2469
|
+
let parsedProt = {};
|
|
2470
|
+
if (jws.protected) try {
|
|
2471
|
+
const protectedHeader = decode(jws.protected);
|
|
2472
|
+
parsedProt = JSON.parse(decoder.decode(protectedHeader));
|
|
2473
|
+
} catch {
|
|
2474
|
+
throw new JWSInvalid('JWS Protected Header is invalid');
|
|
2475
|
+
}
|
|
2476
|
+
if (!is_disjoint(parsedProt, jws.header)) throw new JWSInvalid('JWS Protected and JWS Unprotected Header Parameter names must be disjoint');
|
|
2477
|
+
const joseHeader = {
|
|
2478
|
+
...parsedProt,
|
|
2479
|
+
...jws.header
|
|
2480
|
+
};
|
|
2481
|
+
const extensions = validate_crit(JWSInvalid, new Map([
|
|
2482
|
+
[
|
|
2483
|
+
'b64',
|
|
2484
|
+
true
|
|
2485
|
+
]
|
|
2486
|
+
]), options?.crit, parsedProt, joseHeader);
|
|
2487
|
+
let b64 = true;
|
|
2488
|
+
if (extensions.has('b64')) {
|
|
2489
|
+
b64 = parsedProt.b64;
|
|
2490
|
+
if ('boolean' != typeof b64) throw new JWSInvalid('The "b64" (base64url-encode payload) Header Parameter must be a boolean');
|
|
2491
|
+
}
|
|
2492
|
+
const { alg } = joseHeader;
|
|
2493
|
+
if ('string' != typeof alg || !alg) throw new JWSInvalid('JWS "alg" (Algorithm) Header Parameter missing or invalid');
|
|
2494
|
+
const algorithms = options && validate_algorithms('algorithms', options.algorithms);
|
|
2495
|
+
if (algorithms && !algorithms.has(alg)) throw new JOSEAlgNotAllowed('"alg" (Algorithm) Header Parameter value not allowed');
|
|
2496
|
+
if (b64) {
|
|
2497
|
+
if ('string' != typeof jws.payload) throw new JWSInvalid('JWS Payload must be a string');
|
|
2498
|
+
} else if ('string' != typeof jws.payload && !(jws.payload instanceof Uint8Array)) throw new JWSInvalid('JWS Payload must be a string or an Uint8Array instance');
|
|
2499
|
+
let resolvedKey = false;
|
|
2500
|
+
if ('function' == typeof key) {
|
|
2501
|
+
key = await key(parsedProt, jws);
|
|
2502
|
+
resolvedKey = true;
|
|
2503
|
+
}
|
|
2504
|
+
check_key_type(alg, key, 'verify');
|
|
2505
|
+
const data = concat(encoder.encode(jws.protected ?? ''), encoder.encode('.'), 'string' == typeof jws.payload ? encoder.encode(jws.payload) : jws.payload);
|
|
2506
|
+
let signature;
|
|
2507
|
+
try {
|
|
2508
|
+
signature = decode(jws.signature);
|
|
2509
|
+
} catch {
|
|
2510
|
+
throw new JWSInvalid('Failed to base64url decode the signature');
|
|
2511
|
+
}
|
|
2512
|
+
const k = await normalize_key(key, alg);
|
|
2513
|
+
const verified = await verify(alg, k, signature, data);
|
|
2514
|
+
if (!verified) throw new JWSSignatureVerificationFailed();
|
|
2515
|
+
let payload;
|
|
2516
|
+
if (b64) try {
|
|
2517
|
+
payload = decode(jws.payload);
|
|
2518
|
+
} catch {
|
|
2519
|
+
throw new JWSInvalid('Failed to base64url decode the payload');
|
|
2520
|
+
}
|
|
2521
|
+
else payload = 'string' == typeof jws.payload ? encoder.encode(jws.payload) : jws.payload;
|
|
2522
|
+
const result = {
|
|
2523
|
+
payload
|
|
2524
|
+
};
|
|
2525
|
+
if (void 0 !== jws.protected) result.protectedHeader = parsedProt;
|
|
2526
|
+
if (void 0 !== jws.header) result.unprotectedHeader = jws.header;
|
|
2527
|
+
if (resolvedKey) return {
|
|
2528
|
+
...result,
|
|
2529
|
+
key: k
|
|
2530
|
+
};
|
|
2531
|
+
return result;
|
|
2532
|
+
}
|
|
2533
|
+
async function compactVerify(jws, key, options) {
|
|
2534
|
+
if (jws instanceof Uint8Array) jws = decoder.decode(jws);
|
|
2535
|
+
if ('string' != typeof jws) throw new JWSInvalid('Compact JWS must be a string or Uint8Array');
|
|
2536
|
+
const { 0: protectedHeader, 1: payload, 2: signature, length } = jws.split('.');
|
|
2537
|
+
if (3 !== length) throw new JWSInvalid('Invalid Compact JWS');
|
|
2538
|
+
const verified = await flattenedVerify({
|
|
2539
|
+
payload,
|
|
2540
|
+
protected: protectedHeader,
|
|
2541
|
+
signature
|
|
2542
|
+
}, key, options);
|
|
2543
|
+
const result = {
|
|
2544
|
+
payload: verified.payload,
|
|
2545
|
+
protectedHeader: verified.protectedHeader
|
|
2546
|
+
};
|
|
2547
|
+
if ('function' == typeof key) return {
|
|
2548
|
+
...result,
|
|
2549
|
+
key: verified.key
|
|
2550
|
+
};
|
|
2551
|
+
return result;
|
|
2552
|
+
}
|
|
2553
|
+
async function jwtVerify(jwt, key, options) {
|
|
2554
|
+
const verified = await compactVerify(jwt, key, options);
|
|
2555
|
+
if (verified.protectedHeader.crit?.includes('b64') && false === verified.protectedHeader.b64) throw new JWTInvalid('JWTs MUST NOT use unencoded payload');
|
|
2556
|
+
const payload = validateClaimsSet(verified.protectedHeader, verified.payload, options);
|
|
2557
|
+
const result = {
|
|
2558
|
+
payload,
|
|
2559
|
+
protectedHeader: verified.protectedHeader
|
|
2560
|
+
};
|
|
2561
|
+
if ('function' == typeof key) return {
|
|
2562
|
+
...result,
|
|
2563
|
+
key: verified.key
|
|
2564
|
+
};
|
|
2565
|
+
return result;
|
|
2566
|
+
}
|
|
2567
|
+
const verifyJwtToken = async ({ path, token, jwtSecret })=>{
|
|
2568
|
+
const key = path.replace(/^\/+/, "");
|
|
2569
|
+
if (!token) return {
|
|
2570
|
+
valid: false,
|
|
2571
|
+
error: "Missing token"
|
|
2572
|
+
};
|
|
2573
|
+
try {
|
|
2574
|
+
const secretKey = new TextEncoder().encode(jwtSecret);
|
|
2575
|
+
const { payload } = await jwtVerify(token, secretKey);
|
|
2576
|
+
if (!payload || payload.key !== key) return {
|
|
2577
|
+
valid: false,
|
|
2578
|
+
error: "Token does not match requested file"
|
|
2579
|
+
};
|
|
2580
|
+
return {
|
|
2581
|
+
valid: true,
|
|
2582
|
+
key
|
|
2583
|
+
};
|
|
2584
|
+
} catch (error) {
|
|
2585
|
+
return {
|
|
2586
|
+
valid: false,
|
|
2587
|
+
error: "Invalid or expired token"
|
|
2588
|
+
};
|
|
2589
|
+
}
|
|
2590
|
+
};
|
|
2591
|
+
const getFileResponse = async ({ key, handler })=>{
|
|
2592
|
+
const object = await handler(key);
|
|
2593
|
+
if (!object) return {
|
|
2594
|
+
status: 404,
|
|
2595
|
+
error: "File not found"
|
|
2596
|
+
};
|
|
2597
|
+
const pathParts = key.split("/");
|
|
2598
|
+
const fileName = pathParts[pathParts.length - 1];
|
|
2599
|
+
const headers = {
|
|
2600
|
+
"Content-Type": object.contentType || "application/octet-stream",
|
|
2601
|
+
"Content-Disposition": `attachment; filename=${fileName}`
|
|
2602
|
+
};
|
|
2603
|
+
return {
|
|
2604
|
+
status: 200,
|
|
2605
|
+
responseHeaders: headers,
|
|
2606
|
+
responseBody: object.body
|
|
2607
|
+
};
|
|
2608
|
+
};
|
|
2609
|
+
const verifyJwtSignedUrl = async ({ path, token, jwtSecret, handler })=>{
|
|
2610
|
+
const result = await verifyJwtToken({
|
|
2611
|
+
path,
|
|
2612
|
+
token,
|
|
2613
|
+
jwtSecret
|
|
2614
|
+
});
|
|
2615
|
+
if (!result.valid) {
|
|
2616
|
+
if ("Missing token" === result.error) return {
|
|
2617
|
+
status: 400,
|
|
2618
|
+
error: result.error
|
|
2619
|
+
};
|
|
2620
|
+
return {
|
|
2621
|
+
status: 403,
|
|
2622
|
+
error: result.error || "Unauthorized"
|
|
2623
|
+
};
|
|
2624
|
+
}
|
|
2625
|
+
return getFileResponse({
|
|
2626
|
+
key: result.key,
|
|
2627
|
+
handler
|
|
2628
|
+
});
|
|
1409
2629
|
};
|
|
1410
|
-
export { filterCompatibleAppVersions, getUpdateInfo, semverSatisfies };
|
|
2630
|
+
export { filterCompatibleAppVersions, getUpdateInfo, semverSatisfies, signToken, verifyJwtSignedUrl, verifyJwtToken, withJwtSignedUrl };
|