@arcblock/did-connect-js 1.29.23 → 4.0.0-beta.2

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 (118) hide show
  1. package/{lib/adapters/detect.d.cts → dist/adapters/detect.d.ts} +3 -5
  2. package/dist/adapters/detect.d.ts.map +1 -0
  3. package/dist/adapters/detect.js +13 -0
  4. package/dist/adapters/detect.js.map +1 -0
  5. package/dist/adapters/express.d.ts +40 -0
  6. package/dist/adapters/express.d.ts.map +1 -0
  7. package/dist/adapters/express.js +30 -0
  8. package/dist/adapters/express.js.map +1 -0
  9. package/dist/adapters/hono.d.ts +49 -0
  10. package/dist/adapters/hono.d.ts.map +1 -0
  11. package/dist/adapters/hono.js +176 -0
  12. package/dist/adapters/hono.js.map +1 -0
  13. package/dist/authenticator/base.d.ts +21 -0
  14. package/dist/authenticator/base.d.ts.map +1 -0
  15. package/dist/authenticator/base.js +109 -0
  16. package/dist/authenticator/base.js.map +1 -0
  17. package/dist/authenticator/wallet.d.ts +221 -0
  18. package/dist/authenticator/wallet.d.ts.map +1 -0
  19. package/dist/authenticator/wallet.js +588 -0
  20. package/dist/authenticator/wallet.js.map +1 -0
  21. package/dist/handlers/base.d.ts +25 -0
  22. package/dist/handlers/base.d.ts.map +1 -0
  23. package/dist/handlers/base.js +48 -0
  24. package/dist/handlers/base.js.map +1 -0
  25. package/dist/handlers/util.d.ts +48 -0
  26. package/dist/handlers/util.d.ts.map +1 -0
  27. package/dist/handlers/util.js +812 -0
  28. package/dist/handlers/util.js.map +1 -0
  29. package/dist/handlers/wallet.d.ts +96 -0
  30. package/dist/handlers/wallet.d.ts.map +1 -0
  31. package/dist/handlers/wallet.js +129 -0
  32. package/dist/handlers/wallet.js.map +1 -0
  33. package/dist/index.d.ts +10 -0
  34. package/dist/index.d.ts.map +1 -0
  35. package/dist/index.js +9 -0
  36. package/dist/index.js.map +1 -0
  37. package/dist/protocol.d.ts +14 -0
  38. package/dist/protocol.d.ts.map +1 -0
  39. package/dist/protocol.js +37 -0
  40. package/dist/protocol.js.map +1 -0
  41. package/dist/schema/claims.d.ts +17 -0
  42. package/dist/schema/claims.d.ts.map +1 -0
  43. package/dist/schema/claims.js +205 -0
  44. package/dist/schema/claims.js.map +1 -0
  45. package/dist/schema/index.d.ts +7 -0
  46. package/dist/schema/index.d.ts.map +1 -0
  47. package/dist/schema/index.js +49 -0
  48. package/dist/schema/index.js.map +1 -0
  49. package/dist/storage/kv.d.ts +31 -0
  50. package/dist/storage/kv.d.ts.map +1 -0
  51. package/dist/storage/kv.js +54 -0
  52. package/dist/storage/kv.js.map +1 -0
  53. package/dist/types.d.ts +53 -0
  54. package/dist/types.d.ts.map +1 -0
  55. package/dist/types.js +2 -0
  56. package/dist/types.js.map +1 -0
  57. package/package.json +48 -104
  58. package/LICENSE +0 -13
  59. package/README.md +0 -210
  60. package/esm/_virtual/rolldown_runtime.mjs +0 -8
  61. package/esm/adapters/detect.d.mts +0 -11
  62. package/esm/adapters/detect.mjs +0 -16
  63. package/esm/adapters/express.d.mts +0 -48
  64. package/esm/adapters/express.mjs +0 -39
  65. package/esm/adapters/hono.d.mts +0 -57
  66. package/esm/adapters/hono.mjs +0 -164
  67. package/esm/authenticator/base.d.mts +0 -23
  68. package/esm/authenticator/base.mjs +0 -88
  69. package/esm/authenticator/wallet.d.mts +0 -270
  70. package/esm/authenticator/wallet.mjs +0 -556
  71. package/esm/handlers/base.d.mts +0 -32
  72. package/esm/handlers/base.mjs +0 -37
  73. package/esm/handlers/util.d.mts +0 -70
  74. package/esm/handlers/util.mjs +0 -739
  75. package/esm/handlers/wallet.d.mts +0 -120
  76. package/esm/handlers/wallet.mjs +0 -139
  77. package/esm/index.d.mts +0 -8
  78. package/esm/index.mjs +0 -8
  79. package/esm/package.mjs +0 -118
  80. package/esm/protocol.d.mts +0 -15
  81. package/esm/protocol.mjs +0 -40
  82. package/esm/schema/claims.d.mts +0 -18
  83. package/esm/schema/claims.mjs +0 -154
  84. package/esm/schema/index.d.mts +0 -9
  85. package/esm/schema/index.mjs +0 -49
  86. package/esm/storage/kv.d.mts +0 -33
  87. package/esm/storage/kv.mjs +0 -55
  88. package/esm/types.d.mts +0 -55
  89. package/esm/types.mjs +0 -1
  90. package/lib/_virtual/rolldown_runtime.cjs +0 -31
  91. package/lib/adapters/detect.cjs +0 -18
  92. package/lib/adapters/express.cjs +0 -41
  93. package/lib/adapters/express.d.cts +0 -48
  94. package/lib/adapters/hono.cjs +0 -167
  95. package/lib/adapters/hono.d.cts +0 -57
  96. package/lib/authenticator/base.cjs +0 -91
  97. package/lib/authenticator/base.d.cts +0 -23
  98. package/lib/authenticator/wallet.cjs +0 -564
  99. package/lib/authenticator/wallet.d.cts +0 -270
  100. package/lib/handlers/base.cjs +0 -40
  101. package/lib/handlers/base.d.cts +0 -32
  102. package/lib/handlers/util.cjs +0 -759
  103. package/lib/handlers/util.d.cts +0 -70
  104. package/lib/handlers/wallet.cjs +0 -139
  105. package/lib/handlers/wallet.d.cts +0 -119
  106. package/lib/index.cjs +0 -16
  107. package/lib/index.d.cts +0 -8
  108. package/lib/package.cjs +0 -121
  109. package/lib/protocol.cjs +0 -46
  110. package/lib/protocol.d.cts +0 -15
  111. package/lib/schema/claims.cjs +0 -156
  112. package/lib/schema/claims.d.cts +0 -18
  113. package/lib/schema/index.cjs +0 -52
  114. package/lib/schema/index.d.cts +0 -9
  115. package/lib/storage/kv.cjs +0 -57
  116. package/lib/storage/kv.d.cts +0 -33
  117. package/lib/types.cjs +0 -0
  118. package/lib/types.d.cts +0 -55
@@ -1,564 +0,0 @@
1
- Object.defineProperty(exports, '__esModule', { value: true });
2
- const require_rolldown_runtime = require('../_virtual/rolldown_runtime.cjs');
3
- const require_package$1 = require('../package.cjs');
4
- const require_authenticator_base = require('./base.cjs');
5
- const require_schema_index = require('../schema/index.cjs');
6
- let node_querystring = require("node:querystring");
7
- node_querystring = require_rolldown_runtime.__toESM(node_querystring);
8
- let _arcblock_did = require("@arcblock/did");
9
- let _ocap_client = require("@ocap/client");
10
- _ocap_client = require_rolldown_runtime.__toESM(_ocap_client);
11
- let _ocap_mcrypto_lib_crypter_rsa = require("@ocap/mcrypto/lib/crypter/rsa");
12
- _ocap_mcrypto_lib_crypter_rsa = require_rolldown_runtime.__toESM(_ocap_mcrypto_lib_crypter_rsa);
13
- let _ocap_util = require("@ocap/util");
14
- let _ocap_wallet = require("@ocap/wallet");
15
- let lodash_isEqual = require("lodash/isEqual");
16
- lodash_isEqual = require_rolldown_runtime.__toESM(lodash_isEqual);
17
- let lodash_pick = require("lodash/pick");
18
- lodash_pick = require_rolldown_runtime.__toESM(lodash_pick);
19
- let lodash_random = require("lodash/random");
20
- lodash_random = require_rolldown_runtime.__toESM(lodash_random);
21
- let lodash_shuffle = require("lodash/shuffle");
22
- lodash_shuffle = require_rolldown_runtime.__toESM(lodash_shuffle);
23
-
24
- //#region src/authenticator/wallet.ts
25
- const debug = require("debug")(`${require_package$1.default.name}:authenticator:wallet`);
26
- const DEFAULT_TIMEOUT = 8e3;
27
- const MFA_CODE_COUNT = 3;
28
- var WalletAuthenticator = class WalletAuthenticator extends require_authenticator_base.default {
29
- static formatDisplay(display) {
30
- if (!display) return "";
31
- if (display?.type && display.content) return JSON.stringify((0, lodash_pick.default)(display, ["type", "content"]));
32
- try {
33
- const parsed = JSON.parse(display);
34
- if (parsed?.type && parsed.content) return display;
35
- return "";
36
- } catch (_err) {
37
- return "";
38
- }
39
- }
40
- /**
41
- * Creates an instance of DID Authenticator.
42
- *
43
- * @class
44
- * @param {object} config
45
- * @param {WalletObject|Function} config.wallet - wallet instance {@see @ocap/wallet} or a function that returns wallet instance
46
- * @param {WalletObject|Function} [config.delegator] - the party that authorizes `wallet` to perform actions on behalf of `wallet`
47
- * @param {string|Function} [config.delegation] - the jwt token that proves delegation relationship
48
- * @param {ApplicationInfo|Function} config.appInfo - application basic info or a function that returns application info
49
- * @param {ChainInfo|Function} config.chainInfo - application chain info or a function that returns chain info
50
- * @param {Number} [config.timeout=8000] - timeout in milliseconds when generating claim
51
- * @param {object} [config.baseUrl] - url to assemble wallet request uri, can be inferred from request object
52
- * @param {string} [config.tokenKey='_t_'] - query param key for `token`
53
- */
54
- constructor({ wallet, appInfo: appInfo$1, memberAppInfo, delegator, delegation, timeout = DEFAULT_TIMEOUT, chainInfo: chainInfo$1 = require_authenticator_base.DEFAULT_CHAIN_INFO, baseUrl = "", tokenKey = "_t_" }) {
55
- super();
56
- this.wallet = this._validateWallet(wallet, false);
57
- this.appInfo = this._validateAppInfo(appInfo$1);
58
- this.memberAppInfo = this._validateAppInfo(memberAppInfo, true);
59
- this.chainInfo = chainInfo$1;
60
- this.delegator = delegator;
61
- this.delegation = delegation;
62
- this.baseUrl = baseUrl;
63
- this.tokenKey = tokenKey;
64
- this.timeout = timeout;
65
- if (!this.appInfo.link) this.appInfo.link = this.baseUrl;
66
- }
67
- /**
68
- * Generate a deep link url that can be displayed as QRCode for DID Wallet to consume
69
- *
70
- * @method
71
- * @param {object} params
72
- * @param {string} params.baseUrl - baseUrl inferred from request object
73
- * @param {string} params.pathname - wallet callback pathname
74
- * @param {string} params.token - action token
75
- * @param {object} params.query - params that should be persisted in wallet callback url
76
- * @returns {string}
77
- */
78
- uri({ baseUrl, pathname = "", token = "", query = {} } = {}) {
79
- const params = {
80
- ...query,
81
- [this.tokenKey]: token
82
- };
83
- const payload = {
84
- action: "requestAuth",
85
- url: encodeURIComponent(`${this.baseUrl || baseUrl}${pathname}?${node_querystring.default.stringify(params)}`)
86
- };
87
- const uri = `https://abtwallet.io/i/?${node_querystring.default.stringify(payload)}`;
88
- debug("uri", {
89
- token,
90
- pathname,
91
- uri,
92
- params,
93
- payload
94
- });
95
- return uri;
96
- }
97
- /**
98
- * Compute public url to return to wallet
99
- *
100
- * @method
101
- * @param {string} pathname
102
- * @param {object} params
103
- * @returns {string}
104
- */
105
- getPublicUrl(pathname, params = {}, baseUrl = "") {
106
- return `${this.baseUrl || baseUrl}${pathname}?${node_querystring.default.stringify(params)}`;
107
- }
108
- /**
109
- * Sign a plain response, usually on auth success or error
110
- *
111
- * @method
112
- * @param {object} params
113
- * @param {object} params.response - response
114
- * @param {string} params.errorMessage - error message, default to empty
115
- * @param {string} params.successMessage - success message, default to empty
116
- * @param {string} params.nextWorkflow - https://github.com/ArcBlock/ABT-DID-Protocol#concatenate-multiple-workflow
117
- * @param {string} params.nextUrl - tell wallet do open this url in webview
118
- * @param {object} params.cookies - key-value pairs to be set as cookie before open nextUrl
119
- * @param {object} params.storages - key-value pairs to be set as localStorage before open nextUrl
120
- * @param {string} baseUrl
121
- * @param {object} request
122
- * @returns {Promise<object>} { appPk, agentPk, authInfo }
123
- */
124
- async signResponse({ response = {}, errorMessage = "", successMessage = "", nextWorkflow = "", nextUrl = "", cookies = {}, storages = {} }, baseUrl, request, extraParams = {}) {
125
- const infoParams = {
126
- baseUrl,
127
- request,
128
- ...request.context || {},
129
- extraParams
130
- };
131
- const [wallet, delegator, delegation] = await Promise.all([
132
- this.getWalletInfo(infoParams),
133
- this.getDelegator(infoParams),
134
- this.getDelegation(infoParams)
135
- ]);
136
- const [appInfo$1, memberAppInfo] = await Promise.all([this.getAppInfo({
137
- ...infoParams,
138
- wallet,
139
- delegator
140
- }, "appInfo"), this.getAppInfo({
141
- ...infoParams,
142
- wallet,
143
- delegator
144
- }, "memberAppInfo")]);
145
- const didwallet = request.context.wallet;
146
- const payload = {
147
- appInfo: appInfo$1,
148
- memberAppInfo,
149
- status: errorMessage ? "error" : "ok",
150
- errorMessage: errorMessage || "",
151
- successMessage: successMessage || "",
152
- nextWorkflow: nextWorkflow || "",
153
- nextUrl: nextUrl || "",
154
- cookies: cookies || {},
155
- storages: storages || "",
156
- response
157
- };
158
- if (delegator) {
159
- payload.iss = (0, _ocap_util.toDid)(delegator.address);
160
- payload.agentDid = (0, _ocap_util.toDid)(wallet.address);
161
- payload.verifiableClaims = [{
162
- type: "certificate",
163
- content: delegation
164
- }];
165
- }
166
- const result = {
167
- appPk: (0, _ocap_util.toBase58)(wallet.pk),
168
- authInfo: await wallet.signJWT(payload, true, didwallet ? didwallet.jwt : void 0)
169
- };
170
- if (delegator) {
171
- result.appPk = (0, _ocap_util.toBase58)(delegator.pk);
172
- result.agentPk = (0, _ocap_util.toBase58)(wallet.pk);
173
- }
174
- return result;
175
- }
176
- /**
177
- * Sign a auth response that returned to wallet: tell the wallet the appInfo/chainInfo
178
- *
179
- * @method
180
- * @param {object} params
181
- * @param {object} params.claims - info required by application to complete the auth
182
- * @param {string} params.pathname - pathname to assemble callback url
183
- * @param {string} params.baseUrl - baseUrl
184
- * @param {object} params.challenge - random challenge to be included in the body
185
- * @param {object} params.extraParams - extra query params and locale
186
- * @param {object} params.request
187
- * @param {object} params.context
188
- * @param {string} params.context.token - action token
189
- * @param {number} params.context.currentStep - current step
190
- * @param {string} [params.context.sharedKey] - shared key between app and wallet
191
- * @param {string} [params.context.encryptionKey] - encryption key from wallet
192
- * @param {Function} [params.context.mfaCode] - function used to generate mfa code
193
- * @param {string} params.context.userDid - decoded from req.query, base58
194
- * @param {string} params.context.userPk - decoded from req.query, base58
195
- * @param {string} params.context.didwallet - DID Wallet os and version
196
- * @returns {Promise<object>} { appPk, agentPk, sharedKey, authInfo }
197
- */
198
- async sign({ context, request, claims: claims$1, pathname = "", baseUrl = "", challenge = "", extraParams = {} }) {
199
- const claimsInfo = await this.tryWithTimeout(() => this.genRequestedClaims({
200
- claims: claims$1,
201
- context: {
202
- baseUrl,
203
- request,
204
- ...context
205
- },
206
- extraParams
207
- }));
208
- if (claimsInfo.filter((x) => x.mfaCode && x.mfaCode.length > 0).length > 1) throw new Error("Multiple MFA is not supported when sending more than 1 claim");
209
- const tmp = claimsInfo.find((x) => (0, lodash_isEqual.default)(this._isValidChainInfo(x.chainInfo), require_authenticator_base.DEFAULT_CHAIN_INFO) === false);
210
- const infoParams = {
211
- baseUrl,
212
- request,
213
- ...context,
214
- extraParams
215
- };
216
- const [wallet, delegator, delegation, chainInfo$1] = await Promise.all([
217
- this.getWalletInfo(infoParams),
218
- this.getDelegator(infoParams),
219
- this.getDelegation(infoParams),
220
- this.getChainInfo(infoParams, tmp?.chainInfo)
221
- ]);
222
- const [appInfo$1, memberAppInfo] = await Promise.all([this.getAppInfo({
223
- ...infoParams,
224
- wallet,
225
- delegator
226
- }, "appInfo"), this.getAppInfo({
227
- ...infoParams,
228
- wallet,
229
- delegator
230
- }, "memberAppInfo")]);
231
- const payload = {
232
- action: "responseAuth",
233
- challenge,
234
- appInfo: appInfo$1,
235
- memberAppInfo,
236
- chainInfo: chainInfo$1,
237
- requestedClaims: claimsInfo.map((x) => {
238
- delete x.chainInfo;
239
- return x;
240
- }),
241
- url: `${this.baseUrl || baseUrl}${pathname}?${node_querystring.default.stringify({ [this.tokenKey]: context.token })}`
242
- };
243
- if (delegator) {
244
- payload.iss = (0, _ocap_util.toDid)(delegator.address);
245
- payload.agentDid = (0, _ocap_util.toDid)(wallet.address);
246
- payload.verifiableClaims = [{
247
- type: "certificate",
248
- content: delegation
249
- }];
250
- }
251
- const version = context.didwallet ? context.didwallet.jwt : void 0;
252
- const result = {
253
- appPk: (0, _ocap_util.toBase58)(wallet.pk),
254
- authInfo: await wallet.signJWT(payload, true, version),
255
- sensitive: claimsInfo.every((x) => ["keyPair", "encryptionKey"].includes(x.type))
256
- };
257
- if (result.sensitive && context.sharedKey && context.encryptionKey) try {
258
- const pk = (0, _ocap_util.fromBase58)(context.encryptionKey).toString("utf8");
259
- result.sharedKey = _ocap_mcrypto_lib_crypter_rsa.default.encrypt(context.sharedKey, pk, "base58");
260
- } catch (err) {
261
- console.error("Failed to encrypt shared key", err);
262
- }
263
- if (delegator) {
264
- result.appPk = (0, _ocap_util.toBase58)(delegator.pk);
265
- result.agentPk = (0, _ocap_util.toBase58)(wallet.pk);
266
- }
267
- return result;
268
- }
269
- /**
270
- * Determine chainInfo on the fly
271
- *
272
- * @param {object} params - contains the context of this request
273
- * @param {object|undefined} [info=undefined] - chain info object or function
274
- * @returns {Promise<ChainInfo>}
275
- * @memberof WalletAuthenticator
276
- */
277
- async getChainInfo(params, info) {
278
- if (info && this._isValidChainInfo(info)) return info;
279
- if (typeof this.chainInfo === "function") {
280
- const result = await this.tryWithTimeout(() => this.chainInfo(params));
281
- if (this._isValidChainInfo(result)) return result;
282
- }
283
- if (this.chainInfo && this._isValidChainInfo(this.chainInfo)) return this.chainInfo;
284
- return require_authenticator_base.DEFAULT_CHAIN_INFO;
285
- }
286
- /**
287
- * Determine appInfo/memberAppInfo on the fly
288
- *
289
- * @param {object} params - contains the context of this request
290
- * @param {string} key - appInfo | memberAppInfo
291
- * @returns {Promise<ApplicationInfo>}
292
- * @memberof WalletAuthenticator
293
- */
294
- async getAppInfo(params, key = "appInfo") {
295
- if (typeof this[key] === "function") {
296
- const info = await this.tryWithTimeout(() => this[key](params));
297
- if (info) {
298
- if (!info.link) info.link = params.baseUrl;
299
- if (!info.publisher) info.publisher = (0, _ocap_util.toDid)(params.delegator ? params.delegator.address : params.wallet.address);
300
- }
301
- return this._validateAppInfo(info, key === "memberAppInfo");
302
- }
303
- if (this[key] && !this[key].publisher) this[key].publisher = (0, _ocap_util.toDid)(params.delegator ? params.delegator.address : params.wallet.address);
304
- return this[key];
305
- }
306
- async getWalletInfo(params) {
307
- if (typeof this.wallet === "function") {
308
- const result = await this.tryWithTimeout(() => this.wallet(params));
309
- return this._validateWallet(result, false);
310
- }
311
- return this.wallet;
312
- }
313
- async getDelegator(params) {
314
- if (typeof this.delegator === "function") {
315
- const result = await this.tryWithTimeout(() => this.delegator(params));
316
- return result ? this._validateWallet(result, false) : null;
317
- }
318
- return this.delegator;
319
- }
320
- async getDelegation(params) {
321
- if (typeof this.delegation === "function") return await this.tryWithTimeout(() => this.delegation(params));
322
- return this.delegation;
323
- }
324
- /**
325
- * Verify a DID auth response sent from DID Wallet
326
- *
327
- * @method
328
- * @param {object} data
329
- * @param {string} [locale=en]
330
- * @param {boolean} [enforceTimestamp=true]
331
- * @returns Promise<boolean>
332
- */
333
- async verify(data, locale = "en", enforceTimestamp = true) {
334
- const { iss, iat, challenge = "", action = "responseAuth", requestedClaims } = await this._verify(data, "userPk", "userInfo", locale, enforceTimestamp);
335
- debug("verify.context", {
336
- userPk: data.userPk,
337
- userDid: (0, _arcblock_did.toAddress)(iss),
338
- action,
339
- challenge
340
- });
341
- debug("verify.claims", requestedClaims);
342
- return {
343
- token: data.token,
344
- userDid: (0, _arcblock_did.toAddress)(iss),
345
- userPk: data.userPk,
346
- claims: requestedClaims,
347
- action,
348
- challenge,
349
- timestamp: iat
350
- };
351
- }
352
- genRequestedClaims({ claims: claims$1, context, extraParams }) {
353
- return Promise.all(Object.keys(claims$1).map(async (x) => {
354
- let name = x;
355
- let claim = claims$1[x];
356
- if (Array.isArray(claims$1[x])) [name, claim] = claims$1[x];
357
- if (!require_schema_index.claims[name]) throw new Error(`Unsupported claim type ${name}`);
358
- const fn = typeof this[name] === "function" ? name : "getClaimInfo";
359
- const result = await this[fn]({
360
- claim,
361
- context,
362
- extraParams
363
- });
364
- if (result.mfa && typeof context.mfaCode === "function") {
365
- result.mfaCode = [await context.mfaCode()];
366
- while (result.mfaCode.length < MFA_CODE_COUNT) {
367
- const noise = (0, lodash_random.default)(10, 99);
368
- if (result.mfaCode.includes(noise) === false) result.mfaCode.push(noise);
369
- }
370
- result.mfaCode = (0, lodash_shuffle.default)(result.mfaCode);
371
- }
372
- const { value, error } = require_schema_index.claims[name].validate(result);
373
- if (error) throw new Error(`Invalid ${name} claim: ${error.message}`);
374
- return value;
375
- }));
376
- }
377
- async getClaimInfo({ claim, context, extraParams }) {
378
- const { userDid, userPk, didwallet } = context;
379
- const result = typeof claim === "function" ? await claim({
380
- userDid: userDid ? (0, _arcblock_did.toAddress)(userDid) : "",
381
- userPk: userPk || "",
382
- didwallet,
383
- extraParams,
384
- context
385
- }) : claim;
386
- const infoParams = {
387
- ...context,
388
- ...extraParams
389
- };
390
- result.chainInfo = await this.getChainInfo(infoParams, result.chainInfo);
391
- return result;
392
- }
393
- async signature({ claim, context, extraParams }) {
394
- const { data, type = "mime:text/plain", digest = "", method = "sha3", wallet, sender, display, description: desc, chainInfo: chainInfo$1, meta = {}, mfa = false, nonce = "", requirement = {
395
- tokens: [],
396
- assets: {}
397
- } } = await this.getClaimInfo({
398
- claim,
399
- context,
400
- extraParams
401
- });
402
- debug("claim.signature", {
403
- data,
404
- digest,
405
- type,
406
- sender,
407
- context,
408
- nonce,
409
- requirement
410
- });
411
- if (!data && !digest) throw new Error("Signature claim requires either data or digest to be provided");
412
- const description = desc || "Sign this transaction to continue.";
413
- if (type.endsWith("Tx")) {
414
- if (!chainInfo$1.host) throw new Error("Invalid chainInfo when trying to encoding transaction");
415
- const client = new _ocap_client.default(chainInfo$1.host);
416
- if (typeof client[`encode${type}`] !== "function") throw new Error(`Unsupported transaction type ${type}`);
417
- if (!data.pk) data.pk = context.userPk;
418
- try {
419
- const { buffer: txBuffer } = await client[`encode${type}`]({
420
- tx: data,
421
- wallet: wallet || (0, _ocap_wallet.fromAddress)(sender || context.userDid)
422
- });
423
- return {
424
- type: "signature",
425
- description,
426
- typeUrl: "fg:t:transaction",
427
- origin: (0, _ocap_util.toBase58)(txBuffer),
428
- method,
429
- display: WalletAuthenticator.formatDisplay(display),
430
- digest: "",
431
- chainInfo: chainInfo$1,
432
- meta,
433
- mfa,
434
- nonce,
435
- requirement
436
- };
437
- } catch (err) {
438
- throw new Error(`Failed to encode transaction: ${err.message}`);
439
- }
440
- }
441
- if (type === "fg:t:transaction") return {
442
- type: "signature",
443
- description,
444
- typeUrl: "fg:t:transaction",
445
- origin: (0, _ocap_util.toBase58)(data),
446
- display: WalletAuthenticator.formatDisplay(display),
447
- method,
448
- digest: "",
449
- chainInfo: chainInfo$1,
450
- meta,
451
- mfa,
452
- nonce,
453
- requirement
454
- };
455
- return {
456
- type: "signature",
457
- description: desc || "Sign this message to continue.",
458
- origin: data ? (0, _ocap_util.toBase58)(data) : "",
459
- typeUrl: type,
460
- display: WalletAuthenticator.formatDisplay(display),
461
- method,
462
- digest,
463
- chainInfo: chainInfo$1,
464
- meta,
465
- mfa,
466
- nonce,
467
- requirement
468
- };
469
- }
470
- async prepareTx({ claim, context, extraParams }) {
471
- const { partialTx, requirement = {
472
- tokens: [],
473
- assets: {}
474
- }, type, display, wallet, sender, description: desc, chainInfo: chainInfo$1, meta = {}, mfa = false, nonce = "" } = await this.getClaimInfo({
475
- claim,
476
- context,
477
- extraParams
478
- });
479
- debug("claim.prepareTx", {
480
- partialTx,
481
- requirement,
482
- type,
483
- sender,
484
- context
485
- });
486
- if (!partialTx || !requirement) throw new Error("prepareTx claim requires both partialTx and requirement to be provided");
487
- const description = desc || "Prepare and sign this transaction to continue.";
488
- if (type?.endsWith("Tx")) {
489
- if (!chainInfo$1.host) throw new Error("Invalid chainInfo when trying to encoding partial transaction");
490
- const client = new _ocap_client.default(chainInfo$1.host);
491
- if (typeof client[`encode${type}`] !== "function") throw new Error(`Unsupported transaction type ${type} when encoding partial transaction`);
492
- if (!partialTx.pk) partialTx.pk = context.userPk;
493
- try {
494
- const { buffer: txBuffer } = await client[`encode${type}`]({
495
- tx: partialTx,
496
- wallet: wallet || (0, _ocap_wallet.fromAddress)(sender || context.userDid)
497
- });
498
- return {
499
- type: "prepareTx",
500
- description,
501
- partialTx: (0, _ocap_util.toBase58)(txBuffer),
502
- display: WalletAuthenticator.formatDisplay(display),
503
- requirement,
504
- chainInfo: chainInfo$1,
505
- meta,
506
- mfa,
507
- nonce
508
- };
509
- } catch (err) {
510
- throw new Error(`Failed to encode partial transaction: ${err.message}`);
511
- }
512
- }
513
- return {
514
- type: "prepareTx",
515
- description,
516
- partialTx: (0, _ocap_util.toBase58)(partialTx),
517
- requirement,
518
- display: WalletAuthenticator.formatDisplay(display),
519
- chainInfo: chainInfo$1,
520
- meta,
521
- mfa,
522
- nonce
523
- };
524
- }
525
- _validateAppInfo(info, allowEmpty = false) {
526
- if (typeof info === "function") return info;
527
- if (!info) {
528
- if (allowEmpty === false) throw new Error("Wallet authenticator can not work with invalid appInfo: empty");
529
- return null;
530
- }
531
- const { value, error } = require_schema_index.appInfo.validate(info);
532
- if (error) throw new Error(`Wallet authenticator can not work with invalid appInfo: ${error.message}`);
533
- return value;
534
- }
535
- _isValidChainInfo(x) {
536
- const { error } = require_schema_index.chainInfo.validate(x);
537
- return !error;
538
- }
539
- tryWithTimeout(asyncFn, label = "") {
540
- if (typeof asyncFn !== "function") throw new Error("asyncFn must be a valid function when calling tryWithTimeout");
541
- const timeout = Number(this.timeout) || DEFAULT_TIMEOUT;
542
- const inferredLabel = label || asyncFn.name || asyncFn.toString();
543
- const invocationStack = (/* @__PURE__ */ new Error(`Timeout at: ${inferredLabel}`)).stack;
544
- return new Promise(async (resolve, reject) => {
545
- const timer = setTimeout(() => {
546
- const error = /* @__PURE__ */ new Error(`Async operation (${inferredLabel}) did not complete within ${timeout} ms`);
547
- error.stack = invocationStack;
548
- error.name = "TIMEOUT";
549
- reject(error);
550
- }, timeout);
551
- try {
552
- resolve(await asyncFn());
553
- } catch (err) {
554
- reject(err);
555
- } finally {
556
- clearTimeout(timer);
557
- }
558
- });
559
- }
560
- };
561
- var wallet_default = WalletAuthenticator;
562
-
563
- //#endregion
564
- exports.default = wallet_default;