@arcblock/did-connect-js 1.29.22 → 4.0.0-beta.1

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