@foxnose/sdk 0.7.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 +163 -0
- package/dist/index.cjs +1423 -13
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1034 -4
- package/dist/index.d.ts +1034 -4
- package/dist/index.js +1405 -12
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -180,6 +180,45 @@ var UpstreamError = class extends FoxnoseAPIError {
|
|
|
180
180
|
this.name = "UpstreamError";
|
|
181
181
|
}
|
|
182
182
|
};
|
|
183
|
+
var WebhookEndpointNotFoundError = class extends FoxnoseAPIError {
|
|
184
|
+
constructor(options) {
|
|
185
|
+
super(options);
|
|
186
|
+
this.name = "WebhookEndpointNotFoundError";
|
|
187
|
+
}
|
|
188
|
+
};
|
|
189
|
+
var WebhookEventNotFoundError = class extends FoxnoseAPIError {
|
|
190
|
+
constructor(options) {
|
|
191
|
+
super(options);
|
|
192
|
+
this.name = "WebhookEventNotFoundError";
|
|
193
|
+
}
|
|
194
|
+
};
|
|
195
|
+
var WebhookEndpointLimitExceededError = class extends FoxnoseAPIError {
|
|
196
|
+
constructor(options) {
|
|
197
|
+
super(options);
|
|
198
|
+
this.name = "WebhookEndpointLimitExceededError";
|
|
199
|
+
}
|
|
200
|
+
};
|
|
201
|
+
var WebhookEndpointNotActiveError = class extends FoxnoseAPIError {
|
|
202
|
+
/** The endpoint's state (`paused`, `disabled` or `deleted`) when the call named it. */
|
|
203
|
+
reason;
|
|
204
|
+
/** Endpoints a redelivery without `endpoint_id` passed over, each with `endpoint_id` and `reason`. */
|
|
205
|
+
skipped;
|
|
206
|
+
constructor(options) {
|
|
207
|
+
super(options);
|
|
208
|
+
this.name = "WebhookEndpointNotActiveError";
|
|
209
|
+
this.reason = options.reason;
|
|
210
|
+
this.skipped = options.skipped ?? [];
|
|
211
|
+
}
|
|
212
|
+
};
|
|
213
|
+
var WebhookEndpointNotSubscribedError = class extends FoxnoseAPIError {
|
|
214
|
+
/** Endpoints a redelivery without `endpoint_id` passed over, each with `endpoint_id` and `reason`. */
|
|
215
|
+
skipped;
|
|
216
|
+
constructor(options) {
|
|
217
|
+
super(options);
|
|
218
|
+
this.name = "WebhookEndpointNotSubscribedError";
|
|
219
|
+
this.skipped = options.skipped ?? [];
|
|
220
|
+
}
|
|
221
|
+
};
|
|
183
222
|
function isPlainObject(value) {
|
|
184
223
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
185
224
|
}
|
|
@@ -276,6 +315,30 @@ function buildAPIError(options) {
|
|
|
276
315
|
errorsTruncated: d.errors_truncated === true
|
|
277
316
|
});
|
|
278
317
|
}
|
|
318
|
+
if (statusCode === 404 && errorCode === "webhook_endpoint_not_found") {
|
|
319
|
+
return new WebhookEndpointNotFoundError(options);
|
|
320
|
+
}
|
|
321
|
+
if (statusCode === 404 && errorCode === "webhook_event_not_found") {
|
|
322
|
+
return new WebhookEventNotFoundError(options);
|
|
323
|
+
}
|
|
324
|
+
if (statusCode === 409 && errorCode === "limit_exceeded") {
|
|
325
|
+
return new WebhookEndpointLimitExceededError(options);
|
|
326
|
+
}
|
|
327
|
+
if (statusCode === 409 && errorCode === "endpoint_not_active") {
|
|
328
|
+
const d = isPlainObject(detail) ? detail : {};
|
|
329
|
+
return new WebhookEndpointNotActiveError({
|
|
330
|
+
...options,
|
|
331
|
+
reason: typeof d.reason === "string" ? d.reason : void 0,
|
|
332
|
+
skipped: Array.isArray(d.skipped) ? d.skipped : void 0
|
|
333
|
+
});
|
|
334
|
+
}
|
|
335
|
+
if (statusCode === 409 && errorCode === "endpoint_not_subscribed") {
|
|
336
|
+
const d = isPlainObject(detail) ? detail : {};
|
|
337
|
+
return new WebhookEndpointNotSubscribedError({
|
|
338
|
+
...options,
|
|
339
|
+
skipped: Array.isArray(d.skipped) ? d.skipped : void 0
|
|
340
|
+
});
|
|
341
|
+
}
|
|
279
342
|
if (statusCode === 502 && errorCode === "upstream_error") {
|
|
280
343
|
return new UpstreamError(options);
|
|
281
344
|
}
|
|
@@ -358,6 +421,476 @@ var SimpleKeyAuth = class {
|
|
|
358
421
|
}
|
|
359
422
|
};
|
|
360
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
|
+
|
|
361
894
|
// src/config.ts
|
|
362
895
|
var DEFAULT_RETRY_CONFIG = {
|
|
363
896
|
attempts: 3,
|
|
@@ -365,7 +898,7 @@ var DEFAULT_RETRY_CONFIG = {
|
|
|
365
898
|
statusCodes: [408, 425, 429, 500, 502, 503, 504],
|
|
366
899
|
methods: ["GET", "HEAD", "OPTIONS", "PUT", "DELETE"]
|
|
367
900
|
};
|
|
368
|
-
var SDK_VERSION = "0.
|
|
901
|
+
var SDK_VERSION = "0.9.0";
|
|
369
902
|
var DEFAULT_USER_AGENT = `foxnose-sdk-js/${SDK_VERSION}`;
|
|
370
903
|
function createConfig(options) {
|
|
371
904
|
if (!options.baseUrl) {
|
|
@@ -495,23 +1028,32 @@ var HttpTransport = class {
|
|
|
495
1028
|
}
|
|
496
1029
|
async sendWithRetries(method, path, options) {
|
|
497
1030
|
const allowRetries = options?.allowRetries !== false;
|
|
1031
|
+
let replayed = false;
|
|
498
1032
|
for (let attempt = 1; attempt <= this.retry.attempts; attempt++) {
|
|
499
|
-
const
|
|
500
|
-
const controller = new AbortController();
|
|
501
|
-
const timeoutId = setTimeout(() => controller.abort(), this.config.timeout);
|
|
502
|
-
init.signal = controller.signal;
|
|
1033
|
+
const request = this.buildRequest(method, path, options);
|
|
503
1034
|
let response;
|
|
504
1035
|
try {
|
|
505
|
-
response = await
|
|
1036
|
+
response = await this.send(request);
|
|
506
1037
|
} catch (err) {
|
|
507
|
-
clearTimeout(timeoutId);
|
|
508
1038
|
const delay = this.handleTransportError(err, method, attempt, !allowRetries);
|
|
509
1039
|
if (delay > 0) {
|
|
510
1040
|
await this.sleep(delay);
|
|
511
1041
|
}
|
|
512
1042
|
continue;
|
|
513
|
-
}
|
|
514
|
-
|
|
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
|
+
}
|
|
515
1057
|
}
|
|
516
1058
|
if (response.status >= 400) {
|
|
517
1059
|
if (allowRetries && this.shouldRetry(method, response.status) && attempt < this.retry.attempts) {
|
|
@@ -527,6 +1069,33 @@ var HttpTransport = class {
|
|
|
527
1069
|
}
|
|
528
1070
|
throw new FoxnoseTransportError("All retry attempts exhausted");
|
|
529
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
|
+
}
|
|
530
1099
|
handleTransportError(err, method, attempt, forbidRetry = false) {
|
|
531
1100
|
const canRetry = !forbidRetry && this.retry.methods.includes(method.toUpperCase()) && attempt < this.retry.attempts;
|
|
532
1101
|
if (!canRetry) {
|
|
@@ -635,6 +1204,94 @@ function resolveKey(value) {
|
|
|
635
1204
|
}
|
|
636
1205
|
throw new TypeError(`Expected a string or an object with a 'key' attribute, got ${typeof value}`);
|
|
637
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
|
+
];
|
|
638
1295
|
|
|
639
1296
|
// src/management/paths.ts
|
|
640
1297
|
function managementPaths(environmentKey) {
|
|
@@ -672,6 +1329,22 @@ function managementPaths(environmentKey) {
|
|
|
672
1329
|
fileTombstonesRoot: (collectionKey) => `/v1/${environmentKey}/collections/${collectionKey}/files/tombstones`,
|
|
673
1330
|
filesPolicyRoot: (collectionKey) => `/v1/${environmentKey}/collections/${collectionKey}/files-policy`,
|
|
674
1331
|
filesReviewRoot: () => `/v1/${environmentKey}/files/review`,
|
|
1332
|
+
// Webhooks paths
|
|
1333
|
+
webhooksRoot: () => `/v1/${environmentKey}/webhooks`,
|
|
1334
|
+
webhookEndpointRoot: (endpointId) => `/v1/${environmentKey}/webhooks/endpoints/${encodeURIComponent(endpointId)}`,
|
|
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`,
|
|
675
1348
|
// Caller's own permissions
|
|
676
1349
|
myPermissionsRoot: () => `/v1/${environmentKey}/permissions/me`,
|
|
677
1350
|
// Management API key paths
|
|
@@ -705,6 +1378,192 @@ function managementPaths(environmentKey) {
|
|
|
705
1378
|
}
|
|
706
1379
|
|
|
707
1380
|
// src/management/client.ts
|
|
1381
|
+
function hideSecret(response) {
|
|
1382
|
+
if (response && typeof response === "object" && "secret" in response) {
|
|
1383
|
+
Object.defineProperty(response, "secret", {
|
|
1384
|
+
value: response.secret,
|
|
1385
|
+
enumerable: false,
|
|
1386
|
+
writable: false,
|
|
1387
|
+
configurable: true
|
|
1388
|
+
});
|
|
1389
|
+
}
|
|
1390
|
+
return response;
|
|
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
|
+
}
|
|
1563
|
+
function webhookEndpointBody(request) {
|
|
1564
|
+
const { collection_keys, ...rest } = request;
|
|
1565
|
+
return collection_keys === void 0 ? rest : { ...rest, collection_keys: collection_keys.map((key) => resolveKey(key)) };
|
|
1566
|
+
}
|
|
708
1567
|
var ManagementClient = class {
|
|
709
1568
|
environmentKey;
|
|
710
1569
|
transport;
|
|
@@ -2098,6 +2957,350 @@ var ManagementClient = class {
|
|
|
2098
2957
|
async getMyPermissions() {
|
|
2099
2958
|
return this.request("GET", `${this.paths.myPermissionsRoot()}/`);
|
|
2100
2959
|
}
|
|
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
|
+
// ------------------------------------------------------------------ //
|
|
3147
|
+
// Webhooks
|
|
3148
|
+
// ------------------------------------------------------------------ //
|
|
3149
|
+
/**
|
|
3150
|
+
* List the environment's webhook endpoints, newest first. Each item carries
|
|
3151
|
+
* `stats_24h`; secrets are never included. `params` carries `status` (`active`,
|
|
3152
|
+
* `paused` or `disabled`), `limit` (at most 200) and `offset`.
|
|
3153
|
+
*/
|
|
3154
|
+
async listWebhookEndpoints(params) {
|
|
3155
|
+
return this.request("GET", `${this.paths.webhooksRoot()}/endpoints/`, { params });
|
|
3156
|
+
}
|
|
3157
|
+
/**
|
|
3158
|
+
* Create a webhook endpoint.
|
|
3159
|
+
*
|
|
3160
|
+
* The answer carries the signing `secret`, which is not enumerable: read it as
|
|
3161
|
+
* `created.secret`, and read it again later with {@link getWebhookEndpointSecret}.
|
|
3162
|
+
* An environment holds at most 20 endpoints ({@link WebhookEndpointLimitExceededError}).
|
|
3163
|
+
* A `content` endpoint also needs read access to the content it will deliver.
|
|
3164
|
+
*/
|
|
3165
|
+
async createWebhookEndpoint(request) {
|
|
3166
|
+
const created = await this.transport.request(
|
|
3167
|
+
"POST",
|
|
3168
|
+
`${this.paths.webhooksRoot()}/endpoints/`,
|
|
3169
|
+
{
|
|
3170
|
+
jsonBody: webhookEndpointBody(request),
|
|
3171
|
+
allowRetries: false
|
|
3172
|
+
}
|
|
3173
|
+
);
|
|
3174
|
+
return hideSecret(created);
|
|
3175
|
+
}
|
|
3176
|
+
/** Read one webhook endpoint. It carries neither the secret nor `stats_24h`. */
|
|
3177
|
+
async getWebhookEndpoint(endpointId) {
|
|
3178
|
+
return this.request("GET", `${this.paths.webhookEndpointRoot(endpointId)}/`);
|
|
3179
|
+
}
|
|
3180
|
+
/**
|
|
3181
|
+
* Change the given fields of an endpoint and leave the rest alone.
|
|
3182
|
+
*
|
|
3183
|
+
* `status: 'active'` resumes a paused or disabled endpoint and clears its failure
|
|
3184
|
+
* streak; events that happened meanwhile are not sent, but failed deliveries can be
|
|
3185
|
+
* sent again with {@link recoverWebhookDeliveries}.
|
|
3186
|
+
*/
|
|
3187
|
+
async updateWebhookEndpoint(endpointId, changes) {
|
|
3188
|
+
return this.request("PATCH", `${this.paths.webhookEndpointRoot(endpointId)}/`, {
|
|
3189
|
+
jsonBody: webhookEndpointBody(changes)
|
|
3190
|
+
});
|
|
3191
|
+
}
|
|
3192
|
+
/**
|
|
3193
|
+
* Delete an endpoint and its pending deliveries. Its finished deliveries and
|
|
3194
|
+
* attempts stay in the event log for 30 days, with `endpoint.deleted` true.
|
|
3195
|
+
*/
|
|
3196
|
+
async deleteWebhookEndpoint(endpointId) {
|
|
3197
|
+
await this.request("DELETE", `${this.paths.webhookEndpointRoot(endpointId)}/`, {
|
|
3198
|
+
parseJson: false
|
|
3199
|
+
});
|
|
3200
|
+
}
|
|
3201
|
+
/**
|
|
3202
|
+
* List an endpoint's deliveries, newest first, each with the event it carries.
|
|
3203
|
+
* `params` carries `limit` (at most 200) and `offset`.
|
|
3204
|
+
*/
|
|
3205
|
+
async listWebhookEndpointDeliveries(endpointId, params) {
|
|
3206
|
+
return this.request("GET", `${this.paths.webhookEndpointRoot(endpointId)}/deliveries/`, {
|
|
3207
|
+
params
|
|
3208
|
+
});
|
|
3209
|
+
}
|
|
3210
|
+
/**
|
|
3211
|
+
* Read the endpoint's current signing secret: the newest, during a rotation. Needs
|
|
3212
|
+
* `webhooks:update`. `secret` is not enumerable: read it as `response.secret`.
|
|
3213
|
+
*/
|
|
3214
|
+
async getWebhookEndpointSecret(endpointId) {
|
|
3215
|
+
const response = await this.request(
|
|
3216
|
+
"GET",
|
|
3217
|
+
`${this.paths.webhookEndpointRoot(endpointId)}/secret/`
|
|
3218
|
+
);
|
|
3219
|
+
return hideSecret(response);
|
|
3220
|
+
}
|
|
3221
|
+
/**
|
|
3222
|
+
* Create a new signing secret and return it.
|
|
3223
|
+
*
|
|
3224
|
+
* The previous secret stays valid for 24 hours, and deliveries carry a signature for
|
|
3225
|
+
* each valid secret; with `expire_previous_now` it stops at once. Needs
|
|
3226
|
+
* `webhooks:update`. `secret` is not enumerable: read it as `rotation.secret`.
|
|
3227
|
+
*/
|
|
3228
|
+
async rotateWebhookEndpointSecret(endpointId, options) {
|
|
3229
|
+
const response = await this.transport.request(
|
|
3230
|
+
"POST",
|
|
3231
|
+
`${this.paths.webhookEndpointRoot(endpointId)}/secret/rotate/`,
|
|
3232
|
+
{
|
|
3233
|
+
jsonBody: { expire_previous_now: options?.expire_previous_now ?? false },
|
|
3234
|
+
allowRetries: false
|
|
3235
|
+
}
|
|
3236
|
+
);
|
|
3237
|
+
return hideSecret(response);
|
|
3238
|
+
}
|
|
3239
|
+
/**
|
|
3240
|
+
* Send a sample event of `eventType` to this endpoint only, with `test` true in the
|
|
3241
|
+
* envelope. It is sent whatever the endpoint's event types and collection filter,
|
|
3242
|
+
* but the endpoint must be active ({@link WebhookEndpointNotActiveError}).
|
|
3243
|
+
*/
|
|
3244
|
+
async sendWebhookTestEvent(endpointId, eventType) {
|
|
3245
|
+
return this.transport.request("POST", `${this.paths.webhookEndpointRoot(endpointId)}/test/`, {
|
|
3246
|
+
jsonBody: { event_type: eventType },
|
|
3247
|
+
allowRetries: false
|
|
3248
|
+
});
|
|
3249
|
+
}
|
|
3250
|
+
/**
|
|
3251
|
+
* Send again the endpoint's failed deliveries created at or after `since`.
|
|
3252
|
+
*
|
|
3253
|
+
* Each becomes a new pending delivery of the same event. One call queues at most
|
|
3254
|
+
* 10,000 deliveries; when `more` is true, call again with the same `since`. `since`
|
|
3255
|
+
* is an ISO 8601 time within the last 30 days; a time without a zone is read as UTC.
|
|
3256
|
+
*/
|
|
3257
|
+
async recoverWebhookDeliveries(endpointId, since) {
|
|
3258
|
+
return this.transport.request(
|
|
3259
|
+
"POST",
|
|
3260
|
+
`${this.paths.webhookEndpointRoot(endpointId)}/recover/`,
|
|
3261
|
+
{
|
|
3262
|
+
jsonBody: { since: since instanceof Date ? since.toISOString() : since },
|
|
3263
|
+
allowRetries: false
|
|
3264
|
+
}
|
|
3265
|
+
);
|
|
3266
|
+
}
|
|
3267
|
+
/**
|
|
3268
|
+
* List the events of the last 30 days, newest first, with `delivery_counts`.
|
|
3269
|
+
* `params` carries `type`, `endpoint` (an endpoint `id`), `status` (`pending`,
|
|
3270
|
+
* `succeeded` or `dead`), `test`, `after`, `before` (ISO 8601), `limit` (at most 200)
|
|
3271
|
+
* and `offset`.
|
|
3272
|
+
*/
|
|
3273
|
+
async listWebhookEvents(params) {
|
|
3274
|
+
return this.request("GET", `${this.paths.webhooksRoot()}/events/`, { params });
|
|
3275
|
+
}
|
|
3276
|
+
/** Read one event with its envelope and all its deliveries, oldest first. */
|
|
3277
|
+
async getWebhookEvent(eventId) {
|
|
3278
|
+
return this.request("GET", `${this.paths.webhookEventRoot(eventId)}/`);
|
|
3279
|
+
}
|
|
3280
|
+
/**
|
|
3281
|
+
* List every attempt to deliver the event, across endpoints, oldest first. `params`
|
|
3282
|
+
* carries `limit` (at most 200) and `offset`.
|
|
3283
|
+
*/
|
|
3284
|
+
async listWebhookEventAttempts(eventId, params) {
|
|
3285
|
+
return this.request("GET", `${this.paths.webhookEventRoot(eventId)}/attempts/`, { params });
|
|
3286
|
+
}
|
|
3287
|
+
/**
|
|
3288
|
+
* Send the event again as a new delivery, with the same event `id`.
|
|
3289
|
+
*
|
|
3290
|
+
* With `endpoint_id` the event goes to that endpoint. Without it, the event goes to
|
|
3291
|
+
* every endpoint that had a delivery of it and is active and subscribed to it now;
|
|
3292
|
+
* the others are listed in `skipped`.
|
|
3293
|
+
*/
|
|
3294
|
+
async redeliverWebhookEvent(eventId, options) {
|
|
3295
|
+
return this.transport.request("POST", `${this.paths.webhookEventRoot(eventId)}/redeliver/`, {
|
|
3296
|
+
jsonBody: options?.endpoint_id !== void 0 ? { endpoint_id: options.endpoint_id } : {},
|
|
3297
|
+
allowRetries: false
|
|
3298
|
+
});
|
|
3299
|
+
}
|
|
3300
|
+
/** List the event-type catalogue with the JSON Schema of each payload mode. */
|
|
3301
|
+
async listWebhookEventTypes() {
|
|
3302
|
+
return this.request("GET", `${this.paths.webhooksRoot()}/event-types/`);
|
|
3303
|
+
}
|
|
2101
3304
|
fileRoot(collectionKey, resourceKey) {
|
|
2102
3305
|
return this.paths.fileRoot(resolveKey(collectionKey), resolveKey(resourceKey));
|
|
2103
3306
|
}
|
|
@@ -2327,6 +3530,9 @@ var FluxClient = class {
|
|
|
2327
3530
|
*
|
|
2328
3531
|
* Writes are never retried automatically: a failed write's outcome is
|
|
2329
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' }`.
|
|
2330
3536
|
*/
|
|
2331
3537
|
async createResource(folderPath, data, options) {
|
|
2332
3538
|
const path = this.buildPath(folderPath, "/");
|
|
@@ -2334,6 +3540,9 @@ var FluxClient = class {
|
|
|
2334
3540
|
if (options?.key !== void 0) {
|
|
2335
3541
|
body.key = options.key;
|
|
2336
3542
|
}
|
|
3543
|
+
if (options?.provenance !== void 0) {
|
|
3544
|
+
body.provenance = options.provenance;
|
|
3545
|
+
}
|
|
2337
3546
|
return this.transport.request("POST", path, { jsonBody: body, allowRetries: false });
|
|
2338
3547
|
}
|
|
2339
3548
|
/**
|
|
@@ -2347,9 +3556,13 @@ var FluxClient = class {
|
|
|
2347
3556
|
* raises {@link CollectionNotWritableError}. Like {@link createResource}, it
|
|
2348
3557
|
* is never retried automatically.
|
|
2349
3558
|
*/
|
|
2350
|
-
async updateResource(folderPath, resourceKey, data) {
|
|
3559
|
+
async updateResource(folderPath, resourceKey, data, options) {
|
|
2351
3560
|
const path = this.buildPath(folderPath, `/${resourceKey}/`);
|
|
2352
|
-
|
|
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 });
|
|
2353
3566
|
}
|
|
2354
3567
|
/**
|
|
2355
3568
|
* Get a grant for one upload to a files collection.
|
|
@@ -2531,6 +3744,164 @@ var FluxClient = class {
|
|
|
2531
3744
|
this.transport.close();
|
|
2532
3745
|
}
|
|
2533
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
|
+
}
|
|
2534
3905
|
export {
|
|
2535
3906
|
AnonymousAuth,
|
|
2536
3907
|
CollectionNotWritableError,
|
|
@@ -2545,8 +3916,10 @@ export {
|
|
|
2545
3916
|
FoxnoseAuthError,
|
|
2546
3917
|
FoxnoseError,
|
|
2547
3918
|
FoxnoseTransportError,
|
|
3919
|
+
GUARDRAILS_POLICY_FIELDS,
|
|
2548
3920
|
HttpTransport,
|
|
2549
3921
|
JWTAuth,
|
|
3922
|
+
MalformedTrustMetadataError,
|
|
2550
3923
|
ManagementClient,
|
|
2551
3924
|
PlanExhaustedError,
|
|
2552
3925
|
PlanLimitExceededError,
|
|
@@ -2557,12 +3930,32 @@ export {
|
|
|
2557
3930
|
SimpleKeyAuth,
|
|
2558
3931
|
SpendCapExceededError,
|
|
2559
3932
|
StaticTokenProvider,
|
|
3933
|
+
TENANT_TOKEN_PREFIX,
|
|
3934
|
+
TenantTokenAuth,
|
|
3935
|
+
TenantTokenSource,
|
|
2560
3936
|
UpstreamError,
|
|
2561
3937
|
SDK_VERSION as VERSION,
|
|
3938
|
+
WebhookEndpointLimitExceededError,
|
|
3939
|
+
WebhookEndpointNotActiveError,
|
|
3940
|
+
WebhookEndpointNotFoundError,
|
|
3941
|
+
WebhookEndpointNotSubscribedError,
|
|
3942
|
+
WebhookEventNotFoundError,
|
|
3943
|
+
bearerErrors,
|
|
2562
3944
|
buildSearchBody,
|
|
2563
3945
|
createConfig,
|
|
3946
|
+
generateTenantSigningKey,
|
|
3947
|
+
getFileTrust,
|
|
3948
|
+
getRecordTrust,
|
|
3949
|
+
getResourceGuardrailsSummary,
|
|
3950
|
+
getRevisionGuardrailsSummary,
|
|
3951
|
+
getUntrustedFields,
|
|
3952
|
+
isInvalidTokenChallenge,
|
|
3953
|
+
isRecognizedFileTrust,
|
|
3954
|
+
isRecognizedRecordTrust,
|
|
2564
3955
|
nestedFieldMeta,
|
|
2565
3956
|
parseFindingEvidence,
|
|
2566
|
-
resolveKey
|
|
3957
|
+
resolveKey,
|
|
3958
|
+
signTenantToken,
|
|
3959
|
+
tenantTokenFetch
|
|
2567
3960
|
};
|
|
2568
3961
|
//# sourceMappingURL=index.js.map
|