@arcblock/did-connect-js 1.21.2
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 +211 -0
- package/lib/authenticator/base.js +98 -0
- package/lib/authenticator/wallet.js +768 -0
- package/lib/handlers/base.js +49 -0
- package/lib/handlers/util.js +943 -0
- package/lib/handlers/wallet.js +168 -0
- package/lib/index.d.ts +384 -0
- package/lib/index.js +7 -0
- package/lib/protocol.js +46 -0
- package/lib/schema/claims.js +256 -0
- package/lib/schema/index.js +56 -0
- package/package.json +86 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
Copyright 2018-2025 ArcBlock
|
|
2
|
+
|
|
3
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
4
|
+
you may not use this file except in compliance with the License.
|
|
5
|
+
You may obtain a copy of the License at
|
|
6
|
+
|
|
7
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
8
|
+
|
|
9
|
+
Unless required by applicable law or agreed to in writing, software
|
|
10
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
11
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
12
|
+
See the License for the specific language governing permissions and
|
|
13
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,211 @@
|
|
|
1
|
+

|
|
2
|
+
|
|
3
|
+
[](https://github.com/prettier/prettier)
|
|
4
|
+
[](https://docs.arcblock.io)
|
|
5
|
+
[](https://gitter.im/ArcBlock/community?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)
|
|
6
|
+
|
|
7
|
+
## Overview
|
|
8
|
+
|
|
9
|
+
This library is implemented according to [ABT-DID-Protocol](https://github.com/ArcBlock/abt-did-spec), aiming to make it easier for developers to handle customized DID Connect Sessions in Node.js applications, and should always be used together with [DID Connect UX package](https://www.npmjs.com/package/@arcblock/did-connect), if you are composing a blocklet, you may find the wrapped implementation in [Blocklet SDK](https://www.npmjs.com/package/@blocklet/sdk) more useful.
|
|
10
|
+
|
|
11
|
+
Within a typical DID Connect Session, the application may request user to sign a transaction or provide some information, such as:
|
|
12
|
+
|
|
13
|
+
- Provide a user profile, which may contain name, email
|
|
14
|
+
- Prove ownership of a NFT
|
|
15
|
+
- Prove ownership of a passport
|
|
16
|
+
|
|
17
|
+
The following diagram demonstrates how a typical DID Connect Session works:
|
|
18
|
+
|
|
19
|
+

|
|
20
|
+
|
|
21
|
+
`Claim` is the key concept in DID Connect Session, its used by the application to send specification of required info to finish the session. A claim is identified by `type`, and defined with a set of properties. Checkout the claim section for more information.
|
|
22
|
+
|
|
23
|
+
## Install
|
|
24
|
+
|
|
25
|
+
```sh
|
|
26
|
+
npm install @arcblock/did-connect-js
|
|
27
|
+
// or
|
|
28
|
+
pnpm install @arcblock/did-connect-js
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
## Usage
|
|
32
|
+
|
|
33
|
+
### Basic Usage
|
|
34
|
+
|
|
35
|
+
```js
|
|
36
|
+
const SimpleStorage = require('@arcblock/did-connect-storage-nedb');
|
|
37
|
+
const { fromRandom } = require('@ocap/wallet');
|
|
38
|
+
const { WalletAuthenticator, WalletHandlers } = require('@arcblock/did-connect-js');
|
|
39
|
+
|
|
40
|
+
// First setup authenticator and handler factory
|
|
41
|
+
const wallet = fromRandom();
|
|
42
|
+
const authenticator = new WalletAuthenticator({
|
|
43
|
+
wallet,
|
|
44
|
+
baseUrl: 'http://wangshijun.natapp1.cc',
|
|
45
|
+
appInfo: {
|
|
46
|
+
description: 'Starter projects to develop web application on forge',
|
|
47
|
+
icon: '/images/logo@2x.png',
|
|
48
|
+
name: 'Forge Web Starter',
|
|
49
|
+
},
|
|
50
|
+
chainInfo: {
|
|
51
|
+
host: 'http://did-workshop.arcblock.co:8210/api',
|
|
52
|
+
id: 'forge',
|
|
53
|
+
},
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
const handlers = new WalletHandlers({
|
|
57
|
+
authenticator,
|
|
58
|
+
tokenStorage: new SimpleStorage({ dbPath: '/tmp/test/auth.db' }),
|
|
59
|
+
});
|
|
60
|
+
|
|
61
|
+
// Then attach handler to express server
|
|
62
|
+
const express = require('express');
|
|
63
|
+
const app = express();
|
|
64
|
+
|
|
65
|
+
// This is required if you want to use dynamic baseUrl inference
|
|
66
|
+
app.set('trust proxy', true);
|
|
67
|
+
|
|
68
|
+
handlers.attach({
|
|
69
|
+
action: 'profile',
|
|
70
|
+
claims: {
|
|
71
|
+
// This function can be async or returns a promise
|
|
72
|
+
profile: () => ({
|
|
73
|
+
fields: ['fullName', 'email'],
|
|
74
|
+
description: 'Please provide your name and email to continue',
|
|
75
|
+
}),
|
|
76
|
+
},
|
|
77
|
+
|
|
78
|
+
onAuth: async ({ userDid, claims, extraParams }) => {
|
|
79
|
+
// `userDid` is the current connected did
|
|
80
|
+
// `claims` contains what the user has submitted
|
|
81
|
+
// `extraParams` is set from webapp when creating the session
|
|
82
|
+
try {
|
|
83
|
+
const profile = claims.find((x) => x.type === 'profile');
|
|
84
|
+
console.info('login.success', { userDid, profile });
|
|
85
|
+
} catch (err) {
|
|
86
|
+
console.error('login.error', err);
|
|
87
|
+
}
|
|
88
|
+
},
|
|
89
|
+
});
|
|
90
|
+
```
|
|
91
|
+
|
|
92
|
+
Then your application backend is ready to handle DID Connect Session that request and accept profile from user. For frontend integration please checkout [DID Connect UX](https://www.npmjs.com/package/@arcblock/did-connect).
|
|
93
|
+
|
|
94
|
+
### Multiple Claims
|
|
95
|
+
|
|
96
|
+
You can request multiple claims in a single DID Connect Session:
|
|
97
|
+
|
|
98
|
+
```js
|
|
99
|
+
handlers.attach({
|
|
100
|
+
action: 'multiple-claims',
|
|
101
|
+
claims: {
|
|
102
|
+
profile: () => ({
|
|
103
|
+
fields: ['fullName', 'email'],
|
|
104
|
+
description: 'Please provide your name and email to continue',
|
|
105
|
+
}),
|
|
106
|
+
asset: ({ userDid, extraParams }) => {
|
|
107
|
+
// `userDid` is the current connected did
|
|
108
|
+
// `extraParams` is set from webapp when creating the session
|
|
109
|
+
return {
|
|
110
|
+
description: 'Please provide a valid NFT',
|
|
111
|
+
trustedIssuers: ['nft-issuer-did'],
|
|
112
|
+
};
|
|
113
|
+
},
|
|
114
|
+
},
|
|
115
|
+
onAuth: async ({ claims, userDid }) => {
|
|
116
|
+
// `claims` contains both the profile and the asset claim
|
|
117
|
+
},
|
|
118
|
+
});
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
If you want to provide multiple claims of the same type:
|
|
122
|
+
|
|
123
|
+
```js
|
|
124
|
+
handlers.attach({
|
|
125
|
+
action: 'multiple-claims',
|
|
126
|
+
claims: {
|
|
127
|
+
signText: [
|
|
128
|
+
'signature',
|
|
129
|
+
{
|
|
130
|
+
type: 'mime:text/plain',
|
|
131
|
+
data: 'xxxx',
|
|
132
|
+
description: 'sign the text to continue',
|
|
133
|
+
},
|
|
134
|
+
],
|
|
135
|
+
signHtml: [
|
|
136
|
+
'signature',
|
|
137
|
+
{
|
|
138
|
+
type: 'mime:text/html',
|
|
139
|
+
data: `<h2>This is title</h2>`,
|
|
140
|
+
description: 'sign the html to continue',
|
|
141
|
+
},
|
|
142
|
+
],
|
|
143
|
+
},
|
|
144
|
+
onAuth: async ({ claims, userDid }) => {
|
|
145
|
+
// `claims` contains both the profile and the asset claim
|
|
146
|
+
},
|
|
147
|
+
});
|
|
148
|
+
```
|
|
149
|
+
|
|
150
|
+
### Dynamic Claims
|
|
151
|
+
|
|
152
|
+
By returning a claims object from `onConnect` callback, you can provide dynamic claims for the DID Connect Session.
|
|
153
|
+
|
|
154
|
+
```js
|
|
155
|
+
handlers.attach({
|
|
156
|
+
action: 'dynamic-claims',
|
|
157
|
+
|
|
158
|
+
// Can be async or returns a promise
|
|
159
|
+
onConnect: ({ userDid }) => {
|
|
160
|
+
// check userDid for some business logic
|
|
161
|
+
// then return the claim object
|
|
162
|
+
// you can return multiple claims here
|
|
163
|
+
return {
|
|
164
|
+
profile: () => ({
|
|
165
|
+
fields: ['fullName', 'email'],
|
|
166
|
+
description: 'Please provide your name and email to continue',
|
|
167
|
+
}),
|
|
168
|
+
};
|
|
169
|
+
},
|
|
170
|
+
|
|
171
|
+
onAuth: async ({ claims, userDid }) => {
|
|
172
|
+
// `claims` now contains the result for the dynamic claim
|
|
173
|
+
},
|
|
174
|
+
});
|
|
175
|
+
```
|
|
176
|
+
|
|
177
|
+
## Lifecycle Callbacks
|
|
178
|
+
|
|
179
|
+
Following callbacks are supported during the lifecycle of a DID-Connect session.
|
|
180
|
+
|
|
181
|
+
- `onStart({ req, challenge, didwallet, extraParams, updateSession })`: optional, called when a new session starts, can be async, return values from this callback will be returned to and available from browser, error thrown from `onStart` will halt the session.
|
|
182
|
+
- `onConnect({ req, challenge, userDid, userPk, extraParams, updateSession })`: optional, when wallet has selected `userDid` and `userPk`, you can return dynamic claims here, or do some permission check, error thrown from `onConnect` will halt the session.
|
|
183
|
+
- `onDecline({ req, challenge, userDid, userPk, extraParams, updateSession })`: optional, when wallet has rejected dapp request.
|
|
184
|
+
- `onAuth({ req, challenge, claims, userDid, userPk, extraParams, updateSession })`: required, when wallet has approved dapp request, and submitted info will be available in claims, which is a list of the dapp requested info.
|
|
185
|
+
- `onComplete({ req, userDid, userPk, extraParams, updateSession })`: optional, when the did connect session has completed.
|
|
186
|
+
- `onExpire({ extraParams })`: optional, when the did connect session has expired.
|
|
187
|
+
- `onError({ err, extraParams })`: optional, when the did connect session encountered some error, default to `console.error`.
|
|
188
|
+
|
|
189
|
+
Most commonly used callbacks are `onConnect` and `onAuth`.
|
|
190
|
+
|
|
191
|
+
Developer should always attach an `onAuth` callback for a DID Connect session handler. And put the business logic once user has approved and submitted the requested info in the callback.
|
|
192
|
+
|
|
193
|
+
Sometimes, developer may want to pass some information to the session storage, such as a transaction hash or login token, so that the browser can fetch for later use, developer can achieve this by call `updateSession` from `onAuth`. eg,
|
|
194
|
+
|
|
195
|
+
```js
|
|
196
|
+
handlers.attach({
|
|
197
|
+
action: 'dynamic-claims',
|
|
198
|
+
|
|
199
|
+
onAuth: ({ userDid, updateSession }) => {
|
|
200
|
+
// to persist plain non-sensible info
|
|
201
|
+
await updateSession({ key: 'non-sensible' });
|
|
202
|
+
|
|
203
|
+
// to persist sensible info: that need to be encrypted
|
|
204
|
+
await updateSession({ key: 'sensible' }, true);
|
|
205
|
+
},
|
|
206
|
+
});
|
|
207
|
+
```
|
|
208
|
+
|
|
209
|
+
## Claims
|
|
210
|
+
|
|
211
|
+
A `claim` specifies what kind of information the application can request user to provide. specifications for each claim are defined [here](./lib/schema/claims.js), complete claim request and response specification can be found in the [ABT DID Protocol](https://github.com/ArcBlock/ABT-DID-Protocol).
|
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
/* eslint-disable no-promise-executor-return */
|
|
2
|
+
const Jwt = require('@arcblock/jwt');
|
|
3
|
+
const { isValid } = require('@ocap/wallet');
|
|
4
|
+
|
|
5
|
+
// eslint-disable-next-line
|
|
6
|
+
const debug = require('debug')(`${require('../../package.json').name}:authenticator:base`);
|
|
7
|
+
|
|
8
|
+
class BaseAuthenticator {
|
|
9
|
+
_validateWallet(wallet, canSign = true) {
|
|
10
|
+
if (!wallet) {
|
|
11
|
+
throw new Error('WalletAuthenticator cannot work without wallet');
|
|
12
|
+
}
|
|
13
|
+
|
|
14
|
+
if (typeof wallet === 'function') {
|
|
15
|
+
return wallet;
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
if (isValid(wallet, canSign)) {
|
|
19
|
+
return { sk: wallet.secretKey, pk: wallet.publicKey, address: wallet.address };
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
if (canSign && !wallet.sk) {
|
|
23
|
+
throw new Error('WalletAuthenticator cannot work without wallet.sk');
|
|
24
|
+
}
|
|
25
|
+
if (!wallet.pk) {
|
|
26
|
+
throw new Error('WalletAuthenticator cannot work without wallet.pk');
|
|
27
|
+
}
|
|
28
|
+
if (!wallet.address) {
|
|
29
|
+
throw new Error('WalletAuthenticator cannot work without wallet.address');
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
return wallet;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* Verify a DID auth response sent from DID Wallet
|
|
37
|
+
*
|
|
38
|
+
* @method
|
|
39
|
+
* @param {object} data
|
|
40
|
+
* @param {string} [locale=en]
|
|
41
|
+
* @param {boolean} [enforceTimestamp=true]
|
|
42
|
+
* @returns Promise<boolean>
|
|
43
|
+
*/
|
|
44
|
+
async _verify(data, fieldPk, fieldInfo, locale = 'en', enforceTimestamp = true) {
|
|
45
|
+
debug('verify', data, locale);
|
|
46
|
+
|
|
47
|
+
const errors = {
|
|
48
|
+
pkMissing: {
|
|
49
|
+
en: `${fieldPk} is required to complete auth`,
|
|
50
|
+
zh: `${fieldPk} 参数缺失`,
|
|
51
|
+
},
|
|
52
|
+
tokenMissing: {
|
|
53
|
+
en: `${fieldInfo} is required to complete auth`,
|
|
54
|
+
zh: 'JWT Token 参数缺失',
|
|
55
|
+
},
|
|
56
|
+
pkFormat: {
|
|
57
|
+
en: `${fieldPk} should be either base58 or base16 format`,
|
|
58
|
+
zh: `${fieldPk} 无法解析`,
|
|
59
|
+
},
|
|
60
|
+
tokenInvalid: {
|
|
61
|
+
en: 'Invalid JWT token',
|
|
62
|
+
zh: '签名无效',
|
|
63
|
+
},
|
|
64
|
+
timeInvalid: {
|
|
65
|
+
en: 'JWT token expired, make sure your device time in sync with network',
|
|
66
|
+
zh: '签名中的时间戳无效,请确保设备和网络时间同步',
|
|
67
|
+
},
|
|
68
|
+
};
|
|
69
|
+
|
|
70
|
+
const pk = data[fieldPk];
|
|
71
|
+
const info = data[fieldInfo];
|
|
72
|
+
if (!pk) {
|
|
73
|
+
throw new Error(errors.pkMissing[locale]);
|
|
74
|
+
}
|
|
75
|
+
if (!info) {
|
|
76
|
+
throw new Error(errors.tokenMissing[locale]);
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
if (!pk) {
|
|
80
|
+
throw new Error(errors.pkFormat[locale]);
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
// NOTE: since the token can be invalid because of wallet-app clock not in sync
|
|
84
|
+
// We should tell the user that if it's caused by clock
|
|
85
|
+
if (!Jwt.verify(info, pk)) {
|
|
86
|
+
const isValidSig = await Jwt.verify(info, pk, { tolerance: 0, enforceTimestamp: false });
|
|
87
|
+
if (enforceTimestamp) {
|
|
88
|
+
const error = isValidSig ? errors.timeInvalid[locale] : errors.tokenInvalid[locale];
|
|
89
|
+
throw new Error(error);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
return Jwt.decode(info);
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
module.exports = BaseAuthenticator;
|
|
98
|
+
module.exports.DEFAULT_CHAIN_INFO = { id: 'none', host: 'none', type: 'arcblock' };
|