@witnium/witniumchain 0.0.0-stage → 0.26.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.
@@ -0,0 +1,353 @@
1
+ # WitniumChain — Frontend Integration Guide
2
+
3
+ Audience: the team building the WitniumChain dashboard frontend. This is the
4
+ contract between the backend (accounts + chain-api) and your UI. It covers the
5
+ end-to-end user flows, where keys live, the recovery-file format, and the
6
+ known sharp edges discovered during backend validation.
7
+
8
+ The SDK that backs all of this is **`@witnium/witniumchain`** (npm). Every
9
+ flow below has a typed method on it.
10
+
11
+ ---
12
+
13
+ ## 1. The custody model — read this first
14
+
15
+ Two ed25519 keys are generated **client-side** at signup and never leave the
16
+ user's device in plaintext:
17
+
18
+ | Key | Controls | Used for |
19
+ |---|---|---|
20
+ | **Owner key** | The contract's signing-key set (add/revoke), pause/unpause | Authorizing changes. Never signs witnesses. |
21
+ | **Signing key** | — | Signing witnesses day-to-day |
22
+
23
+ Witnium only ever receives the **public** halves. The backend enforces
24
+ `ownerPublicKey !== initialSigningPublicKey`.
25
+
26
+ **Your job on the frontend:** generate these keys, store them encrypted, let
27
+ the user export/import them, and produce owner-key signatures when the backend
28
+ asks for them (the MCP-CUSTODY ceremony, §6). You are the custody surface. If
29
+ you lose the keys with no recovery file, the account's contract is
30
+ unrecoverable — there is no server-side escrow by design.
31
+
32
+ ### Recommended storage (production)
33
+
34
+ The throwaway test frontend stored keys as plain hex in `localStorage`. **Do
35
+ not ship that.** The intended production design:
36
+
37
+ - Wrap the two private keys with a key derived from a **WebAuthn PRF** assertion
38
+ (passkey). The user authenticates with their passkey to decrypt.
39
+ - Issue **recovery codes** at signup (one-time display) as the fallback when no
40
+ passkey is available (new device, lost authenticator).
41
+ - Persist the wrapped blob in IndexedDB.
42
+
43
+ The backend does not need to know how you wrap the keys — it only sees public
44
+ keys + signatures. But see §7 for the **same-origin requirement**, which is a
45
+ hard constraint on where this storage lives.
46
+
47
+ ---
48
+
49
+ ## 2. Install
50
+
51
+ ```bash
52
+ npm install @witnium/witniumchain
53
+ ```
54
+
55
+ ```ts
56
+ import { WitniumchainClient } from '@witnium/witniumchain';
57
+
58
+ const client = new WitniumchainClient({
59
+ baseUrl: 'https://auth.witniumchain.com', // accounts
60
+ chainBaseUrl: 'https://api.witniumchain.com', // chain-api (read methods)
61
+ });
62
+ ```
63
+
64
+ Generate keys with any ed25519 lib. The backend + SDK speak 64-hex-char
65
+ public keys (no `0x`). Example with `@noble/ed25519`:
66
+
67
+ ```ts
68
+ import * as ed from '@noble/ed25519';
69
+ const priv = ed.utils.randomPrivateKey();
70
+ const pub = await ed.getPublicKeyAsync(priv); // hex-encode both halves
71
+ ```
72
+
73
+ ---
74
+
75
+ ## 3. Signup → org → contract (one call)
76
+
77
+ `createOrg` is the self-serve path. It creates the admin user, the
78
+ organization, the org-admin membership, **and deploys the contract** with the
79
+ client-generated keys — all in one request.
80
+
81
+ ```ts
82
+ const result = await client.createOrg({
83
+ orgName: 'Acme Inc.',
84
+ adminEmail: 'you@example.com',
85
+ adminPassword: '≥12 chars',
86
+ ownerPublicKey: ownerPubHex,
87
+ initialSigningPublicKey: signingPubHex,
88
+ });
89
+ // → { orgId, userId, contractAddress, contractVersion }
90
+ ```
91
+
92
+ Persist the two private keys + `contractAddress` locally (wrapped, per §1) and
93
+ prompt a recovery-file download (§5) before doing anything else.
94
+
95
+ The verification email is sent to `adminEmail`; there is nothing to render.
96
+ The response never carries the verify token. If the email cannot be sent,
97
+ nothing is created and the call fails with a 502; retry the same request.
98
+ **The email is the login gate, not the contract-deploy gate**: the contract is
99
+ already live when this returns.
100
+
101
+ ---
102
+
103
+ ## 4. Auth flows
104
+
105
+ ### Email verify
106
+
107
+ ```ts
108
+ await client.verifyEmail(token); // GET /v1/auth/verify?token=…
109
+ ```
110
+
111
+ > ⚠️ This is a **GET**, not POST. (Caught in testing — easy to get wrong.)
112
+
113
+ ### Password login
114
+
115
+ ```ts
116
+ const res = await client.login({ email, password });
117
+ if (res.status === 'mfa_required') {
118
+ // NO session yet. Ask for the authenticator code (offer "use a recovery code").
119
+ await client.loginMfa({ code }); // or { recoveryCode }
120
+ }
121
+ // status 'authenticated': the wac_session cookie is set
122
+ ```
123
+
124
+ Always check `status`. A user with an authenticator app gets `mfa_required`
125
+ and only a short-lived challenge cookie scoped to `/v1/auth/login/mfa`;
126
+ treating that as logged in leaves the user without a session. `loginMfa`
127
+ errors: 401 `mfa_code_invalid` (wrong or reused code, let them retry), 401
128
+ `mfa_challenge_invalid` (expired or too many tries, back to the password
129
+ step), 429 `mfa_rate_limited` (`retryAfterSeconds` on the error body).
130
+
131
+ In a browser the cookies are set automatically (the SDK uses
132
+ `credentials: 'include'`). Server-side callers must capture + replay the cookie.
133
+
134
+ `client.logout()` ends the session and drops the SDK's cached bearer token,
135
+ even when the request fails.
136
+
137
+ ### Cookie-only dashboard → bearer calls (automatic, no OAuth needed)
138
+
139
+ You do **not** need to run the OAuth code flow to call the operational API
140
+ (delegated keys, witness writes, chain reads). After `login()`, just call them:
141
+
142
+ ```ts
143
+ await client.login({ email, password }); // sets wac_session
144
+ await client.listDelegatedKeys(); // ← works; SDK mints a bearer token
145
+ ```
146
+
147
+ How: those endpoints are bearer-only (they never accept the ambient cookie, so
148
+ there's **no CSRF surface** even with `SameSite=None`). On the first such call
149
+ the SDK transparently exchanges the session cookie for a short-lived access
150
+ token via `POST /v1/auth/access-token`, caches it, and re-mints on a 401. You
151
+ never see the token unless you want it:
152
+
153
+ ```ts
154
+ const { accessToken, expiresAt } = await client.exchangeSessionForToken(); // optional pre-warm
155
+ ```
156
+
157
+ Requirements: in the browser the `wac_session` cookie rides automatically
158
+ (`credentials: 'include'`). Node/SSR callers pass `sessionCookie: '<value>'` to
159
+ the constructor. If there's no valid session, the call throws a descriptive
160
+ "requires an OAuth access token … or provide `sessionCookie`" error — that's
161
+ your cue to send the user back to login.
162
+
163
+ This is the recommended path for a first-party dashboard. Reach for the full
164
+ OAuth flow below only when the dashboard is itself a registered OAuth client
165
+ (e.g. third-party apps, or you want long-lived refresh tokens).
166
+
167
+ ### Magic-link sign-in
168
+
169
+ `beginOAuthLogin` / passwordless paths exist; see the SDK's `OauthNamespace`
170
+ and the accounts OpenAPI for `/v1/auth/magic/*`.
171
+
172
+ ### MFA (TOTP)
173
+
174
+ ```ts
175
+ const { secret, otpauthUrl } = await client.mfa.totp.enroll(); // render QR from otpauthUrl
176
+ const { recoveryCodes } = await client.mfa.totp.confirm(code); // show ONCE
177
+
178
+ // Both need the user's current code (or a recovery code):
179
+ await client.mfa.totp.disable({ code });
180
+ const { recoveryCodes: fresh } = await client.mfa.recoveryCodes.regenerate({ recoveryCode });
181
+ ```
182
+
183
+ `confirm` signs the user out of every other device and connected app (MCP
184
+ connectors included); tell the user so. The SDK drops its cached
185
+ session-minted bearer token and mints a fresh one on the next call.
186
+ `disable` and `regenerate` fail with 403 `mfa_step_up_failed` on a wrong
187
+ proof and 429 `mfa_rate_limited`.
188
+
189
+ ### OAuth 2.1 + PKCE (for when your dashboard is itself an OAuth client)
190
+
191
+ ```ts
192
+ const { authorizationUrl } = await client.beginOAuthLogin({ … });
193
+ // …redirect, then on callback:
194
+ await client.completeOAuthLogin({ … }); // PKCE verifier from sessionStorage
195
+ ```
196
+
197
+ Access token held in memory; refresh token delivered as an HttpOnly
198
+ `wac_refresh` cookie scoped to `/token` (JS never touches it). The SDK does
199
+ transparent single-flight refresh on 401.
200
+
201
+ ---
202
+
203
+ ## 5. Recovery-file format
204
+
205
+ The throwaway frontend used this shape. **Treat it as a starting point** —
206
+ production should wrap `record` with WebAuthn/recovery-code encryption rather
207
+ than storing cleartext keys.
208
+
209
+ ```json
210
+ {
211
+ "version": 1,
212
+ "type": "witnium-recovery",
213
+ "created": "<ISO 8601>",
214
+ "record": {
215
+ "email": "you@example.com",
216
+ "orgId": "<uuid>",
217
+ "userId": "<uuid>",
218
+ "contractAddress": "0x… (lowercase)",
219
+ "contractVersion": "5.0.0",
220
+ "ownerPublicKey": "<64 hex>",
221
+ "ownerPrivateKey": "<64 hex — ENCRYPT THIS>",
222
+ "signingPublicKey": "<64 hex>",
223
+ "signingPrivateKey": "<64 hex — ENCRYPT THIS>"
224
+ }
225
+ }
226
+ ```
227
+
228
+ Import = restore `record` into local storage. The owner private key must be
229
+ retrievable for the MCP-CUSTODY ceremony (§6).
230
+
231
+ ---
232
+
233
+ ## 6. MCP-CUSTODY consent ceremony
234
+
235
+ When a user connects an AI agent (claude.ai's MCP connector, or a self-hosted
236
+ one) the backend runs a ceremony at OAuth-consent time that mints a **fresh
237
+ ephemeral signing key per connection** and asks the user to sign two owner-key
238
+ operations:
239
+
240
+ 1. `addSigningKey(<ephemeral key>)` — registers it on the contract (submitted now)
241
+ 2. `revokeSigningKey(<same key>)` — pre-signed, stored, fired automatically on disconnect
242
+
243
+ **What the frontend must provide:** the page that collects these two
244
+ signatures is currently *server-rendered by accounts* at
245
+ `/interaction/:uid/sign-keys`. It runs inline JS that reads the owner key from
246
+ `localStorage['witnium.ownerPrivateKey:<contractAddress>']`, signs both
247
+ messages, and form-POSTs them back.
248
+
249
+ You have two choices:
250
+
251
+ - **Let accounts render it** (current behavior). Then your only job is to make
252
+ sure the owner key is in `localStorage` under that exact key, **on the
253
+ accounts origin** (see §7).
254
+ - **Render it yourself** and POST the two signatures to
255
+ `/interaction/:uid/sign-keys` (`addOwnerSignature`, `revokeOwnerSignature`,
256
+ `revokeNonce`). Gives you full UX control. The signed message formats are:
257
+ - add: `{"op":1,"contract":"<addr>","nonce":<ownerNonce+1>,"newKey":"<pub>"}`
258
+ - revoke: `{"op":2,"contract":"<addr>","nonce":<ownerNonce+2>,"key":"<pub>"}`
259
+ (canonical JSON, signed as UTF-8 bytes with the owner key)
260
+
261
+ **Dev cross-origin shortcut (pre-launch):** the accounts-rendered sign-keys
262
+ page now also accepts a **recovery-file upload** (the §5 JSON). So while you're
263
+ building on a different origin (e.g. Lovable), the user can export their
264
+ recovery file from your app and upload it on the accounts sign-keys page — the
265
+ page extracts the owner key for the matching contract. This sidesteps the
266
+ same-origin localStorage limitation (§7) without any postMessage plumbing. It's
267
+ a dev convenience, not the production answer; production should solve §7
268
+ properly.
269
+
270
+ To get refresh tokens (required for the agent to stay connected + for the
271
+ disconnect-on-revoke cascade), the OAuth client **must request
272
+ `prompt=consent`** and include `offline_access` in scope. Without
273
+ `prompt=consent` the AS silently drops `offline_access` and no refresh token is
274
+ issued — this is standard OIDC, not a bug.
275
+
276
+ ---
277
+
278
+ ## 7. Same-origin requirement (architectural — needs a decision)
279
+
280
+ **The dashboard that stores keys and the accounts OIDC interaction pages must
281
+ share an origin**, because `localStorage` is origin-scoped. Discovered in
282
+ testing: keys saved on `test-frontend.witniumchain.com` were invisible to the
283
+ sign-keys page rendered at `auth.witniumchain.com` → the ceremony couldn't find
284
+ the owner key.
285
+
286
+ Pick one:
287
+
288
+ - **(Recommended) Serve the dashboard from `auth.witniumchain.com`** (a path,
289
+ or accounts serving the SPA). Owner key in localStorage is naturally visible
290
+ to the OIDC interaction pages. Simplest, no cross-origin plumbing.
291
+ - **Cross-origin with `postMessage`** — dashboard on its own domain passes the
292
+ owner-key signature to the accounts interaction page via a `postMessage`
293
+ handshake. More moving parts; partially erodes the "keys never leave your
294
+ page" story. Only do this if a separate dashboard domain is a hard
295
+ requirement.
296
+
297
+ This decision blocks the key-storage implementation, so settle it early.
298
+
299
+ ---
300
+
301
+ ## 7b. Dev workflow — reset + re-run
302
+
303
+ Testing signup repeatedly piles up users/orgs/contracts. A **pre-launch-only**
304
+ self-serve reset is available:
305
+
306
+ ```ts
307
+ // Authenticated with the wac_session cookie (must be logged in).
308
+ await fetch('https://auth.witniumchain.com/v1/account', {
309
+ method: 'DELETE',
310
+ credentials: 'include',
311
+ });
312
+ // → { deleted: true, userId, organizationId, vaultKeysPurged, notice }
313
+ ```
314
+
315
+ Deletes the caller's user + org + contracts + delegated keys (Vault keys
316
+ destroyed too), so you can sign up fresh. The on-chain contract is orphaned
317
+ (immutable — fine). Returns **403** unless `WITNIUM_PRE_LAUNCH=true` on the
318
+ server (it is, on the current dev deploy). This endpoint will be removed before
319
+ customer onboarding; don't build product UI on it — it's purely a dev-loop tool.
320
+ (Alternatively: just sign up with a fresh email each time, no cleanup needed.)
321
+
322
+ ---
323
+
324
+ ## 8. Known limitations / sharp edges
325
+
326
+ | Issue | Impact | Status |
327
+ |---|---|---|
328
+ | **Pre-signed revoke nonce drift** | If a user opens several agent connections in a row without disconnecting, older connections' on-chain `revokeSigningKey` fails when finally fired (the pre-signed sig is bound to a stale ownerNonce). The Vault key is still destroyed — Witnium genuinely loses signing ability — but the on-chain key stays listed as active. | Known. On-chain cleanup is best-effort under serial grants. Mitigation TBD (revoke-then-add atomic, or periodic re-sign). |
329
+ | **`prompt=consent` required for refresh tokens** | Omitting it silently drops `offline_access`. | Working as designed (OIDC). Document in your OAuth client. |
330
+ | **Email verify is GET** | POST returns "Cannot POST". | Working as designed. |
331
+ | **Same-origin localStorage** | §7. | Architectural decision required. |
332
+
333
+ ---
334
+
335
+ ## 9. API reference
336
+
337
+ - **accounts OpenAPI**: `https://auth.witniumchain.com/openapi.json` (or the
338
+ committed `specs/accounts.openapi.json` in the SDK repo)
339
+ - **chain-api OpenAPI**: `specs/chain-api.openapi.json` in the SDK repo
340
+ - Every SDK method's request/response type is derived from these specs via
341
+ `openapi-typescript`, so they stay in lockstep. Re-export aliases (e.g.
342
+ `CreateOrgRequest`, `SignupResponse`) are in `src/types.ts`.
343
+
344
+ ## 10. SDK clients at a glance
345
+
346
+ | Client | For | Auth |
347
+ |---|---|---|
348
+ | `WitniumchainClient` | end-users (signup, login, OAuth, MFA, delegated keys, witness reads) | session cookie / access token |
349
+ | `WitniumchainOrgClient` | org admins managing members | org API key |
350
+ | `WitniumchainAdminClient` | sysadmin org lifecycle | admin token |
351
+ | `WitniumchainChainAdminClient` | **service-to-service only** — not for frontend use | admin token / service-principal JWT |
352
+
353
+ The frontend lives almost entirely in `WitniumchainClient`.
package/README.md CHANGED
@@ -1,3 +1,270 @@
1
- # Temporary Holding Version
1
+ # @witnium/witniumchain
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ TypeScript SDK for WitniumChain — the canonical single client for both the
4
+ accounts service (identity, billing, OAuth, delegated keys, witness writes)
5
+ and the chain-api read surfaces (contract info, witness lookup, wallet
6
+ balance, dashboards). The two-service backend is hidden behind one
7
+ `WitniumchainClient` class; you give it one OAuth access token and it knows
8
+ where each call belongs.
9
+
10
+ ## Status
11
+
12
+ **v0.5 — adds OAuth 2.1 + PKCE login helpers** on top of the v0.4 surface:
13
+
14
+ - All 41 accounts routes (five auth modes: session / OAuth / org / admin / signed)
15
+ - 9 chain-api read methods, routed to `chainBaseUrl`, reusing the same OAuth
16
+ `accessToken` (accounts mints tokens with `aud=https://api.witniumchain.com`,
17
+ so they're valid against both services unchanged)
18
+ - Three layered clients on top: `WitniumchainClient` (end-user),
19
+ `WitniumchainApiKeyClient` (a server with an org API key),
20
+ `WitniumchainAdminClient` (sysadmin)
21
+ - **`beginOAuthLogin` / `completeOAuthLogin` / `refreshAccessToken` / `signOut`** —
22
+ browser-side Authorization-Code + PKCE login flow. Discovery-driven
23
+ endpoint resolution (`/.well-known/openid-configuration`), PKCE verifier
24
+ in `sessionStorage`, access token held in memory only, transparent 401-retry
25
+ with single-flight refresh-token rotation. Refresh tokens are delivered as
26
+ an HttpOnly `wac_refresh` cookie scoped to `Path=/token` — JavaScript never
27
+ touches them. Non-browser callers (Node SSR, native apps without a cookie
28
+ jar) fall back to in-band refresh-token delivery; the SDK handles both.
29
+ - **`client.mfa.totp.enroll/confirm/disable` + `client.mfa.recoveryCodes.regenerate`** —
30
+ TOTP MFA self-management. `enroll` returns the secret + otpauth URL (render
31
+ as a QR code in your dashboard with any QR lib); `confirm` validates the
32
+ first code and returns 10 single-use recovery codes (shown ONCE). `disable`
33
+ and `regenerate` require a second-factor proof (`{ code }` or
34
+ `{ recoveryCode }`). Password login: check `login()`'s `status`; on
35
+ `mfa_required`, finish with `loginMfa({ code })`.
36
+
37
+ What's NOT exposed (by design): chain-api v5 writes — those are proxied by
38
+ accounts' v5 surface which adds credit reservation + idempotency + scope
39
+ checks. Calling chain-api writes directly would burn credits without
40
+ billing them. See `docs/PLAN-PHASE-SDK-UNIFIED.md` for the routing rules.
41
+
42
+ Every type comes from the OpenAPI specs of both services, vendored in
43
+ `specs/` and compiled with `openapi-typescript`. `npm test` fails when the
44
+ chain spec differs from this repo's `public/openapi.json`, when the accounts
45
+ spec differs from the sha256 recorded in `specs/sources.json`, or when
46
+ `src/generated/` is stale. The accounts service is a separate private repo, so
47
+ CI cannot read it: `npm run openapi:verify:accounts` (with
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`.
50
+ `npm run openapi:refresh` re-vendors both specs and regenerates the types.
51
+
52
+ ## Install
53
+
54
+ ```bash
55
+ npm install @witnium/witniumchain
56
+ ```
57
+
58
+ ## Auth model
59
+
60
+ The SDK accepts five distinct credentials. Configure whichever
61
+ you need on the client; methods that require a credential you didn't supply
62
+ throw at call time.
63
+
64
+ | Credential | Header / Cookie | Used by |
65
+ |---|---|---|
66
+ | `sessionCookie` | `Cookie: wac_session=…` | `/v1/auth/logout`, `/v1/account/*`, `/v1/billing/*`, `/v1/orgs/me*`, `/v1/keys/*`, `/v1/contracts/{pause,unpause}`, `/v1/oauth/sessions*` |
67
+ | `accessToken` | `Authorization: Bearer <JWT>` | `/v1/users/me/delegated-keys/*`, `/v1/sign`, **all chain-api reads** |
68
+ | `apiKey` | `Authorization: Bearer wcak_…` | `/v1/sign`, `/v1/api-key`, v5 witness `propose`/`sign`/`finalize` (via `WitniumchainApiKeyClient`) |
69
+ | `adminToken` | `Authorization: Bearer <ADMIN_TOKEN>` | `/v1/admin/*` |
70
+ | `signedRequest` | `X-Witnium-Key/Timestamp/Signature` | `/v1/contracts/{addr}/witnesses/{propose,sign,finalize,revoke}` |
71
+
72
+ Public routes need no credential (`/v1/auth/{signup,verify,login,…}`,
73
+ `/v1/contracts/provision`, `GET /v1/contracts/{addr}/witnesses/{id}`,
74
+ `/health/*`).
75
+
76
+ ## Two services, one client
77
+
78
+ Accounts and chain-api are separate services today (consolidation is a
79
+ later phase). The SDK hides that:
80
+
81
+ ```ts
82
+ const client = new WitniumchainClient({
83
+ baseUrl: 'https://auth.witniumchain.com', // accounts
84
+ chainBaseUrl: 'https://api.witniumchain.com', // chain-api (omit if you only need accounts)
85
+ accessToken: oauthBearerJwt,
86
+ });
87
+
88
+ // Writes / billing / auth → accounts (baseUrl)
89
+ await client.proposeWitnessV5('0xabc', { ... });
90
+
91
+ // Reads of on-chain state → chain-api (chainBaseUrl)
92
+ const witness = await client.getWitnessV5('0xabc', witnessId);
93
+ const balance = await client.getWalletBalance('0xabc');
94
+ ```
95
+
96
+ If you call a chain-api method without `chainBaseUrl` configured, the SDK
97
+ throws a clear `WitniumchainApiError` at call time naming the missing
98
+ config — no silent fallback to a wrong base URL.
99
+
100
+ ## Examples
101
+
102
+ ### End-user signup + login
103
+
104
+ ```ts
105
+ import { WitniumchainClient } from '@witnium/witniumchain';
106
+
107
+ const client = new WitniumchainClient({
108
+ baseUrl: 'https://auth.witniumchain.com',
109
+ });
110
+
111
+ await client.signup({ email: 'alice@example.com', password: 'correct horse battery staple' });
112
+ // User clicks email link, lands on /verify?token=…
113
+ const { provisioningToken } = await client.verifyEmail('the-token-from-the-link');
114
+
115
+ // Then login (sets the wac_session cookie in a browser; in Node, capture
116
+ // from response headers and pass back via `sessionCookie`).
117
+ const res = await client.login({ email: 'alice@example.com', password: '…' });
118
+ if (res.status === 'mfa_required') await client.loginMfa({ code: '123456' });
119
+ ```
120
+
121
+ ### A server with an org API key
122
+
123
+ An org admin creates the key in the dashboard (Witnium-managed keys only);
124
+ it signs and writes v5 witnesses for the org, billed to the org.
125
+
126
+ ```ts
127
+ import { WitniumchainApiKeyClient } from '@witnium/witniumchain';
128
+
129
+ const server = new WitniumchainApiKeyClient({
130
+ baseUrl: 'https://auth.witniumchain.com',
131
+ apiKey: process.env.WITNIUM_API_KEY!, // wcak_…
132
+ });
133
+
134
+ const me = await server.me(); // its contract and signing key
135
+ const { intentId, payloadToSign } = await server.proposeWitnessV5(me.contractAddress, {
136
+ dataId: sha256Hex,
137
+ requiredSigners: [me.publicKey],
138
+ });
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);
142
+ ```
143
+
144
+ Org admins manage keys with the dashboard session: `client.apiKeys.create({ label })`
145
+ (after a step-up; the secret is returned once), `client.apiKeys.list()`,
146
+ `client.apiKeys.revoke(id)`.
147
+
148
+ ### Org admins: the organization and its team
149
+
150
+ With the dashboard's session cookie, an org admin manages their own org;
151
+ the org comes from the session, never from a parameter.
152
+
153
+ ```ts
154
+ await client.organization.rename('Witnium Newsroom'); // display name; the billing name stays in the billing portal
155
+ await client.orgUsers.invite({ email: 'teammate@example.com', role: 'member' });
156
+ const { members } = await client.orgUsers.list();
157
+ ```
158
+
159
+ ### Sysadmin — create an organization
160
+
161
+ ```ts
162
+ const sys = new WitniumchainClient({
163
+ baseUrl: 'https://auth.witniumchain.com',
164
+ adminToken: process.env.ACCOUNTS_ADMIN_TOKEN!,
165
+ });
166
+
167
+ const { organization, apiKey } = await sys.createOrganization({
168
+ name: 'Acme Inc.',
169
+ email: 'ops@acme.example.com',
170
+ accountType: 'metered',
171
+ signupGrantAmount: 100,
172
+ });
173
+ // `apiKey` is shown ONCE — store it now.
174
+ ```
175
+
176
+ ### Sign in with Witnium (Authorization Code + PKCE)
177
+
178
+ For a browser SPA (e.g. a Lovable app) that wants to authenticate end-users
179
+ against a Witnium org. No backend required.
180
+
181
+ ```ts
182
+ const client = new WitniumchainClient({
183
+ baseUrl: 'https://auth.witniumchain.com',
184
+ oauthClientId: 'your-registered-client-id',
185
+ });
186
+
187
+ // 1. Kick off login. The SDK generates a PKCE pair, stashes the verifier in
188
+ // sessionStorage, and returns the URL to send the user to.
189
+ const { authorizationUrl } = await client.beginOAuthLogin({
190
+ redirectUri: 'https://your-app.example/callback',
191
+ });
192
+ window.location.assign(authorizationUrl);
193
+
194
+ // 2. On the callback page, complete the exchange. Returns the access token
195
+ // (the SDK ALSO holds it in memory; subsequent BearerJWT calls Just Work).
196
+ const { accessToken, expiresAt } = await client.completeOAuthLogin(
197
+ window.location.href,
198
+ );
199
+ window.history.replaceState({}, '', window.location.pathname); // strip ?code=…
200
+
201
+ // 3. Use the SDK normally. When the access token expires, the SDK refreshes
202
+ // transparently on the next call. You only need to redirect to login if
203
+ // refresh itself fails (refresh token revoked or expired).
204
+ const { keys } = await client.listDelegatedKeys();
205
+
206
+ // 4. Sign-out clears in-memory tokens.
207
+ client.signOut();
208
+ ```
209
+
210
+ ### OAuth API — delegated-key + sign
211
+
212
+ ```ts
213
+ const api = new WitniumchainClient({
214
+ baseUrl: 'https://auth.witniumchain.com',
215
+ accessToken: bearerJwt,
216
+ });
217
+
218
+ const prepared = await api.prepareDelegatedKey({ contractAddress: '0x…' });
219
+ // Sign prepared.messageToSign with your owner key locally:
220
+ const ownerSignature = await myOwnerSigner.sign(prepared.messageToSign);
221
+
222
+ const submitted = await api.submitDelegatedKey(prepared.id, { ownerSignature });
223
+ // submitted.confirmed === true once the addSigningKey tx mines (~10–15 s).
224
+
225
+ const { signature } = await api.sign(
226
+ { delegatedKeyId: prepared.id, payload: 'deadbeef…' },
227
+ );
228
+ ```
229
+
230
+ ### SDK signed-request (witness propose/sign/finalize)
231
+
232
+ ```ts
233
+ const sdk = new WitniumchainClient({
234
+ baseUrl: 'https://auth.witniumchain.com',
235
+ signedRequest: {
236
+ publicKeyHex: 'abcd…64-chars…',
237
+ sign: async (canonicalMessage) => {
238
+ // Sign with your Ed25519 key — e.g. via @noble/ed25519 or a KMS.
239
+ // Return the 128-char hex signature.
240
+ return await myEd25519Sign(canonicalMessage);
241
+ },
242
+ },
243
+ });
244
+
245
+ const intent = await sdk.proposeWitness('0x…', {
246
+ dataId: '…64-hex…',
247
+ requiredSigners: ['…signer-pubkey…'],
248
+ });
249
+ ```
250
+
251
+ ## Errors
252
+
253
+ All non-2xx responses surface as `WitniumchainApiError`:
254
+
255
+ ```ts
256
+ import { WitniumchainApiError } from '@witnium/witniumchain';
257
+
258
+ try {
259
+ await client.orgUsers.invite({ email: 'taken@example.com' });
260
+ } catch (err) {
261
+ if (err instanceof WitniumchainApiError) {
262
+ console.error(err.status, err.errorLabel, err.message);
263
+ // err.body holds the raw parsed body for advanced inspection.
264
+ }
265
+ }
266
+ ```
267
+
268
+ ## License
269
+
270
+ MIT.