@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
@@ -0,0 +1,6 @@
1
+ export default function generateBlockletEmbed(): {
2
+ name: string;
3
+ url: string;
4
+ origin: string;
5
+ embed: any[];
6
+ };
@@ -0,0 +1,30 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ function safeJsonParse(input, defaultValue) {
4
+ try {
5
+ return JSON.parse(input);
6
+ }
7
+ catch {
8
+ return defaultValue;
9
+ }
10
+ }
11
+ function generateBlockletEmbed() {
12
+ const { BLOCKLET_APP_NAME, BLOCKLET_APP_URL, BLOCKLET_REAL_NAME } = process.env;
13
+ const BLOCKLET_MOUNT_POINTS = safeJsonParse(process.env.BLOCKLET_MOUNT_POINTS, []);
14
+ let url = '/';
15
+ let name = BLOCKLET_APP_NAME;
16
+ const blockletNames = BLOCKLET_REAL_NAME.split('/');
17
+ const componentBlocklet = BLOCKLET_MOUNT_POINTS.find((blockletItem) => blockletItem.name === blockletNames[blockletNames.length - 1]);
18
+ if (componentBlocklet) {
19
+ // 先假设只有一层 component blocklet
20
+ url = componentBlocklet.mountPoint;
21
+ name = componentBlocklet.title;
22
+ }
23
+ return {
24
+ name,
25
+ url,
26
+ origin: BLOCKLET_APP_URL,
27
+ embed: [],
28
+ };
29
+ }
30
+ exports.default = generateBlockletEmbed;
@@ -0,0 +1 @@
1
+ export default function getEmbedUrlFromUrl(url: string): Promise<string>;
@@ -0,0 +1,55 @@
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
+ const slim_1 = require("cheerio/lib/slim");
7
+ const ufo_1 = require("ufo");
8
+ const axios_1 = __importDefault(require("axios"));
9
+ /**
10
+ * 判断 htmlContent 是否为开发环境
11
+ * @param {string} htmlContent
12
+ * @returns boolean
13
+ */
14
+ function checkViteDev(htmlContent) {
15
+ const $ = (0, slim_1.load)(htmlContent);
16
+ const scirptList = $('script[type="module"]');
17
+ return !![...scirptList].find((scriptItem) => {
18
+ if (scriptItem.firstChild?.type === 'text') {
19
+ return scriptItem.firstChild?.data?.includes('window.__vite_plugin_react_preamble_installed__ = true');
20
+ }
21
+ return false;
22
+ });
23
+ }
24
+ async function getEmbedUrlFromUrl(url) {
25
+ try {
26
+ const { data: htmlContent } = await axios_1.default.get(url, {
27
+ headers: {
28
+ accept: 'text/html,application/xhtml+xml,application/xml',
29
+ },
30
+ });
31
+ let prefix = '/';
32
+ let metaUrl = url;
33
+ const $ = (0, slim_1.load)(htmlContent);
34
+ const link = $('link[rel="blocklet-open-embed"]');
35
+ const blockletScript = $('script[src="__blocklet__.js"]');
36
+ if (link && link.length > 0) {
37
+ metaUrl = link.attr('href') || url;
38
+ }
39
+ else {
40
+ return url;
41
+ }
42
+ const isViteDev = checkViteDev(htmlContent);
43
+ if (blockletScript && blockletScript.length > 0) {
44
+ const scriptUrl = new URL('__blocklet__.js?type=json', (0, ufo_1.withTrailingSlash)(url));
45
+ const { data: blockletMeta } = await axios_1.default.get(scriptUrl.href);
46
+ prefix = blockletMeta.prefix;
47
+ }
48
+ // 在 vite 开发模式下,embed-url 指向的地址会自动被增加一个前缀
49
+ return isViteDev ? (0, ufo_1.joinURL)(prefix, metaUrl.replace(prefix, '')) : (0, ufo_1.joinURL)(prefix, metaUrl);
50
+ }
51
+ catch {
52
+ return url;
53
+ }
54
+ }
55
+ exports.default = getEmbedUrlFromUrl;
@@ -0,0 +1 @@
1
+ export default function getBlockletEmbedFromUrl(url: string): Promise<object | null>;
@@ -0,0 +1,32 @@
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
+ const path_1 = require("path");
7
+ const lodash_1 = require("lodash");
8
+ const axios_1 = __importDefault(require("axios"));
9
+ const get_embed_url_1 = __importDefault(require("./get-embed-url"));
10
+ async function getBlockletEmbedFromUrl(url) {
11
+ const metaUrl = await (0, get_embed_url_1.default)(url);
12
+ try {
13
+ if (metaUrl) {
14
+ let finalUrl = '';
15
+ if (metaUrl.startsWith('http://') || metaUrl.startsWith('https://')) {
16
+ finalUrl = metaUrl;
17
+ }
18
+ else {
19
+ finalUrl = `${new URL(url).origin}${(0, path_1.join)('/', metaUrl)}`;
20
+ }
21
+ const { data: metaData } = await axios_1.default.get(finalUrl);
22
+ if ((0, lodash_1.isObject)(metaData)) {
23
+ return metaData;
24
+ }
25
+ }
26
+ }
27
+ catch {
28
+ /* empty */
29
+ }
30
+ return null;
31
+ }
32
+ exports.default = getBlockletEmbedFromUrl;
@@ -0,0 +1,10 @@
1
+ import generateBlockletEmbed from './generate';
2
+ import expressEmbed from './adapters/express';
3
+ import getBlockletEmbedFromUrl from './get-embed';
4
+ declare const _default: {
5
+ expressEmbed: typeof expressEmbed;
6
+ generateBlockletEmbed: typeof generateBlockletEmbed;
7
+ getBlockletEmbedFromUrl: typeof getBlockletEmbedFromUrl;
8
+ };
9
+ export default _default;
10
+ export { expressEmbed, generateBlockletEmbed, getBlockletEmbedFromUrl };
@@ -0,0 +1,13 @@
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.getBlockletEmbedFromUrl = exports.generateBlockletEmbed = exports.expressEmbed = void 0;
7
+ const generate_1 = __importDefault(require("./generate"));
8
+ exports.generateBlockletEmbed = generate_1.default;
9
+ const express_1 = __importDefault(require("./adapters/express"));
10
+ exports.expressEmbed = express_1.default;
11
+ const get_embed_1 = __importDefault(require("./get-embed"));
12
+ exports.getBlockletEmbedFromUrl = get_embed_1.default;
13
+ exports.default = { expressEmbed: express_1.default, generateBlockletEmbed: generate_1.default, getBlockletEmbedFromUrl: get_embed_1.default };
@@ -0,0 +1,26 @@
1
+ type InstanceType = 'client' | 'server';
2
+ type MessageType = string;
3
+ interface Callback {
4
+ (...args: any[]): void;
5
+ }
6
+ declare class Message {
7
+ id: string;
8
+ type: InstanceType;
9
+ private bc;
10
+ private eventMap;
11
+ init: (cb: Callback) => void;
12
+ onInit: (getData: () => any) => void;
13
+ close: () => void;
14
+ constructor(id: string, type?: InstanceType);
15
+ on(type: MessageType, cb: Callback): void;
16
+ off(type: MessageType, cb: Callback): void;
17
+ once(type: MessageType, cb: Callback): void;
18
+ send(type: MessageType, payload: any): void;
19
+ }
20
+ declare function useMessage(id?: string, type?: InstanceType): any;
21
+ declare const _default: {
22
+ useMessage: typeof useMessage;
23
+ Message: typeof Message;
24
+ };
25
+ export default _default;
26
+ export { useMessage, Message };
@@ -0,0 +1,134 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.Message = exports.useMessage = void 0;
4
+ const INIT = '__init';
5
+ const ON_INIT = '__on-init';
6
+ function checkKey(typeKey) {
7
+ return !typeKey.startsWith(INIT);
8
+ }
9
+ function ensureType(type) {
10
+ if (!checkKey(type)) {
11
+ throw new Error(`Type can't starts with ${INIT}`);
12
+ }
13
+ }
14
+ function notExist() {
15
+ console.error('function not exist');
16
+ }
17
+ class Message {
18
+ constructor(id, type = 'client') {
19
+ this.id = id;
20
+ this.type = type;
21
+ const bc = new BroadcastChannel(this.id);
22
+ this.bc = bc;
23
+ this.eventMap = new Map();
24
+ const onMessage = (event) => {
25
+ const { data } = event;
26
+ const { type: messageType, payload, id: dataId } = data;
27
+ if (dataId === this.id) {
28
+ const cbList = this.eventMap.get(messageType) || [];
29
+ cbList.forEach((cbItem) => {
30
+ cbItem(payload);
31
+ });
32
+ }
33
+ };
34
+ window.addEventListener('message', onMessage, false);
35
+ this.close = () => {
36
+ window.removeEventListener('message', onMessage, false);
37
+ // v1 message
38
+ this.bc.close();
39
+ };
40
+ // v1 message
41
+ bc.onmessage = ({ data }) => {
42
+ const { type: messageType, payload } = data;
43
+ const cbList = this.eventMap.get(messageType) || [];
44
+ cbList.forEach((cbItem) => {
45
+ cbItem(payload);
46
+ });
47
+ };
48
+ this.init = notExist;
49
+ this.onInit = notExist;
50
+ if (type === 'server') {
51
+ this.onInit = (getData = () => null) => {
52
+ this.eventMap.set(INIT, [
53
+ (listenKey) => {
54
+ const initData = getData();
55
+ this.send(listenKey, initData);
56
+ },
57
+ ]);
58
+ };
59
+ }
60
+ if (type === 'client') {
61
+ this.init = (cb) => {
62
+ const uniqueId = String(+new Date());
63
+ const listenKey = `${ON_INIT}_${uniqueId}`;
64
+ this.once(listenKey, cb);
65
+ this.send(INIT, listenKey);
66
+ };
67
+ }
68
+ }
69
+ on(type, cb) {
70
+ ensureType(type);
71
+ const cbList = this.eventMap.get(type) || [];
72
+ cbList.push(cb);
73
+ this.eventMap.set(type, cbList);
74
+ }
75
+ off(type, cb) {
76
+ ensureType(type);
77
+ const cbList = this.eventMap.get(type) || [];
78
+ if (cb) {
79
+ const index = cbList.indexOf(cb);
80
+ if (index !== -1) {
81
+ cbList.splice(index, 1);
82
+ }
83
+ }
84
+ else {
85
+ cbList.length = 0;
86
+ }
87
+ this.eventMap.set(type, cbList);
88
+ }
89
+ once(type, cb) {
90
+ ensureType(type);
91
+ const callback = (...args) => {
92
+ cb(...args);
93
+ this.off(type, callback);
94
+ };
95
+ this.on(type, callback);
96
+ }
97
+ send(type, payload) {
98
+ const data = {
99
+ id: this.id,
100
+ type,
101
+ payload,
102
+ };
103
+ if (this.type === 'server') {
104
+ const iframeList = [...document.querySelectorAll(`iframe[data-id="${this.id}"]`)];
105
+ iframeList.forEach((iframeItem) => {
106
+ iframeItem.contentWindow.postMessage(data, '*');
107
+ });
108
+ }
109
+ else {
110
+ window.parent.postMessage(data, '*');
111
+ }
112
+ // v1 message
113
+ this.bc.postMessage(data);
114
+ }
115
+ }
116
+ exports.Message = Message;
117
+ const messageCache = new Map();
118
+ function useMessage(id, type = 'client') {
119
+ // eslint-disable-next-line @typescript-eslint/naming-convention
120
+ const _id = id || window.frameElement?.dataset.id || window.name;
121
+ if (messageCache.has(_id)) {
122
+ return messageCache.get(_id);
123
+ }
124
+ const isInIframe = window !== window.parent;
125
+ const message = (type === 'server' || isInIframe) && _id ? new Message(_id, type) : null;
126
+ const data = { message };
127
+ messageCache.set(_id, data);
128
+ return data;
129
+ }
130
+ exports.useMessage = useMessage;
131
+ exports.default = {
132
+ useMessage,
133
+ Message,
134
+ };
package/lib/env.d.ts ADDED
@@ -0,0 +1,17 @@
1
+ declare const _default: Readonly<{
2
+ appId: string;
3
+ appPid: string;
4
+ appName: string;
5
+ appDescription: string;
6
+ appUrl: string;
7
+ isComponent: boolean;
8
+ dataDir: string;
9
+ cacheDir: string;
10
+ mode: string;
11
+ appStorageEndpoint: string;
12
+ serverVersion: string;
13
+ preferences: {
14
+ [key: string]: any;
15
+ };
16
+ }>;
17
+ export = _default;
package/lib/env.js ADDED
@@ -0,0 +1,3 @@
1
+ "use strict";
2
+ const env_1 = require("./util/env");
3
+ module.exports = (0, env_1.parseEnv)();
File without changes
@@ -1,9 +1,9 @@
1
1
  process
2
- .on('uncaughtException', (error) => {
3
- console.error(error.message);
2
+ .on('uncaughtException', (err) => {
3
+ console.error(err.message);
4
4
  process.exit(1);
5
- })
6
- .on('unhandledRejection', (reason) => {
5
+ })
6
+ .on('unhandledRejection', (reason) => {
7
7
  console.error(reason.message);
8
8
  process.exit(1);
9
- });
9
+ });
package/lib/index.d.ts ADDED
@@ -0,0 +1,53 @@
1
+ import { TNavigation, TTheme } from '@blocklet/meta/lib/types';
2
+ import Auth from './service/auth';
3
+ import Notification from './service/notification';
4
+ import WalletAuthenticator from './wallet-authenticator';
5
+ import WalletHandlers from './wallet-handler';
6
+ import BlockletAuthenticator from './connect/authenticator';
7
+ import createConnectHandlers from './connect/handler';
8
+ import Database from './database/index';
9
+ import env from './env';
10
+ import middlewares from './middlewares/index';
11
+ import getWallet from './wallet';
12
+ import Component, { MountPoint } from './component/index';
13
+ import Security from './security/index';
14
+ import config from './config';
15
+ export { Auth as AuthService };
16
+ export { Auth };
17
+ export { Notification as NotificationService };
18
+ export { Notification };
19
+ export { WalletHandlers };
20
+ export { WalletAuthenticator };
21
+ export { BlockletAuthenticator };
22
+ export { createConnectHandlers };
23
+ export { Database };
24
+ export { getWallet };
25
+ export { env };
26
+ export { middlewares };
27
+ export { Component as component };
28
+ export { Component };
29
+ export { Security };
30
+ export { config };
31
+ declare global {
32
+ interface Window {
33
+ blocklet: {
34
+ [x: string]: any;
35
+ appId: string;
36
+ appPid: string;
37
+ appName: string;
38
+ appDescription: string;
39
+ appLogo: string;
40
+ appLogoRect: string;
41
+ appUrl: string;
42
+ isComponent: boolean;
43
+ prefix: string;
44
+ groupPrefix: string;
45
+ version: string;
46
+ theme: TTheme;
47
+ navigation: TNavigation[];
48
+ preferences: any;
49
+ componentMountPoints: MountPoint[];
50
+ };
51
+ }
52
+ }
53
+ export * from './component';
package/lib/index.js CHANGED
@@ -1,13 +1,50 @@
1
- const AuthService = require('./service/auth');
2
- const NotificationService = require('./service/notification');
3
- const WalletAuthenticator = require('./wallet-authenticator');
4
- const WalletHandlers = require('./wallet-handler');
5
- const Database = require('./database');
6
-
7
- module.exports = {
8
- AuthService,
9
- NotificationService,
10
- WalletHandlers,
11
- WalletAuthenticator,
12
- Database,
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 __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
13
15
  };
16
+ var __importDefault = (this && this.__importDefault) || function (mod) {
17
+ return (mod && mod.__esModule) ? mod : { "default": mod };
18
+ };
19
+ Object.defineProperty(exports, "__esModule", { value: true });
20
+ exports.config = exports.Security = exports.Component = exports.component = exports.middlewares = exports.env = exports.getWallet = exports.Database = exports.createConnectHandlers = exports.BlockletAuthenticator = exports.WalletAuthenticator = exports.WalletHandlers = exports.Notification = exports.NotificationService = exports.Auth = exports.AuthService = void 0;
21
+ const auth_1 = __importDefault(require("./service/auth"));
22
+ exports.AuthService = auth_1.default;
23
+ exports.Auth = auth_1.default;
24
+ const notification_1 = __importDefault(require("./service/notification"));
25
+ exports.NotificationService = notification_1.default;
26
+ exports.Notification = notification_1.default;
27
+ const wallet_authenticator_1 = __importDefault(require("./wallet-authenticator"));
28
+ exports.WalletAuthenticator = wallet_authenticator_1.default;
29
+ const wallet_handler_1 = __importDefault(require("./wallet-handler"));
30
+ exports.WalletHandlers = wallet_handler_1.default;
31
+ const authenticator_1 = __importDefault(require("./connect/authenticator"));
32
+ exports.BlockletAuthenticator = authenticator_1.default;
33
+ const handler_1 = __importDefault(require("./connect/handler"));
34
+ exports.createConnectHandlers = handler_1.default;
35
+ const index_1 = __importDefault(require("./database/index"));
36
+ exports.Database = index_1.default;
37
+ const env_1 = __importDefault(require("./env"));
38
+ exports.env = env_1.default;
39
+ const index_2 = __importDefault(require("./middlewares/index"));
40
+ exports.middlewares = index_2.default;
41
+ const wallet_1 = __importDefault(require("./wallet"));
42
+ exports.getWallet = wallet_1.default;
43
+ const index_3 = __importDefault(require("./component/index"));
44
+ exports.component = index_3.default;
45
+ exports.Component = index_3.default;
46
+ const index_4 = __importDefault(require("./security/index"));
47
+ exports.Security = index_4.default;
48
+ const config_1 = __importDefault(require("./config"));
49
+ exports.config = config_1.default;
50
+ __exportStar(require("./component"), exports);
@@ -0,0 +1,8 @@
1
+ import { NextFunction, Request, Response } from 'express';
2
+ type MiddlewareParams = {
3
+ roles?: string[];
4
+ permissions?: string[];
5
+ getClient?: Function;
6
+ };
7
+ declare const AuthMiddleware: ({ roles, permissions, getClient }?: MiddlewareParams) => (req: Request, res: Response, next: NextFunction) => Promise<void>;
8
+ export = AuthMiddleware;
@@ -0,0 +1,54 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ const lru_cache_1 = __importDefault(require("lru-cache"));
6
+ const auth_1 = __importDefault(require("../service/auth"));
7
+ const cache = new lru_cache_1.default({ max: 10, maxAge: 60 * 1000 });
8
+ const clients = {};
9
+ const getServiceClient = () => {
10
+ const appId = process.env.BLOCKLET_APP_ID;
11
+ if (!clients[appId]) {
12
+ clients[appId] = new auth_1.default();
13
+ }
14
+ return clients[appId];
15
+ };
16
+ const getPermissionsByRole = async (getClient, role) => {
17
+ if (!role) {
18
+ return [];
19
+ }
20
+ const cached = cache.get(role);
21
+ if (cached) {
22
+ return cached;
23
+ }
24
+ const res = await getClient().getPermissionsByRole(role);
25
+ cache.set(role, res);
26
+ return res;
27
+ };
28
+ const AuthMiddleware = ({ roles, permissions, getClient = getServiceClient } = {}) => {
29
+ if (roles && !Array.isArray(roles)) {
30
+ throw new Error('roles must be array');
31
+ }
32
+ if (permissions && !Array.isArray(permissions)) {
33
+ throw new Error('permissions must be array');
34
+ }
35
+ return async (req, res, next) => {
36
+ if (!req.headers['x-user-did']) {
37
+ res.status(401).json({ code: 'forbidden', error: 'not authorized' });
38
+ return;
39
+ }
40
+ if (roles && !roles.includes(req.headers['x-user-role'])) {
41
+ res.status(403).json({ code: 'forbidden', error: 'no permission' });
42
+ return;
43
+ }
44
+ if (permissions) {
45
+ const { permissions: list } = await getPermissionsByRole(getClient, req.headers['x-user-role']);
46
+ if (!permissions.some((x) => (list || []).some((y) => y.name === x))) {
47
+ res.status(403).json({ code: 'forbidden', error: 'no permission' });
48
+ return;
49
+ }
50
+ }
51
+ next();
52
+ };
53
+ };
54
+ module.exports = AuthMiddleware;
@@ -0,0 +1,7 @@
1
+ import { NextFunction, Request, Response } from 'express';
2
+ declare const verifySig: (req: Request, res: Response, next: NextFunction) => void | Response<any, Record<string, any>>;
3
+ export { verifySig };
4
+ declare const _default: {
5
+ verifySig: (req: Request<import("express-serve-static-core").ParamsDictionary, any, any, import("qs").ParsedQs, Record<string, any>>, res: Response<any, Record<string, any>>, next: NextFunction) => void | Response<any, Record<string, any>>;
6
+ };
7
+ export default _default;
@@ -0,0 +1,32 @@
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.verifySig = void 0;
7
+ const json_stable_stringify_1 = __importDefault(require("json-stable-stringify"));
8
+ const wallet_1 = __importDefault(require("../wallet"));
9
+ const config_1 = require("../config");
10
+ const verifySig = (req, res, next) => {
11
+ try {
12
+ const wallet = (0, wallet_1.default)();
13
+ const sig = req.get('x-component-sig');
14
+ if (!sig) {
15
+ return res.status(400).json({ error: 'Bad Request' });
16
+ }
17
+ const data = typeof req.body === 'undefined' ? {} : req.body;
18
+ const verified = wallet.verify((0, json_stable_stringify_1.default)(data), sig);
19
+ if (!verified) {
20
+ return res.status(401).json({ error: 'verify sig failed' });
21
+ }
22
+ }
23
+ catch (error) {
24
+ config_1.logger.error(error);
25
+ return res.status(401).json({ error: 'verify sig failed' });
26
+ }
27
+ return next();
28
+ };
29
+ exports.verifySig = verifySig;
30
+ exports.default = {
31
+ verifySig,
32
+ };
@@ -0,0 +1,24 @@
1
+ import user from './user';
2
+ import auth from './auth';
3
+ import component from './component';
4
+ export { user };
5
+ export { auth };
6
+ export { component };
7
+ declare const _default: {
8
+ user: () => (req: import("express").Request<import("express-serve-static-core").ParamsDictionary, any, any, import("qs").ParsedQs, Record<string, any>> & {
9
+ user?: {
10
+ did: string;
11
+ role: string;
12
+ fullName: string;
13
+ };
14
+ }, res: import("express").Response<any, Record<string, any>>, next: import("express").NextFunction) => Promise<void>;
15
+ auth: ({ roles, permissions, getClient }?: {
16
+ roles?: string[];
17
+ permissions?: string[];
18
+ getClient?: Function;
19
+ }) => (req: import("express").Request<import("express-serve-static-core").ParamsDictionary, any, any, import("qs").ParsedQs, Record<string, any>>, res: import("express").Response<any, Record<string, any>>, next: import("express").NextFunction) => Promise<void>;
20
+ component: {
21
+ verifySig: (req: import("express").Request<import("express-serve-static-core").ParamsDictionary, any, any, import("qs").ParsedQs, Record<string, any>>, res: import("express").Response<any, Record<string, any>>, next: import("express").NextFunction) => void | import("express").Response<any, Record<string, any>>;
22
+ };
23
+ };
24
+ export default _default;
@@ -0,0 +1,17 @@
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.component = exports.auth = exports.user = void 0;
7
+ const user_1 = __importDefault(require("./user"));
8
+ exports.user = user_1.default;
9
+ const auth_1 = __importDefault(require("./auth"));
10
+ exports.auth = auth_1.default;
11
+ const component_1 = __importDefault(require("./component"));
12
+ exports.component = component_1.default;
13
+ exports.default = {
14
+ user: user_1.default,
15
+ auth: auth_1.default,
16
+ component: component_1.default,
17
+ };
@@ -0,0 +1,10 @@
1
+ import { NextFunction, Request, Response } from 'express';
2
+ type User = {
3
+ did: string;
4
+ role: string | undefined;
5
+ fullName: string;
6
+ };
7
+ declare const userMiddleware: () => (req: Request & {
8
+ user?: User;
9
+ }, res: Response, next: NextFunction) => Promise<void>;
10
+ export = userMiddleware;
@@ -0,0 +1,12 @@
1
+ "use strict";
2
+ const userMiddleware = () => async (req, res, next) => {
3
+ if (req.headers['x-user-did']) {
4
+ req.user = {
5
+ did: req.headers['x-user-did'],
6
+ role: req.headers['x-user-role'],
7
+ fullName: decodeURIComponent(req.headers['x-user-fullname']),
8
+ };
9
+ }
10
+ next();
11
+ };
12
+ module.exports = userMiddleware;
@@ -0,0 +1,9 @@
1
+ declare const encrypt: (message: string) => string;
2
+ declare const decrypt: (message: string) => string;
3
+ export { encrypt };
4
+ export { decrypt };
5
+ declare const _default: {
6
+ encrypt: (message: string) => string;
7
+ decrypt: (message: string) => string;
8
+ };
9
+ export default _default;