@ohos-ports/core 1.0.113-beta.0 → 1.16.33-beta.0
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.
- package/LICENSE +13 -0
- package/README.md +3 -0
- package/lib/api/node.js +176 -0
- package/lib/api/team.js +1889 -0
- package/lib/blocklet/downloader/blocklet-downloader.js +246 -0
- package/lib/blocklet/downloader/bundle-downloader.js +316 -0
- package/lib/blocklet/downloader/constants.js +3 -0
- package/lib/blocklet/downloader/resolve-download.js +187 -0
- package/lib/blocklet/extras.js +177 -0
- package/lib/blocklet/hooks.js +89 -0
- package/lib/blocklet/manager/base.js +49 -0
- package/lib/blocklet/manager/config-synchronizer.js +128 -0
- package/lib/blocklet/manager/disk.js +5170 -0
- package/lib/blocklet/manager/engine.js +124 -0
- package/lib/blocklet/manager/helper/install-application-from-backup.js +285 -0
- package/lib/blocklet/manager/helper/install-application-from-dev.js +72 -0
- package/lib/blocklet/manager/helper/install-application-from-general.js +209 -0
- package/lib/blocklet/manager/helper/install-component-from-dev.js +128 -0
- package/lib/blocklet/manager/helper/install-component-from-upload.js +197 -0
- package/lib/blocklet/manager/helper/install-component-from-url.js +214 -0
- package/lib/blocklet/manager/helper/migrate-application-to-struct-v2.js +557 -0
- package/lib/blocklet/manager/helper/rollback-cache.js +41 -0
- package/lib/blocklet/manager/helper/upgrade-components.js +179 -0
- package/lib/blocklet/manager/pm2-events.js +50 -0
- package/lib/blocklet/migration-dist/migration.cjs +38605 -0
- package/lib/blocklet/migration-dist/run-script.cjs +29 -0
- package/lib/blocklet/migration.js +145 -0
- package/lib/blocklet/project/connect-by-studio.js +91 -0
- package/lib/blocklet/project/connect-to-store.js +64 -0
- package/lib/blocklet/project/create-pack-release.js +293 -0
- package/lib/blocklet/project/disconnect-from-store.js +13 -0
- package/lib/blocklet/project/get-is-multiple-tenant.js +8 -0
- package/lib/blocklet/project/index.js +545 -0
- package/lib/blocklet/project/logo.png +0 -0
- package/lib/blocklet/project/publish-to-store.js +108 -0
- package/lib/blocklet/project/util.js +194 -0
- package/lib/blocklet/security/access-policy.js +131 -0
- package/lib/blocklet/security/index.js +309 -0
- package/lib/blocklet/security/response-header-policy.js +178 -0
- package/lib/blocklet/security/security-rule.js +127 -0
- package/lib/blocklet/security/utils.js +35 -0
- package/lib/blocklet/security/validator.js +40 -0
- package/lib/blocklet/storage/backup/base.js +149 -0
- package/lib/blocklet/storage/backup/blocklet-extras.js +110 -0
- package/lib/blocklet/storage/backup/blocklet.js +159 -0
- package/lib/blocklet/storage/backup/blocklets.js +109 -0
- package/lib/blocklet/storage/backup/data.js +35 -0
- package/lib/blocklet/storage/backup/disk.js +131 -0
- package/lib/blocklet/storage/backup/logs.js +24 -0
- package/lib/blocklet/storage/backup/routing-rule.js +47 -0
- package/lib/blocklet/storage/backup/spaces.js +345 -0
- package/lib/blocklet/storage/restore/base.js +74 -0
- package/lib/blocklet/storage/restore/blocklet-extras.js +89 -0
- package/lib/blocklet/storage/restore/blocklet.js +56 -0
- package/lib/blocklet/storage/restore/blocklets.js +43 -0
- package/lib/blocklet/storage/restore/disk.js +104 -0
- package/lib/blocklet/storage/restore/logs.js +21 -0
- package/lib/blocklet/storage/restore/spaces.js +174 -0
- package/lib/blocklet/storage/utils/disk.js +178 -0
- package/lib/blocklet/storage/utils/hash.js +53 -0
- package/lib/blocklet/storage/utils/zip.js +43 -0
- package/lib/cert.js +221 -0
- package/lib/crons/check-new-version.js +68 -0
- package/lib/crons/monitor-disk-usage.js +46 -0
- package/lib/crons/rotate-pm2-logs/index.js +41 -0
- package/lib/crons/rotate-pm2-logs/script.js +56 -0
- package/lib/event/auto-backup-handler.js +48 -0
- package/lib/event/index.js +520 -0
- package/lib/index.js +768 -364
- package/lib/locales/ar.js +18 -0
- package/lib/locales/de.js +21 -0
- package/lib/locales/en.js +19 -0
- package/lib/locales/es.js +21 -0
- package/lib/locales/fr.js +21 -0
- package/lib/locales/hi.js +18 -0
- package/lib/locales/i18n.db +0 -0
- package/lib/locales/id.js +20 -0
- package/lib/locales/index.js +54 -0
- package/lib/locales/ja.js +19 -0
- package/lib/locales/ko.js +18 -0
- package/lib/locales/pt.js +20 -0
- package/lib/locales/ru.js +21 -0
- package/lib/locales/th.js +18 -0
- package/lib/locales/vi.js +18 -0
- package/lib/locales/zh-tw.js +17 -0
- package/lib/locales/zh.js +17 -0
- package/lib/migrations/1.0.21-update-config.js +34 -0
- package/lib/migrations/1.0.22-max-memory.js +40 -0
- package/lib/migrations/1.0.25.js +36 -0
- package/lib/migrations/1.0.32-update-config.js +30 -0
- package/lib/migrations/1.0.33-blocklets.js +33 -0
- package/lib/migrations/1.0.36-snapshot.js +10 -0
- package/lib/migrations/1.1.10-team.js +26 -0
- package/lib/migrations/1.1.9-snapshot.js +7 -0
- package/lib/migrations/1.16.11-component-status.js +22 -0
- package/lib/migrations/1.16.33-blocklet-security-rule.js +17 -0
- package/lib/migrations/1.16.6-chain-info.js +78 -0
- package/lib/migrations/1.16.8-component-title.js +66 -0
- package/lib/migrations/1.2.11-blocklet-registry.js +10 -0
- package/lib/migrations/1.2.2-blocklet-registry.js +10 -0
- package/lib/migrations/1.3.1-disk-alert-threshold.js +10 -0
- package/lib/migrations/1.4.5-access-key.js +18 -0
- package/lib/migrations/1.5.0-site.js +34 -0
- package/lib/migrations/1.5.15-site.js +184 -0
- package/lib/migrations/1.5.20-registry.js +15 -0
- package/lib/migrations/1.6.17-blocklet-children.js +48 -0
- package/lib/migrations/1.6.21-rename-ip-echo-domain.js +35 -0
- package/lib/migrations/1.6.4-security.js +59 -0
- package/lib/migrations/1.6.5-security.js +60 -0
- package/lib/migrations/1.6.9-update-node-info-and-certificate.js +39 -0
- package/lib/migrations/1.7.1-blocklet-setup.js +18 -0
- package/lib/migrations/1.7.12-blocklet-meta.js +51 -0
- package/lib/migrations/1.7.15-blocklet-bundle-source.js +42 -0
- package/lib/migrations/1.7.20-blocklet-component.js +41 -0
- package/lib/migrations/1.8.33-blocklet-mem-limit.js +20 -0
- package/lib/migrations/README.md +71 -0
- package/lib/migrations/index.js +215 -0
- package/lib/monitor/blocklet-runtime-monitor.js +204 -0
- package/lib/monitor/get-history-list.js +37 -0
- package/lib/monitor/node-monit-sender.js +99 -0
- package/lib/monitor/node-runtime-monitor.js +205 -0
- package/lib/processes/updater.js +186 -0
- package/lib/router/helper.js +1653 -0
- package/lib/router/index.js +341 -0
- package/lib/router/manager.js +806 -0
- package/lib/states/README.md +38 -0
- package/lib/states/access-key.js +124 -0
- package/lib/states/access-policy.js +29 -0
- package/lib/states/audit-log.js +734 -0
- package/lib/states/backup.js +165 -0
- package/lib/states/base.js +25 -0
- package/lib/states/blocklet-extras.js +257 -0
- package/lib/states/blocklet.js +755 -0
- package/lib/states/cache.js +23 -0
- package/lib/states/connect-account.js +8 -0
- package/lib/states/index.js +76 -0
- package/lib/states/job.js +8 -0
- package/lib/states/migration.js +34 -0
- package/lib/states/node.js +324 -0
- package/lib/states/notification.js +81 -0
- package/lib/states/passport.js +8 -0
- package/lib/states/project.js +119 -0
- package/lib/states/release.js +50 -0
- package/lib/states/response-header-policy.js +30 -0
- package/lib/states/routing-snapshot.js +146 -0
- package/lib/states/runtime-insight.js +25 -0
- package/lib/states/security-rule.js +30 -0
- package/lib/states/session.js +53 -0
- package/lib/states/site.js +102 -0
- package/lib/states/tag.js +8 -0
- package/lib/states/traffic-insight.js +25 -0
- package/lib/states/user-session.js +8 -0
- package/lib/states/user.js +717 -0
- package/lib/states/verify-code.js +152 -0
- package/lib/states/webhook.js +66 -0
- package/lib/team/manager.js +508 -0
- package/lib/util/blocklet.js +2182 -0
- package/lib/util/cache.js +63 -0
- package/lib/util/chain.js +29 -0
- package/lib/util/default-node-config.js +46 -0
- package/lib/util/docker/blocklet-custom-dockerfile.js +92 -0
- package/lib/util/docker/check-docker-has-image.js +23 -0
- package/lib/util/docker/check-docker-installed.js +32 -0
- package/lib/util/docker/check-docker-run-history.js +18 -0
- package/lib/util/docker/check-need-run-docker.js +32 -0
- package/lib/util/docker/create-docker-image.js +65 -0
- package/lib/util/docker/debian-dockerfile.js +50 -0
- package/lib/util/docker/docker-container-prune.js +75 -0
- package/lib/util/docker/docker-exec-chown.js +39 -0
- package/lib/util/docker/docker-exec.js +68 -0
- package/lib/util/docker/docker-remove-by-name.js +20 -0
- package/lib/util/docker/get-docker-runtime-info.js +39 -0
- package/lib/util/docker/parse-docker-name.js +10 -0
- package/lib/util/docker/parse-docker-options-from-pm2.js +295 -0
- package/lib/util/docker/shard-network.js +10 -0
- package/lib/util/domain-status.js +118 -0
- package/lib/util/get-accessible-external-node-ip.js +92 -0
- package/lib/util/get-dynamic-components.js +47 -0
- package/lib/util/get-meta-from-url.js +30 -0
- package/lib/util/get-migration-scripts.js +36 -0
- package/lib/util/get-safe-env.js +12 -0
- package/lib/util/index.js +522 -0
- package/lib/util/install-external-dependencies.js +67 -0
- package/lib/util/ip.js +53 -0
- package/lib/util/launcher.js +475 -0
- package/lib/util/log.js +431 -0
- package/lib/util/maintain.js +178 -0
- package/lib/util/promise-debounce.js +29 -0
- package/lib/util/promise-once.js +14 -0
- package/lib/util/promise-spawn.js +93 -0
- package/lib/util/queue.js +44 -0
- package/lib/util/ready.js +89 -0
- package/lib/util/request.js +10 -0
- package/lib/util/requirement.js +61 -0
- package/lib/util/reset-node.js +166 -0
- package/lib/util/rotator.js +194 -0
- package/lib/util/router.js +122 -0
- package/lib/util/rpc.js +78 -0
- package/lib/util/spaces.js +102 -0
- package/lib/util/store.js +184 -0
- package/lib/util/sysinfo.js +46 -0
- package/lib/util/ua.js +54 -0
- package/lib/validators/backup.js +34 -0
- package/lib/validators/blocklet-extra.js +18 -0
- package/lib/validators/node.js +73 -0
- package/lib/validators/permission.js +38 -0
- package/lib/validators/project.js +39 -0
- package/lib/validators/role.js +64 -0
- package/lib/validators/router.js +192 -0
- package/lib/validators/space-gateway.js +33 -0
- package/lib/validators/trusted-factory.js +28 -0
- package/lib/validators/trusted-passport.js +32 -0
- package/lib/validators/user.js +62 -0
- package/lib/validators/util.js +92 -0
- package/lib/validators/webhook.js +42 -0
- package/lib/webhook/index.js +216 -0
- package/lib/webhook/reduce-queue.js +12 -0
- package/lib/webhook/sender/api/index.js +67 -0
- package/lib/webhook/sender/base.js +11 -0
- package/lib/webhook/sender/index.js +44 -0
- package/lib/webhook/sender/slack/index.js +167 -0
- package/lib/webhook/sender/wallet/index.js +62 -0
- package/package.json +107 -34
- package/examples/BatchClient.js +0 -61
- package/examples/compressor/example.js +0 -7
- package/examples/jsonrpcserver/rpcmethod.js +0 -21
- package/examples/jsonrpcserver/rpcrequest.js +0 -20
- package/examples/jsonrpcserver/rpctest.js +0 -6
- package/examples/loader-pipes/test-mc.js +0 -52
- package/examples/loader-pipes/test.js +0 -51
- package/examples/mc-test.js +0 -44
- package/examples/redisdebug.js +0 -80
- package/lib/cache/CFMemcache.js +0 -57
- package/lib/cache/CacheLoader.js +0 -217
- package/lib/cache/Memcache.js +0 -406
- package/lib/class/Class.js +0 -54
- package/lib/client/MemcacheAdapter.js +0 -139
- package/lib/client/Memcached.js +0 -142
- package/lib/client/MemcachedSocket.js +0 -570
- package/lib/client/MySQLPool.js +0 -153
- package/lib/client/PGPool.js +0 -296
- package/lib/client/Redis.js +0 -787
- package/lib/client/S3.js +0 -103
- package/lib/client/S3Client.js +0 -392
- package/lib/client/pg/CursorQueryWorker.js +0 -160
- package/lib/client/rabbitmq/RbmqChannel.js +0 -61
- package/lib/client/rabbitmq/RbmqConfig.js +0 -144
- package/lib/client/rabbitmq/RbmqConnection.js +0 -259
- package/lib/client/rabbitmq/RbmqExchange.js +0 -112
- package/lib/client/rabbitmq/RbmqIncomingMessage.js +0 -53
- package/lib/client/rabbitmq/RbmqMessage.js +0 -120
- package/lib/client/rabbitmq/RbmqOutcomingMessage.js +0 -47
- package/lib/client/rabbitmq/RbmqQueue.js +0 -87
- package/lib/client/rabbitmq/index.js +0 -8
- package/lib/common/Assertions.js +0 -184
- package/lib/common/Merge.js +0 -32
- package/lib/common/Net.js +0 -56
- package/lib/common/Process.js +0 -20
- package/lib/common/Random.js +0 -53
- package/lib/common/Sort.js +0 -19
- package/lib/common/Types.js +0 -163
- package/lib/credentials/CredentialsProvider.js +0 -45
- package/lib/credentials/Manager.js +0 -101
- package/lib/crypto/Crypto.js +0 -66
- package/lib/data/BinaryData.js +0 -363
- package/lib/data/Compressor.js +0 -83
- package/lib/data/FormData.js +0 -144
- package/lib/data/Mime.js +0 -45
- package/lib/event/ErrorEvent.js +0 -71
- package/lib/event/Event.js +0 -20
- package/lib/event/EventDispatcher.js +0 -157
- package/lib/http/ConnectionPool.js +0 -82
- package/lib/http/ExpressServer.js +0 -19
- package/lib/http/Headers.js +0 -165
- package/lib/http/Loader.js +0 -584
- package/lib/http/Message.js +0 -189
- package/lib/http/Request.js +0 -848
- package/lib/http/RequestProcessor.js +0 -150
- package/lib/http/Response.js +0 -850
- package/lib/http/Server.js +0 -267
- package/lib/http/Socket.js +0 -157
- package/lib/http/Url.js +0 -2
- package/lib/jsonrpc/JsonRpcAbstract.js +0 -109
- package/lib/jsonrpc/JsonRpcBatchRequest.js +0 -54
- package/lib/jsonrpc/JsonRpcBatchResponse.js +0 -73
- package/lib/jsonrpc/JsonRpcError.js +0 -191
- package/lib/jsonrpc/JsonRpcMethod.js +0 -67
- package/lib/jsonrpc/JsonRpcRequest.js +0 -224
- package/lib/jsonrpc/JsonRpcRequestProcessor.js +0 -366
- package/lib/jsonrpc/JsonRpcResponse.js +0 -175
- package/lib/jsonrpc/JsonRpcServer.js +0 -81
- package/lib/logger/EmptyLogger.js +0 -15
- package/lib/logger/LoggerFactory.js +0 -20
- package/lib/logger/WildFireLogger.js +0 -267
- package/lib/pattern/Pool.js +0 -187
- package/lib/pattern/decorator/AbstractDecorator.js +0 -49
- package/lib/pattern/decorator/DecoratorChain.js +0 -285
- package/lib/util/DeviceDetector.js +0 -153
- package/lib/yaml/YAML.js +0 -46
- package/patterns.conf +0 -6
- package/tests/cache/CacheLoaderSpec.js +0 -7
- package/tests/class/ClassSpec.js +0 -106
- package/tests/client/MemcachedSocketSpec.js +0 -1228
- package/tests/client/MemcachedSpec.js +0 -77
- package/tests/client/MySQLPoolSpec.js +0 -231
- package/tests/client/PGPoolSpec.js +0 -479
- package/tests/client/RedisSpec.js +0 -471
- package/tests/client/S3ClientSpec.js +0 -26
- package/tests/client/S3Spec.js +0 -129
- package/tests/client/rabbitmq/RbmqConnectionSpec.js +0 -71
- package/tests/common/AssertionsSpec.js +0 -278
- package/tests/common/NetSpec.js +0 -6
- package/tests/common/RandomSpec.js +0 -35
- package/tests/common/TypesSpec.js +0 -7
- package/tests/credentials/CredentialsProviderSpec.js +0 -46
- package/tests/crypto/CryptoSpec.js +0 -33
- package/tests/data/BinaryDataSpec.js +0 -50
- package/tests/data/CompressorSpec.js +0 -7
- package/tests/data/FormDataSpec.js +0 -7
- package/tests/data/MimeSpec.js +0 -7
- package/tests/event/ErrorEventSpec.js +0 -20
- package/tests/event/EventDispatcherSpec.js +0 -319
- package/tests/event/EventSpec.js +0 -17
- package/tests/http/ConnectionPoolSpec.js +0 -7
- package/tests/http/HeadersSpec.js +0 -79
- package/tests/http/LoaderSpec.js +0 -43
- package/tests/http/MessageSpec.js +0 -251
- package/tests/http/RequestProcessorSpec.js +0 -124
- package/tests/http/RequestSpec.js +0 -651
- package/tests/http/ResponseSpec.js +0 -491
- package/tests/http/ServerSpec.js +0 -7
- package/tests/http/SocketSpec.js +0 -7
- package/tests/http/UrlSpec.js +0 -14
- package/tests/jsonrpc/JsonRpcAbstractSpec.js +0 -20
- package/tests/jsonrpc/JsonRpcBatchRequestSpec.js +0 -31
- package/tests/jsonrpc/JsonRpcBatchResponseSpec.js +0 -38
- package/tests/jsonrpc/JsonRpcErrorSpec.js +0 -58
- package/tests/jsonrpc/JsonRpcMethodSpec.js +0 -7
- package/tests/jsonrpc/JsonRpcRequestProcessorSpec.js +0 -271
- package/tests/jsonrpc/JsonRpcRequestSpec.js +0 -70
- package/tests/jsonrpc/JsonRpcResponseSpec.js +0 -63
- package/tests/jsonrpc/JsonRpcServerSpec.js +0 -42
- package/tests/pattern/PoolSpec.js +0 -180
- package/tests/pattern/decorator/AbstractDecoratorSpec.js +0 -7
- package/tests/pattern/decorator/DecoratorChainSpec.js +0 -7
- package/tests/yaml/YAMLSpec.js +0 -132
package/lib/api/team.js
ADDED
|
@@ -0,0 +1,1889 @@
|
|
|
1
|
+
const { EventEmitter } = require('events');
|
|
2
|
+
const axios = require('@abtnode/util/lib/axios');
|
|
3
|
+
const pick = require('lodash/pick');
|
|
4
|
+
const defaults = require('lodash/defaults');
|
|
5
|
+
const isEmpty = require('lodash/isEmpty');
|
|
6
|
+
const cloneDeep = require('lodash/cloneDeep');
|
|
7
|
+
const { joinURL, withoutTrailingSlash } = require('ufo');
|
|
8
|
+
|
|
9
|
+
const logger = require('@abtnode/logger')('@abtnode/core:api:team');
|
|
10
|
+
const {
|
|
11
|
+
ROLES,
|
|
12
|
+
genPermissionName,
|
|
13
|
+
PASSPORT_STATUS,
|
|
14
|
+
WELLKNOWN_SERVICE_PATH_PREFIX,
|
|
15
|
+
MAX_USER_PAGE_SIZE,
|
|
16
|
+
MAIN_CHAIN_ENDPOINT,
|
|
17
|
+
USER_AVATAR_URL_PREFIX,
|
|
18
|
+
SESSION_TTL,
|
|
19
|
+
} = require('@abtnode/constant');
|
|
20
|
+
const { isValid: isValidDid } = require('@arcblock/did');
|
|
21
|
+
const { BlockletEvents, TeamEvents } = require('@blocklet/constant');
|
|
22
|
+
const { sendToUser } = require('@blocklet/sdk/lib/util/send-notification');
|
|
23
|
+
const {
|
|
24
|
+
createPassportVC,
|
|
25
|
+
createPassport,
|
|
26
|
+
upsertToPassports,
|
|
27
|
+
createUserPassport,
|
|
28
|
+
} = require('@abtnode/auth/lib/passport');
|
|
29
|
+
const formatError = require('@abtnode/util/lib/format-error');
|
|
30
|
+
const { getPassportStatusEndpoint } = require('@abtnode/auth/lib/auth');
|
|
31
|
+
const { callFederated, getFederatedMaster, findFederatedSite } = require('@abtnode/auth/lib/util/federated');
|
|
32
|
+
const { hasActiveOwnerPassport } = require('@abtnode/util/lib/passport');
|
|
33
|
+
const getBlockletInfo = require('@blocklet/meta/lib/info');
|
|
34
|
+
const { getUserAvatarUrl, getAppAvatarUrl, extractUserAvatar, getAvatarByUrl } = require('@abtnode/util/lib/user');
|
|
35
|
+
const { getChainClient } = require('@abtnode/util/lib/get-chain-client');
|
|
36
|
+
const { getWalletDid } = require('@blocklet/meta/lib/did-utils');
|
|
37
|
+
const isUrl = require('is-url');
|
|
38
|
+
|
|
39
|
+
const { validateTrustedPassportIssuers } = require('../validators/trusted-passport');
|
|
40
|
+
const { validateTrustedFactories } = require('../validators/trusted-factory');
|
|
41
|
+
const { validateCreateRole, validateUpdateRole } = require('../validators/role');
|
|
42
|
+
const { validateCreatePermission, validateUpdatePermission } = require('../validators/permission');
|
|
43
|
+
|
|
44
|
+
const { getBlocklet } = require('../util/blocklet');
|
|
45
|
+
const StoreUtil = require('../util/store');
|
|
46
|
+
const { profileSchema } = require('../validators/user');
|
|
47
|
+
const { passportDisplaySchema } = require('../validators/util');
|
|
48
|
+
|
|
49
|
+
const sanitizeUrl = (url) => {
|
|
50
|
+
if (!url) {
|
|
51
|
+
throw new Error('Registry URL should not be empty');
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
return url.trim();
|
|
55
|
+
};
|
|
56
|
+
|
|
57
|
+
const validateReservedRole = (role) => {
|
|
58
|
+
if (Object.values(ROLES).includes(role)) {
|
|
59
|
+
throw new Error(`The role ${role} is reserved`);
|
|
60
|
+
}
|
|
61
|
+
return true;
|
|
62
|
+
};
|
|
63
|
+
|
|
64
|
+
const sendPassportVcNotification = ({ userDid, appWallet: wallet, locale, vc, notification }) => {
|
|
65
|
+
try {
|
|
66
|
+
const receiver = userDid;
|
|
67
|
+
const sender = { appDid: wallet.address, appSk: wallet.secretKey };
|
|
68
|
+
const message = { ...notification };
|
|
69
|
+
if (!message.title) {
|
|
70
|
+
message.title = {
|
|
71
|
+
en: 'Receive a Passport',
|
|
72
|
+
zh: '获得通行证',
|
|
73
|
+
}[locale];
|
|
74
|
+
}
|
|
75
|
+
if (!message.body) {
|
|
76
|
+
message.body = {
|
|
77
|
+
en: 'You got a passport',
|
|
78
|
+
zh: '你获得了一张通行证',
|
|
79
|
+
}[locale];
|
|
80
|
+
}
|
|
81
|
+
if (!message.attachments) {
|
|
82
|
+
message.attachments = [
|
|
83
|
+
{
|
|
84
|
+
type: 'vc',
|
|
85
|
+
data: {
|
|
86
|
+
credential: vc,
|
|
87
|
+
tag: vc.credentialSubject.passport.name,
|
|
88
|
+
},
|
|
89
|
+
},
|
|
90
|
+
];
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
sendToUser(receiver, message, sender, process.env.ABT_NODE_SERVICE_PORT).catch((error) => {
|
|
94
|
+
logger.error('Failed send passport vc to wallet', { error });
|
|
95
|
+
});
|
|
96
|
+
} catch (error) {
|
|
97
|
+
logger.error('Failed send passport vc to wallet', { error });
|
|
98
|
+
}
|
|
99
|
+
};
|
|
100
|
+
|
|
101
|
+
const formatTransferData = (data) => ({
|
|
102
|
+
transferId: data.id,
|
|
103
|
+
remark: data.remark || '',
|
|
104
|
+
expireDate: new Date(data.expireDate).toString(),
|
|
105
|
+
appDid: data.appDid,
|
|
106
|
+
status: data.status || '',
|
|
107
|
+
});
|
|
108
|
+
|
|
109
|
+
const validatePassportDisplay = async (role, display) => {
|
|
110
|
+
if (role.extra?.display === 'custom') {
|
|
111
|
+
if (!display) {
|
|
112
|
+
throw new Error(`display is required for custom passport: ${role.name}`);
|
|
113
|
+
}
|
|
114
|
+
const { error, value } = passportDisplaySchema.validate(display);
|
|
115
|
+
if (error) {
|
|
116
|
+
throw new Error(`display invalid for custom passport: ${formatError(error)}`);
|
|
117
|
+
}
|
|
118
|
+
|
|
119
|
+
if (value.type === 'url') {
|
|
120
|
+
try {
|
|
121
|
+
const res = await axios.head(value.content, {
|
|
122
|
+
timeout: 8000,
|
|
123
|
+
maxRedirects: 8,
|
|
124
|
+
validateStatus: null,
|
|
125
|
+
headers: {
|
|
126
|
+
Accept: 'image/avif,image/webp,image/png,image/svg+xml,image/*,*/*;q=0.8',
|
|
127
|
+
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36', // prettier-ignore
|
|
128
|
+
},
|
|
129
|
+
});
|
|
130
|
+
if (res.status >= 400) {
|
|
131
|
+
throw new Error(`Passport display is not accessible: ${res.statusText}`);
|
|
132
|
+
}
|
|
133
|
+
const contentType = res.headers['content-type'];
|
|
134
|
+
if (!contentType?.startsWith('image/')) {
|
|
135
|
+
throw new Error(`Passport display does not return valid image: ${contentType}`);
|
|
136
|
+
}
|
|
137
|
+
} catch (err) {
|
|
138
|
+
throw new Error(`Error validating passport display: ${err.message}`);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
};
|
|
143
|
+
|
|
144
|
+
class TeamAPI extends EventEmitter {
|
|
145
|
+
/**
|
|
146
|
+
*
|
|
147
|
+
* @param {object} states abtnode core StateDB
|
|
148
|
+
*/
|
|
149
|
+
constructor({ teamManager, states, dataDirs }) {
|
|
150
|
+
super();
|
|
151
|
+
|
|
152
|
+
this.notification = states.notification;
|
|
153
|
+
this.node = states.node;
|
|
154
|
+
this.states = states;
|
|
155
|
+
this.memberInviteExpireTime = 1000 * 3600 * 24 * 30; // 30 days
|
|
156
|
+
this.transferOwnerExpireTime = 1000 * 3600; // 1 hour
|
|
157
|
+
this.teamManager = teamManager;
|
|
158
|
+
this.dataDirs = dataDirs;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// Tags
|
|
162
|
+
async createTag({ teamDid, tag }) {
|
|
163
|
+
if (!tag.title) {
|
|
164
|
+
throw new Error('Must specify tag.title to create');
|
|
165
|
+
}
|
|
166
|
+
if (!tag.color || !tag.color.match(/^#[0-9a-f]{6}$/i)) {
|
|
167
|
+
throw new Error('Must specify hex encoded tag.color to create');
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
const state = await this.getTagState(teamDid);
|
|
171
|
+
const doc = await state.insert(pick(tag, ['title', 'color', 'description']));
|
|
172
|
+
logger.info('tags created successfully', { teamDid, tag });
|
|
173
|
+
return doc;
|
|
174
|
+
}
|
|
175
|
+
|
|
176
|
+
async updateTag({ teamDid, tag }) {
|
|
177
|
+
if (!tag.id) {
|
|
178
|
+
throw new Error('Must specify tag.id to update');
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
const state = await this.getTagState(teamDid);
|
|
182
|
+
const result = await state.updateById(tag.id, pick(tag, ['title', 'color', 'description']));
|
|
183
|
+
logger.info('tags updated successfully', { teamDid, tag, result });
|
|
184
|
+
return state.findOne({ id: tag.id });
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
async deleteTag({ teamDid, tag }) {
|
|
188
|
+
if (!tag.id) {
|
|
189
|
+
throw new Error('Must specify tag.id to delete');
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
const state = await this.getTagState(teamDid);
|
|
193
|
+
const doc = await state.remove({ id: tag.id });
|
|
194
|
+
logger.info('tags deleted successfully', { teamDid, tag });
|
|
195
|
+
return doc;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
async getTags({ teamDid, paging }) {
|
|
199
|
+
const state = await this.getTagState(teamDid);
|
|
200
|
+
const result = await state.paginate({}, { createdAt: -1 }, { pageSize: 20, ...paging });
|
|
201
|
+
return { tags: result.list, paging: result.paging };
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
// User && Invitation
|
|
205
|
+
|
|
206
|
+
async loginUser({ teamDid, user, notify = true }) {
|
|
207
|
+
const state = await this.getUserState(teamDid);
|
|
208
|
+
const nodeInfo = await this.node.read();
|
|
209
|
+
|
|
210
|
+
if (user.role === ROLES.OWNER) {
|
|
211
|
+
if (teamDid !== nodeInfo.did) {
|
|
212
|
+
throw new Error('Cannot add user of owner role');
|
|
213
|
+
}
|
|
214
|
+
if (await state.count({ role: ROLES.OWNER })) {
|
|
215
|
+
throw new Error('The owner already exists');
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
const { _action, ...doc } = await state.loginUser(user);
|
|
220
|
+
if (_action === 'update') {
|
|
221
|
+
logger.info('user updated successfully', { teamDid, userDid: user.did });
|
|
222
|
+
this.emit(TeamEvents.userUpdated, { teamDid, user: doc });
|
|
223
|
+
} else if (_action === 'add') {
|
|
224
|
+
if (teamDid === nodeInfo.did && nodeInfo.nodeOwner && user.did !== nodeInfo.nodeOwner.did && notify) {
|
|
225
|
+
await this.notification.create({
|
|
226
|
+
title: 'New member join',
|
|
227
|
+
description: `User with Name (${user.fullName}) and DID (${user.did}) has joined this server`,
|
|
228
|
+
entityType: 'node',
|
|
229
|
+
action: '/team/members',
|
|
230
|
+
entityId: user.did,
|
|
231
|
+
severity: 'success',
|
|
232
|
+
});
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
logger.info('user added successfully', { teamDid, userDid: user.did, userPk: user.pk, userName: user.fullName });
|
|
236
|
+
this.emit(TeamEvents.userAdded, { teamDid, user: doc });
|
|
237
|
+
}
|
|
238
|
+
return doc;
|
|
239
|
+
}
|
|
240
|
+
|
|
241
|
+
async disconnectUserAccount({ teamDid, connectedAccount }) {
|
|
242
|
+
const state = await this.getUserState(teamDid);
|
|
243
|
+
const result = await state.disconnectUserAccount(connectedAccount);
|
|
244
|
+
|
|
245
|
+
logger.info('user disconnect account successfully', {
|
|
246
|
+
teamDid,
|
|
247
|
+
connectedAccountDid: connectedAccount.did,
|
|
248
|
+
connectedAccountPk: connectedAccount.pk,
|
|
249
|
+
connectedAccountProvider: connectedAccount.provider,
|
|
250
|
+
});
|
|
251
|
+
return result;
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
async addUser({ teamDid, user, force = false }) {
|
|
255
|
+
const state = await this.getUserState(teamDid);
|
|
256
|
+
|
|
257
|
+
if (user.role === ROLES.OWNER) {
|
|
258
|
+
const nodeInfo = await this.node.read();
|
|
259
|
+
|
|
260
|
+
if (teamDid !== nodeInfo.did && !force) {
|
|
261
|
+
throw new Error('Cannot add user of owner role');
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
if (await state.count({ role: ROLES.OWNER })) {
|
|
265
|
+
throw new Error('The owner already exists');
|
|
266
|
+
}
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
const doc = await state.addUser(user);
|
|
270
|
+
|
|
271
|
+
logger.info('user added successfully', { teamDid, userDid: user.did, userPk: user.pk, userName: user.fullName });
|
|
272
|
+
|
|
273
|
+
const nodeInfo = await this.node.read();
|
|
274
|
+
if (teamDid === nodeInfo.did && nodeInfo.nodeOwner && user.did !== nodeInfo.nodeOwner.did) {
|
|
275
|
+
await this.notification.create({
|
|
276
|
+
title: 'New member join',
|
|
277
|
+
description: `User with Name (${user.fullName}) and DID (${user.did}) has joined this server`,
|
|
278
|
+
entityType: 'node',
|
|
279
|
+
action: '/team/members',
|
|
280
|
+
entityId: user.did,
|
|
281
|
+
severity: 'success',
|
|
282
|
+
});
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
this.emit(TeamEvents.userAdded, { teamDid, user: doc });
|
|
286
|
+
|
|
287
|
+
return doc;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
async getUsers({ teamDid, query, paging: inputPaging, sort, dids }) {
|
|
291
|
+
const state = await this.getUserState(teamDid);
|
|
292
|
+
const nodeInfo = await this.node.read();
|
|
293
|
+
|
|
294
|
+
// HACK: 如果查询的是 server 的数据库,则不应该查询 userSession 表
|
|
295
|
+
if (teamDid === nodeInfo.did) {
|
|
296
|
+
if (query) {
|
|
297
|
+
delete query.includeUserSessions;
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
if (inputPaging?.pageSize > MAX_USER_PAGE_SIZE) {
|
|
302
|
+
throw new Error(`Length of users should not exceed ${MAX_USER_PAGE_SIZE} per page`);
|
|
303
|
+
}
|
|
304
|
+
|
|
305
|
+
if (dids && dids.length > MAX_USER_PAGE_SIZE) {
|
|
306
|
+
throw new Error(`Length of users should not exceed ${MAX_USER_PAGE_SIZE}`);
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
let list;
|
|
310
|
+
let paging;
|
|
311
|
+
|
|
312
|
+
if (dids) {
|
|
313
|
+
list = await state.getUsersByDids({ query, dids });
|
|
314
|
+
paging = {
|
|
315
|
+
total: list.length,
|
|
316
|
+
pageSize: dids.length,
|
|
317
|
+
pageCount: 1,
|
|
318
|
+
page: 1,
|
|
319
|
+
};
|
|
320
|
+
} else {
|
|
321
|
+
const doc = await state.getUsers({ query, sort, paging: { pageSize: 20, ...inputPaging } });
|
|
322
|
+
list = doc.list;
|
|
323
|
+
paging = doc.paging;
|
|
324
|
+
}
|
|
325
|
+
const now = Date.now();
|
|
326
|
+
let sessionTtl = SESSION_TTL;
|
|
327
|
+
let blocklet;
|
|
328
|
+
if (teamDid !== nodeInfo.did && query?.includeUserSessions) {
|
|
329
|
+
blocklet = await getBlocklet({ did: teamDid, states: this.states, dataDirs: this.dataDirs });
|
|
330
|
+
sessionTtl = blocklet.settings?.session?.ttl || SESSION_TTL;
|
|
331
|
+
}
|
|
332
|
+
|
|
333
|
+
return {
|
|
334
|
+
// FIXME: @zhanghan 这里做字段过滤的目的是?gql 本身已经对字段做了过滤了
|
|
335
|
+
users: list.map(
|
|
336
|
+
(d) => {
|
|
337
|
+
const pickData = pick(d, [
|
|
338
|
+
'did',
|
|
339
|
+
'pk',
|
|
340
|
+
'role',
|
|
341
|
+
'email',
|
|
342
|
+
'phone',
|
|
343
|
+
'fullName',
|
|
344
|
+
'approved',
|
|
345
|
+
'createdAt',
|
|
346
|
+
'updatedAt',
|
|
347
|
+
'passports',
|
|
348
|
+
'firstLoginAt',
|
|
349
|
+
'lastLoginAt',
|
|
350
|
+
'lastLoginIp',
|
|
351
|
+
'remark',
|
|
352
|
+
'avatar',
|
|
353
|
+
'locale',
|
|
354
|
+
'tags',
|
|
355
|
+
'url',
|
|
356
|
+
'inviter',
|
|
357
|
+
'generation',
|
|
358
|
+
'emailVerified',
|
|
359
|
+
'phoneVerified',
|
|
360
|
+
'userSessions',
|
|
361
|
+
// oauth relate fields
|
|
362
|
+
'sourceProvider',
|
|
363
|
+
'sourceAppPid',
|
|
364
|
+
'connectedAccounts',
|
|
365
|
+
]);
|
|
366
|
+
if (teamDid !== nodeInfo.did) {
|
|
367
|
+
if (pickData?.userSessions) {
|
|
368
|
+
pickData.userSessions = pickData.userSessions
|
|
369
|
+
.filter((x) => {
|
|
370
|
+
return x.appPid === blocklet?.appPid;
|
|
371
|
+
})
|
|
372
|
+
.map((x) => {
|
|
373
|
+
const status = now - new Date(x.updatedAt).getTime() > sessionTtl * 1000 ? 'expired' : x.status;
|
|
374
|
+
return { ...x, status };
|
|
375
|
+
});
|
|
376
|
+
}
|
|
377
|
+
}
|
|
378
|
+
return pickData;
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
// eslint-disable-next-line function-paren-newline
|
|
382
|
+
),
|
|
383
|
+
paging,
|
|
384
|
+
};
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
async getUsersCount({ teamDid }) {
|
|
388
|
+
const state = await this.getUserState(teamDid);
|
|
389
|
+
return state.count();
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
async getUsersCountPerRole({ teamDid }) {
|
|
393
|
+
const roles = await this.getRoles({ teamDid });
|
|
394
|
+
const state = await this.getUserState(teamDid);
|
|
395
|
+
const names = ['$all', ...roles.map((x) => x.name), '$none', '$blocked'];
|
|
396
|
+
return Promise.all(
|
|
397
|
+
names.map(async (name) => {
|
|
398
|
+
const count = await state.countByPassport({ name, status: PASSPORT_STATUS.VALID });
|
|
399
|
+
return { key: name, value: count };
|
|
400
|
+
})
|
|
401
|
+
);
|
|
402
|
+
}
|
|
403
|
+
|
|
404
|
+
/**
|
|
405
|
+
* @description
|
|
406
|
+
* @param {{
|
|
407
|
+
* teamDid: string,
|
|
408
|
+
* user: {
|
|
409
|
+
* did: string,
|
|
410
|
+
* },
|
|
411
|
+
* options: Record<string, any>
|
|
412
|
+
* }} { teamDid, user, options = {} }
|
|
413
|
+
* @return {Promise<import('@ohos-ports/models').UserState>}
|
|
414
|
+
* @memberof TeamAPI
|
|
415
|
+
*/
|
|
416
|
+
async getUser({ teamDid, user, options = {} }) {
|
|
417
|
+
const state = await this.getUserState(teamDid);
|
|
418
|
+
return state.getUser(user.did, options);
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
async isEmailUsed({ teamDid, email, verified = false, sourceProvider = '' }) {
|
|
422
|
+
const state = await this.getUserState(teamDid);
|
|
423
|
+
return state.isEmailUsed(email, verified, sourceProvider);
|
|
424
|
+
}
|
|
425
|
+
|
|
426
|
+
async isPhoneUsed({ teamDid, phone, verified = false }) {
|
|
427
|
+
const state = await this.getUserState(teamDid);
|
|
428
|
+
return state.isPhoneUsed(phone, verified);
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
async getUserByDid({ teamDid, userDid }) {
|
|
432
|
+
const state = await this.getUserState(teamDid);
|
|
433
|
+
return state.getUserByDid(userDid);
|
|
434
|
+
}
|
|
435
|
+
|
|
436
|
+
async isUserValid({ teamDid, userDid }) {
|
|
437
|
+
const state = await this.getUserState(teamDid);
|
|
438
|
+
return state.isUserValid(userDid);
|
|
439
|
+
}
|
|
440
|
+
|
|
441
|
+
async isPassportValid({ teamDid, passportId }) {
|
|
442
|
+
const state = await this.getUserState(teamDid);
|
|
443
|
+
return state.isPassportValid(passportId);
|
|
444
|
+
}
|
|
445
|
+
|
|
446
|
+
async isConnectedAccount({ teamDid, did }) {
|
|
447
|
+
const state = await this.getUserState(teamDid);
|
|
448
|
+
return state.isConnectedAccount(did);
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
async getOwner({ teamDid }) {
|
|
452
|
+
const owner = await this.teamManager.getOwner(teamDid);
|
|
453
|
+
|
|
454
|
+
if (!owner) {
|
|
455
|
+
return null;
|
|
456
|
+
}
|
|
457
|
+
|
|
458
|
+
const state = await this.getUserState(teamDid);
|
|
459
|
+
|
|
460
|
+
// NOTICE: 目前 owner 只能为 did-wallet,无需查询 connectedAccount
|
|
461
|
+
const full = await state.getUser(owner.did);
|
|
462
|
+
return full || owner;
|
|
463
|
+
}
|
|
464
|
+
|
|
465
|
+
async updateUser({ teamDid, user }) {
|
|
466
|
+
const state = await this.getUserState(teamDid);
|
|
467
|
+
const exist = await state.getUserByDid(user.did);
|
|
468
|
+
const updated = await state.updateUser(user.did, user);
|
|
469
|
+
logger.info('user updated successfully', { teamDid, userDid: user.did });
|
|
470
|
+
|
|
471
|
+
this.emit(TeamEvents.userUpdated, { teamDid, user: updated });
|
|
472
|
+
const kycChanged =
|
|
473
|
+
(typeof user.emailVerified === 'boolean' && user.emailVerified !== exist.emailVerified) ||
|
|
474
|
+
(typeof user.phoneVerified === 'boolean' && user.phoneVerified !== exist.phoneVerified);
|
|
475
|
+
if (kycChanged) {
|
|
476
|
+
logger.info('user updated with kycChanged', { teamDid, userDid: user.did });
|
|
477
|
+
this.emit(TeamEvents.userPermissionUpdated, { teamDid, user: updated });
|
|
478
|
+
}
|
|
479
|
+
|
|
480
|
+
return updated;
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
updateUserExtra(args) {
|
|
484
|
+
if (args.extra) {
|
|
485
|
+
try {
|
|
486
|
+
args.extra = JSON.parse(args.extra);
|
|
487
|
+
} catch (err) {
|
|
488
|
+
throw new Error('extra should be a valid json string');
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
|
|
492
|
+
return this.updateUser({ teamDid: args.teamDid, user: pick(args, ['did', 'remark', 'extra']) });
|
|
493
|
+
}
|
|
494
|
+
|
|
495
|
+
async updateUserTags({ teamDid, did, tags }) {
|
|
496
|
+
const state = await this.getUserState(teamDid);
|
|
497
|
+
const doc = await state.updateTags(did, tags);
|
|
498
|
+
logger.info('user tags updated successfully', { teamDid, userDid: did, tags });
|
|
499
|
+
this.emit(TeamEvents.userUpdated, { teamDid, user: doc });
|
|
500
|
+
return doc;
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
async removeUser({ teamDid, user }) {
|
|
504
|
+
const { did } = user;
|
|
505
|
+
|
|
506
|
+
if (!did) {
|
|
507
|
+
throw new Error('did does not exist');
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
if (user.role === ROLES.OWNER) {
|
|
511
|
+
throw new Error('Cannot delete owner');
|
|
512
|
+
}
|
|
513
|
+
|
|
514
|
+
const state = await this.getUserState(teamDid);
|
|
515
|
+
await state.remove({ did });
|
|
516
|
+
logger.info('user removed successfully', { teamDid, userDid: did });
|
|
517
|
+
this.emit(TeamEvents.userRemoved, { teamDid, user: { did } });
|
|
518
|
+
|
|
519
|
+
return { did };
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
async updateUserApproval({ teamDid, user }) {
|
|
523
|
+
const state = await this.getUserState(teamDid);
|
|
524
|
+
const doc = await state.getUser(user.did);
|
|
525
|
+
|
|
526
|
+
if (!doc) {
|
|
527
|
+
throw new Error('User does not exist');
|
|
528
|
+
}
|
|
529
|
+
|
|
530
|
+
if (hasActiveOwnerPassport(doc)) {
|
|
531
|
+
throw new Error('Cannot update owner\'s approval'); // prettier-ignore
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
const changeData = pick(user, ['did', 'approved']);
|
|
535
|
+
|
|
536
|
+
const result = await state.updateApproved(changeData);
|
|
537
|
+
|
|
538
|
+
logger.info('user approval updated successfully', { teamDid, userDid: user.did, approved: user.approved });
|
|
539
|
+
|
|
540
|
+
if (changeData?.approved === false) {
|
|
541
|
+
// 需要注销指定 userDid 在当前 member 和 master 中的所有 userSession
|
|
542
|
+
await this.logoutUser({
|
|
543
|
+
teamDid,
|
|
544
|
+
userDid: user.did,
|
|
545
|
+
});
|
|
546
|
+
}
|
|
547
|
+
this.emit(TeamEvents.userUpdated, { teamDid, user: result });
|
|
548
|
+
this.emit(TeamEvents.userPermissionUpdated, { teamDid, user: result });
|
|
549
|
+
|
|
550
|
+
return result;
|
|
551
|
+
}
|
|
552
|
+
|
|
553
|
+
/**
|
|
554
|
+
* @param {object} options
|
|
555
|
+
* @param {string} options.teamDid
|
|
556
|
+
* @param {string} options.userDid
|
|
557
|
+
* @param {string} options.role
|
|
558
|
+
* @param {object} [options.display]
|
|
559
|
+
* @param {string} options.display.type
|
|
560
|
+
* @param {string} options.display.content
|
|
561
|
+
* @param {boolean} [options.notify=true]
|
|
562
|
+
* @param {object} [options.notification]
|
|
563
|
+
*/
|
|
564
|
+
async issuePassportToUser(
|
|
565
|
+
{ teamDid, userDid, role: roleName, display = null, notify = true, notification },
|
|
566
|
+
context = {}
|
|
567
|
+
) {
|
|
568
|
+
try {
|
|
569
|
+
// eslint-disable-next-line no-param-reassign
|
|
570
|
+
notification = JSON.parse(notification);
|
|
571
|
+
} catch {
|
|
572
|
+
logger.error('Failed to parse notification, use notification as undefined', { notification });
|
|
573
|
+
}
|
|
574
|
+
const { locale = 'en' } = context;
|
|
575
|
+
|
|
576
|
+
const userState = await this.getUserState(teamDid);
|
|
577
|
+
// NOTICE: issuePassportToUser 必须传入 wallet did,无需查询 connectedAccount
|
|
578
|
+
const user = await userState.getUser(userDid);
|
|
579
|
+
|
|
580
|
+
if (!user) {
|
|
581
|
+
throw new Error(`user does not exist: ${userDid}`);
|
|
582
|
+
}
|
|
583
|
+
|
|
584
|
+
if (!user.approved) {
|
|
585
|
+
throw new Error(`the user is revoked: ${userDid}`);
|
|
586
|
+
}
|
|
587
|
+
|
|
588
|
+
const rbac = await this.getRBAC(teamDid);
|
|
589
|
+
const role = await rbac.getRole(roleName);
|
|
590
|
+
|
|
591
|
+
if (!role) {
|
|
592
|
+
throw new Error(`passport does not exist: ${roleName}`);
|
|
593
|
+
}
|
|
594
|
+
|
|
595
|
+
await validatePassportDisplay(role, display);
|
|
596
|
+
|
|
597
|
+
// create vc
|
|
598
|
+
const blocklet = await getBlocklet({ did: teamDid, states: this.states, dataDirs: this.dataDirs });
|
|
599
|
+
const nodeInfo = await this.node.read();
|
|
600
|
+
const blockletInfo = getBlockletInfo(blocklet, nodeInfo.sk);
|
|
601
|
+
const { wallet, passportColor, appUrl, name: issuerName } = blockletInfo;
|
|
602
|
+
|
|
603
|
+
const result = await createPassport({ role });
|
|
604
|
+
const vc = createPassportVC({
|
|
605
|
+
issuerName,
|
|
606
|
+
issuerWallet: wallet,
|
|
607
|
+
issuerAvatarUrl: getAppAvatarUrl(appUrl),
|
|
608
|
+
ownerDid: userDid,
|
|
609
|
+
endpoint: getPassportStatusEndpoint({
|
|
610
|
+
baseUrl: joinURL(appUrl, WELLKNOWN_SERVICE_PATH_PREFIX),
|
|
611
|
+
userDid: user.did,
|
|
612
|
+
teamDid,
|
|
613
|
+
}),
|
|
614
|
+
ownerProfile: {
|
|
615
|
+
...user,
|
|
616
|
+
avatar: getUserAvatarUrl(appUrl, user.avatar),
|
|
617
|
+
},
|
|
618
|
+
preferredColor: passportColor,
|
|
619
|
+
passport: result.passport,
|
|
620
|
+
types: result.types,
|
|
621
|
+
purpose: teamDid === nodeInfo.did || isEmpty(result.types) ? 'login' : 'verification',
|
|
622
|
+
display,
|
|
623
|
+
});
|
|
624
|
+
|
|
625
|
+
// write passport to db
|
|
626
|
+
const passport = createUserPassport(vc, { role: role.name, display });
|
|
627
|
+
user.passports = upsertToPassports(user.passports || [], passport);
|
|
628
|
+
await this.updateUser({
|
|
629
|
+
teamDid,
|
|
630
|
+
user: {
|
|
631
|
+
did: user.did,
|
|
632
|
+
pk: user.pk,
|
|
633
|
+
passports: user.passports,
|
|
634
|
+
},
|
|
635
|
+
});
|
|
636
|
+
|
|
637
|
+
// send vc to wallet
|
|
638
|
+
if (notify) {
|
|
639
|
+
sendPassportVcNotification({ userDid, appWallet: wallet, locale, vc, notification });
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
return user;
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
async revokeUserPassport({ teamDid, userDid, passportId } = {}) {
|
|
646
|
+
if (!passportId) {
|
|
647
|
+
throw new Error('Revoked passport should not be empty');
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
const state = await this.getUserState(teamDid);
|
|
651
|
+
|
|
652
|
+
const doc = await state.revokePassportById({ did: userDid, id: passportId });
|
|
653
|
+
|
|
654
|
+
logger.info('user passport revoked successfully', { teamDid, userDid, passportId });
|
|
655
|
+
|
|
656
|
+
this.emit(TeamEvents.userUpdated, { teamDid, user: doc });
|
|
657
|
+
this.emit(TeamEvents.userPermissionUpdated, { teamDid, user: doc });
|
|
658
|
+
|
|
659
|
+
return doc;
|
|
660
|
+
}
|
|
661
|
+
|
|
662
|
+
async enableUserPassport({ teamDid, userDid, passportId } = {}) {
|
|
663
|
+
if (!passportId) {
|
|
664
|
+
throw new Error('Passport should not be empty');
|
|
665
|
+
}
|
|
666
|
+
|
|
667
|
+
const state = await this.getUserState(teamDid);
|
|
668
|
+
|
|
669
|
+
const doc = await state.enablePassportById({ did: userDid, id: passportId });
|
|
670
|
+
|
|
671
|
+
logger.info('user passport enabled successfully', { teamDid, userDid, passportId });
|
|
672
|
+
|
|
673
|
+
this.emit(TeamEvents.userUpdated, { teamDid, user: doc });
|
|
674
|
+
this.emit(TeamEvents.userPermissionUpdated, { teamDid, user: doc });
|
|
675
|
+
|
|
676
|
+
return doc;
|
|
677
|
+
}
|
|
678
|
+
|
|
679
|
+
async removeUserPassport({ passportId, userDid, teamDid }) {
|
|
680
|
+
if (!passportId) {
|
|
681
|
+
throw new Error('Revoked passport should not be empty');
|
|
682
|
+
}
|
|
683
|
+
|
|
684
|
+
const state = await this.getUserState(teamDid);
|
|
685
|
+
|
|
686
|
+
const doc = await state.removePassportById({ id: passportId });
|
|
687
|
+
|
|
688
|
+
logger.info('user passport remove successfully', { teamDid, userDid, passportId });
|
|
689
|
+
|
|
690
|
+
this.emit(TeamEvents.userUpdated, { teamDid, user: doc });
|
|
691
|
+
this.emit(TeamEvents.userPermissionUpdated, { teamDid, user: doc });
|
|
692
|
+
|
|
693
|
+
return doc;
|
|
694
|
+
}
|
|
695
|
+
|
|
696
|
+
async switchProfile({ teamDid, userDid, profile }) {
|
|
697
|
+
const state = await this.getUserState(teamDid);
|
|
698
|
+
// NOTICE: 这个 schema 没有对数据做任何 default 操作,所以没必要用 validate 之后的值
|
|
699
|
+
const { error } = profileSchema.validate({ ...profile, did: userDid });
|
|
700
|
+
if (error) {
|
|
701
|
+
throw new Error(error);
|
|
702
|
+
}
|
|
703
|
+
const oldUser = await state.getUser(userDid);
|
|
704
|
+
if (!oldUser) {
|
|
705
|
+
throw new Error('User is not exist', { userDid, teamDid });
|
|
706
|
+
}
|
|
707
|
+
|
|
708
|
+
const mergeData = { ...profile };
|
|
709
|
+
|
|
710
|
+
if (mergeData.avatar) {
|
|
711
|
+
if (mergeData.avatar.startsWith(USER_AVATAR_URL_PREFIX)) {
|
|
712
|
+
// pass
|
|
713
|
+
} else if (isUrl(mergeData.avatar)) {
|
|
714
|
+
try {
|
|
715
|
+
mergeData.avatar = await getAvatarByUrl(mergeData.avatar);
|
|
716
|
+
const blocklet = await getBlocklet({ did: teamDid, states: this.states, dataDirs: this.dataDirs });
|
|
717
|
+
mergeData.avatar = await extractUserAvatar(mergeData.avatar, { dataDir: blocklet.env.dataDir });
|
|
718
|
+
} catch {
|
|
719
|
+
logger.error('Failed to convert external avatar', { teamDid, userDid, avatar: mergeData.avatar });
|
|
720
|
+
throw new Error('Failed to convert external avatar');
|
|
721
|
+
}
|
|
722
|
+
} else {
|
|
723
|
+
// 仅当 avatar 是 base64 时,对 avatar 进行处理
|
|
724
|
+
const regex = /^data:image\/(\w+);base64,/;
|
|
725
|
+
const match = regex.exec(mergeData.avatar);
|
|
726
|
+
if (match) {
|
|
727
|
+
const blocklet = await getBlocklet({ did: teamDid, states: this.states, dataDirs: this.dataDirs });
|
|
728
|
+
mergeData.avatar = await extractUserAvatar(mergeData.avatar, { dataDir: blocklet.env.dataDir });
|
|
729
|
+
} else {
|
|
730
|
+
logger.error('Profile avatar is invalid', { teamDid, userDid, profile });
|
|
731
|
+
throw new Error('Profile avatar is invalid');
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
}
|
|
735
|
+
const doc = await state.updateUser(userDid, mergeData);
|
|
736
|
+
logger.info('User switch-profile successfully', { teamDid, userDid });
|
|
737
|
+
this.emit(TeamEvents.userUpdated, { teamDid, user: doc });
|
|
738
|
+
this.emit(TeamEvents.userProfileUpdated, { teamDid, user: doc });
|
|
739
|
+
return doc;
|
|
740
|
+
}
|
|
741
|
+
|
|
742
|
+
// Invite member
|
|
743
|
+
|
|
744
|
+
/**
|
|
745
|
+
* @type InvitationSession {
|
|
746
|
+
* type: 'invite';
|
|
747
|
+
* role: string;
|
|
748
|
+
* remark: string;
|
|
749
|
+
* expireDate: number;
|
|
750
|
+
* inviter: {
|
|
751
|
+
* did: string;
|
|
752
|
+
* email?: string;
|
|
753
|
+
* fullName?: string;
|
|
754
|
+
* role?: string;
|
|
755
|
+
* };
|
|
756
|
+
* teamDid: string;
|
|
757
|
+
* status: '' | 'success';
|
|
758
|
+
* receiver: {
|
|
759
|
+
* did: string;
|
|
760
|
+
* };
|
|
761
|
+
* sourceAppPid: string;
|
|
762
|
+
* display: {
|
|
763
|
+
* type: string;
|
|
764
|
+
* tag: string;
|
|
765
|
+
* };
|
|
766
|
+
* }
|
|
767
|
+
* @returns
|
|
768
|
+
*/
|
|
769
|
+
async createMemberInvitation({ teamDid, role: roleName, expireTime, remark, sourceAppPid, display = null }, context) {
|
|
770
|
+
await this.teamManager.checkEnablePassportIssuance(teamDid);
|
|
771
|
+
|
|
772
|
+
if (expireTime && expireTime <= 0) {
|
|
773
|
+
throw new Error('Expire time must be greater than 0');
|
|
774
|
+
}
|
|
775
|
+
if (!roleName) {
|
|
776
|
+
throw new Error('Role cannot be empty');
|
|
777
|
+
}
|
|
778
|
+
|
|
779
|
+
const roles = await this.getRoles({ teamDid });
|
|
780
|
+
const role = roles.find((r) => r.name === roleName);
|
|
781
|
+
if (!role) {
|
|
782
|
+
throw new Error(`Role does not exist: ${roleName}`);
|
|
783
|
+
}
|
|
784
|
+
await validatePassportDisplay(role, display);
|
|
785
|
+
|
|
786
|
+
if (remark && remark.length > 50) {
|
|
787
|
+
throw new Error('Remark length should NOT be more than 50 characters');
|
|
788
|
+
}
|
|
789
|
+
|
|
790
|
+
const { user } = context;
|
|
791
|
+
if (!user || !user.did) {
|
|
792
|
+
throw new Error('Inviter does not exist');
|
|
793
|
+
}
|
|
794
|
+
|
|
795
|
+
const expireDate = Date.now() + (expireTime || this.memberInviteExpireTime);
|
|
796
|
+
const state = await this.getSessionState(teamDid);
|
|
797
|
+
const { id: inviteId } = await state.start({
|
|
798
|
+
type: 'invite',
|
|
799
|
+
role: roleName,
|
|
800
|
+
remark,
|
|
801
|
+
expireDate,
|
|
802
|
+
inviter: user,
|
|
803
|
+
teamDid,
|
|
804
|
+
sourceAppPid,
|
|
805
|
+
display,
|
|
806
|
+
});
|
|
807
|
+
|
|
808
|
+
logger.info('Create invite member', { role: roleName, user, inviteId, display });
|
|
809
|
+
|
|
810
|
+
return {
|
|
811
|
+
inviteId,
|
|
812
|
+
role: roleName,
|
|
813
|
+
remark,
|
|
814
|
+
expireDate: new Date(expireDate).toString(),
|
|
815
|
+
inviter: user,
|
|
816
|
+
teamDid,
|
|
817
|
+
sourceAppPid,
|
|
818
|
+
display,
|
|
819
|
+
};
|
|
820
|
+
}
|
|
821
|
+
|
|
822
|
+
async getInvitation({ teamDid, inviteId }) {
|
|
823
|
+
if (!teamDid || !inviteId) {
|
|
824
|
+
return null;
|
|
825
|
+
}
|
|
826
|
+
|
|
827
|
+
const state = await this.getSessionState(teamDid);
|
|
828
|
+
const invitation = await state.read(inviteId);
|
|
829
|
+
if (!invitation) {
|
|
830
|
+
return null;
|
|
831
|
+
}
|
|
832
|
+
|
|
833
|
+
return {
|
|
834
|
+
// eslint-disable-next-line no-underscore-dangle
|
|
835
|
+
inviteId: invitation.id,
|
|
836
|
+
role: invitation.role,
|
|
837
|
+
remark: invitation.remark,
|
|
838
|
+
expireDate: new Date(invitation.expireDate).toString(),
|
|
839
|
+
inviter: invitation.inviter,
|
|
840
|
+
teamDid: invitation.teamDid,
|
|
841
|
+
status: invitation.status,
|
|
842
|
+
receiver: invitation.receiver,
|
|
843
|
+
sourceAppPid: invitation.sourceAppPid || null,
|
|
844
|
+
display: invitation.display || null,
|
|
845
|
+
};
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
async getInvitations({ teamDid, filter }) {
|
|
849
|
+
const state = await this.getSessionState(teamDid);
|
|
850
|
+
|
|
851
|
+
const invitations = await state.find({ type: 'invite' });
|
|
852
|
+
|
|
853
|
+
return invitations.filter(filter || ((x) => x.status !== 'success')).map((d) => ({
|
|
854
|
+
// eslint-disable-next-line no-underscore-dangle
|
|
855
|
+
inviteId: d.id,
|
|
856
|
+
role: d.role,
|
|
857
|
+
remark: d.remark,
|
|
858
|
+
expireDate: new Date(d.expireDate).toString(),
|
|
859
|
+
inviter: d.inviter,
|
|
860
|
+
teamDid: d.teamDid,
|
|
861
|
+
status: d.status,
|
|
862
|
+
receiver: d.receiver,
|
|
863
|
+
sourceAppPid: d.sourceAppPid || null,
|
|
864
|
+
display: d.display || null,
|
|
865
|
+
}));
|
|
866
|
+
}
|
|
867
|
+
|
|
868
|
+
async deleteInvitation({ teamDid, inviteId }) {
|
|
869
|
+
if (!inviteId) {
|
|
870
|
+
throw new Error('InviteId cannot be empty');
|
|
871
|
+
}
|
|
872
|
+
|
|
873
|
+
const state = await this.getSessionState(teamDid);
|
|
874
|
+
await state.end(inviteId);
|
|
875
|
+
|
|
876
|
+
logger.info('Delete invite session', { inviteId });
|
|
877
|
+
|
|
878
|
+
return true;
|
|
879
|
+
}
|
|
880
|
+
|
|
881
|
+
async checkInvitation({ teamDid, inviteId }) {
|
|
882
|
+
const state = await this.getSessionState(teamDid);
|
|
883
|
+
|
|
884
|
+
const invitation = await state.read(inviteId);
|
|
885
|
+
|
|
886
|
+
if (!invitation) {
|
|
887
|
+
throw new Error(`The invitation does not exist: ${inviteId}`);
|
|
888
|
+
}
|
|
889
|
+
|
|
890
|
+
const { role, expireDate, remark } = invitation;
|
|
891
|
+
|
|
892
|
+
if (Date.now() > expireDate) {
|
|
893
|
+
logger.error('Invite id has expired', { inviteId, expireAt: new Date(expireDate) });
|
|
894
|
+
|
|
895
|
+
throw new Error(`The invitation has expired: ${inviteId}`);
|
|
896
|
+
}
|
|
897
|
+
|
|
898
|
+
const roles = await this.getRoles({ teamDid });
|
|
899
|
+
if (!roles.some((r) => r.name === role)) {
|
|
900
|
+
throw new Error(`Role does not exist: ${role}`);
|
|
901
|
+
}
|
|
902
|
+
|
|
903
|
+
return {
|
|
904
|
+
role,
|
|
905
|
+
remark,
|
|
906
|
+
};
|
|
907
|
+
}
|
|
908
|
+
|
|
909
|
+
async closeInvitation({ teamDid, inviteId, status, receiver, timeout = 30 * 1000 }) {
|
|
910
|
+
const state = await this.getSessionState(teamDid);
|
|
911
|
+
|
|
912
|
+
const invitation = await state.read(inviteId);
|
|
913
|
+
|
|
914
|
+
if (!invitation) {
|
|
915
|
+
throw new Error(`The invitation does not exist: ${inviteId}`);
|
|
916
|
+
}
|
|
917
|
+
|
|
918
|
+
await state.update(inviteId, { status, receiver });
|
|
919
|
+
|
|
920
|
+
setTimeout(async () => {
|
|
921
|
+
try {
|
|
922
|
+
logger.info('Invitation session closed', { inviteId });
|
|
923
|
+
await state.end(inviteId);
|
|
924
|
+
} catch (error) {
|
|
925
|
+
logger.error('close invitation failed', { error });
|
|
926
|
+
}
|
|
927
|
+
}, timeout);
|
|
928
|
+
}
|
|
929
|
+
|
|
930
|
+
// transfer
|
|
931
|
+
|
|
932
|
+
/**
|
|
933
|
+
* this function is only used to create server owner transfer invitation
|
|
934
|
+
*/
|
|
935
|
+
createTransferInvitation({ teamDid, remark }, context = {}) {
|
|
936
|
+
return this.createMemberInvitation(
|
|
937
|
+
{ teamDid, expireTime: this.transferOwnerExpireTime, remark, role: 'owner' },
|
|
938
|
+
context
|
|
939
|
+
);
|
|
940
|
+
}
|
|
941
|
+
|
|
942
|
+
/**
|
|
943
|
+
* this function is only used to create application owner transfer
|
|
944
|
+
*/
|
|
945
|
+
async createTransferAppOwnerSession({ appDid, remark = '' }) {
|
|
946
|
+
const expireTime = this.transferOwnerExpireTime;
|
|
947
|
+
|
|
948
|
+
await this.teamManager.checkEnableTransferAppOwner(appDid);
|
|
949
|
+
|
|
950
|
+
if (remark && remark.length > 50) {
|
|
951
|
+
throw new Error('Remark length should NOT be more than 50 characters');
|
|
952
|
+
}
|
|
953
|
+
|
|
954
|
+
const expireDate = Date.now() + expireTime;
|
|
955
|
+
const state = await this.getSessionState(appDid);
|
|
956
|
+
const { id: transferId } = await state.start({
|
|
957
|
+
type: 'transfer-app-owner',
|
|
958
|
+
remark,
|
|
959
|
+
expireDate,
|
|
960
|
+
appDid,
|
|
961
|
+
});
|
|
962
|
+
|
|
963
|
+
logger.info('createTransferAppOwnerSession', { appDid, transferId });
|
|
964
|
+
|
|
965
|
+
return {
|
|
966
|
+
transferId,
|
|
967
|
+
remark,
|
|
968
|
+
expireDate: new Date(expireDate).toString(),
|
|
969
|
+
appDid,
|
|
970
|
+
status: 'created',
|
|
971
|
+
};
|
|
972
|
+
}
|
|
973
|
+
|
|
974
|
+
async getTransferAppOwnerSession({ appDid, transferId }) {
|
|
975
|
+
if (!appDid || !transferId) {
|
|
976
|
+
return null;
|
|
977
|
+
}
|
|
978
|
+
|
|
979
|
+
const state = await this.getSessionState(appDid);
|
|
980
|
+
|
|
981
|
+
const transfer = await state.read(transferId);
|
|
982
|
+
if (!transfer) {
|
|
983
|
+
return null;
|
|
984
|
+
}
|
|
985
|
+
|
|
986
|
+
return formatTransferData(transfer);
|
|
987
|
+
}
|
|
988
|
+
|
|
989
|
+
async checkTransferAppOwnerSession({ appDid, transferId }) {
|
|
990
|
+
const state = await this.getSessionState(appDid);
|
|
991
|
+
|
|
992
|
+
const transfer = await state.read(transferId);
|
|
993
|
+
|
|
994
|
+
if (!transfer) {
|
|
995
|
+
throw new Error(`The transfer session does not exist: ${transferId}`);
|
|
996
|
+
}
|
|
997
|
+
|
|
998
|
+
const { expireDate } = transfer;
|
|
999
|
+
|
|
1000
|
+
if (Date.now() > expireDate) {
|
|
1001
|
+
logger.error('Transfer session has expired', { transferId, expireAt: new Date(expireDate) });
|
|
1002
|
+
|
|
1003
|
+
throw new Error(`The transfer session has expired: ${transferId}`);
|
|
1004
|
+
}
|
|
1005
|
+
|
|
1006
|
+
return formatTransferData(transfer);
|
|
1007
|
+
}
|
|
1008
|
+
|
|
1009
|
+
async closeTransferAppOwnerSession({ appPid, transferId, status, timeout = 30 * 1000 }) {
|
|
1010
|
+
const state = await this.getSessionState(appPid);
|
|
1011
|
+
|
|
1012
|
+
const session = await state.read(transferId);
|
|
1013
|
+
|
|
1014
|
+
if (!session) {
|
|
1015
|
+
throw new Error(`The transfer app owner session does not exist: ${transferId}`);
|
|
1016
|
+
}
|
|
1017
|
+
|
|
1018
|
+
await state.update(transferId, { status });
|
|
1019
|
+
|
|
1020
|
+
setTimeout(async () => {
|
|
1021
|
+
try {
|
|
1022
|
+
await state.end(transferId);
|
|
1023
|
+
logger.info('Transfer session closed', { transferId });
|
|
1024
|
+
} catch (error) {
|
|
1025
|
+
logger.error('close transfer session failed', { transferId, error });
|
|
1026
|
+
}
|
|
1027
|
+
}, timeout);
|
|
1028
|
+
}
|
|
1029
|
+
|
|
1030
|
+
// Issue Passport
|
|
1031
|
+
|
|
1032
|
+
/**
|
|
1033
|
+
* 为指定用户颁发 passport
|
|
1034
|
+
* @param {string} param.teamDid - 应用的 did
|
|
1035
|
+
* @param {string} param.ownerDid - 指定用户的 did
|
|
1036
|
+
* @param {string} param.name - passport 的 role
|
|
1037
|
+
* @returns {object} passport-info
|
|
1038
|
+
*/
|
|
1039
|
+
async createPassportIssuance({ teamDid, ownerDid, name, display = null }) {
|
|
1040
|
+
if (!name) {
|
|
1041
|
+
throw new Error('Passport cannot be empty');
|
|
1042
|
+
}
|
|
1043
|
+
|
|
1044
|
+
if (!isValidDid(ownerDid)) {
|
|
1045
|
+
throw new Error(`ownerDid is invalid: ${ownerDid}`);
|
|
1046
|
+
}
|
|
1047
|
+
|
|
1048
|
+
await this.teamManager.checkEnablePassportIssuance(teamDid);
|
|
1049
|
+
|
|
1050
|
+
// passport name is same as role
|
|
1051
|
+
const roles = await this.getRoles({ teamDid });
|
|
1052
|
+
const role = roles.find((r) => r.name === name);
|
|
1053
|
+
if (!role) {
|
|
1054
|
+
throw new Error(`Passport does not exist: ${name}`);
|
|
1055
|
+
}
|
|
1056
|
+
if (role.extra?.display === 'custom') {
|
|
1057
|
+
if (!display) {
|
|
1058
|
+
throw new Error(`display is required for custom passport: ${name}`);
|
|
1059
|
+
}
|
|
1060
|
+
const { error } = passportDisplaySchema.validate(display);
|
|
1061
|
+
if (error) {
|
|
1062
|
+
throw new Error(`display invalid for custom passport: ${formatError(error)}`);
|
|
1063
|
+
}
|
|
1064
|
+
}
|
|
1065
|
+
|
|
1066
|
+
await validatePassportDisplay(role, display);
|
|
1067
|
+
|
|
1068
|
+
const expireDate = Date.now() + this.memberInviteExpireTime;
|
|
1069
|
+
|
|
1070
|
+
const state = await this.getSessionState(teamDid);
|
|
1071
|
+
|
|
1072
|
+
// 为指定用户颁发通行证,拿到的 did 是永久 did,无需查询 connectedAccount
|
|
1073
|
+
const currentUser = await this.getUser({ teamDid, user: { did: ownerDid } });
|
|
1074
|
+
const walletDid = getWalletDid(currentUser);
|
|
1075
|
+
const userDid = walletDid || ownerDid;
|
|
1076
|
+
// 这里可能是为一个不存在的用户创建一个 passport,所以需要额外判断一下
|
|
1077
|
+
if (currentUser) {
|
|
1078
|
+
// auth0 账户不需要手动领取
|
|
1079
|
+
if (walletDid !== ownerDid) {
|
|
1080
|
+
const blocklet = await getBlocklet({ did: teamDid, states: this.states, dataDirs: this.dataDirs });
|
|
1081
|
+
const nodeInfo = await this.node.read();
|
|
1082
|
+
const blockletInfo = getBlockletInfo(blocklet, nodeInfo.sk);
|
|
1083
|
+
const { wallet, passportColor, appUrl, name: issuerName } = blockletInfo;
|
|
1084
|
+
const result = await createPassport({ role });
|
|
1085
|
+
const vc = createPassportVC({
|
|
1086
|
+
issuerName,
|
|
1087
|
+
issuerWallet: wallet,
|
|
1088
|
+
issuerAvatarUrl: getAppAvatarUrl(appUrl),
|
|
1089
|
+
ownerDid: userDid,
|
|
1090
|
+
endpoint: getPassportStatusEndpoint({
|
|
1091
|
+
baseUrl: joinURL(appUrl, WELLKNOWN_SERVICE_PATH_PREFIX),
|
|
1092
|
+
userDid: ownerDid,
|
|
1093
|
+
teamDid,
|
|
1094
|
+
}),
|
|
1095
|
+
ownerProfile: {
|
|
1096
|
+
...currentUser,
|
|
1097
|
+
avatar: getUserAvatarUrl(appUrl, currentUser.avatar),
|
|
1098
|
+
},
|
|
1099
|
+
preferredColor: passportColor,
|
|
1100
|
+
display,
|
|
1101
|
+
passport: result.passport,
|
|
1102
|
+
types: result.types,
|
|
1103
|
+
purpose: teamDid === nodeInfo.did || isEmpty(result.types) ? 'login' : 'verification',
|
|
1104
|
+
});
|
|
1105
|
+
|
|
1106
|
+
if (walletDid) {
|
|
1107
|
+
sendPassportVcNotification({ userDid, appWallet: wallet, locale: 'en', vc });
|
|
1108
|
+
}
|
|
1109
|
+
|
|
1110
|
+
// write passport to db
|
|
1111
|
+
const passport = createUserPassport(vc, { role: role.name, display });
|
|
1112
|
+
const passports = upsertToPassports(currentUser.passports || [], passport);
|
|
1113
|
+
await this.updateUser({
|
|
1114
|
+
teamDid,
|
|
1115
|
+
user: {
|
|
1116
|
+
did: currentUser.did,
|
|
1117
|
+
pk: currentUser.pk,
|
|
1118
|
+
passports,
|
|
1119
|
+
},
|
|
1120
|
+
});
|
|
1121
|
+
return undefined;
|
|
1122
|
+
}
|
|
1123
|
+
}
|
|
1124
|
+
const { id } = await state.start({
|
|
1125
|
+
type: 'passport-issuance',
|
|
1126
|
+
key: userDid,
|
|
1127
|
+
expireDate, // session expireDate
|
|
1128
|
+
name: role.name,
|
|
1129
|
+
title: role.title,
|
|
1130
|
+
ownerDid: userDid,
|
|
1131
|
+
teamDid,
|
|
1132
|
+
display,
|
|
1133
|
+
});
|
|
1134
|
+
|
|
1135
|
+
logger.info('Create issuing passport session', { id, passport: name, ownerDid, teamDid });
|
|
1136
|
+
|
|
1137
|
+
return {
|
|
1138
|
+
id,
|
|
1139
|
+
name: role.name,
|
|
1140
|
+
title: role.title,
|
|
1141
|
+
expireDate: new Date(expireDate).toString(),
|
|
1142
|
+
ownerDid: userDid,
|
|
1143
|
+
teamDid,
|
|
1144
|
+
display,
|
|
1145
|
+
};
|
|
1146
|
+
}
|
|
1147
|
+
|
|
1148
|
+
async getPassportIssuances({ teamDid, ownerDid }) {
|
|
1149
|
+
const state = await this.getSessionState(teamDid);
|
|
1150
|
+
|
|
1151
|
+
const query = { type: 'passport-issuance' };
|
|
1152
|
+
|
|
1153
|
+
if (ownerDid) {
|
|
1154
|
+
query.key = ownerDid;
|
|
1155
|
+
}
|
|
1156
|
+
|
|
1157
|
+
const list = await state.find(query);
|
|
1158
|
+
|
|
1159
|
+
return list.map((d) => ({
|
|
1160
|
+
// eslint-disable-next-line no-underscore-dangle
|
|
1161
|
+
id: d.id,
|
|
1162
|
+
name: d.name,
|
|
1163
|
+
title: d.title,
|
|
1164
|
+
expireDate: new Date(d.expireDate).toString(),
|
|
1165
|
+
ownerDid: d.ownerDid,
|
|
1166
|
+
teamDid: d.teamDid,
|
|
1167
|
+
display: d.display,
|
|
1168
|
+
}));
|
|
1169
|
+
}
|
|
1170
|
+
|
|
1171
|
+
async getPassportIssuance({ teamDid, sessionId }) {
|
|
1172
|
+
const state = await this.getSessionState(teamDid);
|
|
1173
|
+
const doc = await state.read(sessionId);
|
|
1174
|
+
// FIXME: @zhanghan 指定被邀请者的邀请需要查询被邀请者的详细信息
|
|
1175
|
+
return doc;
|
|
1176
|
+
}
|
|
1177
|
+
|
|
1178
|
+
async processPassportIssuance({ teamDid, sessionId }) {
|
|
1179
|
+
const state = await this.getSessionState(teamDid);
|
|
1180
|
+
|
|
1181
|
+
const session = await state.read(sessionId);
|
|
1182
|
+
|
|
1183
|
+
if (!session) {
|
|
1184
|
+
throw new Error(`The passport issuance session does not exist: ${sessionId}`);
|
|
1185
|
+
}
|
|
1186
|
+
|
|
1187
|
+
const { name, ownerDid, expireDate } = session;
|
|
1188
|
+
|
|
1189
|
+
if (Date.now() > expireDate) {
|
|
1190
|
+
logger.error('The passport issuance session has expired', { sessionId, expireAt: new Date(expireDate) });
|
|
1191
|
+
throw new Error(`The passport issuance session has expired: ${sessionId}`);
|
|
1192
|
+
}
|
|
1193
|
+
|
|
1194
|
+
const roles = await this.getRoles({ teamDid });
|
|
1195
|
+
if (!roles.find((x) => x.name === name)) {
|
|
1196
|
+
throw new Error(`Passport does not exist: ${name}`);
|
|
1197
|
+
}
|
|
1198
|
+
|
|
1199
|
+
await state.end(sessionId);
|
|
1200
|
+
|
|
1201
|
+
logger.info('The passport issuance session completed successfully', { sessionId, name, ownerDid });
|
|
1202
|
+
|
|
1203
|
+
return {
|
|
1204
|
+
name,
|
|
1205
|
+
ownerDid,
|
|
1206
|
+
};
|
|
1207
|
+
}
|
|
1208
|
+
|
|
1209
|
+
async deletePassportIssuance({ teamDid, sessionId }) {
|
|
1210
|
+
if (!sessionId) {
|
|
1211
|
+
throw new Error('SessionId cannot be empty');
|
|
1212
|
+
}
|
|
1213
|
+
|
|
1214
|
+
const state = await this.getSessionState(teamDid);
|
|
1215
|
+
await state.end(sessionId);
|
|
1216
|
+
|
|
1217
|
+
logger.info('Delete passport issuance session', { sessionId });
|
|
1218
|
+
|
|
1219
|
+
return true;
|
|
1220
|
+
}
|
|
1221
|
+
|
|
1222
|
+
async configTrustedPassports({ teamDid, trustedPassports }) {
|
|
1223
|
+
const value = await validateTrustedPassportIssuers(trustedPassports);
|
|
1224
|
+
await this.teamManager.configTrustedPassports(teamDid, value);
|
|
1225
|
+
if (!this.teamManager.isNodeTeam(teamDid)) {
|
|
1226
|
+
this.emit(BlockletEvents.updated, { meta: { did: teamDid } });
|
|
1227
|
+
}
|
|
1228
|
+
}
|
|
1229
|
+
|
|
1230
|
+
async configTrustedFactories({ teamDid, trustedFactories }) {
|
|
1231
|
+
const value = await validateTrustedFactories(trustedFactories);
|
|
1232
|
+
|
|
1233
|
+
const client = getChainClient(MAIN_CHAIN_ENDPOINT);
|
|
1234
|
+
await Promise.all(
|
|
1235
|
+
value.map(async (x) => {
|
|
1236
|
+
const { state } = await client.getFactoryState({ address: x.factoryAddress });
|
|
1237
|
+
if (!state) {
|
|
1238
|
+
throw new Error(`NFT Collection ${x.factoryAddress} not found on ${MAIN_CHAIN_ENDPOINT}`);
|
|
1239
|
+
}
|
|
1240
|
+
})
|
|
1241
|
+
);
|
|
1242
|
+
|
|
1243
|
+
await this.teamManager.configTrustedFactories(teamDid, value);
|
|
1244
|
+
if (!this.teamManager.isNodeTeam(teamDid)) {
|
|
1245
|
+
this.emit(BlockletEvents.updated, { meta: { did: teamDid } });
|
|
1246
|
+
}
|
|
1247
|
+
}
|
|
1248
|
+
|
|
1249
|
+
async configPassportIssuance({ teamDid, enable }) {
|
|
1250
|
+
await this.teamManager.configPassportIssuance(teamDid, !!enable);
|
|
1251
|
+
|
|
1252
|
+
if (!this.teamManager.isNodeTeam(teamDid)) {
|
|
1253
|
+
this.emit(BlockletEvents.updated, { meta: { did: teamDid } });
|
|
1254
|
+
}
|
|
1255
|
+
}
|
|
1256
|
+
|
|
1257
|
+
// Access Control
|
|
1258
|
+
|
|
1259
|
+
getRoles({ teamDid }) {
|
|
1260
|
+
return this.teamManager.getRoles(teamDid);
|
|
1261
|
+
}
|
|
1262
|
+
|
|
1263
|
+
async getRole({ teamDid, role: { name } = {} }) {
|
|
1264
|
+
if (!name) {
|
|
1265
|
+
throw new Error('role name is invalid');
|
|
1266
|
+
}
|
|
1267
|
+
const rbac = await this.getRBAC(teamDid);
|
|
1268
|
+
const role = await rbac.getRole(name);
|
|
1269
|
+
return role ? pick(role, ['name', 'grants', 'title', 'description', 'extra']) : null;
|
|
1270
|
+
}
|
|
1271
|
+
|
|
1272
|
+
async createRole({ teamDid, name, description, title, childName, permissions = [], extra: raw }) {
|
|
1273
|
+
logger.info('create role', { teamDid, name, description, childName, permissions, raw });
|
|
1274
|
+
const attrs = { name, title, description, childName, permissions };
|
|
1275
|
+
|
|
1276
|
+
if (raw) {
|
|
1277
|
+
try {
|
|
1278
|
+
attrs.extra = JSON.parse(raw);
|
|
1279
|
+
} catch (err) {
|
|
1280
|
+
throw new Error('extra should be a valid json string');
|
|
1281
|
+
}
|
|
1282
|
+
}
|
|
1283
|
+
|
|
1284
|
+
await validateCreateRole(pick(attrs, ['name', 'title', 'description', 'extra']));
|
|
1285
|
+
|
|
1286
|
+
validateReservedRole(name);
|
|
1287
|
+
|
|
1288
|
+
const rbac = await this.getRBAC(teamDid);
|
|
1289
|
+
|
|
1290
|
+
let role;
|
|
1291
|
+
try {
|
|
1292
|
+
role = await rbac.createRole(attrs);
|
|
1293
|
+
return pick(role, ['name', 'title', 'grants', 'description', 'extra']);
|
|
1294
|
+
} catch (err) {
|
|
1295
|
+
if (new RegExp(`Item ${name} already exists`).test(err.message)) {
|
|
1296
|
+
throw new Error(`Id ${name} already exists`);
|
|
1297
|
+
}
|
|
1298
|
+
throw err;
|
|
1299
|
+
}
|
|
1300
|
+
}
|
|
1301
|
+
|
|
1302
|
+
async updateRole({ teamDid, role: { name, title, description, extra: raw } = {} }) {
|
|
1303
|
+
logger.info('update role', { teamDid, name, title, description, raw });
|
|
1304
|
+
|
|
1305
|
+
const attrs = { name, title, description };
|
|
1306
|
+
|
|
1307
|
+
if (raw) {
|
|
1308
|
+
try {
|
|
1309
|
+
attrs.extra = JSON.parse(raw);
|
|
1310
|
+
} catch (err) {
|
|
1311
|
+
throw new Error('extra should be a valid json string');
|
|
1312
|
+
}
|
|
1313
|
+
}
|
|
1314
|
+
|
|
1315
|
+
await validateUpdateRole(attrs);
|
|
1316
|
+
const rbac = await this.getRBAC(teamDid);
|
|
1317
|
+
const state = await rbac.updateRole(attrs);
|
|
1318
|
+
return pick(state, ['name', 'title', 'grants', 'description', 'extra']);
|
|
1319
|
+
}
|
|
1320
|
+
|
|
1321
|
+
async getPermissions({ teamDid }) {
|
|
1322
|
+
const rbac = await this.getRBAC(teamDid);
|
|
1323
|
+
const permissions = await rbac.getPermissions();
|
|
1324
|
+
return permissions.map((d) => {
|
|
1325
|
+
d.isProtected = !!(d.extra && d.extra.isProtected);
|
|
1326
|
+
return pick(d, ['name', 'description', 'isProtected']);
|
|
1327
|
+
});
|
|
1328
|
+
}
|
|
1329
|
+
|
|
1330
|
+
async createPermission({ teamDid, name, description }) {
|
|
1331
|
+
logger.info('create permissions', { teamDid, name });
|
|
1332
|
+
|
|
1333
|
+
await validateCreatePermission({ name, description });
|
|
1334
|
+
|
|
1335
|
+
const rbac = await this.getRBAC(teamDid);
|
|
1336
|
+
const added = await rbac.createPermission({ name, description });
|
|
1337
|
+
|
|
1338
|
+
return pick(added, ['name', 'description']);
|
|
1339
|
+
}
|
|
1340
|
+
|
|
1341
|
+
async updatePermission({ teamDid, permission: { name, description } = {} }) {
|
|
1342
|
+
logger.info('update permission', { teamDid, name, description });
|
|
1343
|
+
|
|
1344
|
+
await validateUpdatePermission({ name, description });
|
|
1345
|
+
|
|
1346
|
+
const rbac = await this.getRBAC(teamDid);
|
|
1347
|
+
const state = await rbac.updatePermission({ name, description });
|
|
1348
|
+
|
|
1349
|
+
return pick(state, ['name', 'description']);
|
|
1350
|
+
}
|
|
1351
|
+
|
|
1352
|
+
async grant({ teamDid, roleName, grantName }) {
|
|
1353
|
+
logger.info('grant', { teamDid, roleName, grantName });
|
|
1354
|
+
|
|
1355
|
+
const rbac = await this.getRBAC(teamDid);
|
|
1356
|
+
await rbac.grant(roleName, grantName);
|
|
1357
|
+
|
|
1358
|
+
return true;
|
|
1359
|
+
}
|
|
1360
|
+
|
|
1361
|
+
async revoke({ teamDid, roleName, grantName }) {
|
|
1362
|
+
logger.info('revoke', { teamDid, roleName, grantName });
|
|
1363
|
+
|
|
1364
|
+
const rbac = await this.getRBAC(teamDid);
|
|
1365
|
+
await rbac.revoke(roleName, grantName);
|
|
1366
|
+
|
|
1367
|
+
return true;
|
|
1368
|
+
}
|
|
1369
|
+
|
|
1370
|
+
async updateGrants({ teamDid, roleName, grantNames }) {
|
|
1371
|
+
logger.info('update grants', { teamDid, roleName, grantNames });
|
|
1372
|
+
|
|
1373
|
+
const rbac = await this.getRBAC(teamDid);
|
|
1374
|
+
const role = await rbac.updateGrants(roleName, grantNames);
|
|
1375
|
+
|
|
1376
|
+
return pick(role, ['name', 'grants', 'title', 'description']);
|
|
1377
|
+
}
|
|
1378
|
+
|
|
1379
|
+
async deleteRole({ teamDid, name }) {
|
|
1380
|
+
logger.info('delete role', { teamDid, name });
|
|
1381
|
+
|
|
1382
|
+
validateReservedRole(name);
|
|
1383
|
+
|
|
1384
|
+
const rbac = await this.getRBAC(teamDid);
|
|
1385
|
+
await rbac.removeRole(name);
|
|
1386
|
+
|
|
1387
|
+
return true;
|
|
1388
|
+
}
|
|
1389
|
+
|
|
1390
|
+
async deletePermission({ teamDid, name }) {
|
|
1391
|
+
logger.info('delete permission', { teamDid, name });
|
|
1392
|
+
|
|
1393
|
+
const rbac = await this.getRBAC(teamDid);
|
|
1394
|
+
|
|
1395
|
+
const permission = await rbac.getPermission(name);
|
|
1396
|
+
if (permission.extra && permission.extra.isProtected) {
|
|
1397
|
+
throw new Error(`The permission ${name} is reserved`);
|
|
1398
|
+
}
|
|
1399
|
+
|
|
1400
|
+
await rbac.removePermission(name);
|
|
1401
|
+
|
|
1402
|
+
return true;
|
|
1403
|
+
}
|
|
1404
|
+
|
|
1405
|
+
async getPermissionsByRole({ teamDid, role }) {
|
|
1406
|
+
const rbac = await this.getRBAC(teamDid);
|
|
1407
|
+
|
|
1408
|
+
const permissions = await rbac.getScope(role.name, true);
|
|
1409
|
+
|
|
1410
|
+
return permissions.map((d) => pick(d, ['name', 'description']));
|
|
1411
|
+
}
|
|
1412
|
+
|
|
1413
|
+
async hasPermission({ teamDid, role, permission }) {
|
|
1414
|
+
const rbac = await this.getRBAC(teamDid);
|
|
1415
|
+
|
|
1416
|
+
const has = await rbac.can(role, ...permission.split('_'));
|
|
1417
|
+
|
|
1418
|
+
return has;
|
|
1419
|
+
}
|
|
1420
|
+
|
|
1421
|
+
async refreshBlockletInterfacePermissions(blockletMeta) {
|
|
1422
|
+
const { did, interfaces } = blockletMeta;
|
|
1423
|
+
|
|
1424
|
+
const rbac = await this.getRBAC(did);
|
|
1425
|
+
|
|
1426
|
+
const oldPermissions = await this.getPermissions({ teamDid: did });
|
|
1427
|
+
|
|
1428
|
+
await Promise.all(
|
|
1429
|
+
(interfaces || []).map(async ({ name, type }) => {
|
|
1430
|
+
const permissionName = genPermissionName(name);
|
|
1431
|
+
if (type === 'web') {
|
|
1432
|
+
if (!oldPermissions.some((x) => x.name === permissionName)) {
|
|
1433
|
+
await rbac.createPermission({
|
|
1434
|
+
name: permissionName,
|
|
1435
|
+
description: `Access resources under the ${name} interface`,
|
|
1436
|
+
extra: {
|
|
1437
|
+
isProtected: true,
|
|
1438
|
+
},
|
|
1439
|
+
});
|
|
1440
|
+
}
|
|
1441
|
+
}
|
|
1442
|
+
})
|
|
1443
|
+
);
|
|
1444
|
+
}
|
|
1445
|
+
|
|
1446
|
+
// eslint-disable-next-line no-unused-vars
|
|
1447
|
+
async addStore({ teamDid, url, scope = '' }, context) {
|
|
1448
|
+
logger.info('add store', { teamDid, url, scope });
|
|
1449
|
+
|
|
1450
|
+
const sanitized = withoutTrailingSlash(await StoreUtil.getStoreUrl(url));
|
|
1451
|
+
const storeList = await this.teamManager.getStoreList(teamDid);
|
|
1452
|
+
const did = context?.user?.did;
|
|
1453
|
+
const exist = storeList.find((x) => {
|
|
1454
|
+
if (x.url !== sanitized) {
|
|
1455
|
+
return false;
|
|
1456
|
+
}
|
|
1457
|
+
if (x.scope && x.scope === did) {
|
|
1458
|
+
return true;
|
|
1459
|
+
}
|
|
1460
|
+
if (!x.scope || x.scope === 'studio') {
|
|
1461
|
+
return true;
|
|
1462
|
+
}
|
|
1463
|
+
return x.scope === scope;
|
|
1464
|
+
});
|
|
1465
|
+
|
|
1466
|
+
if (exist) {
|
|
1467
|
+
throw new Error(`Blocklet Store already exist: ${sanitized}`);
|
|
1468
|
+
}
|
|
1469
|
+
|
|
1470
|
+
const store = await StoreUtil.getStoreMeta(sanitized);
|
|
1471
|
+
|
|
1472
|
+
storeList.push({ ...store, scope, url: sanitized, protected: false });
|
|
1473
|
+
|
|
1474
|
+
return this.teamManager.updateStoreList(teamDid, storeList);
|
|
1475
|
+
}
|
|
1476
|
+
|
|
1477
|
+
// eslint-disable-next-line no-unused-vars
|
|
1478
|
+
async deleteStore({ teamDid, url, projectId, scope }, context) {
|
|
1479
|
+
logger.info('delete registry', { url });
|
|
1480
|
+
const sanitized = sanitizeUrl(url);
|
|
1481
|
+
|
|
1482
|
+
const storeList = await this.teamManager.getStoreList(teamDid);
|
|
1483
|
+
let storeIndex;
|
|
1484
|
+
if (scope) {
|
|
1485
|
+
storeIndex = storeList.findIndex((x) => {
|
|
1486
|
+
if (x.protected) {
|
|
1487
|
+
return false;
|
|
1488
|
+
}
|
|
1489
|
+
return x.url === sanitized && x.scope === scope;
|
|
1490
|
+
});
|
|
1491
|
+
if (storeIndex === -1) {
|
|
1492
|
+
throw new Error(`No permission to delete the Store registry: ${sanitized}`);
|
|
1493
|
+
}
|
|
1494
|
+
} else {
|
|
1495
|
+
storeIndex = storeList.findIndex((x) => x.url === sanitized && !x.scope);
|
|
1496
|
+
if (storeIndex === -1) {
|
|
1497
|
+
throw new Error(`Store registry does not exist: ${sanitized}`);
|
|
1498
|
+
}
|
|
1499
|
+
}
|
|
1500
|
+
|
|
1501
|
+
if (projectId && scope) {
|
|
1502
|
+
const { projectState } = await this.teamManager.getProjectState(teamDid);
|
|
1503
|
+
const store = await StoreUtil.getStoreMeta(sanitized);
|
|
1504
|
+
await projectState.deleteConnectedStore({
|
|
1505
|
+
projectId,
|
|
1506
|
+
storeId: store.id,
|
|
1507
|
+
createdBy: scope === 'studio' ? null : context?.user?.did,
|
|
1508
|
+
});
|
|
1509
|
+
}
|
|
1510
|
+
storeList.splice(storeIndex, 1);
|
|
1511
|
+
return this.teamManager.updateStoreList(teamDid, storeList);
|
|
1512
|
+
}
|
|
1513
|
+
|
|
1514
|
+
createNotification = (payload) => {
|
|
1515
|
+
return this.teamManager.createNotification(payload);
|
|
1516
|
+
};
|
|
1517
|
+
|
|
1518
|
+
async getNotification({ teamDid, ...rest }) {
|
|
1519
|
+
const notificationState = await this.getNotificationState(teamDid);
|
|
1520
|
+
return notificationState.findPaginated({ teamDid, ...rest });
|
|
1521
|
+
}
|
|
1522
|
+
|
|
1523
|
+
async readNotifications({ teamDid, ...rest }) {
|
|
1524
|
+
const notificationState = await this.getNotificationState(teamDid);
|
|
1525
|
+
return notificationState.read({ teamDid, ...rest });
|
|
1526
|
+
}
|
|
1527
|
+
|
|
1528
|
+
async unreadNotifications({ teamDid, ...rest }) {
|
|
1529
|
+
const notificationState = await this.getNotificationState(teamDid);
|
|
1530
|
+
return notificationState.unread({ teamDid, ...rest });
|
|
1531
|
+
}
|
|
1532
|
+
|
|
1533
|
+
// =======
|
|
1534
|
+
// Private
|
|
1535
|
+
// =======
|
|
1536
|
+
|
|
1537
|
+
getRBAC(did) {
|
|
1538
|
+
return this.teamManager.getRBAC(did);
|
|
1539
|
+
}
|
|
1540
|
+
|
|
1541
|
+
getUserState(did) {
|
|
1542
|
+
return this.teamManager.getUserState(did);
|
|
1543
|
+
}
|
|
1544
|
+
|
|
1545
|
+
getVerifyCodeState(did) {
|
|
1546
|
+
return this.teamManager.getVerifyCodeState(did);
|
|
1547
|
+
}
|
|
1548
|
+
|
|
1549
|
+
getUserSessionState(did) {
|
|
1550
|
+
return this.teamManager.getUserSessionState(did);
|
|
1551
|
+
}
|
|
1552
|
+
|
|
1553
|
+
getTagState(did) {
|
|
1554
|
+
return this.teamManager.getTagState(did);
|
|
1555
|
+
}
|
|
1556
|
+
|
|
1557
|
+
getSessionState(did) {
|
|
1558
|
+
return this.teamManager.getSessionState(did);
|
|
1559
|
+
}
|
|
1560
|
+
|
|
1561
|
+
getNotificationState(did) {
|
|
1562
|
+
return this.teamManager.getNotification(did);
|
|
1563
|
+
}
|
|
1564
|
+
|
|
1565
|
+
// =============
|
|
1566
|
+
// Just for test
|
|
1567
|
+
// =============
|
|
1568
|
+
setInviteExpireTime(ms) {
|
|
1569
|
+
this.memberInviteExpireTime = ms;
|
|
1570
|
+
}
|
|
1571
|
+
|
|
1572
|
+
// user-session management
|
|
1573
|
+
async getUserSession({ teamDid, id, userDid, visitorId, appPid }) {
|
|
1574
|
+
const state = await this.getUserSessionState(teamDid);
|
|
1575
|
+
const userState = await this.getUserState(teamDid);
|
|
1576
|
+
|
|
1577
|
+
const where = {
|
|
1578
|
+
status: 'online',
|
|
1579
|
+
};
|
|
1580
|
+
if (id) where.id = id;
|
|
1581
|
+
if (userDid) where.userDid = userDid;
|
|
1582
|
+
if (visitorId) where.visitorId = visitorId;
|
|
1583
|
+
if (appPid) where.appPid = appPid;
|
|
1584
|
+
|
|
1585
|
+
const userSessions = await state.model.findAll({
|
|
1586
|
+
where,
|
|
1587
|
+
attributes: [
|
|
1588
|
+
'id',
|
|
1589
|
+
'appPid',
|
|
1590
|
+
'userDid',
|
|
1591
|
+
'visitorId',
|
|
1592
|
+
'passportId',
|
|
1593
|
+
'createdAt',
|
|
1594
|
+
'updatedAt',
|
|
1595
|
+
'extra',
|
|
1596
|
+
'ua',
|
|
1597
|
+
'lastLoginIp',
|
|
1598
|
+
'status',
|
|
1599
|
+
],
|
|
1600
|
+
include: {
|
|
1601
|
+
model: userState.model,
|
|
1602
|
+
as: 'user',
|
|
1603
|
+
attributes: [
|
|
1604
|
+
'did',
|
|
1605
|
+
'pk',
|
|
1606
|
+
'sourceProvider',
|
|
1607
|
+
'fullName',
|
|
1608
|
+
'email',
|
|
1609
|
+
'avatar',
|
|
1610
|
+
'remark',
|
|
1611
|
+
'sourceAppPid',
|
|
1612
|
+
'approved',
|
|
1613
|
+
],
|
|
1614
|
+
},
|
|
1615
|
+
});
|
|
1616
|
+
return userSessions.map((x) => x.toJSON());
|
|
1617
|
+
}
|
|
1618
|
+
|
|
1619
|
+
async getPassportById({ teamDid, passportId }) {
|
|
1620
|
+
const userState = await this.getUserState(teamDid);
|
|
1621
|
+
const passport = await userState.getPassportById(passportId);
|
|
1622
|
+
return passport;
|
|
1623
|
+
}
|
|
1624
|
+
|
|
1625
|
+
async getPassportFromFederated({ site, passportId, teamDid }) {
|
|
1626
|
+
const blocklet = await getBlocklet({ did: teamDid, states: this.states, dataDirs: this.dataDirs });
|
|
1627
|
+
const nodeInfo = await this.node.read();
|
|
1628
|
+
const { permanentWallet } = getBlockletInfo(blocklet, nodeInfo.sk);
|
|
1629
|
+
|
|
1630
|
+
const result = await callFederated({
|
|
1631
|
+
action: 'getPassport',
|
|
1632
|
+
data: {
|
|
1633
|
+
passportId,
|
|
1634
|
+
},
|
|
1635
|
+
permanentWallet,
|
|
1636
|
+
site,
|
|
1637
|
+
});
|
|
1638
|
+
|
|
1639
|
+
return result;
|
|
1640
|
+
}
|
|
1641
|
+
|
|
1642
|
+
/**
|
|
1643
|
+
* 新增|更新一个 userSession
|
|
1644
|
+
* @param {string} params.teamDid - 当前更新的这个应用的 teamDid
|
|
1645
|
+
* @param {string} params.appPid - 记录的 userSession 中应用的 appPid
|
|
1646
|
+
* @param {string} params.userDid - 记录的 userSession 中当前用户的 did
|
|
1647
|
+
* @param {string} params.visitorId - 记录的 userSession 中当前用户所使用设备的 visitorId
|
|
1648
|
+
* @param {string} params.ua - 记录的 userSession 中当前用户所使用设备的 ua
|
|
1649
|
+
* @param {string} params.lastLoginIp - 记录的 userSession 中当前用户的最后登录 ip
|
|
1650
|
+
* @param {string} params.passportId - 记录的 userSession 中当前用户登录所使用的 passportId
|
|
1651
|
+
* @param {string} params.status - 记录的 userSession 的状态
|
|
1652
|
+
* @param {Object} params.extra - 记录的 userSession 额外的数据
|
|
1653
|
+
* @returns
|
|
1654
|
+
*/
|
|
1655
|
+
|
|
1656
|
+
async upsertUserSession({ teamDid, appPid, userDid, visitorId, ua, lastLoginIp, passportId, status, extra }) {
|
|
1657
|
+
if (!userDid) {
|
|
1658
|
+
throw new Error('userDid is required');
|
|
1659
|
+
}
|
|
1660
|
+
|
|
1661
|
+
const state = await this.getUserSessionState(teamDid);
|
|
1662
|
+
let data;
|
|
1663
|
+
if (!visitorId) {
|
|
1664
|
+
data = await state.insert({
|
|
1665
|
+
userDid,
|
|
1666
|
+
ua,
|
|
1667
|
+
lastLoginIp,
|
|
1668
|
+
appPid,
|
|
1669
|
+
passportId,
|
|
1670
|
+
extra,
|
|
1671
|
+
});
|
|
1672
|
+
logger.info('insert userSession successfully', { userDid, ua, lastLoginIp, appPid, passportId, extra });
|
|
1673
|
+
} else {
|
|
1674
|
+
const exist = await state.findOne({ userDid, visitorId, appPid });
|
|
1675
|
+
if (exist) {
|
|
1676
|
+
const mergeExtra = defaults({}, extra || {}, exist.extra || {});
|
|
1677
|
+
|
|
1678
|
+
[, [data]] = await state.update(exist.id, {
|
|
1679
|
+
ua,
|
|
1680
|
+
lastLoginIp,
|
|
1681
|
+
passportId,
|
|
1682
|
+
status,
|
|
1683
|
+
extra: mergeExtra,
|
|
1684
|
+
});
|
|
1685
|
+
logger.info('update userSession successfully', { id: exist.id, ua, lastLoginIp, passportId, status, extra });
|
|
1686
|
+
} else {
|
|
1687
|
+
data = await state.insert({
|
|
1688
|
+
visitorId,
|
|
1689
|
+
userDid,
|
|
1690
|
+
ua,
|
|
1691
|
+
lastLoginIp,
|
|
1692
|
+
appPid,
|
|
1693
|
+
passportId,
|
|
1694
|
+
extra,
|
|
1695
|
+
});
|
|
1696
|
+
logger.info('insert userSession successfully', {
|
|
1697
|
+
visitorId,
|
|
1698
|
+
userDid,
|
|
1699
|
+
ua,
|
|
1700
|
+
lastLoginIp,
|
|
1701
|
+
appPid,
|
|
1702
|
+
passportId,
|
|
1703
|
+
extra,
|
|
1704
|
+
});
|
|
1705
|
+
}
|
|
1706
|
+
}
|
|
1707
|
+
|
|
1708
|
+
return data;
|
|
1709
|
+
}
|
|
1710
|
+
|
|
1711
|
+
/**
|
|
1712
|
+
* 同步一个 userSession(userSession 只能向 master 同步,或 master 向 member 同步,不能由 member 向 member 同步)
|
|
1713
|
+
* @param {string} params.teamDid - 当前更新的这个应用的 teamDid
|
|
1714
|
+
* @param {string} params.targetAppPid - 同步的 userSession 的目标站点 appPid
|
|
1715
|
+
* @param {string} params.userDid - 同步的 userSession 中当前用户的 did
|
|
1716
|
+
* @param {string} params.visitorId - 同步的 userSession 中当前用户所使用设备的 visitorId
|
|
1717
|
+
* @param {string} params.ua - 同步的 userSession 中当前用户所使用设备的 ua
|
|
1718
|
+
* @param {string} params.lastLoginIp - 同步的 userSession 中当前用户的最后登录 ip
|
|
1719
|
+
* @param {string} params.passportId - 同步的 userSession 中当前用户登录所使用的 passportId
|
|
1720
|
+
* @param {object} params.extra - 同步的 userSession 中当前用户登录额外的数据
|
|
1721
|
+
* @returns
|
|
1722
|
+
*/
|
|
1723
|
+
async syncUserSession({ teamDid, targetAppPid, userDid, visitorId, ua, lastLoginIp, passportId, extra }) {
|
|
1724
|
+
if (!targetAppPid) return;
|
|
1725
|
+
|
|
1726
|
+
const blocklet = await getBlocklet({ did: teamDid, states: this.states, dataDirs: this.dataDirs });
|
|
1727
|
+
const nodeInfo = await this.node.read();
|
|
1728
|
+
const { permanentWallet } = getBlockletInfo(blocklet, nodeInfo.sk);
|
|
1729
|
+
|
|
1730
|
+
const targetSite = findFederatedSite(blocklet, targetAppPid);
|
|
1731
|
+
const masterSite = getFederatedMaster(blocklet);
|
|
1732
|
+
|
|
1733
|
+
let syncSite = null;
|
|
1734
|
+
let appPid;
|
|
1735
|
+
if (masterSite && targetSite) {
|
|
1736
|
+
if (targetSite.appPid === masterSite.appPid) {
|
|
1737
|
+
if (teamDid !== masterSite.appPid) {
|
|
1738
|
+
syncSite = masterSite;
|
|
1739
|
+
appPid = teamDid;
|
|
1740
|
+
}
|
|
1741
|
+
} else if (teamDid === masterSite.appPid) {
|
|
1742
|
+
syncSite = targetSite;
|
|
1743
|
+
appPid = targetAppPid;
|
|
1744
|
+
}
|
|
1745
|
+
|
|
1746
|
+
if (syncSite) {
|
|
1747
|
+
try {
|
|
1748
|
+
const userSession = {
|
|
1749
|
+
action: 'login',
|
|
1750
|
+
userDid,
|
|
1751
|
+
visitorId,
|
|
1752
|
+
ua,
|
|
1753
|
+
lastLoginIp,
|
|
1754
|
+
appPid,
|
|
1755
|
+
passportId,
|
|
1756
|
+
extra,
|
|
1757
|
+
};
|
|
1758
|
+
await callFederated({
|
|
1759
|
+
action: 'sync',
|
|
1760
|
+
permanentWallet,
|
|
1761
|
+
site: targetSite,
|
|
1762
|
+
data: {
|
|
1763
|
+
userSessions: [userSession],
|
|
1764
|
+
},
|
|
1765
|
+
});
|
|
1766
|
+
logger.debug('Sync userSession to federated site successfully', {
|
|
1767
|
+
userDid,
|
|
1768
|
+
visitorId,
|
|
1769
|
+
ua,
|
|
1770
|
+
lastLoginIp,
|
|
1771
|
+
appPid,
|
|
1772
|
+
passportId,
|
|
1773
|
+
targetSite,
|
|
1774
|
+
extra,
|
|
1775
|
+
});
|
|
1776
|
+
} catch (err) {
|
|
1777
|
+
logger.error(
|
|
1778
|
+
'Sync userSession to federated site failed',
|
|
1779
|
+
{
|
|
1780
|
+
userDid,
|
|
1781
|
+
visitorId,
|
|
1782
|
+
ua,
|
|
1783
|
+
lastLoginIp,
|
|
1784
|
+
appPid,
|
|
1785
|
+
passportId,
|
|
1786
|
+
targetSite,
|
|
1787
|
+
extra,
|
|
1788
|
+
},
|
|
1789
|
+
err
|
|
1790
|
+
);
|
|
1791
|
+
}
|
|
1792
|
+
}
|
|
1793
|
+
}
|
|
1794
|
+
}
|
|
1795
|
+
|
|
1796
|
+
async logoutUser({ teamDid, userDid, visitorId, appPid }) {
|
|
1797
|
+
if (!userDid) {
|
|
1798
|
+
throw new Error('userDid is required');
|
|
1799
|
+
}
|
|
1800
|
+
if (!teamDid) {
|
|
1801
|
+
throw new Error('teamDid is required');
|
|
1802
|
+
}
|
|
1803
|
+
|
|
1804
|
+
const nodeInfo = await this.node.read();
|
|
1805
|
+
if (nodeInfo.did === teamDid) {
|
|
1806
|
+
return 0;
|
|
1807
|
+
}
|
|
1808
|
+
const state = await this.getUserSessionState(teamDid);
|
|
1809
|
+
const userSessionParams = { userDid };
|
|
1810
|
+
if (visitorId) {
|
|
1811
|
+
userSessionParams.visitorId = visitorId;
|
|
1812
|
+
}
|
|
1813
|
+
if (appPid) {
|
|
1814
|
+
userSessionParams.appPid = appPid;
|
|
1815
|
+
}
|
|
1816
|
+
const result = await state.remove(userSessionParams);
|
|
1817
|
+
const blocklet = await getBlocklet({ did: teamDid, states: this.states, dataDirs: this.dataDirs });
|
|
1818
|
+
const { permanentWallet } = getBlockletInfo(blocklet, nodeInfo.sk);
|
|
1819
|
+
const federated = defaults(cloneDeep(blocklet.settings.federated || {}), {
|
|
1820
|
+
config: {},
|
|
1821
|
+
sites: [],
|
|
1822
|
+
});
|
|
1823
|
+
const masterSite = federated.sites[0];
|
|
1824
|
+
if (masterSite && masterSite.isMaster !== false && masterSite.appPid !== teamDid) {
|
|
1825
|
+
callFederated({
|
|
1826
|
+
action: 'sync',
|
|
1827
|
+
permanentWallet,
|
|
1828
|
+
// FIXME: @zhanghan 是否还需要通知其他 Member 站点,执行退出登录的操作
|
|
1829
|
+
site: masterSite,
|
|
1830
|
+
data: {
|
|
1831
|
+
userSessions: [
|
|
1832
|
+
{
|
|
1833
|
+
action: 'logout',
|
|
1834
|
+
userDid,
|
|
1835
|
+
visitorId,
|
|
1836
|
+
// HACK: 如果未传入 appPid,代表要注销当前用户在 master 中所有登录状态,所以传入 undefined;否则就只注销 master 中记录的当前 member 的登录状态
|
|
1837
|
+
appPid: appPid ? teamDid : undefined,
|
|
1838
|
+
},
|
|
1839
|
+
],
|
|
1840
|
+
},
|
|
1841
|
+
});
|
|
1842
|
+
}
|
|
1843
|
+
return result;
|
|
1844
|
+
}
|
|
1845
|
+
|
|
1846
|
+
// KYC related
|
|
1847
|
+
async createVerifyCode({ teamDid, subject, scope = 'email' }) {
|
|
1848
|
+
const state = await this.getVerifyCodeState(teamDid);
|
|
1849
|
+
return state.create(subject, scope);
|
|
1850
|
+
}
|
|
1851
|
+
|
|
1852
|
+
async consumeVerifyCode({ teamDid, code }) {
|
|
1853
|
+
const state = await this.getVerifyCodeState(teamDid);
|
|
1854
|
+
return state.verify(code);
|
|
1855
|
+
}
|
|
1856
|
+
|
|
1857
|
+
async issueVerifyCode({ teamDid, code }) {
|
|
1858
|
+
const state = await this.getVerifyCodeState(teamDid);
|
|
1859
|
+
return state.issue(code);
|
|
1860
|
+
}
|
|
1861
|
+
|
|
1862
|
+
async sendVerifyCode({ teamDid, code }) {
|
|
1863
|
+
const state = await this.getVerifyCodeState(teamDid);
|
|
1864
|
+
return state.send(code);
|
|
1865
|
+
}
|
|
1866
|
+
|
|
1867
|
+
async isSubjectVerified({ teamDid, subject }) {
|
|
1868
|
+
const state = await this.getVerifyCodeState(teamDid);
|
|
1869
|
+
return state.isVerified(subject);
|
|
1870
|
+
}
|
|
1871
|
+
|
|
1872
|
+
async isSubjectIssued({ teamDid, userDid, subject }) {
|
|
1873
|
+
const state = await this.getUserState(teamDid);
|
|
1874
|
+
return state.isSubjectIssued(userDid, subject);
|
|
1875
|
+
}
|
|
1876
|
+
|
|
1877
|
+
async isSubjectSent({ teamDid, subject }) {
|
|
1878
|
+
const state = await this.getVerifyCodeState(teamDid);
|
|
1879
|
+
return state.isSent(subject);
|
|
1880
|
+
}
|
|
1881
|
+
|
|
1882
|
+
async getVerifyCode({ teamDid, code }) {
|
|
1883
|
+
const state = await this.getVerifyCodeState(teamDid);
|
|
1884
|
+
return state.findOne({ code });
|
|
1885
|
+
}
|
|
1886
|
+
}
|
|
1887
|
+
|
|
1888
|
+
module.exports = TeamAPI;
|
|
1889
|
+
module.exports.validatePassportDisplay = validatePassportDisplay;
|