@arcblock/did-connect-js 1.30.0 → 4.0.0-beta.10

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