@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.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(
@@ -84,6 +178,9 @@ var WitniumchainClient = class {
84
178
  // jar) get the refresh token in the response body and the SDK stashes it
85
179
  // here as a fallback. Either path drives `refreshAccessToken` identically.
86
180
  refreshToken;
181
+ // The ID token from the last code exchange or refresh, kept for
182
+ // RP-initiated logout (`id_token_hint`). Memory only, like the tokens.
183
+ idToken;
87
184
  // Sentinel: the most recent token response set an HttpOnly refresh cookie.
88
185
  // The SDK can't directly observe an HttpOnly cookie, but the response body
89
186
  // tells us indirectly — server strips `refresh_token` when it sets the
@@ -207,17 +304,17 @@ var WitniumchainClient = class {
207
304
  // Backing methods for the `orgUsers` namespace. All resolve the caller's
208
305
  // org + org-admin role server-side from the session — no orgId in the path.
209
306
  getDashboardKey() {
210
- return this.req("GET", "/v1/account/dashboard-key", { auth: "SessionCookie" });
307
+ return this.req("GET", "/v1/account/dashboard-key", { auth: "SessionOrBearer" });
211
308
  }
212
309
  ensureDashboardKey() {
213
- return this.req("POST", "/v1/account/dashboard-key", { auth: "SessionCookie" });
310
+ return this.req("POST", "/v1/account/dashboard-key", { auth: "SessionOrBearer" });
214
311
  }
215
312
  /** Revoke your own added dashboard key on chain; 409 for the organization's base key. */
216
313
  revokeDashboardKey() {
217
- return this.req("DELETE", "/v1/account/dashboard-key", { auth: "SessionCookie", expectNoContent: true });
314
+ return this.req("DELETE", "/v1/account/dashboard-key", { auth: "SessionOrBearer", expectNoContent: true });
218
315
  }
219
316
  pauseOrgContract() {
220
- return this.req("POST", "/v1/orgs/me/contract/pause", { auth: "SessionCookie" });
317
+ return this.req("POST", "/v1/orgs/me/contract/pause", { auth: "SessionOrBearer" });
221
318
  }
222
319
  /**
223
320
  * Add a key you hold to the org's managed contract (plan §17.7): org
@@ -233,10 +330,10 @@ var WitniumchainClient = class {
233
330
  }
234
331
  /** Needs a step-up within 5 minutes (`client.security.stepUp`). */
235
332
  resumeOrgContract() {
236
- return this.req("POST", "/v1/orgs/me/contract/resume", { auth: "SessionCookie" });
333
+ return this.req("POST", "/v1/orgs/me/contract/resume", { auth: "SessionOrBearer" });
237
334
  }
238
335
  getContractActivity(limit) {
239
- return this.req("GET", "/v1/orgs/me/owner-operations", { auth: "SessionCookie", query: { limit } });
336
+ return this.req("GET", "/v1/orgs/me/owner-operations", { auth: "SessionOrBearer", query: { limit } });
240
337
  }
241
338
  /** Create an API key (org admin, after a step-up). The secret is in this response only. */
242
339
  createApiKey(body) {
@@ -256,7 +353,7 @@ var WitniumchainClient = class {
256
353
  return this.req("PATCH", "/v1/orgs/me", { auth: "SessionCookie", body });
257
354
  }
258
355
  listMembers() {
259
- return this.req("GET", "/v1/orgs/me/members", { auth: "SessionCookie" });
356
+ return this.req("GET", "/v1/orgs/me/members", { auth: "SessionOrBearer" });
260
357
  }
261
358
  inviteMember(body) {
262
359
  return this.req("POST", "/v1/orgs/me/members/invite", {
@@ -333,17 +430,17 @@ var WitniumchainClient = class {
333
430
  return this.req("POST", "/v1/account/signing-key-requests", { auth: "SessionOrBearer", body });
334
431
  }
335
432
  listSigningKeyRequests() {
336
- return this.req("GET", "/v1/account/signing-key-requests", { auth: "SessionCookie" });
433
+ return this.req("GET", "/v1/account/signing-key-requests", { auth: "SessionOrBearer" });
337
434
  }
338
435
  approveSigningKeyRequest(id, body) {
339
436
  return this.req("POST", `/v1/account/signing-key-requests/${encodeURIComponent(id)}/approve`, {
340
- auth: "SessionCookie",
437
+ auth: "SessionOrBearer",
341
438
  body
342
439
  });
343
440
  }
344
441
  declineSigningKeyRequest(id) {
345
442
  return this.req("POST", `/v1/account/signing-key-requests/${encodeURIComponent(id)}/decline`, {
346
- auth: "SessionCookie",
443
+ auth: "SessionOrBearer",
347
444
  expectNoContent: true
348
445
  });
349
446
  }
@@ -397,12 +494,12 @@ var WitniumchainClient = class {
397
494
  // ────────────────────────────────────────────────────────────────────────
398
495
  createCheckoutSession(body) {
399
496
  return this.req("POST", "/v1/billing/checkout", {
400
- auth: "SessionCookie",
497
+ auth: "SessionOrBearer",
401
498
  body
402
499
  });
403
500
  }
404
501
  createPortalSession() {
405
- return this.req("GET", "/v1/billing/portal", { auth: "SessionCookie" });
502
+ return this.req("GET", "/v1/billing/portal", { auth: "SessionOrBearer" });
406
503
  }
407
504
  // Webhook endpoint is intentionally NOT exposed: only Stripe should call it.
408
505
  // ────────────────────────────────────────────────────────────────────────
@@ -476,13 +573,13 @@ var WitniumchainClient = class {
476
573
  }
477
574
  pauseContract(body) {
478
575
  return this.req("POST", "/v1/contracts/pause", {
479
- auth: "SessionCookie",
576
+ auth: "SessionOrBearer",
480
577
  body
481
578
  });
482
579
  }
483
580
  unpauseContract(body) {
484
581
  return this.req("POST", "/v1/contracts/unpause", {
485
- auth: "SessionCookie",
582
+ auth: "SessionOrBearer",
486
583
  body
487
584
  });
488
585
  }
@@ -526,29 +623,24 @@ var WitniumchainClient = class {
526
623
  { auth: "Public" }
527
624
  );
528
625
  }
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
626
  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
- );
627
+ const path = `/v5/contracts/${encodeURIComponent(contractAddress)}/witnesses/propose`;
628
+ if (idempotencyKey !== void 0) {
629
+ if (idempotencyKey.trim() === "") {
630
+ throw new Error("proposeWitnessV5: idempotencyKey must not be empty (pass a `scope` in the body instead)");
631
+ }
632
+ if (body.scope !== void 0) {
633
+ throw new Error("proposeWitnessV5: pass either a `scope` in the body or the deprecated idempotencyKey, not both");
634
+ }
635
+ return this.req("POST", path, { auth: this.writeAuth(), body, headers: { "idempotency-key": idempotencyKey } });
636
+ }
637
+ const scope = resolveWitnessScope(body.scope);
638
+ try {
639
+ const answer = await this.req("POST", path, { auth: this.writeAuth(), body: { ...body, scope } });
640
+ return scopedProposeResult(answer, scope);
641
+ } catch (err) {
642
+ throw scopedProposeError(err, scope);
643
+ }
552
644
  }
553
645
  /**
554
646
  * What happened to an intent whose propose or finalize answer was lost
@@ -588,10 +680,10 @@ var WitniumchainClient = class {
588
680
  // Users / account (/v1/account/*)
589
681
  // ────────────────────────────────────────────────────────────────────────
590
682
  getAccount() {
591
- return this.req("GET", "/v1/account", { auth: "SessionCookie" });
683
+ return this.req("GET", "/v1/account", { auth: "SessionOrBearer" });
592
684
  }
593
685
  getLedger() {
594
- return this.req("GET", "/v1/account/ledger", { auth: "SessionCookie" });
686
+ return this.req("GET", "/v1/account/ledger", { auth: "SessionOrBearer" });
595
687
  }
596
688
  /**
597
689
  * DEV-ONLY: hard-delete the authenticated user + their org + contracts +
@@ -803,6 +895,15 @@ var WitniumchainClient = class {
803
895
  url.searchParams.set("code_challenge", challenge);
804
896
  url.searchParams.set("code_challenge_method", "S256");
805
897
  if (args.prompt) url.searchParams.set("prompt", args.prompt);
898
+ if (args.maxAge !== void 0) {
899
+ if (!Number.isInteger(args.maxAge) || args.maxAge < 0) {
900
+ throw new WitniumchainApiError({
901
+ status: 0,
902
+ message: `WitniumchainClient: beginOAuthLogin \`maxAge\` must be a non-negative integer (got ${args.maxAge}).`
903
+ });
904
+ }
905
+ url.searchParams.set("max_age", String(args.maxAge));
906
+ }
806
907
  const storage = this.verifierStorageOrDefault();
807
908
  storage.set(state, verifier);
808
909
  storage.set(redirectUriKey(state), args.redirectUri);
@@ -968,6 +1069,7 @@ var WitniumchainClient = class {
968
1069
  this.accessToken = void 0;
969
1070
  this.accessTokenFromSession = false;
970
1071
  this.refreshToken = void 0;
1072
+ this.idToken = void 0;
971
1073
  this.hasRefreshCookie = false;
972
1074
  this.sessionExchangeInFlight = void 0;
973
1075
  this.refreshInFlight = void 0;
@@ -1026,6 +1128,47 @@ var WitniumchainClient = class {
1026
1128
  signOut() {
1027
1129
  this.invalidateCredentials();
1028
1130
  }
1131
+ /**
1132
+ * End the session at the authorization server (OIDC RP-Initiated Logout).
1133
+ *
1134
+ * Builds the `end_session_endpoint` URL with `id_token_hint` (the ID token
1135
+ * from {@link completeOAuthLogin}), `client_id` and
1136
+ * `post_logout_redirect_uri`, then forgets every in-memory credential like
1137
+ * {@link signOut}. The caller does the redirect
1138
+ * (`window.location.assign(result.logoutUrl)`).
1139
+ *
1140
+ * Throws when no `oauthClientId` is configured, when this client holds no
1141
+ * ID token (the login was not completed here, or it did not ask for
1142
+ * `openid`), or when the discovery document has no `end_session_endpoint`.
1143
+ */
1144
+ async beginOAuthLogout(args) {
1145
+ if (!this.oauthClientId) {
1146
+ throw new WitniumchainApiError({
1147
+ status: 0,
1148
+ message: "WitniumchainClient: beginOAuthLogout requires `oauthClientId` to be set on the constructor."
1149
+ });
1150
+ }
1151
+ if (!this.idToken) {
1152
+ throw new WitniumchainApiError({
1153
+ status: 0,
1154
+ message: "WitniumchainClient: beginOAuthLogout needs the ID token from completeOAuthLogin (request the `openid` scope and complete the login with this client)."
1155
+ });
1156
+ }
1157
+ const discovery = await this.fetchDiscovery();
1158
+ if (!discovery.end_session_endpoint) {
1159
+ throw new WitniumchainApiError({
1160
+ status: 0,
1161
+ message: "OIDC discovery doc has no `end_session_endpoint`: the authorization server does not offer RP-initiated logout."
1162
+ });
1163
+ }
1164
+ const url = new URL(discovery.end_session_endpoint);
1165
+ url.searchParams.set("id_token_hint", this.idToken);
1166
+ url.searchParams.set("client_id", this.oauthClientId);
1167
+ url.searchParams.set("post_logout_redirect_uri", args.postLogoutRedirectUri);
1168
+ if (args.state !== void 0) url.searchParams.set("state", args.state);
1169
+ this.invalidateCredentials();
1170
+ return { logoutUrl: url.toString() };
1171
+ }
1029
1172
  // ────────────────────────────────────────────────────────────────────────
1030
1173
  // Internal: OAuth flow helpers
1031
1174
  // ────────────────────────────────────────────────────────────────────────
@@ -1068,6 +1211,7 @@ var WitniumchainClient = class {
1068
1211
  return {
1069
1212
  authorization_endpoint: parsed.authorization_endpoint,
1070
1213
  token_endpoint: parsed.token_endpoint,
1214
+ end_session_endpoint: parsed.end_session_endpoint,
1071
1215
  issuer: parsed.issuer ?? this.baseUrl
1072
1216
  };
1073
1217
  })();
@@ -1119,6 +1263,7 @@ var WitniumchainClient = class {
1119
1263
  });
1120
1264
  }
1121
1265
  this.accessToken = tokens.access_token;
1266
+ if (tokens.id_token) this.idToken = tokens.id_token;
1122
1267
  this.accessTokenFromSession = false;
1123
1268
  if (tokens.refresh_token) {
1124
1269
  this.refreshToken = tokens.refresh_token;
@@ -1208,9 +1353,11 @@ var WitniumchainClient = class {
1208
1353
  headers,
1209
1354
  body: bodyString,
1210
1355
  signal: controller.signal,
1211
- // Send cookies cross-origin when the consumer is a browser using
1212
- // SessionCookie auth via document.cookie.
1213
- credentials: "include"
1356
+ // A request that carries a bearer credential sends no cookies: an
1357
+ // OAuth client on another site must not depend on (or leak) a
1358
+ // third-party cookie. Everything else sends cookies cross-origin for
1359
+ // a browser using the cookie session.
1360
+ credentials: headers["authorization"] === void 0 ? "include" : "omit"
1214
1361
  });
1215
1362
  } catch (err) {
1216
1363
  throw new WitniumchainApiError({
@@ -1333,7 +1480,7 @@ var WitniumchainClient = class {
1333
1480
  return;
1334
1481
  }
1335
1482
  case "SessionOrBearer": {
1336
- if (this.accessToken) headers["authorization"] = `Bearer ${this.accessToken}`;
1483
+ if (this.accessToken && !this.accessTokenFromSession) headers["authorization"] = `Bearer ${this.accessToken}`;
1337
1484
  else if (this.cfg.sessionCookie) headers["cookie"] = `wac_session=${this.cfg.sessionCookie}`;
1338
1485
  return;
1339
1486
  }
@@ -1926,9 +2073,8 @@ var WitniumchainApiKeyClient = class {
1926
2073
  sign(body, requestId) {
1927
2074
  return this.inner.sign(body, requestId);
1928
2075
  }
1929
- /** Propose a witness on the org's contract; reserves one credit. */
1930
2076
  proposeWitnessV5(contractAddress, body, idempotencyKey) {
1931
- return this.inner.proposeWitnessV5(contractAddress, body, idempotencyKey);
2077
+ return idempotencyKey === void 0 ? this.inner.proposeWitnessV5(contractAddress, body) : this.inner.proposeWitnessV5(contractAddress, body, idempotencyKey);
1932
2078
  }
1933
2079
  /** Submit the signature for an intent this key proposed. */
1934
2080
  signWitnessV5(contractAddress, intentId, body) {
@@ -2074,6 +2220,6 @@ var ownerKeyFile = {
2074
2220
  sign: signWithOwnerKeyFile
2075
2221
  };
2076
2222
 
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 };
2223
+ 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
2224
  //# sourceMappingURL=index.mjs.map
2079
2225
  //# sourceMappingURL=index.mjs.map