@arcblock/did-connect-js 1.30.0 → 4.0.0-beta.10

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (124) hide show
  1. package/{lib/adapters/detect.d.cts → dist/adapters/detect.d.ts} +3 -5
  2. package/dist/adapters/detect.d.ts.map +1 -0
  3. package/dist/adapters/detect.js +13 -0
  4. package/dist/adapters/detect.js.map +1 -0
  5. package/dist/adapters/express.d.ts +40 -0
  6. package/dist/adapters/express.d.ts.map +1 -0
  7. package/dist/adapters/express.js +30 -0
  8. package/dist/adapters/express.js.map +1 -0
  9. package/dist/adapters/hono.d.ts +49 -0
  10. package/dist/adapters/hono.d.ts.map +1 -0
  11. package/dist/adapters/hono.js +176 -0
  12. package/dist/adapters/hono.js.map +1 -0
  13. package/dist/authenticator/base.d.ts +21 -0
  14. package/dist/authenticator/base.d.ts.map +1 -0
  15. package/dist/authenticator/base.js +109 -0
  16. package/dist/authenticator/base.js.map +1 -0
  17. package/dist/authenticator/wallet.d.ts +252 -0
  18. package/dist/authenticator/wallet.d.ts.map +1 -0
  19. package/dist/authenticator/wallet.js +590 -0
  20. package/dist/authenticator/wallet.js.map +1 -0
  21. package/dist/handlers/base.d.ts +25 -0
  22. package/dist/handlers/base.d.ts.map +1 -0
  23. package/dist/handlers/base.js +48 -0
  24. package/dist/handlers/base.js.map +1 -0
  25. package/dist/handlers/util.d.ts +48 -0
  26. package/dist/handlers/util.d.ts.map +1 -0
  27. package/dist/handlers/util.js +805 -0
  28. package/dist/handlers/util.js.map +1 -0
  29. package/dist/handlers/wallet.d.ts +96 -0
  30. package/dist/handlers/wallet.d.ts.map +1 -0
  31. package/dist/handlers/wallet.js +129 -0
  32. package/dist/handlers/wallet.js.map +1 -0
  33. package/dist/index.d.ts +11 -0
  34. package/dist/index.d.ts.map +1 -0
  35. package/dist/index.js +9 -0
  36. package/dist/index.js.map +1 -0
  37. package/dist/protocol.d.ts +14 -0
  38. package/dist/protocol.d.ts.map +1 -0
  39. package/dist/protocol.js +37 -0
  40. package/dist/protocol.js.map +1 -0
  41. package/dist/schema/claims.d.ts +11 -0
  42. package/dist/schema/claims.d.ts.map +1 -0
  43. package/dist/schema/claims.js +226 -0
  44. package/dist/schema/claims.js.map +1 -0
  45. package/dist/schema/index.d.ts +4 -0
  46. package/dist/schema/index.d.ts.map +1 -0
  47. package/dist/schema/index.js +89 -0
  48. package/dist/schema/index.js.map +1 -0
  49. package/dist/storage/kv.d.ts +31 -0
  50. package/dist/storage/kv.d.ts.map +1 -0
  51. package/dist/storage/kv.js +54 -0
  52. package/dist/storage/kv.js.map +1 -0
  53. package/dist/types.d.ts +53 -0
  54. package/dist/types.d.ts.map +1 -0
  55. package/dist/types.js +2 -0
  56. package/dist/types.js.map +1 -0
  57. package/dist/utils/helpers.d.ts +19 -0
  58. package/dist/utils/helpers.d.ts.map +1 -0
  59. package/dist/utils/helpers.js +77 -0
  60. package/dist/utils/helpers.js.map +1 -0
  61. package/package.json +51 -107
  62. package/LICENSE +0 -13
  63. package/README.md +0 -210
  64. package/esm/_virtual/rolldown_runtime.mjs +0 -8
  65. package/esm/adapters/detect.d.mts +0 -11
  66. package/esm/adapters/detect.mjs +0 -16
  67. package/esm/adapters/express.d.mts +0 -48
  68. package/esm/adapters/express.mjs +0 -39
  69. package/esm/adapters/hono.d.mts +0 -57
  70. package/esm/adapters/hono.mjs +0 -164
  71. package/esm/authenticator/base.d.mts +0 -23
  72. package/esm/authenticator/base.mjs +0 -88
  73. package/esm/authenticator/wallet.d.mts +0 -270
  74. package/esm/authenticator/wallet.mjs +0 -556
  75. package/esm/did/did-connect/package.mjs +0 -118
  76. package/esm/handlers/base.d.mts +0 -32
  77. package/esm/handlers/base.mjs +0 -37
  78. package/esm/handlers/util.d.mts +0 -70
  79. package/esm/handlers/util.mjs +0 -739
  80. package/esm/handlers/wallet.d.mts +0 -120
  81. package/esm/handlers/wallet.mjs +0 -139
  82. package/esm/index.d.mts +0 -8
  83. package/esm/index.mjs +0 -8
  84. package/esm/node_modules/valibot/dist/index.mjs +0 -736
  85. package/esm/protocol.d.mts +0 -15
  86. package/esm/protocol.mjs +0 -40
  87. package/esm/schema/claims.d.mts +0 -16
  88. package/esm/schema/claims.mjs +0 -216
  89. package/esm/schema/index.d.mts +0 -29
  90. package/esm/schema/index.mjs +0 -75
  91. package/esm/storage/kv.d.mts +0 -33
  92. package/esm/storage/kv.mjs +0 -55
  93. package/esm/types.d.mts +0 -55
  94. package/esm/types.mjs +0 -1
  95. package/lib/_virtual/rolldown_runtime.cjs +0 -31
  96. package/lib/adapters/detect.cjs +0 -18
  97. package/lib/adapters/express.cjs +0 -41
  98. package/lib/adapters/express.d.cts +0 -48
  99. package/lib/adapters/hono.cjs +0 -167
  100. package/lib/adapters/hono.d.cts +0 -57
  101. package/lib/authenticator/base.cjs +0 -91
  102. package/lib/authenticator/base.d.cts +0 -23
  103. package/lib/authenticator/wallet.cjs +0 -565
  104. package/lib/authenticator/wallet.d.cts +0 -270
  105. package/lib/did/did-connect/package.cjs +0 -121
  106. package/lib/handlers/base.cjs +0 -40
  107. package/lib/handlers/base.d.cts +0 -32
  108. package/lib/handlers/util.cjs +0 -759
  109. package/lib/handlers/util.d.cts +0 -70
  110. package/lib/handlers/wallet.cjs +0 -139
  111. package/lib/handlers/wallet.d.cts +0 -119
  112. package/lib/index.cjs +0 -16
  113. package/lib/index.d.cts +0 -8
  114. package/lib/node_modules/valibot/dist/index.cjs +0 -756
  115. package/lib/protocol.cjs +0 -46
  116. package/lib/protocol.d.cts +0 -15
  117. package/lib/schema/claims.cjs +0 -218
  118. package/lib/schema/claims.d.cts +0 -16
  119. package/lib/schema/index.cjs +0 -79
  120. package/lib/schema/index.d.cts +0 -29
  121. package/lib/storage/kv.cjs +0 -57
  122. package/lib/storage/kv.d.cts +0 -33
  123. package/lib/types.cjs +0 -0
  124. package/lib/types.d.cts +0 -55
@@ -0,0 +1,805 @@
1
+ import { isValid as isValidDid } from '@arcblock/did';
2
+ import * as Mcrypto from '@ocap/mcrypto';
3
+ import { fromBase64, stripHexPrefix, toBase64 } from '@ocap/util';
4
+ import stringify from 'fast-json-stable-stringify';
5
+ // @ts-expect-error - tweetnacl-sealedbox-js has no type declarations
6
+ import SealedBox from 'tweetnacl-sealedbox-js';
7
+ import url from 'url';
8
+ import { decrypt, encrypt, PROTECTED_KEYS, SESSION_STATUS } from '../protocol.js';
9
+ import { cloneDeep, isEqual, isPlainObject, omit, pick, random } from '../utils/helpers.js';
10
+ // Scheme: https://tools.ietf.org/html/rfc3986#section-3.1
11
+ // Absolute URL: https://tools.ietf.org/html/rfc3986#section-4.3
12
+ const ABSOLUTE_URL_REGEX = /^[a-zA-Z][a-zA-Z\d+\-.]*?:/;
13
+ // Windows paths like `c:\`
14
+ const WINDOWS_PATH_REGEX = /^[a-zA-Z]:\\/;
15
+ const isUrl = (input) => {
16
+ if (typeof input !== 'string') {
17
+ return false;
18
+ }
19
+ if (WINDOWS_PATH_REGEX.test(input)) {
20
+ return false;
21
+ }
22
+ return ABSOLUTE_URL_REGEX.test(input);
23
+ };
24
+ import Debug from 'debug';
25
+ const _debug = Debug('@arcblock/did-connect-js:handlers:util');
26
+ const sha3 = Mcrypto.Hasher.SHA3.hash256;
27
+ const getLocale = (req) => (req.acceptsLanguages('en-US', 'zh-CN') || 'en-US').split('-').shift() || 'en';
28
+ const getSessionId = () => Date.now().toString();
29
+ const noop = () => ({});
30
+ const noTouch = (x) => x;
31
+ export const errors = {
32
+ tokenMissing: {
33
+ en: 'Session Id is required to check status',
34
+ zh: '缺少会话 ID 参数',
35
+ },
36
+ didMismatch: {
37
+ en: 'Login user and wallet user mismatch, please relogin and try again',
38
+ zh: '登录用户和扫码用户不匹配,为保障安全,请重新登录应用',
39
+ },
40
+ mfaMismatch: {
41
+ en: 'Dynamic verification code mismatch, please try again later',
42
+ zh: '动态验证码不匹配,请重试',
43
+ },
44
+ challengeMismatch: {
45
+ en: 'Challenge mismatch',
46
+ zh: '随机校验码不匹配',
47
+ },
48
+ token404: {
49
+ en: 'Session not found or expired',
50
+ zh: '会话不存在或已过期',
51
+ },
52
+ didMissing: {
53
+ en: 'userDid is required to start auth',
54
+ zh: 'userDid 参数缺失,请勿尝试连接多个不同的钱包',
55
+ },
56
+ pkMissing: {
57
+ en: 'userPk is required to start auth',
58
+ zh: 'userPk 参数缺失,请勿尝试连接多个不同的钱包',
59
+ },
60
+ authClaim: {
61
+ en: 'authPrincipal claim is not configured correctly',
62
+ zh: 'authPrincipal 声明配置不正确',
63
+ },
64
+ userDeclined: {
65
+ en: 'You have declined the authentication request',
66
+ zh: '授权请求被拒绝',
67
+ },
68
+ userBusy: {
69
+ en: 'Busy processing another DID Connect request',
70
+ zh: '正在处理其他请求',
71
+ },
72
+ };
73
+ // This logic exist because the handlers maybe attached to a nested router
74
+ // pathname pattern: /:prefix/:action/auth
75
+ // But the group of handlers may be attached to a sub router, which has a baseUrl of `/api/login` (can only be extracted from `req.originalUrl`)
76
+ // We need to ensure the full url is given to DID Wallet
77
+ // eg: `/agent/login/auth` on the current router will be converted to `/api/login/agent/login/auth`
78
+ export const preparePathname = (path, req) => {
79
+ const delimiter = path.replace(/\/retrieve$/, '').replace(/\/auth$/, '');
80
+ const fullPath = url.parse(req.originalUrl).pathname;
81
+ const [prefix] = fullPath.split(delimiter);
82
+ const cleanPath = [prefix, path].join('/').replace(/\/+/g, '/');
83
+ // console.log('preparePathname', { path, delimiter, fullPath, prefix, cleanPath });
84
+ return cleanPath;
85
+ };
86
+ const getBaseUrl = (req) => {
87
+ if (req.headers['x-path-prefix']) {
88
+ return `/${req.headers['x-path-prefix']}/`.replace(/\/+/g, '/');
89
+ }
90
+ return '/';
91
+ };
92
+ // This makes the lib smart enough to infer baseURL from request object
93
+ export const prepareBaseUrl = (req, params) => {
94
+ const pathPrefix = getBaseUrl(req).replace(/\/$/, '');
95
+ const [hostname = '', port = 80] = (req.get('x-forwarded-host') ||
96
+ req.get('x-real-hostname') ||
97
+ req.get('host') ||
98
+ '').split(':');
99
+ // NOTE: x-real-port exist because sometimes the auth api is behind a port-forwarding proxy
100
+ const finalPort = (params?.['x-real-port'] ?? null) || req.get('X-Real-Port') || port || '';
101
+ return url.format({
102
+ protocol: params?.['x-real-protocol'] || req.get('X-Real-protocol') || req.get('X-Forwarded-Proto') || req.protocol,
103
+ hostname,
104
+ port: Number(finalPort) === 80 ? '' : finalPort,
105
+ pathname: pathPrefix,
106
+ });
107
+ };
108
+ // https://github.com/joaquimserafim/base64-url/blob/54d9c9ede66a8724f280cf24fd18c38b9a53915f/index.js#L10
109
+ const base64UrlUnescape = (str) => (str + '==='.slice((str.length + 3) % 4)).replace(/-/g, '+').replace(/_/g, '/');
110
+ const decodeEncKey = (str) => new Uint8Array(Buffer.from(base64UrlUnescape(str), 'base64'));
111
+ export const getStepChallenge = () => stripHexPrefix(Mcrypto.getRandomBytes(16)).toUpperCase();
112
+ export const parseWalletUA = (userAgent) => {
113
+ const ua = (userAgent || '').toString().toLowerCase();
114
+ let os = '';
115
+ let version = '';
116
+ if (ua.indexOf('android') > -1) {
117
+ os = 'android';
118
+ }
119
+ else if (ua.indexOf('iphone') > -1) {
120
+ os = 'ios';
121
+ }
122
+ else if (ua.indexOf('ipad') > -1) {
123
+ os = 'ios';
124
+ }
125
+ else if (ua.indexOf('ipod') > -1) {
126
+ os = 'ios';
127
+ }
128
+ else if (ua.indexOf('arcwallet') === 0) {
129
+ os = 'web';
130
+ }
131
+ else if (ua.indexOf('abtwallet') === 0) {
132
+ os = 'web';
133
+ }
134
+ const match = ua.split(/\s+/).find((x) => x.startsWith('arcwallet/') || x.startsWith('abtwallet/'));
135
+ if (match) {
136
+ const tmp = match.split('/');
137
+ const coerced = tmp.length > 1 ? (tmp[1].match(/(\d+\.\d+\.\d+)/) || [])[1] : undefined;
138
+ if (coerced) {
139
+ version = coerced;
140
+ }
141
+ }
142
+ return { os, version, jwt: '1.1.0' };
143
+ };
144
+ export const isDeepLink = (str) => str.startsWith('https://abtwallet.io/i/') || str.startsWith('https://didwallet.io/i/');
145
+ // whether we should force did-wallet to connect with userDid from session
146
+ export const isConnectedOnly = (params, sessionUserDid = '') => {
147
+ if (typeof params.forceConnected === 'string' && isValidDid(params.forceConnected)) {
148
+ return params.forceConnected;
149
+ }
150
+ if (!sessionUserDid) {
151
+ return false;
152
+ }
153
+ if (isValidDid(sessionUserDid) === false) {
154
+ return false;
155
+ }
156
+ if (params.connectedDid !== sessionUserDid) {
157
+ return false;
158
+ }
159
+ // auto
160
+ if (typeof params.forceConnected === 'undefined') {
161
+ return true;
162
+ }
163
+ // query string from client: `true` | `false` | did
164
+ if (typeof params.forceConnected === 'string') {
165
+ try {
166
+ return !!JSON.parse(params.forceConnected);
167
+ }
168
+ catch {
169
+ return false;
170
+ }
171
+ }
172
+ return !!params.forceConnected;
173
+ };
174
+ // If we treat an did-connect roundtrip as a session, then action token is the session id
175
+ export default function createHandlers({ action, pathname, claims, onStart, onConnect, onAuth, onDecline, onComplete, onExpire, onError, pathTransformer, tokenStorage, authenticator, authPrincipal, persistentDynamicClaims = false, getSignParams = noop, getPathName = noTouch, options, }) {
176
+ const { tokenKey, encKey, versionKey, cleanupDelay } = options;
177
+ const defaultSteps = (Array.isArray(claims) ? claims : [claims]).filter(Boolean);
178
+ // Smart detection of user-defined authPrincipal claim
179
+ if (defaultSteps.length > 0) {
180
+ const keys = Object.keys(defaultSteps[0]);
181
+ const firstClaim = defaultSteps[0][keys[0]];
182
+ if (Array.isArray(firstClaim)) {
183
+ if (firstClaim[0] === 'authPrincipal') {
184
+ authPrincipal = false;
185
+ }
186
+ }
187
+ else if (keys[0] === 'authPrincipal') {
188
+ authPrincipal = false;
189
+ }
190
+ }
191
+ // Prepend default authPrincipal claim if not set
192
+ if (authPrincipal) {
193
+ let target = '';
194
+ let description = 'Please continue with your account';
195
+ let chainInfo;
196
+ let targetType;
197
+ if (typeof authPrincipal === 'string') {
198
+ if (isValidDid(authPrincipal)) {
199
+ // If auth principal is provided as a did
200
+ target = authPrincipal;
201
+ }
202
+ else {
203
+ // If auth principal is provided as a string
204
+ description = authPrincipal;
205
+ }
206
+ }
207
+ if (typeof authPrincipal === 'object') {
208
+ target = authPrincipal.target ?? target;
209
+ description = authPrincipal.description ?? description;
210
+ targetType = authPrincipal.targetType ?? targetType;
211
+ // If provided a chainInfo
212
+ if (authPrincipal.chainInfo && authenticator._isValidChainInfo(authPrincipal.chainInfo)) {
213
+ chainInfo = authPrincipal.chainInfo;
214
+ }
215
+ }
216
+ const supervised = defaultSteps.length === 0;
217
+ defaultSteps.unshift({
218
+ authPrincipal: {
219
+ skippable: true,
220
+ description,
221
+ target,
222
+ chainInfo,
223
+ targetType,
224
+ supervised,
225
+ },
226
+ });
227
+ }
228
+ // Whether we can skip the authPrincipal step safely
229
+ const canSkipConnect = defaultSteps[0]?.authPrincipal?.skippable;
230
+ const createExtraParams = (locale, params, extra = {}) => {
231
+ const finalParams = { ...params, ...(extra || {}) };
232
+ return {
233
+ locale,
234
+ action,
235
+ ...Object.keys(finalParams)
236
+ .filter((x) => !['userDid', 'userInfo', 'userSession', 'appSession', 'userPk', 'token'].includes(x))
237
+ .reduce((obj, x) => {
238
+ obj[x] = finalParams[x];
239
+ return obj;
240
+ }, {}),
241
+ };
242
+ };
243
+ const createSessionUpdater = (token, params) => async (key, value, secure = false) => {
244
+ const getUpdate = (k, v) => {
245
+ if (secure && params[encKey]) {
246
+ const encrypted = SealedBox.seal(Buffer.from(stringify(v)), decodeEncKey(params[encKey]));
247
+ return { [k]: Buffer.from(encrypted).toString('base64') };
248
+ }
249
+ return { [k]: v };
250
+ };
251
+ // If key is an object, update multiple keys
252
+ if (typeof key === 'object') {
253
+ secure = value;
254
+ const keys = Object.keys(key);
255
+ const updates = Object.assign({}, ...keys.map((k) => getUpdate(k, key[k])));
256
+ return tokenStorage.update(token, updates);
257
+ }
258
+ return tokenStorage.update(token, omit(getUpdate(key, value), PROTECTED_KEYS));
259
+ };
260
+ // used for multi-factor authentication
261
+ const createMfaCodeGenerator = (token) => async () => {
262
+ const mfaCode = random(10, 99);
263
+ await tokenStorage.update(token, { mfaCode });
264
+ return mfaCode;
265
+ };
266
+ const onProcessError = ({ req, res, stage, err, }) => {
267
+ const { token, store } = req.context || {};
268
+ if (token) {
269
+ tokenStorage.update(token, { status: SESSION_STATUS.ERROR, error: err.message, mfaCode: 0 });
270
+ }
271
+ res.jsonp({ error: err.message });
272
+ onError({ token, extraParams: store?.extraParams ?? {}, stage, err });
273
+ };
274
+ const _preparePathname = (str, req) => {
275
+ const auto = preparePathname(str, req);
276
+ const custom = pathTransformer(auto);
277
+ // console.log('preparePathname', { str, auto, custom });
278
+ return custom;
279
+ };
280
+ // For web app
281
+ const generateSession = async (req, res) => {
282
+ try {
283
+ const params = {
284
+ 'x-real-port': req.get('x-real-port'),
285
+ 'x-real-protocol': req.get('x-real-protocol'),
286
+ deviceDid: req.get('x-device-did'),
287
+ connectedDid: req.cookies?.connected_did ?? '',
288
+ connectedPk: req.cookies?.connected_pk ?? '',
289
+ ...req.body,
290
+ ...req.query,
291
+ ...req.params,
292
+ };
293
+ // force to connected user if we are during a session, and this behavior is customizable
294
+ params.forceConnected = isConnectedOnly(params, req.get('x-user-did'));
295
+ const token = sha3(getSessionId())
296
+ .replace(/^0x/, '')
297
+ .slice(0, 8);
298
+ await tokenStorage.create(token, SESSION_STATUS.CREATED);
299
+ // These fields are used to track the source session
300
+ // - sourceToken is the token of previous session
301
+ // - destToken is the token of final target session
302
+ let sourceToken = params.sourceToken || '';
303
+ const sourceTokenState = sourceToken ? await tokenStorage.read(sourceToken) : null;
304
+ if (sourceTokenState) {
305
+ if ([SESSION_STATUS.SUCCEED].includes(sourceTokenState.status)) {
306
+ sourceToken = '';
307
+ }
308
+ else {
309
+ await tokenStorage.update(sourceToken, { destToken: token });
310
+ }
311
+ }
312
+ const finalPath = _preparePathname(getPathName(pathname, req), req);
313
+ const baseUrl = prepareBaseUrl(req, params);
314
+ const uri = await authenticator.uri({ token, pathname: finalPath, baseUrl, query: {} });
315
+ // Always set currentStep to 0 when generate a new token
316
+ // Since the did of logged in user may be different of the auth did
317
+ const challenge = getStepChallenge();
318
+ const didwallet = parseWalletUA(req.query['user-agent'] || req.headers['user-agent']);
319
+ const extraParams = createExtraParams(getLocale(req), params);
320
+ const hookParams = {
321
+ req,
322
+ request: req,
323
+ challenge,
324
+ baseUrl,
325
+ deepLink: uri,
326
+ extraParams,
327
+ updateSession: createSessionUpdater(token, extraParams),
328
+ didwallet,
329
+ };
330
+ const [wallet, delegator] = await Promise.all([
331
+ authenticator.getWalletInfo({ baseUrl, request: req, extraParams }),
332
+ authenticator.getDelegator({ baseUrl, request: req, extraParams }),
333
+ ]);
334
+ const [appInfo, memberAppInfo] = await Promise.all([
335
+ authenticator.getAppInfo({ baseUrl, request: req, wallet, delegator, extraParams }, 'appInfo'),
336
+ authenticator.getAppInfo({ baseUrl, request: req, wallet, delegator, extraParams }, 'memberAppInfo'),
337
+ ]);
338
+ await tokenStorage.update(token, {
339
+ currentStep: 0,
340
+ mfaSupported: !didwallet.os, // If we are mobile (both webview and mobile browsers , os is truthy), mfa should be disabled
341
+ challenge,
342
+ sharedKey: getStepChallenge(), // used for wallet to encrypt userInfo
343
+ extraParams: params,
344
+ appInfo,
345
+ memberAppInfo,
346
+ sourceToken,
347
+ });
348
+ // debug('generate token', { action, pathname, token });
349
+ // The data returned by onStart will be set to extra of response data
350
+ // {String} extra.connectedDid:The server will notify the connectedDid in wallet to automatically connect (no code scanning is required) (notification is unreliable)
351
+ // {Boolean} extra.saveConnect: The server tells the app web side to remember the connect session did after the connect is complete
352
+ const extra = await onStart(hookParams);
353
+ res.jsonp({ token, status: SESSION_STATUS.CREATED, url: uri, appInfo, memberAppInfo, extra: extra || {} });
354
+ }
355
+ catch (err) {
356
+ onProcessError({ req, res, stage: 'generate-token', err });
357
+ }
358
+ };
359
+ // For web app
360
+ const checkSession = async (req, res) => {
361
+ try {
362
+ const { locale, token, store, params } = req.context;
363
+ if (!token) {
364
+ res.status(400).json({ error: errors.tokenMissing[locale] });
365
+ return;
366
+ }
367
+ if (!store) {
368
+ res.status(400).json({ error: errors.token404[locale] });
369
+ return;
370
+ }
371
+ if (store.status === SESSION_STATUS.FORBIDDEN) {
372
+ res.status(403).json({ error: errors.didMismatch[locale] });
373
+ return;
374
+ }
375
+ if (store.status === SESSION_STATUS.SUCCEED) {
376
+ setTimeout(() => {
377
+ tokenStorage.delete(token).catch(console.error);
378
+ }, cleanupDelay);
379
+ const extraParams = createExtraParams(locale, params, store?.extraParams ?? {});
380
+ await onComplete({
381
+ req,
382
+ request: req,
383
+ userDid: store.did,
384
+ userPk: store.pk,
385
+ extraParams,
386
+ updateSession: createSessionUpdater(token, extraParams),
387
+ });
388
+ }
389
+ res.status(200).json(Object.keys(store)
390
+ .filter((x) => PROTECTED_KEYS.includes(x) === false)
391
+ .reduce((acc, key) => {
392
+ acc[key] = store[key];
393
+ return acc;
394
+ }, {}));
395
+ }
396
+ catch (err) {
397
+ onProcessError({ req, res, stage: 'check-token-status', err });
398
+ }
399
+ };
400
+ // For web app
401
+ const expireSession = async (req, res) => {
402
+ try {
403
+ const { locale, token, store } = req.context;
404
+ if (!token) {
405
+ res.status(400).json({ error: errors.tokenMissing[locale] });
406
+ return;
407
+ }
408
+ if (!store) {
409
+ res.status(400).json({ error: errors.token404[locale] });
410
+ return;
411
+ }
412
+ onExpire({ token, extraParams: store?.extraParams ?? {}, status: 'expired' });
413
+ // We do not delete tokens that are scanned by wallet since it will cause confusing
414
+ if (store.status !== SESSION_STATUS.SCANNED) {
415
+ await tokenStorage.delete(token);
416
+ }
417
+ res.status(200).json({ token });
418
+ }
419
+ catch (err) {
420
+ onProcessError({ req, res, stage: 'mark-token-timeout', err });
421
+ }
422
+ };
423
+ // Only check userDid and userPk if we have done auth principal
424
+ const checkUser = async ({ context, userDid, userPk }) => {
425
+ const { locale, token, store } = context;
426
+ const isConnected = store.currentStep > 0;
427
+ // Only check userDid and userPk if we have done auth principal
428
+ if (isConnected) {
429
+ if (!userDid) {
430
+ return errors.didMissing[locale];
431
+ }
432
+ if (!userPk) {
433
+ return errors.pkMissing[locale];
434
+ }
435
+ // check userDid mismatch
436
+ if (userDid !== store.did) {
437
+ await tokenStorage.update(token, { status: SESSION_STATUS.FORBIDDEN });
438
+ return errors.didMismatch[locale];
439
+ }
440
+ }
441
+ return false;
442
+ };
443
+ const onAuthRequest = async (req, res) => {
444
+ const { locale, token, store, params, didwallet } = req.context;
445
+ const extraParams = createExtraParams(locale, params, store?.extraParams ?? {});
446
+ const userDid = params.userDid || store.did || extraParams.connectedDid;
447
+ const userPk = params.userPk || store.pk || extraParams.connectedPk;
448
+ const error = await checkUser({ context: req.context, userDid, userPk });
449
+ if (error) {
450
+ return res.jsonp({ error });
451
+ }
452
+ if (params[versionKey] && store.clientVersion !== params[versionKey]) {
453
+ store.clientVersion = params[versionKey];
454
+ store.encryptionKey = params[encKey];
455
+ await tokenStorage.update(token, { clientVersion: params[versionKey], encryptionKey: params[encKey] });
456
+ }
457
+ try {
458
+ const steps = [...cloneDeep(defaultSteps)];
459
+ const shouldSkipConnect = canSkipConnect && !!extraParams.connectedDid;
460
+ if (shouldSkipConnect) {
461
+ steps[0].authPrincipal.supervised = false;
462
+ }
463
+ if (extraParams.forceConnected) {
464
+ let target = extraParams.connectedDid;
465
+ if (typeof extraParams.forceConnected === 'string' && isValidDid(extraParams.forceConnected)) {
466
+ target = extraParams.forceConnected;
467
+ }
468
+ if (isValidDid(target)) {
469
+ steps[0].authPrincipal.target = target;
470
+ }
471
+ }
472
+ if (store.status !== SESSION_STATUS.SCANNED) {
473
+ await tokenStorage.update(token, { status: SESSION_STATUS.SCANNED, connectedWallet: didwallet });
474
+ }
475
+ // Since we can not store dynamic claims anywhere, we should calculate it on the fly
476
+ if (store.dynamic || shouldSkipConnect) {
477
+ const newClaims = await onConnect({
478
+ req,
479
+ request: req,
480
+ userDid,
481
+ userPk,
482
+ didwallet,
483
+ challenge: store.challenge,
484
+ pathname: _preparePathname(getPathName(pathname, req), req),
485
+ baseUrl: prepareBaseUrl(req, extraParams),
486
+ extraParams,
487
+ updateSession: createSessionUpdater(token, extraParams),
488
+ });
489
+ if (newClaims) {
490
+ if (Array.isArray(newClaims)) {
491
+ steps.push(...newClaims);
492
+ }
493
+ else {
494
+ steps.push(newClaims);
495
+ }
496
+ }
497
+ }
498
+ const signParams = await getSignParams(req);
499
+ const signedClaim = await authenticator.sign(Object.assign(signParams, {
500
+ context: {
501
+ token,
502
+ userDid,
503
+ userPk,
504
+ didwallet,
505
+ ...pick(store, ['currentStep', 'sharedKey', 'encryptionKey']),
506
+ mfaCode: store.mfaSupported ? createMfaCodeGenerator(token) : undefined,
507
+ },
508
+ claims: steps[store.currentStep],
509
+ pathname: _preparePathname(getPathName(pathname, req), req),
510
+ baseUrl: prepareBaseUrl(req, extraParams),
511
+ extraParams,
512
+ challenge: store.challenge,
513
+ appInfo: store.appInfo,
514
+ memberAppInfo: store.memberAppInfo,
515
+ request: req,
516
+ }));
517
+ res.jsonp(encrypt(signedClaim, store));
518
+ }
519
+ catch (err) {
520
+ onProcessError({ req, res, stage: 'send-auth-claim', err });
521
+ }
522
+ };
523
+ const onAuthResponse = async (req, res) => {
524
+ const { locale, token, store, params, didwallet } = req.context;
525
+ try {
526
+ const { userDid, userPk, action: userAction, challenge: userChallenge, claims: claimResponse, timestamp, } = await authenticator.verify(decrypt(params, store), locale);
527
+ // debug('onAuthResponse.verify', { userDid, token, claims: claimResponse });
528
+ if (!store.did || !store.pk) {
529
+ await tokenStorage.update(token, { did: userDid, pk: userPk });
530
+ }
531
+ const extraParams = createExtraParams(locale, params, store?.extraParams ?? {});
532
+ const cbParams = {
533
+ step: store.currentStep,
534
+ req,
535
+ request: req,
536
+ userDid,
537
+ userPk,
538
+ challenge: store.challenge,
539
+ didwallet,
540
+ claims: claimResponse,
541
+ baseUrl: prepareBaseUrl(req, extraParams),
542
+ extraParams,
543
+ updateSession: createSessionUpdater(token, extraParams),
544
+ timestamp,
545
+ };
546
+ const steps = [...defaultSteps];
547
+ const shouldSkipConnect = canSkipConnect && !!extraParams.connectedDid;
548
+ // Since we can not store dynamic claims anywhere, we should calculate it on the fly
549
+ if (store.dynamic || shouldSkipConnect) {
550
+ const newClaims = await onConnect(cbParams);
551
+ if (newClaims) {
552
+ if (Array.isArray(newClaims)) {
553
+ steps.push(...newClaims);
554
+ }
555
+ else {
556
+ steps.push(newClaims);
557
+ }
558
+ }
559
+ }
560
+ else if (persistentDynamicClaims && Array.isArray(store.dynamicClaims)) {
561
+ steps.push(...store.dynamicClaims);
562
+ }
563
+ // Ensure user approval
564
+ if (userAction === 'declineAuth') {
565
+ await tokenStorage.update(token, {
566
+ status: SESSION_STATUS.ERROR,
567
+ error: errors.userDeclined[locale],
568
+ mfaCode: 0,
569
+ currentStep: steps.length - 1,
570
+ });
571
+ const result = await onDecline(cbParams);
572
+ return res.jsonp({ ...(result || {}) });
573
+ }
574
+ if (userAction === 'busy') {
575
+ await tokenStorage.update(token, {
576
+ status: SESSION_STATUS.BUSY,
577
+ error: errors.userBusy[locale],
578
+ mfaCode: 0,
579
+ currentStep: steps.length - 1,
580
+ });
581
+ return res.jsonp({});
582
+ }
583
+ // Since only 1 MFA is allowed when multiple claims is requested, we just need to check the first one
584
+ if (store.mfaCode && !claimResponse.some((x) => isEqual(x.mfaCode, [store.mfaCode]))) {
585
+ return onProcessError({ req, res, stage: 'verify-mfa-code', err: new Error(errors.mfaMismatch[locale]) });
586
+ }
587
+ // Ensure JWT challenge match
588
+ if (!userChallenge) {
589
+ return res.jsonp({ error: errors.challengeMismatch[locale] });
590
+ }
591
+ if (userChallenge !== store.challenge) {
592
+ return res.jsonp({ error: errors.challengeMismatch[locale] });
593
+ }
594
+ // Ensure userDid match between authPrincipal and later process
595
+ const error = await checkUser({ context: req.context, userDid, userPk });
596
+ if (error) {
597
+ return res.jsonp({ error });
598
+ }
599
+ const isConnected = store.currentStep > 0;
600
+ if (isConnected === false) {
601
+ // Some permission check login can be done here
602
+ // Error thrown from this callback will terminate the process
603
+ const newClaims = await onConnect(cbParams);
604
+ if (newClaims) {
605
+ await tokenStorage.update(token, {
606
+ dynamic: !persistentDynamicClaims,
607
+ dynamicClaims: persistentDynamicClaims ? newClaims : undefined,
608
+ });
609
+ if (Array.isArray(newClaims)) {
610
+ steps.push(...newClaims);
611
+ }
612
+ else {
613
+ steps.push(newClaims);
614
+ }
615
+ }
616
+ }
617
+ const onLastStep = async (result) => {
618
+ let nextWorkflow = isUrl(extraParams.nw) ? extraParams.nw : '';
619
+ if (nextWorkflow && result?.nextWorkflowData) {
620
+ if (isPlainObject(result.nextWorkflowData) === false) {
621
+ const err = new Error(`expect nextWorkflowData should be a plain object, got: ${result.nextWorkflowData}`);
622
+ return onProcessError({ req, res, stage: 'validate-next-workflow-data', err });
623
+ }
624
+ const tmp = new URL(nextWorkflow);
625
+ const merged = Object.assign(extraParams.previousWorkflowData || {}, result.nextWorkflowData);
626
+ const previousWorkflowData = toBase64(JSON.stringify(merged));
627
+ // For max url length please refer to discussion at https://stackoverflow.com/a/417184/686854
628
+ if (previousWorkflowData.length > 8192) {
629
+ const err = new Error('base64 encoded nextWorkflowData should be less than 8192 characters');
630
+ return onProcessError({ req, res, stage: 'append-next-workflow', err });
631
+ }
632
+ if (isDeepLink(nextWorkflow)) {
633
+ const actualUrl = decodeURIComponent(tmp.searchParams.get('url'));
634
+ const obj = new URL(actualUrl);
635
+ obj.searchParams.set('previousWorkflowData', previousWorkflowData);
636
+ tmp.searchParams.set('url', obj.href);
637
+ }
638
+ else {
639
+ tmp.searchParams.set('previousWorkflowData', previousWorkflowData);
640
+ }
641
+ nextWorkflow = tmp.href;
642
+ }
643
+ const updates = {};
644
+ // If we have nextWorkflow, return it to browser
645
+ let actualNw = nextWorkflow || result?.nextWorkflow || '';
646
+ if (actualNw) {
647
+ if (isDeepLink(actualNw)) {
648
+ actualNw = new URL(actualNw).searchParams.get('url');
649
+ }
650
+ if (actualNw) {
651
+ updates.nextWorkflow = decodeURIComponent(actualNw);
652
+ }
653
+ }
654
+ // If we have nextWorkflow, do not mark current session as complete
655
+ // Instead, save the relationship between the two
656
+ // Then, mark both session as complete on nextWorkflow complete
657
+ // In theory, we can use this mechanism to concat infinite sessions
658
+ if (result?.nextToken && result.nextWorkflow) {
659
+ try {
660
+ await tokenStorage.update(result.nextToken, { prevToken: token });
661
+ }
662
+ catch (err) {
663
+ console.error('DIDAuth: failed to to update nextToken', err);
664
+ updates.status = SESSION_STATUS.SUCCEED;
665
+ }
666
+ }
667
+ else {
668
+ if (store.prevToken) {
669
+ try {
670
+ await tokenStorage.update(store.prevToken, { status: SESSION_STATUS.SUCCEED });
671
+ }
672
+ catch (err) {
673
+ console.error('DIDAuth: failed to to update prevToken', err);
674
+ }
675
+ }
676
+ updates.status = SESSION_STATUS.SUCCEED;
677
+ }
678
+ await tokenStorage.update(token, updates);
679
+ return res.jsonp({ ...Object.assign({ nextWorkflow }, result || {}) });
680
+ };
681
+ // If we are only requesting the authPrincipal claim
682
+ // We make such assertion here, because the onConnect callback can modify the steps
683
+ if (steps.length === 1) {
684
+ const result = await onAuth(cbParams);
685
+ return onLastStep(result);
686
+ }
687
+ // If we got requestedClaims other than the authPrincipal
688
+ if (isConnected && store.currentStep < steps.length) {
689
+ // Call onAuth on each step, since we do not hold all results until complete
690
+ const result = await onAuth(cbParams);
691
+ // Only return if we are walked through all steps
692
+ const isLastStep = store.currentStep === steps.length - 1;
693
+ if (isLastStep) {
694
+ return onLastStep(result);
695
+ }
696
+ }
697
+ // Move to next step: nextStep is persisted here to avoid an memory storage error
698
+ const nextStep = store.currentStep + 1;
699
+ const nextChallenge = getStepChallenge();
700
+ await tokenStorage.update(token, { currentStep: nextStep, challenge: nextChallenge, mfaCode: 0 });
701
+ const signParams = await getSignParams(req);
702
+ try {
703
+ const nextSignedClaim = await authenticator.sign(Object.assign(signParams, {
704
+ context: {
705
+ token,
706
+ userDid,
707
+ userPk,
708
+ didwallet,
709
+ ...pick(store, ['currentStep', 'sharedKey', 'encryptionKey']),
710
+ mfaCode: store.mfaSupported ? createMfaCodeGenerator(token) : undefined,
711
+ },
712
+ claims: steps[nextStep],
713
+ pathname: _preparePathname(getPathName(pathname, req), req),
714
+ baseUrl: prepareBaseUrl(req, extraParams),
715
+ extraParams,
716
+ challenge: nextChallenge,
717
+ appInfo: store.appInfo,
718
+ memberAppInfo: store.memberAppInfo,
719
+ request: req,
720
+ }));
721
+ return res.jsonp(encrypt(nextSignedClaim, store));
722
+ }
723
+ catch (err) {
724
+ return onProcessError({ req, res, stage: 'next-auth-claim', err });
725
+ }
726
+ }
727
+ catch (err) {
728
+ onProcessError({ req, res, stage: 'verify-auth-claim', err });
729
+ }
730
+ };
731
+ const ensureContext = async (req, _res, next) => {
732
+ const didwallet = parseWalletUA(req.query['user-agent'] || req.headers['user-agent']);
733
+ const params = { ...req.body, ...req.query, ...req.params };
734
+ const token = params[tokenKey];
735
+ const locale = getLocale(req);
736
+ let store = null;
737
+ if (token) {
738
+ store = await tokenStorage.read(token);
739
+ if (params.previousWorkflowData) {
740
+ try {
741
+ store.extraParams.previousWorkflowData = JSON.parse(fromBase64(params.previousWorkflowData).toString());
742
+ await tokenStorage.update(token, { extraParams: store.extraParams });
743
+ }
744
+ catch (e) {
745
+ console.warn('Could not parse previousWorkflowData', params.previousWorkflowData, e);
746
+ }
747
+ }
748
+ if (store?.destToken && typeof params.notrace === 'undefined') {
749
+ const result = await tokenStorage.read(store.destToken);
750
+ if (result) {
751
+ store = result;
752
+ }
753
+ }
754
+ }
755
+ req.context = { locale, token, didwallet, params, store };
756
+ return next();
757
+ };
758
+ const ensureSignedJson = (req, res, next) => {
759
+ if (req.ensureSignedJson === undefined) {
760
+ req.ensureSignedJson = true;
761
+ const originJsonp = res.jsonp;
762
+ res.jsonp = async (payload) => {
763
+ if (payload.appPk && payload.authInfo) {
764
+ return originJsonp.call(res, payload);
765
+ }
766
+ const data = payload.response ? { response: payload.response } : { response: payload };
767
+ const fields = ['error', 'errorMessage', 'successMessage', 'nextWorkflow', 'nextUrl', 'cookies', 'storages'];
768
+ // Attach protocol fields to the root
769
+ fields.forEach((x) => {
770
+ if (payload[x]) {
771
+ data[x] = payload[x];
772
+ }
773
+ });
774
+ data.errorMessage = data.error || data.errorMessage || '';
775
+ // Remove protocol fields from the response
776
+ if (typeof data.response === 'object') {
777
+ data.response = omit(data.response, fields);
778
+ }
779
+ const params = { ...req.body, ...req.query, ...req.params };
780
+ const token = params[tokenKey];
781
+ const store = token ? await tokenStorage.read(token) : null;
782
+ const extraParams = store?.extraParams ?? {};
783
+ const signedData = await authenticator.signResponse(data, prepareBaseUrl(req, extraParams), req, extraParams);
784
+ // debug('ensureSignedJson.do', signed);
785
+ originJsonp.call(res, encrypt(signedData, store));
786
+ };
787
+ }
788
+ const { token, store, locale } = req.context;
789
+ if (!token || !store) {
790
+ return res.jsonp({ error: errors.token404[locale] });
791
+ }
792
+ next();
793
+ };
794
+ return {
795
+ generateSession,
796
+ expireSession,
797
+ checkSession,
798
+ onAuthRequest,
799
+ onAuthResponse,
800
+ ensureContext,
801
+ ensureSignedJson,
802
+ createExtraParams,
803
+ };
804
+ }
805
+ //# sourceMappingURL=util.js.map