@atproto/lex-server 0.0.0-spaces-alpha-20260818163953
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +393 -0
- package/LICENSE.txt +7 -0
- package/README.md +615 -0
- package/dist/errors.d.ts +78 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +124 -0
- package/dist/errors.js.map +1 -0
- package/dist/index.d.ts +4 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +4 -0
- package/dist/index.js.map +1 -0
- package/dist/lex-router.d.ts +597 -0
- package/dist/lex-router.d.ts.map +1 -0
- package/dist/lex-router.js +491 -0
- package/dist/lex-router.js.map +1 -0
- package/dist/lib/drain-websocket.d.ts +13 -0
- package/dist/lib/drain-websocket.d.ts.map +1 -0
- package/dist/lib/drain-websocket.js +24 -0
- package/dist/lib/drain-websocket.js.map +1 -0
- package/dist/lib/sleep.d.ts +2 -0
- package/dist/lib/sleep.d.ts.map +1 -0
- package/dist/lib/sleep.js +19 -0
- package/dist/lib/sleep.js.map +1 -0
- package/dist/lib/www-authenticate.d.ts +74 -0
- package/dist/lib/www-authenticate.d.ts.map +1 -0
- package/dist/lib/www-authenticate.js +60 -0
- package/dist/lib/www-authenticate.js.map +1 -0
- package/dist/nodejs.d.ts +312 -0
- package/dist/nodejs.d.ts.map +1 -0
- package/dist/nodejs.js +442 -0
- package/dist/nodejs.js.map +1 -0
- package/dist/service-auth.d.ts +209 -0
- package/dist/service-auth.d.ts.map +1 -0
- package/dist/service-auth.js +225 -0
- package/dist/service-auth.js.map +1 -0
- package/package.json +61 -0
package/README.md
ADDED
|
@@ -0,0 +1,615 @@
|
|
|
1
|
+
# @atproto/lex-server
|
|
2
|
+
|
|
3
|
+
Request router for Atproto Lexicon protocols and schemas. See the [Changelog](./CHANGELOG.md) for version history.
|
|
4
|
+
|
|
5
|
+
```bash
|
|
6
|
+
npm install @atproto/lex-server
|
|
7
|
+
```
|
|
8
|
+
|
|
9
|
+
- Type-safe request routing based on Lexicon schemas
|
|
10
|
+
- Support for queries, procedures, and WebSocket subscriptions
|
|
11
|
+
- Built on Web standard `Request`/`Response` APIs (portable across runtimes)
|
|
12
|
+
- Custom authentication with credential passing
|
|
13
|
+
- Graceful shutdown with `AsyncDisposable` pattern
|
|
14
|
+
|
|
15
|
+
> [!IMPORTANT]
|
|
16
|
+
>
|
|
17
|
+
> This package is currently in **preview**. The API and features are subject to change before the stable release.
|
|
18
|
+
|
|
19
|
+
**What is this?**
|
|
20
|
+
|
|
21
|
+
Building AT Protocol servers requires handling XRPC requests, validating inputs against Lexicon schemas, managing authentication, and supporting real-time subscriptions. `@atproto/lex-server` automates this by:
|
|
22
|
+
|
|
23
|
+
1. Routing requests to type-safe handlers based on Lexicon schemas
|
|
24
|
+
2. Automatically validating request parameters and bodies
|
|
25
|
+
3. Providing a flexible authentication system with custom strategies
|
|
26
|
+
4. Supporting WebSocket subscriptions with backpressure handling
|
|
27
|
+
|
|
28
|
+
```typescript
|
|
29
|
+
import { LexRouter } from '@atproto/lex-server'
|
|
30
|
+
import { serve, upgradeWebSocket } from '@atproto/lex-server/nodejs'
|
|
31
|
+
import * as app from './lexicons/app.js'
|
|
32
|
+
|
|
33
|
+
const router = new LexRouter({ upgradeWebSocket })
|
|
34
|
+
.add(app.bsky.actor.getProfile, async ({ params }) => {
|
|
35
|
+
const profile = await db.getProfile(params.actor)
|
|
36
|
+
return { body: profile }
|
|
37
|
+
})
|
|
38
|
+
.add(app.bsky.feed.post.create, {
|
|
39
|
+
auth: requireAuth,
|
|
40
|
+
handler: async ({ credentials, input }) => {
|
|
41
|
+
const result = await db.createPost(credentials.did, input.body)
|
|
42
|
+
return { body: result }
|
|
43
|
+
},
|
|
44
|
+
})
|
|
45
|
+
|
|
46
|
+
await serve(router, { port: 3000 })
|
|
47
|
+
```
|
|
48
|
+
|
|
49
|
+
<!-- START doctoc generated TOC please keep comment here to allow auto update -->
|
|
50
|
+
<!-- DON'T EDIT THIS SECTION, INSTEAD RE-RUN doctoc TO UPDATE -->
|
|
51
|
+
|
|
52
|
+
- [Quick Start](#quick-start)
|
|
53
|
+
- [LexRouter](#lexrouter)
|
|
54
|
+
- [Creating a Router](#creating-a-router)
|
|
55
|
+
- [Adding Routes](#adding-routes)
|
|
56
|
+
- [Handler Context](#handler-context)
|
|
57
|
+
- [Handler Output](#handler-output)
|
|
58
|
+
- [Queries and Procedures](#queries-and-procedures)
|
|
59
|
+
- [Query Handler](#query-handler)
|
|
60
|
+
- [Procedure Handler](#procedure-handler)
|
|
61
|
+
- [Binary Payloads](#binary-payloads)
|
|
62
|
+
- [Subscriptions](#subscriptions)
|
|
63
|
+
- [Authentication](#authentication)
|
|
64
|
+
- [Custom Authentication](#custom-authentication)
|
|
65
|
+
- [WWW-Authenticate Headers](#www-authenticate-headers)
|
|
66
|
+
- [Error Handling](#error-handling)
|
|
67
|
+
- [LexServerError](#lexservererror)
|
|
68
|
+
- [LexServerAuthError](#lexserverautherror)
|
|
69
|
+
- [Error Handler Callback](#error-handler-callback)
|
|
70
|
+
- [Node.js Server](#nodejs-server)
|
|
71
|
+
- [serve()](#serve)
|
|
72
|
+
- [createServer()](#createserver)
|
|
73
|
+
- [toRequestListener()](#torequestlistener)
|
|
74
|
+
- [upgradeWebSocket()](#upgradewebsocket)
|
|
75
|
+
- [Advanced Usage](#advanced-usage)
|
|
76
|
+
- [Custom Response Objects](#custom-response-objects)
|
|
77
|
+
- [Response Headers](#response-headers)
|
|
78
|
+
- [Connection Info](#connection-info)
|
|
79
|
+
- [License](#license)
|
|
80
|
+
|
|
81
|
+
<!-- END doctoc generated TOC please keep comment here to allow auto update -->
|
|
82
|
+
|
|
83
|
+
## Quick Start
|
|
84
|
+
|
|
85
|
+
**1. Install the package**
|
|
86
|
+
|
|
87
|
+
```bash
|
|
88
|
+
npm install @atproto/lex-server
|
|
89
|
+
```
|
|
90
|
+
|
|
91
|
+
**2. Generate Lexicon schemas**
|
|
92
|
+
|
|
93
|
+
Use `@atproto/lex` to generate TypeScript schemas from your Lexicon definitions:
|
|
94
|
+
|
|
95
|
+
```bash
|
|
96
|
+
lex install app.bsky.actor.getProfile
|
|
97
|
+
lex build
|
|
98
|
+
```
|
|
99
|
+
|
|
100
|
+
**3. Create a router and add handlers**
|
|
101
|
+
|
|
102
|
+
```typescript
|
|
103
|
+
import { LexRouter, LexServerError } from '@atproto/lex-server'
|
|
104
|
+
import { serve, upgradeWebSocket } from '@atproto/lex-server/nodejs'
|
|
105
|
+
import * as app from './lexicons/app.js'
|
|
106
|
+
|
|
107
|
+
const router = new LexRouter({ upgradeWebSocket })
|
|
108
|
+
|
|
109
|
+
// Add a query handler
|
|
110
|
+
router.add(app.bsky.actor.getProfile, async ({ params }) => {
|
|
111
|
+
const profile = await db.getProfile(params.actor)
|
|
112
|
+
if (!profile) {
|
|
113
|
+
throw new LexServerError(404, {
|
|
114
|
+
error: 'NotFound',
|
|
115
|
+
message: 'Profile not found',
|
|
116
|
+
})
|
|
117
|
+
}
|
|
118
|
+
return { body: profile }
|
|
119
|
+
})
|
|
120
|
+
|
|
121
|
+
// Start the server
|
|
122
|
+
const server = await serve(router, { port: 3000 })
|
|
123
|
+
console.log('Server listening on port 3000')
|
|
124
|
+
```
|
|
125
|
+
|
|
126
|
+
## LexRouter
|
|
127
|
+
|
|
128
|
+
The `LexRouter` class is the core of `@atproto/lex-server`. It routes XRPC requests to type-safe handlers based on Lexicon schemas.
|
|
129
|
+
|
|
130
|
+
### Creating a Router
|
|
131
|
+
|
|
132
|
+
```typescript
|
|
133
|
+
import { LexRouter } from '@atproto/lex-server'
|
|
134
|
+
import { upgradeWebSocket } from '@atproto/lex-server/nodejs'
|
|
135
|
+
|
|
136
|
+
const router = new LexRouter({
|
|
137
|
+
// Required for WebSocket subscriptions (Node.js)
|
|
138
|
+
upgradeWebSocket,
|
|
139
|
+
|
|
140
|
+
// Optional: Add logging or error reporting for unexpected errors in handlers
|
|
141
|
+
onHandlerError: ({ error, request, method }) => {
|
|
142
|
+
console.error(`Error in ${method.nsid}:`, error)
|
|
143
|
+
},
|
|
144
|
+
|
|
145
|
+
// Optional: WebSocket backpressure settings
|
|
146
|
+
highWaterMark: 250_000, // bytes (default: 250KB)
|
|
147
|
+
lowWaterMark: 50_000, // bytes (default: 50KB)
|
|
148
|
+
})
|
|
149
|
+
```
|
|
150
|
+
|
|
151
|
+
### Adding Routes
|
|
152
|
+
|
|
153
|
+
Routes are added using the `.add()` method, which accepts a Lexicon schema and a handler:
|
|
154
|
+
|
|
155
|
+
```typescript
|
|
156
|
+
// Simple handler (no authentication)
|
|
157
|
+
router.add(schema, async ({ params, input, request }) => {
|
|
158
|
+
return { body: result }
|
|
159
|
+
})
|
|
160
|
+
|
|
161
|
+
// Handler with authentication
|
|
162
|
+
router.add(schema, {
|
|
163
|
+
auth: async ({ request, params }) => credentials,
|
|
164
|
+
handler: async ({ params, input, credentials, request }) => {
|
|
165
|
+
return { body: result }
|
|
166
|
+
},
|
|
167
|
+
})
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
The router supports method chaining:
|
|
171
|
+
|
|
172
|
+
```typescript
|
|
173
|
+
const router = new LexRouter()
|
|
174
|
+
.add(app.bsky.actor.getProfile, profileHandler)
|
|
175
|
+
.add(app.bsky.feed.getTimeline, timelineHandler)
|
|
176
|
+
.add(app.bsky.feed.post.create, postHandler)
|
|
177
|
+
```
|
|
178
|
+
|
|
179
|
+
### Handler Context
|
|
180
|
+
|
|
181
|
+
Handlers receive a context object with the following properties:
|
|
182
|
+
|
|
183
|
+
```typescript
|
|
184
|
+
type LexRouterHandlerContext<Method, Credentials> = {
|
|
185
|
+
credentials: Credentials // Result of auth function (undefined if no auth)
|
|
186
|
+
input: InferMethodInput<Method> // Parsed request body (procedures only)
|
|
187
|
+
params: InferMethodParams<Method> // Parsed URL query parameters
|
|
188
|
+
request: Request // Original Web Request object
|
|
189
|
+
connection?: ConnectionInfo // Network connection info
|
|
190
|
+
}
|
|
191
|
+
```
|
|
192
|
+
|
|
193
|
+
### Handler Output
|
|
194
|
+
|
|
195
|
+
Handlers can return various output formats:
|
|
196
|
+
|
|
197
|
+
```typescript
|
|
198
|
+
// JSON response (encoding inferred from schema)
|
|
199
|
+
return { body: { key: 'value' } }
|
|
200
|
+
|
|
201
|
+
// With custom encoding
|
|
202
|
+
return { encoding: 'text/plain', body: 'Hello, world!' }
|
|
203
|
+
|
|
204
|
+
// With response headers
|
|
205
|
+
return { body: data, headers: { 'x-custom': 'value' } }
|
|
206
|
+
|
|
207
|
+
// Empty response (200 OK with no body)
|
|
208
|
+
return {}
|
|
209
|
+
|
|
210
|
+
// Custom Response object (full control)
|
|
211
|
+
return new Response(body, { status: 201, headers })
|
|
212
|
+
|
|
213
|
+
// Proxy Response
|
|
214
|
+
return fetch('https://example.com/data')
|
|
215
|
+
```
|
|
216
|
+
|
|
217
|
+
## Queries and Procedures
|
|
218
|
+
|
|
219
|
+
### Query Handler
|
|
220
|
+
|
|
221
|
+
Queries handle `GET` requests and receive parameters from the URL query string:
|
|
222
|
+
|
|
223
|
+
```typescript
|
|
224
|
+
import * as app from './lexicons/app.js'
|
|
225
|
+
|
|
226
|
+
router.add(app.bsky.actor.getProfile, async ({ params }) => {
|
|
227
|
+
// params.actor is typed and validated
|
|
228
|
+
const profile = await db.getProfile(params.actor)
|
|
229
|
+
return { body: profile }
|
|
230
|
+
})
|
|
231
|
+
```
|
|
232
|
+
|
|
233
|
+
### Procedure Handler
|
|
234
|
+
|
|
235
|
+
Procedures handle `POST` requests and receive a request body:
|
|
236
|
+
|
|
237
|
+
```typescript
|
|
238
|
+
router.add(app.bsky.feed.post.create, async ({ input }) => {
|
|
239
|
+
// input.body contains the parsed and validated request body
|
|
240
|
+
const post = await db.createPost(input.body)
|
|
241
|
+
return { body: { uri: post.uri, cid: post.cid } }
|
|
242
|
+
})
|
|
243
|
+
```
|
|
244
|
+
|
|
245
|
+
### Binary Payloads
|
|
246
|
+
|
|
247
|
+
For endpoints that accept or return binary data:
|
|
248
|
+
|
|
249
|
+
```typescript
|
|
250
|
+
// Binary input
|
|
251
|
+
router.add(app.example.uploadBlob, async ({ input }) => {
|
|
252
|
+
// input.body is a Request object for streaming
|
|
253
|
+
// input.encoding contains the content-type
|
|
254
|
+
const blob = await input.body.arrayBuffer()
|
|
255
|
+
return { body: { cid: await store(blob) } }
|
|
256
|
+
})
|
|
257
|
+
|
|
258
|
+
// Binary output
|
|
259
|
+
router.add(app.example.getBlob, async ({ params }) => {
|
|
260
|
+
const stream = await getBlob(params.cid)
|
|
261
|
+
return {
|
|
262
|
+
encoding: 'application/octet-stream',
|
|
263
|
+
body: stream,
|
|
264
|
+
}
|
|
265
|
+
})
|
|
266
|
+
```
|
|
267
|
+
|
|
268
|
+
## Subscriptions
|
|
269
|
+
|
|
270
|
+
Subscriptions provide real-time data over WebSocket connections. Handlers are async generators that yield messages:
|
|
271
|
+
|
|
272
|
+
```typescript
|
|
273
|
+
import { LexRouter, LexError } from '@atproto/lex-server'
|
|
274
|
+
import { serve, upgradeWebSocket } from '@atproto/lex-server/nodejs'
|
|
275
|
+
import { scheduler } from 'node:timers/promises'
|
|
276
|
+
|
|
277
|
+
const router = new LexRouter({
|
|
278
|
+
upgradeWebSocket, // Required for WebSocket support in nodejs
|
|
279
|
+
})
|
|
280
|
+
|
|
281
|
+
router.add(com.example.stream, async function* ({ params, request }) {
|
|
282
|
+
const { cursor = 0, limit = 10 } = params
|
|
283
|
+
const { signal } = request
|
|
284
|
+
|
|
285
|
+
for (let i = 0; i < limit; i++) {
|
|
286
|
+
// Yield messages to the client
|
|
287
|
+
yield com.example.stream.message.$build({
|
|
288
|
+
data: `Message ${cursor + i}`,
|
|
289
|
+
cursor: cursor + i,
|
|
290
|
+
})
|
|
291
|
+
|
|
292
|
+
// Wait between messages (respects abort signal)
|
|
293
|
+
await scheduler.wait(1000, { signal })
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
// Throwing a LexError closes the connection with an error frame
|
|
297
|
+
throw new LexError('LimitReached', `Limit of ${limit} messages reached`)
|
|
298
|
+
})
|
|
299
|
+
```
|
|
300
|
+
|
|
301
|
+
Messages are CBOR-encoded and sent as WebSocket binary frames. The router handles:
|
|
302
|
+
|
|
303
|
+
- WebSocket upgrade negotiation
|
|
304
|
+
- Backpressure management
|
|
305
|
+
- Graceful connection cleanup
|
|
306
|
+
- Error frame encoding
|
|
307
|
+
|
|
308
|
+
## Authentication
|
|
309
|
+
|
|
310
|
+
### Custom Authentication
|
|
311
|
+
|
|
312
|
+
Authentication is implemented through the `auth` function in handler configs:
|
|
313
|
+
|
|
314
|
+
```typescript
|
|
315
|
+
import { LexError, LexServerAuthError } from '@atproto/lex-server'
|
|
316
|
+
|
|
317
|
+
type Credentials = { did: string; scope: string[] }
|
|
318
|
+
|
|
319
|
+
const requireAuth = async ({
|
|
320
|
+
request,
|
|
321
|
+
}: {
|
|
322
|
+
request: Request
|
|
323
|
+
}): Promise<Credentials> => {
|
|
324
|
+
const header = request.headers.get('authorization')
|
|
325
|
+
if (!header?.startsWith('Bearer ')) {
|
|
326
|
+
throw new LexServerAuthError(
|
|
327
|
+
'AuthenticationRequired',
|
|
328
|
+
'Bearer token required',
|
|
329
|
+
{
|
|
330
|
+
Bearer: { realm: 'api' },
|
|
331
|
+
},
|
|
332
|
+
)
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
const token = header.slice(7)
|
|
336
|
+
const session = await verifyToken(token)
|
|
337
|
+
if (!session) {
|
|
338
|
+
throw new LexServerAuthError(
|
|
339
|
+
'InvalidToken',
|
|
340
|
+
'Token is invalid or expired',
|
|
341
|
+
{
|
|
342
|
+
Bearer: { realm: 'api', error: 'invalid_token' },
|
|
343
|
+
},
|
|
344
|
+
)
|
|
345
|
+
}
|
|
346
|
+
|
|
347
|
+
return { did: session.did, scope: session.scope }
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
// Use with handlers
|
|
351
|
+
router.add(app.bsky.feed.post.create, {
|
|
352
|
+
auth: requireAuth,
|
|
353
|
+
handler: async ({ credentials, input }) => {
|
|
354
|
+
// credentials.did is available here
|
|
355
|
+
const post = await db.createPost(credentials.did, input.body)
|
|
356
|
+
return { body: post }
|
|
357
|
+
},
|
|
358
|
+
})
|
|
359
|
+
```
|
|
360
|
+
|
|
361
|
+
The auth function:
|
|
362
|
+
|
|
363
|
+
1. Is called **before** parsing the request body
|
|
364
|
+
2. Receives `params`, `request`, and `connection` info
|
|
365
|
+
3. Should throw `LexServerError` (or `LexServerAuthError`) on failure
|
|
366
|
+
4. Returns credentials that are passed to the handler
|
|
367
|
+
|
|
368
|
+
### WWW-Authenticate Headers
|
|
369
|
+
|
|
370
|
+
Use `LexServerAuthError` to include `WWW-Authenticate` headers in error responses:
|
|
371
|
+
|
|
372
|
+
```typescript
|
|
373
|
+
import { LexServerAuthError } from '@atproto/lex-server'
|
|
374
|
+
|
|
375
|
+
// Simple Bearer challenge
|
|
376
|
+
throw new LexServerAuthError('AuthenticationRequired', 'Login required', {
|
|
377
|
+
Bearer: { realm: 'api' },
|
|
378
|
+
})
|
|
379
|
+
// WWW-Authenticate: Bearer realm="api"
|
|
380
|
+
|
|
381
|
+
// Multiple schemes
|
|
382
|
+
throw new LexServerAuthError('AuthenticationRequired', 'Auth required', {
|
|
383
|
+
Bearer: { realm: 'api', scope: 'read write' },
|
|
384
|
+
Basic: { realm: 'api' },
|
|
385
|
+
})
|
|
386
|
+
// WWW-Authenticate: Bearer realm="api", scope="read write", Basic realm="api"
|
|
387
|
+
|
|
388
|
+
// Token68 format
|
|
389
|
+
throw new LexServerAuthError('AuthenticationRequired', 'Auth required', {
|
|
390
|
+
Bearer: 'token68value',
|
|
391
|
+
})
|
|
392
|
+
// WWW-Authenticate: Bearer token68value
|
|
393
|
+
```
|
|
394
|
+
|
|
395
|
+
## Error Handling
|
|
396
|
+
|
|
397
|
+
### LexServerError
|
|
398
|
+
|
|
399
|
+
Throw `LexServerError` to return structured XRPC error responses:
|
|
400
|
+
|
|
401
|
+
```typescript
|
|
402
|
+
import { LexServerError } from '@atproto/lex-server'
|
|
403
|
+
|
|
404
|
+
router.add(app.bsky.actor.getProfile, async ({ params }) => {
|
|
405
|
+
try {
|
|
406
|
+
const profile = await db.getProfile(params.actor)
|
|
407
|
+
return { body: profile }
|
|
408
|
+
} catch (cause) {
|
|
409
|
+
throw new LexServerError(
|
|
410
|
+
404,
|
|
411
|
+
{
|
|
412
|
+
error: 'NotFound',
|
|
413
|
+
message: 'Profile not found',
|
|
414
|
+
},
|
|
415
|
+
{
|
|
416
|
+
'cache-control': 'max-age=600',
|
|
417
|
+
},
|
|
418
|
+
{ cause },
|
|
419
|
+
)
|
|
420
|
+
}
|
|
421
|
+
})
|
|
422
|
+
```
|
|
423
|
+
|
|
424
|
+
Error responses follow the XRPC format:
|
|
425
|
+
|
|
426
|
+
```json
|
|
427
|
+
{
|
|
428
|
+
"error": "NotFound",
|
|
429
|
+
"message": "Profile not found"
|
|
430
|
+
}
|
|
431
|
+
```
|
|
432
|
+
|
|
433
|
+
### LexServerAuthError
|
|
434
|
+
|
|
435
|
+
`LexServerAuthError` extends `LexServerError` with `WWW-Authenticate` header support:
|
|
436
|
+
|
|
437
|
+
```typescript
|
|
438
|
+
import { LexServerAuthError } from '@atproto/lex-server'
|
|
439
|
+
|
|
440
|
+
throw new LexServerAuthError('AuthenticationRequired', 'Invalid credentials', {
|
|
441
|
+
Bearer: { realm: 'api' },
|
|
442
|
+
})
|
|
443
|
+
```
|
|
444
|
+
|
|
445
|
+
This returns a 401 response with the `WWW-Authenticate` header.
|
|
446
|
+
|
|
447
|
+
### Error Handler Callback
|
|
448
|
+
|
|
449
|
+
Use `onHandlerError` to log or report unexpected errors:
|
|
450
|
+
|
|
451
|
+
```typescript
|
|
452
|
+
const router = new LexRouter({
|
|
453
|
+
onHandlerError: async ({ error, request, method }) => {
|
|
454
|
+
// Log errors (excluding expected abort signals)
|
|
455
|
+
console.error(`Error in ${method.nsid}:`, error)
|
|
456
|
+
await reportToSentry(error)
|
|
457
|
+
},
|
|
458
|
+
})
|
|
459
|
+
```
|
|
460
|
+
|
|
461
|
+
> [!NOTE]
|
|
462
|
+
>
|
|
463
|
+
> The callback is only invoked for unexpected errors, not for `LexError` instances or request aborts.
|
|
464
|
+
|
|
465
|
+
## Node.js Server
|
|
466
|
+
|
|
467
|
+
The `@atproto/lex-server/nodejs` subpath provides Node.js-specific utilities.
|
|
468
|
+
|
|
469
|
+
### serve()
|
|
470
|
+
|
|
471
|
+
Start a server and begin listening:
|
|
472
|
+
|
|
473
|
+
```typescript
|
|
474
|
+
import { serve } from '@atproto/lex-server/nodejs'
|
|
475
|
+
|
|
476
|
+
const server = await serve(router, { port: 3000 })
|
|
477
|
+
console.log('Server listening on port 3000')
|
|
478
|
+
|
|
479
|
+
// Graceful shutdown
|
|
480
|
+
await server.terminate()
|
|
481
|
+
```
|
|
482
|
+
|
|
483
|
+
The server supports `AsyncDisposable`:
|
|
484
|
+
|
|
485
|
+
```typescript
|
|
486
|
+
await using server = await serve(router, { port: 3000 })
|
|
487
|
+
// Server is automatically terminated when scope exits
|
|
488
|
+
```
|
|
489
|
+
|
|
490
|
+
Options:
|
|
491
|
+
|
|
492
|
+
```typescript
|
|
493
|
+
type StartServerOptions = {
|
|
494
|
+
port?: number
|
|
495
|
+
host?: string
|
|
496
|
+
gracefulTerminationTimeout?: number // ms to wait for connections to close
|
|
497
|
+
}
|
|
498
|
+
```
|
|
499
|
+
|
|
500
|
+
### createServer()
|
|
501
|
+
|
|
502
|
+
Create a server without starting it:
|
|
503
|
+
|
|
504
|
+
```typescript
|
|
505
|
+
import { createServer } from '@atproto/lex-server/nodejs'
|
|
506
|
+
|
|
507
|
+
const server = createServer(router, {
|
|
508
|
+
gracefulTerminationTimeout: 5000,
|
|
509
|
+
})
|
|
510
|
+
|
|
511
|
+
server.listen(3000, () => {
|
|
512
|
+
console.log('Server listening')
|
|
513
|
+
})
|
|
514
|
+
```
|
|
515
|
+
|
|
516
|
+
### toRequestListener()
|
|
517
|
+
|
|
518
|
+
Convert a handler to an Express/Connect-compatible middleware:
|
|
519
|
+
|
|
520
|
+
```typescript
|
|
521
|
+
import express from 'express'
|
|
522
|
+
import { toRequestListener } from '@atproto/lex-server/nodejs'
|
|
523
|
+
|
|
524
|
+
const app = express()
|
|
525
|
+
|
|
526
|
+
// Mount the XRPC router
|
|
527
|
+
app.use(toRequestListener(router.fetch))
|
|
528
|
+
|
|
529
|
+
app.listen(3000)
|
|
530
|
+
```
|
|
531
|
+
|
|
532
|
+
### upgradeWebSocket()
|
|
533
|
+
|
|
534
|
+
Required for WebSocket subscription support in Node.js:
|
|
535
|
+
|
|
536
|
+
```typescript
|
|
537
|
+
import { LexRouter } from '@atproto/lex-server'
|
|
538
|
+
import { upgradeWebSocket } from '@atproto/lex-server/nodejs'
|
|
539
|
+
|
|
540
|
+
const router = new LexRouter({ upgradeWebSocket })
|
|
541
|
+
```
|
|
542
|
+
|
|
543
|
+
## Advanced Usage
|
|
544
|
+
|
|
545
|
+
### Custom Response Objects
|
|
546
|
+
|
|
547
|
+
Return a `Response` object for full control over the response (disables any kind
|
|
548
|
+
of validation of the body):
|
|
549
|
+
|
|
550
|
+
```typescript
|
|
551
|
+
router.add(schema, async ({ params }) => {
|
|
552
|
+
if (params.redirect) {
|
|
553
|
+
return Response.redirect('https://example.com', 302)
|
|
554
|
+
}
|
|
555
|
+
|
|
556
|
+
return Response.json(
|
|
557
|
+
{ custom: true },
|
|
558
|
+
{
|
|
559
|
+
status: 201,
|
|
560
|
+
headers: {
|
|
561
|
+
'X-Custom-Header': 'value',
|
|
562
|
+
},
|
|
563
|
+
},
|
|
564
|
+
)
|
|
565
|
+
})
|
|
566
|
+
```
|
|
567
|
+
|
|
568
|
+
### Response Headers
|
|
569
|
+
|
|
570
|
+
Add headers to responses:
|
|
571
|
+
|
|
572
|
+
```typescript
|
|
573
|
+
router.add(schema, async ({ params }) => {
|
|
574
|
+
return {
|
|
575
|
+
body: { data: 'value' },
|
|
576
|
+
headers: {
|
|
577
|
+
'Cache-Control': 'public, max-age=3600',
|
|
578
|
+
'X-Request-Id': crypto.randomUUID(),
|
|
579
|
+
},
|
|
580
|
+
}
|
|
581
|
+
})
|
|
582
|
+
```
|
|
583
|
+
|
|
584
|
+
### Connection Info
|
|
585
|
+
|
|
586
|
+
Access network connection information:
|
|
587
|
+
|
|
588
|
+
```typescript
|
|
589
|
+
router.add(schema, async ({ connection }) => {
|
|
590
|
+
console.log('Remote address:', connection?.remoteAddr?.hostname)
|
|
591
|
+
console.log('Local address:', connection?.localAddr?.hostname)
|
|
592
|
+
return { body: { status: 'ok' } }
|
|
593
|
+
})
|
|
594
|
+
```
|
|
595
|
+
|
|
596
|
+
Connection info structure:
|
|
597
|
+
|
|
598
|
+
```typescript
|
|
599
|
+
type ConnectionInfo = {
|
|
600
|
+
localAddr?: {
|
|
601
|
+
hostname: string
|
|
602
|
+
port: number
|
|
603
|
+
transport: 'tcp' | 'udp'
|
|
604
|
+
}
|
|
605
|
+
remoteAddr?: {
|
|
606
|
+
hostname: string
|
|
607
|
+
port: number
|
|
608
|
+
transport: 'tcp' | 'udp'
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
```
|
|
612
|
+
|
|
613
|
+
## License
|
|
614
|
+
|
|
615
|
+
MIT or Apache2
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import type { LexErrorCode, LexErrorData } from '@atproto/lex-data';
|
|
2
|
+
import { LexError } from '@atproto/lex-data';
|
|
3
|
+
import type { WWWAuthenticate } from './lib/www-authenticate.js';
|
|
4
|
+
export { LexError };
|
|
5
|
+
export type { LexErrorCode, LexErrorData, WWWAuthenticate };
|
|
6
|
+
/**
|
|
7
|
+
* Base error class for representing errors that should be converted to XRPC
|
|
8
|
+
* error responses.
|
|
9
|
+
*/
|
|
10
|
+
export declare class LexServerError<N extends LexErrorCode = LexErrorCode> extends LexError<N> {
|
|
11
|
+
readonly status: number;
|
|
12
|
+
readonly body: LexErrorData<N>;
|
|
13
|
+
name: string;
|
|
14
|
+
readonly headers?: Headers;
|
|
15
|
+
constructor(status: number, body: LexErrorData<N>, headers?: HeadersInit, options?: ErrorOptions);
|
|
16
|
+
toJSON(): LexErrorData<N>;
|
|
17
|
+
toResponse(): Response;
|
|
18
|
+
static from(cause: unknown): LexServerError;
|
|
19
|
+
}
|
|
20
|
+
/**
|
|
21
|
+
* Error class for authentication failures in XRPC server handlers.
|
|
22
|
+
*
|
|
23
|
+
* Extends {@link LexError} to include WWW-Authenticate header support,
|
|
24
|
+
* which is required by HTTP authentication standards (RFC 7235).
|
|
25
|
+
* The error automatically generates the appropriate 401 response with
|
|
26
|
+
* the WWW-Authenticate header when converted to a Response.
|
|
27
|
+
*
|
|
28
|
+
* @typeParam N - The Lexicon error code type
|
|
29
|
+
*
|
|
30
|
+
* @example Throwing an auth error
|
|
31
|
+
* ```typescript
|
|
32
|
+
* import { LexServerAuthError } from '@atproto/lex-server'
|
|
33
|
+
*
|
|
34
|
+
* throw new LexServerAuthError(
|
|
35
|
+
* 'AuthenticationRequired',
|
|
36
|
+
* 'Invalid or expired token',
|
|
37
|
+
* { Bearer: { error: 'InvalidToken', realm: 'api.example.com' } }
|
|
38
|
+
* )
|
|
39
|
+
* ```
|
|
40
|
+
*/
|
|
41
|
+
export declare class LexServerAuthError<N extends LexErrorCode = LexErrorCode> extends LexServerError<N> {
|
|
42
|
+
readonly wwwAuthenticate: WWWAuthenticate;
|
|
43
|
+
name: string;
|
|
44
|
+
/**
|
|
45
|
+
* Creates a new authentication error.
|
|
46
|
+
*
|
|
47
|
+
* @param error - The Lexicon error code (e.g., 'AuthenticationRequired')
|
|
48
|
+
* @param message - Human-readable error message
|
|
49
|
+
* @param wwwAuthenticate - WWW-Authenticate header parameters
|
|
50
|
+
* @param options - Standard Error options including `cause`
|
|
51
|
+
*/
|
|
52
|
+
constructor(error: N, message: string, wwwAuthenticate?: WWWAuthenticate, options?: ErrorOptions);
|
|
53
|
+
/**
|
|
54
|
+
* Creates a LexServerAuthError from an existing LexError.
|
|
55
|
+
*
|
|
56
|
+
* If the input is already a LexServerAuthError, returns it unchanged.
|
|
57
|
+
* Otherwise, wraps the error with the provided WWW-Authenticate parameters.
|
|
58
|
+
*
|
|
59
|
+
* @param cause - The original LexError to wrap
|
|
60
|
+
* @param wwwAuthenticate - WWW-Authenticate header parameters
|
|
61
|
+
* @returns A LexServerAuthError instance
|
|
62
|
+
*
|
|
63
|
+
* @example
|
|
64
|
+
* ```typescript
|
|
65
|
+
* function authenticate(token: string): Promise<User> {
|
|
66
|
+
* try {
|
|
67
|
+
* return await validateToken(token)
|
|
68
|
+
* } catch (cause) {
|
|
69
|
+
* throw LexServerAuthError.from(cause, {
|
|
70
|
+
* Bearer: { error: 'InvalidToken' }
|
|
71
|
+
* })
|
|
72
|
+
* }
|
|
73
|
+
* }
|
|
74
|
+
* ```
|
|
75
|
+
*/
|
|
76
|
+
static from(cause: unknown, wwwAuthenticate?: WWWAuthenticate): LexServerAuthError;
|
|
77
|
+
}
|
|
78
|
+
//# sourceMappingURL=errors.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,mBAAmB,CAAA;AACnE,OAAO,EAAE,QAAQ,EAAE,MAAM,mBAAmB,CAAA;AAE5C,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,2BAA2B,CAAA;AAGhE,OAAO,EAAE,QAAQ,EAAE,CAAA;AACnB,YAAY,EAAE,YAAY,EAAE,YAAY,EAAE,eAAe,EAAE,CAAA;AAE3D;;;GAGG;AACH,qBAAa,cAAc,CACzB,CAAC,SAAS,YAAY,GAAG,YAAY,CACrC,SAAQ,QAAQ,CAAC,CAAC,CAAC;IAMjB,QAAQ,CAAC,MAAM,EAAE,MAAM;IACvB,QAAQ,CAAC,IAAI,EAAE,YAAY,CAAC,CAAC,CAAC;IANhC,IAAI,SAAmB;IAEvB,QAAQ,CAAC,OAAO,CAAC,EAAE,OAAO,CAAA;IAE1B,YACW,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,YAAY,CAAC,CAAC,CAAC,EAC9B,OAAO,CAAC,EAAE,WAAW,EACrB,OAAO,CAAC,EAAE,YAAY,EAIvB;IAEQ,MAAM,IAAI,YAAY,CAAC,CAAC,CAAC,CAEjC;IAEM,UAAU,IAAI,QAAQ,CAI5B;IAED,MAAM,CAAC,IAAI,CAAC,KAAK,EAAE,OAAO,GAAG,cAAc,CA+B1C;CACF;AAED;;;;;;;;;;;;;;;;;;;;GAoBG;AACH,qBAAa,kBAAkB,CAC7B,CAAC,SAAS,YAAY,GAAG,YAAY,CACrC,SAAQ,cAAc,CAAC,CAAC,CAAC;IAcvB,QAAQ,CAAC,eAAe,EAAE,eAAe;IAb3C,IAAI,SAAuB;IAE3B;;;;;;;OAOG;IACH,YACE,KAAK,EAAE,CAAC,EACR,OAAO,EAAE,MAAM,EACN,eAAe,GAAE,eAAoB,EAC9C,OAAO,CAAC,EAAE,YAAY,EASvB;IAED;;;;;;;;;;;;;;;;;;;;;;OAsBG;IACH,MAAM,CAAC,IAAI,CACT,KAAK,EAAE,OAAO,EACd,eAAe,CAAC,EAAE,eAAe,GAChC,kBAAkB,CAoBpB;CACF"}
|