@blocklet/sdk 1.15.17 → 1.16.0-beta-8ee536d7

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 (69) hide show
  1. package/README.md +1 -198
  2. package/lib/component/index.d.ts +35 -0
  3. package/lib/component/index.js +95 -0
  4. package/lib/config.d.ts +33 -0
  5. package/lib/config.js +17 -0
  6. package/lib/connect/authenticator.d.ts +5 -0
  7. package/lib/connect/authenticator.js +18 -0
  8. package/lib/connect/handler.d.ts +2 -0
  9. package/lib/connect/handler.js +90 -0
  10. package/lib/connect/shared.d.ts +19 -0
  11. package/lib/connect/shared.js +81 -0
  12. package/lib/database/index.d.ts +13 -0
  13. package/lib/database/index.js +46 -0
  14. package/lib/embed/adapters/express.d.ts +3 -0
  15. package/lib/embed/adapters/express.js +13 -0
  16. package/lib/embed/generate.d.ts +6 -0
  17. package/lib/embed/generate.js +30 -0
  18. package/lib/embed/get-embed-url.d.ts +1 -0
  19. package/lib/embed/get-embed-url.js +55 -0
  20. package/lib/embed/get-embed.d.ts +1 -0
  21. package/lib/embed/get-embed.js +32 -0
  22. package/lib/embed/index.d.ts +10 -0
  23. package/lib/embed/index.js +13 -0
  24. package/lib/embed/message.d.ts +26 -0
  25. package/lib/embed/message.js +134 -0
  26. package/lib/env.d.ts +17 -0
  27. package/lib/env.js +3 -0
  28. package/lib/error-handler.d.ts +0 -0
  29. package/lib/error-handler.js +5 -5
  30. package/lib/index.d.ts +53 -0
  31. package/lib/index.js +49 -12
  32. package/lib/middlewares/auth.d.ts +8 -0
  33. package/lib/middlewares/auth.js +54 -0
  34. package/lib/middlewares/component.d.ts +7 -0
  35. package/lib/middlewares/component.js +32 -0
  36. package/lib/middlewares/index.d.ts +24 -0
  37. package/lib/middlewares/index.js +17 -0
  38. package/lib/middlewares/user.d.ts +10 -0
  39. package/lib/middlewares/user.js +12 -0
  40. package/lib/security/index.d.ts +9 -0
  41. package/lib/security/index.js +27 -0
  42. package/lib/service/auth.d.ts +31 -0
  43. package/lib/service/auth.js +129 -136
  44. package/lib/service/notification.d.ts +47 -0
  45. package/lib/service/notification.js +182 -18
  46. package/lib/types/notification.d.ts +113 -0
  47. package/lib/types/notification.js +3 -0
  48. package/lib/util/check-blocklet-env.d.ts +2 -0
  49. package/lib/util/check-blocklet-env.js +20 -17
  50. package/lib/util/constants.d.ts +5 -0
  51. package/lib/util/constants.js +6 -2
  52. package/lib/util/env.d.ts +19 -0
  53. package/lib/util/env.js +33 -0
  54. package/lib/util/send-notification.d.ts +26 -0
  55. package/lib/util/send-notification.js +149 -38
  56. package/lib/validators/index.d.ts +12 -0
  57. package/lib/validators/index.js +13 -5
  58. package/lib/validators/notification.d.ts +74 -0
  59. package/lib/validators/notification.js +227 -69
  60. package/lib/version.d.ts +6 -0
  61. package/lib/version.js +6 -0
  62. package/lib/wallet-authenticator.d.ts +5 -0
  63. package/lib/wallet-authenticator.js +16 -51
  64. package/lib/wallet-handler.d.ts +19 -0
  65. package/lib/wallet-handler.js +109 -87
  66. package/lib/wallet.d.ts +9 -0
  67. package/lib/wallet.js +23 -0
  68. package/package.json +53 -19
  69. package/lib/database.js +0 -98
@@ -1,79 +1,237 @@
1
- const JOI = require('joi');
2
-
3
- const { didExtension } = require('@blocklet/meta/lib/extension');
4
-
5
- const Joi = JOI.extend(didExtension);
6
-
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.feedTypeSchema = exports.connectTypeSchema = exports.notificationTypeSchema = exports.inputNotificationSchema = exports.NOTIFICATION_TYPES = exports.channelEventSchema = exports.optionSchema = exports.messageSchema = exports.notificationSchema = exports.attachmentSchema = exports.dappSchema = exports.imageSchema = exports.linkSchema = exports.textSchema = exports.transactionSchema = exports.vcSchema = exports.assetSchema = exports.actionSchema = exports.tokenSchema = exports.validateOption = exports.validateChannelEvent = exports.validateMessage = exports.validateNotification = exports.validateReceiver = void 0;
7
+ const joi_1 = __importDefault(require("joi"));
8
+ const extension_1 = require("@blocklet/meta/lib/extension");
9
+ const Joi = joi_1.default.extend(extension_1.didExtension);
7
10
  const TYPES = {
8
- NOTIFICATION: 'notification',
9
- CONNECT: 'connect',
11
+ NOTIFICATION: 'notification',
12
+ CONNECT: 'connect',
13
+ FEED: 'feed',
14
+ HI: 'hi',
15
+ };
16
+ exports.NOTIFICATION_TYPES = TYPES;
17
+ const SEVERITIES = {
18
+ NORMAL: 'normal',
19
+ SUCCESS: 'success',
20
+ ERROR: 'error',
21
+ WARNING: 'warning',
22
+ };
23
+ const ATTACHMENT_TYPES = {
24
+ ASSET: 'asset',
25
+ VC: 'vc',
26
+ TOKEN: 'token',
27
+ TEXT: 'text',
28
+ IMAGE: 'image',
29
+ DIVIDER: 'divider',
30
+ TRANSACTION: 'transaction',
31
+ DAPP: 'dapp',
32
+ LINK: 'link',
33
+ SECTION: 'section',
10
34
  };
11
-
12
35
  const assetSchema = Joi.object({
13
- did: Joi.DID().trim().required(),
14
- chainHost: Joi.string().uri().required(),
15
- }).required();
16
-
36
+ did: Joi.DID().trim().required(),
37
+ chainHost: Joi.string().uri().required(),
38
+ })
39
+ .required()
40
+ .meta({ className: 'TDataAsset' });
41
+ exports.assetSchema = assetSchema;
17
42
  const vcSchema = Joi.object({
18
- credential: Joi.object().required().unknown(true),
19
- tag: Joi.string(),
20
- }).required();
21
-
43
+ credential: Joi.object().required().unknown(true),
44
+ tag: Joi.string(),
45
+ })
46
+ .required()
47
+ .meta({ className: 'TDataVC', unknownType: 'any' });
48
+ exports.vcSchema = vcSchema;
22
49
  const tokenSchema = Joi.object({
23
- address: Joi.DID().trim().allow(''),
24
- amount: Joi.string().required(),
25
- symbol: Joi.string().required(),
26
- senderDid: Joi.DID().trim().required(),
27
- chainHost: Joi.string().uri().required(),
28
- decimal: Joi.number().integer().required(),
29
- }).required();
30
-
50
+ address: Joi.DID().trim().allow(''),
51
+ amount: Joi.string().required(),
52
+ symbol: Joi.string().required(),
53
+ senderDid: Joi.DID().trim().required(),
54
+ chainHost: Joi.string().uri().required(),
55
+ decimal: Joi.number().integer().required(),
56
+ })
57
+ .required()
58
+ .meta({ className: 'TDataToken' });
59
+ exports.tokenSchema = tokenSchema;
60
+ const textSchema = Joi.object({
61
+ type: Joi.string().required(),
62
+ text: Joi.string().required(),
63
+ color: Joi.string().min(0),
64
+ size: Joi.string().valid('small', 'normal', 'big'),
65
+ })
66
+ .required()
67
+ .meta({ className: 'TDataText' });
68
+ exports.textSchema = textSchema;
69
+ const imageSchema = Joi.object({
70
+ url: Joi.string().uri().required(),
71
+ alt: Joi.string().min(0),
72
+ })
73
+ .required()
74
+ .meta({ className: 'TDataImage' });
75
+ exports.imageSchema = imageSchema;
76
+ const transactionSchema = Joi.object({
77
+ hash: Joi.string().required(),
78
+ chainId: Joi.string().required(),
79
+ })
80
+ .required()
81
+ .meta({ className: 'TDataTransaction' });
82
+ exports.transactionSchema = transactionSchema;
83
+ const dappSchema = Joi.object({
84
+ url: Joi.string().uri().required(),
85
+ appDID: Joi.DID().trim().required(),
86
+ logo: Joi.string().uri().required(),
87
+ title: Joi.string().required(),
88
+ desc: Joi.string().min(0),
89
+ })
90
+ .required()
91
+ .meta({ className: 'TDataDapp' });
92
+ exports.dappSchema = dappSchema;
93
+ const linkSchema = Joi.object({
94
+ url: Joi.string().uri().required(),
95
+ description: Joi.string().min(0),
96
+ title: Joi.string().min(0),
97
+ image: Joi.string().uri().min(0),
98
+ })
99
+ .required()
100
+ .meta({ className: 'TDataLink' });
101
+ exports.linkSchema = linkSchema;
31
102
  const actionSchema = Joi.object({
32
- name: Joi.string().required(),
33
- title: Joi.string(),
34
- color: Joi.string(),
35
- bgColor: Joi.string(),
36
- link: Joi.string().uri(),
37
- });
38
-
103
+ name: Joi.string().required(),
104
+ title: Joi.string(),
105
+ color: Joi.string(),
106
+ bgColor: Joi.string(),
107
+ link: Joi.string().uri(),
108
+ }).meta({ className: 'TNotificationAction' });
109
+ exports.actionSchema = actionSchema;
39
110
  const attachmentSchema = Joi.object({
40
- type: Joi.string().required().valid('asset', 'vc', 'token'),
41
- data: Joi.object()
42
- .when('type', { is: 'asset', then: assetSchema })
43
- .concat(Joi.object().when('type', { is: 'vc', then: vcSchema }))
44
- .concat(Joi.object().when('type', { is: 'token', then: tokenSchema })),
45
- }).required();
46
-
111
+ type: Joi.string()
112
+ .valid(...Object.values(ATTACHMENT_TYPES))
113
+ .required(),
114
+ data: Joi.when('type', {
115
+ switch: [
116
+ { is: ATTACHMENT_TYPES.ASSET, then: assetSchema },
117
+ { is: ATTACHMENT_TYPES.VC, then: vcSchema },
118
+ { is: ATTACHMENT_TYPES.TOKEN, then: tokenSchema },
119
+ { is: ATTACHMENT_TYPES.TEXT, then: textSchema },
120
+ { is: ATTACHMENT_TYPES.IMAGE, then: imageSchema },
121
+ { is: ATTACHMENT_TYPES.TRANSACTION, then: transactionSchema },
122
+ { is: ATTACHMENT_TYPES.DAPP, then: dappSchema },
123
+ { is: ATTACHMENT_TYPES.LINK, then: linkSchema },
124
+ { is: ATTACHMENT_TYPES.DIVIDER, then: Joi.object({}) },
125
+ ],
126
+ }),
127
+ fields: Joi.when('type', {
128
+ is: ATTACHMENT_TYPES.SECTION,
129
+ then: Joi.array().items(Joi.object({
130
+ type: Joi.string().valid(ATTACHMENT_TYPES.TEXT).required(),
131
+ data: textSchema,
132
+ })),
133
+ }),
134
+ }).meta({ className: 'TNotificationAttachment' });
135
+ exports.attachmentSchema = attachmentSchema;
47
136
  const notificationTypeSchema = Joi.object({
48
- type: Joi.string().valid(TYPES.NOTIFICATION),
49
- title: Joi.string(),
50
- body: Joi.string(),
51
- attachments: Joi.array().items(attachmentSchema).default([]),
52
- actions: Joi.array().items(actionSchema).default([]),
53
- }).required();
54
-
137
+ type: Joi.string().valid(TYPES.NOTIFICATION),
138
+ title: Joi.string(),
139
+ body: Joi.string(),
140
+ severity: Joi.string().valid(...Object.values(SEVERITIES)),
141
+ blocks: Joi.array().items(attachmentSchema).default([]),
142
+ attachments: Joi.array().items(attachmentSchema).default([]),
143
+ actions: Joi.array().items(actionSchema).default([]),
144
+ })
145
+ .required()
146
+ .meta({ className: 'TNotificationItem' });
147
+ exports.notificationTypeSchema = notificationTypeSchema;
55
148
  const connectTypeSchema = Joi.object({
56
- type: Joi.string().valid(TYPES.CONNECT),
57
- url: Joi.string().uri().required(),
58
- checkUrl: Joi.string().uri(),
59
- }).required();
60
-
61
- const notificationSchema = Joi.alternatives().try(notificationTypeSchema, connectTypeSchema).required();
62
-
63
- const receiverSchema = Joi.DID().trim().required();
64
-
65
- const inputNotificationSchema = Joi.alternatives()
66
- .try(Joi.array().items(notificationSchema), notificationSchema)
67
- .required();
68
-
69
- const inputReceiverSchema = Joi.alternatives().try(Joi.array().items(receiverSchema), receiverSchema).required();
70
-
71
- module.exports = {
72
- validateReceiver: inputReceiverSchema.validateAsync.bind(inputReceiverSchema),
73
- validateNotification: inputNotificationSchema.validateAsync.bind(inputNotificationSchema),
74
- tokenSchema,
75
- actionSchema,
76
- assetSchema,
77
- vcSchema,
78
- attachmentSchema,
149
+ type: Joi.string().valid(TYPES.CONNECT),
150
+ url: Joi.string().uri().required(),
151
+ checkUrl: Joi.string().uri(),
152
+ })
153
+ .required()
154
+ .meta({ className: 'TNotificationConnect' });
155
+ exports.connectTypeSchema = connectTypeSchema;
156
+ const feedTypeSchema = Joi.object({
157
+ type: Joi.string().valid(TYPES.FEED),
158
+ feedType: Joi.string().required(),
159
+ data: Joi.object().required(),
160
+ })
161
+ .required()
162
+ .meta({ className: 'TNotificationFeed' });
163
+ exports.feedTypeSchema = feedTypeSchema;
164
+ const notificationSchema = Joi.object({
165
+ type: Joi.string().valid(...Object.values(TYPES)),
166
+ // feed type
167
+ feedType: Joi.string(),
168
+ data: Joi.object(),
169
+ // connect type
170
+ url: Joi.string().uri(),
171
+ checkUrl: Joi.string(),
172
+ // notification type
173
+ title: Joi.string(),
174
+ body: Joi.string(),
175
+ severity: Joi.string().valid(...Object.values(SEVERITIES)),
176
+ blocks: Joi.array().items(attachmentSchema).default([]),
177
+ attachments: Joi.array().items(attachmentSchema).default([]),
178
+ actions: Joi.array().items(actionSchema).default([]),
179
+ })
180
+ .required()
181
+ .meta({ className: 'TNotification' });
182
+ exports.notificationSchema = notificationSchema;
183
+ const messageSchema = Joi.object({
184
+ id: Joi.string().required(),
185
+ createdAt: Joi.date().iso().required(),
186
+ type: Joi.string().required(),
187
+ receiver: Joi.object({
188
+ did: Joi.DID().trim().required(),
189
+ }).required(),
190
+ })
191
+ .unknown()
192
+ .required()
193
+ .meta({ className: 'TMessage', unknownType: 'any' });
194
+ exports.messageSchema = messageSchema;
195
+ const receiverSchema = Joi.DID().trim().required().meta({ className: 'TReceiver' });
196
+ const inputNotificationSchema = Joi.array()
197
+ .items(notificationSchema)
198
+ .single()
199
+ .required()
200
+ .meta({ className: 'TNotificationInput' });
201
+ exports.inputNotificationSchema = inputNotificationSchema;
202
+ const inputReceiverSchema = Joi.array().items(receiverSchema).single().required().meta({ className: 'TReceiverInput' });
203
+ const optionSchema = Joi.object({
204
+ keepForOfflineUser: Joi.boolean(),
205
+ })
206
+ .unknown()
207
+ .meta({ className: 'TSendOptions', unknownType: 'any' });
208
+ exports.optionSchema = optionSchema;
209
+ const channelEventSchema = Joi.string().required().meta({ className: 'TChannelEvent' });
210
+ exports.channelEventSchema = channelEventSchema;
211
+ exports.validateReceiver = inputReceiverSchema.validateAsync.bind(inputReceiverSchema);
212
+ exports.validateNotification = inputNotificationSchema.validateAsync.bind(inputNotificationSchema);
213
+ exports.validateMessage = messageSchema.validateAsync.bind(messageSchema);
214
+ exports.validateChannelEvent = channelEventSchema.validateAsync.bind(channelEventSchema);
215
+ exports.validateOption = optionSchema.validateAsync.bind(optionSchema);
216
+ exports.default = {
217
+ validateReceiver: exports.validateReceiver,
218
+ validateNotification: exports.validateNotification,
219
+ validateMessage: exports.validateMessage,
220
+ validateChannelEvent: exports.validateChannelEvent,
221
+ validateOption: exports.validateOption,
222
+ tokenSchema,
223
+ actionSchema,
224
+ assetSchema,
225
+ vcSchema,
226
+ transactionSchema,
227
+ textSchema,
228
+ linkSchema,
229
+ imageSchema,
230
+ dappSchema,
231
+ attachmentSchema,
232
+ notificationSchema,
233
+ messageSchema,
234
+ optionSchema,
235
+ channelEventSchema,
236
+ NOTIFICATION_TYPES: TYPES,
79
237
  };
@@ -0,0 +1,6 @@
1
+ declare const version = "1.16.0";
2
+ export { version };
3
+ declare const _default: {
4
+ version: string;
5
+ };
6
+ export default _default;
package/lib/version.js ADDED
@@ -0,0 +1,6 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.version = void 0;
4
+ const version = '1.16.0';
5
+ exports.version = version;
6
+ exports.default = { version };
@@ -0,0 +1,5 @@
1
+ import { WalletAuthenticator as Authenticator } from '@arcblock/did-auth';
2
+ declare class WalletAuthenticator extends Authenticator {
3
+ constructor(options?: {});
4
+ }
5
+ export = WalletAuthenticator;
@@ -1,53 +1,18 @@
1
- const joinUrl = require('url-join');
2
- const { WalletAuthenticator: Authenticator } = require('@arcblock/did-auth');
3
- const { fromSecretKey, WalletType } = require('@ocap/wallet');
4
- const { types } = require('@ocap/mcrypto');
5
-
6
- const checkBlockletEnv = require('./util/check-blocklet-env');
7
- const { AUTH_SERVICE_PREFIX } = require('./util/constants');
8
-
9
- const type =
10
- process.env.BLOCKLET_WALLET_TYPE !== 'eth'
11
- ? WalletType({ role: types.RoleType.ROLE_APPLICATION, pk: types.KeyType.ED25519, hash: types.HashType.SHA3 })
12
- : 'eth';
13
-
14
- // wraps value in closure or returns closure
15
- const closure = (value) => (typeof value === 'function' ? value : () => value);
16
-
17
- class WalletAuthenticator extends Authenticator {
18
- constructor(options = {}) {
19
- checkBlockletEnv();
20
-
21
- super({
22
- wallet: fromSecretKey(process.env.BLOCKLET_APP_SK, type).toJSON(),
23
-
24
- chainInfo: () => {
25
- const chainHost = process.env.CHAIN_HOST;
26
- return chainHost ? { host: chainHost, id: 'chain' } : { host: 'none', id: 'none' };
27
- },
28
-
29
- ...options,
30
-
31
- appInfo: async (...args) => {
32
- const info = await closure(options.appInfo)(...args);
33
-
34
- const { request, baseUrl } = args[0];
35
- const groupPathPrefix = request.headers['x-group-path-prefix'] || '/';
36
- const blockletDid = request.headers['x-blocklet-did'];
37
-
38
- return {
39
- name: process.env.BLOCKLET_APP_NAME,
40
- description: process.env.BLOCKLET_APP_DESCRIPTION,
41
- ...(info || {}),
42
- link: baseUrl,
43
- icon: joinUrl(baseUrl, AUTH_SERVICE_PREFIX, `/blocklet/logo/${blockletDid}`),
44
- updateSubEndpoint: true,
45
- subscriptionEndpoint: joinUrl(groupPathPrefix, AUTH_SERVICE_PREFIX, 'websocket'),
46
- nodeDid: process.env.ABT_NODE_DID,
47
- };
48
- },
49
- });
50
- }
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ const did_auth_1 = require("@arcblock/did-auth");
6
+ const wallet_1 = __importDefault(require("./wallet"));
7
+ const check_blocklet_env_1 = __importDefault(require("./util/check-blocklet-env"));
8
+ const shared_1 = require("./connect/shared");
9
+ class WalletAuthenticator extends did_auth_1.WalletAuthenticator {
10
+ constructor(options = {}) {
11
+ (0, check_blocklet_env_1.default)();
12
+ super({
13
+ wallet: (0, wallet_1.default)().toJSON(),
14
+ ...(0, shared_1.getAuthenticatorProps)(options),
15
+ });
16
+ }
51
17
  }
52
-
53
18
  module.exports = WalletAuthenticator;
@@ -0,0 +1,19 @@
1
+ import { WalletHandlers as Handler } from '@arcblock/did-auth';
2
+ declare class WalletHandlers extends Handler {
3
+ enableConnect: boolean;
4
+ sendNotificationFn: Function;
5
+ sendToRelayFn: Function;
6
+ /**
7
+ * @param {boolean} params.autoConnect enable auto connect to wallet (wallet does not need to scan qr code)
8
+ * @param {boolean} params.connectedDidOnly only current login did or connected did can connect
9
+ * @param {function} [params.sendNotificationFn] use in a non-blocklet environment
10
+ * @param {function} [params.sendToRelayFn]
11
+ */
12
+ constructor({ autoConnect, connectedDidOnly, sendNotificationFn, sendToRelayFn, options, ...opts }: any);
13
+ getConnectedDid: ({ req, didwallet, extraParams }: $TSFixMe) => any;
14
+ attach({ onStart, ...opts }: {
15
+ [x: string]: any;
16
+ onStart?: () => {};
17
+ }): void;
18
+ }
19
+ export = WalletHandlers;
@@ -1,96 +1,118 @@
1
- const get = require('lodash/get');
2
- const { WalletHandlers: Handler } = require('@arcblock/did-auth');
3
- const Notification = require('./service/notification');
4
-
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || function (mod) {
19
+ if (mod && mod.__esModule) return mod;
20
+ var result = {};
21
+ if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
22
+ __setModuleDefault(result, mod);
23
+ return result;
24
+ };
25
+ var __importDefault = (this && this.__importDefault) || function (mod) {
26
+ return (mod && mod.__esModule) ? mod : { "default": mod };
27
+ };
28
+ const get_1 = __importDefault(require("lodash/get"));
29
+ const did_auth_1 = require("@arcblock/did-auth");
30
+ const notification_1 = __importStar(require("./service/notification"));
5
31
  const noop = () => ({});
6
-
7
32
  const CONNECTED_DID_KEY = 'headers[x-connected-did]';
8
-
9
33
  // whether app web page is in mobile DID wallet
10
- const inMobileWallet = (abtwallet) => {
11
- return abtwallet && ['ios', 'android'].includes(abtwallet.os);
34
+ const inMobileWallet = (didwallet) => {
35
+ return didwallet && ['ios', 'android'].includes(didwallet.os);
12
36
  };
13
-
14
- class WalletHandlers extends Handler {
15
- /**
16
- * @param {boolean} autoConnect enable auto connect to wallet (wallet does not need to scan qr code)
17
- * @param {boolean} connectedDidOnly only current login did or connected did can connect
18
- * @param {function} sendNotificationFn use in a non-blocklet environment
19
- */
20
- constructor({ autoConnect = true, connectedDidOnly = false, sendNotificationFn, options = {}, ...opts }) {
21
- if (autoConnect && connectedDidOnly) {
22
- options.sessionDidKey = CONNECTED_DID_KEY;
23
- }
24
-
25
- super({ options, ...opts });
26
-
27
- this.enableConnect = !!autoConnect;
28
- this.sendNotificationFn = sendNotificationFn || Notification.sendToUser.bind(Notification);
29
- }
30
-
31
- getConnectedDid = ({ req, abtwallet, extraParams }) => {
32
- if (extraParams && extraParams.autoConnect === 'false') {
33
- return null;
34
- }
35
-
36
- if (!this.enableConnect) {
37
- return null;
38
- }
39
-
40
- if (inMobileWallet(abtwallet)) {
41
- return null;
37
+ class WalletHandlers extends did_auth_1.WalletHandlers {
38
+ /**
39
+ * @param {boolean} params.autoConnect enable auto connect to wallet (wallet does not need to scan qr code)
40
+ * @param {boolean} params.connectedDidOnly only current login did or connected did can connect
41
+ * @param {function} [params.sendNotificationFn] use in a non-blocklet environment
42
+ * @param {function} [params.sendToRelayFn]
43
+ */
44
+ constructor({ autoConnect = true, connectedDidOnly = false, sendNotificationFn = null, sendToRelayFn = null, options = {}, ...opts }) {
45
+ super({
46
+ options: {
47
+ ...options,
48
+ ...{
49
+ sessionDidKey: autoConnect && connectedDidOnly ? CONNECTED_DID_KEY : options?.sessionDidKey,
50
+ },
51
+ },
52
+ ...opts,
53
+ });
54
+ this.getConnectedDid = ({ req, didwallet, extraParams }) => {
55
+ if (extraParams && extraParams.autoConnect === 'false') {
56
+ return null;
57
+ }
58
+ if (!this.enableConnect) {
59
+ return null;
60
+ }
61
+ if (inMobileWallet(didwallet)) {
62
+ return null;
63
+ }
64
+ return (0, get_1.default)(req, CONNECTED_DID_KEY);
65
+ };
66
+ this.enableConnect = !!autoConnect;
67
+ this.sendNotificationFn = sendNotificationFn || notification_1.sendToUser.bind(notification_1.default);
68
+ this.sendToRelayFn = sendToRelayFn || notification_1.sendToRelay.bind(notification_1.default);
69
+ // @ts-ignore
70
+ this.on('updated', (session) => {
71
+ this.sendToRelayFn(session.token, 'updated', session).catch(console.error);
72
+ });
42
73
  }
43
-
44
- return get(req, CONNECTED_DID_KEY);
45
- };
46
-
47
- attach({ onStart = noop, ...opts }) {
48
- const _onStart = async (params) => {
49
- const extra = (await onStart(params)) || {};
50
-
51
- const connectedDid = this.getConnectedDid(params);
52
-
53
- // fill extra
54
- extra.connectedDid = connectedDid || '';
55
- extra.saveConnect = this.enableConnect;
56
-
57
- // send notification to wallet to trigger wallet to auto connect
58
- if (connectedDid) {
59
- // wallet use check url to check status of the session
60
- let checkUrl = '';
61
- try {
62
- checkUrl = new URL(decodeURIComponent(new URL(params.deepLink).searchParams.get('url')));
63
- checkUrl.pathname = checkUrl.pathname.replace(/auth$/, 'status');
64
- } catch (e) {
65
- checkUrl = '';
66
- console.error(e);
67
- }
68
-
69
- const message = {
70
- type: 'connect',
71
- url: params.deepLink,
74
+ attach({ onStart = noop, ...opts }) {
75
+ const realOnStart = async (params) => {
76
+ // @ts-expect-error TS(2554) FIXME: Expected 0 arguments, but got 1.
77
+ const extra = (await onStart(params)) || {};
78
+ const connectedDid = this.getConnectedDid(params);
79
+ // fill extra
80
+ extra.connectedDid = connectedDid || '';
81
+ extra.saveConnect = this.enableConnect;
82
+ // send notification to wallet to trigger wallet to auto connect
83
+ if (connectedDid) {
84
+ // wallet use check url to check status of the session
85
+ let checkUrl;
86
+ try {
87
+ checkUrl = new URL(decodeURIComponent(new URL(params.deepLink).searchParams.get('url')));
88
+ checkUrl.pathname = checkUrl.pathname.replace(/auth$/, 'status');
89
+ }
90
+ catch (e) {
91
+ checkUrl = '';
92
+ console.error(e);
93
+ }
94
+ const message = {
95
+ type: 'connect',
96
+ url: params.deepLink,
97
+ };
98
+ if (checkUrl) {
99
+ message.checkUrl = checkUrl.href;
100
+ }
101
+ // sendNotificationFn maybe custom function so we need params
102
+ this.sendNotificationFn(connectedDid, message, params).catch((err) => {
103
+ console.error(err);
104
+ if (typeof opts.onError === 'function') {
105
+ opts.onError(err);
106
+ }
107
+ });
108
+ }
109
+ return extra;
72
110
  };
73
-
74
- if (checkUrl) {
75
- message.checkUrl = checkUrl.href;
76
- }
77
-
78
- this.sendNotificationFn(connectedDid, message, params).catch((err) => {
79
- console.error(err);
80
- if (typeof opts.onError === 'function') {
81
- opts.onError(err);
82
- }
111
+ // @ts-expect-error TS(2345) FIXME: Argument of type '{ onStart: (params: any) => Prom... Remove this comment to see the full error message
112
+ super.attach({
113
+ onStart: realOnStart,
114
+ ...opts,
83
115
  });
84
- }
85
-
86
- return extra;
87
- };
88
-
89
- super.attach({
90
- onStart: _onStart,
91
- ...opts,
92
- });
93
- }
116
+ }
94
117
  }
95
-
96
118
  module.exports = WalletHandlers;
@@ -0,0 +1,9 @@
1
+ import { WalletObject } from '@ocap/wallet';
2
+ import { DIDTypeShortcut } from '@arcblock/did';
3
+ /**
4
+ * @param {string} [type=process.env.BLOCKLET_WALLET_TYPE] can only be 'eth|ethereum' or 'default|arcblock'
5
+ * @param {string} [appSk=process.env.BLOCKLET_APP_SK] must be hex
6
+ * @return {WalletObject} {WalletObject}
7
+ */
8
+ declare const getWallet: (type?: DIDTypeShortcut, appSk?: string) => WalletObject;
9
+ export = getWallet;
package/lib/wallet.js ADDED
@@ -0,0 +1,23 @@
1
+ "use strict";
2
+ const wallet_1 = require("@ocap/wallet");
3
+ const mcrypto_1 = require("@ocap/mcrypto");
4
+ const did_1 = require("@arcblock/did");
5
+ /**
6
+ * @param {string} [type=process.env.BLOCKLET_WALLET_TYPE] can only be 'eth|ethereum' or 'default|arcblock'
7
+ * @param {string} [appSk=process.env.BLOCKLET_APP_SK] must be hex
8
+ * @return {WalletObject} {WalletObject}
9
+ */
10
+ const getWallet = (type = process.env.BLOCKLET_WALLET_TYPE, appSk = process.env.BLOCKLET_APP_SK) => {
11
+ let t;
12
+ let sk;
13
+ if ((0, did_1.isEthereumType)((0, did_1.DidType)(type))) {
14
+ sk = appSk.slice(0, 66);
15
+ t = (0, wallet_1.WalletType)(type);
16
+ }
17
+ else {
18
+ sk = appSk;
19
+ t = (0, wallet_1.WalletType)({ role: mcrypto_1.types.RoleType.ROLE_APPLICATION, pk: mcrypto_1.types.KeyType.ED25519, hash: mcrypto_1.types.HashType.SHA3 });
20
+ }
21
+ return (0, wallet_1.fromSecretKey)(sk, t);
22
+ };
23
+ module.exports = getWallet;