@cubist-labs/cubesigner-sdk 0.2.2 → 0.2.15

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.
Files changed (55) hide show
  1. package/dist/package.json +68 -0
  2. package/dist/src/api.d.ts +493 -0
  3. package/dist/src/api.js +1166 -0
  4. package/dist/src/client.d.ts +432 -335
  5. package/dist/src/client.js +195 -863
  6. package/dist/src/ethers/index.d.ts +33 -6
  7. package/dist/src/ethers/index.js +59 -12
  8. package/dist/src/index.d.ts +31 -26
  9. package/dist/src/index.js +51 -32
  10. package/dist/src/key.d.ts +28 -21
  11. package/dist/src/key.js +17 -10
  12. package/dist/src/mfa.d.ts +7 -7
  13. package/dist/src/mfa.js +20 -32
  14. package/dist/src/org.d.ts +37 -279
  15. package/dist/src/org.js +48 -194
  16. package/dist/src/paginator.js +1 -1
  17. package/dist/src/response.d.ts +101 -0
  18. package/dist/src/response.js +164 -0
  19. package/dist/src/role.d.ts +11 -9
  20. package/dist/src/role.js +1 -1
  21. package/dist/src/schema.d.ts +586 -10
  22. package/dist/src/schema.js +1 -1
  23. package/dist/src/schema_types.d.ts +6 -0
  24. package/dist/src/schema_types.js +1 -1
  25. package/dist/src/session/cognito_manager.d.ts +15 -3
  26. package/dist/src/session/cognito_manager.js +23 -5
  27. package/dist/src/session/session_manager.d.ts +1 -1
  28. package/dist/src/session/session_manager.js +3 -11
  29. package/dist/src/session/session_storage.js +1 -1
  30. package/dist/src/session/signer_session_manager.d.ts +3 -7
  31. package/dist/src/session/signer_session_manager.js +2 -8
  32. package/dist/src/signer_session.d.ts +8 -266
  33. package/dist/src/signer_session.js +15 -221
  34. package/dist/src/user_export.d.ts +52 -0
  35. package/dist/src/user_export.js +129 -0
  36. package/dist/src/util.d.ts +15 -0
  37. package/dist/src/util.js +33 -11
  38. package/package.json +12 -10
  39. package/src/api.ts +1395 -0
  40. package/src/client.ts +216 -1025
  41. package/src/ethers/index.ts +70 -12
  42. package/src/index.ts +59 -43
  43. package/src/key.ts +19 -12
  44. package/src/mfa.ts +16 -28
  45. package/src/org.ts +49 -204
  46. package/src/response.ts +196 -0
  47. package/src/role.ts +5 -3
  48. package/src/schema.ts +586 -10
  49. package/src/schema_types.ts +7 -0
  50. package/src/session/cognito_manager.ts +33 -6
  51. package/src/session/session_manager.ts +2 -8
  52. package/src/session/signer_session_manager.ts +3 -10
  53. package/src/signer_session.ts +13 -261
  54. package/src/user_export.ts +116 -0
  55. package/src/util.ts +29 -10
package/src/api.ts ADDED
@@ -0,0 +1,1395 @@
1
+ import createClient from "openapi-fetch";
2
+ import { paths } from "./schema";
3
+ import {
4
+ SignerSessionData,
5
+ SignerSessionLifetime,
6
+ SignerSessionManager,
7
+ } from "./session/signer_session_manager";
8
+ import {
9
+ CreateOidcUserOptions,
10
+ IdentityProof,
11
+ KeyInRoleInfo,
12
+ KeyInfoApi,
13
+ ListKeysResponse,
14
+ ListRoleKeysResponse,
15
+ ListRoleUsersResponse,
16
+ ListRolesResponse,
17
+ OidcIdentity,
18
+ SessionsResponse,
19
+ PublicKeyCredential,
20
+ RoleInfo,
21
+ UpdateKeyRequest,
22
+ UpdateOrgRequest,
23
+ UpdateOrgResponse,
24
+ UpdateRoleRequest,
25
+ UserIdInfo,
26
+ UserInRoleInfo,
27
+ UserInfo,
28
+ SessionInfo,
29
+ OrgInfo,
30
+ RatchetConfig,
31
+ EvmSignRequest,
32
+ EvmSignResponse,
33
+ Eth2SignRequest,
34
+ Eth2SignResponse,
35
+ Eth2StakeRequest,
36
+ Eth2StakeResponse,
37
+ Eth2UnstakeRequest,
38
+ Eth2UnstakeResponse,
39
+ BlobSignRequest,
40
+ BlobSignResponse,
41
+ BtcSignResponse,
42
+ BtcSignRequest,
43
+ SolanaSignRequest,
44
+ SolanaSignResponse,
45
+ AvaSignResponse,
46
+ AvaSignRequest,
47
+ AvaTx,
48
+ MfaRequestInfo,
49
+ MemberRole,
50
+ UserExportCompleteResponse,
51
+ UserExportInitResponse,
52
+ UserExportListResponse,
53
+ } from "./schema_types";
54
+ import { assertOk, encodeToBase64 } from "./util";
55
+ import { AddFidoChallenge, MfaFidoChallenge, MfaReceipt, TotpChallenge } from "./mfa";
56
+ import { CubeSignerResponse, mapResponse } from "./response";
57
+ import { Key, KeyType } from "./key";
58
+ import { Page, PageOpts, PageQueryArgs, Paginator } from "./paginator";
59
+ import { KeyPolicy } from "./role";
60
+ import { EnvInterface } from "./env";
61
+ import { NAME, VERSION } from ".";
62
+ import { loadSubtleCrypto } from "./user_export";
63
+
64
+ /** @internal */
65
+ export type Client = ReturnType<typeof createClient<paths>>;
66
+
67
+ export { paths };
68
+
69
+ /**
70
+ * Creates a new HTTP client, setting the "User-Agent" header to this package's {name}@{version}.
71
+ *
72
+ * @param {string} baseUrl The base URL of the client (e.g., "https://gamma.signer.cubist.dev")
73
+ * @param {string} authToken The value to send as "Authorization" header.
74
+ * @return {Client} The new HTTP client.
75
+ */
76
+ export function createHttpClient(baseUrl: string, authToken: string): Client {
77
+ return createClient<paths>({
78
+ baseUrl,
79
+ headers: {
80
+ Authorization: authToken,
81
+ ["User-Agent"]: `${NAME}@${VERSION}`,
82
+ },
83
+ });
84
+ }
85
+
86
+ /**
87
+ * Client to use to send requests to CubeSigner services
88
+ * when authenticating using a CubeSigner session token.
89
+ */
90
+ export class CubeSignerApi {
91
+ readonly #orgId: string;
92
+ readonly #sessionMgr: SignerSessionManager;
93
+
94
+ /** Underlying session manager */
95
+ get sessionMgr(): SignerSessionManager {
96
+ return this.#sessionMgr;
97
+ }
98
+
99
+ /** Target environment */
100
+ get env(): EnvInterface {
101
+ return this.sessionMgr.env;
102
+ }
103
+
104
+ /**
105
+ * Constructor.
106
+ * @param {SignerSessionManager} sessionMgr The session manager to use
107
+ * @param {string?} orgId Optional organization ID; if omitted, uses the org ID from the session manager.
108
+ */
109
+ constructor(sessionMgr: SignerSessionManager, orgId?: string) {
110
+ this.#sessionMgr = sessionMgr;
111
+ this.#orgId = orgId ?? sessionMgr.orgId;
112
+ }
113
+
114
+ /**
115
+ * Returns a new instance of this class using the same session manager but targeting a different organization.
116
+ *
117
+ * @param {string} orgId The organization ID.
118
+ * @return {CubeSignerApi} A new instance of this class using the same session manager but targeting different organization.
119
+ */
120
+ withOrg(orgId?: string): CubeSignerApi {
121
+ return orgId ? new CubeSignerApi(this.#sessionMgr, orgId) : this;
122
+ }
123
+
124
+ /** Org id or name */
125
+ get orgId() {
126
+ return this.#orgId;
127
+ }
128
+
129
+ // #region USERS: userGet, userResetTotp(Init|Complete), userVerifyTotp, userRegisterFido(Init|Complete)
130
+
131
+ /**
132
+ * Obtain information about the current user.
133
+ *
134
+ * @return {Promise<UserInfo>} Retrieves information about the current user.
135
+ */
136
+ async userGet(): Promise<UserInfo> {
137
+ const client = await this.client();
138
+ const resp =
139
+ `${this.orgId}` !== "undefined"
140
+ ? await client.get("/v0/org/{org_id}/user/me", {
141
+ params: { path: { org_id: this.orgId } },
142
+ parseAs: "json",
143
+ })
144
+ : await client.get("/v0/about_me", { parseAs: "json" });
145
+ return assertOk(resp);
146
+ }
147
+
148
+ /**
149
+ * Creates a request to change user's TOTP. Returns a {@link TotpChallenge}
150
+ * that must be answered either by calling {@link TotpChallenge.answer} (or
151
+ * {@link CubeSignerApi.userResetTotpComplete}).
152
+ *
153
+ * @param {string} issuer Optional issuer; defaults to "Cubist"
154
+ * @param {MfaReceipt} mfaReceipt MFA receipt to include in HTTP headers
155
+ */
156
+ async userResetTotpInit(
157
+ issuer?: string,
158
+ mfaReceipt?: MfaReceipt,
159
+ ): Promise<CubeSignerResponse<TotpChallenge>> {
160
+ const resetTotpFn = async (headers?: HeadersInit) => {
161
+ const client = await this.client();
162
+ const resp = await client.post("/v0/org/{org_id}/user/me/totp", {
163
+ headers,
164
+ params: { path: { org_id: this.orgId } },
165
+ body: issuer
166
+ ? {
167
+ issuer,
168
+ }
169
+ : null,
170
+ parseAs: "json",
171
+ });
172
+ const data = assertOk(resp);
173
+ return mapResponse(data, (totpInfo) => new TotpChallenge(this, totpInfo));
174
+ };
175
+ return await CubeSignerResponse.create(resetTotpFn, mfaReceipt);
176
+ }
177
+
178
+ /**
179
+ * Answer the TOTP challenge issued by {@link userResetTotpInit}. If successful, user's
180
+ * TOTP configuration will be updated to that of the TOTP challenge.
181
+ *
182
+ * Instead of calling this method directly, prefer {@link TotpChallenge.answer}.
183
+ *
184
+ * @param {string} totpId - The ID of the TOTP challenge
185
+ * @param {string} code - The TOTP code that should verify against the TOTP configuration from the challenge.
186
+ */
187
+ async userResetTotpComplete(totpId: string, code: string): Promise<void> {
188
+ const client = await this.client();
189
+ const resp = await client.patch("/v0/org/{org_id}/user/me/totp", {
190
+ parseAs: "json",
191
+ params: { path: { org_id: this.orgId } },
192
+ body: { totp_id: totpId, code },
193
+ });
194
+ assertOk(resp);
195
+ }
196
+
197
+ /**
198
+ * Verifies a given TOTP code against the current user's TOTP configuration.
199
+ * Throws an error if the verification fails.
200
+ *
201
+ * @param {string} code Current TOTP code
202
+ */
203
+ async userVerifyTotp(code: string) {
204
+ const client = await this.client();
205
+ const resp = await client.post("/v0/org/{org_id}/user/me/totp/verify", {
206
+ params: { path: { org_id: this.orgId } },
207
+ body: { code },
208
+ parseAs: "json",
209
+ });
210
+ assertOk(resp);
211
+ }
212
+
213
+ /**
214
+ * Initiate adding a new FIDO device. MFA may be required. This returns a {@link AddFidoChallenge}
215
+ * that must be answered with {@link AddFidoChallenge.answer} or {@link userRegisterFidoComplete}
216
+ * (after MFA approvals).
217
+ *
218
+ * @param {string} name The name of the new device.
219
+ * @param {MfaReceipt} mfaReceipt Optional MFA receipt to include in HTTP headers
220
+ * @return {Promise<CubeSignerResponse<AddFidoChallenge>>} A challenge that must be answered in order to complete FIDO registration.
221
+ */
222
+ async userRegisterFidoInit(
223
+ name: string,
224
+ mfaReceipt?: MfaReceipt,
225
+ ): Promise<CubeSignerResponse<AddFidoChallenge>> {
226
+ const addFidoFn = async (headers?: HeadersInit) => {
227
+ const client = await this.client();
228
+ const resp = await client.post("/v0/org/{org_id}/user/me/fido", {
229
+ headers,
230
+ params: { path: { org_id: this.orgId } },
231
+ body: { name },
232
+ parseAs: "json",
233
+ });
234
+ const data = assertOk(resp);
235
+ return mapResponse(data, (c) => new AddFidoChallenge(this, c));
236
+ };
237
+ return await CubeSignerResponse.create(addFidoFn, mfaReceipt);
238
+ }
239
+
240
+ /**
241
+ * Complete a previously initiated (via {@link userRegisterFidoInit}) request to add a new FIDO device.
242
+ *
243
+ * Instead of calling this method directly, prefer {@link AddFidoChallenge.answer} or
244
+ * {@link AddFidoChallenge.createCredentialAndAnswer}.
245
+ *
246
+ * @param {string} challengeId The ID of the challenge returned by the remote end.
247
+ * @param {PublicKeyCredential} credential The answer to the challenge.
248
+ */
249
+ async userRegisterFidoComplete(challengeId: string, credential: PublicKeyCredential) {
250
+ const client = await this.client();
251
+ const resp = await client.patch("/v0/org/{org_id}/user/me/fido", {
252
+ params: { path: { org_id: this.orgId } },
253
+ body: {
254
+ challenge_id: challengeId,
255
+ credential,
256
+ },
257
+ parseAs: "json",
258
+ });
259
+ assertOk(resp);
260
+ }
261
+
262
+ // #endregion
263
+
264
+ // #region ORGS: orgGet, orgUpdate
265
+
266
+ /**
267
+ * Obtain information about the current organization.
268
+ * @return {OrgInfo} Information about the organization.
269
+ */
270
+ async orgGet(): Promise<OrgInfo> {
271
+ const client = await this.client();
272
+ const resp = await client.get("/v0/org/{org_id}", {
273
+ params: { path: { org_id: this.orgId } },
274
+ parseAs: "json",
275
+ });
276
+ return assertOk(resp);
277
+ }
278
+
279
+ /**
280
+ * Update the org.
281
+ * @param {UpdateOrgRequest} request The JSON request to send to the API server.
282
+ * @return {UpdateOrgResponse} Updated org information.
283
+ */
284
+ async orgUpdate(request: UpdateOrgRequest): Promise<UpdateOrgResponse> {
285
+ const client = await this.client();
286
+ const resp = await client.patch("/v0/org/{org_id}", {
287
+ params: { path: { org_id: this.orgId } },
288
+ body: request,
289
+ parseAs: "json",
290
+ });
291
+ return assertOk(resp);
292
+ }
293
+
294
+ // #endregion
295
+
296
+ // #region ORG USERS: orgUserInvite, orgUsersList, orgUserCreateOidc, orgUserDeleteOidc
297
+
298
+ /**
299
+ * Create a new (first-party) user in the organization and send an email invitation to that user.
300
+ *
301
+ * @param {string} email Email of the user
302
+ * @param {string} name The full name of the user
303
+ * @param {MemberRole} role Optional role. Defaults to "alien".
304
+ */
305
+ async orgUserInvite(email: string, name: string, role?: MemberRole): Promise<void> {
306
+ const client = await this.client();
307
+ const resp = await client.post("/v0/org/{org_id}/invite", {
308
+ params: { path: { org_id: this.orgId } },
309
+ body: {
310
+ email,
311
+ name,
312
+ role,
313
+ skip_email: false,
314
+ },
315
+ parseAs: "json",
316
+ });
317
+ assertOk(resp);
318
+ }
319
+
320
+ /**
321
+ * List users.
322
+ * @return {User[]} Org users.
323
+ */
324
+ async orgUsersList(): Promise<UserIdInfo[]> {
325
+ const client = await this.client();
326
+ const resp = await client.get("/v0/org/{org_id}/users", {
327
+ params: { path: { org_id: this.orgId } },
328
+ parseAs: "json",
329
+ });
330
+ const data = assertOk(resp);
331
+ return data.users;
332
+ }
333
+
334
+ /**
335
+ * Create a new OIDC user. This can be a first-party "Member" or third-party "Alien".
336
+ * @param {OidcIdentity} identity The identity of the OIDC user
337
+ * @param {string} email Email of the OIDC user
338
+ * @param {CreateOidcUserOptions} opts Additional options for new OIDC users
339
+ * @return {string} User id of the new user
340
+ */
341
+ async orgUserCreateOidc(
342
+ identity: OidcIdentity,
343
+ email: string,
344
+ opts: CreateOidcUserOptions = {},
345
+ ): Promise<string> {
346
+ const client = await this.client();
347
+ const resp = await client.post("/v0/org/{org_id}/users", {
348
+ params: { path: { org_id: this.orgId } },
349
+ body: {
350
+ identity,
351
+ role: opts.memberRole ?? "Alien",
352
+ email: email,
353
+ mfa_policy: opts.mfaPolicy ?? null,
354
+ },
355
+ parseAs: "json",
356
+ });
357
+ return assertOk(resp).user_id;
358
+ }
359
+
360
+ /**
361
+ * Delete an existing OIDC user.
362
+ * @param {OidcIdentity} identity The identity of the OIDC user
363
+ */
364
+ async orgUserDeleteOidc(identity: OidcIdentity) {
365
+ const client = await this.client();
366
+ const resp = await client.del("/v0/org/{org_id}/users/oidc", {
367
+ params: { path: { org_id: this.orgId } },
368
+ body: identity,
369
+ parseAs: "json",
370
+ });
371
+ return assertOk(resp);
372
+ }
373
+
374
+ // #endregion
375
+
376
+ // #region KEYS: keyGet, keyUpdate, keyDelete, keysCreate, keysDerive, keysList
377
+
378
+ /**
379
+ * Get a key by its id.
380
+ *
381
+ * @param {string} keyId The id of the key to get.
382
+ * @return {KeyInfoApi} The key information.
383
+ */
384
+ async keyGet(keyId: string): Promise<KeyInfoApi> {
385
+ const client = await this.client();
386
+ const resp = await client.get("/v0/org/{org_id}/keys/{key_id}", {
387
+ params: { path: { org_id: this.orgId, key_id: keyId } },
388
+ parseAs: "json",
389
+ });
390
+ return assertOk(resp);
391
+ }
392
+
393
+ /**
394
+ * Update key.
395
+ * @param {string} keyId The ID of the key to update.
396
+ * @param {UpdateKeyRequest} request The JSON request to send to the API server.
397
+ * @return {KeyInfoApi} The JSON response from the API server.
398
+ */
399
+ async keyUpdate(keyId: string, request: UpdateKeyRequest): Promise<KeyInfoApi> {
400
+ const client = await this.client();
401
+ const resp = await client.patch("/v0/org/{org_id}/keys/{key_id}", {
402
+ params: { path: { org_id: this.orgId, key_id: keyId } },
403
+ body: request,
404
+ parseAs: "json",
405
+ });
406
+ return assertOk(resp);
407
+ }
408
+
409
+ /**
410
+ * Deletes a key.
411
+ *
412
+ * @param {string} keyId - Key id
413
+ */
414
+ async keyDelete(keyId: string) {
415
+ const client = await this.client();
416
+ const resp = await client.del("/v0/org/{org_id}/keys/{key_id}", {
417
+ params: { path: { org_id: this.orgId, key_id: keyId } },
418
+ parseAs: "json",
419
+ });
420
+ assertOk(resp);
421
+ }
422
+
423
+ /**
424
+ * Create new signing keys.
425
+ *
426
+ * @param {KeyType} keyType The type of key to create.
427
+ * @param {number} count The number of keys to create.
428
+ * @param {string?} ownerId The owner of the keys. Defaults to the session's user.
429
+ * @return {KeyInfoApi[]} The new keys.
430
+ */
431
+ async keysCreate(keyType: KeyType, count: number, ownerId?: string): Promise<KeyInfoApi[]> {
432
+ const chain_id = 0; // not used anymore
433
+ const client = await this.client();
434
+ const resp = await client.post("/v0/org/{org_id}/keys", {
435
+ params: { path: { org_id: this.orgId } },
436
+ body: {
437
+ count,
438
+ chain_id,
439
+ key_type: keyType,
440
+ owner: ownerId || null,
441
+ },
442
+ parseAs: "json",
443
+ });
444
+ const data = assertOk(resp);
445
+ return data.keys;
446
+ }
447
+
448
+ /**
449
+ * Derive a set of keys of a specified type using a supplied derivation path and an existing long-lived mnemonic.
450
+ *
451
+ * The owner of the derived key will be the owner of the mnemonic.
452
+ *
453
+ * @param {KeyType} keyType The type of key to create.
454
+ * @param {string[]} derivationPaths Derivation paths from which to derive new keys.
455
+ * @param {string} mnemonicId materialId of mnemonic key used to derive the new key.
456
+ *
457
+ * @return {KeyInfoApi[]} The newly derived keys.
458
+ */
459
+ async keysDerive(
460
+ keyType: KeyType,
461
+ derivationPaths: string[],
462
+ mnemonicId: string,
463
+ ): Promise<KeyInfoApi[]> {
464
+ const client = await this.client();
465
+ const resp = await client.put("/v0/org/{org_id}/derive_key", {
466
+ params: { path: { org_id: this.orgId } },
467
+ body: {
468
+ derivation_path: derivationPaths,
469
+ mnemonic_id: mnemonicId,
470
+ key_type: keyType,
471
+ },
472
+ parseAs: "json",
473
+ });
474
+ return assertOk(resp).keys;
475
+ }
476
+
477
+ /**
478
+ * List all keys in the org.
479
+ * @param {KeyType?} type Optional key type to filter list for.
480
+ * @param {PageOpts?} page Pagination options. Defaults to fetching the entire result set.
481
+ * @return {Paginator<ListKeysResponse, KeyInfoApi>} Paginator for iterating over keys.
482
+ */
483
+ keysList(type?: KeyType, page?: PageOpts): Paginator<ListKeysResponse, KeyInfoApi> {
484
+ const listFn = async (query: PageQueryArgs) => {
485
+ const client = await this.client();
486
+ const resp = await client.get("/v0/org/{org_id}/keys", {
487
+ params: {
488
+ path: { org_id: this.orgId },
489
+ query: {
490
+ key_type: type,
491
+ ...query,
492
+ },
493
+ },
494
+ parseAs: "json",
495
+ });
496
+ return assertOk(resp);
497
+ };
498
+ return new Paginator(
499
+ page ?? Page.default(),
500
+ listFn,
501
+ (r) => r.keys,
502
+ (r) => r.last_evaluated_key,
503
+ );
504
+ }
505
+ // #endregion
506
+
507
+ // #region ROLES: roleCreate, roleRead, roleUpdate, roleDelete, rolesList
508
+
509
+ /**
510
+ * Create a new role.
511
+ *
512
+ * @param {string?} name The optional name of the role.
513
+ * @return {string} The ID of the new role.
514
+ */
515
+ async roleCreate(name?: string): Promise<string> {
516
+ const client = await this.client();
517
+ const resp = await client.post("/v0/org/{org_id}/roles", {
518
+ params: { path: { org_id: this.orgId } },
519
+ body: name ? { name } : undefined,
520
+ parseAs: "json",
521
+ });
522
+ return assertOk(resp).role_id;
523
+ }
524
+
525
+ /**
526
+ * Get a role by its id (or name).
527
+ * @param {string} roleId The id of the role to get.
528
+ * @return {RoleInfo} The role.
529
+ */
530
+ async roleGet(roleId: string): Promise<RoleInfo> {
531
+ const client = await this.client();
532
+ const resp = await client.get("/v0/org/{org_id}/roles/{role_id}", {
533
+ params: { path: { org_id: this.orgId, role_id: roleId } },
534
+ parseAs: "json",
535
+ });
536
+ return assertOk(resp);
537
+ }
538
+
539
+ /**
540
+ * Update a role.
541
+ *
542
+ * @param {string} roleId The ID of the role to update.
543
+ * @param {UpdateRoleRequest} request The update request.
544
+ * @return {Promise<RoleInfo>} The updated role information.
545
+ */
546
+ async roleUpdate(roleId: string, request: UpdateRoleRequest): Promise<RoleInfo> {
547
+ const client = await this.client();
548
+ const resp = await client.patch("/v0/org/{org_id}/roles/{role_id}", {
549
+ params: { path: { org_id: this.orgId, role_id: roleId } },
550
+ body: request,
551
+ parseAs: "json",
552
+ });
553
+ return assertOk(resp);
554
+ }
555
+
556
+ /**
557
+ * Delete a role by its ID.
558
+ *
559
+ * @param {string} roleId The ID of the role to delete.
560
+ */
561
+ async roleDelete(roleId: string): Promise<void> {
562
+ const client = await this.client();
563
+ const resp = await client.del("/v0/org/{org_id}/roles/{role_id}", {
564
+ params: { path: { org_id: this.orgId, role_id: roleId } },
565
+ parseAs: "json",
566
+ });
567
+ assertOk(resp);
568
+ }
569
+
570
+ /**
571
+ * List all roles in the org.
572
+ *
573
+ * @param {PageOpts} page Pagination options. Defaults to fetching the entire result set.
574
+ * @return {RoleInfo} Paginator for iterating over roles.
575
+ */
576
+ rolesList(page?: PageOpts): Paginator<ListRolesResponse, RoleInfo> {
577
+ const listFn = async (query: PageQueryArgs) => {
578
+ const client = await this.client();
579
+ const resp = await client.get("/v0/org/{org_id}/roles", {
580
+ params: {
581
+ path: { org_id: this.orgId },
582
+ query,
583
+ },
584
+ parseAs: "json",
585
+ });
586
+ return assertOk(resp);
587
+ };
588
+ return new Paginator(
589
+ page ?? Page.default(),
590
+ listFn,
591
+ (r) => r.roles,
592
+ (r) => r.last_evaluated_key,
593
+ );
594
+ }
595
+
596
+ // #endregion
597
+
598
+ // #region ROLE KEYS: roleKeysAdd, roleKeysDelete, roleKeysList
599
+
600
+ /**
601
+ * Add existing keys to an existing role.
602
+ *
603
+ * @param {string} roleId The ID of the role
604
+ * @param {string[]} keyIds The IDs of the keys to add to the role.
605
+ * @param {KeyPolicy?} policy The optional policy to apply to each key.
606
+ */
607
+ async roleKeysAdd(roleId: string, keyIds: string[], policy?: KeyPolicy) {
608
+ const client = await this.client();
609
+ const resp = await client.put("/v0/org/{org_id}/roles/{role_id}/add_keys", {
610
+ params: { path: { org_id: this.#orgId, role_id: roleId } },
611
+ body: {
612
+ key_ids: keyIds,
613
+ policy: (policy ?? null) as Record<string, never>[] | null,
614
+ },
615
+ parseAs: "json",
616
+ });
617
+ assertOk(resp, "Failed to add keys to role");
618
+ }
619
+
620
+ /**
621
+ * Remove an existing key from an existing role.
622
+ *
623
+ * @param {string} roleId The ID of the role
624
+ * @param {string} keyId The ID of the key to remove from the role
625
+ */
626
+ async roleKeysRemove(roleId: string, keyId: string) {
627
+ const client = await this.client();
628
+ const resp = await client.del("/v0/org/{org_id}/roles/{role_id}/keys/{key_id}", {
629
+ params: { path: { org_id: this.#orgId, role_id: roleId, key_id: keyId } },
630
+ parseAs: "json",
631
+ });
632
+ assertOk(resp, "Failed to remove key from a role");
633
+ }
634
+
635
+ /**
636
+ * List all keys in a role.
637
+ *
638
+ * @param {string} roleId The ID of the role whose keys to retrieve.
639
+ * @param {PageOpts} page Pagination options. Defaults to fetching the entire result set.
640
+ * @return {Paginator<ListRoleKeysResponse, KeyInRoleInfo>} Paginator for iterating over the keys in the role.
641
+ */
642
+ roleKeysList(roleId: string, page?: PageOpts): Paginator<ListRoleKeysResponse, KeyInRoleInfo> {
643
+ const listFn = async (query: PageQueryArgs) => {
644
+ const client = await this.client();
645
+ const resp = await client.get("/v0/org/{org_id}/roles/{role_id}/keys", {
646
+ params: {
647
+ path: { org_id: this.orgId, role_id: roleId },
648
+ query,
649
+ },
650
+ parseAs: "json",
651
+ });
652
+ return assertOk(resp);
653
+ };
654
+ return new Paginator(
655
+ page ?? Page.default(),
656
+ listFn,
657
+ (r) => r.keys,
658
+ (r) => r.last_evaluated_key,
659
+ );
660
+ }
661
+
662
+ // #endregion
663
+
664
+ // #region ROLE USERS: roleUserAdd, roleUsersList
665
+
666
+ /**
667
+ * Add an existing user to an existing role.
668
+ *
669
+ * @param {string} roleId The ID of the role.
670
+ * @param {string} userId The ID of the user to add to the role.
671
+ */
672
+ async roleUserAdd(roleId: string, userId: string) {
673
+ const client = await this.client();
674
+ const resp = await client.put("/v0/org/{org_id}/roles/{role_id}/add_user/{user_id}", {
675
+ params: { path: { org_id: this.#orgId, role_id: roleId, user_id: userId } },
676
+ parseAs: "json",
677
+ });
678
+ assertOk(resp, "Failed to add user to role");
679
+ }
680
+
681
+ /**
682
+ * List all users in a role.
683
+ *
684
+ * @param {string} roleId The ID of the role whose users to retrieve.
685
+ * @param {PageOpts} page Pagination options. Defaults to fetching the entire result set.
686
+ * @return {Paginator<ListRoleUsersResponse, UserInRoleInfo>} Paginator for iterating over the users in the role.
687
+ */
688
+ roleUsersList(roleId: string, page?: PageOpts): Paginator<ListRoleUsersResponse, UserInRoleInfo> {
689
+ const listFn = async (query: PageQueryArgs) => {
690
+ const client = await this.client();
691
+ const resp = await client.get("/v0/org/{org_id}/roles/{role_id}/users", {
692
+ params: {
693
+ path: { org_id: this.orgId, role_id: roleId },
694
+ query,
695
+ },
696
+ parseAs: "json",
697
+ });
698
+ return assertOk(resp);
699
+ };
700
+ return new Paginator(
701
+ page ?? Page.default(),
702
+ listFn,
703
+ (r) => r.users,
704
+ (r) => r.last_evaluated_key,
705
+ );
706
+ }
707
+
708
+ // #endregion
709
+
710
+ // #region SESSIONS: sessionCreateForRole, sessionRefresh, sessionRevoke, sessionsList, sessionKeysList
711
+
712
+ /**
713
+ * Create a new signer session for a given role.
714
+ *
715
+ * @param {string} roleId Role ID
716
+ * @param {string} purpose The purpose of the session
717
+ * @param {string[]} scopes Session scopes. Only `sign:*` scopes are allowed.
718
+ * @param {SignerSessionLifetime} lifetimes Lifetime settings
719
+ * @return {Promise<SignerSessionData>} New signer session info.
720
+ */
721
+ async sessionCreateForRole(
722
+ roleId: string,
723
+ purpose: string,
724
+ scopes?: string[],
725
+ lifetimes?: SignerSessionLifetime,
726
+ ): Promise<SignerSessionData> {
727
+ lifetimes ??= defaultSignerSessionLifetime;
728
+ const invalidScopes = (scopes || []).filter((s) => !s.startsWith("sign:"));
729
+ if (invalidScopes.length > 0) {
730
+ throw new Error(`Role scopes must start with 'sign:'; invalid scopes: ${invalidScopes}`);
731
+ }
732
+
733
+ const client = await this.client();
734
+ const resp = await client.post("/v0/org/{org_id}/roles/{role_id}/tokens", {
735
+ params: { path: { org_id: this.orgId, role_id: roleId } },
736
+ body: {
737
+ purpose,
738
+ scopes,
739
+ auth_lifetime: lifetimes.auth,
740
+ refresh_lifetime: lifetimes.refresh,
741
+ session_lifetime: lifetimes.session,
742
+ grace_lifetime: lifetimes.grace,
743
+ },
744
+ parseAs: "json",
745
+ });
746
+ const data = assertOk(resp);
747
+ return {
748
+ org_id: this.orgId,
749
+ role_id: roleId,
750
+ purpose,
751
+ token: data.token,
752
+ session_info: data.session_info,
753
+ // Keep compatibility with tokens produced by CLI
754
+ env: {
755
+ ["Dev-CubeSignerStack"]: this.#sessionMgr.env,
756
+ },
757
+ };
758
+ }
759
+
760
+ /**
761
+ * Revoke a session.
762
+ *
763
+ * @param {string} sessionId The ID of the session to revoke.
764
+ */
765
+ async sessionRevoke(sessionId: string) {
766
+ const client = await this.client();
767
+ const resp = await client.del("/v0/org/{org_id}/session/{session_id}", {
768
+ params: { path: { org_id: this.orgId, session_id: sessionId } },
769
+ parseAs: "json",
770
+ });
771
+ assertOk(resp);
772
+ }
773
+
774
+ /**
775
+ * Returns a paginator for iterating over all signer sessions optionally filtered by a role.
776
+ *
777
+ * @param {string?} roleId If set, limit to sessions for this role only.
778
+ * @param {PageOpts?} page Pagination options. Defaults to fetching the entire result set.
779
+ * @return {Promise<SignerSessionInfo[]>} Signer sessions for this role.
780
+ */
781
+ sessionsList(roleId?: string, page?: PageOpts): Paginator<SessionsResponse, SessionInfo> {
782
+ const listFn = async (query: PageQueryArgs) => {
783
+ const client = await this.client();
784
+ const resp = await client.get("/v0/org/{org_id}/session", {
785
+ params: {
786
+ path: { org_id: this.#orgId },
787
+ query: { role: roleId, ...query },
788
+ },
789
+ parseAs: "json",
790
+ });
791
+ return assertOk(resp);
792
+ };
793
+ return new Paginator(
794
+ page ?? Page.default(),
795
+ listFn,
796
+ (r) => r.sessions,
797
+ (r) => r.last_evaluated_key,
798
+ );
799
+ }
800
+
801
+ /**
802
+ * Returns the list of keys that this session has access to.
803
+ * @return {Key[]} The list of keys.
804
+ */
805
+ async sessionKeysList(): Promise<KeyInfoApi[]> {
806
+ const client = await this.client();
807
+ const resp = await client.get("/v0/org/{org_id}/token/keys", {
808
+ params: { path: { org_id: this.orgId } },
809
+ parseAs: "json",
810
+ });
811
+ return assertOk(resp).keys;
812
+ }
813
+
814
+ // #endregion
815
+
816
+ // #region IDENTITY: identityProve, identityVerify
817
+
818
+ /**
819
+ * Obtain proof of authentication using the current CubeSigner session.
820
+ *
821
+ * @return {Promise<IdentityProof>} Proof of authentication
822
+ */
823
+ async identityProve(): Promise<IdentityProof> {
824
+ const client = await this.client();
825
+ const resp = await client.post("/v0/org/{org_id}/identity/prove", {
826
+ params: { path: { org_id: this.orgId } },
827
+ parseAs: "json",
828
+ });
829
+ return assertOk(resp);
830
+ }
831
+
832
+ /**
833
+ * Checks if a given identity proof is valid.
834
+ *
835
+ * @param {IdentityProof} proof The proof of authentication.
836
+ */
837
+ async identityVerify(proof: IdentityProof) {
838
+ const client = await this.client();
839
+ const resp = await client.post("/v0/org/{org_id}/identity/verify", {
840
+ params: { path: { org_id: this.orgId } },
841
+ body: proof,
842
+ parseAs: "json",
843
+ });
844
+ assertOk(resp);
845
+ }
846
+
847
+ // #endregion
848
+
849
+ // #region MFA: mfaGet, mfaList, mfaApprove, mfaList, mfaApprove, mfaApproveTotp, mfaApproveFido(Init|Complete)
850
+
851
+ /**
852
+ * Retrieves existing MFA request.
853
+ *
854
+ * @param {string} mfaId MFA request ID
855
+ * @return {Promise<MfaRequestInfo>} MFA request information
856
+ */
857
+ async mfaGet(mfaId: string): Promise<MfaRequestInfo> {
858
+ const client = await this.client();
859
+ const resp = await client.get("/v0/org/{org_id}/mfa/{mfa_id}", {
860
+ params: { path: { org_id: this.orgId, mfa_id: mfaId } },
861
+ });
862
+ return assertOk(resp);
863
+ }
864
+
865
+ /**
866
+ * List pending MFA requests accessible to the current user.
867
+ *
868
+ * @return {Promise<MfaRequestInfo[]>} The MFA requests.
869
+ */
870
+ async mfaList(): Promise<MfaRequestInfo[]> {
871
+ const client = await this.client();
872
+ const resp = await client.get("/v0/org/{org_id}/mfa", {
873
+ params: { path: { org_id: this.orgId } },
874
+ });
875
+ return assertOk(resp).mfa_requests;
876
+ }
877
+
878
+ /**
879
+ * Approve a pending MFA request using the current session.
880
+ *
881
+ * @param {string} mfaId The id of the MFA request
882
+ * @return {Promise<MfaRequestInfo>} The result of the MFA request
883
+ */
884
+ async mfaApprove(mfaId: string): Promise<MfaRequestInfo> {
885
+ const client = await this.client();
886
+ const resp = await client.patch("/v0/org/{org_id}/mfa/{mfa_id}", {
887
+ params: { path: { org_id: this.orgId, mfa_id: mfaId } },
888
+ });
889
+ return assertOk(resp);
890
+ }
891
+
892
+ /**
893
+ * Approve a pending MFA request using TOTP.
894
+ *
895
+ * @param {string} mfaId The MFA request to approve
896
+ * @param {string} code The TOTP code
897
+ * @return {Promise<MfaRequestInfo>} The current status of the MFA request
898
+ */
899
+ async mfaApproveTotp(mfaId: string, code: string): Promise<MfaRequestInfo> {
900
+ const client = await this.client();
901
+ const resp = await client.patch("/v0/org/{org_id}/mfa/{mfa_id}/totp", {
902
+ params: { path: { org_id: this.#orgId, mfa_id: mfaId } },
903
+ body: { code },
904
+ parseAs: "json",
905
+ });
906
+ return assertOk(resp);
907
+ }
908
+
909
+ /**
910
+ * Initiate approval of an existing MFA request using FIDO. A challenge is
911
+ * returned which must be answered via {@link MfaFidoChallenge.answer} or {@link mfaApproveFidoComplete}.
912
+ *
913
+ * @param {string} mfaId The MFA request ID.
914
+ * @return {Promise<MfaFidoChallenge>} A challenge that needs to be answered to complete the approval.
915
+ */
916
+ async mfaApproveFidoInit(mfaId: string): Promise<MfaFidoChallenge> {
917
+ const client = await this.client();
918
+ const resp = await client.post("/v0/org/{org_id}/mfa/{mfa_id}/fido", {
919
+ params: { path: { org_id: this.orgId, mfa_id: mfaId } },
920
+ parseAs: "json",
921
+ });
922
+ const challenge = assertOk(resp);
923
+ return new MfaFidoChallenge(this, mfaId, challenge);
924
+ }
925
+
926
+ /**
927
+ * Complete a previously initiated (via {@link mfaApproveFidoInit}) MFA request approval using FIDO.
928
+ *
929
+ * Instead of calling this method directly, prefer {@link MfaFidoChallenge.answer} or
930
+ * {@link MfaFidoChallenge.createCredentialAndAnswer}.
931
+ *
932
+ * @param {string} mfaId The MFA request ID
933
+ * @param {string} challengeId The ID of the challenge issued by {@link mfaApproveFidoInit}
934
+ * @param {PublicKeyCredential} credential The answer to the challenge
935
+ * @return {Promise<MfaRequestInfo>} The current status of the MFA request.
936
+ */
937
+ async mfaApproveFidoComplete(
938
+ mfaId: string,
939
+ challengeId: string,
940
+ credential: PublicKeyCredential,
941
+ ): Promise<MfaRequestInfo> {
942
+ const client = await this.client();
943
+ const resp = await client.patch("/v0/org/{org_id}/mfa/{mfa_id}/fido", {
944
+ params: { path: { org_id: this.orgId, mfa_id: mfaId } },
945
+ body: {
946
+ challenge_id: challengeId,
947
+ credential,
948
+ },
949
+ parseAs: "json",
950
+ });
951
+ return assertOk(resp);
952
+ }
953
+
954
+ // #endregion
955
+
956
+ // #region SIGN: signEvm, signEth2, signStake, signUnstake, signAva, signBlob, signBtc, signSolana
957
+
958
+ /**
959
+ * Sign an EVM transaction.
960
+ * @param {Key | string} key The key to sign with (either {@link Key} or its material ID).
961
+ * @param {EvmSignRequest} req What to sign.
962
+ * @param {MfaReceipt} mfaReceipt Optional MFA receipt.
963
+ * @return {Promise<EvmSignResponse | AcceptedResponse>} Signature (or MFA approval request).
964
+ */
965
+ async signEvm(
966
+ key: Key | string,
967
+ req: EvmSignRequest,
968
+ mfaReceipt?: MfaReceipt,
969
+ ): Promise<CubeSignerResponse<EvmSignResponse>> {
970
+ const pubkey = typeof key === "string" ? (key as string) : key.materialId;
971
+ const sign = async (headers?: HeadersInit) => {
972
+ const client = await this.client();
973
+ const resp = await client.post("/v1/org/{org_id}/eth1/sign/{pubkey}", {
974
+ params: { path: { org_id: this.orgId, pubkey } },
975
+ body: req,
976
+ headers,
977
+ parseAs: "json",
978
+ });
979
+ return assertOk(resp);
980
+ };
981
+ return await CubeSignerResponse.create(sign, mfaReceipt);
982
+ }
983
+
984
+ /**
985
+ * Sign an Eth2/Beacon-chain validation message.
986
+ *
987
+ * @param {Key | string} key The key to sign with (either {@link Key} or its material ID).
988
+ * @param {Eth2SignRequest} req What to sign.
989
+ * @param {MfaReceipt} mfaReceipt Optional MFA receipt
990
+ * @return {Promise<Eth2SignResponse | AcceptedResponse>} Signature
991
+ */
992
+ async signEth2(
993
+ key: Key | string,
994
+ req: Eth2SignRequest,
995
+ mfaReceipt?: MfaReceipt,
996
+ ): Promise<CubeSignerResponse<Eth2SignResponse>> {
997
+ const pubkey = typeof key === "string" ? (key as string) : key.materialId;
998
+ const sign = async (headers?: HeadersInit) => {
999
+ const client = await this.client();
1000
+ const resp = await client.post("/v1/org/{org_id}/eth2/sign/{pubkey}", {
1001
+ params: { path: { org_id: this.orgId, pubkey } },
1002
+ body: req,
1003
+ headers,
1004
+ parseAs: "json",
1005
+ });
1006
+ return assertOk(resp);
1007
+ };
1008
+ return await CubeSignerResponse.create(sign, mfaReceipt);
1009
+ }
1010
+
1011
+ /**
1012
+ * Sign an Eth2/Beacon-chain deposit (or staking) message.
1013
+ *
1014
+ * @param {Eth2StakeRequest} req The request to sign.
1015
+ * @param {MfaReceipt} mfaReceipt Optional MFA receipt
1016
+ * @return {Promise<Eth2StakeResponse | AcceptedResponse>} The response.
1017
+ */
1018
+ async signStake(
1019
+ req: Eth2StakeRequest,
1020
+ mfaReceipt?: MfaReceipt,
1021
+ ): Promise<CubeSignerResponse<Eth2StakeResponse>> {
1022
+ const sign = async (headers?: HeadersInit) => {
1023
+ const client = await this.client();
1024
+ const resp = await client.post("/v1/org/{org_id}/eth2/stake", {
1025
+ params: { path: { org_id: this.orgId } },
1026
+ body: req,
1027
+ headers,
1028
+ parseAs: "json",
1029
+ });
1030
+ return assertOk(resp);
1031
+ };
1032
+ return await CubeSignerResponse.create(sign, mfaReceipt);
1033
+ }
1034
+
1035
+ /**
1036
+ * Sign an Eth2/Beacon-chain unstake/exit request.
1037
+ *
1038
+ * @param {Key | string} key The key to sign with (either {@link Key} or its material ID).
1039
+ * @param {Eth2UnstakeRequest} req The request to sign.
1040
+ * @param {MfaReceipt} mfaReceipt Optional MFA receipt
1041
+ * @return {Promise<Eth2UnstakeResponse | AcceptedResponse>} The response.
1042
+ */
1043
+ async signUnstake(
1044
+ key: Key | string,
1045
+ req: Eth2UnstakeRequest,
1046
+ mfaReceipt?: MfaReceipt,
1047
+ ): Promise<CubeSignerResponse<Eth2UnstakeResponse>> {
1048
+ const pubkey = typeof key === "string" ? (key as string) : key.materialId;
1049
+ const sign = async (headers?: HeadersInit) => {
1050
+ const client = await this.client();
1051
+ const resp = await client.post("/v1/org/{org_id}/eth2/unstake/{pubkey}", {
1052
+ params: { path: { org_id: this.orgId, pubkey } },
1053
+ body: req,
1054
+ headers,
1055
+ parseAs: "json",
1056
+ });
1057
+ return assertOk(resp);
1058
+ };
1059
+ return await CubeSignerResponse.create(sign, mfaReceipt);
1060
+ }
1061
+
1062
+ /**
1063
+ * Sign an Avalanche P- or X-chain message.
1064
+ * @param {Key | string} key The key to sign with (either {@link Key} or its material ID).
1065
+ * @param {AvaTx} tx Avalanche message (transaction) to sign
1066
+ * @param {MfaReceipt} mfaReceipt Optional MFA receipt
1067
+ * @return {Promise<AvaSignResponse | AcceptedResponse>} The response.
1068
+ */
1069
+ async signAva(
1070
+ key: Key | string,
1071
+ tx: AvaTx,
1072
+ mfaReceipt?: MfaReceipt,
1073
+ ): Promise<CubeSignerResponse<AvaSignResponse>> {
1074
+ const pubkey = typeof key === "string" ? (key as string) : key.materialId;
1075
+ const sign = async (headers?: HeadersInit) => {
1076
+ const req = <AvaSignRequest>{
1077
+ tx: tx as unknown,
1078
+ };
1079
+ const client = await this.client();
1080
+ const resp = await client.post("/v0/org/{org_id}/ava/sign/{pubkey}", {
1081
+ params: { path: { org_id: this.orgId, pubkey } },
1082
+ body: req,
1083
+ headers,
1084
+ parseAs: "json",
1085
+ });
1086
+ return assertOk(resp);
1087
+ };
1088
+ return await CubeSignerResponse.create(sign, mfaReceipt);
1089
+ }
1090
+
1091
+ /**
1092
+ * Sign a raw blob.
1093
+ *
1094
+ * This requires the key to have a '"AllowRawBlobSigning"' {@link KeyPolicy}. This is because
1095
+ * signing arbitrary messages is, in general, dangerous (and you should instead
1096
+ * prefer typed end-points as used by, for example, {@link signEvm}). For Secp256k1 keys,
1097
+ * for example, you **must** call this function with a message that is 32 bytes long and
1098
+ * the output of a secure hash function.
1099
+ *
1100
+ * This function returns signatures serialized as;
1101
+ *
1102
+ * - ECDSA signatures are serialized as big-endian r and s plus recovery-id
1103
+ * byte v, which can in general take any of the values 0, 1, 2, or 3.
1104
+ *
1105
+ * - EdDSA signatures are serialized in the standard format.
1106
+ *
1107
+ * - BLS signatures are not supported on the blob-sign endpoint.
1108
+ *
1109
+ * @param {Key | string} key The key to sign with (either {@link Key} or its ID).
1110
+ * @param {BlobSignRequest} req What to sign
1111
+ * @param {MfaReceipt} mfaReceipt Optional MFA receipt
1112
+ * @return {Promise<BlobSignResponse | AcceptedResponse>} The response.
1113
+ */
1114
+ async signBlob(
1115
+ key: Key | string,
1116
+ req: BlobSignRequest,
1117
+ mfaReceipt?: MfaReceipt,
1118
+ ): Promise<CubeSignerResponse<BlobSignResponse>> {
1119
+ const key_id = typeof key === "string" ? (key as string) : key.id;
1120
+ const sign = async (headers?: HeadersInit) => {
1121
+ const client = await this.client();
1122
+ const resp = await client.post("/v1/org/{org_id}/blob/sign/{key_id}", {
1123
+ params: {
1124
+ path: { org_id: this.orgId, key_id },
1125
+ },
1126
+ body: req,
1127
+ headers,
1128
+ parseAs: "json",
1129
+ });
1130
+ return assertOk(resp);
1131
+ };
1132
+ return await CubeSignerResponse.create(sign, mfaReceipt);
1133
+ }
1134
+
1135
+ /**
1136
+ * Sign a Bitcoin message.
1137
+ *
1138
+ * @param {Key | string} key The key to sign with (either {@link Key} or its material ID).
1139
+ * @param {BtcSignRequest} req What to sign
1140
+ * @param {MfaReceipt} mfaReceipt Optional MFA receipt
1141
+ * @return {Promise<BtcSignResponse | AcceptedResponse>} The response.
1142
+ */
1143
+ async signBtc(
1144
+ key: Key | string,
1145
+ req: BtcSignRequest,
1146
+ mfaReceipt?: MfaReceipt,
1147
+ ): Promise<CubeSignerResponse<BtcSignResponse>> {
1148
+ const pubkey = typeof key === "string" ? (key as string) : key.materialId;
1149
+ const sign = async (headers?: HeadersInit) => {
1150
+ const client = await this.client();
1151
+ const resp = await client.post("/v0/org/{org_id}/btc/sign/{pubkey}", {
1152
+ params: {
1153
+ path: { org_id: this.orgId, pubkey },
1154
+ },
1155
+ body: req,
1156
+ headers: headers,
1157
+ parseAs: "json",
1158
+ });
1159
+ return assertOk(resp);
1160
+ };
1161
+ return await CubeSignerResponse.create(sign, mfaReceipt);
1162
+ }
1163
+
1164
+ /**
1165
+ * Sign a Solana message.
1166
+ *
1167
+ * @param {Key | string} key The key to sign with (either {@link Key} or its material ID).
1168
+ * @param {SolanaSignRequest} req What to sign
1169
+ * @param {MfaReceipt} mfaReceipt Optional MFA receipt
1170
+ * @return {Promise<SolanaSignResponse | AcceptedResponse>} The response.
1171
+ */
1172
+ async signSolana(
1173
+ key: Key | string,
1174
+ req: SolanaSignRequest,
1175
+ mfaReceipt?: MfaReceipt,
1176
+ ): Promise<CubeSignerResponse<SolanaSignResponse>> {
1177
+ const pubkey = typeof key === "string" ? (key as string) : key.materialId;
1178
+ const sign = async (headers?: HeadersInit) => {
1179
+ const client = await this.client();
1180
+ const resp = await client.post("/v0/org/{org_id}/solana/sign/{pubkey}", {
1181
+ params: { path: { org_id: this.orgId, pubkey } },
1182
+ body: req,
1183
+ headers,
1184
+ parseAs: "json",
1185
+ });
1186
+ return assertOk(resp);
1187
+ };
1188
+ return await CubeSignerResponse.create(sign, mfaReceipt);
1189
+ }
1190
+ // #endregion
1191
+
1192
+ /** HTTPS client */
1193
+ private async client(): Promise<Client> {
1194
+ return await this.#sessionMgr.client();
1195
+ }
1196
+
1197
+ // #region USER EXPORT: userExport(Init,Complete,List,Delete)
1198
+ /**
1199
+ * List outstanding user-export requests.
1200
+ *
1201
+ * @param {string?} keyId Optional key ID. If supplied, list the outstanding request (if any) only for the specified key; otherwise, list all outstanding requests for the specified user.
1202
+ * @param {string?} userId Optional user ID. If omtted, uses the current user's ID. Only org owners can list user-export requests for users other than themselves.
1203
+ * @param {PageOpts?} page Pagination options. Defaults to fetching the entire result set.
1204
+ * @return {Paginator<UserExportListResponse, UserExportInitResponse>} Paginator for iterating over the result set.
1205
+ */
1206
+ userExportList(
1207
+ keyId?: string,
1208
+ userId?: string,
1209
+ page?: PageOpts,
1210
+ ): Paginator<UserExportListResponse, UserExportInitResponse> {
1211
+ const listFn = async (query: PageQueryArgs) => {
1212
+ const client = await this.client();
1213
+ const resp = await client.get("/v0/org/{org_id}/user/me/export", {
1214
+ params: {
1215
+ path: { org_id: this.orgId },
1216
+ query: {
1217
+ user_id: userId,
1218
+ key_id: keyId,
1219
+ ...query,
1220
+ },
1221
+ },
1222
+ parseAs: "json",
1223
+ });
1224
+ return assertOk(resp);
1225
+ };
1226
+ return new Paginator(
1227
+ page ?? Page.default(),
1228
+ listFn,
1229
+ (r) => r.export_requests,
1230
+ (r) => r.last_evaluated_key,
1231
+ );
1232
+ }
1233
+
1234
+ /**
1235
+ * Delete an outstanding user-export request.
1236
+ *
1237
+ * @param {string} keyId The key-id corresponding to the user-export request to delete.
1238
+ * @param {string?} userId Optional user ID. If omitted, uses the current user's ID. Only org owners can delete user-export requests for users other than themselves.
1239
+ */
1240
+ async userExportDelete(keyId: string, userId?: string): Promise<void> {
1241
+ const client = await this.client();
1242
+ const resp = await client.del("/v0/org/{org_id}/user/me/export", {
1243
+ params: {
1244
+ path: { org_id: this.orgId },
1245
+ query: {
1246
+ key_id: keyId,
1247
+ user_id: userId,
1248
+ },
1249
+ },
1250
+ parseAs: "json",
1251
+ });
1252
+ assertOk(resp);
1253
+ }
1254
+
1255
+ /**
1256
+ * Initiate a user-export request.
1257
+ *
1258
+ * @param {string} keyId The key-id for which to initiate an export.
1259
+ * @param {MfaReceipt} mfaReceipt Optional MFA receipt.
1260
+ * @return {Promise<UserExportInitResponse | AcceptedResponse>} The response.
1261
+ */
1262
+ async userExportInit(
1263
+ keyId: string,
1264
+ mfaReceipt?: MfaReceipt,
1265
+ ): Promise<CubeSignerResponse<UserExportInitResponse>> {
1266
+ const init = async (headers?: HeadersInit) => {
1267
+ const client = await this.client();
1268
+ const resp = await client.post("/v0/org/{org_id}/user/me/export", {
1269
+ params: { path: { org_id: this.orgId } },
1270
+ body: { key_id: keyId },
1271
+ headers,
1272
+ parseAs: "json",
1273
+ });
1274
+ return assertOk(resp);
1275
+ };
1276
+ return await CubeSignerResponse.create(init, mfaReceipt);
1277
+ }
1278
+
1279
+ /**
1280
+ * Complete a user-export request.
1281
+ *
1282
+ * @param {string} keyId The key-id for which to initiate an export.
1283
+ * @param {CryptoKey} publicKey The NIST P-256 public key to which the export will be encrypted. This should be the `publicKey` property of a value returned by `userExportKeygen`.
1284
+ * @param {MfaReceipt} mfaReceipt Optional MFA receipt.
1285
+ * @return {Promise<UserExportCompleteResponse | AcceptedResponse>} The response.
1286
+ */
1287
+ async userExportComplete(
1288
+ keyId: string,
1289
+ publicKey: CryptoKey,
1290
+ mfaReceipt?: MfaReceipt,
1291
+ ): Promise<CubeSignerResponse<UserExportCompleteResponse>> {
1292
+ // base64-encode the public key
1293
+ const subtle = await loadSubtleCrypto();
1294
+ const publicKeyB64 = encodeToBase64(Buffer.from(await subtle.exportKey("raw", publicKey)));
1295
+
1296
+ // make the request
1297
+ const complete = async (headers?: HeadersInit) => {
1298
+ const client = await this.client();
1299
+ const resp = await client.patch("/v0/org/{org_id}/user/me/export", {
1300
+ params: { path: { org_id: this.orgId } },
1301
+ body: {
1302
+ key_id: keyId,
1303
+ public_key: publicKeyB64,
1304
+ },
1305
+ headers,
1306
+ parseAs: "json",
1307
+ });
1308
+ return assertOk(resp);
1309
+ };
1310
+ return await CubeSignerResponse.create(complete, mfaReceipt);
1311
+ }
1312
+ // #endregion
1313
+ }
1314
+
1315
+ /**
1316
+ * Client to use to send requests to CubeSigner services
1317
+ * when authenticating using an OIDC token.
1318
+ */
1319
+ export class OidcClient {
1320
+ readonly #env: EnvInterface;
1321
+ readonly #orgId: string;
1322
+ readonly #client: Client;
1323
+
1324
+ /**
1325
+ * @param {EnvInterface} env CubeSigner deployment
1326
+ * @param {string} orgId Target organization ID
1327
+ * @param {string} oidcToken User's OIDC token
1328
+ */
1329
+ constructor(env: EnvInterface, orgId: string, oidcToken: string) {
1330
+ this.#orgId = orgId;
1331
+ this.#env = env;
1332
+ this.#client = createHttpClient(env.SignerApiRoot, oidcToken);
1333
+ }
1334
+
1335
+ /**
1336
+ * Exchange an OIDC token for a CubeSigner session token.
1337
+ * @param {List<string>} scopes The scopes for the new session
1338
+ * @param {RatchetConfig} lifetimes Lifetimes of the new session.
1339
+ * @param {MfaReceipt} mfaReceipt Optional MFA receipt (id + confirmation code)
1340
+ * @return {Promise<CubeSignerResponse<SignerSessionData>>} The session data.
1341
+ */
1342
+ async sessionCreate(
1343
+ scopes: Array<string>,
1344
+ lifetimes?: RatchetConfig,
1345
+ mfaReceipt?: MfaReceipt,
1346
+ ): Promise<CubeSignerResponse<SignerSessionData>> {
1347
+ const loginFn = async (headers?: HeadersInit) => {
1348
+ const resp = await this.#client.post("/v0/org/{org_id}/oidc", {
1349
+ params: { path: { org_id: this.#orgId } },
1350
+ headers,
1351
+ body: {
1352
+ scopes,
1353
+ tokens: lifetimes,
1354
+ },
1355
+ parseAs: "json",
1356
+ });
1357
+ const data = assertOk(resp);
1358
+ return mapResponse(
1359
+ data,
1360
+ (sessionInfo) =>
1361
+ <SignerSessionData>{
1362
+ env: {
1363
+ ["Dev-CubeSignerStack"]: this.#env,
1364
+ },
1365
+ org_id: this.#orgId,
1366
+ token: sessionInfo.token,
1367
+ purpose: "sign via oidc",
1368
+ session_info: sessionInfo.session_info,
1369
+ },
1370
+ );
1371
+ };
1372
+
1373
+ return await CubeSignerResponse.create(loginFn, mfaReceipt);
1374
+ }
1375
+
1376
+ /**
1377
+ * Exchange an OIDC token for a proof of authentication.
1378
+ *
1379
+ * @return {Promise<IdentityProof>} Proof of authentication
1380
+ */
1381
+ async identityProve(): Promise<IdentityProof> {
1382
+ const resp = await this.#client.post("/v0/org/{org_id}/identity/prove/oidc", {
1383
+ params: { path: { org_id: this.#orgId } },
1384
+ parseAs: "json",
1385
+ });
1386
+ return assertOk(resp);
1387
+ }
1388
+ }
1389
+
1390
+ const defaultSignerSessionLifetime: SignerSessionLifetime = {
1391
+ session: 604800, // 1 week
1392
+ auth: 300, // 5 min
1393
+ refresh: 86400, // 1 day
1394
+ grace: 30, // seconds
1395
+ };