@blocklet/sdk 1.16.54-beta-20251017-133309-7d40faa6 → 1.16.54-beta-20251023-041534-36eec6b9

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 (62) hide show
  1. package/lib/config.js +5 -5
  2. package/lib/connect/authenticator.d.ts +1 -1
  3. package/lib/connect/authenticator.js +9 -11
  4. package/lib/connect/handler.d.ts +1 -1
  5. package/lib/connect/handler.js +3 -1
  6. package/lib/connect/shared.d.ts +1 -1
  7. package/lib/connect/shared.js +17 -6
  8. package/lib/database/index.d.ts +2 -2
  9. package/lib/database/index.js +4 -2
  10. package/lib/did.d.ts +2 -2
  11. package/lib/did.js +4 -7
  12. package/lib/env.d.ts +2 -2
  13. package/lib/env.js +4 -5
  14. package/lib/index.d.ts +9 -9
  15. package/lib/index.js +18 -18
  16. package/lib/middlewares/auth.d.ts +3 -3
  17. package/lib/middlewares/auth.js +7 -8
  18. package/lib/middlewares/blocklet.d.ts +2 -2
  19. package/lib/middlewares/blocklet.js +2 -2
  20. package/lib/middlewares/csrf.js +2 -4
  21. package/lib/middlewares/fallback.d.ts +1 -1
  22. package/lib/middlewares/fallback.js +3 -1
  23. package/lib/middlewares/index.d.ts +5 -5
  24. package/lib/middlewares/index.js +15 -15
  25. package/lib/middlewares/session.d.ts +1 -1
  26. package/lib/middlewares/session.js +3 -1
  27. package/lib/middlewares/sitemap.d.ts +1 -1
  28. package/lib/middlewares/sitemap.js +3 -1
  29. package/lib/middlewares/user.d.ts +1 -1
  30. package/lib/middlewares/user.js +3 -1
  31. package/lib/security/index.d.ts +2 -2
  32. package/lib/security/index.js +3 -3
  33. package/lib/service/blocklet.d.ts +5 -2
  34. package/lib/service/blocklet.js +14 -11
  35. package/lib/service/eventbus.d.ts +2 -2
  36. package/lib/service/eventbus.js +5 -8
  37. package/lib/service/notification.d.ts +7 -6
  38. package/lib/service/notification.js +33 -29
  39. package/lib/service/signature.d.ts +27 -0
  40. package/lib/service/signature.js +112 -0
  41. package/lib/util/app-info.d.ts +1 -1
  42. package/lib/util/app-info.js +2 -2
  43. package/lib/util/check-blocklet-env.d.ts +1 -1
  44. package/lib/util/check-blocklet-env.js +4 -2
  45. package/lib/util/component-api.js +8 -4
  46. package/lib/util/csrf.d.ts +5 -0
  47. package/lib/util/csrf.js +9 -0
  48. package/lib/util/jest-setup.js +9 -4
  49. package/lib/util/jest-teardown.js +2 -2
  50. package/lib/util/send-notification.d.ts +13 -10
  51. package/lib/util/send-notification.js +42 -47
  52. package/lib/util/service-api.js +8 -4
  53. package/lib/util/verify-session.js +10 -7
  54. package/lib/util/verify-sign.d.ts +8 -7
  55. package/lib/util/verify-sign.js +11 -42
  56. package/lib/wallet-authenticator.d.ts +1 -1
  57. package/lib/wallet-authenticator.js +9 -10
  58. package/lib/wallet-handler.d.ts +1 -1
  59. package/lib/wallet-handler.js +3 -1
  60. package/lib/wallet.d.ts +35 -7
  61. package/lib/wallet.js +136 -29
  62. package/package.json +19 -18
@@ -8,11 +8,11 @@ exports.default = setupJest;
8
8
  const os_1 = __importDefault(require("os"));
9
9
  const fs_extra_1 = __importDefault(require("fs-extra"));
10
10
  const path_1 = __importDefault(require("path"));
11
- const parse_1 = __importDefault(require("@blocklet/meta/lib/parse"));
11
+ const parse_1 = require("@blocklet/meta/lib/parse");
12
12
  function setupJest() {
13
13
  try {
14
14
  const dir = process.cwd();
15
- const meta = (0, parse_1.default)(dir, { ensureComponentStore: false });
15
+ const meta = (0, parse_1.parse)(dir, { ensureComponentStore: false });
16
16
  const tmpDir = path_1.default.join(os_1.default.tmpdir(), meta.did);
17
17
  if (fs_extra_1.default.existsSync(tmpDir)) {
18
18
  fs_extra_1.default.rm(tmpDir, { recursive: true });
@@ -1,7 +1,9 @@
1
+ import { WalletObject } from '@ocap/wallet';
1
2
  import { TNotification, TNotificationInput, TSendOptions } from '../types/notification';
2
3
  export type TNotificationSender = {
3
4
  appDid: string;
4
- appSk: string;
5
+ wallet?: WalletObject;
6
+ appSk?: string;
5
7
  type?: 'server' | 'blocklet';
6
8
  };
7
9
  /**
@@ -9,33 +11,34 @@ export type TNotificationSender = {
9
11
  * @param {Object} notification
10
12
  * @param {{
11
13
  * appDid: String
12
- * appSk: String
14
+ * wallet?: WalletObject
15
+ * appSk?: string
13
16
  * }} sender
14
17
  * @param {String|Number} port port of abtnode service endpoint
15
18
  * @param {Object} options
16
19
  * @returns
17
20
  */
18
- declare const sendToUser: (receiver: string | string[], notification: TNotification | TNotificationInput, { appDid, appSk, type }: TNotificationSender, options?: {
21
+ declare const sendToUser: (receiver: string | string[], notification: TNotification | TNotificationInput, sender: TNotificationSender, options?: {
19
22
  keepForOfflineUser?: boolean;
20
23
  locale?: string;
21
24
  channels?: ("app" | "email" | "push" | "webhook")[];
22
25
  raw?: boolean;
23
26
  ttl?: number;
24
27
  }, pathname?: string, port?: string) => Promise<any>;
25
- declare const sendToAppChannel: (channel: string, event: string, notification: TNotificationInput, { appDid, appSk }: TNotificationSender, options?: TSendOptions, port?: string) => Promise<any>;
26
- declare const sendToRelay: (topic: string, event: string, data: any, { appDid, appSk }: TNotificationSender, port?: string) => Promise<any>;
27
- declare const sendToEventBus: (event: any, { appDid, appSk }: TNotificationSender, port?: string) => Promise<any>;
28
+ declare const sendToAppChannel: (channel: string, event: string, notification: TNotificationInput, sender: TNotificationSender, options?: TSendOptions, port?: string) => Promise<any>;
29
+ declare const sendToRelay: (topic: string, event: string, data: any, sender: TNotificationSender, port?: string) => Promise<any>;
30
+ declare const sendToEventBus: (event: any, sender: TNotificationSender, port?: string) => Promise<any>;
28
31
  export { sendToUser, sendToAppChannel, sendToRelay, sendToEventBus };
29
32
  declare const _default: {
30
- sendToUser: (receiver: string | string[], notification: TNotification | TNotificationInput, { appDid, appSk, type }: TNotificationSender, options?: {
33
+ sendToUser: (receiver: string | string[], notification: TNotification | TNotificationInput, sender: TNotificationSender, options?: {
31
34
  keepForOfflineUser?: boolean;
32
35
  locale?: string;
33
36
  channels?: ("app" | "email" | "push" | "webhook")[];
34
37
  raw?: boolean;
35
38
  ttl?: number;
36
39
  }, pathname?: string, port?: string) => Promise<any>;
37
- sendToAppChannel: (channel: string, event: string, notification: TNotificationInput, { appDid, appSk }: TNotificationSender, options?: TSendOptions, port?: string) => Promise<any>;
38
- sendToRelay: (topic: string, event: string, data: any, { appDid, appSk }: TNotificationSender, port?: string) => Promise<any>;
39
- sendToEventBus: (event: any, { appDid, appSk }: TNotificationSender, port?: string) => Promise<any>;
40
+ sendToAppChannel: (channel: string, event: string, notification: TNotificationInput, sender: TNotificationSender, options?: TSendOptions, port?: string) => Promise<any>;
41
+ sendToRelay: (topic: string, event: string, data: any, sender: TNotificationSender, port?: string) => Promise<any>;
42
+ sendToEventBus: (event: any, sender: TNotificationSender, port?: string) => Promise<any>;
40
43
  };
41
44
  export default _default;
@@ -1,37 +1,4 @@
1
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 () {
19
- var ownKeys = function(o) {
20
- ownKeys = Object.getOwnPropertyNames || function (o) {
21
- var ar = [];
22
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
- return ar;
24
- };
25
- return ownKeys(o);
26
- };
27
- return function (mod) {
28
- if (mod && mod.__esModule) return mod;
29
- var result = {};
30
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
- __setModuleDefault(result, mod);
32
- return result;
33
- };
34
- })();
35
2
  var __importDefault = (this && this.__importDefault) || function (mod) {
36
3
  return (mod && mod.__esModule) ? mod : { "default": mod };
37
4
  };
@@ -39,12 +6,13 @@ Object.defineProperty(exports, "__esModule", { value: true });
39
6
  exports.sendToEventBus = exports.sendToRelay = exports.sendToAppChannel = exports.sendToUser = void 0;
40
7
  const axios_1 = __importDefault(require("axios"));
41
8
  const pick_1 = __importDefault(require("lodash/pick"));
42
- const JWT = __importStar(require("@arcblock/jwt"));
43
9
  const constant_1 = __importDefault(require("@abtnode/constant"));
44
10
  const channel_1 = require("@blocklet/meta/lib/channel");
45
11
  const did_1 = require("@arcblock/did");
46
12
  const ufo_1 = require("ufo");
47
13
  const error_1 = require("@blocklet/error");
14
+ const wallet_1 = require("@ocap/wallet");
15
+ const mcrypto_1 = require("@ocap/mcrypto");
48
16
  const index_1 = require("../validators/index");
49
17
  const constants_1 = require("./constants");
50
18
  const version_1 = require("../version");
@@ -54,18 +22,37 @@ const { NODE_MODES } = constant_1.default;
54
22
  const VERSION = version_1.version; // version of notification sdk
55
23
  const SERVER_MODE = process.env.ABT_NODE_MODE;
56
24
  const getRequestHeaders = () => ({ 'User-Agent': `BlockletSDK/${VERSION}` });
25
+ /**
26
+ * Helper function to ensure we have a wallet object
27
+ * If wallet is not provided but appSk is, create wallet from appSk
28
+ */
29
+ const ensureWallet = (sender) => {
30
+ if (sender.wallet) {
31
+ return sender.wallet;
32
+ }
33
+ if (sender.appSk) {
34
+ const walletType = (0, wallet_1.WalletType)({
35
+ role: mcrypto_1.types.RoleType.ROLE_APPLICATION,
36
+ pk: mcrypto_1.types.KeyType.ED25519,
37
+ hash: mcrypto_1.types.HashType.SHA3,
38
+ });
39
+ return (0, wallet_1.fromSecretKey)(sender.appSk, walletType);
40
+ }
41
+ throw new Error('Either wallet or appSk must be provided in sender');
42
+ };
57
43
  /**
58
44
  * @param {String|Array} receiver
59
45
  * @param {Object} notification
60
46
  * @param {{
61
47
  * appDid: String
62
- * appSk: String
48
+ * wallet?: WalletObject
49
+ * appSk?: string
63
50
  * }} sender
64
51
  * @param {String|Number} port port of abtnode service endpoint
65
52
  * @param {Object} options
66
53
  * @returns
67
54
  */
68
- const sendToUser = async (receiver, notification, { appDid, appSk, type }, options = {}, pathname = 'send-to-user', port = process.env.ABT_NODE_SERVICE_PORT) => {
55
+ const sendToUser = async (receiver, notification, sender, options = {}, pathname = 'send-to-user', port = process.env.ABT_NODE_SERVICE_PORT) => {
69
56
  if (['send-to-user', 'send-to-push-kit', 'send-to-wallet'].includes(pathname)) {
70
57
  await (0, index_1.validateReceiver)(receiver);
71
58
  }
@@ -78,13 +65,15 @@ const sendToUser = async (receiver, notification, { appDid, appSk, type }, optio
78
65
  await (0, index_1.validateNotification)(notification);
79
66
  }
80
67
  try {
68
+ const wallet = ensureWallet(sender);
69
+ const token = await wallet.signJWT({});
81
70
  const { data: res } = await axios.post((0, ufo_1.joinURL)(`http://${(0, parse_docker_endpoint_1.getServerHost)()}:${port}`, constants_1.SERVICE_PREFIX, 'api', pathname), {
82
71
  apiVersion: VERSION,
83
72
  data: {
84
73
  sender: {
85
- appDid,
86
- type,
87
- token: JWT.sign(appDid, appSk),
74
+ appDid: sender.appDid,
75
+ type: sender.type,
76
+ token,
88
77
  componentDid: process.env.BLOCKLET_COMPONENT_DID,
89
78
  },
90
79
  receiver: Array.isArray(receiver) ? receiver.map(did_1.toAddress) : (0, did_1.toAddress)(receiver),
@@ -103,7 +92,7 @@ const sendToUser = async (receiver, notification, { appDid, appSk, type }, optio
103
92
  }
104
93
  };
105
94
  exports.sendToUser = sendToUser;
106
- const sendToAppChannel = async (channel, event, notification, { appDid, appSk }, options = {}, port = process.env.ABT_NODE_SERVICE_PORT) => {
95
+ const sendToAppChannel = async (channel, event, notification, sender, options = {}, port = process.env.ABT_NODE_SERVICE_PORT) => {
107
96
  if (!channel) {
108
97
  throw new Error('channel is required');
109
98
  }
@@ -121,10 +110,12 @@ const sendToAppChannel = async (channel, event, notification, { appDid, appSk },
121
110
  await (0, index_1.validateNotification)(notification);
122
111
  }
123
112
  try {
113
+ const wallet = ensureWallet(sender);
114
+ const token = await wallet.signJWT({});
124
115
  const { data: res } = await axios.post(`http://${(0, parse_docker_endpoint_1.getServerHost)()}:${port}${constants_1.SERVICE_PREFIX}/api/send-to-app-channel`, {
125
116
  apiVersion: VERSION,
126
117
  data: {
127
- sender: { appDid, token: JWT.sign(appDid, appSk) },
118
+ sender: { appDid: sender.appDid, token },
128
119
  channel,
129
120
  event,
130
121
  notification,
@@ -142,7 +133,7 @@ const sendToAppChannel = async (channel, event, notification, { appDid, appSk },
142
133
  }
143
134
  };
144
135
  exports.sendToAppChannel = sendToAppChannel;
145
- const sendToRelay = async (topic, event, data, { appDid, appSk }, port = process.env.ABT_NODE_SERVICE_PORT) => {
136
+ const sendToRelay = async (topic, event, data, sender, port = process.env.ABT_NODE_SERVICE_PORT) => {
146
137
  if (!topic) {
147
138
  throw new Error('topic is required');
148
139
  }
@@ -153,11 +144,13 @@ const sendToRelay = async (topic, event, data, { appDid, appSk }, port = process
153
144
  throw new Error('data is required');
154
145
  }
155
146
  try {
147
+ const wallet = ensureWallet(sender);
148
+ const token = await wallet.signJWT({});
156
149
  const { data: res } = await axios.post(`http://${(0, parse_docker_endpoint_1.getServerHost)()}:${port}${constants_1.SERVICE_PREFIX}/relay/api/send-to-relay-channel`, {
157
150
  apiVersion: VERSION,
158
151
  data: {
159
- sender: { appDid, token: JWT.sign(appDid, appSk) },
160
- channel: (0, channel_1.getRelayChannel)(appDid, topic),
152
+ sender: { appDid: sender.appDid, token },
153
+ channel: (0, channel_1.getRelayChannel)(sender.appDid, topic),
161
154
  event,
162
155
  data,
163
156
  },
@@ -173,16 +166,18 @@ const sendToRelay = async (topic, event, data, { appDid, appSk }, port = process
173
166
  }
174
167
  };
175
168
  exports.sendToRelay = sendToRelay;
176
- const sendToEventBus = async (event, { appDid, appSk }, port = process.env.ABT_NODE_SERVICE_PORT) => {
169
+ const sendToEventBus = async (event, sender, port = process.env.ABT_NODE_SERVICE_PORT) => {
177
170
  if (!event) {
178
171
  throw new Error('event is required');
179
172
  }
180
173
  try {
174
+ const wallet = ensureWallet(sender);
175
+ const token = await wallet.signJWT({});
181
176
  const { data: res } = await axios.post(`http://${(0, parse_docker_endpoint_1.getServerHost)()}:${port}${constants_1.SERVICE_PREFIX}/api/send-to-event-bus`, {
182
177
  apiVersion: VERSION,
183
178
  data: {
184
- sender: { appDid, token: JWT.sign(appDid, appSk) },
185
- channel: (0, channel_1.getEventBusChannel)(appDid),
179
+ sender: { appDid: sender.appDid, token },
180
+ channel: (0, channel_1.getEventBusChannel)(sender.appDid),
186
181
  event,
187
182
  },
188
183
  }, {
@@ -13,6 +13,7 @@ const ufo_1 = require("ufo");
13
13
  const constants_1 = require("./constants");
14
14
  const verify_sign_1 = require("./verify-sign");
15
15
  const parse_docker_endpoint_1 = require("./parse-docker-endpoint");
16
+ const { serverVersion } = env_1.blockletEnv;
16
17
  const axios = axios_1.default.create({
17
18
  // 为当前机器的内部调用,必须禁止 proxy 配置
18
19
  proxy: false,
@@ -20,19 +21,22 @@ const axios = axios_1.default.create({
20
21
  // 内部调用,超时时间不用过长
21
22
  timeout: 6 * 1000,
22
23
  headers: {
23
- 'User-Agent': `BlockletSDK/${env_1.serverVersion}`,
24
- 'x-blocklet-server-version': env_1.serverVersion,
24
+ 'User-Agent': `BlockletSDK/${serverVersion}`,
25
+ 'x-blocklet-server-version': serverVersion,
25
26
  // NOTICE: 需要注入以下两个 header,才能使 blocklet-service 中的代码识别到当前的 blocklet 环境
26
27
  'x-blocklet-did': process.env.BLOCKLET_DID,
27
28
  'x-blocklet-component-id': process.env.BLOCKLET_REAL_DID,
28
29
  },
29
30
  });
30
- axios.interceptors.request.use((config) => {
31
- const { sig, exp, iat, version } = (0, verify_sign_1.getSignData)({
31
+ axios.interceptors.request.use(async (config) => {
32
+ const { sig, exp, iat, version } = await (0, verify_sign_1.getSignData)({
32
33
  data: config.data,
33
34
  method: config.method,
34
35
  params: config.params,
35
36
  url: (0, ufo_1.joinURL)(constants_1.SERVICE_PREFIX, config.url),
37
+ }, {
38
+ // Compatible with previous version where APP_ASK does not exist
39
+ appSk: process.env.BLOCKLET_APP_ASK || process.env.BLOCKLET_APP_SK,
36
40
  });
37
41
  // 同时对 post 和 get 参数做签名,确保同时支持 post get 请求的校验
38
42
  // 签名使用的是当前 blocklet 的 appSk,固命名为 x-blocklet-sig,以后可做统一使用
@@ -9,16 +9,19 @@ exports.verifyAccessKey = verifyAccessKey;
9
9
  exports.verifyComponentCall = verifyComponentCall;
10
10
  exports.verifySignedToken = verifySignedToken;
11
11
  const constant_1 = require("@blocklet/constant");
12
+ const jwt_1 = require("@arcblock/jwt");
12
13
  const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
13
14
  const mcrypto_1 = require("@ocap/mcrypto");
14
- const jwt_1 = require("@arcblock/jwt");
15
- const wallet_1 = __importDefault(require("../wallet"));
16
- const auth_1 = __importDefault(require("../middlewares/auth"));
15
+ const wallet_1 = require("../wallet");
16
+ const auth_1 = require("../middlewares/auth");
17
17
  const login_1 = require("./login");
18
18
  const config_1 = require("../config");
19
19
  const verify_sign_1 = require("./verify-sign");
20
20
  const getSessionSecret = () => {
21
- const wallet = (0, wallet_1.default)();
21
+ if (process.env.BLOCKLET_SESSION_SECRET) {
22
+ return process.env.BLOCKLET_SESSION_SECRET;
23
+ }
24
+ const wallet = (0, wallet_1.getWallet)();
22
25
  const secret = mcrypto_1.Hasher.SHA3.hash256(Buffer.concat([wallet.secretKey, wallet.address, config_1.env.sessionSalt].filter(Boolean).map((v) => Buffer.from(v))));
23
26
  return secret;
24
27
  };
@@ -56,7 +59,7 @@ async function verifyAccessKey({ token, strictMode }) {
56
59
  if (!token)
57
60
  return null;
58
61
  try {
59
- const client = auth_1.default.getServiceClient();
62
+ const client = auth_1.authMiddleware.getServiceClient();
60
63
  const result = await client.verifyAccessKey({ accessKeyId: token });
61
64
  const { createdBy, accessKeyId, passport = 'guest', remark = '' } = result.data;
62
65
  return {
@@ -80,7 +83,7 @@ async function verifyComponentCall({ req, strictMode }) {
80
83
  const { sig, data } = (0, verify_sign_1.getVerifyData)(req);
81
84
  if (!sig)
82
85
  return null;
83
- if ((await (0, verify_sign_1.verify)(data, sig)) === false) {
86
+ if ((await (0, verify_sign_1.verify)(data, sig, { appSk: process.env.BLOCKLET_APP_ASK || process.env.BLOCKLET_APP_SK })) === false) {
84
87
  if (strictMode) {
85
88
  throw new Error('Unauthorized: Invalid signature');
86
89
  }
@@ -100,7 +103,7 @@ async function verifyComponentCall({ req, strictMode }) {
100
103
  async function verifySignedToken({ token, strictMode }) {
101
104
  if (!token)
102
105
  return null;
103
- const wallet = (0, wallet_1.default)();
106
+ const wallet = (0, wallet_1.getWallet)();
104
107
  if (!(await (0, jwt_1.verify)(token, wallet.publicKey))) {
105
108
  if (strictMode) {
106
109
  throw new Error('Unauthorized: Invalid signed token');
@@ -1,14 +1,15 @@
1
1
  import { DIDTypeShortcut } from '@arcblock/did';
2
2
  import type { Request } from 'express';
3
- declare const verify: (data: object, sig: string, { type, appSk, appPk, }?: {
3
+ type SignOptions = {
4
4
  type?: DIDTypeShortcut;
5
5
  appSk?: string;
6
- appPk?: string;
7
- }) => any;
8
- declare const sign: (data: object, { type, appSk, }?: {
6
+ };
7
+ declare const verify: (data: object, sig: string, { type, appSk, appPk, }?: {
9
8
  type?: DIDTypeShortcut;
10
9
  appSk?: string;
11
- }) => string;
10
+ appPk?: string;
11
+ }) => Promise<any>;
12
+ declare const sign: (data: object, { type, appSk }?: SignOptions) => Promise<string>;
12
13
  type SignType = 'component' | 'blocklet';
13
14
  declare const getVerifyData: (req: Request, type?: SignType) => {
14
15
  sig: string;
@@ -29,11 +30,11 @@ declare const getSignData: ({ data, params, method, url, }: {
29
30
  params: object;
30
31
  method: string;
31
32
  url: string;
32
- }, signOptions?: object) => {
33
+ }, signOptions?: SignOptions) => Promise<{
33
34
  sig: string;
34
35
  iat: number;
35
36
  exp: number;
36
37
  version: string;
37
38
  raw: SignSeed;
38
- };
39
+ }>;
39
40
  export { verify, sign, getVerifyData, getSignData };
@@ -2,39 +2,6 @@
2
2
  /*
3
3
  * @Description: 用于 sdk 中调用 blocklet-service 接口时的加解密工具库
4
4
  */
5
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
6
- if (k2 === undefined) k2 = k;
7
- var desc = Object.getOwnPropertyDescriptor(m, k);
8
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
9
- desc = { enumerable: true, get: function() { return m[k]; } };
10
- }
11
- Object.defineProperty(o, k2, desc);
12
- }) : (function(o, m, k, k2) {
13
- if (k2 === undefined) k2 = k;
14
- o[k2] = m[k];
15
- }));
16
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
17
- Object.defineProperty(o, "default", { enumerable: true, value: v });
18
- }) : function(o, v) {
19
- o["default"] = v;
20
- });
21
- var __importStar = (this && this.__importStar) || (function () {
22
- var ownKeys = function(o) {
23
- ownKeys = Object.getOwnPropertyNames || function (o) {
24
- var ar = [];
25
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
26
- return ar;
27
- };
28
- return ownKeys(o);
29
- };
30
- return function (mod) {
31
- if (mod && mod.__esModule) return mod;
32
- var result = {};
33
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
34
- __setModuleDefault(result, mod);
35
- return result;
36
- };
37
- })();
38
5
  var __importDefault = (this && this.__importDefault) || function (mod) {
39
6
  return (mod && mod.__esModule) ? mod : { "default": mod };
40
7
  };
@@ -46,20 +13,21 @@ const ufo_1 = require("ufo");
46
13
  const constant_1 = require("@blocklet/constant");
47
14
  const semver_1 = __importDefault(require("semver"));
48
15
  const qs_1 = __importDefault(require("qs"));
49
- const wallet_1 = __importStar(require("../wallet"));
50
- const verify = (data, sig, { type, appSk, appPk, } = {}) => {
16
+ const wallet_1 = require("../wallet");
17
+ const { getPkWallet } = wallet_1.getWallet;
18
+ const verify = async (data, sig, { type, appSk, appPk, } = {}) => {
51
19
  try {
52
20
  if (!sig) {
53
21
  throw new Error('empty sig');
54
22
  }
55
23
  let wallet;
56
24
  if (appPk) {
57
- wallet = (0, wallet_1.getPkWallet)(type, appPk);
25
+ wallet = getPkWallet(type, appPk);
58
26
  }
59
27
  else {
60
- wallet = (0, wallet_1.default)(type, appSk);
28
+ wallet = (0, wallet_1.getWallet)(type, appSk);
61
29
  }
62
- const verified = wallet.verify((0, json_stable_stringify_1.default)(data || {}), sig);
30
+ const verified = await wallet.verify((0, json_stable_stringify_1.default)(data || {}), sig);
63
31
  return verified;
64
32
  }
65
33
  catch {
@@ -67,8 +35,9 @@ const verify = (data, sig, { type, appSk, appPk, } = {}) => {
67
35
  }
68
36
  };
69
37
  exports.verify = verify;
70
- const sign = (data, { type, appSk, } = {}) => {
71
- const wallet = (0, wallet_1.default)(type, appSk);
38
+ // eslint-disable-next-line require-await
39
+ const sign = async (data, { type, appSk } = {}) => {
40
+ const wallet = (0, wallet_1.getWallet)(type, appSk);
72
41
  return wallet.sign((0, json_stable_stringify_1.default)(data || {}));
73
42
  };
74
43
  exports.sign = sign;
@@ -115,7 +84,7 @@ const getVerifyData = (req, type = 'component') => {
115
84
  return { sig, data, sigVersion, sigPk };
116
85
  };
117
86
  exports.getVerifyData = getVerifyData;
118
- const getSignData = ({ data, params, method, url, }, signOptions) => {
87
+ const getSignData = async ({ data, params, method, url, }, signOptions) => {
119
88
  const iat = Math.floor(Date.now() / 1000);
120
89
  const exp = iat + 60 * 5;
121
90
  const raw = {
@@ -129,7 +98,7 @@ const getSignData = ({ data, params, method, url, }, signOptions) => {
129
98
  raw.query = qs_1.default.parse(qs_1.default.stringify((0, merge_1.default)(qs_1.default.parse(tmp.search.slice(1)), params ?? {})));
130
99
  raw.method = method.toLowerCase();
131
100
  raw.url = tmp.pathname;
132
- const sig = sign(raw, signOptions);
101
+ const sig = await sign(raw, signOptions);
133
102
  const version = constant_1.SIG_VERSION.DEFAULT;
134
103
  return {
135
104
  sig,
@@ -5,4 +5,4 @@ declare class WalletAuthenticator extends Authenticator {
5
5
  private authClient;
6
6
  private blockletClient;
7
7
  }
8
- export = WalletAuthenticator;
8
+ export { WalletAuthenticator };
@@ -1,21 +1,20 @@
1
1
  "use strict";
2
- var __importDefault = (this && this.__importDefault) || function (mod) {
3
- return (mod && mod.__esModule) ? mod : { "default": mod };
4
- };
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.WalletAuthenticator = void 0;
5
4
  const did_connect_js_1 = require("@arcblock/did-connect-js");
6
- const wallet_1 = __importDefault(require("./wallet"));
7
- const check_blocklet_env_1 = __importDefault(require("./util/check-blocklet-env"));
5
+ const wallet_1 = require("./wallet");
6
+ const check_blocklet_env_1 = require("./util/check-blocklet-env");
8
7
  const shared_1 = require("./connect/shared");
9
- const blocklet_1 = __importDefault(require("./service/blocklet"));
8
+ const blocklet_1 = require("./service/blocklet");
10
9
  class WalletAuthenticator extends did_connect_js_1.WalletAuthenticator {
11
10
  constructor(options = {}) {
12
- (0, check_blocklet_env_1.default)();
11
+ (0, check_blocklet_env_1.checkBlockletEnvironment)();
13
12
  super({
14
- wallet: (0, wallet_1.default)().toJSON(),
13
+ wallet: (0, wallet_1.getWallet)(),
15
14
  ...(0, shared_1.getAuthenticatorProps)(options),
16
15
  });
17
- this.blockletClient = new blocklet_1.default();
16
+ this.blockletClient = new blocklet_1.BlockletService();
18
17
  this.authClient = this.blockletClient;
19
18
  }
20
19
  }
21
- module.exports = WalletAuthenticator;
20
+ exports.WalletAuthenticator = WalletAuthenticator;
@@ -16,4 +16,4 @@ declare class WalletHandlers extends Handler {
16
16
  onStart?: () => {};
17
17
  }): void;
18
18
  }
19
- export = WalletHandlers;
19
+ export { WalletHandlers };
@@ -35,6 +35,8 @@ var __importStar = (this && this.__importStar) || (function () {
35
35
  var __importDefault = (this && this.__importDefault) || function (mod) {
36
36
  return (mod && mod.__esModule) ? mod : { "default": mod };
37
37
  };
38
+ Object.defineProperty(exports, "__esModule", { value: true });
39
+ exports.WalletHandlers = void 0;
38
40
  const get_1 = __importDefault(require("lodash/get"));
39
41
  const did_connect_js_1 = require("@arcblock/did-connect-js");
40
42
  const notification_1 = __importStar(require("./service/notification"));
@@ -129,4 +131,4 @@ class WalletHandlers extends did_connect_js_1.WalletHandlers {
129
131
  });
130
132
  }
131
133
  }
132
- module.exports = WalletHandlers;
134
+ exports.WalletHandlers = WalletHandlers;
package/lib/wallet.d.ts CHANGED
@@ -1,14 +1,42 @@
1
1
  import { WalletObject } from '@ocap/wallet';
2
- import { DIDTypeShortcut } from '@arcblock/did';
2
+ import { DIDTypeShortcut, DIDTypeArg } from '@arcblock/did';
3
+ import { LRUCache } from 'lru-cache';
4
+ export declare const cacheWallet: LRUCache<string, WalletObject<string>, unknown>;
5
+ /**
6
+ * Create a wallet from public key
7
+ * Internal helper function used by both createRemoteWallet and getWallet.getPkWallet
8
+ */
9
+ export declare const getPkWallet: (type?: DIDTypeShortcut, appPk?: string) => WalletObject;
10
+ /**
11
+ * Create a remote wallet with sign and signJWT methods that call blocklet-service
12
+ * @param publicKey - The public key to create the wallet from
13
+ * @param type - The wallet type
14
+ * @param keyType - Key type to use ('sk' or 'psk')
15
+ * @returns Wallet object with remote sign and signJWT methods
16
+ */
17
+ export declare const createRemoteWallet: (publicKey: string, type?: any, keyType?: "sk" | "psk") => WalletObject;
3
18
  /**
4
19
  * @param {string} [type=process.env.CHAIN_TYPE] can only be 'eth|ethereum' or 'default|arcblock'
5
20
  * @param {string} [appSk=process.env.BLOCKLET_APP_SK] must be hex
21
+ * @param {string} [keyType='sk'] key type to use ('sk' or 'psk')
6
22
  * @return {WalletObject} {WalletObject}
7
23
  */
8
- declare const getWallet: {
9
- (type?: DIDTypeShortcut, appSk?: string): WalletObject;
10
- getPermanentWallet(): WalletObject<string>;
11
- getEthereumWallet(permanent?: boolean): WalletObject<string>;
12
- getPkWallet(type?: DIDTypeShortcut, appPk?: string): WalletObject<string>;
24
+ export declare const getWallet: {
25
+ (type?: DIDTypeShortcut, appSk?: string, keyType?: "sk" | "psk"): WalletObject;
26
+ getPermanentWallet: () => WalletObject<string>;
27
+ getEthereumWallet: (permanent?: boolean) => WalletObject<string>;
28
+ getPkWallet: (type?: DIDTypeShortcut, appPk?: string) => WalletObject;
29
+ deriveWallet: (sub: string, type?: DIDTypeArg, index?: number) => Promise<WalletObject>;
30
+ getAccessWallet: () => WalletObject<string>;
13
31
  };
14
- export = getWallet;
32
+ /**
33
+ * Create wallet from app DID with automatic fallback to remote signing
34
+ * @param sub - Subject identifier (e.g., 'email|user@example.com')
35
+ * @param type - DID type shortcut (e.g., 'ethereum')
36
+ * @param index - Index for deriving wallet (default: 0)
37
+ * @returns Wallet object with sign and signJWT methods
38
+ */
39
+ export declare const deriveWallet: (sub: string, type?: DIDTypeArg, index?: number) => Promise<WalletObject>;
40
+ export declare const getPermanentWallet: () => WalletObject<string>;
41
+ export declare const getEthereumWallet: (permanent?: boolean) => WalletObject<string>;
42
+ export declare const getAccessWallet: () => WalletObject<string>;