@witnium/witniumchain 0.25.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(
@@ -133,6 +227,8 @@ var WitniumchainClient = class {
133
227
  recovery;
134
228
  /** The signed-in user's sign-in methods, behind step-up. `client.security.*`. */
135
229
  security;
230
+ /** The signed-in member's org: rename it (org admins). `client.organization.*`. */
231
+ organization;
136
232
  /** Session-cookie team management (org-admin only). `client.orgUsers.*`. */
137
233
  orgUsers;
138
234
  /** The home org's API keys (session; org admins create and revoke). `client.apiKeys.*`. */
@@ -167,6 +263,7 @@ var WitniumchainClient = class {
167
263
  this.enrollment = new Enrollment(this);
168
264
  this.recovery = new Recovery(this);
169
265
  this.security = new AccountSecurity(this);
266
+ this.organization = new Organization(this);
170
267
  this.orgUsers = new OrgMembers(this);
171
268
  this.apiKeys = new OrgApiKeys(this);
172
269
  this.dashboardKey = new DashboardKey(this);
@@ -249,6 +346,9 @@ var WitniumchainClient = class {
249
346
  expectNoContent: true
250
347
  });
251
348
  }
349
+ renameOrg(body) {
350
+ return this.req("PATCH", "/v1/orgs/me", { auth: "SessionCookie", body });
351
+ }
252
352
  listMembers() {
253
353
  return this.req("GET", "/v1/orgs/me/members", { auth: "SessionCookie" });
254
354
  }
@@ -520,29 +620,24 @@ var WitniumchainClient = class {
520
620
  { auth: "Public" }
521
621
  );
522
622
  }
523
- // ────────────────────────────────────────────────────────────────────────
524
- // v5 Witnesses (/v5/contracts/{addr}/witnesses/*)
525
- //
526
- // The v5 write surface is a metered proxy in accounts: every billable
527
- // call (propose, revoke) reserves a credit; sign/finalize forward to
528
- // chain-api with the admin token. Auth is OAuth Bearer (the URL
529
- // contract must match the user's bound contract), or an org API key for
530
- // propose, sign and finalize (its org's active contract).
531
- //
532
- // The propose/revoke methods default Idempotency-Key to a stable hash
533
- // of the request body so an application-level retry with the same
534
- // arguments dedupes against the original reservation instead of
535
- // burning a second credit. Pass an explicit `idempotencyKey` to
536
- // override (e.g. if you genuinely want two witnesses for the same
537
- // body).
538
- // ────────────────────────────────────────────────────────────────────────
539
623
  async proposeWitnessV5(contractAddress, body, idempotencyKey) {
540
- const key = idempotencyKey ?? await deriveBodyKey("v5:propose", contractAddress, body);
541
- return this.req(
542
- "POST",
543
- `/v5/contracts/${encodeURIComponent(contractAddress)}/witnesses/propose`,
544
- { auth: this.writeAuth(), body, headers: { "idempotency-key": key } }
545
- );
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
+ }
546
641
  }
547
642
  /**
548
643
  * What happened to an intent whose propose or finalize answer was lost
@@ -1706,6 +1801,21 @@ var OrgApiKeys = class {
1706
1801
  return this.client.revokeApiKey(id);
1707
1802
  }
1708
1803
  };
1804
+ var Organization = class {
1805
+ constructor(client) {
1806
+ this.client = client;
1807
+ }
1808
+ client;
1809
+ /**
1810
+ * Rename the org (org admins). This is the display name the dashboard and
1811
+ * invitations show; the billing name on invoices is separate and edited in
1812
+ * the billing portal. Surrounding spaces are dropped; the current name
1813
+ * again is a no-op.
1814
+ */
1815
+ rename(name) {
1816
+ return this.client.renameOrg({ name });
1817
+ }
1818
+ };
1709
1819
  var OrgMembers = class {
1710
1820
  constructor(client) {
1711
1821
  this.client = client;
@@ -1905,9 +2015,8 @@ var WitniumchainApiKeyClient = class {
1905
2015
  sign(body, requestId) {
1906
2016
  return this.inner.sign(body, requestId);
1907
2017
  }
1908
- /** Propose a witness on the org's contract; reserves one credit. */
1909
2018
  proposeWitnessV5(contractAddress, body, idempotencyKey) {
1910
- return this.inner.proposeWitnessV5(contractAddress, body, idempotencyKey);
2019
+ return idempotencyKey === void 0 ? this.inner.proposeWitnessV5(contractAddress, body) : this.inner.proposeWitnessV5(contractAddress, body, idempotencyKey);
1911
2020
  }
1912
2021
  /** Submit the signature for an intent this key proposed. */
1913
2022
  signWitnessV5(contractAddress, intentId, body) {
@@ -2053,6 +2162,6 @@ var ownerKeyFile = {
2053
2162
  sign: signWithOwnerKeyFile
2054
2163
  };
2055
2164
 
2056
- export { AccountSecurity, DashboardKey, DelegatedKeys, Enrollment, OWNER_KEY_FILE_FORMAT, OWNER_OP, OauthNamespace, OauthSessions, OrgApiKeys, OrgContract, OrgMembers, 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 };
2057
2166
  //# sourceMappingURL=index.mjs.map
2058
2167
  //# sourceMappingURL=index.mjs.map