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