@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/README.md CHANGED
@@ -46,7 +46,7 @@ spec differs from the sha256 recorded in `specs/sources.json`, or when
46
46
  `src/generated/` is stale. The accounts service is a separate private repo, so
47
47
  CI cannot read it: `npm run openapi:verify:accounts` (with
48
48
  `WITNIUMCHAIN_ACCOUNTS_REPO` pointing at a clone) checks the recorded commit
49
- and the current `origin/main` there, and runs ahead of every `npm publish`.
49
+ and the tip of the branch it tracks there, and runs ahead of every `npm publish`.
50
50
  `npm run openapi:refresh` re-vendors both specs and regenerates the types.
51
51
 
52
52
  ## Install
@@ -69,6 +69,17 @@ throw at call time.
69
69
  | `adminToken` | `Authorization: Bearer <ADMIN_TOKEN>` | `/v1/admin/*` |
70
70
  | `signedRequest` | `X-Witnium-Key/Timestamp/Signature` | `/v1/contracts/{addr}/witnesses/{propose,sign,finalize,revoke}` |
71
71
 
72
+ **Session or token.** The accounts routes an OAuth client such as the
73
+ WitniumChain dashboard calls (`me`, the ledger, billing checkout and portal,
74
+ the dashboard key, signing-key requests, contract pause and resume, the
75
+ org's owner operations, self-custody setup and keys) take either credential.
76
+ A client holding an OAuth `accessToken` sends it as `Authorization: Bearer`
77
+ with `credentials: 'omit'`, so no cookie is needed or sent; a client without
78
+ one (the account app) keeps its `wac_session` cookie, also when it has
79
+ minted a token from that session. Listing the team takes either too
80
+ (read-only); changes to the team or the org, API keys, OAuth sessions and
81
+ account security stay cookie-only.
82
+
72
83
  Public routes need no credential (`/v1/auth/{signup,verify,login,…}`,
73
84
  `/v1/contracts/provision`, `GET /v1/contracts/{addr}/witnesses/{id}`,
74
85
  `/health/*`).
@@ -132,15 +143,87 @@ const server = new WitniumchainApiKeyClient({
132
143
  });
133
144
 
134
145
  const me = await server.me(); // its contract and signing key
135
- const { intentId, payloadToSign } = await server.proposeWitnessV5(me.contractAddress, {
146
+ const proposed = await server.proposeWitnessV5(me.contractAddress, {
136
147
  dataId: sha256Hex,
137
148
  requiredSigners: [me.publicKey],
149
+ // no scope: the SDK generates one, so this is a new witness (see "Witness scopes")
138
150
  });
139
- const { signature } = await server.sign({ delegatedKeyId: me.delegatedKeyId, payload: Buffer.from(payloadToSign, 'utf8').toString('hex') });
140
- await server.signWitnessV5(me.contractAddress, intentId, { signerPubKey: me.publicKey, signature });
141
- const { witnessId } = await server.finalizeWitnessV5(me.contractAddress, intentId);
151
+ if (proposed.outcome === 'created') {
152
+ const { intentId, payloadToSign } = proposed;
153
+ const { signature } = await server.sign({ delegatedKeyId: me.delegatedKeyId, payload: Buffer.from(payloadToSign, 'utf8').toString('hex') });
154
+ await server.signWitnessV5(me.contractAddress, intentId, { signerPubKey: me.publicKey, signature });
155
+ const { witnessId } = await server.finalizeWitnessV5(me.contractAddress, intentId);
156
+ }
142
157
  ```
143
158
 
159
+ ### Witness scopes
160
+
161
+ A v5 propose runs in a **witness scope**: a scope holds at most one witness
162
+ per content hash (`dataId`), ever, shared by everyone who writes to the
163
+ contract (colleagues, API keys, MCP connections of the org).
164
+
165
+ - Same scope and `dataId`: the same witness, never a second one. Once it
166
+ is mined, a repeat gets `outcome: "existing"` with that witness and is
167
+ not charged. While your attempt is still in flight, a retry with the
168
+ identical body gets `outcome: "created"` with the same intent (sign and
169
+ finalize it as usual).
170
+ - Same scope, another `dataId`: another witness in that scope.
171
+ - Duplicates on purpose: a new scope.
172
+
173
+ The scope is the SHA-256 of a key you choose, as 64 hex characters; Witnium
174
+ never sees the key. Pass it as `scope` in the propose body:
175
+
176
+ ```ts
177
+ import { witnessScopeFor, WitnessProposeError, WitnessScopeConflictError } from '@witnium/witniumchain';
178
+
179
+ const scope = await witnessScopeFor(`daily-report:${today}`); // once per day; or a project id, a record id
180
+ try {
181
+ const proposed = await server.proposeWitnessV5(me.contractAddress, { dataId, requiredSigners: [me.publicKey], scope });
182
+ if (proposed.outcome === 'existing') {
183
+ // Already witnessed: proposed.witnessId, made at proposed.chainTimestamp (unix seconds). Nothing to sign.
184
+ } else {
185
+ // 'created': sign proposed.payloadToSign and finalize proposed.intentId, as above.
186
+ }
187
+ } catch (err) {
188
+ if (err instanceof WitnessScopeConflictError) {
189
+ // err.code: 'scope_details_mismatch' (this dataId is in the scope with another
190
+ // userTimestamp, revealAfter or drandRound; err.witnessId once mined),
191
+ // 'scope_in_progress' (an attempt you cannot join is in flight: retry later,
192
+ // with the identical body), or 'scope_registry_mismatch'.
193
+ } else if (err instanceof WitnessProposeError) {
194
+ // Any other failure: an API error, a network error or timeout, a malformed
195
+ // answer (err.status 0, err.cause). Retry with { ...body, scope: err.scope }:
196
+ // the retry can never create or charge a second witness.
197
+ }
198
+ throw err;
199
+ }
200
+ ```
201
+
202
+ Without a `scope`, the SDK generates 32 random bytes before the request
203
+ (`randomWitnessScope()`) and returns them as `scope` in the result and in
204
+ every `WitnessProposeError`. The SDK does not retry a failed propose for you
205
+ (its only resend is after a token refresh, with the same scope): to retry,
206
+ call `proposeWitnessV5` again with `err.scope`. Store the scope before you
207
+ rely on a retry: it is what makes the retry safe.
208
+
209
+ The details of a repeat must match: the same scope and `dataId` with another
210
+ `userTimestamp`, `revealAfter` or `drandRound` is a 409
211
+ `scope_details_mismatch`, never a second witness. A caller whose timestamp
212
+ naturally varies puts it in the scope key. A failed, cancelled or expired
213
+ attempt frees the scope; a revoked witness still occupies it.
214
+
215
+ **Deprecated: the `idempotencyKey` argument.** `proposeWitnessV5(addr, body,
216
+ idempotencyKey)` still sends the old `Idempotency-Key` header for one more
217
+ release of accounts, then the header path is removed. Its answer has no
218
+ `outcome` or `scope`, and passing both a key and a `scope` throws. Move to
219
+ `scope: await witnessScopeFor(key)` (or the key itself when it is already
220
+ 64 hex). The rule changes with it: a key was one request per caller (another
221
+ body under the same key was a 409); a scope is one witness per `dataId` for
222
+ the whole contract. The SDK no longer derives a key from the request body:
223
+ before this release, two proposes of the same content without a key were
224
+ merged into one witness forever; now each is a new witness unless you give
225
+ them the same scope.
226
+
144
227
  Org admins manage keys with the dashboard session: `client.apiKeys.create({ label })`
145
228
  (after a step-up; the secret is returned once), `client.apiKeys.list()`,
146
229
  `client.apiKeys.revoke(id)`.
@@ -205,8 +288,21 @@ const { keys } = await client.listDelegatedKeys();
205
288
 
206
289
  // 4. Sign-out clears in-memory tokens.
207
290
  client.signOut();
291
+
292
+ // Or end the session at the issuer too (RP-initiated logout). Needs the ID
293
+ // token from step 2, so ask for the `openid` scope.
294
+ const { logoutUrl } = await client.beginOAuthLogout({
295
+ postLogoutRedirectUri: 'https://your-app.example/signed-out',
296
+ });
297
+ window.location.assign(logoutUrl);
208
298
  ```
209
299
 
300
+ Step-up before a sensitive action: `beginOAuthLogin({ redirectUri, maxAge: 0 })`
301
+ makes the issuer re-authenticate the user; the new tokens carry a fresh
302
+ `auth_time`. `prompt: 'none'` asks for a token without any UI (renewal from
303
+ the issuer's session) and comes back with `error=login_required` when the
304
+ user has to sign in.
305
+
210
306
  ### OAuth API — delegated-key + sign
211
307
 
212
308
  ```ts
@@ -250,7 +346,9 @@ const intent = await sdk.proposeWitness('0x…', {
250
346
 
251
347
  ## Errors
252
348
 
253
- All non-2xx responses surface as `WitniumchainApiError`:
349
+ All non-2xx responses surface as `WitniumchainApiError` (a scoped v5
350
+ propose throws its subclasses `WitnessProposeError` and
351
+ `WitnessScopeConflictError`, see [Witness scopes](#witness-scopes)):
254
352
 
255
353
  ```ts
256
354
  import { WitniumchainApiError } from '@witnium/witniumchain';