verdifax 1.3.0 → 1.5.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.js CHANGED
@@ -31,9 +31,11 @@ __export(index_exports, {
31
31
  MAX_BATCH_ROWS: () => MAX_BATCH_ROWS,
32
32
  NotFoundError: () => NotFoundError,
33
33
  RUN_STATUSES: () => RUN_STATUSES,
34
+ SignalFeedError: () => SignalFeedError,
34
35
  VerdifaxClient: () => VerdifaxClient,
35
36
  VerdifaxError: () => VerdifaxError,
36
37
  VerdifaxJob: () => VerdifaxJob,
38
+ approverKeyProof: () => approverKeyProof,
37
39
  captureEnvironment: () => captureEnvironment,
38
40
  cresReceiptHash: () => cresReceiptHash,
39
41
  dcaeClosureHash: () => dcaeClosureHash,
@@ -48,11 +50,14 @@ __export(index_exports, {
48
50
  requestKeyRegistrationBody: () => requestKeyRegistrationBody,
49
51
  requestSignaturePreimage: () => requestSignaturePreimage,
50
52
  requestSignaturePreimageV2: () => requestSignaturePreimageV2,
53
+ signOffPreimage: () => signOffPreimage,
51
54
  signRequest: () => signRequest,
52
55
  signRequestV2: () => signRequestV2,
56
+ signalEventHash: () => signalEventHash,
53
57
  validateHex64: () => validateHex64,
54
58
  validateJobName: () => validateJobName,
55
- validateRouteId: () => validateRouteId
59
+ validateRouteId: () => validateRouteId,
60
+ verifyWebhook: () => verifyWebhook
56
61
  });
57
62
  module.exports = __toCommonJS(index_exports);
58
63
 
@@ -106,6 +111,17 @@ var APIKeyRequiredError = class extends VerdifaxError {
106
111
  super("verdifax: apiKey is required for this endpoint");
107
112
  }
108
113
  };
114
+ var SignalFeedError = class extends VerdifaxError {
115
+ constructor(lastSequence, reason, options) {
116
+ super(
117
+ `verdifax: the signal feed stopped after sequence ${lastSequence}: ${reason}; follow again with after: ${lastSequence}`,
118
+ options
119
+ );
120
+ this.lastSequence = lastSequence;
121
+ }
122
+ lastSequence;
123
+ name = "VerdifaxSignalFeedError";
124
+ };
109
125
 
110
126
  // src/signing.ts
111
127
  var import_node_crypto = require("crypto");
@@ -145,6 +161,18 @@ function validateJobName(value, fieldName) {
145
161
  );
146
162
  }
147
163
  }
164
+ function requirePositiveId(id, name) {
165
+ if (!Number.isSafeInteger(id) || id <= 0) {
166
+ throw new VerdifaxError(`verdifax: ${name} must be a whole number > 0`);
167
+ }
168
+ }
169
+ function asOwnerOf(options, method) {
170
+ const asOwner = options?.asOwner;
171
+ if (asOwner !== void 0 && typeof asOwner !== "boolean") {
172
+ throw new VerdifaxError(`verdifax: ${method} asOwner must be true or false`);
173
+ }
174
+ return asOwner === true;
175
+ }
148
176
 
149
177
  // src/helpers.ts
150
178
  function formatProviderPayload(provider, prompt, response) {
@@ -389,7 +417,10 @@ var JOB_FORM = "verdifax.job.v1";
389
417
  var REQUEST_KEY_PROOF_FORM = "verdifax.request-key.v1";
390
418
  var REQUEST_KEY_CHANGE_FORM = "verdifax.request-key-change.v1";
391
419
  var POLICY_ACTIVATION_FORM = "verdifax.policy-activation.v1";
420
+ var SIGNOFF_FORM = "verdifax.signoff.v1";
421
+ var APPROVER_KEY_PROOF_FORM = "verdifax.approver-key.v1";
392
422
  var SIGNING_KEY_BYTES = 32;
423
+ var SPKI_ED25519_HEADER = Buffer.from("302a300506032b6570032100", "hex");
393
424
  var PKCS8_ED25519_HEADER = Buffer.from(
394
425
  "302e020100300506032b657004220420",
395
426
  "hex"
@@ -573,6 +604,71 @@ function policyActivationApproval(signingKey, fields, options = {}) {
573
604
  nonce
574
605
  };
575
606
  }
607
+ function signOffPreimage(fields) {
608
+ const { target } = fields;
609
+ return Buffer.from(
610
+ [
611
+ SIGNOFF_FORM,
612
+ fields.chain_id,
613
+ fields.previous_signoff_hash,
614
+ target.kind,
615
+ String(target.run_id),
616
+ target.digest,
617
+ target.job_id ?? "",
618
+ fields.decision,
619
+ fields.note_hash,
620
+ fields.signed_at,
621
+ fields.nonce
622
+ ].join("\0"),
623
+ "utf8"
624
+ );
625
+ }
626
+ function signOffSignature(approverKey, fields, options = {}) {
627
+ const key = loadSigningKey(approverKey);
628
+ const signed_at = options.signedAt ?? signedAtNow();
629
+ const nonce = options.nonce ?? (0, import_node_crypto.randomBytes)(16).toString("hex");
630
+ const preimage = signOffPreimage({ ...fields, signed_at, nonce });
631
+ return {
632
+ approver_key: rawPublicKey((0, import_node_crypto.createPublicKey)(key)).toString("base64"),
633
+ signature: (0, import_node_crypto.sign)(null, preimage, key).toString("base64"),
634
+ signed_at,
635
+ nonce
636
+ };
637
+ }
638
+ function approverKeyProof(approverKey) {
639
+ const key = loadSigningKey(approverKey);
640
+ const public_key = rawPublicKey((0, import_node_crypto.createPublicKey)(key)).toString("base64");
641
+ const proof = (0, import_node_crypto.sign)(
642
+ null,
643
+ Buffer.from(`${APPROVER_KEY_PROOF_FORM}\0${public_key}`, "utf8"),
644
+ key
645
+ ).toString("base64");
646
+ return { public_key, proof };
647
+ }
648
+ function approverKeyProofVerifies(proof) {
649
+ if (typeof proof?.public_key !== "string" || typeof proof?.proof !== "string") {
650
+ return false;
651
+ }
652
+ const raw = Buffer.from(proof.public_key, "base64");
653
+ const signature = Buffer.from(proof.proof, "base64");
654
+ if (raw.length !== 32 || raw.toString("base64") !== proof.public_key || signature.length !== 64 || signature.toString("base64") !== proof.proof) {
655
+ return false;
656
+ }
657
+ const publicKey = (0, import_node_crypto.createPublicKey)({
658
+ key: Buffer.concat([SPKI_ED25519_HEADER, raw]),
659
+ format: "der",
660
+ type: "spki"
661
+ });
662
+ return (0, import_node_crypto.verify)(
663
+ null,
664
+ Buffer.from(`${APPROVER_KEY_PROOF_FORM}\0${proof.public_key}`, "utf8"),
665
+ publicKey,
666
+ signature
667
+ );
668
+ }
669
+ function publicKeyOf(key) {
670
+ return rawPublicKey((0, import_node_crypto.createPublicKey)(key)).toString("base64");
671
+ }
576
672
 
577
673
  // src/job.ts
578
674
  var STEP_OPTIONS = {
@@ -673,10 +769,327 @@ var VerdifaxJob = class {
673
769
  }
674
770
  };
675
771
 
772
+ // src/signals.ts
773
+ var import_node_crypto2 = require("crypto");
774
+ var SIGNAL_FORM = "verdifax.signal.v1";
775
+ var SIGNALS_PATH = "/signals";
776
+ var ACCOUNT_SIGNALS_PATH = "/account/signals";
777
+ var FEED_KEYS_PATH = "/account/feed-keys";
778
+ var WEBHOOKS_PATH = "/account/webhooks";
779
+ var MAX_SIGNAL_LIMIT = 500;
780
+ var MAX_SIGNAL_WAIT_SECONDS = 25;
781
+ var DEFAULT_FOLLOW_WAIT_SECONDS = 25;
782
+ var SIGNAL_TIMEOUT_MARGIN_MS = 3e4;
783
+ var EMPTY_PAGE_PAUSE_MS = 1e3;
784
+ var MAX_DELIVERY_LIMIT = 500;
785
+ var MAX_FEED_KEY_NAME_BYTES = 200;
786
+ var WEBHOOK_SECRET_PREFIX = "whsec_";
787
+ var WEBHOOK_SIGNATURE_VERSION = "v1";
788
+ var DEFAULT_WEBHOOK_TOLERANCE_SECONDS = 300;
789
+ var HMAC_SHA256_BYTES = 32;
790
+ var SIGNAL_KINDS = Object.freeze([
791
+ "run.refused",
792
+ "run.halted",
793
+ "run.failed",
794
+ "policy.changed",
795
+ "signoff.recorded",
796
+ "approver.registered",
797
+ "approver.revoked",
798
+ "key.created",
799
+ "key.revoked"
800
+ ]);
801
+ function signalsRead(options, method, clientTimeoutMs) {
802
+ const asOwner = asOwnerOf(options, method);
803
+ const after = given(options?.after, 0);
804
+ const limit = options?.limit;
805
+ const wait = given(options?.wait, 0);
806
+ requireAfter(after, method);
807
+ if (limit !== void 0) requireLimit(limit, method, MAX_SIGNAL_LIMIT);
808
+ requireWait(wait, method);
809
+ const q = new URLSearchParams();
810
+ q.set("after", String(after));
811
+ if (limit !== void 0) q.set("limit", String(limit));
812
+ q.set("wait", String(wait));
813
+ return {
814
+ path: `${asOwner ? ACCOUNT_SIGNALS_PATH : SIGNALS_PATH}?${q.toString()}`,
815
+ timeoutMs: Math.max(clientTimeoutMs, wait * 1e3 + SIGNAL_TIMEOUT_MARGIN_MS)
816
+ };
817
+ }
818
+ function followStart(options) {
819
+ const method = "followSignals";
820
+ const asOwner = asOwnerOf(options, method);
821
+ const after = given(options?.after, 0);
822
+ const wait = given(options?.wait, DEFAULT_FOLLOW_WAIT_SECONDS);
823
+ requireAfter(after, method);
824
+ requireWait(wait, method);
825
+ return { after, wait, asOwner };
826
+ }
827
+ async function* followSignalFeed(read, start) {
828
+ let last = start.after;
829
+ for (; ; ) {
830
+ let page;
831
+ try {
832
+ page = await read(last);
833
+ } catch (err) {
834
+ throw new SignalFeedError(
835
+ last,
836
+ err instanceof Error ? err.message : String(err),
837
+ { cause: err }
838
+ );
839
+ }
840
+ const events = pageEvents(page, last);
841
+ for (const event of events) {
842
+ yield event;
843
+ last = event.data.sequence;
844
+ }
845
+ if (events.length === 0 && start.wait === 0) {
846
+ await new Promise((r) => setTimeout(r, EMPTY_PAGE_PAUSE_MS));
847
+ }
848
+ }
849
+ }
850
+ function pageEvents(page, after) {
851
+ const events = page?.events ?? [];
852
+ if (!Array.isArray(events)) {
853
+ throw new SignalFeedError(after, "the server's page has no events list");
854
+ }
855
+ let previous = after;
856
+ for (const event of events) {
857
+ const sequence = event?.data?.sequence;
858
+ if (!Number.isSafeInteger(sequence) || sequence <= previous) {
859
+ throw new SignalFeedError(
860
+ after,
861
+ `the server's page holds an event out of order (sequence ${String(sequence)} after ${previous})`
862
+ );
863
+ }
864
+ previous = sequence;
865
+ }
866
+ if (page?.next_after !== previous) {
867
+ throw new SignalFeedError(
868
+ after,
869
+ `the server's next_after ${String(page?.next_after)} is not the last sequence on its page (${previous})`
870
+ );
871
+ }
872
+ return events;
873
+ }
874
+ function feedKeyBody(name, expiresAt) {
875
+ if (typeof name !== "string" || name.trim() === "" || Buffer.byteLength(name.trim(), "utf8") > MAX_FEED_KEY_NAME_BYTES) {
876
+ throw new VerdifaxError(
877
+ "verdifax: createFeedKey needs a name of at most 200 bytes"
878
+ );
879
+ }
880
+ if (expiresAt !== void 0 && typeof expiresAt !== "string") {
881
+ throw new VerdifaxError(
882
+ "verdifax: createFeedKey expiresAt must be an RFC 3339 time or a YYYY-MM-DD date, as a string"
883
+ );
884
+ }
885
+ return expiresAt === void 0 ? { name } : { name, expires_at: expiresAt };
886
+ }
887
+ function webhookBody(url, options) {
888
+ if (typeof url !== "string" || !url.startsWith("https://") || url.length <= 8) {
889
+ throw new VerdifaxError(
890
+ "verdifax: createWebhook needs a url that starts with https://"
891
+ );
892
+ }
893
+ const types = options?.types;
894
+ if (types === void 0) return { url };
895
+ if (!Array.isArray(types)) {
896
+ throw new VerdifaxError(
897
+ "verdifax: createWebhook types must be a list of signal kinds"
898
+ );
899
+ }
900
+ const seen = /* @__PURE__ */ new Set();
901
+ for (const kind of types) {
902
+ if (!SIGNAL_KINDS.includes(kind) || seen.has(kind)) {
903
+ throw new VerdifaxError(
904
+ `verdifax: createWebhook types must be distinct signal kinds (${SIGNAL_KINDS.join(", ")}); an empty list takes every kind`
905
+ );
906
+ }
907
+ seen.add(kind);
908
+ }
909
+ return { url, types: [...types] };
910
+ }
911
+ function deliveriesPath(id, options) {
912
+ const limit = options?.limit;
913
+ if (limit === void 0) return `${WEBHOOKS_PATH}/${id}/deliveries`;
914
+ requireLimit(limit, "listWebhookDeliveries", MAX_DELIVERY_LIMIT);
915
+ return `${WEBHOOKS_PATH}/${id}/deliveries?limit=${limit}`;
916
+ }
917
+ function verifyWebhook(headers, body, secret, options = {}) {
918
+ const key = webhookSecretBytes(secret);
919
+ const tolerance = options?.toleranceSeconds ?? DEFAULT_WEBHOOK_TOLERANCE_SECONDS;
920
+ if (typeof tolerance !== "number" || !Number.isFinite(tolerance) || tolerance < 0) {
921
+ throw new VerdifaxError(
922
+ "verdifax: verifyWebhook toleranceSeconds must be a number of seconds of 0 or more"
923
+ );
924
+ }
925
+ const now = options?.now ?? /* @__PURE__ */ new Date();
926
+ if (!(now instanceof Date) || Number.isNaN(now.getTime())) {
927
+ throw new VerdifaxError("verdifax: verifyWebhook now must be a valid Date");
928
+ }
929
+ let raw;
930
+ if (typeof body === "string") {
931
+ raw = Buffer.from(body, "utf8");
932
+ } else if (body instanceof Uint8Array) {
933
+ raw = Buffer.from(body.buffer, body.byteOffset, body.byteLength);
934
+ } else {
935
+ throw new VerdifaxError(
936
+ "verdifax: verifyWebhook needs the body as the raw bytes received (a Buffer, Uint8Array or string), not parsed JSON"
937
+ );
938
+ }
939
+ const id = singleHeader(headers, "webhook-id");
940
+ const timestamp = singleHeader(headers, "webhook-timestamp");
941
+ const signatures = headerValues(headers, "webhook-signature").join(" ");
942
+ if (!signatures) {
943
+ throw new VerdifaxError("verdifax: webhook check failed: the webhook-signature header is missing");
944
+ }
945
+ if (!/^[0-9]{1,15}$/.test(timestamp)) {
946
+ throw new VerdifaxError(
947
+ "verdifax: webhook check failed: webhook-timestamp is not a whole number of seconds"
948
+ );
949
+ }
950
+ const age = Math.abs(now.getTime() / 1e3 - Number(timestamp));
951
+ if (age > tolerance) {
952
+ throw new VerdifaxError(
953
+ `verdifax: webhook check failed: webhook-timestamp is more than ${tolerance} seconds from now`
954
+ );
955
+ }
956
+ const expected = (0, import_node_crypto2.createHmac)("sha256", key).update(`${id}.${timestamp}.`, "utf8").update(raw).digest();
957
+ let v1Seen = false;
958
+ let matched = false;
959
+ for (const entry of signatures.split(" ")) {
960
+ const comma = entry.indexOf(",");
961
+ if (comma < 0 || entry.slice(0, comma) !== WEBHOOK_SIGNATURE_VERSION) continue;
962
+ v1Seen = true;
963
+ const given2 = Buffer.from(entry.slice(comma + 1), "base64");
964
+ if (given2.length === HMAC_SHA256_BYTES && (0, import_node_crypto2.timingSafeEqual)(given2, expected)) {
965
+ matched = true;
966
+ }
967
+ }
968
+ if (!v1Seen) {
969
+ throw new VerdifaxError(
970
+ "verdifax: webhook check failed: webhook-signature holds no v1 signature"
971
+ );
972
+ }
973
+ if (!matched) {
974
+ throw new VerdifaxError(
975
+ "verdifax: webhook check failed: no v1 signature in webhook-signature matches the id, timestamp and body under this secret"
976
+ );
977
+ }
978
+ let event;
979
+ try {
980
+ event = JSON.parse(raw.toString("utf8"));
981
+ } catch {
982
+ throw new VerdifaxError(
983
+ "verdifax: webhook check failed: the signature matches but the body is not JSON"
984
+ );
985
+ }
986
+ if (typeof event !== "object" || event === null || Array.isArray(event)) {
987
+ throw new VerdifaxError(
988
+ "verdifax: webhook check failed: the signature matches but the body is not a CloudEvent object"
989
+ );
990
+ }
991
+ if (event.id !== id) {
992
+ throw new VerdifaxError(
993
+ "verdifax: webhook check failed: the event id in the body does not match webhook-id"
994
+ );
995
+ }
996
+ return event;
997
+ }
998
+ function signalEventHash(kind, entryHash, fields) {
999
+ const { account, sequence, previousSignalHash } = fields ?? {};
1000
+ for (const [name, value] of [
1001
+ ["kind", kind],
1002
+ ["entryHash", entryHash],
1003
+ ["account", account],
1004
+ ["previousSignalHash", previousSignalHash]
1005
+ ]) {
1006
+ if (typeof value !== "string" || value.includes("\0")) {
1007
+ throw new VerdifaxError(
1008
+ `verdifax: signalEventHash ${name} must be text without a zero byte`
1009
+ );
1010
+ }
1011
+ }
1012
+ if (!Number.isSafeInteger(sequence) || sequence < 0) {
1013
+ throw new VerdifaxError(
1014
+ "verdifax: signalEventHash sequence must be a whole number of 0 or more"
1015
+ );
1016
+ }
1017
+ return (0, import_node_crypto2.createHash)("sha256").update(
1018
+ [SIGNAL_FORM, kind, entryHash, account, String(sequence), previousSignalHash].join("\0"),
1019
+ "utf8"
1020
+ ).digest("hex");
1021
+ }
1022
+ function given(value, fallback) {
1023
+ return value === void 0 ? fallback : value;
1024
+ }
1025
+ function requireAfter(after, method) {
1026
+ if (!Number.isSafeInteger(after) || after < 0) {
1027
+ throw new VerdifaxError(
1028
+ `verdifax: ${method} after must be a whole number of 0 or more, the last sequence read`
1029
+ );
1030
+ }
1031
+ }
1032
+ function requireLimit(limit, method, max) {
1033
+ if (!Number.isSafeInteger(limit) || limit < 1 || limit > max) {
1034
+ throw new VerdifaxError(
1035
+ `verdifax: ${method} limit must be a whole number from 1 to ${max}`
1036
+ );
1037
+ }
1038
+ }
1039
+ function requireWait(wait, method) {
1040
+ if (!Number.isSafeInteger(wait) || wait < 0 || wait > MAX_SIGNAL_WAIT_SECONDS) {
1041
+ throw new VerdifaxError(
1042
+ `verdifax: ${method} wait must be a whole number of seconds from 0 to ${MAX_SIGNAL_WAIT_SECONDS}`
1043
+ );
1044
+ }
1045
+ }
1046
+ function webhookSecretBytes(secret) {
1047
+ if (typeof secret !== "string" || !secret.startsWith(WEBHOOK_SECRET_PREFIX)) {
1048
+ throw new VerdifaxError(
1049
+ "verdifax: verifyWebhook needs the subscription's secret, which starts with whsec_"
1050
+ );
1051
+ }
1052
+ const encoded = secret.slice(WEBHOOK_SECRET_PREFIX.length);
1053
+ const key = Buffer.from(encoded, "base64");
1054
+ if (!/^[A-Za-z0-9+/]+={0,2}$/.test(encoded) || key.length === 0 || key.toString("base64").replace(/=+$/, "") !== encoded.replace(/=+$/, "")) {
1055
+ throw new VerdifaxError(
1056
+ "verdifax: verifyWebhook needs the subscription's secret: whsec_ and then base64"
1057
+ );
1058
+ }
1059
+ return key;
1060
+ }
1061
+ function headerValues(headers, name) {
1062
+ if (typeof headers !== "object" || headers === null) {
1063
+ throw new VerdifaxError("verdifax: verifyWebhook needs the delivery's headers");
1064
+ }
1065
+ if (typeof headers.get === "function") {
1066
+ const value = headers.get(name);
1067
+ return value === null || value === void 0 ? [] : [String(value)];
1068
+ }
1069
+ const out = [];
1070
+ for (const [key, value] of Object.entries(headers)) {
1071
+ if (key.toLowerCase() !== name) continue;
1072
+ if (Array.isArray(value)) out.push(...value.map(String));
1073
+ else if (value !== void 0) out.push(String(value));
1074
+ }
1075
+ return out;
1076
+ }
1077
+ function singleHeader(headers, name) {
1078
+ const values = headerValues(headers, name);
1079
+ if (values.length === 0 || values[0] === "") {
1080
+ throw new VerdifaxError(`verdifax: webhook check failed: the ${name} header is missing`);
1081
+ }
1082
+ if (values.length > 1) {
1083
+ throw new VerdifaxError(`verdifax: webhook check failed: the ${name} header appears more than once`);
1084
+ }
1085
+ return values[0];
1086
+ }
1087
+
676
1088
  // src/version.ts
677
- var SDK_VERSION = "1.3.0";
1089
+ var SDK_VERSION = "1.5.0";
678
1090
 
679
1091
  // src/client.ts
1092
+ var import_node_crypto3 = require("crypto");
680
1093
  var DEFAULT_BASE_URL = "https://api.verdifax.com";
681
1094
  var DEFAULT_TIMEOUT_MS = 9e4;
682
1095
  var DEFAULT_MAX_RETRIES = 3;
@@ -689,6 +1102,12 @@ var ACCOUNT_PATH = "/account";
689
1102
  var ACCOUNT_REQUEST_KEY_PATH = "/account/request-key";
690
1103
  var ACCOUNT_POLICIES_PATH = "/account/policies";
691
1104
  var ACCOUNT_CHAIN_ID = /^account-[1-9][0-9]*$/;
1105
+ var SIGNOFFS_PATH = "/signoffs";
1106
+ var ACCOUNT_SIGNOFFS_PATH = "/account/signoffs";
1107
+ var APPROVERS_PATH = "/account/approvers";
1108
+ var SIGNOFF_TARGET_KINDS = /* @__PURE__ */ new Set(["record", "receipt", "job"]);
1109
+ var SIGNOFF_DECISIONS = /* @__PURE__ */ new Set(["approve", "reject"]);
1110
+ var MAX_APPROVER_NAME_BYTES = 200;
692
1111
  var HEADER_EXPORT_TOTAL = "X-Verdifax-Total";
693
1112
  var HEADER_EXPORT_TRUNCATED = "X-Verdifax-Truncated";
694
1113
  var RETRYABLE_STATUSES = /* @__PURE__ */ new Set([429, 502, 503, 504]);
@@ -1195,6 +1614,271 @@ var VerdifaxClient = class {
1195
1614
  }
1196
1615
  return this.activatePolicyAt(ACCOUNT_POLICIES_PATH, documentHash, chain);
1197
1616
  }
1617
+ // ── Sign-off ─────────────────────────────────────────────────
1618
+ //
1619
+ // An account's owner registers approver keys. An approver signs a
1620
+ // decision, approve or reject, on one exact result on their own machine,
1621
+ // and any key in the account, or the owner key with asOwner, submits it.
1622
+ // A sign-off shows that the holder of a registered approver key signed
1623
+ // that decision on that exact result and that Verdifax logged it on the
1624
+ // public log. It does not show the review was careful, the result right,
1625
+ // or who the person is, and it gates nothing on its own.
1626
+ /** Registers an approver key to the owner's account. `approver` is the
1627
+ * approver's signing key, from which the proof is made on this machine,
1628
+ * or the `{ public_key, proof }` that {@link approverKeyProof} made on
1629
+ * the approver's own machine, so the owner need not hold the private
1630
+ * key. A proof that does not verify is refused before sending. The
1631
+ * server refuses a key that is a request key in the same account.
1632
+ * `name` is a label, not an identity. */
1633
+ async registerApprover(name, approver) {
1634
+ this.requireAPIKey();
1635
+ if (typeof name !== "string" || name.trim() === "" || Buffer.byteLength(name.trim(), "utf8") > MAX_APPROVER_NAME_BYTES) {
1636
+ throw new VerdifaxError(
1637
+ "verdifax: registerApprover needs a name of at most 200 bytes"
1638
+ );
1639
+ }
1640
+ const body = approver instanceof Uint8Array || approver instanceof import_node_crypto3.KeyObject ? approverKeyProof(approver) : { public_key: approver?.public_key, proof: approver?.proof };
1641
+ if (!approverKeyProofVerifies(body)) {
1642
+ throw new VerdifaxError(
1643
+ "verdifax: registerApprover needs the approver's signing key, or a public_key and proof from approverKeyProof that verify"
1644
+ );
1645
+ }
1646
+ if (this.signingKey && publicKeyOf(this.signingKey) === body.public_key) {
1647
+ throw new VerdifaxError(
1648
+ "verdifax: an approver key must not be a request key in the same account, and this is the client's signingKey"
1649
+ );
1650
+ }
1651
+ return this.request("POST", APPROVERS_PATH, {
1652
+ public_key: body.public_key,
1653
+ name,
1654
+ proof: body.proof
1655
+ });
1656
+ }
1657
+ /** The account's approver keys, revoked ones included. */
1658
+ async listApprovers() {
1659
+ this.requireAPIKey();
1660
+ const out = await this.request("GET", APPROVERS_PATH);
1661
+ return { ...out, approvers: out?.approvers ?? [] };
1662
+ }
1663
+ /** Revokes one of the account's approver keys. Its earlier sign-offs
1664
+ * stay on the record. A key that is not an active approver in the
1665
+ * account throws {@link NotFoundError}. */
1666
+ async revokeApprover(approverId) {
1667
+ this.requireAPIKey();
1668
+ requirePositiveId(approverId, "approverId");
1669
+ return this.request(
1670
+ "DELETE",
1671
+ `${APPROVERS_PATH}/${approverId}`
1672
+ );
1673
+ }
1674
+ /** What an approver signs against: the account's chain `account-N` and
1675
+ * its newest sign-off (64 zeros when there is none yet). With
1676
+ * `asOwner` it reads the owner key's route. */
1677
+ async getNewestSignOff(options = {}) {
1678
+ this.requireAPIKey();
1679
+ return this.request(
1680
+ "GET",
1681
+ `${signOffsBase(options, "getNewestSignOff")}/newest`
1682
+ );
1683
+ }
1684
+ /** Signs an approver's decision, approve or reject, on one exact result
1685
+ * and submits it. It first reads {@link getNewestSignOff} for the
1686
+ * account's chain and its newest sign-off, then signs over them with
1687
+ * `approverKey` on this machine. The approver's private key is never
1688
+ * sent.
1689
+ *
1690
+ * `target.digest` is what the result's public-log entry covers: for a
1691
+ * record, the `bundle_anchor.anchored_digest` of the bundle
1692
+ * {@link getRunArtifacts} returns; for a receipt, its hash; for a job,
1693
+ * the final step's record digest, read as a record's, with `job_id`.
1694
+ *
1695
+ * `note` is hashed here and only its SHA-256 is sent and signed: the
1696
+ * text never reaches Verdifax. With `asOwner` it uses the owner key's
1697
+ * routes. Bad input is refused before anything is sent.
1698
+ *
1699
+ * The record the server returns must carry the signature,
1700
+ * approver_key, decision, previous_signoff_hash and target that were
1701
+ * sent, or this throws {@link VerdifaxError}.
1702
+ *
1703
+ * A later sign-off on the same result supersedes this one, and neither
1704
+ * is deleted. An HTTP 409 means the chain moved or the target is not
1705
+ * this account's result: it throws the usual {@link APIError} and is
1706
+ * not retried. */
1707
+ async signOff(target, decision, approverKey, options = {}) {
1708
+ this.requireAPIKey();
1709
+ const base = signOffsBase(options, "signOff");
1710
+ const exact = signOffTargetOf(target);
1711
+ if (!SIGNOFF_DECISIONS.has(decision)) {
1712
+ throw new VerdifaxError(
1713
+ "verdifax: signOff decision must be approve or reject"
1714
+ );
1715
+ }
1716
+ const note = options?.note;
1717
+ if (note !== void 0 && (typeof note !== "string" || note === "")) {
1718
+ throw new VerdifaxError(
1719
+ "verdifax: signOff note must be non-empty text when given"
1720
+ );
1721
+ }
1722
+ const key = loadSigningKey(approverKey);
1723
+ const note_hash = note === void 0 ? "" : sha256Hex(note);
1724
+ const newest = await this.getNewestSignOff(options);
1725
+ if (typeof newest?.chain_id !== "string" || !ACCOUNT_CHAIN_ID.test(newest.chain_id)) {
1726
+ throw new VerdifaxError(
1727
+ "verdifax: the server did not report an account chain_id (account-N), so the sign-off cannot be signed"
1728
+ );
1729
+ }
1730
+ const previous = newest.newest_signoff_hash;
1731
+ if (typeof previous !== "string" || !/^[0-9a-f]{64}$/.test(previous)) {
1732
+ throw new VerdifaxError(
1733
+ "verdifax: the server did not report newest_signoff_hash, so the sign-off cannot name the one it follows"
1734
+ );
1735
+ }
1736
+ const signed = signOffSignature(key, {
1737
+ chain_id: newest.chain_id,
1738
+ previous_signoff_hash: previous,
1739
+ target: exact,
1740
+ decision,
1741
+ note_hash
1742
+ });
1743
+ const body = {
1744
+ previous_signoff_hash: previous,
1745
+ target: exact,
1746
+ decision,
1747
+ ...note_hash ? { note_hash } : {},
1748
+ ...signed
1749
+ };
1750
+ const out = await this.request(
1751
+ "POST",
1752
+ base,
1753
+ body
1754
+ );
1755
+ const record = out?.signoff;
1756
+ if (!recordMatchesSent(record, exact, decision, previous, signed)) {
1757
+ throw new VerdifaxError(
1758
+ "verdifax: the sign-off the server returned does not carry the signature, approver_key, decision, previous_signoff_hash and target that were sent"
1759
+ );
1760
+ }
1761
+ return record;
1762
+ }
1763
+ /** The sign-offs on one run, oldest first, in the form
1764
+ * `verdifax-verify --signoff FILE` reads: for a member key, a run it
1765
+ * made; with `asOwner`, any run of the account. The latest is the
1766
+ * decision in force. */
1767
+ async getSignOffs(runId, options = {}) {
1768
+ this.requireAPIKey();
1769
+ requirePositiveId(runId, "runId");
1770
+ const base = asOwnerOf(options, "getSignOffs") ? `${ACCOUNT_PATH}/runs` : "/runs";
1771
+ return await this.request(
1772
+ "GET",
1773
+ `${base}/${runId}/signoffs`
1774
+ ) ?? [];
1775
+ }
1776
+ /** The account's whole chain of sign-offs, oldest first, in the form
1777
+ * `verdifax-verify --signoff-history FILE` reads. Needs the owner key. */
1778
+ async getSignOffHistory() {
1779
+ this.requireAPIKey();
1780
+ return await this.request(
1781
+ "GET",
1782
+ `${ACCOUNT_SIGNOFFS_PATH}/history`
1783
+ ) ?? [];
1784
+ }
1785
+ // ── Signal feed ──────────────────────────────────────────────
1786
+ //
1787
+ // Every control signal Verdifax recorded for the account, in order, each
1788
+ // with its sealed entry. The feed cannot show a signal Verdifax never
1789
+ // recorded. A feed key reads it on GET /signals and does nothing else;
1790
+ // the owner key reads it with asOwner and manages feed keys and webhooks.
1791
+ // The feed and webhook logic is in signals.ts.
1792
+ /** One page of the account's feed: the events after `after`, oldest
1793
+ * first, with `next_after` to read from next. With `wait` the server
1794
+ * holds the request open up to that many seconds for the next event, and
1795
+ * this call's timeout is at least the wait plus 30 seconds. With
1796
+ * `asOwner` it reads GET /account/signals with the owner key. Bad
1797
+ * options are refused before sending. Save the events and check them
1798
+ * with `verdifax-verify --signals`. */
1799
+ async getSignals(options = {}) {
1800
+ this.requireAPIKey();
1801
+ const read = signalsRead(options, "getSignals", this.timeoutMs);
1802
+ const out = await this.request(
1803
+ "GET",
1804
+ read.path,
1805
+ void 0,
1806
+ false,
1807
+ read.timeoutMs
1808
+ );
1809
+ return { ...out, events: out?.events ?? [] };
1810
+ }
1811
+ /** Follows the feed from `after`, yielding each event once, in order,
1812
+ * until you stop with `break` or `return`. Each read starts at the page
1813
+ * before's `next_after`, waits up to `wait` seconds (default 25) when
1814
+ * there is no event, and is retried like any GET. A read that still
1815
+ * fails throws {@link SignalFeedError}, whose `lastSequence` is the last
1816
+ * sequence yielded: follow again from there and nothing is lost. Bad
1817
+ * options are refused here, before anything is sent. */
1818
+ followSignals(options = {}) {
1819
+ this.requireAPIKey();
1820
+ const start = followStart(options);
1821
+ return followSignalFeed(
1822
+ (after) => this.getSignals({ after, wait: start.wait, asOwner: start.asOwner }),
1823
+ start
1824
+ );
1825
+ }
1826
+ /** Creates a feed key in the owner's account. A feed key reads the
1827
+ * account's signal feed, with {@link getSignals} and
1828
+ * {@link followSignals}, and nothing else. The secret is in the result
1829
+ * this once. */
1830
+ async createFeedKey(name, options = {}) {
1831
+ this.requireAPIKey();
1832
+ return this.request(
1833
+ "POST",
1834
+ FEED_KEYS_PATH,
1835
+ feedKeyBody(name, options?.expiresAt)
1836
+ );
1837
+ }
1838
+ /** Revokes one of the account's feed keys. An id that is not a feed key
1839
+ * of the account throws {@link NotFoundError}. */
1840
+ async revokeFeedKey(id) {
1841
+ this.requireAPIKey();
1842
+ requirePositiveId(id, "id");
1843
+ return this.request("DELETE", `${FEED_KEYS_PATH}/${id}`);
1844
+ }
1845
+ /** Subscribes an https address to the account's signals. `types` are the
1846
+ * kinds to deliver, each once; empty or left out takes every kind. The
1847
+ * secret, `whsec_` and base64, is in the result this once: check each
1848
+ * delivery with {@link verifyWebhook}. A delivery is a copy: the pull
1849
+ * feed and the public log are the record. The server checks the address
1850
+ * too, and refuses an eleventh subscription with HTTP 409. */
1851
+ async createWebhook(url, options = {}) {
1852
+ this.requireAPIKey();
1853
+ return this.request(
1854
+ "POST",
1855
+ WEBHOOKS_PATH,
1856
+ webhookBody(url, options)
1857
+ );
1858
+ }
1859
+ /** The account's webhook subscriptions, without their secrets. */
1860
+ async listWebhooks() {
1861
+ this.requireAPIKey();
1862
+ const out = await this.request("GET", WEBHOOKS_PATH);
1863
+ return { ...out, webhooks: out?.webhooks ?? [] };
1864
+ }
1865
+ /** Ends a webhook subscription. Its events stay in the pull feed. */
1866
+ async deleteWebhook(id) {
1867
+ this.requireAPIKey();
1868
+ requirePositiveId(id, "id");
1869
+ return this.request("DELETE", `${WEBHOOKS_PATH}/${id}`);
1870
+ }
1871
+ /** A webhook's newest deliveries first, up to `limit` (1 to 500; the
1872
+ * server's default is 50). */
1873
+ async listWebhookDeliveries(id, options = {}) {
1874
+ this.requireAPIKey();
1875
+ requirePositiveId(id, "id");
1876
+ const out = await this.request(
1877
+ "GET",
1878
+ deliveriesPath(id, options)
1879
+ );
1880
+ return { ...out, deliveries: out?.deliveries ?? [] };
1881
+ }
1198
1882
  // ── Runs ──────────────────────────────────────────────────────
1199
1883
  async getRun(runId) {
1200
1884
  this.requireAPIKey();
@@ -1340,6 +2024,14 @@ var VerdifaxClient = class {
1340
2024
  async getCESAuditRecord(runId) {
1341
2025
  return this.getRunArtifact(runId, "ces-audit-record");
1342
2026
  }
2027
+ /** A failed run's sealed failure receipt, in the form `verdifax-verify`
2028
+ * reads. A run that failed before failure receipts were sealed has none
2029
+ * and throws {@link NotFoundError}. */
2030
+ async getFailureReceipt(runId) {
2031
+ this.requireAPIKey();
2032
+ requirePositiveId(runId, "runId");
2033
+ return this.getRunArtifact(runId, "failure-receipt");
2034
+ }
1343
2035
  /** The audit report for a run, as JSON. */
1344
2036
  async getRunReport(runId) {
1345
2037
  const out = await this.getRunArtifact(runId, "report");
@@ -1537,7 +2229,7 @@ var VerdifaxClient = class {
1537
2229
  });
1538
2230
  }
1539
2231
  // ── HTTP plumbing, retry-aware ──────────────────────────────
1540
- async request(method, path, body, rawText = false) {
2232
+ async request(method, path, body, rawText = false, timeoutMs = this.timeoutMs) {
1541
2233
  const url = this.baseURL + path;
1542
2234
  const headers = {
1543
2235
  "User-Agent": this.userAgent
@@ -1554,7 +2246,7 @@ var VerdifaxClient = class {
1554
2246
  await new Promise((r) => setTimeout(r, sleep));
1555
2247
  }
1556
2248
  const controller = new AbortController();
1557
- const timer = setTimeout(() => controller.abort(), this.timeoutMs);
2249
+ const timer = setTimeout(() => controller.abort(), timeoutMs);
1558
2250
  let resp;
1559
2251
  try {
1560
2252
  resp = await fetch(url, {
@@ -1648,10 +2340,44 @@ var VerdifaxClient = class {
1648
2340
  return this.signingKey ? signRequestV2(this.signingKey, req) : withExecuteFlags(req);
1649
2341
  }
1650
2342
  };
1651
- function requirePositiveId(id, name) {
1652
- if (!Number.isSafeInteger(id) || id <= 0) {
1653
- throw new VerdifaxError(`verdifax: ${name} must be a whole number > 0`);
2343
+ function signOffsBase(options, method) {
2344
+ return asOwnerOf(options, method) ? ACCOUNT_SIGNOFFS_PATH : SIGNOFFS_PATH;
2345
+ }
2346
+ function signOffTargetOf(target) {
2347
+ if (typeof target !== "object" || target === null || Array.isArray(target)) {
2348
+ throw new VerdifaxError("verdifax: signOff needs a target object");
2349
+ }
2350
+ for (const name of Object.keys(target)) {
2351
+ if (!["kind", "run_id", "digest", "job_id"].includes(name)) {
2352
+ throw new VerdifaxError(`verdifax: signOff target has an unknown field: ${name}`);
2353
+ }
2354
+ }
2355
+ if (!SIGNOFF_TARGET_KINDS.has(target.kind)) {
2356
+ throw new VerdifaxError(
2357
+ "verdifax: signOff target kind must be record, receipt or job"
2358
+ );
1654
2359
  }
2360
+ requirePositiveId(target.run_id, "target.run_id");
2361
+ validateHex64(target.digest, "target.digest");
2362
+ if (target.kind === "job") {
2363
+ validateJobName(target.job_id, "target.job_id");
2364
+ return {
2365
+ kind: target.kind,
2366
+ run_id: target.run_id,
2367
+ digest: target.digest,
2368
+ job_id: target.job_id
2369
+ };
2370
+ }
2371
+ if (target.job_id !== void 0) {
2372
+ throw new VerdifaxError(
2373
+ "verdifax: signOff target job_id is for a job target only"
2374
+ );
2375
+ }
2376
+ return { kind: target.kind, run_id: target.run_id, digest: target.digest };
2377
+ }
2378
+ function recordMatchesSent(record, target, decision, previous, signed) {
2379
+ const got = record?.target;
2380
+ return typeof record === "object" && record !== null && record.signature === signed.signature && record.approver_key === signed.approver_key && record.decision === decision && record.previous_signoff_hash === previous && typeof got === "object" && got !== null && got.kind === target.kind && got.run_id === target.run_id && got.digest === target.digest && (got.job_id ?? "") === (target.job_id ?? "");
1655
2381
  }
1656
2382
  function withSignedText(result, sent) {
1657
2383
  return "signed_request" in sent ? { ...result, signed_request: sent.signed_request } : result;
@@ -1778,13 +2504,13 @@ var RUN_STATUSES = [
1778
2504
  ];
1779
2505
 
1780
2506
  // src/section0.ts
1781
- var import_node_crypto2 = require("crypto");
2507
+ var import_node_crypto4 = require("crypto");
1782
2508
  var DSE_FORMULA_VERSION = "dse.tcu.dispatch.v1";
1783
2509
  var DCAE_PREIMAGE_VERSION = "verdifax.dcae.v1";
1784
2510
  var CRES_PREIMAGE_VERSION = "verdifax.cres.v1";
1785
2511
  var CRES_ENGINE_VERSION = "verdifax-cres/1.0.0";
1786
2512
  function sha256Hex2(preimage) {
1787
- return (0, import_node_crypto2.createHash)("sha256").update(Buffer.from(preimage, "utf8")).digest("hex");
2513
+ return (0, import_node_crypto4.createHash)("sha256").update(Buffer.from(preimage, "utf8")).digest("hex");
1788
2514
  }
1789
2515
  function requireHex64(value, name) {
1790
2516
  try {
@@ -1851,9 +2577,11 @@ function cresReceiptHash(fields) {
1851
2577
  MAX_BATCH_ROWS,
1852
2578
  NotFoundError,
1853
2579
  RUN_STATUSES,
2580
+ SignalFeedError,
1854
2581
  VerdifaxClient,
1855
2582
  VerdifaxError,
1856
2583
  VerdifaxJob,
2584
+ approverKeyProof,
1857
2585
  captureEnvironment,
1858
2586
  cresReceiptHash,
1859
2587
  dcaeClosureHash,
@@ -1868,9 +2596,12 @@ function cresReceiptHash(fields) {
1868
2596
  requestKeyRegistrationBody,
1869
2597
  requestSignaturePreimage,
1870
2598
  requestSignaturePreimageV2,
2599
+ signOffPreimage,
1871
2600
  signRequest,
1872
2601
  signRequestV2,
2602
+ signalEventHash,
1873
2603
  validateHex64,
1874
2604
  validateJobName,
1875
- validateRouteId
2605
+ validateRouteId,
2606
+ verifyWebhook
1876
2607
  });