@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/dist/index.cjs CHANGED
@@ -33,8 +33,10 @@ __export(index_exports, {
33
33
  FoxnoseAuthError: () => FoxnoseAuthError,
34
34
  FoxnoseError: () => FoxnoseError,
35
35
  FoxnoseTransportError: () => FoxnoseTransportError,
36
+ GUARDRAILS_POLICY_FIELDS: () => GUARDRAILS_POLICY_FIELDS,
36
37
  HttpTransport: () => HttpTransport,
37
38
  JWTAuth: () => JWTAuth,
39
+ MalformedTrustMetadataError: () => MalformedTrustMetadataError,
38
40
  ManagementClient: () => ManagementClient,
39
41
  PlanExhaustedError: () => PlanExhaustedError,
40
42
  PlanLimitExceededError: () => PlanLimitExceededError,
@@ -45,6 +47,9 @@ __export(index_exports, {
45
47
  SimpleKeyAuth: () => SimpleKeyAuth,
46
48
  SpendCapExceededError: () => SpendCapExceededError,
47
49
  StaticTokenProvider: () => StaticTokenProvider,
50
+ TENANT_TOKEN_PREFIX: () => TENANT_TOKEN_PREFIX,
51
+ TenantTokenAuth: () => TenantTokenAuth,
52
+ TenantTokenSource: () => TenantTokenSource,
48
53
  UpstreamError: () => UpstreamError,
49
54
  VERSION: () => SDK_VERSION,
50
55
  WebhookEndpointLimitExceededError: () => WebhookEndpointLimitExceededError,
@@ -52,11 +57,23 @@ __export(index_exports, {
52
57
  WebhookEndpointNotFoundError: () => WebhookEndpointNotFoundError,
53
58
  WebhookEndpointNotSubscribedError: () => WebhookEndpointNotSubscribedError,
54
59
  WebhookEventNotFoundError: () => WebhookEventNotFoundError,
60
+ bearerErrors: () => bearerErrors,
55
61
  buildSearchBody: () => buildSearchBody,
56
62
  createConfig: () => createConfig,
63
+ generateTenantSigningKey: () => generateTenantSigningKey,
64
+ getFileTrust: () => getFileTrust,
65
+ getRecordTrust: () => getRecordTrust,
66
+ getResourceGuardrailsSummary: () => getResourceGuardrailsSummary,
67
+ getRevisionGuardrailsSummary: () => getRevisionGuardrailsSummary,
68
+ getUntrustedFields: () => getUntrustedFields,
69
+ isInvalidTokenChallenge: () => isInvalidTokenChallenge,
70
+ isRecognizedFileTrust: () => isRecognizedFileTrust,
71
+ isRecognizedRecordTrust: () => isRecognizedRecordTrust,
57
72
  nestedFieldMeta: () => nestedFieldMeta,
58
73
  parseFindingEvidence: () => parseFindingEvidence,
59
- resolveKey: () => resolveKey
74
+ resolveKey: () => resolveKey,
75
+ signTenantToken: () => signTenantToken,
76
+ tenantTokenFetch: () => tenantTokenFetch
60
77
  });
61
78
  module.exports = __toCommonJS(index_exports);
62
79
 
@@ -483,6 +500,471 @@ var SimpleKeyAuth = class {
483
500
  }
484
501
  };
485
502
 
503
+ // src/tenantTokens.ts
504
+ var import_node_crypto2 = require("crypto");
505
+ var TENANT_TOKEN_PREFIX = "fxt_";
506
+ var MAX_TOKEN_BYTES = 4096;
507
+ var MAX_TTL_SECONDS = 86400;
508
+ var MAX_ANCHORS = 10;
509
+ var SUB_MAX = 128;
510
+ var ANCHOR_RECORD_MAX = 64;
511
+ var KID_RE = /^tsk_[A-Za-z0-9]{12}$/;
512
+ var JTI_RE = /^[A-Za-z0-9_-]{16,64}$/;
513
+ var NOT_PRINTABLE_RE = /[\p{C}\p{Z}]/u;
514
+ function generateTenantSigningKey() {
515
+ const { privateKey, publicKey } = (0, import_node_crypto2.generateKeyPairSync)("ec", { namedCurve: "P-256" });
516
+ const pair = {
517
+ publicKey: publicKey.export({ format: "der", type: "spki" }).toString("base64")
518
+ };
519
+ Object.defineProperty(pair, "privateKey", {
520
+ value: privateKey.export({ format: "der", type: "pkcs8" }).toString("base64"),
521
+ enumerable: false,
522
+ writable: false
523
+ });
524
+ return pair;
525
+ }
526
+ function isInt(value) {
527
+ return typeof value === "number" && Number.isSafeInteger(value);
528
+ }
529
+ function stringList(name, value) {
530
+ if (!Array.isArray(value) || !value.every((v) => typeof v === "string")) {
531
+ throw new Error(`${name} must be an array of strings`);
532
+ }
533
+ return [...value];
534
+ }
535
+ function anchorClaim(anchors) {
536
+ if (!Array.isArray(anchors)) {
537
+ throw new Error("anchors must be an array of [collectionKey, recordKey] pairs");
538
+ }
539
+ if (anchors.length < 1 || anchors.length > MAX_ANCHORS) {
540
+ throw new Error(`anchors must hold 1 to ${MAX_ANCHORS} entries`);
541
+ }
542
+ const seen = /* @__PURE__ */ new Set();
543
+ return anchors.map((item) => {
544
+ let collection;
545
+ let record;
546
+ if (Array.isArray(item) && item.length === 2) {
547
+ [collection, record] = item;
548
+ } else if (item && typeof item === "object" && !Array.isArray(item)) {
549
+ const anchor = item;
550
+ collection = anchor.collection ?? anchor.c;
551
+ record = anchor.record ?? anchor.r;
552
+ } else {
553
+ throw new Error("each anchor must be a [collectionKey, recordKey] pair");
554
+ }
555
+ if (typeof collection !== "string" || collection.length === 0) {
556
+ throw new Error("an anchor's collection key must be a non-empty string");
557
+ }
558
+ if (typeof record !== "string" || [...record].length < 1 || [...record].length > ANCHOR_RECORD_MAX) {
559
+ throw new Error(
560
+ `an anchor's record key must be a string of 1 to ${ANCHOR_RECORD_MAX} characters`
561
+ );
562
+ }
563
+ const id = `${collection}\0${record}`;
564
+ if (seen.has(id)) {
565
+ throw new Error("anchors must not repeat");
566
+ }
567
+ seen.add(id);
568
+ return { c: collection, r: record };
569
+ });
570
+ }
571
+ function loadPrivateKey(privateKey) {
572
+ let key;
573
+ try {
574
+ if (typeof privateKey === "object" && "asymmetricKeyType" in privateKey) {
575
+ key = privateKey;
576
+ } else if (typeof privateKey === "string" && privateKey.trimStart().startsWith("-----BEGIN")) {
577
+ key = (0, import_node_crypto2.createPrivateKey)(privateKey);
578
+ } else {
579
+ const der = typeof privateKey === "string" ? Buffer.from(privateKey, "base64") : Buffer.from(privateKey);
580
+ try {
581
+ key = (0, import_node_crypto2.createPrivateKey)({ key: der, format: "der", type: "pkcs8" });
582
+ } catch {
583
+ key = (0, import_node_crypto2.createPrivateKey)({ key: der, format: "der", type: "sec1" });
584
+ }
585
+ }
586
+ } catch {
587
+ throw new Error(
588
+ "privateKey is not a P-256 private key in PEM, PKCS#8 DER or base64 PKCS#8 DER form"
589
+ );
590
+ }
591
+ if (key.type !== "private" || key.asymmetricKeyType !== "ec" || key.asymmetricKeyDetails?.namedCurve !== "prime256v1") {
592
+ throw new Error("privateKey must be a P-256 (prime256v1) private key");
593
+ }
594
+ return key;
595
+ }
596
+ function b64url(data) {
597
+ return Buffer.from(data).toString("base64url");
598
+ }
599
+ function signTenantToken(privateKey, options) {
600
+ const { kid, environmentKey, sub } = options;
601
+ if (typeof kid !== "string" || !KID_RE.test(kid)) {
602
+ throw new Error("kid must be 'tsk_' followed by 12 letters or digits");
603
+ }
604
+ if (typeof environmentKey !== "string" || environmentKey.length === 0) {
605
+ throw new Error("environmentKey must be a non-empty string");
606
+ }
607
+ if (typeof sub !== "string" || [...sub].length < 1 || [...sub].length > SUB_MAX || [...sub].some((ch) => ch !== " " && NOT_PRINTABLE_RE.test(ch))) {
608
+ throw new Error(`sub must be 1 to ${SUB_MAX} printable characters`);
609
+ }
610
+ const ttl = options.ttl ?? 900;
611
+ if (!isInt(ttl) || ttl < 1 || ttl > MAX_TTL_SECONDS) {
612
+ throw new Error(`ttl must be an integer from 1 to ${MAX_TTL_SECONDS}`);
613
+ }
614
+ const jti = options.jti ?? (0, import_node_crypto2.randomBytes)(24).toString("base64url");
615
+ if (typeof jti !== "string" || !JTI_RE.test(jti)) {
616
+ throw new Error("jti must be 16 to 64 characters of A-Z a-z 0-9 - _");
617
+ }
618
+ const iat = options.now ?? Math.floor(Date.now() / 1e3);
619
+ if (!isInt(iat)) {
620
+ throw new Error("now must be an integer number of seconds");
621
+ }
622
+ const exp = iat + ttl;
623
+ const claims = {
624
+ aud: `flux:${environmentKey}`,
625
+ sub,
626
+ anc: anchorClaim(options.anchors),
627
+ iat,
628
+ exp,
629
+ jti
630
+ };
631
+ if (options.notBefore !== void 0) {
632
+ if (!isInt(options.notBefore) || options.notBefore >= exp) {
633
+ throw new Error("notBefore must be an integer before the token's expiry");
634
+ }
635
+ claims.nbf = options.notBefore;
636
+ }
637
+ if (options.apis !== void 0) {
638
+ if (!options.apis || typeof options.apis !== "object" || Array.isArray(options.apis)) {
639
+ throw new Error("apis must map an API prefix to a list of actions");
640
+ }
641
+ const apis = {};
642
+ for (const [prefix, actions] of Object.entries(options.apis)) {
643
+ apis[prefix] = stringList("each apis entry", actions);
644
+ }
645
+ claims.apis = apis;
646
+ }
647
+ if (options.collections !== void 0) {
648
+ claims.col = stringList("collections", options.collections);
649
+ }
650
+ if (options.sharedRead !== void 0) {
651
+ claims.shr = stringList("sharedRead", options.sharedRead);
652
+ }
653
+ const key = loadPrivateKey(privateKey);
654
+ const header = { alg: "ES256", typ: "fxt+jwt", kid };
655
+ const signingInput = `${b64url(JSON.stringify(header))}.${b64url(JSON.stringify(claims))}`;
656
+ const signature = (0, import_node_crypto2.sign)("sha256", Buffer.from(signingInput, "ascii"), {
657
+ key,
658
+ dsaEncoding: "ieee-p1363"
659
+ });
660
+ const token = `${TENANT_TOKEN_PREFIX}${signingInput}.${b64url(signature)}`;
661
+ if (Buffer.byteLength(token, "utf8") > MAX_TOKEN_BYTES) {
662
+ throw new Error(
663
+ `the token is longer than ${MAX_TOKEN_BYTES} bytes; use fewer or shorter claims`
664
+ );
665
+ }
666
+ return token;
667
+ }
668
+ var HTTP_TOKEN = "[!#$%&'*+\\-.^_`|~0-9A-Za-z]+";
669
+ var SCHEME_RE = new RegExp(HTTP_TOKEN, "y");
670
+ var PARAM_RE = new RegExp(
671
+ `(${HTTP_TOKEN})[ \\t]*=[ \\t]*(?:"((?:[^"\\\\]|\\\\.)*)"|(${HTTP_TOKEN}))`,
672
+ "y"
673
+ );
674
+ function bearerErrors(wwwAuthenticate) {
675
+ const errors = [];
676
+ let scheme = null;
677
+ let i = 0;
678
+ while (i < wwwAuthenticate.length) {
679
+ const ch = wwwAuthenticate[i];
680
+ if (ch === " " || ch === " " || ch === ",") {
681
+ i += 1;
682
+ continue;
683
+ }
684
+ PARAM_RE.lastIndex = i;
685
+ const param = scheme !== null ? PARAM_RE.exec(wwwAuthenticate) : null;
686
+ if (param) {
687
+ const name = param[1].toLowerCase();
688
+ const value = param[2] !== void 0 ? param[2].replace(/\\(.)/g, "$1") : param[3];
689
+ if (scheme === "bearer" && name === "error") {
690
+ errors.push(value);
691
+ }
692
+ i = PARAM_RE.lastIndex;
693
+ continue;
694
+ }
695
+ SCHEME_RE.lastIndex = i;
696
+ const word = SCHEME_RE.exec(wwwAuthenticate);
697
+ if (word) {
698
+ scheme = word[0].toLowerCase();
699
+ i = SCHEME_RE.lastIndex;
700
+ continue;
701
+ }
702
+ i += 1;
703
+ }
704
+ return errors;
705
+ }
706
+ function isInvalidTokenChallenge(status, wwwAuthenticate) {
707
+ if (status !== 401 || !wwwAuthenticate) {
708
+ return false;
709
+ }
710
+ return bearerErrors(wwwAuthenticate).includes("invalid_token");
711
+ }
712
+ function notAToken(detail) {
713
+ return new Error(`mint must return a tenant token (fxt_...): ${detail}`);
714
+ }
715
+ function decodeSegment(segment) {
716
+ if (!/^[A-Za-z0-9_-]*$/.test(segment)) {
717
+ throw notAToken("it cannot be decoded");
718
+ }
719
+ try {
720
+ return JSON.parse(Buffer.from(segment, "base64url").toString("utf8"));
721
+ } catch {
722
+ throw notAToken("it cannot be decoded");
723
+ }
724
+ }
725
+ function sortedStrings(value, name) {
726
+ if (value === void 0) {
727
+ return null;
728
+ }
729
+ if (!Array.isArray(value) || !value.every((v) => typeof v === "string")) {
730
+ throw notAToken(`${name} is not a list of strings`);
731
+ }
732
+ return [...new Set(value)].sort();
733
+ }
734
+ function isObject(value) {
735
+ return value !== null && typeof value === "object" && !Array.isArray(value);
736
+ }
737
+ function inspectMinted(token) {
738
+ if (typeof token !== "string" || !token.startsWith(TENANT_TOKEN_PREFIX)) {
739
+ throw notAToken("no fxt_ prefix");
740
+ }
741
+ const parts = token.slice(TENANT_TOKEN_PREFIX.length).split(".");
742
+ if (parts.length !== 3) {
743
+ throw notAToken("it cannot be decoded");
744
+ }
745
+ const header = decodeSegment(parts[0]);
746
+ const claims = decodeSegment(parts[1]);
747
+ if (!isObject(header) || !isObject(claims)) {
748
+ throw notAToken("its header or claims are not objects");
749
+ }
750
+ for (const [name, value] of [
751
+ ["kid", header.kid],
752
+ ["aud", claims.aud],
753
+ ["sub", claims.sub]
754
+ ]) {
755
+ if (typeof value !== "string") {
756
+ throw notAToken(`${name} is not a string`);
757
+ }
758
+ }
759
+ if (!isInt(claims.exp)) {
760
+ throw notAToken("exp is not an integer");
761
+ }
762
+ const anchors = claims.anc;
763
+ if (!Array.isArray(anchors) || !anchors.every(
764
+ (a) => isObject(a) && Object.keys(a).sort().join(",") === "c,r" && typeof a.c === "string" && typeof a.r === "string"
765
+ )) {
766
+ throw notAToken("anc is not a list of {c, r} strings");
767
+ }
768
+ let apis = null;
769
+ if (claims.apis !== void 0) {
770
+ if (!isObject(claims.apis)) {
771
+ throw notAToken("apis is not an object");
772
+ }
773
+ apis = {};
774
+ for (const prefix of Object.keys(claims.apis).sort()) {
775
+ apis[prefix] = sortedStrings(claims.apis[prefix], "an apis entry");
776
+ }
777
+ }
778
+ const scope = JSON.stringify([
779
+ header.kid,
780
+ claims.aud,
781
+ claims.sub,
782
+ [
783
+ ...new Set(anchors.map((a) => `${a.c}\0${a.r}`))
784
+ ].sort(),
785
+ apis === null ? null : Object.entries(apis),
786
+ sortedStrings(claims.col, "col"),
787
+ sortedStrings(claims.shr, "shr")
788
+ ]);
789
+ return { token, expiresAt: claims.exp, scope };
790
+ }
791
+ var SOURCE_STATE = /* @__PURE__ */ new WeakMap();
792
+ function stateOf(source) {
793
+ return SOURCE_STATE.get(source);
794
+ }
795
+ var INSPECT = /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom");
796
+ var TenantTokenSource = class {
797
+ mint;
798
+ refreshBefore;
799
+ clock;
800
+ constructor(mint, options) {
801
+ if (typeof mint !== "function") {
802
+ throw new TypeError("mint must be a function that returns a token");
803
+ }
804
+ const refreshBefore = options?.refreshBefore ?? 60;
805
+ if (!isInt(refreshBefore) || refreshBefore < 0) {
806
+ throw new Error("refreshBefore must be a non-negative integer");
807
+ }
808
+ this.mint = mint;
809
+ this.refreshBefore = refreshBefore;
810
+ this.clock = options?.clock ?? Date.now;
811
+ SOURCE_STATE.set(this, { current: null, scope: null, inFlight: null });
812
+ }
813
+ toJSON() {
814
+ return { refreshBefore: this.refreshBefore };
815
+ }
816
+ [INSPECT]() {
817
+ return `TenantTokenSource { refreshBefore: ${this.refreshBefore} }`;
818
+ }
819
+ fresh() {
820
+ const current = stateOf(this).current;
821
+ if (current && this.clock() / 1e3 < current.expiresAt - this.refreshBefore) {
822
+ return current.token;
823
+ }
824
+ return null;
825
+ }
826
+ accept(raw) {
827
+ const minted = inspectMinted(raw);
828
+ const state = stateOf(this);
829
+ if (state.scope === null) {
830
+ state.scope = minted.scope;
831
+ } else if (minted.scope !== state.scope) {
832
+ throw new Error(
833
+ "mint returned a token for another scope (signing key, environment, sub, anchors or narrowing claims); use one TenantTokenSource per end user"
834
+ );
835
+ }
836
+ state.current = minted;
837
+ return minted.token;
838
+ }
839
+ /** The current token, minted again when close to expiry. `mint` must be synchronous. */
840
+ tokenSync() {
841
+ const fresh = this.fresh();
842
+ if (fresh !== null) {
843
+ return fresh;
844
+ }
845
+ const raw = this.mint();
846
+ if (raw && typeof raw.then === "function") {
847
+ raw.then(void 0, () => void 0);
848
+ throw new TypeError("mint returned a Promise; use token() or tenantTokenFetch");
849
+ }
850
+ return this.accept(raw);
851
+ }
852
+ /** The current token, minted again when close to expiry. Concurrent callers share one mint. */
853
+ async token() {
854
+ const fresh = this.fresh();
855
+ if (fresh !== null) {
856
+ return fresh;
857
+ }
858
+ const state = stateOf(this);
859
+ if (state.inFlight === null) {
860
+ state.inFlight = (async () => {
861
+ try {
862
+ return this.accept(await this.mint());
863
+ } finally {
864
+ state.inFlight = null;
865
+ }
866
+ })();
867
+ }
868
+ return state.inFlight;
869
+ }
870
+ /**
871
+ * Mint a new token on the next request. With `token`, only if the cached token is
872
+ * still that one, so a refusal of an older token leaves a newer one in place.
873
+ */
874
+ invalidate(token) {
875
+ const state = stateOf(this);
876
+ if (token === void 0 || state.current !== null && state.current.token === token) {
877
+ state.current = null;
878
+ }
879
+ }
880
+ };
881
+ function sourceOf(mint, options) {
882
+ return mint instanceof TenantTokenSource ? mint : new TenantTokenSource(mint, options);
883
+ }
884
+ function refusedToken(status, wwwAuthenticate, failedAuthorization) {
885
+ if (!isInvalidTokenChallenge(status, wwwAuthenticate)) {
886
+ return null;
887
+ }
888
+ const prefix = `Bearer ${TENANT_TOKEN_PREFIX}`;
889
+ if (!failedAuthorization || !failedAuthorization.startsWith(prefix)) {
890
+ return null;
891
+ }
892
+ return failedAuthorization.slice("Bearer ".length);
893
+ }
894
+ var TenantTokenAuth = class {
895
+ source;
896
+ constructor(mint, options) {
897
+ this.source = sourceOf(mint, options);
898
+ }
899
+ buildHeaders(_request) {
900
+ return { Authorization: `Bearer ${this.source.tokenSync()}` };
901
+ }
902
+ refreshAfterUnauthorized(status, headers, failedAuthorization) {
903
+ const refused = refusedToken(status, headers.get("www-authenticate"), failedAuthorization);
904
+ if (refused === null) {
905
+ return false;
906
+ }
907
+ this.source.invalidate(refused);
908
+ return true;
909
+ }
910
+ toJSON() {
911
+ return this.source.toJSON();
912
+ }
913
+ [INSPECT]() {
914
+ return `TenantTokenAuth { source: ${this.source[INSPECT]()} }`;
915
+ }
916
+ };
917
+ function replayableBody(body) {
918
+ if (body === void 0 || body === null || typeof body === "string") {
919
+ return true;
920
+ }
921
+ if (body instanceof URLSearchParams || body instanceof ArrayBuffer || ArrayBuffer.isView(body)) {
922
+ return true;
923
+ }
924
+ if (typeof Blob !== "undefined" && body instanceof Blob) {
925
+ return true;
926
+ }
927
+ if (typeof FormData !== "undefined" && body instanceof FormData) {
928
+ return true;
929
+ }
930
+ return false;
931
+ }
932
+ function tenantTokenFetch(mint, options) {
933
+ const source = sourceOf(mint, options);
934
+ const wrapped = async (input, init) => {
935
+ const baseFetch = options?.fetch ?? globalThis.fetch;
936
+ const isRequest = typeof Request !== "undefined" && input instanceof Request;
937
+ const signal = init?.signal ?? (isRequest ? input.signal : void 0);
938
+ const canReplay = replayableBody(init?.body) && !(isRequest && input.body !== null);
939
+ const send = async () => {
940
+ const authorization = `Bearer ${await source.token()}`;
941
+ const headers = new Headers(isRequest ? input.headers : void 0);
942
+ if (init?.headers !== void 0) {
943
+ new Headers(init.headers).forEach((value, name) => headers.set(name, value));
944
+ }
945
+ headers.set("Authorization", authorization);
946
+ const response = isRequest ? await baseFetch(new Request(input, { ...init, headers })) : await baseFetch(input, { ...init, headers });
947
+ return { response, authorization };
948
+ };
949
+ const first = await send();
950
+ if (!canReplay || signal?.aborted) {
951
+ return first.response;
952
+ }
953
+ const refused = refusedToken(
954
+ first.response.status,
955
+ first.response.headers.get("www-authenticate"),
956
+ first.authorization
957
+ );
958
+ if (refused === null) {
959
+ return first.response;
960
+ }
961
+ source.invalidate(refused);
962
+ await first.response.body?.cancel().catch(() => void 0);
963
+ return (await send()).response;
964
+ };
965
+ return wrapped;
966
+ }
967
+
486
968
  // src/config.ts
487
969
  var DEFAULT_RETRY_CONFIG = {
488
970
  attempts: 3,
@@ -490,7 +972,7 @@ var DEFAULT_RETRY_CONFIG = {
490
972
  statusCodes: [408, 425, 429, 500, 502, 503, 504],
491
973
  methods: ["GET", "HEAD", "OPTIONS", "PUT", "DELETE"]
492
974
  };
493
- var SDK_VERSION = "0.8.0";
975
+ var SDK_VERSION = "0.9.0";
494
976
  var DEFAULT_USER_AGENT = `foxnose-sdk-js/${SDK_VERSION}`;
495
977
  function createConfig(options) {
496
978
  if (!options.baseUrl) {
@@ -620,23 +1102,32 @@ var HttpTransport = class {
620
1102
  }
621
1103
  async sendWithRetries(method, path, options) {
622
1104
  const allowRetries = options?.allowRetries !== false;
1105
+ let replayed = false;
623
1106
  for (let attempt = 1; attempt <= this.retry.attempts; attempt++) {
624
- const { url, init } = this.buildRequest(method, path, options);
625
- const controller = new AbortController();
626
- const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);
627
- init.signal = controller.signal;
1107
+ const request = this.buildRequest(method, path, options);
628
1108
  let response;
629
1109
  try {
630
- response = await fetch(url, init);
1110
+ response = await this.send(request);
631
1111
  } catch (err) {
632
- clearTimeout(timeoutId);
633
1112
  const delay = this.handleTransportError(err, method, attempt, !allowRetries);
634
1113
  if (delay > 0) {
635
1114
  await this.sleep(delay);
636
1115
  }
637
1116
  continue;
638
- } finally {
639
- clearTimeout(timeoutId);
1117
+ }
1118
+ if (!replayed && this.refreshAuthAfter(response)) {
1119
+ replayed = true;
1120
+ await response.body?.cancel().catch(() => void 0);
1121
+ const again = this.buildRequest(method, path, options);
1122
+ try {
1123
+ response = await this.send(again);
1124
+ } catch (err) {
1125
+ const delay = this.handleTransportError(err, method, attempt, !allowRetries);
1126
+ if (delay > 0) {
1127
+ await this.sleep(delay);
1128
+ }
1129
+ continue;
1130
+ }
640
1131
  }
641
1132
  if (response.status >= 400) {
642
1133
  if (allowRetries && this.shouldRetry(method, response.status) && attempt < this.retry.attempts) {
@@ -652,6 +1143,33 @@ var HttpTransport = class {
652
1143
  }
653
1144
  throw new FoxnoseTransportError("All retry attempts exhausted");
654
1145
  }
1146
+ /** Send one built request; the `Authorization` it carried is kept for the 401 hook. */
1147
+ async send(request) {
1148
+ const { url, init } = request;
1149
+ const controller = new AbortController();
1150
+ const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);
1151
+ init.signal = controller.signal;
1152
+ try {
1153
+ const response = await fetch(url, init);
1154
+ const sent = new Headers(init.headers).get("authorization");
1155
+ this.sentAuthorization.set(response, sent ?? void 0);
1156
+ return response;
1157
+ } finally {
1158
+ clearTimeout(timeoutId);
1159
+ }
1160
+ }
1161
+ sentAuthorization = /* @__PURE__ */ new WeakMap();
1162
+ /** Whether the auth strategy wants a `401` sent once more with new credentials. */
1163
+ refreshAuthAfter(response) {
1164
+ if (response.status !== 401 || typeof this.auth.refreshAfterUnauthorized !== "function") {
1165
+ return false;
1166
+ }
1167
+ return this.auth.refreshAfterUnauthorized(
1168
+ response.status,
1169
+ response.headers,
1170
+ this.sentAuthorization.get(response)
1171
+ );
1172
+ }
655
1173
  handleTransportError(err, method, attempt, forbidRetry = false) {
656
1174
  const canRetry = !forbidRetry && this.retry.methods.includes(method.toUpperCase()) && attempt < this.retry.attempts;
657
1175
  if (!canRetry) {
@@ -760,6 +1278,94 @@ function resolveKey(value) {
760
1278
  }
761
1279
  throw new TypeError(`Expected a string or an object with a 'key' attribute, got ${typeof value}`);
762
1280
  }
1281
+ function isPlainObject2(value) {
1282
+ return value !== null && typeof value === "object" && !Array.isArray(value);
1283
+ }
1284
+ function untrustedFields(value) {
1285
+ if (!Array.isArray(value) || !value.every(isUntrustedField)) {
1286
+ throw new TypeError("guardrails.untrusted_fields is malformed");
1287
+ }
1288
+ return value;
1289
+ }
1290
+ var UNTRUSTED_FIELD_STRINGS = ["field_label", "writer_type", "cause", "principal_key"];
1291
+ function isUntrustedField(value) {
1292
+ if (!isPlainObject2(value) || typeof value.path !== "string") {
1293
+ return false;
1294
+ }
1295
+ const absentOrNull = (v) => v === void 0 || v === null;
1296
+ return UNTRUSTED_FIELD_STRINGS.every((k) => absentOrNull(value[k]) || typeof value[k] === "string") && (absentOrNull(value.reviewed) || typeof value.reviewed === "boolean");
1297
+ }
1298
+ function str(value, name) {
1299
+ if (value === void 0 || value === null) {
1300
+ return null;
1301
+ }
1302
+ if (typeof value !== "string") {
1303
+ throw new TypeError(`guardrails.${name} is not a string`);
1304
+ }
1305
+ return value;
1306
+ }
1307
+ function bool(value, name) {
1308
+ if (typeof value !== "boolean") {
1309
+ throw new TypeError(`guardrails.${name} is not a boolean`);
1310
+ }
1311
+ return value;
1312
+ }
1313
+ function getResourceGuardrailsSummary(resource) {
1314
+ const g = resource.guardrails;
1315
+ if (g === void 0 || g === null) {
1316
+ return null;
1317
+ }
1318
+ if (!isPlainObject2(g)) {
1319
+ throw new TypeError("guardrails is not an object");
1320
+ }
1321
+ return {
1322
+ ...g,
1323
+ untrusted: bool(g.untrusted, "untrusted"),
1324
+ needs_review: bool(g.needs_review, "needs_review"),
1325
+ verdict: str(g.verdict, "verdict"),
1326
+ held: bool(g.held, "held"),
1327
+ untrusted_fields: untrustedFields(g.untrusted_fields)
1328
+ };
1329
+ }
1330
+ function getRevisionGuardrailsSummary(revision) {
1331
+ const g = revision.guardrails;
1332
+ if (g === void 0 || g === null) {
1333
+ return null;
1334
+ }
1335
+ if (!isPlainObject2(g)) {
1336
+ throw new TypeError("guardrails is not an object");
1337
+ }
1338
+ const list = (v, name) => {
1339
+ if (!Array.isArray(v) || !v.every((x) => typeof x === "string")) {
1340
+ throw new TypeError(`guardrails.${name} is not a list of strings`);
1341
+ }
1342
+ return v;
1343
+ };
1344
+ return {
1345
+ ...g,
1346
+ untrusted: bool(g.untrusted, "untrusted"),
1347
+ needs_review: bool(g.needs_review, "needs_review"),
1348
+ tainted_paths: list(g.tainted_paths, "tainted_paths"),
1349
+ state: str(g.state, "state"),
1350
+ review_state: str(g.review_state, "review_state"),
1351
+ verdict: str(g.verdict, "verdict"),
1352
+ reason: str(g.reason, "reason"),
1353
+ reasons: list(g.reasons, "reasons"),
1354
+ held: bool(g.held, "held"),
1355
+ untrusted_fields: untrustedFields(g.untrusted_fields)
1356
+ };
1357
+ }
1358
+ var GUARDRAILS_POLICY_FIELDS = [
1359
+ "mode",
1360
+ "overrides",
1361
+ "trusted_keys",
1362
+ "acknowledge_agent_trust",
1363
+ "link_allowlist",
1364
+ "hold",
1365
+ "suspicious_action",
1366
+ "screen",
1367
+ "max_screened_chars"
1368
+ ];
763
1369
 
764
1370
  // src/management/paths.ts
765
1371
  function managementPaths(environmentKey) {
@@ -801,6 +1407,18 @@ function managementPaths(environmentKey) {
801
1407
  webhooksRoot: () => `/v1/${environmentKey}/webhooks`,
802
1408
  webhookEndpointRoot: (endpointId) => `/v1/${environmentKey}/webhooks/endpoints/${encodeURIComponent(endpointId)}`,
803
1409
  webhookEventRoot: (eventId) => `/v1/${environmentKey}/webhooks/events/${encodeURIComponent(eventId)}`,
1410
+ // Tenant token paths
1411
+ tenantSigningKeysRoot: () => `/v1/${environmentKey}/tenant-signing-keys`,
1412
+ tenantSigningKeyRoot: (kid) => `/v1/${environmentKey}/tenant-signing-keys/${encodeURIComponent(kid)}`,
1413
+ tenantLimitsRoot: () => `/v1/${environmentKey}/tenant-limits`,
1414
+ // Guardrails paths
1415
+ guardrailsPolicyRoot: (collectionKey) => `/v1/${environmentKey}/collections/${collectionKey}/guardrails-policy`,
1416
+ guardrailsHeldRoot: (collectionKey) => `/v1/${environmentKey}/collections/${collectionKey}/guardrails/held`,
1417
+ guardrailsUsageRoot: (collectionKey) => `/v1/${environmentKey}/collections/${collectionKey}/guardrails/usage`,
1418
+ revisionGuardrailsRoot: (collectionKey, resourceKey, revisionKey) => `/v1/${environmentKey}/collections/${collectionKey}/resources/${resourceKey}/revisions/${revisionKey}/guardrails`,
1419
+ resourceGuardrailsRoot: (collectionKey, resourceKey) => `/v1/${environmentKey}/collections/${collectionKey}/resources/${resourceKey}/guardrails`,
1420
+ guardrailsReviewRoot: () => `/v1/${environmentKey}/guardrails/review`,
1421
+ guardrailsCatalogRoot: () => `/v1/${environmentKey}/guardrails/catalog`,
804
1422
  // Caller's own permissions
805
1423
  myPermissionsRoot: () => `/v1/${environmentKey}/permissions/me`,
806
1424
  // Management API key paths
@@ -845,6 +1463,177 @@ function hideSecret(response) {
845
1463
  }
846
1464
  return response;
847
1465
  }
1466
+ function isInteger(value) {
1467
+ return typeof value === "number" && Number.isSafeInteger(value);
1468
+ }
1469
+ function limitValues(limits, name) {
1470
+ for (const [key, value] of Object.entries(limits)) {
1471
+ if (value !== null && value !== void 0 && !isInteger(value)) {
1472
+ throw new Error(`${name}.${key} must be an integer or null`);
1473
+ }
1474
+ }
1475
+ return limits;
1476
+ }
1477
+ 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}))?)$/;
1478
+ var DAYS_IN_MONTH = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
1479
+ function isTimestampWithOffset(value) {
1480
+ const match = TIMESTAMP_WITH_OFFSET.exec(value);
1481
+ if (match === null) return false;
1482
+ const n = (i) => Number(match[i] ?? 0);
1483
+ const [year, month, day, hour, minute, second] = [1, 3, 4, 5, 7, 8].map(n);
1484
+ const fraction = match[9] ?? "";
1485
+ const leap = year % 4 === 0 && (year % 100 !== 0 || year % 400 === 0);
1486
+ if (year < 1 || month < 1 || month > 12) return false;
1487
+ const days = month === 2 && leap ? 29 : DAYS_IN_MONTH[month - 1];
1488
+ if (day < 1 || day > days) return false;
1489
+ if (hour === 24) {
1490
+ const lastDay = year === 9999 && month === 12 && day === 31;
1491
+ if (minute || second || /[1-9]/.test(fraction) || lastDay) return false;
1492
+ } else if (hour > 23 || minute > 59 || second > 59) {
1493
+ return false;
1494
+ }
1495
+ if (match[10] !== void 0 && (n(10) > 23 || n(11) > 59)) return false;
1496
+ return true;
1497
+ }
1498
+ function cutoff(value, name, allowNow) {
1499
+ if (value instanceof Date) {
1500
+ if (Number.isNaN(value.getTime())) {
1501
+ throw new Error(`${name} is an invalid Date`);
1502
+ }
1503
+ return value.toISOString();
1504
+ }
1505
+ if (typeof value !== "string") {
1506
+ throw new TypeError(`${name} must be a Date or a string`);
1507
+ }
1508
+ if (allowNow && value === "now") {
1509
+ return value;
1510
+ }
1511
+ if (!isTimestampWithOffset(value)) {
1512
+ const expected = allowNow ? '"now" or ' : "";
1513
+ throw new Error(`${name} must be ${expected}an ISO 8601 timestamp with a UTC offset`);
1514
+ }
1515
+ return value;
1516
+ }
1517
+ function signingKeyBody(request) {
1518
+ const hasPublic = request.public_key !== void 0;
1519
+ const generate = request.generate === true;
1520
+ if (hasPublic === generate) {
1521
+ throw new Error("Pass exactly one of public_key and generate: true");
1522
+ }
1523
+ const body = {
1524
+ parent_key: resolveKey(request.parent_key),
1525
+ anchor_collections: request.anchor_collections.map((c) => resolveKey(c)),
1526
+ apis: request.apis
1527
+ };
1528
+ if (hasPublic) {
1529
+ body.public_key = request.public_key;
1530
+ } else {
1531
+ body.generate = true;
1532
+ }
1533
+ if (request.collections !== void 0) {
1534
+ body.collections = request.collections.map((c) => resolveKey(c));
1535
+ }
1536
+ if (request.shared_read !== void 0) {
1537
+ body.shared_read = request.shared_read.map((c) => resolveKey(c));
1538
+ }
1539
+ for (const name of ["max_ttl_seconds", "max_anchors"]) {
1540
+ if (request[name] !== void 0) {
1541
+ if (!isInteger(request[name])) {
1542
+ throw new Error(`${name} must be an integer`);
1543
+ }
1544
+ body[name] = request[name];
1545
+ }
1546
+ }
1547
+ if (request.limits !== void 0) {
1548
+ body.limits = limitValues(request.limits, "limits");
1549
+ }
1550
+ if (request.description !== void 0) {
1551
+ body.description = request.description;
1552
+ }
1553
+ return body;
1554
+ }
1555
+ function signingKeyPatchBody(changes) {
1556
+ const body = {};
1557
+ if (changes.description !== void 0) {
1558
+ body.description = changes.description;
1559
+ }
1560
+ if (changes.limits !== void 0) {
1561
+ body.limits = changes.limits === null ? null : limitValues(changes.limits, "limits");
1562
+ }
1563
+ if (changes.not_before !== void 0) {
1564
+ body.not_before = cutoff(changes.not_before, "not_before", true);
1565
+ }
1566
+ if (Object.keys(body).length === 0) {
1567
+ throw new Error("Pass at least one of description, limits and not_before");
1568
+ }
1569
+ return body;
1570
+ }
1571
+ function revocationBody(entry) {
1572
+ if (entry.jti === void 0 === (entry.sub === void 0)) {
1573
+ throw new Error("Pass exactly one of jti and sub");
1574
+ }
1575
+ if (entry.jti !== void 0) {
1576
+ if (entry.before !== void 0) {
1577
+ throw new Error("before applies to a sub revocation only");
1578
+ }
1579
+ return { jti: entry.jti };
1580
+ }
1581
+ const body = { sub: entry.sub };
1582
+ if (entry.before !== void 0) {
1583
+ if (typeof entry.before === "string" && entry.before.trim().toLowerCase() === "now") {
1584
+ throw new Error("before must be a time; leave it out for 60 seconds from now");
1585
+ }
1586
+ body.before = cutoff(entry.before, "before", false);
1587
+ }
1588
+ return body;
1589
+ }
1590
+ var POLICY_FIELDS = new Set(GUARDRAILS_POLICY_FIELDS);
1591
+ function guardrailsPolicyBody(payload) {
1592
+ if (!payload || typeof payload !== "object" || Array.isArray(payload)) {
1593
+ throw new TypeError("payload must be an object");
1594
+ }
1595
+ const unknown = Object.keys(payload).filter((name) => !POLICY_FIELDS.has(name));
1596
+ if (unknown.length > 0) {
1597
+ throw new Error(`Unknown guardrails policy field(s): ${unknown.sort().join(", ")}`);
1598
+ }
1599
+ const body = {};
1600
+ for (const [name, value] of Object.entries(payload)) {
1601
+ if (value !== void 0) {
1602
+ body[name] = value;
1603
+ }
1604
+ }
1605
+ return body;
1606
+ }
1607
+ function heldItems(items) {
1608
+ const seen = /* @__PURE__ */ new Set();
1609
+ const result = items.map((item) => {
1610
+ const pair = Array.isArray(item) ? { resource_key: resolveKey(item[0]), revision_key: resolveKey(item[1]) } : {
1611
+ resource_key: item.resource_key,
1612
+ revision_key: item.revision_key
1613
+ };
1614
+ const id = `${pair.resource_key}\0${pair.revision_key}`;
1615
+ if (seen.has(id)) {
1616
+ throw new Error("Each held revision may appear once");
1617
+ }
1618
+ seen.add(id);
1619
+ return pair;
1620
+ });
1621
+ if (result.length < 1 || result.length > 50) {
1622
+ throw new Error("Pass 1 to 50 held revisions");
1623
+ }
1624
+ return result;
1625
+ }
1626
+ function hidePrivateKey(response) {
1627
+ if (response && typeof response === "object" && "private_key" in response) {
1628
+ Object.defineProperty(response, "private_key", {
1629
+ value: response.private_key,
1630
+ enumerable: false,
1631
+ writable: false,
1632
+ configurable: true
1633
+ });
1634
+ }
1635
+ return response;
1636
+ }
848
1637
  function webhookEndpointBody(request) {
849
1638
  const { collection_keys, ...rest } = request;
850
1639
  return collection_keys === void 0 ? rest : { ...rest, collection_keys: collection_keys.map((key) => resolveKey(key)) };
@@ -2243,6 +3032,192 @@ var ManagementClient = class {
2243
3032
  return this.request("GET", `${this.paths.myPermissionsRoot()}/`);
2244
3033
  }
2245
3034
  // ------------------------------------------------------------------ //
3035
+ // Tenant signing keys and tenant limits
3036
+ // ------------------------------------------------------------------ //
3037
+ /**
3038
+ * List the environment's tenant signing keys, revoked ones included, oldest first.
3039
+ * Keys the caller cannot read are left out. `params` carries `limit` and `offset`.
3040
+ */
3041
+ async listTenantSigningKeys(options) {
3042
+ const params = { ...options?.params };
3043
+ if (options?.parentKey !== void 0) {
3044
+ params.parent_key = resolveKey(options.parentKey);
3045
+ }
3046
+ return this.request("GET", `${this.paths.tenantSigningKeysRoot()}/`, { params });
3047
+ }
3048
+ /**
3049
+ * Register a tenant signing key, or have FoxNose generate the key pair.
3050
+ *
3051
+ * Send exactly one of `public_key` and `generate: true`. With `generate` the answer
3052
+ * carries `private_key` once (not enumerable; it is not stored). To keep the private
3053
+ * key on your side only, make the pair with {@link generateTenantSigningKey} and send
3054
+ * its `publicKey`. Never retried automatically.
3055
+ */
3056
+ async createTenantSigningKey(request) {
3057
+ const created = await this.transport.request("POST", `${this.paths.tenantSigningKeysRoot()}/`, {
3058
+ jsonBody: signingKeyBody(request),
3059
+ allowRetries: false
3060
+ });
3061
+ return hidePrivateKey(created);
3062
+ }
3063
+ /** Read one tenant signing key. */
3064
+ async getTenantSigningKey(kid) {
3065
+ return this.request("GET", `${this.paths.tenantSigningKeyRoot(kid)}/`);
3066
+ }
3067
+ /**
3068
+ * Change a signing key's label, per-key limits or cutoff for older tokens.
3069
+ *
3070
+ * `not_before: 'now'` means 60 seconds from now; an explicit time must be at least
3071
+ * that far ahead. Tokens with `iat` before it are refused. It only moves forward.
3072
+ */
3073
+ async updateTenantSigningKey(kid, changes) {
3074
+ return this.request("PATCH", `${this.paths.tenantSigningKeyRoot(kid)}/`, {
3075
+ jsonBody: signingKeyPatchBody(changes)
3076
+ });
3077
+ }
3078
+ /** Revoke a signing key. Repeating the call also succeeds. */
3079
+ async deleteTenantSigningKey(kid) {
3080
+ await this.request("DELETE", `${this.paths.tenantSigningKeyRoot(kid)}/`, {
3081
+ parseJson: false
3082
+ });
3083
+ }
3084
+ /**
3085
+ * Refuse one token (`jti`) or one end user's tokens (`sub`, those with `iat` at or
3086
+ * before `before`, 60 seconds from now by default). Send exactly one of `jti` and
3087
+ * `sub`. Neither value is stored, only its hash. Never retried automatically.
3088
+ */
3089
+ async addTenantTokenRevocation(kid, entry) {
3090
+ return this.transport.request("POST", `${this.paths.tenantSigningKeyRoot(kid)}/revocations/`, {
3091
+ jsonBody: revocationBody(entry),
3092
+ allowRetries: false
3093
+ });
3094
+ }
3095
+ /** Read the environment's tenant-token rate limits, with defaults and ceilings. */
3096
+ async getTenantLimits() {
3097
+ return this.request("GET", `${this.paths.tenantLimitsRoot()}/`);
3098
+ }
3099
+ /** Replace the environment's tenant-token rate limits. A field left out returns to its default. */
3100
+ async updateTenantLimits(limits) {
3101
+ return this.request("PUT", `${this.paths.tenantLimitsRoot()}/`, {
3102
+ jsonBody: limitValues(
3103
+ {
3104
+ rpm_per_subject: limits.rpm_per_subject ?? null,
3105
+ rpm_per_anchor: limits.rpm_per_anchor ?? null,
3106
+ uploads_per_subject_per_hour: limits.uploads_per_subject_per_hour ?? null
3107
+ },
3108
+ "limits"
3109
+ )
3110
+ });
3111
+ }
3112
+ // ------------------------------------------------------------------ //
3113
+ // Guardrails
3114
+ // ------------------------------------------------------------------ //
3115
+ /** Read a collection's guardrails policy. Without one, mode is `off` and `version` is `null`. */
3116
+ async getGuardrailsPolicy(collectionKey) {
3117
+ return this.request("GET", `${this.paths.guardrailsPolicyRoot(resolveKey(collectionKey))}/`);
3118
+ }
3119
+ /**
3120
+ * Replace a collection's guardrails policy with a new version. Only the fields that
3121
+ * are set are sent; a `mode` left out keeps the collection's mode. An unknown field
3122
+ * throws before anything is sent.
3123
+ */
3124
+ async updateGuardrailsPolicy(collectionKey, payload) {
3125
+ return this.request("PUT", `${this.paths.guardrailsPolicyRoot(resolveKey(collectionKey))}/`, {
3126
+ jsonBody: guardrailsPolicyBody(payload)
3127
+ });
3128
+ }
3129
+ /** List a collection's retained held revisions, newest first. `params` carries `limit` (at most 200) and `offset`. */
3130
+ async listHeldRevisions(collectionKey, options) {
3131
+ const params = { ...options?.params };
3132
+ if (options?.status !== void 0) {
3133
+ params.status = options.status;
3134
+ }
3135
+ return this.request("GET", `${this.paths.guardrailsHeldRoot(resolveKey(collectionKey))}/`, {
3136
+ params
3137
+ });
3138
+ }
3139
+ /** Publish a held revision; it is re-evaluated under the live policy first. Never retried automatically. */
3140
+ async releaseHeldRevision(collectionKey, resourceKey, revisionKey) {
3141
+ const root = this.paths.revisionGuardrailsRoot(
3142
+ resolveKey(collectionKey),
3143
+ resolveKey(resourceKey),
3144
+ resolveKey(revisionKey)
3145
+ );
3146
+ return this.transport.request("POST", `${root}/release/`, { allowRetries: false });
3147
+ }
3148
+ /** Reject a held revision; it is never published. `reason` is at most 500 characters. */
3149
+ async rejectHeldRevision(collectionKey, resourceKey, revisionKey, options) {
3150
+ const root = this.paths.revisionGuardrailsRoot(
3151
+ resolveKey(collectionKey),
3152
+ resolveKey(resourceKey),
3153
+ resolveKey(revisionKey)
3154
+ );
3155
+ return this.transport.request("POST", `${root}/reject/`, {
3156
+ jsonBody: options?.reason === void 0 ? void 0 : { reason: options.reason },
3157
+ allowRetries: false
3158
+ });
3159
+ }
3160
+ /** Reject up to 50 held revisions. Each item succeeds or fails on its own. */
3161
+ async rejectHeldRevisions(collectionKey, items, options) {
3162
+ const body = { items: heldItems(items) };
3163
+ if (options?.reason !== void 0) {
3164
+ body.reason = options.reason;
3165
+ }
3166
+ return this.transport.request(
3167
+ "POST",
3168
+ `${this.paths.guardrailsHeldRoot(resolveKey(collectionKey))}/reject/`,
3169
+ { jsonBody: body, allowRetries: false }
3170
+ );
3171
+ }
3172
+ /** Screen up to 50 held revisions again; each is published only if `clean`. */
3173
+ async rescreenHeldRevisions(collectionKey, items) {
3174
+ return this.transport.request(
3175
+ "POST",
3176
+ `${this.paths.guardrailsHeldRoot(resolveKey(collectionKey))}/rescreen/`,
3177
+ { jsonBody: { items: heldItems(items) }, allowRetries: false }
3178
+ );
3179
+ }
3180
+ /** Read a collection's review backlog and this hour's screening budget. */
3181
+ async getGuardrailsUsage(collectionKey) {
3182
+ return this.request("GET", `${this.paths.guardrailsUsageRoot(resolveKey(collectionKey))}/`);
3183
+ }
3184
+ /**
3185
+ * List what the environment holds for a person to review, newest first. `kind` is
3186
+ * `held` (the default) or `needs_review`; `status` applies to `held` only.
3187
+ * `params` carries `limit` (at most 100) and `offset`.
3188
+ */
3189
+ async listGuardrailsReviewQueue(options) {
3190
+ const params = { ...options?.params };
3191
+ if (options?.kind !== void 0) params.kind = options.kind;
3192
+ if (options?.collection !== void 0) params.collection = resolveKey(options.collection);
3193
+ if (options?.status !== void 0) params.status = options.status;
3194
+ return this.request("GET", `${this.paths.guardrailsReviewRoot()}/`, { params });
3195
+ }
3196
+ /** Read the team view of a revision: provenance, findings and review state. */
3197
+ async getRevisionGuardrails(collectionKey, resourceKey, revisionKey) {
3198
+ const root = this.paths.revisionGuardrailsRoot(
3199
+ resolveKey(collectionKey),
3200
+ resolveKey(resourceKey),
3201
+ resolveKey(revisionKey)
3202
+ );
3203
+ return this.request("GET", `${root}/`);
3204
+ }
3205
+ /**
3206
+ * Vouch for a record's published content: a revision with the same data is created
3207
+ * and published, with the caller as its origin. Never retried automatically.
3208
+ */
3209
+ async markResourceReviewed(collectionKey, resourceKey) {
3210
+ const root = this.paths.resourceGuardrailsRoot(
3211
+ resolveKey(collectionKey),
3212
+ resolveKey(resourceKey)
3213
+ );
3214
+ return this.transport.request("POST", `${root}/mark-reviewed/`, { allowRetries: false });
3215
+ }
3216
+ /** Read the wording the API uses for findings, states and writers. */
3217
+ async getGuardrailsCatalog() {
3218
+ return this.request("GET", `${this.paths.guardrailsCatalogRoot()}/`);
3219
+ }
3220
+ // ------------------------------------------------------------------ //
2246
3221
  // Webhooks
2247
3222
  // ------------------------------------------------------------------ //
2248
3223
  /**
@@ -2629,6 +3604,9 @@ var FluxClient = class {
2629
3604
  *
2630
3605
  * Writes are never retried automatically: a failed write's outcome is
2631
3606
  * unknown, so re-read with a GET before retrying.
3607
+ *
3608
+ * `options.provenance` declares untrusted fields for the collection's guardrails,
3609
+ * such as `{ untrusted_fields: ['body'], source: 'support-inbox' }`.
2632
3610
  */
2633
3611
  async createResource(folderPath, data, options) {
2634
3612
  const path = this.buildPath(folderPath, "/");
@@ -2636,6 +3614,9 @@ var FluxClient = class {
2636
3614
  if (options?.key !== void 0) {
2637
3615
  body.key = options.key;
2638
3616
  }
3617
+ if (options?.provenance !== void 0) {
3618
+ body.provenance = options.provenance;
3619
+ }
2639
3620
  return this.transport.request("POST", path, { jsonBody: body, allowRetries: false });
2640
3621
  }
2641
3622
  /**
@@ -2649,9 +3630,13 @@ var FluxClient = class {
2649
3630
  * raises {@link CollectionNotWritableError}. Like {@link createResource}, it
2650
3631
  * is never retried automatically.
2651
3632
  */
2652
- async updateResource(folderPath, resourceKey, data) {
3633
+ async updateResource(folderPath, resourceKey, data, options) {
2653
3634
  const path = this.buildPath(folderPath, `/${resourceKey}/`);
2654
- return this.transport.request("PUT", path, { jsonBody: { data }, allowRetries: false });
3635
+ const body = { data };
3636
+ if (options?.provenance !== void 0) {
3637
+ body.provenance = options.provenance;
3638
+ }
3639
+ return this.transport.request("PUT", path, { jsonBody: body, allowRetries: false });
2655
3640
  }
2656
3641
  /**
2657
3642
  * Get a grant for one upload to a files collection.
@@ -2833,6 +3818,164 @@ var FluxClient = class {
2833
3818
  this.transport.close();
2834
3819
  }
2835
3820
  };
3821
+
3822
+ // src/flux/trust.ts
3823
+ var RECORD_TRUST_SOURCE = "record_write";
3824
+ var FILE_TRUST_SOURCE = "end_user_upload";
3825
+ var FILE_VERDICTS = ["clean", "suspicious"];
3826
+ var PROVENANCE_STATES = ["recorded", "unknown"];
3827
+ var FILE_PROCESSING = ["agent_ready", "storage_only"];
3828
+ var FLAG_SCOPES = ["line", "page", "region"];
3829
+ var DEFAULT_FILE_BLOCK_KEY = "file";
3830
+ var MalformedTrustMetadataError = class extends Error {
3831
+ constructor(message) {
3832
+ super(message);
3833
+ this.name = "MalformedTrustMetadataError";
3834
+ }
3835
+ };
3836
+ function isObject2(value) {
3837
+ return value !== null && typeof value === "object" && !Array.isArray(value);
3838
+ }
3839
+ function isInt2(value) {
3840
+ return typeof value === "number" && Number.isSafeInteger(value);
3841
+ }
3842
+ function isStringArray(value) {
3843
+ return Array.isArray(value) && value.every((v) => typeof v === "string");
3844
+ }
3845
+ function isStringMap(value) {
3846
+ return isObject2(value) && Object.values(value).every((v) => typeof v === "string");
3847
+ }
3848
+ var TOP_LEVEL_POINTER = /^\/(?:[^/~]|~[01])*$/;
3849
+ function pointerField(pointer) {
3850
+ if (typeof pointer !== "string" || !TOP_LEVEL_POINTER.test(pointer)) {
3851
+ throw new MalformedTrustMetadataError("a tainted path is not a top-level JSON Pointer");
3852
+ }
3853
+ return pointer.slice(1).replace(/~1/g, "/").replace(/~0/g, "~");
3854
+ }
3855
+ function dottedField(path) {
3856
+ if (typeof path !== "string" || path.length === 0 || path.startsWith("/") || path.split(".").some((part) => part.length === 0)) {
3857
+ throw new MalformedTrustMetadataError("a files tainted path is not a dotted path");
3858
+ }
3859
+ return path.split(".")[0];
3860
+ }
3861
+ function optional(value, check) {
3862
+ return value === void 0 || value === null || check(value);
3863
+ }
3864
+ function isBox(value) {
3865
+ 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];
3866
+ }
3867
+ function isRegion(value) {
3868
+ return isObject2(value) && isInt2(value.page) && value.page >= 1 && typeof value.reason === "string" && Array.isArray(value.boxes) && value.boxes.every(isBox);
3869
+ }
3870
+ function isFlag(value) {
3871
+ if (!isRegion(value)) return false;
3872
+ const flag = value;
3873
+ return (flag.scope === null || FLAG_SCOPES.includes(flag.scope)) && Array.isArray(flag.lines) && flag.lines.every((line) => isInt2(line) && line >= 0);
3874
+ }
3875
+ function parseRecordTrust(value) {
3876
+ if (!isObject2(value)) {
3877
+ throw new MalformedTrustMetadataError("_sys.trust is not an object");
3878
+ }
3879
+ 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);
3880
+ const tainted = new Set(ok ? value.tainted_paths : []);
3881
+ const writers = ok ? Object.keys(value.writers) : [];
3882
+ 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)
3883
+ !(value.provenance === "unknown" && tainted.size > 0) && (!ok || Object.keys(value.sources).every((path) => tainted.has(path)));
3884
+ if (!ok || !consistent) {
3885
+ throw new MalformedTrustMetadataError("_sys.trust is malformed");
3886
+ }
3887
+ const trust = { ...value };
3888
+ for (const path of [
3889
+ ...trust.tainted_paths,
3890
+ ...Object.keys(trust.writers),
3891
+ ...Object.keys(trust.sources)
3892
+ ]) {
3893
+ pointerField(path);
3894
+ }
3895
+ return trust;
3896
+ }
3897
+ function parseFileTrust(value) {
3898
+ if (!isObject2(value)) {
3899
+ throw new MalformedTrustMetadataError("data.trust is not an object");
3900
+ }
3901
+ 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);
3902
+ if (!ok) {
3903
+ throw new MalformedTrustMetadataError("data.trust is malformed");
3904
+ }
3905
+ const trust = { ...value };
3906
+ for (const path of trust.tainted_paths) {
3907
+ dottedField(path);
3908
+ }
3909
+ return trust;
3910
+ }
3911
+ function isRecognizedRecordTrust(trust) {
3912
+ 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));
3913
+ }
3914
+ function isRecognizedFileTrust(trust) {
3915
+ return trust.version === 1 && trust.source === FILE_TRUST_SOURCE && FILE_VERDICTS.includes(trust.verdict) && FILE_PROCESSING.includes(trust.processing);
3916
+ }
3917
+ function getRecordTrust(record) {
3918
+ const sys = isObject2(record) ? record._sys : void 0;
3919
+ if (!isObject2(sys) || !("trust" in sys)) {
3920
+ return null;
3921
+ }
3922
+ return parseRecordTrust(sys.trust);
3923
+ }
3924
+ function fileBlocks(data) {
3925
+ return Object.entries(data).filter(
3926
+ ([key, value]) => isObject2(value) && "processing" in value && (key === DEFAULT_FILE_BLOCK_KEY || "uuid" in value && "tainted_paths" in value)
3927
+ ).map(([, value]) => value);
3928
+ }
3929
+ function boundBlock(data, upload) {
3930
+ if (typeof upload !== "string" || upload.length === 0) return void 0;
3931
+ const found = Object.entries(data).find(
3932
+ ([key, value]) => key !== "trust" && isObject2(value) && "processing" in value && value.uuid === upload
3933
+ );
3934
+ return found?.[1];
3935
+ }
3936
+ function isFilesData(data) {
3937
+ const trust = data.trust;
3938
+ return isObject2(trust) && trust.source === FILE_TRUST_SOURCE || fileBlocks(data).length > 0 || isObject2(trust) && boundBlock(data, trust.upload) !== void 0;
3939
+ }
3940
+ function getFileTrust(record) {
3941
+ const data = isObject2(record) ? record.data : void 0;
3942
+ if (!isObject2(data) || !isFilesData(data)) {
3943
+ return null;
3944
+ }
3945
+ if (!("trust" in data)) {
3946
+ throw new MalformedTrustMetadataError("a files record has no data.trust");
3947
+ }
3948
+ const trust = parseFileTrust(data.trust);
3949
+ const block = boundBlock(data, trust.upload);
3950
+ if (block === void 0) {
3951
+ throw new MalformedTrustMetadataError("data.trust.upload is not a file block's uuid");
3952
+ }
3953
+ if (FILE_PROCESSING.includes(trust.processing) && block.processing === "agent_ready" !== (trust.processing === "agent_ready")) {
3954
+ throw new MalformedTrustMetadataError("data.trust.processing disagrees with the file block");
3955
+ }
3956
+ return trust;
3957
+ }
3958
+ function getUntrustedFields(record) {
3959
+ const data = isObject2(record) && isObject2(record.data) ? record.data : {};
3960
+ const fields = /* @__PURE__ */ new Set();
3961
+ const recordTrust = getRecordTrust(record);
3962
+ const fileTrust = getFileTrust(record);
3963
+ if (recordTrust) {
3964
+ const tainted = recordTrust.tainted_paths.map(pointerField);
3965
+ if (!isRecognizedRecordTrust(recordTrust)) {
3966
+ return Object.keys(data).sort();
3967
+ }
3968
+ tainted.forEach((f) => fields.add(f));
3969
+ }
3970
+ if (fileTrust) {
3971
+ const tainted = fileTrust.tainted_paths.map(dottedField);
3972
+ if (!isRecognizedFileTrust(fileTrust)) {
3973
+ return Object.keys(data).sort();
3974
+ }
3975
+ tainted.forEach((f) => fields.add(f));
3976
+ }
3977
+ return [...fields].sort();
3978
+ }
2836
3979
  // Annotate the CommonJS export names for ESM import in node:
2837
3980
  0 && (module.exports = {
2838
3981
  AnonymousAuth,
@@ -2848,8 +3991,10 @@ var FluxClient = class {
2848
3991
  FoxnoseAuthError,
2849
3992
  FoxnoseError,
2850
3993
  FoxnoseTransportError,
3994
+ GUARDRAILS_POLICY_FIELDS,
2851
3995
  HttpTransport,
2852
3996
  JWTAuth,
3997
+ MalformedTrustMetadataError,
2853
3998
  ManagementClient,
2854
3999
  PlanExhaustedError,
2855
4000
  PlanLimitExceededError,
@@ -2860,6 +4005,9 @@ var FluxClient = class {
2860
4005
  SimpleKeyAuth,
2861
4006
  SpendCapExceededError,
2862
4007
  StaticTokenProvider,
4008
+ TENANT_TOKEN_PREFIX,
4009
+ TenantTokenAuth,
4010
+ TenantTokenSource,
2863
4011
  UpstreamError,
2864
4012
  VERSION,
2865
4013
  WebhookEndpointLimitExceededError,
@@ -2867,10 +4015,22 @@ var FluxClient = class {
2867
4015
  WebhookEndpointNotFoundError,
2868
4016
  WebhookEndpointNotSubscribedError,
2869
4017
  WebhookEventNotFoundError,
4018
+ bearerErrors,
2870
4019
  buildSearchBody,
2871
4020
  createConfig,
4021
+ generateTenantSigningKey,
4022
+ getFileTrust,
4023
+ getRecordTrust,
4024
+ getResourceGuardrailsSummary,
4025
+ getRevisionGuardrailsSummary,
4026
+ getUntrustedFields,
4027
+ isInvalidTokenChallenge,
4028
+ isRecognizedFileTrust,
4029
+ isRecognizedRecordTrust,
2872
4030
  nestedFieldMeta,
2873
4031
  parseFindingEvidence,
2874
- resolveKey
4032
+ resolveKey,
4033
+ signTenantToken,
4034
+ tenantTokenFetch
2875
4035
  });
2876
4036
  //# sourceMappingURL=index.cjs.map