@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
package/README.md DELETED
@@ -1,210 +0,0 @@
1
- ![did-connect](https://www.arcblock.io/.netlify/functions/badge/?text=did-connect)
2
-
3
- [![docs](https://img.shields.io/badge/powered%20by-arcblock-green.svg)](https://docs.arcblock.io)
4
- [![Gitter](https://badges.gitter.im/ArcBlock/community.svg)](https://gitter.im/ArcBlock/community?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge)
5
-
6
- ## Overview
7
-
8
- 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.
9
-
10
- Within a typical DID Connect Session, the application may request user to sign a transaction or provide some information, such as:
11
-
12
- - Provide a user profile, which may contain name, email
13
- - Prove ownership of a NFT
14
- - Prove ownership of a passport
15
-
16
- The following diagram demonstrates how a typical DID Connect Session works:
17
-
18
- ![](./docs/workflow.png)
19
-
20
- `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.
21
-
22
- ## Install
23
-
24
- ```sh
25
- npm install @arcblock/did-connect-js
26
- // or
27
- bun install @arcblock/did-connect-js
28
- ```
29
-
30
- ## Usage
31
-
32
- ### Basic Usage
33
-
34
- ```js
35
- const SimpleStorage = require('@arcblock/did-connect-storage-nedb');
36
- const { fromRandom } = require('@ocap/wallet');
37
- const { WalletAuthenticator, WalletHandlers } = require('@arcblock/did-connect-js');
38
-
39
- // First setup authenticator and handler factory
40
- const wallet = fromRandom();
41
- const authenticator = new WalletAuthenticator({
42
- wallet,
43
- baseUrl: 'http://wangshijun.natapp1.cc',
44
- appInfo: {
45
- description: 'Starter projects to develop web application on forge',
46
- icon: '/images/logo@2x.png',
47
- name: 'Forge Web Starter',
48
- },
49
- chainInfo: {
50
- host: 'http://did-workshop.arcblock.co:8210/api',
51
- id: 'forge',
52
- },
53
- });
54
-
55
- const handlers = new WalletHandlers({
56
- authenticator,
57
- tokenStorage: new SimpleStorage({ dbPath: '/tmp/test/auth.db' }),
58
- });
59
-
60
- // Then attach handler to express server
61
- const express = require('express');
62
- const app = express();
63
-
64
- // This is required if you want to use dynamic baseUrl inference
65
- app.set('trust proxy', true);
66
-
67
- handlers.attach({
68
- action: 'profile',
69
- claims: {
70
- // This function can be async or returns a promise
71
- profile: () => ({
72
- fields: ['fullName', 'email'],
73
- description: 'Please provide your name and email to continue',
74
- }),
75
- },
76
-
77
- onAuth: async ({ userDid, claims, extraParams }) => {
78
- // `userDid` is the current connected did
79
- // `claims` contains what the user has submitted
80
- // `extraParams` is set from webapp when creating the session
81
- try {
82
- const profile = claims.find((x) => x.type === 'profile');
83
- console.info('login.success', { userDid, profile });
84
- } catch (err) {
85
- console.error('login.error', err);
86
- }
87
- },
88
- });
89
- ```
90
-
91
- 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).
92
-
93
- ### Multiple Claims
94
-
95
- You can request multiple claims in a single DID Connect Session:
96
-
97
- ```js
98
- handlers.attach({
99
- action: 'multiple-claims',
100
- claims: {
101
- profile: () => ({
102
- fields: ['fullName', 'email'],
103
- description: 'Please provide your name and email to continue',
104
- }),
105
- asset: ({ userDid, extraParams }) => {
106
- // `userDid` is the current connected did
107
- // `extraParams` is set from webapp when creating the session
108
- return {
109
- description: 'Please provide a valid NFT',
110
- trustedIssuers: ['nft-issuer-did'],
111
- };
112
- },
113
- },
114
- onAuth: async ({ claims, userDid }) => {
115
- // `claims` contains both the profile and the asset claim
116
- },
117
- });
118
- ```
119
-
120
- If you want to provide multiple claims of the same type:
121
-
122
- ```js
123
- handlers.attach({
124
- action: 'multiple-claims',
125
- claims: {
126
- signText: [
127
- 'signature',
128
- {
129
- type: 'mime:text/plain',
130
- data: 'xxxx',
131
- description: 'sign the text to continue',
132
- },
133
- ],
134
- signHtml: [
135
- 'signature',
136
- {
137
- type: 'mime:text/html',
138
- data: `<h2>This is title</h2>`,
139
- description: 'sign the html to continue',
140
- },
141
- ],
142
- },
143
- onAuth: async ({ claims, userDid }) => {
144
- // `claims` contains both the profile and the asset claim
145
- },
146
- });
147
- ```
148
-
149
- ### Dynamic Claims
150
-
151
- By returning a claims object from `onConnect` callback, you can provide dynamic claims for the DID Connect Session.
152
-
153
- ```js
154
- handlers.attach({
155
- action: 'dynamic-claims',
156
-
157
- // Can be async or returns a promise
158
- onConnect: ({ userDid }) => {
159
- // check userDid for some business logic
160
- // then return the claim object
161
- // you can return multiple claims here
162
- return {
163
- profile: () => ({
164
- fields: ['fullName', 'email'],
165
- description: 'Please provide your name and email to continue',
166
- }),
167
- };
168
- },
169
-
170
- onAuth: async ({ claims, userDid }) => {
171
- // `claims` now contains the result for the dynamic claim
172
- },
173
- });
174
- ```
175
-
176
- ## Lifecycle Callbacks
177
-
178
- Following callbacks are supported during the lifecycle of a DID-Connect session.
179
-
180
- - `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.
181
- - `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.
182
- - `onDecline({ req, challenge, userDid, userPk, extraParams, updateSession })`: optional, when wallet has rejected dapp request.
183
- - `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.
184
- - `onComplete({ req, userDid, userPk, extraParams, updateSession })`: optional, when the did connect session has completed.
185
- - `onExpire({ extraParams })`: optional, when the did connect session has expired.
186
- - `onError({ err, extraParams })`: optional, when the did connect session encountered some error, default to `console.error`.
187
-
188
- Most commonly used callbacks are `onConnect` and `onAuth`.
189
-
190
- 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.
191
-
192
- 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,
193
-
194
- ```js
195
- handlers.attach({
196
- action: 'dynamic-claims',
197
-
198
- onAuth: ({ userDid, updateSession }) => {
199
- // to persist plain non-sensible info
200
- await updateSession({ key: 'non-sensible' });
201
-
202
- // to persist sensible info: that need to be encrypted
203
- await updateSession({ key: 'sensible' }, true);
204
- },
205
- });
206
- ```
207
-
208
- ## Claims
209
-
210
- 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).
@@ -1,8 +0,0 @@
1
- import { createRequire } from "node:module";
2
-
3
- //#region rolldown:runtime
4
- var __commonJSMin = (cb, mod) => () => (mod || cb((mod = { exports: {} }).exports, mod), mod.exports);
5
- var __require = /* @__PURE__ */ createRequire(import.meta.url);
6
-
7
- //#endregion
8
- export { __commonJSMin, __require };
@@ -1,11 +0,0 @@
1
- //#region src/adapters/detect.d.ts
2
- /**
3
- * Detect whether an app object is Express or Hono.
4
- *
5
- * Express: has set(), engine(), and lazyrouter() or _router
6
- * Hono: has fetch() method + basePath property, no Express set/engine
7
- */
8
- declare function isExpressApp(app: any): boolean;
9
- declare function isHonoApp(app: any): boolean;
10
- //#endregion
11
- export { isExpressApp, isHonoApp };
@@ -1,16 +0,0 @@
1
- //#region src/adapters/detect.ts
2
- /**
3
- * Detect whether an app object is Express or Hono.
4
- *
5
- * Express: has set(), engine(), and lazyrouter() or _router
6
- * Hono: has fetch() method + basePath property, no Express set/engine
7
- */
8
- function isExpressApp(app) {
9
- return typeof app?.set === "function" && typeof app?.engine === "function";
10
- }
11
- function isHonoApp(app) {
12
- return typeof app?.fetch === "function" && !isExpressApp(app);
13
- }
14
-
15
- //#endregion
16
- export { isExpressApp, isHonoApp };
@@ -1,48 +0,0 @@
1
- import { ConnectRequest, ConnectResponse, NextFunction } from "../types.mjs";
2
-
3
- //#region src/adapters/express.d.ts
4
- interface ExpressLikeApp {
5
- use(path: string, ...handlers: any[]): void;
6
- get(path: string, ...handlers: any[]): void;
7
- post(path: string, ...handlers: any[]): void;
8
- }
9
- interface HandlerFunctions {
10
- generateSession: (req: ConnectRequest, res: ConnectResponse) => Promise<void>;
11
- checkSession: (req: ConnectRequest, res: ConnectResponse) => Promise<void>;
12
- expireSession: (req: ConnectRequest, res: ConnectResponse) => Promise<void>;
13
- onAuthRequest: (req: ConnectRequest, res: ConnectResponse) => Promise<void>;
14
- onAuthResponse: (req: ConnectRequest, res: ConnectResponse) => Promise<void>;
15
- ensureContext: (req: ConnectRequest, res: ConnectResponse, next: NextFunction) => Promise<void>;
16
- ensureSignedJson: (req: ConnectRequest, res: ConnectResponse, next: NextFunction) => void;
17
- }
18
- interface AttachExpressOptions {
19
- app: ExpressLikeApp;
20
- prefix: string;
21
- action: string;
22
- handlers: HandlerFunctions;
23
- }
24
- /**
25
- * Register DID Connect routes on an Express-compatible app.
26
- *
27
- * Routes registered:
28
- * - GET/POST `{prefix}/{action}/token` — generate session
29
- * - GET `{prefix}/{action}/status` — check session status
30
- * - GET `{prefix}/{action}/timeout` — expire session
31
- * - GET `{prefix}/{action}/auth` — wallet fetches auth request
32
- * - POST `{prefix}/{action}/auth` — wallet submits auth response
33
- * - GET `{prefix}/{action}/auth/submit` — web wallet submit
34
- */
35
- declare function attachExpress({
36
- app,
37
- prefix,
38
- action,
39
- handlers
40
- }: AttachExpressOptions): {
41
- generateSession: (req: ConnectRequest, res: ConnectResponse) => Promise<void>;
42
- expireSession: (req: ConnectRequest, res: ConnectResponse) => Promise<void>;
43
- checkSession: (req: ConnectRequest, res: ConnectResponse) => Promise<void>;
44
- onAuthRequest: (req: ConnectRequest, res: ConnectResponse) => Promise<void>;
45
- onAuthResponse: (req: ConnectRequest, res: ConnectResponse) => Promise<void>;
46
- };
47
- //#endregion
48
- export { AttachExpressOptions, ExpressLikeApp, HandlerFunctions, attachExpress };
@@ -1,39 +0,0 @@
1
- import cors from "cors";
2
-
3
- //#region src/adapters/express.ts
4
- /**
5
- * Register DID Connect routes on an Express-compatible app.
6
- *
7
- * Routes registered:
8
- * - GET/POST `{prefix}/{action}/token` — generate session
9
- * - GET `{prefix}/{action}/status` — check session status
10
- * - GET `{prefix}/{action}/timeout` — expire session
11
- * - GET `{prefix}/{action}/auth` — wallet fetches auth request
12
- * - POST `{prefix}/{action}/auth` — wallet submits auth response
13
- * - GET `{prefix}/{action}/auth/submit` — web wallet submit
14
- */
15
- function attachExpress({ app, prefix, action, handlers }) {
16
- const pathname = `${prefix}/${action}/auth`;
17
- const { generateSession, checkSession, expireSession, onAuthRequest, onAuthResponse, ensureContext, ensureSignedJson } = handlers;
18
- app.use(`${prefix}/${action}`, cors({
19
- origin: "*",
20
- optionsSuccessStatus: 204
21
- }));
22
- app.get(`${prefix}/${action}/token`, generateSession);
23
- app.post(`${prefix}/${action}/token`, generateSession);
24
- app.get(`${prefix}/${action}/status`, ensureContext, checkSession);
25
- app.get(`${prefix}/${action}/timeout`, ensureContext, expireSession);
26
- app.get(pathname, ensureContext, ensureSignedJson, onAuthRequest);
27
- app.post(pathname, ensureContext, ensureSignedJson, onAuthResponse);
28
- app.get(`${pathname}/submit`, ensureContext, ensureSignedJson, onAuthResponse);
29
- return {
30
- generateSession,
31
- expireSession,
32
- checkSession,
33
- onAuthRequest,
34
- onAuthResponse
35
- };
36
- }
37
-
38
- //#endregion
39
- export { attachExpress };
@@ -1,57 +0,0 @@
1
- import { ConnectRequest, ConnectResponse } from "../types.mjs";
2
- import { HandlerFunctions } from "./express.mjs";
3
-
4
- //#region src/adapters/hono.d.ts
5
- interface HonoLikeApp {
6
- get(path: string, handler: (c: any) => any): void;
7
- post(path: string, handler: (c: any) => any): void;
8
- use(path: string, handler: any): void;
9
- }
10
- interface AttachHonoOptions {
11
- app: HonoLikeApp;
12
- prefix: string;
13
- action: string;
14
- handlers: HandlerFunctions;
15
- }
16
- /**
17
- * Create a ConnectRequest from a Hono-like Context.
18
- *
19
- * @param c - Hono Context object
20
- * @param bodyCache - Pre-parsed request body (since c.req.json() is async)
21
- */
22
- declare function createHonoRequest(c: any, bodyCache?: any): ConnectRequest;
23
- /**
24
- * Create a ConnectResponse that buffers the handler's response.
25
- * The Hono route wrapper reads the buffer via _getResult() to return c.json().
26
- */
27
- declare function createHonoResponse(): ConnectResponse & {
28
- _getResult(): {
29
- statusCode: number;
30
- body: any;
31
- } | null;
32
- };
33
- /**
34
- * Register DID Connect routes on a Hono-compatible app.
35
- *
36
- * Routes registered are the same as attachExpress:
37
- * - GET/POST `{prefix}/{action}/token`
38
- * - GET `{prefix}/{action}/status`
39
- * - GET `{prefix}/{action}/timeout`
40
- * - GET `{prefix}/{action}/auth`
41
- * - POST `{prefix}/{action}/auth`
42
- * - GET `{prefix}/{action}/auth/submit`
43
- */
44
- declare function attachHono({
45
- app,
46
- prefix,
47
- action,
48
- handlers
49
- }: AttachHonoOptions): {
50
- generateSession: (req: ConnectRequest, res: ConnectResponse) => Promise<void>;
51
- expireSession: (req: ConnectRequest, res: ConnectResponse) => Promise<void>;
52
- checkSession: (req: ConnectRequest, res: ConnectResponse) => Promise<void>;
53
- onAuthRequest: (req: ConnectRequest, res: ConnectResponse) => Promise<void>;
54
- onAuthResponse: (req: ConnectRequest, res: ConnectResponse) => Promise<void>;
55
- };
56
- //#endregion
57
- export { AttachHonoOptions, HonoLikeApp, attachHono, createHonoRequest, createHonoResponse };
@@ -1,164 +0,0 @@
1
- //#region src/adapters/hono.ts
2
- /**
3
- * Parse a raw Cookie header string into a key-value map.
4
- */
5
- function parseCookieHeader(header) {
6
- const cookies = {};
7
- if (!header) return cookies;
8
- for (const pair of header.split(";")) {
9
- const idx = pair.indexOf("=");
10
- if (idx > 0) {
11
- const key = pair.slice(0, idx).trim();
12
- const val = pair.slice(idx + 1).trim();
13
- cookies[key] = decodeURIComponent(val);
14
- }
15
- }
16
- return cookies;
17
- }
18
- /**
19
- * Simple Accept-Language negotiation matching Express's req.acceptsLanguages().
20
- * Only needs to handle the two languages used by DID Connect: 'en-US' and 'zh-CN'.
21
- */
22
- function negotiateLanguage(acceptHeader, ...langs) {
23
- if (!acceptHeader || langs.length === 0) return langs[0] || false;
24
- const lower = acceptHeader.toLowerCase();
25
- for (const lang of langs) {
26
- const prefix = lang.toLowerCase().split("-")[0];
27
- if (lower.includes(lang.toLowerCase()) || lower.includes(prefix)) return lang;
28
- }
29
- return langs[0] || false;
30
- }
31
- /**
32
- * Create a ConnectRequest from a Hono-like Context.
33
- *
34
- * @param c - Hono Context object
35
- * @param bodyCache - Pre-parsed request body (since c.req.json() is async)
36
- */
37
- function createHonoRequest(c, bodyCache = {}) {
38
- const url = new URL(c.req.url);
39
- const rawHeaders = {};
40
- if (c.req.raw?.headers) c.req.raw.headers.forEach((value, key) => {
41
- rawHeaders[key.toLowerCase()] = value;
42
- });
43
- return {
44
- body: bodyCache,
45
- query: Object.fromEntries(url.searchParams.entries()),
46
- params: typeof c.req.param === "function" ? c.req.param() : {},
47
- headers: rawHeaders,
48
- cookies: parseCookieHeader(rawHeaders.cookie || ""),
49
- protocol: url.protocol.replace(":", ""),
50
- originalUrl: url.pathname + url.search,
51
- get(name) {
52
- return rawHeaders[name.toLowerCase()];
53
- },
54
- acceptsLanguages(...langs) {
55
- return negotiateLanguage(rawHeaders["accept-language"] || "", ...langs);
56
- },
57
- raw: c
58
- };
59
- }
60
- /**
61
- * Create a ConnectResponse that buffers the handler's response.
62
- * The Hono route wrapper reads the buffer via _getResult() to return c.json().
63
- */
64
- function createHonoResponse() {
65
- let result = null;
66
- return {
67
- jsonp(data) {
68
- result = {
69
- statusCode: 200,
70
- body: data
71
- };
72
- },
73
- json(data) {
74
- result = {
75
- statusCode: 200,
76
- body: data
77
- };
78
- },
79
- status(code) {
80
- return { json(data) {
81
- result = {
82
- statusCode: code,
83
- body: data
84
- };
85
- } };
86
- },
87
- _getResult() {
88
- return result;
89
- }
90
- };
91
- }
92
- /**
93
- * Wrap a middleware chain + handler into a single Hono route handler.
94
- * Runs middlewares sequentially with manual next() control,
95
- * then runs the handler, then returns the buffered response.
96
- */
97
- function wrapHandler(middlewares, handler) {
98
- return async (c) => {
99
- let body = {};
100
- try {
101
- const text = await c.req.text();
102
- if (text) {
103
- const contentType = c.req.header("content-type") || "";
104
- if (contentType.includes("json")) body = JSON.parse(text);
105
- else if (contentType.includes("urlencoded")) body = Object.fromEntries(new URLSearchParams(text).entries());
106
- }
107
- } catch {}
108
- const req = createHonoRequest(c, body);
109
- const res = createHonoResponse();
110
- for (const mw of middlewares) {
111
- let nextCalled = false;
112
- await mw(req, res, () => {
113
- nextCalled = true;
114
- });
115
- if (!nextCalled) {
116
- const r$1 = res._getResult();
117
- if (r$1) return c.json(r$1.body, r$1.statusCode);
118
- return c.json({ error: "Unknown error" }, 500);
119
- }
120
- }
121
- await handler(req, res);
122
- const r = res._getResult();
123
- return c.json(r?.body ?? {}, r?.statusCode ?? 200);
124
- };
125
- }
126
- /**
127
- * Register DID Connect routes on a Hono-compatible app.
128
- *
129
- * Routes registered are the same as attachExpress:
130
- * - GET/POST `{prefix}/{action}/token`
131
- * - GET `{prefix}/{action}/status`
132
- * - GET `{prefix}/{action}/timeout`
133
- * - GET `{prefix}/{action}/auth`
134
- * - POST `{prefix}/{action}/auth`
135
- * - GET `{prefix}/{action}/auth/submit`
136
- */
137
- function attachHono({ app, prefix, action, handlers }) {
138
- const pathname = `${prefix}/${action}/auth`;
139
- const { generateSession, checkSession, expireSession, onAuthRequest, onAuthResponse, ensureContext, ensureSignedJson } = handlers;
140
- app.use(`${prefix}/${action}/*`, async (c, next) => {
141
- c.header("Access-Control-Allow-Origin", "*");
142
- c.header("Access-Control-Allow-Methods", "GET, POST, OPTIONS");
143
- c.header("Access-Control-Allow-Headers", "Content-Type, Authorization");
144
- if (c.req.method === "OPTIONS") return c.text("", 204);
145
- await next();
146
- });
147
- app.get(`${prefix}/${action}/token`, wrapHandler([], generateSession));
148
- app.post(`${prefix}/${action}/token`, wrapHandler([], generateSession));
149
- app.get(`${prefix}/${action}/status`, wrapHandler([ensureContext], checkSession));
150
- app.get(`${prefix}/${action}/timeout`, wrapHandler([ensureContext], expireSession));
151
- app.get(pathname, wrapHandler([ensureContext, ensureSignedJson], onAuthRequest));
152
- app.post(pathname, wrapHandler([ensureContext, ensureSignedJson], onAuthResponse));
153
- app.get(`${pathname}/submit`, wrapHandler([ensureContext, ensureSignedJson], onAuthResponse));
154
- return {
155
- generateSession,
156
- expireSession,
157
- checkSession,
158
- onAuthRequest,
159
- onAuthResponse
160
- };
161
- }
162
-
163
- //#endregion
164
- export { attachHono, createHonoRequest, createHonoResponse };
@@ -1,23 +0,0 @@
1
- import * as Jwt from "@arcblock/jwt";
2
-
3
- //#region src/authenticator/base.d.ts
4
- declare const DEFAULT_CHAIN_INFO: {
5
- id: string;
6
- host: string;
7
- type: string;
8
- };
9
- declare class BaseAuthenticator {
10
- _validateWallet(wallet: any, canSign?: boolean): any;
11
- /**
12
- * Verify a DID auth response sent from DID Wallet
13
- *
14
- * @method
15
- * @param {object} data
16
- * @param {string} [locale=en]
17
- * @param {boolean} [enforceTimestamp=true]
18
- * @returns Promise<boolean>
19
- */
20
- _verify(data: any, fieldPk: string, fieldInfo: string, locale?: string, enforceTimestamp?: boolean): Promise<Jwt.JwtBody>;
21
- }
22
- //#endregion
23
- export { DEFAULT_CHAIN_INFO, BaseAuthenticator as default };
@@ -1,88 +0,0 @@
1
- import { __require } from "../_virtual/rolldown_runtime.mjs";
2
- import { require_package } from "../did/did-connect/package.mjs";
3
- import { fromJSON, isValid } from "@ocap/wallet";
4
- import * as Jwt from "@arcblock/jwt";
5
-
6
- //#region src/authenticator/base.ts
7
- const debug = __require("debug")(`${require_package().name}:authenticator:base`);
8
- const DEFAULT_CHAIN_INFO = {
9
- id: "none",
10
- host: "none",
11
- type: "arcblock"
12
- };
13
- var BaseAuthenticator = class {
14
- _validateWallet(wallet, canSign = true) {
15
- if (!wallet) throw new Error("WalletAuthenticator cannot work without wallet");
16
- if (typeof wallet === "function") return wallet;
17
- if (isValid(wallet, canSign)) {
18
- if (!wallet.pk && wallet.publicKey) wallet.pk = wallet.publicKey;
19
- if (!wallet.sk && wallet.secretKey) wallet.sk = wallet.secretKey;
20
- return wallet;
21
- }
22
- if (canSign && !wallet.sk) throw new Error("WalletAuthenticator cannot work without wallet.sk");
23
- if (!wallet.pk) throw new Error("WalletAuthenticator cannot work without wallet.pk");
24
- if (!wallet.address) throw new Error("WalletAuthenticator cannot work without wallet.address");
25
- try {
26
- const fullWallet = fromJSON(wallet);
27
- if (!fullWallet.pk && fullWallet.publicKey) fullWallet.pk = fullWallet.publicKey;
28
- if (!fullWallet.sk && fullWallet.secretKey) fullWallet.sk = fullWallet.secretKey;
29
- return fullWallet;
30
- } catch (_err) {
31
- return wallet;
32
- }
33
- }
34
- /**
35
- * Verify a DID auth response sent from DID Wallet
36
- *
37
- * @method
38
- * @param {object} data
39
- * @param {string} [locale=en]
40
- * @param {boolean} [enforceTimestamp=true]
41
- * @returns Promise<boolean>
42
- */
43
- async _verify(data, fieldPk, fieldInfo, locale = "en", enforceTimestamp = true) {
44
- debug("verify", data, locale);
45
- const errors = {
46
- pkMissing: {
47
- en: `${fieldPk} is required to complete auth`,
48
- zh: `${fieldPk} 参数缺失`
49
- },
50
- tokenMissing: {
51
- en: `${fieldInfo} is required to complete auth`,
52
- zh: "JWT Token 参数缺失"
53
- },
54
- pkFormat: {
55
- en: `${fieldPk} should be either base58 or base16 format`,
56
- zh: `${fieldPk} 无法解析`
57
- },
58
- tokenInvalid: {
59
- en: "Invalid JWT token",
60
- zh: "签名无效"
61
- },
62
- timeInvalid: {
63
- en: "JWT token expired, make sure your device time in sync with network",
64
- zh: "签名中的时间戳无效,请确保设备和网络时间同步"
65
- }
66
- };
67
- const pk = data[fieldPk];
68
- const info = data[fieldInfo];
69
- if (!pk) throw new Error(errors.pkMissing[locale]);
70
- if (!info) throw new Error(errors.tokenMissing[locale]);
71
- if (!pk) throw new Error(errors.pkFormat[locale]);
72
- if (!await Jwt.verify(info, pk)) {
73
- const isValidSig = await Jwt.verify(info, pk, {
74
- tolerance: 0,
75
- enforceTimestamp: false
76
- });
77
- if (enforceTimestamp) {
78
- const error = isValidSig ? errors.timeInvalid[locale] : errors.tokenInvalid[locale];
79
- throw new Error(error);
80
- }
81
- }
82
- return Jwt.decode(info);
83
- }
84
- };
85
- var base_default = BaseAuthenticator;
86
-
87
- //#endregion
88
- export { DEFAULT_CHAIN_INFO, base_default as default };