@witnium/witniumchain 0.26.0 → 0.27.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.mjs CHANGED
@@ -11,6 +11,100 @@ var WitniumchainApiError = class extends Error {
11
11
  this.body = args.body ?? null;
12
12
  }
13
13
  };
14
+ var WitnessProposeError = class extends WitniumchainApiError {
15
+ /** The scope of the failed propose (64 lowercase hex). */
16
+ scope;
17
+ constructor(cause, scope) {
18
+ if (cause instanceof WitniumchainApiError) {
19
+ super({ status: cause.status, message: cause.message, errorLabel: cause.errorLabel, body: cause.body });
20
+ } else {
21
+ super({ status: 0, message: cause instanceof Error ? cause.message : String(cause) });
22
+ }
23
+ this.name = "WitnessProposeError";
24
+ this.scope = scope;
25
+ this.cause = cause;
26
+ }
27
+ };
28
+ var WitnessScopeConflictError = class extends WitnessProposeError {
29
+ code;
30
+ /** The witness already in the scope (`scope_details_mismatch` once it is mined). */
31
+ witnessId;
32
+ constructor(cause, scope, code, witnessId) {
33
+ super(cause, scope);
34
+ this.name = "WitnessScopeConflictError";
35
+ this.code = code;
36
+ this.witnessId = witnessId;
37
+ }
38
+ };
39
+
40
+ // src/witness-scope.ts
41
+ var SCOPE_PATTERN = /^[0-9a-fA-F]{64}$/;
42
+ var CONFLICT_CODES = /* @__PURE__ */ new Set([
43
+ "scope_details_mismatch",
44
+ "scope_in_progress",
45
+ "scope_registry_mismatch"
46
+ ]);
47
+ function randomWitnessScope() {
48
+ const bytes = new Uint8Array(32);
49
+ cryptoRef().getRandomValues(bytes);
50
+ return toHex(bytes);
51
+ }
52
+ async function witnessScopeFor(key) {
53
+ if (key.length === 0) {
54
+ throw new Error("witnessScopeFor: key must not be empty");
55
+ }
56
+ const digest = await cryptoRef().subtle.digest("SHA-256", new TextEncoder().encode(key));
57
+ return toHex(new Uint8Array(digest));
58
+ }
59
+ function resolveWitnessScope(scope) {
60
+ if (scope === void 0) return randomWitnessScope();
61
+ if (!SCOPE_PATTERN.test(scope)) {
62
+ throw new Error(
63
+ "proposeWitnessV5: scope must be the SHA-256 of your key, exactly 64 hex characters (see witnessScopeFor)"
64
+ );
65
+ }
66
+ return scope.toLowerCase();
67
+ }
68
+ function scopedProposeResult(answer, scope) {
69
+ const a = typeof answer === "object" && answer !== null ? answer : {};
70
+ const required = a.outcome === "created" ? { intentId: "string", witnessNonce: "string", payloadToSign: "string", expiresInSeconds: "number", requiredSigners: "string[]" } : a.outcome === "existing" ? { intentId: "string", witnessId: "string", blockNumber: "number", chainTimestamp: "number" } : void 0;
71
+ if (required === void 0) {
72
+ throw new Error(
73
+ `proposeWitnessV5: accounts answered a scoped propose without a valid outcome (got ${JSON.stringify(a.outcome)}); this accounts does not support witness scopes`
74
+ );
75
+ }
76
+ const missing = Object.entries(required).filter(
77
+ ([field, type]) => type === "string[]" ? !(Array.isArray(a[field]) && a[field].every((v) => typeof v === "string")) : typeof a[field] !== type
78
+ ).map(([field]) => field);
79
+ if (missing.length > 0) {
80
+ throw new Error(`proposeWitnessV5: accounts' "${String(a.outcome)}" answer lacks ${missing.join(", ")}`);
81
+ }
82
+ return { ...a, scope };
83
+ }
84
+ function scopedProposeError(err, scope) {
85
+ if (err instanceof WitniumchainApiError && err.status === 409) {
86
+ const body = err.body;
87
+ if (typeof body?.code === "string" && CONFLICT_CODES.has(body.code)) {
88
+ const witnessId = typeof body.witnessId === "string" ? body.witnessId : void 0;
89
+ return new WitnessScopeConflictError(err, scope, body.code, witnessId);
90
+ }
91
+ }
92
+ return new WitnessProposeError(err, scope);
93
+ }
94
+ function toHex(bytes) {
95
+ let out = "";
96
+ for (const b of bytes) out += b.toString(16).padStart(2, "0");
97
+ return out;
98
+ }
99
+ function cryptoRef() {
100
+ const c = globalThis.crypto;
101
+ if (!c || !c.subtle || !c.getRandomValues) {
102
+ throw new Error(
103
+ "WitniumchainClient: globalThis.crypto with subtle + getRandomValues is required for witness scopes. Modern browsers and Node 18+ provide this natively."
104
+ );
105
+ }
106
+ return c;
107
+ }
14
108
 
15
109
  // src/pkce.ts
16
110
  var STORAGE_PREFIX = "witniumchain.pkce.";
@@ -35,17 +129,17 @@ function defaultVerifierStorage() {
35
129
  }
36
130
  function generateCodeVerifier() {
37
131
  const bytes = new Uint8Array(64);
38
- cryptoRef().getRandomValues(bytes);
132
+ cryptoRef2().getRandomValues(bytes);
39
133
  return base64UrlEncode(bytes);
40
134
  }
41
135
  async function deriveCodeChallenge(verifier) {
42
136
  const data = new TextEncoder().encode(verifier);
43
- const digest = await cryptoRef().subtle.digest("SHA-256", data);
137
+ const digest = await cryptoRef2().subtle.digest("SHA-256", data);
44
138
  return base64UrlEncode(new Uint8Array(digest));
45
139
  }
46
140
  function generateState() {
47
141
  const bytes = new Uint8Array(32);
48
- cryptoRef().getRandomValues(bytes);
142
+ cryptoRef2().getRandomValues(bytes);
49
143
  return base64UrlEncode(bytes);
50
144
  }
51
145
  function base64UrlEncode(bytes) {
@@ -54,7 +148,7 @@ function base64UrlEncode(bytes) {
54
148
  const b64 = typeof btoa === "function" ? btoa(binary) : Buffer.from(binary, "binary").toString("base64");
55
149
  return b64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
56
150
  }
57
- function cryptoRef() {
151
+ function cryptoRef2() {
58
152
  const c = globalThis.crypto;
59
153
  if (!c || !c.subtle || !c.getRandomValues) {
60
154
  throw new Error(
@@ -526,29 +620,24 @@ var WitniumchainClient = class {
526
620
  { auth: "Public" }
527
621
  );
528
622
  }
529
- // ────────────────────────────────────────────────────────────────────────
530
- // v5 Witnesses (/v5/contracts/{addr}/witnesses/*)
531
- //
532
- // The v5 write surface is a metered proxy in accounts: every billable
533
- // call (propose, revoke) reserves a credit; sign/finalize forward to
534
- // chain-api with the admin token. Auth is OAuth Bearer (the URL
535
- // contract must match the user's bound contract), or an org API key for
536
- // propose, sign and finalize (its org's active contract).
537
- //
538
- // The propose/revoke methods default Idempotency-Key to a stable hash
539
- // of the request body so an application-level retry with the same
540
- // arguments dedupes against the original reservation instead of
541
- // burning a second credit. Pass an explicit `idempotencyKey` to
542
- // override (e.g. if you genuinely want two witnesses for the same
543
- // body).
544
- // ────────────────────────────────────────────────────────────────────────
545
623
  async proposeWitnessV5(contractAddress, body, idempotencyKey) {
546
- const key = idempotencyKey ?? await deriveBodyKey("v5:propose", contractAddress, body);
547
- return this.req(
548
- "POST",
549
- `/v5/contracts/${encodeURIComponent(contractAddress)}/witnesses/propose`,
550
- { auth: this.writeAuth(), body, headers: { "idempotency-key": key } }
551
- );
624
+ const path = `/v5/contracts/${encodeURIComponent(contractAddress)}/witnesses/propose`;
625
+ if (idempotencyKey !== void 0) {
626
+ if (idempotencyKey.trim() === "") {
627
+ throw new Error("proposeWitnessV5: idempotencyKey must not be empty (pass a `scope` in the body instead)");
628
+ }
629
+ if (body.scope !== void 0) {
630
+ throw new Error("proposeWitnessV5: pass either a `scope` in the body or the deprecated idempotencyKey, not both");
631
+ }
632
+ return this.req("POST", path, { auth: this.writeAuth(), body, headers: { "idempotency-key": idempotencyKey } });
633
+ }
634
+ const scope = resolveWitnessScope(body.scope);
635
+ try {
636
+ const answer = await this.req("POST", path, { auth: this.writeAuth(), body: { ...body, scope } });
637
+ return scopedProposeResult(answer, scope);
638
+ } catch (err) {
639
+ throw scopedProposeError(err, scope);
640
+ }
552
641
  }
553
642
  /**
554
643
  * What happened to an intent whose propose or finalize answer was lost
@@ -1926,9 +2015,8 @@ var WitniumchainApiKeyClient = class {
1926
2015
  sign(body, requestId) {
1927
2016
  return this.inner.sign(body, requestId);
1928
2017
  }
1929
- /** Propose a witness on the org's contract; reserves one credit. */
1930
2018
  proposeWitnessV5(contractAddress, body, idempotencyKey) {
1931
- return this.inner.proposeWitnessV5(contractAddress, body, idempotencyKey);
2019
+ return idempotencyKey === void 0 ? this.inner.proposeWitnessV5(contractAddress, body) : this.inner.proposeWitnessV5(contractAddress, body, idempotencyKey);
1932
2020
  }
1933
2021
  /** Submit the signature for an intent this key proposed. */
1934
2022
  signWitnessV5(contractAddress, intentId, body) {
@@ -2074,6 +2162,6 @@ var ownerKeyFile = {
2074
2162
  sign: signWithOwnerKeyFile
2075
2163
  };
2076
2164
 
2077
- export { AccountSecurity, DashboardKey, DelegatedKeys, Enrollment, OWNER_KEY_FILE_FORMAT, OWNER_OP, OauthNamespace, OauthSessions, OrgApiKeys, OrgContract, OrgMembers, Organization, Recovery, SigningKeys, Subscriptions, WitniumchainApiError, WitniumchainApiKeyClient, WitniumchainChainAdminClient, WitniumchainClient, buildAddSigningKeyPayload, buildPausePayload, buildRevokeSigningKeyPayload, buildUnpausePayload, defaultVerifierStorage, generateOwnerKeyFile, ownerKeyFile, ownerKeyFileName, parseOwnerKeyFile, serializeOwnerKeyFile, signWithOwnerKeyFile };
2165
+ export { AccountSecurity, DashboardKey, DelegatedKeys, Enrollment, OWNER_KEY_FILE_FORMAT, OWNER_OP, OauthNamespace, OauthSessions, OrgApiKeys, OrgContract, OrgMembers, Organization, Recovery, SigningKeys, Subscriptions, WitnessProposeError, WitnessScopeConflictError, WitniumchainApiError, WitniumchainApiKeyClient, WitniumchainChainAdminClient, WitniumchainClient, buildAddSigningKeyPayload, buildPausePayload, buildRevokeSigningKeyPayload, buildUnpausePayload, defaultVerifierStorage, generateOwnerKeyFile, ownerKeyFile, ownerKeyFileName, parseOwnerKeyFile, randomWitnessScope, serializeOwnerKeyFile, signWithOwnerKeyFile, witnessScopeFor };
2078
2166
  //# sourceMappingURL=index.mjs.map
2079
2167
  //# sourceMappingURL=index.mjs.map