@witnium/witniumchain 0.26.0 → 0.28.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
@@ -13,6 +13,100 @@ var WitniumchainApiError = class extends Error {
13
13
  this.body = args.body ?? null;
14
14
  }
15
15
  };
16
+ var WitnessProposeError = class extends WitniumchainApiError {
17
+ /** The scope of the failed propose (64 lowercase hex). */
18
+ scope;
19
+ constructor(cause, scope) {
20
+ if (cause instanceof WitniumchainApiError) {
21
+ super({ status: cause.status, message: cause.message, errorLabel: cause.errorLabel, body: cause.body });
22
+ } else {
23
+ super({ status: 0, message: cause instanceof Error ? cause.message : String(cause) });
24
+ }
25
+ this.name = "WitnessProposeError";
26
+ this.scope = scope;
27
+ this.cause = cause;
28
+ }
29
+ };
30
+ var WitnessScopeConflictError = class extends WitnessProposeError {
31
+ code;
32
+ /** The witness already in the scope (`scope_details_mismatch` once it is mined). */
33
+ witnessId;
34
+ constructor(cause, scope, code, witnessId) {
35
+ super(cause, scope);
36
+ this.name = "WitnessScopeConflictError";
37
+ this.code = code;
38
+ this.witnessId = witnessId;
39
+ }
40
+ };
41
+
42
+ // src/witness-scope.ts
43
+ var SCOPE_PATTERN = /^[0-9a-fA-F]{64}$/;
44
+ var CONFLICT_CODES = /* @__PURE__ */ new Set([
45
+ "scope_details_mismatch",
46
+ "scope_in_progress",
47
+ "scope_registry_mismatch"
48
+ ]);
49
+ function randomWitnessScope() {
50
+ const bytes = new Uint8Array(32);
51
+ cryptoRef().getRandomValues(bytes);
52
+ return toHex(bytes);
53
+ }
54
+ async function witnessScopeFor(key) {
55
+ if (key.length === 0) {
56
+ throw new Error("witnessScopeFor: key must not be empty");
57
+ }
58
+ const digest = await cryptoRef().subtle.digest("SHA-256", new TextEncoder().encode(key));
59
+ return toHex(new Uint8Array(digest));
60
+ }
61
+ function resolveWitnessScope(scope) {
62
+ if (scope === void 0) return randomWitnessScope();
63
+ if (!SCOPE_PATTERN.test(scope)) {
64
+ throw new Error(
65
+ "proposeWitnessV5: scope must be the SHA-256 of your key, exactly 64 hex characters (see witnessScopeFor)"
66
+ );
67
+ }
68
+ return scope.toLowerCase();
69
+ }
70
+ function scopedProposeResult(answer, scope) {
71
+ const a = typeof answer === "object" && answer !== null ? answer : {};
72
+ 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;
73
+ if (required === void 0) {
74
+ throw new Error(
75
+ `proposeWitnessV5: accounts answered a scoped propose without a valid outcome (got ${JSON.stringify(a.outcome)}); this accounts does not support witness scopes`
76
+ );
77
+ }
78
+ const missing = Object.entries(required).filter(
79
+ ([field, type]) => type === "string[]" ? !(Array.isArray(a[field]) && a[field].every((v) => typeof v === "string")) : typeof a[field] !== type
80
+ ).map(([field]) => field);
81
+ if (missing.length > 0) {
82
+ throw new Error(`proposeWitnessV5: accounts' "${String(a.outcome)}" answer lacks ${missing.join(", ")}`);
83
+ }
84
+ return { ...a, scope };
85
+ }
86
+ function scopedProposeError(err, scope) {
87
+ if (err instanceof WitniumchainApiError && err.status === 409) {
88
+ const body = err.body;
89
+ if (typeof body?.code === "string" && CONFLICT_CODES.has(body.code)) {
90
+ const witnessId = typeof body.witnessId === "string" ? body.witnessId : void 0;
91
+ return new WitnessScopeConflictError(err, scope, body.code, witnessId);
92
+ }
93
+ }
94
+ return new WitnessProposeError(err, scope);
95
+ }
96
+ function toHex(bytes) {
97
+ let out = "";
98
+ for (const b of bytes) out += b.toString(16).padStart(2, "0");
99
+ return out;
100
+ }
101
+ function cryptoRef() {
102
+ const c = globalThis.crypto;
103
+ if (!c || !c.subtle || !c.getRandomValues) {
104
+ throw new Error(
105
+ "WitniumchainClient: globalThis.crypto with subtle + getRandomValues is required for witness scopes. Modern browsers and Node 18+ provide this natively."
106
+ );
107
+ }
108
+ return c;
109
+ }
16
110
 
17
111
  // src/pkce.ts
18
112
  var STORAGE_PREFIX = "witniumchain.pkce.";
@@ -37,17 +131,17 @@ function defaultVerifierStorage() {
37
131
  }
38
132
  function generateCodeVerifier() {
39
133
  const bytes = new Uint8Array(64);
40
- cryptoRef().getRandomValues(bytes);
134
+ cryptoRef2().getRandomValues(bytes);
41
135
  return base64UrlEncode(bytes);
42
136
  }
43
137
  async function deriveCodeChallenge(verifier) {
44
138
  const data = new TextEncoder().encode(verifier);
45
- const digest = await cryptoRef().subtle.digest("SHA-256", data);
139
+ const digest = await cryptoRef2().subtle.digest("SHA-256", data);
46
140
  return base64UrlEncode(new Uint8Array(digest));
47
141
  }
48
142
  function generateState() {
49
143
  const bytes = new Uint8Array(32);
50
- cryptoRef().getRandomValues(bytes);
144
+ cryptoRef2().getRandomValues(bytes);
51
145
  return base64UrlEncode(bytes);
52
146
  }
53
147
  function base64UrlEncode(bytes) {
@@ -56,7 +150,7 @@ function base64UrlEncode(bytes) {
56
150
  const b64 = typeof btoa === "function" ? btoa(binary) : Buffer.from(binary, "binary").toString("base64");
57
151
  return b64.replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
58
152
  }
59
- function cryptoRef() {
153
+ function cryptoRef2() {
60
154
  const c = globalThis.crypto;
61
155
  if (!c || !c.subtle || !c.getRandomValues) {
62
156
  throw new Error(
@@ -86,6 +180,9 @@ var WitniumchainClient = class {
86
180
  // jar) get the refresh token in the response body and the SDK stashes it
87
181
  // here as a fallback. Either path drives `refreshAccessToken` identically.
88
182
  refreshToken;
183
+ // The ID token from the last code exchange or refresh, kept for
184
+ // RP-initiated logout (`id_token_hint`). Memory only, like the tokens.
185
+ idToken;
89
186
  // Sentinel: the most recent token response set an HttpOnly refresh cookie.
90
187
  // The SDK can't directly observe an HttpOnly cookie, but the response body
91
188
  // tells us indirectly — server strips `refresh_token` when it sets the
@@ -209,17 +306,17 @@ var WitniumchainClient = class {
209
306
  // Backing methods for the `orgUsers` namespace. All resolve the caller's
210
307
  // org + org-admin role server-side from the session — no orgId in the path.
211
308
  getDashboardKey() {
212
- return this.req("GET", "/v1/account/dashboard-key", { auth: "SessionCookie" });
309
+ return this.req("GET", "/v1/account/dashboard-key", { auth: "SessionOrBearer" });
213
310
  }
214
311
  ensureDashboardKey() {
215
- return this.req("POST", "/v1/account/dashboard-key", { auth: "SessionCookie" });
312
+ return this.req("POST", "/v1/account/dashboard-key", { auth: "SessionOrBearer" });
216
313
  }
217
314
  /** Revoke your own added dashboard key on chain; 409 for the organization's base key. */
218
315
  revokeDashboardKey() {
219
- return this.req("DELETE", "/v1/account/dashboard-key", { auth: "SessionCookie", expectNoContent: true });
316
+ return this.req("DELETE", "/v1/account/dashboard-key", { auth: "SessionOrBearer", expectNoContent: true });
220
317
  }
221
318
  pauseOrgContract() {
222
- return this.req("POST", "/v1/orgs/me/contract/pause", { auth: "SessionCookie" });
319
+ return this.req("POST", "/v1/orgs/me/contract/pause", { auth: "SessionOrBearer" });
223
320
  }
224
321
  /**
225
322
  * Add a key you hold to the org's managed contract (plan §17.7): org
@@ -235,10 +332,10 @@ var WitniumchainClient = class {
235
332
  }
236
333
  /** Needs a step-up within 5 minutes (`client.security.stepUp`). */
237
334
  resumeOrgContract() {
238
- return this.req("POST", "/v1/orgs/me/contract/resume", { auth: "SessionCookie" });
335
+ return this.req("POST", "/v1/orgs/me/contract/resume", { auth: "SessionOrBearer" });
239
336
  }
240
337
  getContractActivity(limit) {
241
- return this.req("GET", "/v1/orgs/me/owner-operations", { auth: "SessionCookie", query: { limit } });
338
+ return this.req("GET", "/v1/orgs/me/owner-operations", { auth: "SessionOrBearer", query: { limit } });
242
339
  }
243
340
  /** Create an API key (org admin, after a step-up). The secret is in this response only. */
244
341
  createApiKey(body) {
@@ -258,7 +355,7 @@ var WitniumchainClient = class {
258
355
  return this.req("PATCH", "/v1/orgs/me", { auth: "SessionCookie", body });
259
356
  }
260
357
  listMembers() {
261
- return this.req("GET", "/v1/orgs/me/members", { auth: "SessionCookie" });
358
+ return this.req("GET", "/v1/orgs/me/members", { auth: "SessionOrBearer" });
262
359
  }
263
360
  inviteMember(body) {
264
361
  return this.req("POST", "/v1/orgs/me/members/invite", {
@@ -335,17 +432,17 @@ var WitniumchainClient = class {
335
432
  return this.req("POST", "/v1/account/signing-key-requests", { auth: "SessionOrBearer", body });
336
433
  }
337
434
  listSigningKeyRequests() {
338
- return this.req("GET", "/v1/account/signing-key-requests", { auth: "SessionCookie" });
435
+ return this.req("GET", "/v1/account/signing-key-requests", { auth: "SessionOrBearer" });
339
436
  }
340
437
  approveSigningKeyRequest(id, body) {
341
438
  return this.req("POST", `/v1/account/signing-key-requests/${encodeURIComponent(id)}/approve`, {
342
- auth: "SessionCookie",
439
+ auth: "SessionOrBearer",
343
440
  body
344
441
  });
345
442
  }
346
443
  declineSigningKeyRequest(id) {
347
444
  return this.req("POST", `/v1/account/signing-key-requests/${encodeURIComponent(id)}/decline`, {
348
- auth: "SessionCookie",
445
+ auth: "SessionOrBearer",
349
446
  expectNoContent: true
350
447
  });
351
448
  }
@@ -399,12 +496,12 @@ var WitniumchainClient = class {
399
496
  // ────────────────────────────────────────────────────────────────────────
400
497
  createCheckoutSession(body) {
401
498
  return this.req("POST", "/v1/billing/checkout", {
402
- auth: "SessionCookie",
499
+ auth: "SessionOrBearer",
403
500
  body
404
501
  });
405
502
  }
406
503
  createPortalSession() {
407
- return this.req("GET", "/v1/billing/portal", { auth: "SessionCookie" });
504
+ return this.req("GET", "/v1/billing/portal", { auth: "SessionOrBearer" });
408
505
  }
409
506
  // Webhook endpoint is intentionally NOT exposed: only Stripe should call it.
410
507
  // ────────────────────────────────────────────────────────────────────────
@@ -478,13 +575,13 @@ var WitniumchainClient = class {
478
575
  }
479
576
  pauseContract(body) {
480
577
  return this.req("POST", "/v1/contracts/pause", {
481
- auth: "SessionCookie",
578
+ auth: "SessionOrBearer",
482
579
  body
483
580
  });
484
581
  }
485
582
  unpauseContract(body) {
486
583
  return this.req("POST", "/v1/contracts/unpause", {
487
- auth: "SessionCookie",
584
+ auth: "SessionOrBearer",
488
585
  body
489
586
  });
490
587
  }
@@ -528,29 +625,24 @@ var WitniumchainClient = class {
528
625
  { auth: "Public" }
529
626
  );
530
627
  }
531
- // ────────────────────────────────────────────────────────────────────────
532
- // v5 Witnesses (/v5/contracts/{addr}/witnesses/*)
533
- //
534
- // The v5 write surface is a metered proxy in accounts: every billable
535
- // call (propose, revoke) reserves a credit; sign/finalize forward to
536
- // chain-api with the admin token. Auth is OAuth Bearer (the URL
537
- // contract must match the user's bound contract), or an org API key for
538
- // propose, sign and finalize (its org's active contract).
539
- //
540
- // The propose/revoke methods default Idempotency-Key to a stable hash
541
- // of the request body so an application-level retry with the same
542
- // arguments dedupes against the original reservation instead of
543
- // burning a second credit. Pass an explicit `idempotencyKey` to
544
- // override (e.g. if you genuinely want two witnesses for the same
545
- // body).
546
- // ────────────────────────────────────────────────────────────────────────
547
628
  async proposeWitnessV5(contractAddress, body, idempotencyKey) {
548
- const key = idempotencyKey ?? await deriveBodyKey("v5:propose", contractAddress, body);
549
- return this.req(
550
- "POST",
551
- `/v5/contracts/${encodeURIComponent(contractAddress)}/witnesses/propose`,
552
- { auth: this.writeAuth(), body, headers: { "idempotency-key": key } }
553
- );
629
+ const path = `/v5/contracts/${encodeURIComponent(contractAddress)}/witnesses/propose`;
630
+ if (idempotencyKey !== void 0) {
631
+ if (idempotencyKey.trim() === "") {
632
+ throw new Error("proposeWitnessV5: idempotencyKey must not be empty (pass a `scope` in the body instead)");
633
+ }
634
+ if (body.scope !== void 0) {
635
+ throw new Error("proposeWitnessV5: pass either a `scope` in the body or the deprecated idempotencyKey, not both");
636
+ }
637
+ return this.req("POST", path, { auth: this.writeAuth(), body, headers: { "idempotency-key": idempotencyKey } });
638
+ }
639
+ const scope = resolveWitnessScope(body.scope);
640
+ try {
641
+ const answer = await this.req("POST", path, { auth: this.writeAuth(), body: { ...body, scope } });
642
+ return scopedProposeResult(answer, scope);
643
+ } catch (err) {
644
+ throw scopedProposeError(err, scope);
645
+ }
554
646
  }
555
647
  /**
556
648
  * What happened to an intent whose propose or finalize answer was lost
@@ -590,10 +682,10 @@ var WitniumchainClient = class {
590
682
  // Users / account (/v1/account/*)
591
683
  // ────────────────────────────────────────────────────────────────────────
592
684
  getAccount() {
593
- return this.req("GET", "/v1/account", { auth: "SessionCookie" });
685
+ return this.req("GET", "/v1/account", { auth: "SessionOrBearer" });
594
686
  }
595
687
  getLedger() {
596
- return this.req("GET", "/v1/account/ledger", { auth: "SessionCookie" });
688
+ return this.req("GET", "/v1/account/ledger", { auth: "SessionOrBearer" });
597
689
  }
598
690
  /**
599
691
  * DEV-ONLY: hard-delete the authenticated user + their org + contracts +
@@ -805,6 +897,15 @@ var WitniumchainClient = class {
805
897
  url.searchParams.set("code_challenge", challenge);
806
898
  url.searchParams.set("code_challenge_method", "S256");
807
899
  if (args.prompt) url.searchParams.set("prompt", args.prompt);
900
+ if (args.maxAge !== void 0) {
901
+ if (!Number.isInteger(args.maxAge) || args.maxAge < 0) {
902
+ throw new WitniumchainApiError({
903
+ status: 0,
904
+ message: `WitniumchainClient: beginOAuthLogin \`maxAge\` must be a non-negative integer (got ${args.maxAge}).`
905
+ });
906
+ }
907
+ url.searchParams.set("max_age", String(args.maxAge));
908
+ }
808
909
  const storage = this.verifierStorageOrDefault();
809
910
  storage.set(state, verifier);
810
911
  storage.set(redirectUriKey(state), args.redirectUri);
@@ -970,6 +1071,7 @@ var WitniumchainClient = class {
970
1071
  this.accessToken = void 0;
971
1072
  this.accessTokenFromSession = false;
972
1073
  this.refreshToken = void 0;
1074
+ this.idToken = void 0;
973
1075
  this.hasRefreshCookie = false;
974
1076
  this.sessionExchangeInFlight = void 0;
975
1077
  this.refreshInFlight = void 0;
@@ -1028,6 +1130,47 @@ var WitniumchainClient = class {
1028
1130
  signOut() {
1029
1131
  this.invalidateCredentials();
1030
1132
  }
1133
+ /**
1134
+ * End the session at the authorization server (OIDC RP-Initiated Logout).
1135
+ *
1136
+ * Builds the `end_session_endpoint` URL with `id_token_hint` (the ID token
1137
+ * from {@link completeOAuthLogin}), `client_id` and
1138
+ * `post_logout_redirect_uri`, then forgets every in-memory credential like
1139
+ * {@link signOut}. The caller does the redirect
1140
+ * (`window.location.assign(result.logoutUrl)`).
1141
+ *
1142
+ * Throws when no `oauthClientId` is configured, when this client holds no
1143
+ * ID token (the login was not completed here, or it did not ask for
1144
+ * `openid`), or when the discovery document has no `end_session_endpoint`.
1145
+ */
1146
+ async beginOAuthLogout(args) {
1147
+ if (!this.oauthClientId) {
1148
+ throw new WitniumchainApiError({
1149
+ status: 0,
1150
+ message: "WitniumchainClient: beginOAuthLogout requires `oauthClientId` to be set on the constructor."
1151
+ });
1152
+ }
1153
+ if (!this.idToken) {
1154
+ throw new WitniumchainApiError({
1155
+ status: 0,
1156
+ message: "WitniumchainClient: beginOAuthLogout needs the ID token from completeOAuthLogin (request the `openid` scope and complete the login with this client)."
1157
+ });
1158
+ }
1159
+ const discovery = await this.fetchDiscovery();
1160
+ if (!discovery.end_session_endpoint) {
1161
+ throw new WitniumchainApiError({
1162
+ status: 0,
1163
+ message: "OIDC discovery doc has no `end_session_endpoint`: the authorization server does not offer RP-initiated logout."
1164
+ });
1165
+ }
1166
+ const url = new URL(discovery.end_session_endpoint);
1167
+ url.searchParams.set("id_token_hint", this.idToken);
1168
+ url.searchParams.set("client_id", this.oauthClientId);
1169
+ url.searchParams.set("post_logout_redirect_uri", args.postLogoutRedirectUri);
1170
+ if (args.state !== void 0) url.searchParams.set("state", args.state);
1171
+ this.invalidateCredentials();
1172
+ return { logoutUrl: url.toString() };
1173
+ }
1031
1174
  // ────────────────────────────────────────────────────────────────────────
1032
1175
  // Internal: OAuth flow helpers
1033
1176
  // ────────────────────────────────────────────────────────────────────────
@@ -1070,6 +1213,7 @@ var WitniumchainClient = class {
1070
1213
  return {
1071
1214
  authorization_endpoint: parsed.authorization_endpoint,
1072
1215
  token_endpoint: parsed.token_endpoint,
1216
+ end_session_endpoint: parsed.end_session_endpoint,
1073
1217
  issuer: parsed.issuer ?? this.baseUrl
1074
1218
  };
1075
1219
  })();
@@ -1121,6 +1265,7 @@ var WitniumchainClient = class {
1121
1265
  });
1122
1266
  }
1123
1267
  this.accessToken = tokens.access_token;
1268
+ if (tokens.id_token) this.idToken = tokens.id_token;
1124
1269
  this.accessTokenFromSession = false;
1125
1270
  if (tokens.refresh_token) {
1126
1271
  this.refreshToken = tokens.refresh_token;
@@ -1210,9 +1355,11 @@ var WitniumchainClient = class {
1210
1355
  headers,
1211
1356
  body: bodyString,
1212
1357
  signal: controller.signal,
1213
- // Send cookies cross-origin when the consumer is a browser using
1214
- // SessionCookie auth via document.cookie.
1215
- credentials: "include"
1358
+ // A request that carries a bearer credential sends no cookies: an
1359
+ // OAuth client on another site must not depend on (or leak) a
1360
+ // third-party cookie. Everything else sends cookies cross-origin for
1361
+ // a browser using the cookie session.
1362
+ credentials: headers["authorization"] === void 0 ? "include" : "omit"
1216
1363
  });
1217
1364
  } catch (err) {
1218
1365
  throw new WitniumchainApiError({
@@ -1335,7 +1482,7 @@ var WitniumchainClient = class {
1335
1482
  return;
1336
1483
  }
1337
1484
  case "SessionOrBearer": {
1338
- if (this.accessToken) headers["authorization"] = `Bearer ${this.accessToken}`;
1485
+ if (this.accessToken && !this.accessTokenFromSession) headers["authorization"] = `Bearer ${this.accessToken}`;
1339
1486
  else if (this.cfg.sessionCookie) headers["cookie"] = `wac_session=${this.cfg.sessionCookie}`;
1340
1487
  return;
1341
1488
  }
@@ -1928,9 +2075,8 @@ var WitniumchainApiKeyClient = class {
1928
2075
  sign(body, requestId) {
1929
2076
  return this.inner.sign(body, requestId);
1930
2077
  }
1931
- /** Propose a witness on the org's contract; reserves one credit. */
1932
2078
  proposeWitnessV5(contractAddress, body, idempotencyKey) {
1933
- return this.inner.proposeWitnessV5(contractAddress, body, idempotencyKey);
2079
+ return idempotencyKey === void 0 ? this.inner.proposeWitnessV5(contractAddress, body) : this.inner.proposeWitnessV5(contractAddress, body, idempotencyKey);
1934
2080
  }
1935
2081
  /** Submit the signature for an intent this key proposed. */
1936
2082
  signWitnessV5(contractAddress, intentId, body) {
@@ -2091,6 +2237,8 @@ exports.Organization = Organization;
2091
2237
  exports.Recovery = Recovery;
2092
2238
  exports.SigningKeys = SigningKeys;
2093
2239
  exports.Subscriptions = Subscriptions;
2240
+ exports.WitnessProposeError = WitnessProposeError;
2241
+ exports.WitnessScopeConflictError = WitnessScopeConflictError;
2094
2242
  exports.WitniumchainApiError = WitniumchainApiError;
2095
2243
  exports.WitniumchainApiKeyClient = WitniumchainApiKeyClient;
2096
2244
  exports.WitniumchainChainAdminClient = WitniumchainChainAdminClient;
@@ -2104,7 +2252,9 @@ exports.generateOwnerKeyFile = generateOwnerKeyFile;
2104
2252
  exports.ownerKeyFile = ownerKeyFile;
2105
2253
  exports.ownerKeyFileName = ownerKeyFileName;
2106
2254
  exports.parseOwnerKeyFile = parseOwnerKeyFile;
2255
+ exports.randomWitnessScope = randomWitnessScope;
2107
2256
  exports.serializeOwnerKeyFile = serializeOwnerKeyFile;
2108
2257
  exports.signWithOwnerKeyFile = signWithOwnerKeyFile;
2258
+ exports.witnessScopeFor = witnessScopeFor;
2109
2259
  //# sourceMappingURL=index.js.map
2110
2260
  //# sourceMappingURL=index.js.map