@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.d.ts CHANGED
@@ -6533,7 +6533,7 @@ interface paths$1 {
6533
6533
  put?: never;
6534
6534
  /**
6535
6535
  * Propose a v5 witness (metered)
6536
- * @description Reserves one credit and forwards to chain-api v5. Auth is an OAuth Bearer token (the URL contract must be the user's) or an org API key (its organization's active contract). 120 proposes per minute per caller. Pass an `Idempotency-Key` HTTP header (the SDK auto-generates one if omitted) so retries dedupe at both the accounts reservation layer and chain-api propose.
6536
+ * @description Proposes the witness of `dataId` in the witness `scope`. Auth is an OAuth Bearer token (the URL contract must be the user's) or an org API key (its organization's active contract). 120 proposes per minute per caller. A scope holds at most one witness per dataId, ever. When it already holds it, the answer is 200 with that witness and `outcome: "existing"`, and nothing is charged. Otherwise one credit is reserved and the answer is 201, an intent to sign and finalize, `outcome: "created"`; a retry while it is in flight gets the same intent, and a failed, cancelled or expired attempt frees the scope. The same scope and dataId with another `userTimestamp`, `revealAfter` or `drandRound` is a 409 (`tlockCiphertext` is not compared: tlock encryption is randomized). Deprecated for one release: no `scope` and an `Idempotency-Key` header instead (per-caller key, no `outcome`).
6537
6537
  */
6538
6538
  post: {
6539
6539
  parameters: {
@@ -6547,6 +6547,8 @@ interface paths$1 {
6547
6547
  requestBody?: {
6548
6548
  content: {
6549
6549
  "application/json": {
6550
+ /** @description The witness scope: the SHA-256 of a key you choose, as 64 hex characters (case-insensitive). A scope holds at most one witness per dataId, ever, shared by every caller on the contract. Hash a date for "once per day", a project id for "once per project", a record id for a pipeline, or 32 random bytes for a new witness. Same scope and dataId: the same witness (`outcome: "existing"`, not charged). Required; for one release a propose without it may still send the deprecated `Idempotency-Key` header instead. */
6551
+ scope?: string;
6550
6552
  /** @description Content hash being witnessed. */
6551
6553
  dataId: string;
6552
6554
  /** @description Ed25519 public keys whose signatures must be collected before finalize. */
@@ -6567,6 +6569,31 @@ interface paths$1 {
6567
6569
  };
6568
6570
  };
6569
6571
  responses: {
6572
+ /** @description Success */
6573
+ 200: {
6574
+ headers: {
6575
+ [name: string]: unknown;
6576
+ };
6577
+ content: {
6578
+ "application/json": {
6579
+ /**
6580
+ * @description The scope already holds the witness for this dataId: this call created nothing and charged nothing.
6581
+ * @enum {string}
6582
+ */
6583
+ outcome: "existing";
6584
+ /**
6585
+ * Format: uuid
6586
+ * @description UUID minted at propose time. Identifies the in-flight v5 witness intent until finalize; once finalized, the intent maps to an on-chain witnessId returned in the finalize response.
6587
+ */
6588
+ intentId: string;
6589
+ /** @description 32-byte hash, lower-case hex without 0x prefix. */
6590
+ witnessId: string;
6591
+ blockNumber: number;
6592
+ /** @description Block timestamp of the block that created the witness (unix seconds): when it was made. */
6593
+ chainTimestamp: number;
6594
+ };
6595
+ };
6596
+ };
6570
6597
  /** @description Created */
6571
6598
  201: {
6572
6599
  headers: {
@@ -6586,6 +6613,11 @@ interface paths$1 {
6586
6613
  /** @description Prepare-record TTL on chain-api. Sign + finalize within this window. */
6587
6614
  expiresInSeconds: number;
6588
6615
  requiredSigners: string[];
6616
+ /**
6617
+ * @description Set on a scoped propose: this intent creates the witness in the scope (sign and finalize it). A retry while the intent is in flight gets the same intent. Absent on the deprecated Idempotency-Key path.
6618
+ * @enum {string}
6619
+ */
6620
+ outcome?: "created";
6589
6621
  };
6590
6622
  };
6591
6623
  };
@@ -6689,6 +6721,41 @@ interface paths$1 {
6689
6721
  };
6690
6722
  };
6691
6723
  };
6724
+ /** @description Conflict */
6725
+ 409: {
6726
+ headers: {
6727
+ [name: string]: unknown;
6728
+ };
6729
+ content: {
6730
+ "application/json": {
6731
+ /**
6732
+ * @description `scope_details_mismatch`: the scope holds (or is creating) the witness for this dataId with another userTimestamp, revealAfter or drandRound (v5). `scope_in_progress`: an attempt this request cannot join is in flight in the scope (another caller, or your own with another body); retry later. `scope_registry_mismatch`: proposed on another registry version.
6733
+ * @enum {string}
6734
+ */
6735
+ code: "scope_details_mismatch" | "scope_in_progress" | "scope_registry_mismatch";
6736
+ message: string;
6737
+ scope: string;
6738
+ /** @description The witness already in the scope (`scope_details_mismatch` once it is mined). */
6739
+ witnessId?: string;
6740
+ } | {
6741
+ /**
6742
+ * @description HTTP status code
6743
+ * @example 400
6744
+ */
6745
+ statusCode?: number;
6746
+ /**
6747
+ * @description Short error label
6748
+ * @example Bad Request
6749
+ */
6750
+ error?: string;
6751
+ /**
6752
+ * @description Human-readable error message. Validation errors from `ZodError.flatten()` may be returned as an array.
6753
+ * @example Validation failed
6754
+ */
6755
+ message: string | string[];
6756
+ };
6757
+ };
6758
+ };
6692
6759
  /** @description Too Many Requests */
6693
6760
  429: {
6694
6761
  headers: {
@@ -15783,7 +15850,40 @@ type RevokeWitnessRequest = Req<'/v1/contracts/{contractAddress}/witnesses/{witn
15783
15850
  type RevokeWitnessResponse = Res<'/v1/contracts/{contractAddress}/witnesses/{witnessId}/revoke', 'post'>;
15784
15851
  type GetWitnessResponse = Res<'/v1/contracts/{contractAddress}/witnesses/{witnessId}', 'get'>;
15785
15852
  type ProposeWitnessV5Request = Req<'/v5/contracts/{contractAddress}/witnesses/propose', 'post'>;
15786
- type ProposeWitnessV5Response = Res<'/v5/contracts/{contractAddress}/witnesses/propose', 'post'>;
15853
+ /** accounts' answer to a v5 propose: 201 (an intent) or 200 (the scope already holds the witness). */
15854
+ type ProposeWitnessV5Answer = Res<'/v5/contracts/{contractAddress}/witnesses/propose', 'post'>;
15855
+ type ProposeWitnessV5Intent = Extract<ProposeWitnessV5Answer, {
15856
+ payloadToSign: string;
15857
+ }>;
15858
+ /**
15859
+ * A scoped propose that created the witness: an intent to sign and
15860
+ * finalize. `scope` is the one the propose ran in (the caller's, or the
15861
+ * one the SDK generated).
15862
+ */
15863
+ type ProposeWitnessV5Created = Omit<ProposeWitnessV5Intent, 'outcome'> & {
15864
+ outcome: 'created';
15865
+ scope: string;
15866
+ };
15867
+ /**
15868
+ * The scope already held the witness for this dataId: nothing was created
15869
+ * or charged, and there is nothing to sign. `witnessId` and
15870
+ * `chainTimestamp` say which witness and when it was made.
15871
+ */
15872
+ type ProposeWitnessV5Existing = Extract<ProposeWitnessV5Answer, {
15873
+ outcome: 'existing';
15874
+ }> & {
15875
+ scope: string;
15876
+ };
15877
+ /** What {@link WitniumchainClient.proposeWitnessV5} resolves to; branch on `outcome`. */
15878
+ type ProposeWitnessV5Result = ProposeWitnessV5Created | ProposeWitnessV5Existing;
15879
+ /** @deprecated The body of a propose on the deprecated `Idempotency-Key` path (no `scope`). */
15880
+ type ProposeWitnessV5LegacyRequest = Omit<ProposeWitnessV5Request, 'scope'>;
15881
+ /** @deprecated The answer on the deprecated `Idempotency-Key` path: an intent, no `outcome`, no `scope`. */
15882
+ type ProposeWitnessV5LegacyResponse = Omit<ProposeWitnessV5Intent, 'outcome'>;
15883
+ /** The `code` of a 409 to a scoped propose, from the spec's 409 body. */
15884
+ type WitnessScopeConflictCode = Extract<JsonBody<paths$1['/v5/contracts/{contractAddress}/witnesses/propose']['post']['responses'][409]>, {
15885
+ code: string;
15886
+ }>['code'];
15787
15887
  type SubmitSignatureV5Request = Req<'/v5/contracts/{contractAddress}/witnesses/{intentId}/sign', 'post'>;
15788
15888
  type SubmitSignatureV5Response = Res<'/v5/contracts/{contractAddress}/witnesses/{intentId}/sign', 'post'>;
15789
15889
  type FinalizeWitnessV5Response = Res<'/v5/contracts/{contractAddress}/witnesses/{intentId}/finalize', 'post'>;
@@ -16231,7 +16331,33 @@ declare class WitniumchainClient {
16231
16331
  finalizeWitness(contractAddress: string, witnessId: string): Promise<FinalizeWitnessResponse>;
16232
16332
  revokeWitness(contractAddress: string, witnessId: string, body: RevokeWitnessRequest, idempotencyKey?: string): Promise<RevokeWitnessResponse>;
16233
16333
  getWitness(contractAddress: string, witnessId: string): Promise<GetWitnessResponse>;
16234
- proposeWitnessV5(contractAddress: string, body: ProposeWitnessV5Request, idempotencyKey?: string): Promise<ProposeWitnessV5Response>;
16334
+ /**
16335
+ * Propose the witness of `body.dataId` in the witness scope `body.scope`
16336
+ * (64 hex, the SHA-256 of a key you choose; see {@link witnessScopeFor}).
16337
+ * Without a scope the SDK generates a random one, so the call is a new
16338
+ * witness; the scope comes back in the result and in every error, for a
16339
+ * retry that can never create or charge a second witness.
16340
+ *
16341
+ * - `outcome: "created"`: an intent; sign and finalize it as before.
16342
+ * One credit is reserved.
16343
+ * - `outcome: "existing"`: the scope already held the witness for this
16344
+ * dataId (`witnessId`, `blockNumber`, `chainTimestamp`). Nothing was
16345
+ * created or charged; there is nothing to sign.
16346
+ *
16347
+ * Errors are {@link WitnessProposeError} (with `scope`); a scope 409 is
16348
+ * {@link WitnessScopeConflictError} (with `code` and `witnessId`).
16349
+ */
16350
+ proposeWitnessV5(contractAddress: string, body: ProposeWitnessV5Request): Promise<ProposeWitnessV5Result>;
16351
+ /**
16352
+ * @deprecated The `Idempotency-Key` path for proposes works for one more
16353
+ * release of accounts, then it is removed. Pass a `scope` in the body
16354
+ * instead (`await witnessScopeFor(key)`, or the key itself when it is
16355
+ * already 64 hex). The rule changes with it: a scope holds one witness
16356
+ * per dataId, shared by every caller on the contract, where a key was
16357
+ * one request per caller. The answer here has no `outcome` and no
16358
+ * `scope`; its errors are plain {@link WitniumchainApiError}s.
16359
+ */
16360
+ proposeWitnessV5(contractAddress: string, body: ProposeWitnessV5LegacyRequest, idempotencyKey: string): Promise<ProposeWitnessV5LegacyResponse>;
16235
16361
  /**
16236
16362
  * What happened to an intent whose propose or finalize answer was lost
16237
16363
  * (read-only, the caller's own contract): accounts' stored finalize
@@ -16807,8 +16933,21 @@ declare class WitniumchainApiKeyClient {
16807
16933
  me(): Promise<ApiKeySelfResponse>;
16808
16934
  /** Sign a payload with the key's own signing key (`delegatedKeyId` from {@link me}). */
16809
16935
  sign(body: SignRequest, requestId?: string): Promise<SignResponse>;
16810
- /** Propose a witness on the org's contract; reserves one credit. */
16811
- proposeWitnessV5(contractAddress: string, body: ProposeWitnessV5Request, idempotencyKey?: string): Promise<ProposeWitnessV5Response>;
16936
+ /**
16937
+ * Propose a witness on the org's contract in the witness scope
16938
+ * `body.scope` (generated when absent; returned in the result and in
16939
+ * every error). `outcome: "created"` reserves one credit and is an
16940
+ * intent to sign and finalize; `outcome: "existing"` is the witness the
16941
+ * scope already held, not charged. See
16942
+ * {@link WitniumchainClient.proposeWitnessV5}.
16943
+ */
16944
+ proposeWitnessV5(contractAddress: string, body: ProposeWitnessV5Request): Promise<ProposeWitnessV5Result>;
16945
+ /**
16946
+ * @deprecated The `Idempotency-Key` path for proposes works for one more
16947
+ * release of accounts. Pass a `scope` in the body instead; see
16948
+ * {@link WitniumchainClient.proposeWitnessV5}.
16949
+ */
16950
+ proposeWitnessV5(contractAddress: string, body: ProposeWitnessV5LegacyRequest, idempotencyKey: string): Promise<ProposeWitnessV5LegacyResponse>;
16812
16951
  /** Submit the signature for an intent this key proposed. */
16813
16952
  signWitnessV5(contractAddress: string, intentId: string, body: SubmitSignatureV5Request): Promise<SubmitSignatureV5Response>;
16814
16953
  /** Finalize an intent this key proposed; returns the witness id. */
@@ -16834,6 +16973,61 @@ declare class WitniumchainApiError extends Error {
16834
16973
  body?: unknown;
16835
16974
  });
16836
16975
  }
16976
+ /**
16977
+ * Every error of a scoped witness propose (`proposeWitnessV5` without the
16978
+ * deprecated idempotency key): API errors, network errors and timeouts, a
16979
+ * response that broke off or is malformed. Carries the `scope` the propose
16980
+ * ran in, so the caller can retry in the same scope: a retry can never
16981
+ * create or charge a second witness for the same dataId. `status` is 0 when
16982
+ * there was no HTTP error status; the original error is `cause`.
16983
+ */
16984
+ declare class WitnessProposeError extends WitniumchainApiError {
16985
+ /** The scope of the failed propose (64 lowercase hex). */
16986
+ readonly scope: string;
16987
+ constructor(cause: unknown, scope: string);
16988
+ }
16989
+ /**
16990
+ * A 409 to a scoped propose; branch on `code`:
16991
+ * - `scope_details_mismatch`: the scope holds (or is creating) the witness
16992
+ * for this dataId with another `userTimestamp`, `revealAfter` or
16993
+ * `drandRound`. `witnessId` is that witness once it is mined. Put the
16994
+ * detail into the scope, or use another scope.
16995
+ * - `scope_in_progress`: an attempt in the scope is in flight that this
16996
+ * request cannot join (another caller's, or your own with another body,
16997
+ * e.g. a re-encrypted `tlockCiphertext`: resend the identical body).
16998
+ * Retry later: once it is mined the answer is `existing`; once it failed
16999
+ * or expired the scope is free.
17000
+ * - `scope_registry_mismatch`: the scope's witness was proposed on the
17001
+ * other registry version.
17002
+ */
17003
+ declare class WitnessScopeConflictError extends WitnessProposeError {
17004
+ readonly code: WitnessScopeConflictCode;
17005
+ /** The witness already in the scope (`scope_details_mismatch` once it is mined). */
17006
+ readonly witnessId: string | undefined;
17007
+ constructor(cause: WitniumchainApiError, scope: string, code: WitnessScopeConflictCode, witnessId: string | undefined);
17008
+ }
17009
+
17010
+ /**
17011
+ * Witness scopes. A scope holds at most one witness per content hash
17012
+ * (`dataId`), ever, shared by every caller on the contract. The scope is
17013
+ * the SHA-256 of a key the caller chooses, as 64 hex characters: hash a
17014
+ * date for "once per day", a project id for "once per project", a record id
17015
+ * for a pipeline, or use 32 random bytes for a new witness.
17016
+ *
17017
+ * - Same scope and dataId: the same witness (`outcome: "existing"`, not
17018
+ * charged), whoever proposed it.
17019
+ * - Same scope, another dataId: another witness in that scope.
17020
+ * - Duplicates on purpose: a new random scope.
17021
+ */
17022
+
17023
+ /** A new scope: 32 random bytes as 64 lowercase hex. Every propose in it is a new witness. */
17024
+ declare function randomWitnessScope(): string;
17025
+ /**
17026
+ * The scope of a key you choose: SHA-256 of its UTF-8 bytes, 64 lowercase
17027
+ * hex. Witnium never sees the key itself. `witnessScopeFor('2026-11-06')`
17028
+ * holds one witness per dataId for that day.
17029
+ */
17030
+ declare function witnessScopeFor(key: string): Promise<string>;
16837
17031
 
16838
17032
  /**
16839
17033
  * Canonical owner-operation messages.
@@ -16941,4 +17135,4 @@ declare const ownerKeyFile: {
16941
17135
  sign: typeof signWithOwnerKeyFile;
16942
17136
  };
16943
17137
 
16944
- export { type AcceptInviteResponse, type AccountContractStatusResponse, type AccountResponse, AccountSecurity, type AccountSecurityResponse, type paths$1 as AccountsPaths, type AddContractKeyRequest, type AddPasswordTotpResponse, type AddSigningKeyRequest$1 as AddSigningKeyRequest, type AddSigningKeyResponse, type ApiKeySelfResponse, type ApproveSigningKeyRequest, type BeginOAuthLoginArgs, type BeginOAuthLoginResult, type paths as ChainPaths, type CheckoutRequest, type CheckoutResponse, type ChooseCustodyRequest, type ChooseCustodyResponse, type ContractActivityResponse, type ContractOwnerOpResponse, type CreateApiKeyRequest, type CreateApiKeyResponse, type CreateOrgRequest, type CreateOrgResponse, DashboardKey, type DashboardKeyResponse, DelegatedKeys, type DeploySelfCustodyRequest, type DeploySelfCustodyResponse, Enrollment, type EnrollmentCompleteResponse, type EnrollmentStateResponse, type FinalizeWitnessResponse, type ForgotPasswordRequest, type ForgotPasswordResponse, type GetWitnessResponse, type HealthLiveResponse, type HealthReadyResponse, type InviteMemberRequest, type InviteMemberResponse, type LedgerResponse, type ListApiKeysResponse, type ListDelegatedKeysResponse, type ListOauthSessionsResponse, type LoginRequest, type LoginResponse, type LogoutResponse, type MembersListResponse, type MessageResponse, type MfaProofRequest, type OAuthTokenSnapshot, OWNER_KEY_FILE_FORMAT, OWNER_OP, OauthNamespace, OauthSessions, OrgApiKeys, OrgContract, OrgMembers, Organization, type OwnerKeyFile, type OwnerOpName, type OwnerSigner, type PauseRequest$1 as PauseRequest, type PauseResponse, type PkceVerifierStorage, type PortalResponse, type PrepareDelegatedKeyRequest, type PreparedDelegatedKeyResponse, type ProposeWitnessRequest, type ProposeWitnessResponse, type ProvisionContractRequest, type ProvisionContractResponse, type ProvisionDelegatedKeyArgs, type ProvisionDelegatedKeyResult, Recovery, type RecoveryCodesResponse, type RecoveryStatusResponse, type ReissueProvisioningTokenResponse, type RemoveContractKeyResponse, type RemoveMemberResponse, type RenameOrgRequest, type RenameOrgResponse, type ResendInviteResponse, type ResetAccountResponse, type ResetPasswordRequest, type ResetPasswordResponse, type RevokeDelegatedKeyResponse, type RevokeSigningKeyRequest$1 as RevokeSigningKeyRequest, type RevokeSigningKeyResponse, type RevokeWitnessRequest, type RevokeWitnessResponse, type SessionStartedResponse, type SetMemberRoleRequest, type SetMemberRoleResponse, type SignRequest, type SignResponse, type SignWitnessRequest, type SignWitnessResponse, type SignedRequestSigner, type SigningKeyRequestCreate, type SigningKeyRequestView, type SigningKeyRequestsResponse, type SigningKeyView, SigningKeys, type SigningKeysResponse, type SignupRequest, type SignupResponse, type StepUpProof, type SubmitDelegatedKeyRequest, type SubmitDelegatedKeyResponse, Subscriptions, type SuspendMemberResponse, type TotpSetupResponse, type UnpauseRequest, type UnpauseResponse, type VerifySignupRequest, type VerifySignupResponse, type WitnessIntentRecoveryV5, WitniumchainApiError, WitniumchainApiKeyClient, type WitniumchainApiKeyClientConfig, WitniumchainChainAdminClient, type WitniumchainChainAdminClientConfig, WitniumchainClient, type WitniumchainClientConfig, buildAddSigningKeyPayload, buildPausePayload, buildRevokeSigningKeyPayload, buildUnpausePayload, defaultVerifierStorage, generateOwnerKeyFile, ownerKeyFile, ownerKeyFileName, parseOwnerKeyFile, serializeOwnerKeyFile, signWithOwnerKeyFile };
17138
+ export { type AcceptInviteResponse, type AccountContractStatusResponse, type AccountResponse, AccountSecurity, type AccountSecurityResponse, type paths$1 as AccountsPaths, type AddContractKeyRequest, type AddPasswordTotpResponse, type AddSigningKeyRequest$1 as AddSigningKeyRequest, type AddSigningKeyResponse, type ApiKeySelfResponse, type ApproveSigningKeyRequest, type BeginOAuthLoginArgs, type BeginOAuthLoginResult, type paths as ChainPaths, type CheckoutRequest, type CheckoutResponse, type ChooseCustodyRequest, type ChooseCustodyResponse, type ContractActivityResponse, type ContractOwnerOpResponse, type CreateApiKeyRequest, type CreateApiKeyResponse, type CreateOrgRequest, type CreateOrgResponse, DashboardKey, type DashboardKeyResponse, DelegatedKeys, type DeploySelfCustodyRequest, type DeploySelfCustodyResponse, Enrollment, type EnrollmentCompleteResponse, type EnrollmentStateResponse, type FinalizeWitnessResponse, type ForgotPasswordRequest, type ForgotPasswordResponse, type GetWitnessResponse, type HealthLiveResponse, type HealthReadyResponse, type InviteMemberRequest, type InviteMemberResponse, type LedgerResponse, type ListApiKeysResponse, type ListDelegatedKeysResponse, type ListOauthSessionsResponse, type LoginRequest, type LoginResponse, type LogoutResponse, type MembersListResponse, type MessageResponse, type MfaProofRequest, type OAuthTokenSnapshot, OWNER_KEY_FILE_FORMAT, OWNER_OP, OauthNamespace, OauthSessions, OrgApiKeys, OrgContract, OrgMembers, Organization, type OwnerKeyFile, type OwnerOpName, type OwnerSigner, type PauseRequest$1 as PauseRequest, type PauseResponse, type PkceVerifierStorage, type PortalResponse, type PrepareDelegatedKeyRequest, type PreparedDelegatedKeyResponse, type ProposeWitnessRequest, type ProposeWitnessResponse, type ProposeWitnessV5Created, type ProposeWitnessV5Existing, type ProposeWitnessV5LegacyRequest, type ProposeWitnessV5LegacyResponse, type ProposeWitnessV5Request, type ProposeWitnessV5Result, type ProvisionContractRequest, type ProvisionContractResponse, type ProvisionDelegatedKeyArgs, type ProvisionDelegatedKeyResult, Recovery, type RecoveryCodesResponse, type RecoveryStatusResponse, type ReissueProvisioningTokenResponse, type RemoveContractKeyResponse, type RemoveMemberResponse, type RenameOrgRequest, type RenameOrgResponse, type ResendInviteResponse, type ResetAccountResponse, type ResetPasswordRequest, type ResetPasswordResponse, type RevokeDelegatedKeyResponse, type RevokeSigningKeyRequest$1 as RevokeSigningKeyRequest, type RevokeSigningKeyResponse, type RevokeWitnessRequest, type RevokeWitnessResponse, type SessionStartedResponse, type SetMemberRoleRequest, type SetMemberRoleResponse, type SignRequest, type SignResponse, type SignWitnessRequest, type SignWitnessResponse, type SignedRequestSigner, type SigningKeyRequestCreate, type SigningKeyRequestView, type SigningKeyRequestsResponse, type SigningKeyView, SigningKeys, type SigningKeysResponse, type SignupRequest, type SignupResponse, type StepUpProof, type SubmitDelegatedKeyRequest, type SubmitDelegatedKeyResponse, Subscriptions, type SuspendMemberResponse, type TotpSetupResponse, type UnpauseRequest, type UnpauseResponse, type VerifySignupRequest, type VerifySignupResponse, type WitnessIntentRecoveryV5, WitnessProposeError, type WitnessScopeConflictCode, WitnessScopeConflictError, WitniumchainApiError, WitniumchainApiKeyClient, type WitniumchainApiKeyClientConfig, WitniumchainChainAdminClient, type WitniumchainChainAdminClientConfig, WitniumchainClient, type WitniumchainClientConfig, buildAddSigningKeyPayload, buildPausePayload, buildRevokeSigningKeyPayload, buildUnpausePayload, defaultVerifierStorage, generateOwnerKeyFile, ownerKeyFile, ownerKeyFileName, parseOwnerKeyFile, randomWitnessScope, serializeOwnerKeyFile, signWithOwnerKeyFile, witnessScopeFor };
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(
@@ -528,29 +622,24 @@ var WitniumchainClient = class {
528
622
  { auth: "Public" }
529
623
  );
530
624
  }
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
625
  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
- );
626
+ const path = `/v5/contracts/${encodeURIComponent(contractAddress)}/witnesses/propose`;
627
+ if (idempotencyKey !== void 0) {
628
+ if (idempotencyKey.trim() === "") {
629
+ throw new Error("proposeWitnessV5: idempotencyKey must not be empty (pass a `scope` in the body instead)");
630
+ }
631
+ if (body.scope !== void 0) {
632
+ throw new Error("proposeWitnessV5: pass either a `scope` in the body or the deprecated idempotencyKey, not both");
633
+ }
634
+ return this.req("POST", path, { auth: this.writeAuth(), body, headers: { "idempotency-key": idempotencyKey } });
635
+ }
636
+ const scope = resolveWitnessScope(body.scope);
637
+ try {
638
+ const answer = await this.req("POST", path, { auth: this.writeAuth(), body: { ...body, scope } });
639
+ return scopedProposeResult(answer, scope);
640
+ } catch (err) {
641
+ throw scopedProposeError(err, scope);
642
+ }
554
643
  }
555
644
  /**
556
645
  * What happened to an intent whose propose or finalize answer was lost
@@ -1928,9 +2017,8 @@ var WitniumchainApiKeyClient = class {
1928
2017
  sign(body, requestId) {
1929
2018
  return this.inner.sign(body, requestId);
1930
2019
  }
1931
- /** Propose a witness on the org's contract; reserves one credit. */
1932
2020
  proposeWitnessV5(contractAddress, body, idempotencyKey) {
1933
- return this.inner.proposeWitnessV5(contractAddress, body, idempotencyKey);
2021
+ return idempotencyKey === void 0 ? this.inner.proposeWitnessV5(contractAddress, body) : this.inner.proposeWitnessV5(contractAddress, body, idempotencyKey);
1934
2022
  }
1935
2023
  /** Submit the signature for an intent this key proposed. */
1936
2024
  signWitnessV5(contractAddress, intentId, body) {
@@ -2091,6 +2179,8 @@ exports.Organization = Organization;
2091
2179
  exports.Recovery = Recovery;
2092
2180
  exports.SigningKeys = SigningKeys;
2093
2181
  exports.Subscriptions = Subscriptions;
2182
+ exports.WitnessProposeError = WitnessProposeError;
2183
+ exports.WitnessScopeConflictError = WitnessScopeConflictError;
2094
2184
  exports.WitniumchainApiError = WitniumchainApiError;
2095
2185
  exports.WitniumchainApiKeyClient = WitniumchainApiKeyClient;
2096
2186
  exports.WitniumchainChainAdminClient = WitniumchainChainAdminClient;
@@ -2104,7 +2194,9 @@ exports.generateOwnerKeyFile = generateOwnerKeyFile;
2104
2194
  exports.ownerKeyFile = ownerKeyFile;
2105
2195
  exports.ownerKeyFileName = ownerKeyFileName;
2106
2196
  exports.parseOwnerKeyFile = parseOwnerKeyFile;
2197
+ exports.randomWitnessScope = randomWitnessScope;
2107
2198
  exports.serializeOwnerKeyFile = serializeOwnerKeyFile;
2108
2199
  exports.signWithOwnerKeyFile = signWithOwnerKeyFile;
2200
+ exports.witnessScopeFor = witnessScopeFor;
2109
2201
  //# sourceMappingURL=index.js.map
2110
2202
  //# sourceMappingURL=index.js.map