@foxnose/sdk 0.8.0 → 0.9.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +98 -0
- package/dist/index.cjs +1173 -13
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +693 -4
- package/dist/index.d.ts +693 -4
- package/dist/index.js +1160 -12
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -421,6 +421,476 @@ var SimpleKeyAuth = class {
|
|
|
421
421
|
}
|
|
422
422
|
};
|
|
423
423
|
|
|
424
|
+
// src/tenantTokens.ts
|
|
425
|
+
import {
|
|
426
|
+
createPrivateKey,
|
|
427
|
+
generateKeyPairSync,
|
|
428
|
+
randomBytes,
|
|
429
|
+
sign as cryptoSign
|
|
430
|
+
} from "crypto";
|
|
431
|
+
var TENANT_TOKEN_PREFIX = "fxt_";
|
|
432
|
+
var MAX_TOKEN_BYTES = 4096;
|
|
433
|
+
var MAX_TTL_SECONDS = 86400;
|
|
434
|
+
var MAX_ANCHORS = 10;
|
|
435
|
+
var SUB_MAX = 128;
|
|
436
|
+
var ANCHOR_RECORD_MAX = 64;
|
|
437
|
+
var KID_RE = /^tsk_[A-Za-z0-9]{12}$/;
|
|
438
|
+
var JTI_RE = /^[A-Za-z0-9_-]{16,64}$/;
|
|
439
|
+
var NOT_PRINTABLE_RE = /[\p{C}\p{Z}]/u;
|
|
440
|
+
function generateTenantSigningKey() {
|
|
441
|
+
const { privateKey, publicKey } = generateKeyPairSync("ec", { namedCurve: "P-256" });
|
|
442
|
+
const pair = {
|
|
443
|
+
publicKey: publicKey.export({ format: "der", type: "spki" }).toString("base64")
|
|
444
|
+
};
|
|
445
|
+
Object.defineProperty(pair, "privateKey", {
|
|
446
|
+
value: privateKey.export({ format: "der", type: "pkcs8" }).toString("base64"),
|
|
447
|
+
enumerable: false,
|
|
448
|
+
writable: false
|
|
449
|
+
});
|
|
450
|
+
return pair;
|
|
451
|
+
}
|
|
452
|
+
function isInt(value) {
|
|
453
|
+
return typeof value === "number" && Number.isSafeInteger(value);
|
|
454
|
+
}
|
|
455
|
+
function stringList(name, value) {
|
|
456
|
+
if (!Array.isArray(value) || !value.every((v) => typeof v === "string")) {
|
|
457
|
+
throw new Error(`${name} must be an array of strings`);
|
|
458
|
+
}
|
|
459
|
+
return [...value];
|
|
460
|
+
}
|
|
461
|
+
function anchorClaim(anchors) {
|
|
462
|
+
if (!Array.isArray(anchors)) {
|
|
463
|
+
throw new Error("anchors must be an array of [collectionKey, recordKey] pairs");
|
|
464
|
+
}
|
|
465
|
+
if (anchors.length < 1 || anchors.length > MAX_ANCHORS) {
|
|
466
|
+
throw new Error(`anchors must hold 1 to ${MAX_ANCHORS} entries`);
|
|
467
|
+
}
|
|
468
|
+
const seen = /* @__PURE__ */ new Set();
|
|
469
|
+
return anchors.map((item) => {
|
|
470
|
+
let collection;
|
|
471
|
+
let record;
|
|
472
|
+
if (Array.isArray(item) && item.length === 2) {
|
|
473
|
+
[collection, record] = item;
|
|
474
|
+
} else if (item && typeof item === "object" && !Array.isArray(item)) {
|
|
475
|
+
const anchor = item;
|
|
476
|
+
collection = anchor.collection ?? anchor.c;
|
|
477
|
+
record = anchor.record ?? anchor.r;
|
|
478
|
+
} else {
|
|
479
|
+
throw new Error("each anchor must be a [collectionKey, recordKey] pair");
|
|
480
|
+
}
|
|
481
|
+
if (typeof collection !== "string" || collection.length === 0) {
|
|
482
|
+
throw new Error("an anchor's collection key must be a non-empty string");
|
|
483
|
+
}
|
|
484
|
+
if (typeof record !== "string" || [...record].length < 1 || [...record].length > ANCHOR_RECORD_MAX) {
|
|
485
|
+
throw new Error(
|
|
486
|
+
`an anchor's record key must be a string of 1 to ${ANCHOR_RECORD_MAX} characters`
|
|
487
|
+
);
|
|
488
|
+
}
|
|
489
|
+
const id = `${collection}\0${record}`;
|
|
490
|
+
if (seen.has(id)) {
|
|
491
|
+
throw new Error("anchors must not repeat");
|
|
492
|
+
}
|
|
493
|
+
seen.add(id);
|
|
494
|
+
return { c: collection, r: record };
|
|
495
|
+
});
|
|
496
|
+
}
|
|
497
|
+
function loadPrivateKey(privateKey) {
|
|
498
|
+
let key;
|
|
499
|
+
try {
|
|
500
|
+
if (typeof privateKey === "object" && "asymmetricKeyType" in privateKey) {
|
|
501
|
+
key = privateKey;
|
|
502
|
+
} else if (typeof privateKey === "string" && privateKey.trimStart().startsWith("-----BEGIN")) {
|
|
503
|
+
key = createPrivateKey(privateKey);
|
|
504
|
+
} else {
|
|
505
|
+
const der = typeof privateKey === "string" ? Buffer.from(privateKey, "base64") : Buffer.from(privateKey);
|
|
506
|
+
try {
|
|
507
|
+
key = createPrivateKey({ key: der, format: "der", type: "pkcs8" });
|
|
508
|
+
} catch {
|
|
509
|
+
key = createPrivateKey({ key: der, format: "der", type: "sec1" });
|
|
510
|
+
}
|
|
511
|
+
}
|
|
512
|
+
} catch {
|
|
513
|
+
throw new Error(
|
|
514
|
+
"privateKey is not a P-256 private key in PEM, PKCS#8 DER or base64 PKCS#8 DER form"
|
|
515
|
+
);
|
|
516
|
+
}
|
|
517
|
+
if (key.type !== "private" || key.asymmetricKeyType !== "ec" || key.asymmetricKeyDetails?.namedCurve !== "prime256v1") {
|
|
518
|
+
throw new Error("privateKey must be a P-256 (prime256v1) private key");
|
|
519
|
+
}
|
|
520
|
+
return key;
|
|
521
|
+
}
|
|
522
|
+
function b64url(data) {
|
|
523
|
+
return Buffer.from(data).toString("base64url");
|
|
524
|
+
}
|
|
525
|
+
function signTenantToken(privateKey, options) {
|
|
526
|
+
const { kid, environmentKey, sub } = options;
|
|
527
|
+
if (typeof kid !== "string" || !KID_RE.test(kid)) {
|
|
528
|
+
throw new Error("kid must be 'tsk_' followed by 12 letters or digits");
|
|
529
|
+
}
|
|
530
|
+
if (typeof environmentKey !== "string" || environmentKey.length === 0) {
|
|
531
|
+
throw new Error("environmentKey must be a non-empty string");
|
|
532
|
+
}
|
|
533
|
+
if (typeof sub !== "string" || [...sub].length < 1 || [...sub].length > SUB_MAX || [...sub].some((ch) => ch !== " " && NOT_PRINTABLE_RE.test(ch))) {
|
|
534
|
+
throw new Error(`sub must be 1 to ${SUB_MAX} printable characters`);
|
|
535
|
+
}
|
|
536
|
+
const ttl = options.ttl ?? 900;
|
|
537
|
+
if (!isInt(ttl) || ttl < 1 || ttl > MAX_TTL_SECONDS) {
|
|
538
|
+
throw new Error(`ttl must be an integer from 1 to ${MAX_TTL_SECONDS}`);
|
|
539
|
+
}
|
|
540
|
+
const jti = options.jti ?? randomBytes(24).toString("base64url");
|
|
541
|
+
if (typeof jti !== "string" || !JTI_RE.test(jti)) {
|
|
542
|
+
throw new Error("jti must be 16 to 64 characters of A-Z a-z 0-9 - _");
|
|
543
|
+
}
|
|
544
|
+
const iat = options.now ?? Math.floor(Date.now() / 1e3);
|
|
545
|
+
if (!isInt(iat)) {
|
|
546
|
+
throw new Error("now must be an integer number of seconds");
|
|
547
|
+
}
|
|
548
|
+
const exp = iat + ttl;
|
|
549
|
+
const claims = {
|
|
550
|
+
aud: `flux:${environmentKey}`,
|
|
551
|
+
sub,
|
|
552
|
+
anc: anchorClaim(options.anchors),
|
|
553
|
+
iat,
|
|
554
|
+
exp,
|
|
555
|
+
jti
|
|
556
|
+
};
|
|
557
|
+
if (options.notBefore !== void 0) {
|
|
558
|
+
if (!isInt(options.notBefore) || options.notBefore >= exp) {
|
|
559
|
+
throw new Error("notBefore must be an integer before the token's expiry");
|
|
560
|
+
}
|
|
561
|
+
claims.nbf = options.notBefore;
|
|
562
|
+
}
|
|
563
|
+
if (options.apis !== void 0) {
|
|
564
|
+
if (!options.apis || typeof options.apis !== "object" || Array.isArray(options.apis)) {
|
|
565
|
+
throw new Error("apis must map an API prefix to a list of actions");
|
|
566
|
+
}
|
|
567
|
+
const apis = {};
|
|
568
|
+
for (const [prefix, actions] of Object.entries(options.apis)) {
|
|
569
|
+
apis[prefix] = stringList("each apis entry", actions);
|
|
570
|
+
}
|
|
571
|
+
claims.apis = apis;
|
|
572
|
+
}
|
|
573
|
+
if (options.collections !== void 0) {
|
|
574
|
+
claims.col = stringList("collections", options.collections);
|
|
575
|
+
}
|
|
576
|
+
if (options.sharedRead !== void 0) {
|
|
577
|
+
claims.shr = stringList("sharedRead", options.sharedRead);
|
|
578
|
+
}
|
|
579
|
+
const key = loadPrivateKey(privateKey);
|
|
580
|
+
const header = { alg: "ES256", typ: "fxt+jwt", kid };
|
|
581
|
+
const signingInput = `${b64url(JSON.stringify(header))}.${b64url(JSON.stringify(claims))}`;
|
|
582
|
+
const signature = cryptoSign("sha256", Buffer.from(signingInput, "ascii"), {
|
|
583
|
+
key,
|
|
584
|
+
dsaEncoding: "ieee-p1363"
|
|
585
|
+
});
|
|
586
|
+
const token = `${TENANT_TOKEN_PREFIX}${signingInput}.${b64url(signature)}`;
|
|
587
|
+
if (Buffer.byteLength(token, "utf8") > MAX_TOKEN_BYTES) {
|
|
588
|
+
throw new Error(
|
|
589
|
+
`the token is longer than ${MAX_TOKEN_BYTES} bytes; use fewer or shorter claims`
|
|
590
|
+
);
|
|
591
|
+
}
|
|
592
|
+
return token;
|
|
593
|
+
}
|
|
594
|
+
var HTTP_TOKEN = "[!#$%&'*+\\-.^_`|~0-9A-Za-z]+";
|
|
595
|
+
var SCHEME_RE = new RegExp(HTTP_TOKEN, "y");
|
|
596
|
+
var PARAM_RE = new RegExp(
|
|
597
|
+
`(${HTTP_TOKEN})[ \\t]*=[ \\t]*(?:"((?:[^"\\\\]|\\\\.)*)"|(${HTTP_TOKEN}))`,
|
|
598
|
+
"y"
|
|
599
|
+
);
|
|
600
|
+
function bearerErrors(wwwAuthenticate) {
|
|
601
|
+
const errors = [];
|
|
602
|
+
let scheme = null;
|
|
603
|
+
let i = 0;
|
|
604
|
+
while (i < wwwAuthenticate.length) {
|
|
605
|
+
const ch = wwwAuthenticate[i];
|
|
606
|
+
if (ch === " " || ch === " " || ch === ",") {
|
|
607
|
+
i += 1;
|
|
608
|
+
continue;
|
|
609
|
+
}
|
|
610
|
+
PARAM_RE.lastIndex = i;
|
|
611
|
+
const param = scheme !== null ? PARAM_RE.exec(wwwAuthenticate) : null;
|
|
612
|
+
if (param) {
|
|
613
|
+
const name = param[1].toLowerCase();
|
|
614
|
+
const value = param[2] !== void 0 ? param[2].replace(/\\(.)/g, "$1") : param[3];
|
|
615
|
+
if (scheme === "bearer" && name === "error") {
|
|
616
|
+
errors.push(value);
|
|
617
|
+
}
|
|
618
|
+
i = PARAM_RE.lastIndex;
|
|
619
|
+
continue;
|
|
620
|
+
}
|
|
621
|
+
SCHEME_RE.lastIndex = i;
|
|
622
|
+
const word = SCHEME_RE.exec(wwwAuthenticate);
|
|
623
|
+
if (word) {
|
|
624
|
+
scheme = word[0].toLowerCase();
|
|
625
|
+
i = SCHEME_RE.lastIndex;
|
|
626
|
+
continue;
|
|
627
|
+
}
|
|
628
|
+
i += 1;
|
|
629
|
+
}
|
|
630
|
+
return errors;
|
|
631
|
+
}
|
|
632
|
+
function isInvalidTokenChallenge(status, wwwAuthenticate) {
|
|
633
|
+
if (status !== 401 || !wwwAuthenticate) {
|
|
634
|
+
return false;
|
|
635
|
+
}
|
|
636
|
+
return bearerErrors(wwwAuthenticate).includes("invalid_token");
|
|
637
|
+
}
|
|
638
|
+
function notAToken(detail) {
|
|
639
|
+
return new Error(`mint must return a tenant token (fxt_...): ${detail}`);
|
|
640
|
+
}
|
|
641
|
+
function decodeSegment(segment) {
|
|
642
|
+
if (!/^[A-Za-z0-9_-]*$/.test(segment)) {
|
|
643
|
+
throw notAToken("it cannot be decoded");
|
|
644
|
+
}
|
|
645
|
+
try {
|
|
646
|
+
return JSON.parse(Buffer.from(segment, "base64url").toString("utf8"));
|
|
647
|
+
} catch {
|
|
648
|
+
throw notAToken("it cannot be decoded");
|
|
649
|
+
}
|
|
650
|
+
}
|
|
651
|
+
function sortedStrings(value, name) {
|
|
652
|
+
if (value === void 0) {
|
|
653
|
+
return null;
|
|
654
|
+
}
|
|
655
|
+
if (!Array.isArray(value) || !value.every((v) => typeof v === "string")) {
|
|
656
|
+
throw notAToken(`${name} is not a list of strings`);
|
|
657
|
+
}
|
|
658
|
+
return [...new Set(value)].sort();
|
|
659
|
+
}
|
|
660
|
+
function isObject(value) {
|
|
661
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
662
|
+
}
|
|
663
|
+
function inspectMinted(token) {
|
|
664
|
+
if (typeof token !== "string" || !token.startsWith(TENANT_TOKEN_PREFIX)) {
|
|
665
|
+
throw notAToken("no fxt_ prefix");
|
|
666
|
+
}
|
|
667
|
+
const parts = token.slice(TENANT_TOKEN_PREFIX.length).split(".");
|
|
668
|
+
if (parts.length !== 3) {
|
|
669
|
+
throw notAToken("it cannot be decoded");
|
|
670
|
+
}
|
|
671
|
+
const header = decodeSegment(parts[0]);
|
|
672
|
+
const claims = decodeSegment(parts[1]);
|
|
673
|
+
if (!isObject(header) || !isObject(claims)) {
|
|
674
|
+
throw notAToken("its header or claims are not objects");
|
|
675
|
+
}
|
|
676
|
+
for (const [name, value] of [
|
|
677
|
+
["kid", header.kid],
|
|
678
|
+
["aud", claims.aud],
|
|
679
|
+
["sub", claims.sub]
|
|
680
|
+
]) {
|
|
681
|
+
if (typeof value !== "string") {
|
|
682
|
+
throw notAToken(`${name} is not a string`);
|
|
683
|
+
}
|
|
684
|
+
}
|
|
685
|
+
if (!isInt(claims.exp)) {
|
|
686
|
+
throw notAToken("exp is not an integer");
|
|
687
|
+
}
|
|
688
|
+
const anchors = claims.anc;
|
|
689
|
+
if (!Array.isArray(anchors) || !anchors.every(
|
|
690
|
+
(a) => isObject(a) && Object.keys(a).sort().join(",") === "c,r" && typeof a.c === "string" && typeof a.r === "string"
|
|
691
|
+
)) {
|
|
692
|
+
throw notAToken("anc is not a list of {c, r} strings");
|
|
693
|
+
}
|
|
694
|
+
let apis = null;
|
|
695
|
+
if (claims.apis !== void 0) {
|
|
696
|
+
if (!isObject(claims.apis)) {
|
|
697
|
+
throw notAToken("apis is not an object");
|
|
698
|
+
}
|
|
699
|
+
apis = {};
|
|
700
|
+
for (const prefix of Object.keys(claims.apis).sort()) {
|
|
701
|
+
apis[prefix] = sortedStrings(claims.apis[prefix], "an apis entry");
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
const scope = JSON.stringify([
|
|
705
|
+
header.kid,
|
|
706
|
+
claims.aud,
|
|
707
|
+
claims.sub,
|
|
708
|
+
[
|
|
709
|
+
...new Set(anchors.map((a) => `${a.c}\0${a.r}`))
|
|
710
|
+
].sort(),
|
|
711
|
+
apis === null ? null : Object.entries(apis),
|
|
712
|
+
sortedStrings(claims.col, "col"),
|
|
713
|
+
sortedStrings(claims.shr, "shr")
|
|
714
|
+
]);
|
|
715
|
+
return { token, expiresAt: claims.exp, scope };
|
|
716
|
+
}
|
|
717
|
+
var SOURCE_STATE = /* @__PURE__ */ new WeakMap();
|
|
718
|
+
function stateOf(source) {
|
|
719
|
+
return SOURCE_STATE.get(source);
|
|
720
|
+
}
|
|
721
|
+
var INSPECT = /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom");
|
|
722
|
+
var TenantTokenSource = class {
|
|
723
|
+
mint;
|
|
724
|
+
refreshBefore;
|
|
725
|
+
clock;
|
|
726
|
+
constructor(mint, options) {
|
|
727
|
+
if (typeof mint !== "function") {
|
|
728
|
+
throw new TypeError("mint must be a function that returns a token");
|
|
729
|
+
}
|
|
730
|
+
const refreshBefore = options?.refreshBefore ?? 60;
|
|
731
|
+
if (!isInt(refreshBefore) || refreshBefore < 0) {
|
|
732
|
+
throw new Error("refreshBefore must be a non-negative integer");
|
|
733
|
+
}
|
|
734
|
+
this.mint = mint;
|
|
735
|
+
this.refreshBefore = refreshBefore;
|
|
736
|
+
this.clock = options?.clock ?? Date.now;
|
|
737
|
+
SOURCE_STATE.set(this, { current: null, scope: null, inFlight: null });
|
|
738
|
+
}
|
|
739
|
+
toJSON() {
|
|
740
|
+
return { refreshBefore: this.refreshBefore };
|
|
741
|
+
}
|
|
742
|
+
[INSPECT]() {
|
|
743
|
+
return `TenantTokenSource { refreshBefore: ${this.refreshBefore} }`;
|
|
744
|
+
}
|
|
745
|
+
fresh() {
|
|
746
|
+
const current = stateOf(this).current;
|
|
747
|
+
if (current && this.clock() / 1e3 < current.expiresAt - this.refreshBefore) {
|
|
748
|
+
return current.token;
|
|
749
|
+
}
|
|
750
|
+
return null;
|
|
751
|
+
}
|
|
752
|
+
accept(raw) {
|
|
753
|
+
const minted = inspectMinted(raw);
|
|
754
|
+
const state = stateOf(this);
|
|
755
|
+
if (state.scope === null) {
|
|
756
|
+
state.scope = minted.scope;
|
|
757
|
+
} else if (minted.scope !== state.scope) {
|
|
758
|
+
throw new Error(
|
|
759
|
+
"mint returned a token for another scope (signing key, environment, sub, anchors or narrowing claims); use one TenantTokenSource per end user"
|
|
760
|
+
);
|
|
761
|
+
}
|
|
762
|
+
state.current = minted;
|
|
763
|
+
return minted.token;
|
|
764
|
+
}
|
|
765
|
+
/** The current token, minted again when close to expiry. `mint` must be synchronous. */
|
|
766
|
+
tokenSync() {
|
|
767
|
+
const fresh = this.fresh();
|
|
768
|
+
if (fresh !== null) {
|
|
769
|
+
return fresh;
|
|
770
|
+
}
|
|
771
|
+
const raw = this.mint();
|
|
772
|
+
if (raw && typeof raw.then === "function") {
|
|
773
|
+
raw.then(void 0, () => void 0);
|
|
774
|
+
throw new TypeError("mint returned a Promise; use token() or tenantTokenFetch");
|
|
775
|
+
}
|
|
776
|
+
return this.accept(raw);
|
|
777
|
+
}
|
|
778
|
+
/** The current token, minted again when close to expiry. Concurrent callers share one mint. */
|
|
779
|
+
async token() {
|
|
780
|
+
const fresh = this.fresh();
|
|
781
|
+
if (fresh !== null) {
|
|
782
|
+
return fresh;
|
|
783
|
+
}
|
|
784
|
+
const state = stateOf(this);
|
|
785
|
+
if (state.inFlight === null) {
|
|
786
|
+
state.inFlight = (async () => {
|
|
787
|
+
try {
|
|
788
|
+
return this.accept(await this.mint());
|
|
789
|
+
} finally {
|
|
790
|
+
state.inFlight = null;
|
|
791
|
+
}
|
|
792
|
+
})();
|
|
793
|
+
}
|
|
794
|
+
return state.inFlight;
|
|
795
|
+
}
|
|
796
|
+
/**
|
|
797
|
+
* Mint a new token on the next request. With `token`, only if the cached token is
|
|
798
|
+
* still that one, so a refusal of an older token leaves a newer one in place.
|
|
799
|
+
*/
|
|
800
|
+
invalidate(token) {
|
|
801
|
+
const state = stateOf(this);
|
|
802
|
+
if (token === void 0 || state.current !== null && state.current.token === token) {
|
|
803
|
+
state.current = null;
|
|
804
|
+
}
|
|
805
|
+
}
|
|
806
|
+
};
|
|
807
|
+
function sourceOf(mint, options) {
|
|
808
|
+
return mint instanceof TenantTokenSource ? mint : new TenantTokenSource(mint, options);
|
|
809
|
+
}
|
|
810
|
+
function refusedToken(status, wwwAuthenticate, failedAuthorization) {
|
|
811
|
+
if (!isInvalidTokenChallenge(status, wwwAuthenticate)) {
|
|
812
|
+
return null;
|
|
813
|
+
}
|
|
814
|
+
const prefix = `Bearer ${TENANT_TOKEN_PREFIX}`;
|
|
815
|
+
if (!failedAuthorization || !failedAuthorization.startsWith(prefix)) {
|
|
816
|
+
return null;
|
|
817
|
+
}
|
|
818
|
+
return failedAuthorization.slice("Bearer ".length);
|
|
819
|
+
}
|
|
820
|
+
var TenantTokenAuth = class {
|
|
821
|
+
source;
|
|
822
|
+
constructor(mint, options) {
|
|
823
|
+
this.source = sourceOf(mint, options);
|
|
824
|
+
}
|
|
825
|
+
buildHeaders(_request) {
|
|
826
|
+
return { Authorization: `Bearer ${this.source.tokenSync()}` };
|
|
827
|
+
}
|
|
828
|
+
refreshAfterUnauthorized(status, headers, failedAuthorization) {
|
|
829
|
+
const refused = refusedToken(status, headers.get("www-authenticate"), failedAuthorization);
|
|
830
|
+
if (refused === null) {
|
|
831
|
+
return false;
|
|
832
|
+
}
|
|
833
|
+
this.source.invalidate(refused);
|
|
834
|
+
return true;
|
|
835
|
+
}
|
|
836
|
+
toJSON() {
|
|
837
|
+
return this.source.toJSON();
|
|
838
|
+
}
|
|
839
|
+
[INSPECT]() {
|
|
840
|
+
return `TenantTokenAuth { source: ${this.source[INSPECT]()} }`;
|
|
841
|
+
}
|
|
842
|
+
};
|
|
843
|
+
function replayableBody(body) {
|
|
844
|
+
if (body === void 0 || body === null || typeof body === "string") {
|
|
845
|
+
return true;
|
|
846
|
+
}
|
|
847
|
+
if (body instanceof URLSearchParams || body instanceof ArrayBuffer || ArrayBuffer.isView(body)) {
|
|
848
|
+
return true;
|
|
849
|
+
}
|
|
850
|
+
if (typeof Blob !== "undefined" && body instanceof Blob) {
|
|
851
|
+
return true;
|
|
852
|
+
}
|
|
853
|
+
if (typeof FormData !== "undefined" && body instanceof FormData) {
|
|
854
|
+
return true;
|
|
855
|
+
}
|
|
856
|
+
return false;
|
|
857
|
+
}
|
|
858
|
+
function tenantTokenFetch(mint, options) {
|
|
859
|
+
const source = sourceOf(mint, options);
|
|
860
|
+
const wrapped = async (input, init) => {
|
|
861
|
+
const baseFetch = options?.fetch ?? globalThis.fetch;
|
|
862
|
+
const isRequest = typeof Request !== "undefined" && input instanceof Request;
|
|
863
|
+
const signal = init?.signal ?? (isRequest ? input.signal : void 0);
|
|
864
|
+
const canReplay = replayableBody(init?.body) && !(isRequest && input.body !== null);
|
|
865
|
+
const send = async () => {
|
|
866
|
+
const authorization = `Bearer ${await source.token()}`;
|
|
867
|
+
const headers = new Headers(isRequest ? input.headers : void 0);
|
|
868
|
+
if (init?.headers !== void 0) {
|
|
869
|
+
new Headers(init.headers).forEach((value, name) => headers.set(name, value));
|
|
870
|
+
}
|
|
871
|
+
headers.set("Authorization", authorization);
|
|
872
|
+
const response = isRequest ? await baseFetch(new Request(input, { ...init, headers })) : await baseFetch(input, { ...init, headers });
|
|
873
|
+
return { response, authorization };
|
|
874
|
+
};
|
|
875
|
+
const first = await send();
|
|
876
|
+
if (!canReplay || signal?.aborted) {
|
|
877
|
+
return first.response;
|
|
878
|
+
}
|
|
879
|
+
const refused = refusedToken(
|
|
880
|
+
first.response.status,
|
|
881
|
+
first.response.headers.get("www-authenticate"),
|
|
882
|
+
first.authorization
|
|
883
|
+
);
|
|
884
|
+
if (refused === null) {
|
|
885
|
+
return first.response;
|
|
886
|
+
}
|
|
887
|
+
source.invalidate(refused);
|
|
888
|
+
await first.response.body?.cancel().catch(() => void 0);
|
|
889
|
+
return (await send()).response;
|
|
890
|
+
};
|
|
891
|
+
return wrapped;
|
|
892
|
+
}
|
|
893
|
+
|
|
424
894
|
// src/config.ts
|
|
425
895
|
var DEFAULT_RETRY_CONFIG = {
|
|
426
896
|
attempts: 3,
|
|
@@ -428,7 +898,7 @@ var DEFAULT_RETRY_CONFIG = {
|
|
|
428
898
|
statusCodes: [408, 425, 429, 500, 502, 503, 504],
|
|
429
899
|
methods: ["GET", "HEAD", "OPTIONS", "PUT", "DELETE"]
|
|
430
900
|
};
|
|
431
|
-
var SDK_VERSION = "0.
|
|
901
|
+
var SDK_VERSION = "0.9.0";
|
|
432
902
|
var DEFAULT_USER_AGENT = `foxnose-sdk-js/${SDK_VERSION}`;
|
|
433
903
|
function createConfig(options) {
|
|
434
904
|
if (!options.baseUrl) {
|
|
@@ -558,23 +1028,32 @@ var HttpTransport = class {
|
|
|
558
1028
|
}
|
|
559
1029
|
async sendWithRetries(method, path, options) {
|
|
560
1030
|
const allowRetries = options?.allowRetries !== false;
|
|
1031
|
+
let replayed = false;
|
|
561
1032
|
for (let attempt = 1; attempt <= this.retry.attempts; attempt++) {
|
|
562
|
-
const
|
|
563
|
-
const controller = new AbortController();
|
|
564
|
-
const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);
|
|
565
|
-
init.signal = controller.signal;
|
|
1033
|
+
const request = this.buildRequest(method, path, options);
|
|
566
1034
|
let response;
|
|
567
1035
|
try {
|
|
568
|
-
response = await
|
|
1036
|
+
response = await this.send(request);
|
|
569
1037
|
} catch (err) {
|
|
570
|
-
clearTimeout(timeoutId);
|
|
571
1038
|
const delay = this.handleTransportError(err, method, attempt, !allowRetries);
|
|
572
1039
|
if (delay > 0) {
|
|
573
1040
|
await this.sleep(delay);
|
|
574
1041
|
}
|
|
575
1042
|
continue;
|
|
576
|
-
}
|
|
577
|
-
|
|
1043
|
+
}
|
|
1044
|
+
if (!replayed && this.refreshAuthAfter(response)) {
|
|
1045
|
+
replayed = true;
|
|
1046
|
+
await response.body?.cancel().catch(() => void 0);
|
|
1047
|
+
const again = this.buildRequest(method, path, options);
|
|
1048
|
+
try {
|
|
1049
|
+
response = await this.send(again);
|
|
1050
|
+
} catch (err) {
|
|
1051
|
+
const delay = this.handleTransportError(err, method, attempt, !allowRetries);
|
|
1052
|
+
if (delay > 0) {
|
|
1053
|
+
await this.sleep(delay);
|
|
1054
|
+
}
|
|
1055
|
+
continue;
|
|
1056
|
+
}
|
|
578
1057
|
}
|
|
579
1058
|
if (response.status >= 400) {
|
|
580
1059
|
if (allowRetries && this.shouldRetry(method, response.status) && attempt < this.retry.attempts) {
|
|
@@ -590,6 +1069,33 @@ var HttpTransport = class {
|
|
|
590
1069
|
}
|
|
591
1070
|
throw new FoxnoseTransportError("All retry attempts exhausted");
|
|
592
1071
|
}
|
|
1072
|
+
/** Send one built request; the `Authorization` it carried is kept for the 401 hook. */
|
|
1073
|
+
async send(request) {
|
|
1074
|
+
const { url, init } = request;
|
|
1075
|
+
const controller = new AbortController();
|
|
1076
|
+
const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);
|
|
1077
|
+
init.signal = controller.signal;
|
|
1078
|
+
try {
|
|
1079
|
+
const response = await fetch(url, init);
|
|
1080
|
+
const sent = new Headers(init.headers).get("authorization");
|
|
1081
|
+
this.sentAuthorization.set(response, sent ?? void 0);
|
|
1082
|
+
return response;
|
|
1083
|
+
} finally {
|
|
1084
|
+
clearTimeout(timeoutId);
|
|
1085
|
+
}
|
|
1086
|
+
}
|
|
1087
|
+
sentAuthorization = /* @__PURE__ */ new WeakMap();
|
|
1088
|
+
/** Whether the auth strategy wants a `401` sent once more with new credentials. */
|
|
1089
|
+
refreshAuthAfter(response) {
|
|
1090
|
+
if (response.status !== 401 || typeof this.auth.refreshAfterUnauthorized !== "function") {
|
|
1091
|
+
return false;
|
|
1092
|
+
}
|
|
1093
|
+
return this.auth.refreshAfterUnauthorized(
|
|
1094
|
+
response.status,
|
|
1095
|
+
response.headers,
|
|
1096
|
+
this.sentAuthorization.get(response)
|
|
1097
|
+
);
|
|
1098
|
+
}
|
|
593
1099
|
handleTransportError(err, method, attempt, forbidRetry = false) {
|
|
594
1100
|
const canRetry = !forbidRetry && this.retry.methods.includes(method.toUpperCase()) && attempt < this.retry.attempts;
|
|
595
1101
|
if (!canRetry) {
|
|
@@ -698,6 +1204,94 @@ function resolveKey(value) {
|
|
|
698
1204
|
}
|
|
699
1205
|
throw new TypeError(`Expected a string or an object with a 'key' attribute, got ${typeof value}`);
|
|
700
1206
|
}
|
|
1207
|
+
function isPlainObject2(value) {
|
|
1208
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
1209
|
+
}
|
|
1210
|
+
function untrustedFields(value) {
|
|
1211
|
+
if (!Array.isArray(value) || !value.every(isUntrustedField)) {
|
|
1212
|
+
throw new TypeError("guardrails.untrusted_fields is malformed");
|
|
1213
|
+
}
|
|
1214
|
+
return value;
|
|
1215
|
+
}
|
|
1216
|
+
var UNTRUSTED_FIELD_STRINGS = ["field_label", "writer_type", "cause", "principal_key"];
|
|
1217
|
+
function isUntrustedField(value) {
|
|
1218
|
+
if (!isPlainObject2(value) || typeof value.path !== "string") {
|
|
1219
|
+
return false;
|
|
1220
|
+
}
|
|
1221
|
+
const absentOrNull = (v) => v === void 0 || v === null;
|
|
1222
|
+
return UNTRUSTED_FIELD_STRINGS.every((k) => absentOrNull(value[k]) || typeof value[k] === "string") && (absentOrNull(value.reviewed) || typeof value.reviewed === "boolean");
|
|
1223
|
+
}
|
|
1224
|
+
function str(value, name) {
|
|
1225
|
+
if (value === void 0 || value === null) {
|
|
1226
|
+
return null;
|
|
1227
|
+
}
|
|
1228
|
+
if (typeof value !== "string") {
|
|
1229
|
+
throw new TypeError(`guardrails.${name} is not a string`);
|
|
1230
|
+
}
|
|
1231
|
+
return value;
|
|
1232
|
+
}
|
|
1233
|
+
function bool(value, name) {
|
|
1234
|
+
if (typeof value !== "boolean") {
|
|
1235
|
+
throw new TypeError(`guardrails.${name} is not a boolean`);
|
|
1236
|
+
}
|
|
1237
|
+
return value;
|
|
1238
|
+
}
|
|
1239
|
+
function getResourceGuardrailsSummary(resource) {
|
|
1240
|
+
const g = resource.guardrails;
|
|
1241
|
+
if (g === void 0 || g === null) {
|
|
1242
|
+
return null;
|
|
1243
|
+
}
|
|
1244
|
+
if (!isPlainObject2(g)) {
|
|
1245
|
+
throw new TypeError("guardrails is not an object");
|
|
1246
|
+
}
|
|
1247
|
+
return {
|
|
1248
|
+
...g,
|
|
1249
|
+
untrusted: bool(g.untrusted, "untrusted"),
|
|
1250
|
+
needs_review: bool(g.needs_review, "needs_review"),
|
|
1251
|
+
verdict: str(g.verdict, "verdict"),
|
|
1252
|
+
held: bool(g.held, "held"),
|
|
1253
|
+
untrusted_fields: untrustedFields(g.untrusted_fields)
|
|
1254
|
+
};
|
|
1255
|
+
}
|
|
1256
|
+
function getRevisionGuardrailsSummary(revision) {
|
|
1257
|
+
const g = revision.guardrails;
|
|
1258
|
+
if (g === void 0 || g === null) {
|
|
1259
|
+
return null;
|
|
1260
|
+
}
|
|
1261
|
+
if (!isPlainObject2(g)) {
|
|
1262
|
+
throw new TypeError("guardrails is not an object");
|
|
1263
|
+
}
|
|
1264
|
+
const list = (v, name) => {
|
|
1265
|
+
if (!Array.isArray(v) || !v.every((x) => typeof x === "string")) {
|
|
1266
|
+
throw new TypeError(`guardrails.${name} is not a list of strings`);
|
|
1267
|
+
}
|
|
1268
|
+
return v;
|
|
1269
|
+
};
|
|
1270
|
+
return {
|
|
1271
|
+
...g,
|
|
1272
|
+
untrusted: bool(g.untrusted, "untrusted"),
|
|
1273
|
+
needs_review: bool(g.needs_review, "needs_review"),
|
|
1274
|
+
tainted_paths: list(g.tainted_paths, "tainted_paths"),
|
|
1275
|
+
state: str(g.state, "state"),
|
|
1276
|
+
review_state: str(g.review_state, "review_state"),
|
|
1277
|
+
verdict: str(g.verdict, "verdict"),
|
|
1278
|
+
reason: str(g.reason, "reason"),
|
|
1279
|
+
reasons: list(g.reasons, "reasons"),
|
|
1280
|
+
held: bool(g.held, "held"),
|
|
1281
|
+
untrusted_fields: untrustedFields(g.untrusted_fields)
|
|
1282
|
+
};
|
|
1283
|
+
}
|
|
1284
|
+
var GUARDRAILS_POLICY_FIELDS = [
|
|
1285
|
+
"mode",
|
|
1286
|
+
"overrides",
|
|
1287
|
+
"trusted_keys",
|
|
1288
|
+
"acknowledge_agent_trust",
|
|
1289
|
+
"link_allowlist",
|
|
1290
|
+
"hold",
|
|
1291
|
+
"suspicious_action",
|
|
1292
|
+
"screen",
|
|
1293
|
+
"max_screened_chars"
|
|
1294
|
+
];
|
|
701
1295
|
|
|
702
1296
|
// src/management/paths.ts
|
|
703
1297
|
function managementPaths(environmentKey) {
|
|
@@ -739,6 +1333,18 @@ function managementPaths(environmentKey) {
|
|
|
739
1333
|
webhooksRoot: () => `/v1/${environmentKey}/webhooks`,
|
|
740
1334
|
webhookEndpointRoot: (endpointId) => `/v1/${environmentKey}/webhooks/endpoints/${encodeURIComponent(endpointId)}`,
|
|
741
1335
|
webhookEventRoot: (eventId) => `/v1/${environmentKey}/webhooks/events/${encodeURIComponent(eventId)}`,
|
|
1336
|
+
// Tenant token paths
|
|
1337
|
+
tenantSigningKeysRoot: () => `/v1/${environmentKey}/tenant-signing-keys`,
|
|
1338
|
+
tenantSigningKeyRoot: (kid) => `/v1/${environmentKey}/tenant-signing-keys/${encodeURIComponent(kid)}`,
|
|
1339
|
+
tenantLimitsRoot: () => `/v1/${environmentKey}/tenant-limits`,
|
|
1340
|
+
// Guardrails paths
|
|
1341
|
+
guardrailsPolicyRoot: (collectionKey) => `/v1/${environmentKey}/collections/${collectionKey}/guardrails-policy`,
|
|
1342
|
+
guardrailsHeldRoot: (collectionKey) => `/v1/${environmentKey}/collections/${collectionKey}/guardrails/held`,
|
|
1343
|
+
guardrailsUsageRoot: (collectionKey) => `/v1/${environmentKey}/collections/${collectionKey}/guardrails/usage`,
|
|
1344
|
+
revisionGuardrailsRoot: (collectionKey, resourceKey, revisionKey) => `/v1/${environmentKey}/collections/${collectionKey}/resources/${resourceKey}/revisions/${revisionKey}/guardrails`,
|
|
1345
|
+
resourceGuardrailsRoot: (collectionKey, resourceKey) => `/v1/${environmentKey}/collections/${collectionKey}/resources/${resourceKey}/guardrails`,
|
|
1346
|
+
guardrailsReviewRoot: () => `/v1/${environmentKey}/guardrails/review`,
|
|
1347
|
+
guardrailsCatalogRoot: () => `/v1/${environmentKey}/guardrails/catalog`,
|
|
742
1348
|
// Caller's own permissions
|
|
743
1349
|
myPermissionsRoot: () => `/v1/${environmentKey}/permissions/me`,
|
|
744
1350
|
// Management API key paths
|
|
@@ -783,6 +1389,177 @@ function hideSecret(response) {
|
|
|
783
1389
|
}
|
|
784
1390
|
return response;
|
|
785
1391
|
}
|
|
1392
|
+
function isInteger(value) {
|
|
1393
|
+
return typeof value === "number" && Number.isSafeInteger(value);
|
|
1394
|
+
}
|
|
1395
|
+
function limitValues(limits, name) {
|
|
1396
|
+
for (const [key, value] of Object.entries(limits)) {
|
|
1397
|
+
if (value !== null && value !== void 0 && !isInteger(value)) {
|
|
1398
|
+
throw new Error(`${name}.${key} must be an integer or null`);
|
|
1399
|
+
}
|
|
1400
|
+
}
|
|
1401
|
+
return limits;
|
|
1402
|
+
}
|
|
1403
|
+
var TIMESTAMP_WITH_OFFSET = /^(\d{4})(-?)(\d{2})\2(\d{2})[Tt ](\d{2})(?:(:?)(\d{2})(?:\6(\d{2})(?:[.,](\d+))?)?)?(?:[Zz]|[+-](\d{2})(?::?(\d{2}))?)$/;
|
|
1404
|
+
var DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
|
|
1405
|
+
function isTimestampWithOffset(value) {
|
|
1406
|
+
const match = TIMESTAMP_WITH_OFFSET.exec(value);
|
|
1407
|
+
if (match === null) return false;
|
|
1408
|
+
const n = (i) => Number(match[i] ?? 0);
|
|
1409
|
+
const [year, month, day, hour, minute, second] = [1, 3, 4, 5, 7, 8].map(n);
|
|
1410
|
+
const fraction = match[9] ?? "";
|
|
1411
|
+
const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
|
|
1412
|
+
if (year < 1 || month < 1 || month > 12) return false;
|
|
1413
|
+
const days = month === 2 && leap ? 29 : DAYS_IN_MONTH[month - 1];
|
|
1414
|
+
if (day < 1 || day > days) return false;
|
|
1415
|
+
if (hour === 24) {
|
|
1416
|
+
const lastDay = year === 9999 && month === 12 && day === 31;
|
|
1417
|
+
if (minute || second || /[1-9]/.test(fraction) || lastDay) return false;
|
|
1418
|
+
} else if (hour > 23 || minute > 59 || second > 59) {
|
|
1419
|
+
return false;
|
|
1420
|
+
}
|
|
1421
|
+
if (match[10] !== void 0 && (n(10) > 23 || n(11) > 59)) return false;
|
|
1422
|
+
return true;
|
|
1423
|
+
}
|
|
1424
|
+
function cutoff(value, name, allowNow) {
|
|
1425
|
+
if (value instanceof Date) {
|
|
1426
|
+
if (Number.isNaN(value.getTime())) {
|
|
1427
|
+
throw new Error(`${name} is an invalid Date`);
|
|
1428
|
+
}
|
|
1429
|
+
return value.toISOString();
|
|
1430
|
+
}
|
|
1431
|
+
if (typeof value !== "string") {
|
|
1432
|
+
throw new TypeError(`${name} must be a Date or a string`);
|
|
1433
|
+
}
|
|
1434
|
+
if (allowNow && value === "now") {
|
|
1435
|
+
return value;
|
|
1436
|
+
}
|
|
1437
|
+
if (!isTimestampWithOffset(value)) {
|
|
1438
|
+
const expected = allowNow ? '"now" or ' : "";
|
|
1439
|
+
throw new Error(`${name} must be ${expected}an ISO 8601 timestamp with a UTC offset`);
|
|
1440
|
+
}
|
|
1441
|
+
return value;
|
|
1442
|
+
}
|
|
1443
|
+
function signingKeyBody(request) {
|
|
1444
|
+
const hasPublic = request.public_key !== void 0;
|
|
1445
|
+
const generate = request.generate === true;
|
|
1446
|
+
if (hasPublic === generate) {
|
|
1447
|
+
throw new Error("Pass exactly one of public_key and generate: true");
|
|
1448
|
+
}
|
|
1449
|
+
const body = {
|
|
1450
|
+
parent_key: resolveKey(request.parent_key),
|
|
1451
|
+
anchor_collections: request.anchor_collections.map((c) => resolveKey(c)),
|
|
1452
|
+
apis: request.apis
|
|
1453
|
+
};
|
|
1454
|
+
if (hasPublic) {
|
|
1455
|
+
body.public_key = request.public_key;
|
|
1456
|
+
} else {
|
|
1457
|
+
body.generate = true;
|
|
1458
|
+
}
|
|
1459
|
+
if (request.collections !== void 0) {
|
|
1460
|
+
body.collections = request.collections.map((c) => resolveKey(c));
|
|
1461
|
+
}
|
|
1462
|
+
if (request.shared_read !== void 0) {
|
|
1463
|
+
body.shared_read = request.shared_read.map((c) => resolveKey(c));
|
|
1464
|
+
}
|
|
1465
|
+
for (const name of ["max_ttl_seconds", "max_anchors"]) {
|
|
1466
|
+
if (request[name] !== void 0) {
|
|
1467
|
+
if (!isInteger(request[name])) {
|
|
1468
|
+
throw new Error(`${name} must be an integer`);
|
|
1469
|
+
}
|
|
1470
|
+
body[name] = request[name];
|
|
1471
|
+
}
|
|
1472
|
+
}
|
|
1473
|
+
if (request.limits !== void 0) {
|
|
1474
|
+
body.limits = limitValues(request.limits, "limits");
|
|
1475
|
+
}
|
|
1476
|
+
if (request.description !== void 0) {
|
|
1477
|
+
body.description = request.description;
|
|
1478
|
+
}
|
|
1479
|
+
return body;
|
|
1480
|
+
}
|
|
1481
|
+
function signingKeyPatchBody(changes) {
|
|
1482
|
+
const body = {};
|
|
1483
|
+
if (changes.description !== void 0) {
|
|
1484
|
+
body.description = changes.description;
|
|
1485
|
+
}
|
|
1486
|
+
if (changes.limits !== void 0) {
|
|
1487
|
+
body.limits = changes.limits === null ? null : limitValues(changes.limits, "limits");
|
|
1488
|
+
}
|
|
1489
|
+
if (changes.not_before !== void 0) {
|
|
1490
|
+
body.not_before = cutoff(changes.not_before, "not_before", true);
|
|
1491
|
+
}
|
|
1492
|
+
if (Object.keys(body).length === 0) {
|
|
1493
|
+
throw new Error("Pass at least one of description, limits and not_before");
|
|
1494
|
+
}
|
|
1495
|
+
return body;
|
|
1496
|
+
}
|
|
1497
|
+
function revocationBody(entry) {
|
|
1498
|
+
if (entry.jti === void 0 === (entry.sub === void 0)) {
|
|
1499
|
+
throw new Error("Pass exactly one of jti and sub");
|
|
1500
|
+
}
|
|
1501
|
+
if (entry.jti !== void 0) {
|
|
1502
|
+
if (entry.before !== void 0) {
|
|
1503
|
+
throw new Error("before applies to a sub revocation only");
|
|
1504
|
+
}
|
|
1505
|
+
return { jti: entry.jti };
|
|
1506
|
+
}
|
|
1507
|
+
const body = { sub: entry.sub };
|
|
1508
|
+
if (entry.before !== void 0) {
|
|
1509
|
+
if (typeof entry.before === "string" && entry.before.trim().toLowerCase() === "now") {
|
|
1510
|
+
throw new Error("before must be a time; leave it out for 60 seconds from now");
|
|
1511
|
+
}
|
|
1512
|
+
body.before = cutoff(entry.before, "before", false);
|
|
1513
|
+
}
|
|
1514
|
+
return body;
|
|
1515
|
+
}
|
|
1516
|
+
var POLICY_FIELDS = new Set(GUARDRAILS_POLICY_FIELDS);
|
|
1517
|
+
function guardrailsPolicyBody(payload) {
|
|
1518
|
+
if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
|
|
1519
|
+
throw new TypeError("payload must be an object");
|
|
1520
|
+
}
|
|
1521
|
+
const unknown = Object.keys(payload).filter((name) => !POLICY_FIELDS.has(name));
|
|
1522
|
+
if (unknown.length > 0) {
|
|
1523
|
+
throw new Error(`Unknown guardrails policy field(s): ${unknown.sort().join(", ")}`);
|
|
1524
|
+
}
|
|
1525
|
+
const body = {};
|
|
1526
|
+
for (const [name, value] of Object.entries(payload)) {
|
|
1527
|
+
if (value !== void 0) {
|
|
1528
|
+
body[name] = value;
|
|
1529
|
+
}
|
|
1530
|
+
}
|
|
1531
|
+
return body;
|
|
1532
|
+
}
|
|
1533
|
+
function heldItems(items) {
|
|
1534
|
+
const seen = /* @__PURE__ */ new Set();
|
|
1535
|
+
const result = items.map((item) => {
|
|
1536
|
+
const pair = Array.isArray(item) ? { resource_key: resolveKey(item[0]), revision_key: resolveKey(item[1]) } : {
|
|
1537
|
+
resource_key: item.resource_key,
|
|
1538
|
+
revision_key: item.revision_key
|
|
1539
|
+
};
|
|
1540
|
+
const id = `${pair.resource_key}\0${pair.revision_key}`;
|
|
1541
|
+
if (seen.has(id)) {
|
|
1542
|
+
throw new Error("Each held revision may appear once");
|
|
1543
|
+
}
|
|
1544
|
+
seen.add(id);
|
|
1545
|
+
return pair;
|
|
1546
|
+
});
|
|
1547
|
+
if (result.length < 1 || result.length > 50) {
|
|
1548
|
+
throw new Error("Pass 1 to 50 held revisions");
|
|
1549
|
+
}
|
|
1550
|
+
return result;
|
|
1551
|
+
}
|
|
1552
|
+
function hidePrivateKey(response) {
|
|
1553
|
+
if (response && typeof response === "object" && "private_key" in response) {
|
|
1554
|
+
Object.defineProperty(response, "private_key", {
|
|
1555
|
+
value: response.private_key,
|
|
1556
|
+
enumerable: false,
|
|
1557
|
+
writable: false,
|
|
1558
|
+
configurable: true
|
|
1559
|
+
});
|
|
1560
|
+
}
|
|
1561
|
+
return response;
|
|
1562
|
+
}
|
|
786
1563
|
function webhookEndpointBody(request) {
|
|
787
1564
|
const { collection_keys, ...rest } = request;
|
|
788
1565
|
return collection_keys === void 0 ? rest : { ...rest, collection_keys: collection_keys.map((key) => resolveKey(key)) };
|
|
@@ -2181,6 +2958,192 @@ var ManagementClient = class {
|
|
|
2181
2958
|
return this.request("GET", `${this.paths.myPermissionsRoot()}/`);
|
|
2182
2959
|
}
|
|
2183
2960
|
// ------------------------------------------------------------------ //
|
|
2961
|
+
// Tenant signing keys and tenant limits
|
|
2962
|
+
// ------------------------------------------------------------------ //
|
|
2963
|
+
/**
|
|
2964
|
+
* List the environment's tenant signing keys, revoked ones included, oldest first.
|
|
2965
|
+
* Keys the caller cannot read are left out. `params` carries `limit` and `offset`.
|
|
2966
|
+
*/
|
|
2967
|
+
async listTenantSigningKeys(options) {
|
|
2968
|
+
const params = { ...options?.params };
|
|
2969
|
+
if (options?.parentKey !== void 0) {
|
|
2970
|
+
params.parent_key = resolveKey(options.parentKey);
|
|
2971
|
+
}
|
|
2972
|
+
return this.request("GET", `${this.paths.tenantSigningKeysRoot()}/`, { params });
|
|
2973
|
+
}
|
|
2974
|
+
/**
|
|
2975
|
+
* Register a tenant signing key, or have FoxNose generate the key pair.
|
|
2976
|
+
*
|
|
2977
|
+
* Send exactly one of `public_key` and `generate: true`. With `generate` the answer
|
|
2978
|
+
* carries `private_key` once (not enumerable; it is not stored). To keep the private
|
|
2979
|
+
* key on your side only, make the pair with {@link generateTenantSigningKey} and send
|
|
2980
|
+
* its `publicKey`. Never retried automatically.
|
|
2981
|
+
*/
|
|
2982
|
+
async createTenantSigningKey(request) {
|
|
2983
|
+
const created = await this.transport.request("POST", `${this.paths.tenantSigningKeysRoot()}/`, {
|
|
2984
|
+
jsonBody: signingKeyBody(request),
|
|
2985
|
+
allowRetries: false
|
|
2986
|
+
});
|
|
2987
|
+
return hidePrivateKey(created);
|
|
2988
|
+
}
|
|
2989
|
+
/** Read one tenant signing key. */
|
|
2990
|
+
async getTenantSigningKey(kid) {
|
|
2991
|
+
return this.request("GET", `${this.paths.tenantSigningKeyRoot(kid)}/`);
|
|
2992
|
+
}
|
|
2993
|
+
/**
|
|
2994
|
+
* Change a signing key's label, per-key limits or cutoff for older tokens.
|
|
2995
|
+
*
|
|
2996
|
+
* `not_before: 'now'` means 60 seconds from now; an explicit time must be at least
|
|
2997
|
+
* that far ahead. Tokens with `iat` before it are refused. It only moves forward.
|
|
2998
|
+
*/
|
|
2999
|
+
async updateTenantSigningKey(kid, changes) {
|
|
3000
|
+
return this.request("PATCH", `${this.paths.tenantSigningKeyRoot(kid)}/`, {
|
|
3001
|
+
jsonBody: signingKeyPatchBody(changes)
|
|
3002
|
+
});
|
|
3003
|
+
}
|
|
3004
|
+
/** Revoke a signing key. Repeating the call also succeeds. */
|
|
3005
|
+
async deleteTenantSigningKey(kid) {
|
|
3006
|
+
await this.request("DELETE", `${this.paths.tenantSigningKeyRoot(kid)}/`, {
|
|
3007
|
+
parseJson: false
|
|
3008
|
+
});
|
|
3009
|
+
}
|
|
3010
|
+
/**
|
|
3011
|
+
* Refuse one token (`jti`) or one end user's tokens (`sub`, those with `iat` at or
|
|
3012
|
+
* before `before`, 60 seconds from now by default). Send exactly one of `jti` and
|
|
3013
|
+
* `sub`. Neither value is stored, only its hash. Never retried automatically.
|
|
3014
|
+
*/
|
|
3015
|
+
async addTenantTokenRevocation(kid, entry) {
|
|
3016
|
+
return this.transport.request("POST", `${this.paths.tenantSigningKeyRoot(kid)}/revocations/`, {
|
|
3017
|
+
jsonBody: revocationBody(entry),
|
|
3018
|
+
allowRetries: false
|
|
3019
|
+
});
|
|
3020
|
+
}
|
|
3021
|
+
/** Read the environment's tenant-token rate limits, with defaults and ceilings. */
|
|
3022
|
+
async getTenantLimits() {
|
|
3023
|
+
return this.request("GET", `${this.paths.tenantLimitsRoot()}/`);
|
|
3024
|
+
}
|
|
3025
|
+
/** Replace the environment's tenant-token rate limits. A field left out returns to its default. */
|
|
3026
|
+
async updateTenantLimits(limits) {
|
|
3027
|
+
return this.request("PUT", `${this.paths.tenantLimitsRoot()}/`, {
|
|
3028
|
+
jsonBody: limitValues(
|
|
3029
|
+
{
|
|
3030
|
+
rpm_per_subject: limits.rpm_per_subject ?? null,
|
|
3031
|
+
rpm_per_anchor: limits.rpm_per_anchor ?? null,
|
|
3032
|
+
uploads_per_subject_per_hour: limits.uploads_per_subject_per_hour ?? null
|
|
3033
|
+
},
|
|
3034
|
+
"limits"
|
|
3035
|
+
)
|
|
3036
|
+
});
|
|
3037
|
+
}
|
|
3038
|
+
// ------------------------------------------------------------------ //
|
|
3039
|
+
// Guardrails
|
|
3040
|
+
// ------------------------------------------------------------------ //
|
|
3041
|
+
/** Read a collection's guardrails policy. Without one, mode is `off` and `version` is `null`. */
|
|
3042
|
+
async getGuardrailsPolicy(collectionKey) {
|
|
3043
|
+
return this.request("GET", `${this.paths.guardrailsPolicyRoot(resolveKey(collectionKey))}/`);
|
|
3044
|
+
}
|
|
3045
|
+
/**
|
|
3046
|
+
* Replace a collection's guardrails policy with a new version. Only the fields that
|
|
3047
|
+
* are set are sent; a `mode` left out keeps the collection's mode. An unknown field
|
|
3048
|
+
* throws before anything is sent.
|
|
3049
|
+
*/
|
|
3050
|
+
async updateGuardrailsPolicy(collectionKey, payload) {
|
|
3051
|
+
return this.request("PUT", `${this.paths.guardrailsPolicyRoot(resolveKey(collectionKey))}/`, {
|
|
3052
|
+
jsonBody: guardrailsPolicyBody(payload)
|
|
3053
|
+
});
|
|
3054
|
+
}
|
|
3055
|
+
/** List a collection's retained held revisions, newest first. `params` carries `limit` (at most 200) and `offset`. */
|
|
3056
|
+
async listHeldRevisions(collectionKey, options) {
|
|
3057
|
+
const params = { ...options?.params };
|
|
3058
|
+
if (options?.status !== void 0) {
|
|
3059
|
+
params.status = options.status;
|
|
3060
|
+
}
|
|
3061
|
+
return this.request("GET", `${this.paths.guardrailsHeldRoot(resolveKey(collectionKey))}/`, {
|
|
3062
|
+
params
|
|
3063
|
+
});
|
|
3064
|
+
}
|
|
3065
|
+
/** Publish a held revision; it is re-evaluated under the live policy first. Never retried automatically. */
|
|
3066
|
+
async releaseHeldRevision(collectionKey, resourceKey, revisionKey) {
|
|
3067
|
+
const root = this.paths.revisionGuardrailsRoot(
|
|
3068
|
+
resolveKey(collectionKey),
|
|
3069
|
+
resolveKey(resourceKey),
|
|
3070
|
+
resolveKey(revisionKey)
|
|
3071
|
+
);
|
|
3072
|
+
return this.transport.request("POST", `${root}/release/`, { allowRetries: false });
|
|
3073
|
+
}
|
|
3074
|
+
/** Reject a held revision; it is never published. `reason` is at most 500 characters. */
|
|
3075
|
+
async rejectHeldRevision(collectionKey, resourceKey, revisionKey, options) {
|
|
3076
|
+
const root = this.paths.revisionGuardrailsRoot(
|
|
3077
|
+
resolveKey(collectionKey),
|
|
3078
|
+
resolveKey(resourceKey),
|
|
3079
|
+
resolveKey(revisionKey)
|
|
3080
|
+
);
|
|
3081
|
+
return this.transport.request("POST", `${root}/reject/`, {
|
|
3082
|
+
jsonBody: options?.reason === void 0 ? void 0 : { reason: options.reason },
|
|
3083
|
+
allowRetries: false
|
|
3084
|
+
});
|
|
3085
|
+
}
|
|
3086
|
+
/** Reject up to 50 held revisions. Each item succeeds or fails on its own. */
|
|
3087
|
+
async rejectHeldRevisions(collectionKey, items, options) {
|
|
3088
|
+
const body = { items: heldItems(items) };
|
|
3089
|
+
if (options?.reason !== void 0) {
|
|
3090
|
+
body.reason = options.reason;
|
|
3091
|
+
}
|
|
3092
|
+
return this.transport.request(
|
|
3093
|
+
"POST",
|
|
3094
|
+
`${this.paths.guardrailsHeldRoot(resolveKey(collectionKey))}/reject/`,
|
|
3095
|
+
{ jsonBody: body, allowRetries: false }
|
|
3096
|
+
);
|
|
3097
|
+
}
|
|
3098
|
+
/** Screen up to 50 held revisions again; each is published only if `clean`. */
|
|
3099
|
+
async rescreenHeldRevisions(collectionKey, items) {
|
|
3100
|
+
return this.transport.request(
|
|
3101
|
+
"POST",
|
|
3102
|
+
`${this.paths.guardrailsHeldRoot(resolveKey(collectionKey))}/rescreen/`,
|
|
3103
|
+
{ jsonBody: { items: heldItems(items) }, allowRetries: false }
|
|
3104
|
+
);
|
|
3105
|
+
}
|
|
3106
|
+
/** Read a collection's review backlog and this hour's screening budget. */
|
|
3107
|
+
async getGuardrailsUsage(collectionKey) {
|
|
3108
|
+
return this.request("GET", `${this.paths.guardrailsUsageRoot(resolveKey(collectionKey))}/`);
|
|
3109
|
+
}
|
|
3110
|
+
/**
|
|
3111
|
+
* List what the environment holds for a person to review, newest first. `kind` is
|
|
3112
|
+
* `held` (the default) or `needs_review`; `status` applies to `held` only.
|
|
3113
|
+
* `params` carries `limit` (at most 100) and `offset`.
|
|
3114
|
+
*/
|
|
3115
|
+
async listGuardrailsReviewQueue(options) {
|
|
3116
|
+
const params = { ...options?.params };
|
|
3117
|
+
if (options?.kind !== void 0) params.kind = options.kind;
|
|
3118
|
+
if (options?.collection !== void 0) params.collection = resolveKey(options.collection);
|
|
3119
|
+
if (options?.status !== void 0) params.status = options.status;
|
|
3120
|
+
return this.request("GET", `${this.paths.guardrailsReviewRoot()}/`, { params });
|
|
3121
|
+
}
|
|
3122
|
+
/** Read the team view of a revision: provenance, findings and review state. */
|
|
3123
|
+
async getRevisionGuardrails(collectionKey, resourceKey, revisionKey) {
|
|
3124
|
+
const root = this.paths.revisionGuardrailsRoot(
|
|
3125
|
+
resolveKey(collectionKey),
|
|
3126
|
+
resolveKey(resourceKey),
|
|
3127
|
+
resolveKey(revisionKey)
|
|
3128
|
+
);
|
|
3129
|
+
return this.request("GET", `${root}/`);
|
|
3130
|
+
}
|
|
3131
|
+
/**
|
|
3132
|
+
* Vouch for a record's published content: a revision with the same data is created
|
|
3133
|
+
* and published, with the caller as its origin. Never retried automatically.
|
|
3134
|
+
*/
|
|
3135
|
+
async markResourceReviewed(collectionKey, resourceKey) {
|
|
3136
|
+
const root = this.paths.resourceGuardrailsRoot(
|
|
3137
|
+
resolveKey(collectionKey),
|
|
3138
|
+
resolveKey(resourceKey)
|
|
3139
|
+
);
|
|
3140
|
+
return this.transport.request("POST", `${root}/mark-reviewed/`, { allowRetries: false });
|
|
3141
|
+
}
|
|
3142
|
+
/** Read the wording the API uses for findings, states and writers. */
|
|
3143
|
+
async getGuardrailsCatalog() {
|
|
3144
|
+
return this.request("GET", `${this.paths.guardrailsCatalogRoot()}/`);
|
|
3145
|
+
}
|
|
3146
|
+
// ------------------------------------------------------------------ //
|
|
2184
3147
|
// Webhooks
|
|
2185
3148
|
// ------------------------------------------------------------------ //
|
|
2186
3149
|
/**
|
|
@@ -2567,6 +3530,9 @@ var FluxClient = class {
|
|
|
2567
3530
|
*
|
|
2568
3531
|
* Writes are never retried automatically: a failed write's outcome is
|
|
2569
3532
|
* unknown, so re-read with a GET before retrying.
|
|
3533
|
+
*
|
|
3534
|
+
* `options.provenance` declares untrusted fields for the collection's guardrails,
|
|
3535
|
+
* such as `{ untrusted_fields: ['body'], source: 'support-inbox' }`.
|
|
2570
3536
|
*/
|
|
2571
3537
|
async createResource(folderPath, data, options) {
|
|
2572
3538
|
const path = this.buildPath(folderPath, "/");
|
|
@@ -2574,6 +3540,9 @@ var FluxClient = class {
|
|
|
2574
3540
|
if (options?.key !== void 0) {
|
|
2575
3541
|
body.key = options.key;
|
|
2576
3542
|
}
|
|
3543
|
+
if (options?.provenance !== void 0) {
|
|
3544
|
+
body.provenance = options.provenance;
|
|
3545
|
+
}
|
|
2577
3546
|
return this.transport.request("POST", path, { jsonBody: body, allowRetries: false });
|
|
2578
3547
|
}
|
|
2579
3548
|
/**
|
|
@@ -2587,9 +3556,13 @@ var FluxClient = class {
|
|
|
2587
3556
|
* raises {@link CollectionNotWritableError}. Like {@link createResource}, it
|
|
2588
3557
|
* is never retried automatically.
|
|
2589
3558
|
*/
|
|
2590
|
-
async updateResource(folderPath, resourceKey, data) {
|
|
3559
|
+
async updateResource(folderPath, resourceKey, data, options) {
|
|
2591
3560
|
const path = this.buildPath(folderPath, `/${resourceKey}/`);
|
|
2592
|
-
|
|
3561
|
+
const body = { data };
|
|
3562
|
+
if (options?.provenance !== void 0) {
|
|
3563
|
+
body.provenance = options.provenance;
|
|
3564
|
+
}
|
|
3565
|
+
return this.transport.request("PUT", path, { jsonBody: body, allowRetries: false });
|
|
2593
3566
|
}
|
|
2594
3567
|
/**
|
|
2595
3568
|
* Get a grant for one upload to a files collection.
|
|
@@ -2771,6 +3744,164 @@ var FluxClient = class {
|
|
|
2771
3744
|
this.transport.close();
|
|
2772
3745
|
}
|
|
2773
3746
|
};
|
|
3747
|
+
|
|
3748
|
+
// src/flux/trust.ts
|
|
3749
|
+
var RECORD_TRUST_SOURCE = "record_write";
|
|
3750
|
+
var FILE_TRUST_SOURCE = "end_user_upload";
|
|
3751
|
+
var FILE_VERDICTS = ["clean", "suspicious"];
|
|
3752
|
+
var PROVENANCE_STATES = ["recorded", "unknown"];
|
|
3753
|
+
var FILE_PROCESSING = ["agent_ready", "storage_only"];
|
|
3754
|
+
var FLAG_SCOPES = ["line", "page", "region"];
|
|
3755
|
+
var DEFAULT_FILE_BLOCK_KEY = "file";
|
|
3756
|
+
var MalformedTrustMetadataError = class extends Error {
|
|
3757
|
+
constructor(message) {
|
|
3758
|
+
super(message);
|
|
3759
|
+
this.name = "MalformedTrustMetadataError";
|
|
3760
|
+
}
|
|
3761
|
+
};
|
|
3762
|
+
function isObject2(value) {
|
|
3763
|
+
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
3764
|
+
}
|
|
3765
|
+
function isInt2(value) {
|
|
3766
|
+
return typeof value === "number" && Number.isSafeInteger(value);
|
|
3767
|
+
}
|
|
3768
|
+
function isStringArray(value) {
|
|
3769
|
+
return Array.isArray(value) && value.every((v) => typeof v === "string");
|
|
3770
|
+
}
|
|
3771
|
+
function isStringMap(value) {
|
|
3772
|
+
return isObject2(value) && Object.values(value).every((v) => typeof v === "string");
|
|
3773
|
+
}
|
|
3774
|
+
var TOP_LEVEL_POINTER = /^\/(?:[^/~]|~[01])*$/;
|
|
3775
|
+
function pointerField(pointer) {
|
|
3776
|
+
if (typeof pointer !== "string" || !TOP_LEVEL_POINTER.test(pointer)) {
|
|
3777
|
+
throw new MalformedTrustMetadataError("a tainted path is not a top-level JSON Pointer");
|
|
3778
|
+
}
|
|
3779
|
+
return pointer.slice(1).replace(/~1/g, "/").replace(/~0/g, "~");
|
|
3780
|
+
}
|
|
3781
|
+
function dottedField(path) {
|
|
3782
|
+
if (typeof path !== "string" || path.length === 0 || path.startsWith("/") || path.split(".").some((part) => part.length === 0)) {
|
|
3783
|
+
throw new MalformedTrustMetadataError("a files tainted path is not a dotted path");
|
|
3784
|
+
}
|
|
3785
|
+
return path.split(".")[0];
|
|
3786
|
+
}
|
|
3787
|
+
function optional(value, check) {
|
|
3788
|
+
return value === void 0 || value === null || check(value);
|
|
3789
|
+
}
|
|
3790
|
+
function isBox(value) {
|
|
3791
|
+
return Array.isArray(value) && value.length === 4 && value.every((n) => typeof n === "number" && Number.isFinite(n) && n >= 0 && n <= 1) && value[0] <= value[2] && value[1] <= value[3];
|
|
3792
|
+
}
|
|
3793
|
+
function isRegion(value) {
|
|
3794
|
+
return isObject2(value) && isInt2(value.page) && value.page >= 1 && typeof value.reason === "string" && Array.isArray(value.boxes) && value.boxes.every(isBox);
|
|
3795
|
+
}
|
|
3796
|
+
function isFlag(value) {
|
|
3797
|
+
if (!isRegion(value)) return false;
|
|
3798
|
+
const flag = value;
|
|
3799
|
+
return (flag.scope === null || FLAG_SCOPES.includes(flag.scope)) && Array.isArray(flag.lines) && flag.lines.every((line) => isInt2(line) && line >= 0);
|
|
3800
|
+
}
|
|
3801
|
+
function parseRecordTrust(value) {
|
|
3802
|
+
if (!isObject2(value)) {
|
|
3803
|
+
throw new MalformedTrustMetadataError("_sys.trust is not an object");
|
|
3804
|
+
}
|
|
3805
|
+
const ok = isInt2(value.version) && typeof value.source === "string" && typeof value.provenance === "string" && typeof value.screened === "boolean" && optional(value.verdict, (v) => typeof v === "string") && optional(value.reasons, isStringArray) && typeof value.path_format === "string" && isStringArray(value.tainted_paths) && isStringMap(value.writers) && isStringMap(value.sources);
|
|
3806
|
+
const tainted = new Set(ok ? value.tainted_paths : []);
|
|
3807
|
+
const writers = ok ? Object.keys(value.writers) : [];
|
|
3808
|
+
const consistent = value.verdict !== null && value.reasons !== null && value.verdict === void 0 === (value.reasons === void 0) && !(value.screened === true && value.verdict === void 0) && writers.length === tainted.size && writers.every((path) => tainted.has(path)) && // writers not recorded: no path is known to be tainted (nor, so, a writer or source)
|
|
3809
|
+
!(value.provenance === "unknown" && tainted.size > 0) && (!ok || Object.keys(value.sources).every((path) => tainted.has(path)));
|
|
3810
|
+
if (!ok || !consistent) {
|
|
3811
|
+
throw new MalformedTrustMetadataError("_sys.trust is malformed");
|
|
3812
|
+
}
|
|
3813
|
+
const trust = { ...value };
|
|
3814
|
+
for (const path of [
|
|
3815
|
+
...trust.tainted_paths,
|
|
3816
|
+
...Object.keys(trust.writers),
|
|
3817
|
+
...Object.keys(trust.sources)
|
|
3818
|
+
]) {
|
|
3819
|
+
pointerField(path);
|
|
3820
|
+
}
|
|
3821
|
+
return trust;
|
|
3822
|
+
}
|
|
3823
|
+
function parseFileTrust(value) {
|
|
3824
|
+
if (!isObject2(value)) {
|
|
3825
|
+
throw new MalformedTrustMetadataError("data.trust is not an object");
|
|
3826
|
+
}
|
|
3827
|
+
const ok = isInt2(value.version) && typeof value.source === "string" && typeof value.upload === "string" && typeof value.verdict === "string" && isStringArray(value.reasons) && typeof value.processing === "string" && Array.isArray(value.redacted) && value.redacted.every(isRegion) && Array.isArray(value.unreliable) && value.unreliable.every(isFlag) && isStringArray(value.tainted_paths);
|
|
3828
|
+
if (!ok) {
|
|
3829
|
+
throw new MalformedTrustMetadataError("data.trust is malformed");
|
|
3830
|
+
}
|
|
3831
|
+
const trust = { ...value };
|
|
3832
|
+
for (const path of trust.tainted_paths) {
|
|
3833
|
+
dottedField(path);
|
|
3834
|
+
}
|
|
3835
|
+
return trust;
|
|
3836
|
+
}
|
|
3837
|
+
function isRecognizedRecordTrust(trust) {
|
|
3838
|
+
return trust.version === 1 && trust.source === RECORD_TRUST_SOURCE && PROVENANCE_STATES.includes(trust.provenance) && trust.path_format === "json_pointer" && (trust.verdict === void 0 || FILE_VERDICTS.includes(trust.verdict));
|
|
3839
|
+
}
|
|
3840
|
+
function isRecognizedFileTrust(trust) {
|
|
3841
|
+
return trust.version === 1 && trust.source === FILE_TRUST_SOURCE && FILE_VERDICTS.includes(trust.verdict) && FILE_PROCESSING.includes(trust.processing);
|
|
3842
|
+
}
|
|
3843
|
+
function getRecordTrust(record) {
|
|
3844
|
+
const sys = isObject2(record) ? record._sys : void 0;
|
|
3845
|
+
if (!isObject2(sys) || !("trust" in sys)) {
|
|
3846
|
+
return null;
|
|
3847
|
+
}
|
|
3848
|
+
return parseRecordTrust(sys.trust);
|
|
3849
|
+
}
|
|
3850
|
+
function fileBlocks(data) {
|
|
3851
|
+
return Object.entries(data).filter(
|
|
3852
|
+
([key, value]) => isObject2(value) && "processing" in value && (key === DEFAULT_FILE_BLOCK_KEY || "uuid" in value && "tainted_paths" in value)
|
|
3853
|
+
).map(([, value]) => value);
|
|
3854
|
+
}
|
|
3855
|
+
function boundBlock(data, upload) {
|
|
3856
|
+
if (typeof upload !== "string" || upload.length === 0) return void 0;
|
|
3857
|
+
const found = Object.entries(data).find(
|
|
3858
|
+
([key, value]) => key !== "trust" && isObject2(value) && "processing" in value && value.uuid === upload
|
|
3859
|
+
);
|
|
3860
|
+
return found?.[1];
|
|
3861
|
+
}
|
|
3862
|
+
function isFilesData(data) {
|
|
3863
|
+
const trust = data.trust;
|
|
3864
|
+
return isObject2(trust) && trust.source === FILE_TRUST_SOURCE || fileBlocks(data).length > 0 || isObject2(trust) && boundBlock(data, trust.upload) !== void 0;
|
|
3865
|
+
}
|
|
3866
|
+
function getFileTrust(record) {
|
|
3867
|
+
const data = isObject2(record) ? record.data : void 0;
|
|
3868
|
+
if (!isObject2(data) || !isFilesData(data)) {
|
|
3869
|
+
return null;
|
|
3870
|
+
}
|
|
3871
|
+
if (!("trust" in data)) {
|
|
3872
|
+
throw new MalformedTrustMetadataError("a files record has no data.trust");
|
|
3873
|
+
}
|
|
3874
|
+
const trust = parseFileTrust(data.trust);
|
|
3875
|
+
const block = boundBlock(data, trust.upload);
|
|
3876
|
+
if (block === void 0) {
|
|
3877
|
+
throw new MalformedTrustMetadataError("data.trust.upload is not a file block's uuid");
|
|
3878
|
+
}
|
|
3879
|
+
if (FILE_PROCESSING.includes(trust.processing) && block.processing === "agent_ready" !== (trust.processing === "agent_ready")) {
|
|
3880
|
+
throw new MalformedTrustMetadataError("data.trust.processing disagrees with the file block");
|
|
3881
|
+
}
|
|
3882
|
+
return trust;
|
|
3883
|
+
}
|
|
3884
|
+
function getUntrustedFields(record) {
|
|
3885
|
+
const data = isObject2(record) && isObject2(record.data) ? record.data : {};
|
|
3886
|
+
const fields = /* @__PURE__ */ new Set();
|
|
3887
|
+
const recordTrust = getRecordTrust(record);
|
|
3888
|
+
const fileTrust = getFileTrust(record);
|
|
3889
|
+
if (recordTrust) {
|
|
3890
|
+
const tainted = recordTrust.tainted_paths.map(pointerField);
|
|
3891
|
+
if (!isRecognizedRecordTrust(recordTrust)) {
|
|
3892
|
+
return Object.keys(data).sort();
|
|
3893
|
+
}
|
|
3894
|
+
tainted.forEach((f) => fields.add(f));
|
|
3895
|
+
}
|
|
3896
|
+
if (fileTrust) {
|
|
3897
|
+
const tainted = fileTrust.tainted_paths.map(dottedField);
|
|
3898
|
+
if (!isRecognizedFileTrust(fileTrust)) {
|
|
3899
|
+
return Object.keys(data).sort();
|
|
3900
|
+
}
|
|
3901
|
+
tainted.forEach((f) => fields.add(f));
|
|
3902
|
+
}
|
|
3903
|
+
return [...fields].sort();
|
|
3904
|
+
}
|
|
2774
3905
|
export {
|
|
2775
3906
|
AnonymousAuth,
|
|
2776
3907
|
CollectionNotWritableError,
|
|
@@ -2785,8 +3916,10 @@ export {
|
|
|
2785
3916
|
FoxnoseAuthError,
|
|
2786
3917
|
FoxnoseError,
|
|
2787
3918
|
FoxnoseTransportError,
|
|
3919
|
+
GUARDRAILS_POLICY_FIELDS,
|
|
2788
3920
|
HttpTransport,
|
|
2789
3921
|
JWTAuth,
|
|
3922
|
+
MalformedTrustMetadataError,
|
|
2790
3923
|
ManagementClient,
|
|
2791
3924
|
PlanExhaustedError,
|
|
2792
3925
|
PlanLimitExceededError,
|
|
@@ -2797,6 +3930,9 @@ export {
|
|
|
2797
3930
|
SimpleKeyAuth,
|
|
2798
3931
|
SpendCapExceededError,
|
|
2799
3932
|
StaticTokenProvider,
|
|
3933
|
+
TENANT_TOKEN_PREFIX,
|
|
3934
|
+
TenantTokenAuth,
|
|
3935
|
+
TenantTokenSource,
|
|
2800
3936
|
UpstreamError,
|
|
2801
3937
|
SDK_VERSION as VERSION,
|
|
2802
3938
|
WebhookEndpointLimitExceededError,
|
|
@@ -2804,10 +3940,22 @@ export {
|
|
|
2804
3940
|
WebhookEndpointNotFoundError,
|
|
2805
3941
|
WebhookEndpointNotSubscribedError,
|
|
2806
3942
|
WebhookEventNotFoundError,
|
|
3943
|
+
bearerErrors,
|
|
2807
3944
|
buildSearchBody,
|
|
2808
3945
|
createConfig,
|
|
3946
|
+
generateTenantSigningKey,
|
|
3947
|
+
getFileTrust,
|
|
3948
|
+
getRecordTrust,
|
|
3949
|
+
getResourceGuardrailsSummary,
|
|
3950
|
+
getRevisionGuardrailsSummary,
|
|
3951
|
+
getUntrustedFields,
|
|
3952
|
+
isInvalidTokenChallenge,
|
|
3953
|
+
isRecognizedFileTrust,
|
|
3954
|
+
isRecognizedRecordTrust,
|
|
2809
3955
|
nestedFieldMeta,
|
|
2810
3956
|
parseFindingEvidence,
|
|
2811
|
-
resolveKey
|
|
3957
|
+
resolveKey,
|
|
3958
|
+
signTenantToken,
|
|
3959
|
+
tenantTokenFetch
|
|
2812
3960
|
};
|
|
2813
3961
|
//# sourceMappingURL=index.js.map
|