@atproto/xrpc-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.
Files changed (68) hide show
  1. package/CHANGELOG.md +921 -0
  2. package/LICENSE.txt +7 -0
  3. package/README.md +62 -0
  4. package/dist/auth.d.ts +30 -0
  5. package/dist/auth.d.ts.map +1 -0
  6. package/dist/auth.js +147 -0
  7. package/dist/auth.js.map +1 -0
  8. package/dist/errors.d.ts +60 -0
  9. package/dist/errors.d.ts.map +1 -0
  10. package/dist/errors.js +187 -0
  11. package/dist/errors.js.map +1 -0
  12. package/dist/index.d.ts +9 -0
  13. package/dist/index.d.ts.map +1 -0
  14. package/dist/index.js +8 -0
  15. package/dist/index.js.map +1 -0
  16. package/dist/logger.d.ts +5 -0
  17. package/dist/logger.d.ts.map +1 -0
  18. package/dist/logger.js +5 -0
  19. package/dist/logger.js.map +1 -0
  20. package/dist/rate-limiter-http.d.ts +24 -0
  21. package/dist/rate-limiter-http.d.ts.map +1 -0
  22. package/dist/rate-limiter-http.js +53 -0
  23. package/dist/rate-limiter-http.js.map +1 -0
  24. package/dist/rate-limiter.d.ts +95 -0
  25. package/dist/rate-limiter.d.ts.map +1 -0
  26. package/dist/rate-limiter.js +168 -0
  27. package/dist/rate-limiter.js.map +1 -0
  28. package/dist/server.d.ts +52 -0
  29. package/dist/server.d.ts.map +1 -0
  30. package/dist/server.js +487 -0
  31. package/dist/server.js.map +1 -0
  32. package/dist/stream/frames.d.ts +31 -0
  33. package/dist/stream/frames.d.ts.map +1 -0
  34. package/dist/stream/frames.js +100 -0
  35. package/dist/stream/frames.js.map +1 -0
  36. package/dist/stream/index.d.ts +6 -0
  37. package/dist/stream/index.d.ts.map +1 -0
  38. package/dist/stream/index.js +6 -0
  39. package/dist/stream/index.js.map +1 -0
  40. package/dist/stream/logger.d.ts +4 -0
  41. package/dist/stream/logger.d.ts.map +1 -0
  42. package/dist/stream/logger.js +4 -0
  43. package/dist/stream/logger.js.map +1 -0
  44. package/dist/stream/server.d.ts +23 -0
  45. package/dist/stream/server.d.ts.map +1 -0
  46. package/dist/stream/server.js +70 -0
  47. package/dist/stream/server.js.map +1 -0
  48. package/dist/stream/stream.d.ts +8 -0
  49. package/dist/stream/stream.d.ts.map +1 -0
  50. package/dist/stream/stream.js +37 -0
  51. package/dist/stream/stream.js.map +1 -0
  52. package/dist/stream/subscription.d.ts +31 -0
  53. package/dist/stream/subscription.d.ts.map +1 -0
  54. package/dist/stream/subscription.js +92 -0
  55. package/dist/stream/subscription.js.map +1 -0
  56. package/dist/stream/types.d.ts +29 -0
  57. package/dist/stream/types.d.ts.map +1 -0
  58. package/dist/stream/types.js +19 -0
  59. package/dist/stream/types.js.map +1 -0
  60. package/dist/types.d.ts +166 -0
  61. package/dist/types.d.ts.map +1 -0
  62. package/dist/types.js +46 -0
  63. package/dist/types.js.map +1 -0
  64. package/dist/util.d.ts +45 -0
  65. package/dist/util.d.ts.map +1 -0
  66. package/dist/util.js +516 -0
  67. package/dist/util.js.map +1 -0
  68. package/package.json +68 -0
package/dist/util.js ADDED
@@ -0,0 +1,516 @@
1
+ import assert from 'node:assert';
2
+ import { pipeline } from 'node:stream';
3
+ import { json, text, } from 'express';
4
+ import { contentType } from 'mime-types';
5
+ import { MaxSizeChecker, createDecoders } from '@atproto/common';
6
+ import { jsonToLex } from '@atproto/lex-json';
7
+ import { l } from '@atproto/lex-schema';
8
+ import { jsonToLex as jsonToLexWithBlobRef, } from '@atproto/lexicon';
9
+ import { ResponseType } from '@atproto/xrpc';
10
+ import { InternalServerError, InvalidRequestError, XRPCError, } from './errors.js';
11
+ import { handlerSuccess, } from './types.js';
12
+ export const asArray = (arr) => Array.isArray(arr) ? arr : [arr];
13
+ export function setHeaders(res, headers) {
14
+ if (headers) {
15
+ for (const [name, val] of Object.entries(headers)) {
16
+ if (val != null)
17
+ res.setHeader(name, val);
18
+ }
19
+ }
20
+ }
21
+ function decodeQueryParams(def, params) {
22
+ const decoded = {};
23
+ for (const k in params) {
24
+ const val = params[k];
25
+ const property = def.parameters?.properties?.[k];
26
+ if (property) {
27
+ if (property.type === 'array') {
28
+ const vals = [];
29
+ decoded[k] = val
30
+ ? vals
31
+ .concat(val) // Cast to array
32
+ .flatMap((v) => decodeQueryParam(property.items.type, v) ?? [])
33
+ : undefined;
34
+ }
35
+ else {
36
+ decoded[k] = decodeQueryParam(property.type, val);
37
+ }
38
+ }
39
+ }
40
+ return decoded;
41
+ }
42
+ export function decodeQueryParam(type, value) {
43
+ if (!value) {
44
+ return undefined;
45
+ }
46
+ if (type === 'string' || type === 'datetime') {
47
+ return String(value);
48
+ }
49
+ if (type === 'float') {
50
+ return Number(String(value));
51
+ }
52
+ else if (type === 'integer') {
53
+ return parseInt(String(value), 10) || 0;
54
+ }
55
+ else if (type === 'boolean') {
56
+ return value === 'true';
57
+ }
58
+ }
59
+ function getSearchParams(url, opts) {
60
+ if (!url)
61
+ return undefined;
62
+ const queryStringIdx = url.indexOf('?');
63
+ if (queryStringIdx === -1)
64
+ return undefined;
65
+ const queryString = url.slice(queryStringIdx + 1);
66
+ if (queryString.length === 0)
67
+ return undefined;
68
+ const urlSearchParams = new URLSearchParams(queryString);
69
+ if (opts?.parseLoose) {
70
+ // @NOTE this is non-standard and should only be used for limited backwards-compatibility purposes.
71
+ // Converts "foo[]=bar&foo[0]=baz" syntax into "foo=bar&foo=baz"
72
+ // We cannot "delete()" while iterating. SO we'll first collect all keys
73
+ // that need to be changed, then apply the changes after
74
+ const toAppend = new URLSearchParams();
75
+ const toDelete = new Set();
76
+ for (const [key, value] of urlSearchParams) {
77
+ const match = key.endsWith(']') ? key.match(/^([^[]*)\[\d*\]$/) : null;
78
+ if (match) {
79
+ toAppend.append(match[1], value);
80
+ toDelete.add(key);
81
+ }
82
+ }
83
+ for (const key of toDelete) {
84
+ urlSearchParams.delete(key);
85
+ }
86
+ for (const [key, value] of toAppend) {
87
+ urlSearchParams.append(key, value);
88
+ }
89
+ }
90
+ return urlSearchParams;
91
+ }
92
+ export function getQueryParams(req, opts) {
93
+ const result = Object.create(null);
94
+ const expressQuery = 'query' in req ? req.query : undefined;
95
+ const searchParams = getSearchParams(req.url, opts);
96
+ if (!searchParams) {
97
+ return expressQuery ?? result;
98
+ }
99
+ if (searchParams.has('__proto__')) {
100
+ // Prevent prototype pollution
101
+ throw new InvalidRequestError(`Invalid query parameter: __proto__`, 'InvalidQueryParameter');
102
+ }
103
+ for (const key of searchParams.keys()) {
104
+ const values = searchParams.getAll(key);
105
+ result[key] = values.length === 1 ? values[0] : values;
106
+ }
107
+ // Preserve Express's support for bracket-style query parameters in the
108
+ // legacy Lexicons path, but let repeated standard params from the URL win so
109
+ // Express/qs array limits cannot collapse them into numeric-keyed objects.
110
+ if (expressQuery) {
111
+ for (const [key, value] of Object.entries(expressQuery)) {
112
+ if (!(key in result)) {
113
+ result[key] = value;
114
+ }
115
+ }
116
+ }
117
+ return result;
118
+ }
119
+ export function createLexiconParamsVerifier(nsid, def, lexicons) {
120
+ return (req) => {
121
+ const queryParams = getQueryParams(req);
122
+ const params = decodeQueryParams(def, queryParams);
123
+ try {
124
+ return lexicons.assertValidXrpcParams(nsid, params);
125
+ }
126
+ catch (cause) {
127
+ // @NOTE WE historically did not check for specific error types here,
128
+ throw new InvalidRequestError(String(cause), undefined, { cause });
129
+ }
130
+ };
131
+ }
132
+ export function createSchemaParamsVerifier(ns, options) {
133
+ const schema = l.getMain(ns);
134
+ const queryOpts = { parseLoose: options?.paramsParseLoose };
135
+ return (req) => {
136
+ const urlSearchParams = getSearchParams(req.url, queryOpts) ?? new URLSearchParams();
137
+ try {
138
+ const params = schema.parameters.fromURLSearchParams(urlSearchParams);
139
+ return params;
140
+ }
141
+ catch (cause) {
142
+ if (cause instanceof l.LexValidationError) {
143
+ const message = `Invalid ${schema.nsid} params: ${cause.issues
144
+ .map((issue) => issue.message)
145
+ .join(', ')}`;
146
+ throw new InvalidRequestError(message, undefined, { cause });
147
+ }
148
+ throw cause;
149
+ }
150
+ };
151
+ }
152
+ export function createLexiconInputVerifier(nsid, def, options, lexicons) {
153
+ if (def.type === 'query' || !def.input) {
154
+ return async (req) => {
155
+ // @NOTE We allow (and ignore) "empty" bodies
156
+ if (getBodyPresence(req) === 'present') {
157
+ throw new InvalidRequestError(`A request body was provided when none was expected`);
158
+ }
159
+ return undefined;
160
+ };
161
+ }
162
+ // Lexicon definition expects a request body
163
+ const { input } = def;
164
+ const { blobLimit } = options;
165
+ const allowedEncodings = parseDefEncoding(input);
166
+ const checkEncoding = allowedEncodings.includes(ENCODING_ANY)
167
+ ? undefined // No need to check
168
+ : (encoding) => allowedEncodings.includes(encoding);
169
+ const bodyParser = createBodyParser(input.encoding, options);
170
+ return async (req, res) => {
171
+ if (getBodyPresence(req) === 'missing') {
172
+ throw new InvalidRequestError(`A request body is expected but none was provided`);
173
+ }
174
+ const reqEncoding = parseReqEncoding(req);
175
+ if (checkEncoding && !checkEncoding(reqEncoding)) {
176
+ throw new InvalidRequestError(`Wrong request encoding (Content-Type): ${reqEncoding}`);
177
+ }
178
+ if (bodyParser) {
179
+ await bodyParser(req, res);
180
+ }
181
+ if (input.schema) {
182
+ try {
183
+ const lexBody = req.body ? jsonToLexWithBlobRef(req.body) : req.body;
184
+ req.body = lexicons.assertValidXrpcInput(nsid, lexBody);
185
+ }
186
+ catch (cause) {
187
+ throw new InvalidRequestError(cause instanceof Error ? cause.message : String(cause), undefined, { cause });
188
+ }
189
+ }
190
+ // if middleware already got the body, we pass that along as input
191
+ // otherwise, we pass along a decoded readable stream
192
+ const body = req.readableEnded ? req.body : decodeBodyStream(req, blobLimit);
193
+ return { encoding: reqEncoding, body };
194
+ };
195
+ }
196
+ export function createSchemaInputVerifier(ns, options) {
197
+ const schema = l.getMain(ns);
198
+ const { blobLimit } = options;
199
+ const input = 'input' in schema ? schema.input : undefined;
200
+ if (!input?.encoding) {
201
+ //
202
+ return async (req) => {
203
+ if (getBodyPresence(req) === 'present') {
204
+ // @NOTE we *could* also discard the body here instead of throwing an error
205
+ throw new InvalidRequestError(`A request body was provided when none was expected`);
206
+ }
207
+ return undefined;
208
+ };
209
+ }
210
+ const bodyParser = createBodyParser(input.encoding, options);
211
+ return async (req, res) => {
212
+ if (getBodyPresence(req) === 'missing') {
213
+ throw new InvalidRequestError(`A request body is expected but none was provided`);
214
+ }
215
+ const reqEncoding = parseReqEncoding(req);
216
+ if (!input.matchesEncoding(reqEncoding)) {
217
+ throw new InvalidRequestError(`Wrong request encoding (Content-Type): ${reqEncoding}`);
218
+ }
219
+ if (bodyParser) {
220
+ await bodyParser(req, res);
221
+ }
222
+ if (input.schema) {
223
+ try {
224
+ const lexBody = req.body ? jsonToLex(req.body) : req.body;
225
+ req.body = input.schema.parse(lexBody);
226
+ }
227
+ catch (cause) {
228
+ throw new InvalidRequestError(cause instanceof Error ? cause.message : String(cause), undefined, { cause });
229
+ }
230
+ }
231
+ // if middleware already got the body, we pass that along as input
232
+ // otherwise, we pass along a decoded readable stream
233
+ const body = req.readableEnded ? req.body : decodeBodyStream(req, blobLimit);
234
+ return { encoding: reqEncoding, body };
235
+ };
236
+ }
237
+ export function createLexiconOutputVerifier(nsid, def, lexicons) {
238
+ const outputDef = def.output;
239
+ // Expects no output
240
+ if (!outputDef) {
241
+ return (handlerOutput) => {
242
+ if (handlerOutput !== undefined) {
243
+ throw new InternalServerError(`A response body was provided when none was expected`);
244
+ }
245
+ };
246
+ }
247
+ // An output is expected
248
+ return (handlerOutput) => {
249
+ if (handlerOutput === undefined) {
250
+ throw new InternalServerError(`A response body is expected but none was provided`);
251
+ }
252
+ if (!('encoding' in handlerOutput)) {
253
+ // Ensure handlerOutput is valid ErrorResult
254
+ if ('status' in handlerOutput && handlerOutput.status >= 400) {
255
+ return;
256
+ }
257
+ throw new InternalServerError(`Invalid handler output: missing encoding`);
258
+ }
259
+ if (!('body' in handlerOutput)) {
260
+ // Ensure handlerOutput is valid HandlerPipeThrough
261
+ if ('stream' in handlerOutput || 'buffer' in handlerOutput) {
262
+ return; // Validation is ignored for pipe-through outputs
263
+ }
264
+ throw new InternalServerError(`Invalid handler output: missing body`);
265
+ }
266
+ // Fool-proofing (should not be necessary due to type system)
267
+ const result = handlerSuccess.safeParse(handlerOutput);
268
+ if (!result.success) {
269
+ throw new InternalServerError(`Invalid handler output`, undefined, {
270
+ cause: result.reason,
271
+ });
272
+ }
273
+ // output mime
274
+ const { encoding } = handlerOutput;
275
+ if (!isValidEncoding(outputDef, encoding)) {
276
+ throw new InternalServerError(`Invalid response encoding: ${encoding}`);
277
+ }
278
+ // output schema
279
+ try {
280
+ lexicons.assertValidXrpcOutput(nsid, handlerOutput.body);
281
+ // @TODO Since the output verifier is typically enabled in dev/tests and
282
+ // disabled in production, we don't want to assign the (altered) output
283
+ // back to the handlerOutput object, as this would cause different
284
+ // behaviors between environments. Instead, we should compare the value
285
+ // returned by assertValidXrpcOutput with the original output and throw if
286
+ // they differ (indicating that the output was mutated during validation,
287
+ // e.g. due to default values being applied).
288
+ }
289
+ catch (cause) {
290
+ const message = cause instanceof Error ? cause.message : 'Output body validation failed';
291
+ throw new InternalServerError(message, undefined, { cause });
292
+ }
293
+ };
294
+ }
295
+ export function createSchemaOutputVerifier(ns) {
296
+ const outputSchema = l.getMain(ns).output;
297
+ return (handlerOutput) => {
298
+ // @NOTE If the user of the lib wants to return an output that doesn't
299
+ // conform to the schema, they can use HandlerPipeThrough return types
300
+ if (!outputSchema.matchesEncoding(handlerOutput?.encoding)) {
301
+ throw new InternalServerError('Output encoding mismatch');
302
+ }
303
+ if (outputSchema.schema) {
304
+ const result = outputSchema.schema.safeValidate(handlerOutput?.body);
305
+ if (!result.success) {
306
+ throw new InternalServerError(result.reason.message, undefined, {
307
+ cause: result.reason,
308
+ });
309
+ }
310
+ }
311
+ else if (!outputSchema.encoding && handlerOutput?.body !== undefined) {
312
+ throw new InternalServerError('Output body not expected');
313
+ }
314
+ };
315
+ }
316
+ export function parseReqEncoding(req) {
317
+ const encoding = normalizeMime(req.headers['content-type']);
318
+ if (encoding)
319
+ return encoding;
320
+ throw new InvalidRequestError(`Request encoding (Content-Type) required but not provided`);
321
+ }
322
+ function normalizeMime(v) {
323
+ if (!v)
324
+ return null;
325
+ const fullType = contentType(v);
326
+ if (!fullType)
327
+ return null;
328
+ const shortType = fullType.split(';')[0];
329
+ if (!shortType)
330
+ return null;
331
+ return shortType;
332
+ }
333
+ const ENCODING_ANY = '*/*';
334
+ function parseDefEncoding({ encoding }) {
335
+ return encoding.split(',').map(trimString);
336
+ }
337
+ function trimString(str) {
338
+ return str.trim();
339
+ }
340
+ function isValidEncoding(output, encoding) {
341
+ if (!encoding)
342
+ return false;
343
+ const normalized = normalizeMime(encoding);
344
+ if (!normalized)
345
+ return false;
346
+ const allowed = parseDefEncoding(output);
347
+ if (!allowed.length)
348
+ return false;
349
+ if (allowed.includes(ENCODING_ANY))
350
+ return true;
351
+ if (allowed.includes(normalized))
352
+ return true;
353
+ // Check for wildcard matches (e.g. normalized=application/json, allowed=application/*)
354
+ for (const allowedEnc of allowed) {
355
+ if (allowedEnc.endsWith('/*') &&
356
+ normalized.startsWith(allowedEnc.slice(0, -1))) {
357
+ return true;
358
+ }
359
+ }
360
+ return false;
361
+ }
362
+ function getBodyPresence(req) {
363
+ if (req.headers['transfer-encoding'] != null)
364
+ return 'present';
365
+ if (req.headers['content-length'] === '0')
366
+ return 'empty';
367
+ if (req.headers['content-length'] != null)
368
+ return 'present';
369
+ return 'missing';
370
+ }
371
+ function createBodyParser(inputEncoding, options) {
372
+ if (inputEncoding === ENCODING_ANY) {
373
+ // When the lexicon's input encoding is */*, the handler will determine how to process it
374
+ return;
375
+ }
376
+ const { jsonLimit, textLimit } = options;
377
+ const jsonParser = json({ limit: jsonLimit });
378
+ const textParser = text({ limit: textLimit });
379
+ // Transform json and text parser middlewares into a single function
380
+ return (req, res) => {
381
+ return new Promise((resolve, reject) => {
382
+ jsonParser(req, res, (err) => {
383
+ if (err)
384
+ return reject(XRPCError.fromError(err));
385
+ textParser(req, res, (err) => {
386
+ if (err)
387
+ return reject(XRPCError.fromError(err));
388
+ resolve();
389
+ });
390
+ });
391
+ });
392
+ };
393
+ }
394
+ function decodeBodyStream(req, maxSize) {
395
+ const contentEncoding = req.headers['content-encoding'];
396
+ const contentLength = req.headers['content-length'];
397
+ const contentLengthParsed = contentLength
398
+ ? parseInt(contentLength, 10)
399
+ : undefined;
400
+ if (Number.isNaN(contentLengthParsed)) {
401
+ throw new XRPCError(ResponseType.InvalidRequest, 'invalid content-length');
402
+ }
403
+ if (maxSize !== undefined &&
404
+ contentLengthParsed !== undefined &&
405
+ contentLengthParsed > maxSize) {
406
+ throw new XRPCError(ResponseType.PayloadTooLarge, 'request entity too large');
407
+ }
408
+ let transforms;
409
+ try {
410
+ transforms = createDecoders(contentEncoding);
411
+ }
412
+ catch (cause) {
413
+ throw new XRPCError(ResponseType.UnsupportedMediaType, 'unsupported content-encoding', undefined, { cause });
414
+ }
415
+ if (maxSize !== undefined) {
416
+ const maxSizeChecker = new MaxSizeChecker(maxSize, () => new XRPCError(ResponseType.PayloadTooLarge, 'request entity too large'));
417
+ transforms.push(maxSizeChecker);
418
+ }
419
+ return transforms.length > 0
420
+ ? pipeline([req, ...transforms], () => { })
421
+ : req;
422
+ }
423
+ export function serverTimingHeader(timings) {
424
+ return timings
425
+ .map((timing) => {
426
+ let header = timing.name;
427
+ if (timing.duration)
428
+ header += `;dur=${timing.duration}`;
429
+ if (timing.description)
430
+ header += `;desc="${timing.description}"`;
431
+ return header;
432
+ })
433
+ .join(', ');
434
+ }
435
+ export class ServerTimer {
436
+ constructor(name, description) {
437
+ this.name = name;
438
+ this.description = description;
439
+ }
440
+ start() {
441
+ this.startMs = Date.now();
442
+ return this;
443
+ }
444
+ stop() {
445
+ assert(this.startMs, "timer hasn't been started");
446
+ this.duration = Date.now() - this.startMs;
447
+ return this;
448
+ }
449
+ }
450
+ export const parseReqNsid = (req) => parseUrlNsid('originalUrl' in req ? req.originalUrl : req.url || '/');
451
+ /**
452
+ * Validates and extracts the nsid from an xrpc path
453
+ */
454
+ export const parseUrlNsid = (url) => {
455
+ const nsid = extractUrlNsid(url);
456
+ if (nsid)
457
+ return nsid;
458
+ throw new InvalidRequestError('invalid xrpc path');
459
+ };
460
+ export const extractUrlNsid = (url) => {
461
+ // /!\ Hot path
462
+ if (
463
+ // Ordered by likelihood of failure
464
+ url.length <= 6 ||
465
+ url[5] !== '/' ||
466
+ url[4] !== 'c' ||
467
+ url[3] !== 'p' ||
468
+ url[2] !== 'r' ||
469
+ url[1] !== 'x' ||
470
+ url[0] !== '/') {
471
+ return undefined;
472
+ }
473
+ const startOfNsid = 6;
474
+ let curr = startOfNsid;
475
+ let char;
476
+ let alphaNumRequired = true;
477
+ for (; curr < url.length; curr++) {
478
+ char = url.charCodeAt(curr);
479
+ if ((char >= 48 && char <= 57) || // 0-9
480
+ (char >= 65 && char <= 90) || // A-Z
481
+ (char >= 97 && char <= 122) // a-z
482
+ ) {
483
+ alphaNumRequired = false;
484
+ }
485
+ else if (char === 45 /* "-" */ || char === 46 /* "." */) {
486
+ if (alphaNumRequired) {
487
+ return undefined;
488
+ }
489
+ alphaNumRequired = true;
490
+ }
491
+ else if (char === 47 /* "/" */) {
492
+ // Allow trailing slash (next char is either EOS or "?")
493
+ if (curr === url.length - 1 || url.charCodeAt(curr + 1) === 63) {
494
+ break;
495
+ }
496
+ return undefined;
497
+ }
498
+ else if (char === 63 /* "?"" */) {
499
+ break;
500
+ }
501
+ else {
502
+ return undefined;
503
+ }
504
+ }
505
+ // last char was one of: '-', '.', '/'
506
+ if (alphaNumRequired) {
507
+ return undefined;
508
+ }
509
+ // A domain name consists of minimum two characters
510
+ if (curr - startOfNsid < 2) {
511
+ return undefined;
512
+ }
513
+ // @TODO check max length of nsid
514
+ return url.slice(startOfNsid, curr);
515
+ };
516
+ //# sourceMappingURL=util.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"util.js","sourceRoot":"","sources":["../src/util.ts"],"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SAAS,IAAI,IAAI,KAAK,EAAE,CAAC,SAAS,EAAE,CAAC;YAC1D,IAAI,gBAAgB,EAAE,CAAC;gBACrB,OAAO,SAAS,CAAA;YAClB,CAAC;YACD,gBAAgB,GAAG,IAAI,CAAA;QACzB,CAAC;aAAM,IAAI,IAAI,KAAK,EAAE,CAAC,SAAS,EAAE,CAAC;YACjC,wDAAwD;YACxD,IAAI,IAAI,KAAK,GAAG,CAAC,MAAM,GAAG,CAAC,IAAI,GAAG,CAAC,UAAU,CAAC,IAAI,GAAG,CAAC,CAAC,KAAK,EAAE,EAAE,CAAC;gBAC/D,MAAK;YACP,CAAC;YACD,OAAO,SAAS,CAAA;QAClB,CAAC;aAAM,IAAI,IAAI,KAAK,EAAE,CAAC,UAAU,EAAE,CAAC;YAClC,MAAK;QACP,CAAC;aAAM,CAAC;YACN,OAAO,SAAS,CAAA;QAClB,CAAC;IACH,CAAC;IAED,sCAAsC;IACtC,IAAI,gBAAgB,EAAE,CAAC;QACrB,OAAO,SAAS,CAAA;IAClB,CAAC;IAED,mDAAmD;IACnD,IAAI,IAAI,GAAG,WAAW,GAAG,CAAC,EAAE,CAAC;QAC3B,OAAO,SAAS,CAAA;IAClB,CAAC;IAED,iCAAiC;IAEjC,OAAO,GAAG,CAAC,KAAK,CAAC,WAAW,EAAE,IAAI,CAAC,CAAA;AACrC,CAAC,CAAA","sourcesContent":["import assert from 'node:assert'\nimport type { IncomingMessage, OutgoingMessage } from 'node:http'\nimport { type Duplex, type Readable, pipeline } from 'node:stream'\nimport {\n type Request as ExpressRequest,\n type Response as ExpressResponse,\n json,\n text,\n} from 'express'\nimport { contentType } from 'mime-types'\nimport { MaxSizeChecker, createDecoders } from '@atproto/common'\nimport { jsonToLex } from '@atproto/lex-json'\nimport { l } from '@atproto/lex-schema'\nimport {\n type LexXrpcBody,\n type LexXrpcProcedure,\n type LexXrpcQuery,\n type LexXrpcSubscription,\n type Lexicons,\n jsonToLex as jsonToLexWithBlobRef,\n} from '@atproto/lexicon'\nimport { ResponseType } from '@atproto/xrpc'\nimport {\n type ErrorResult,\n InternalServerError,\n InvalidRequestError,\n XRPCError,\n} from './errors.js'\nimport {\n type Auth,\n type Input,\n type LexMethodInput,\n type LexMethodOutput,\n type LexMethodParams,\n type Output,\n type Params,\n type RouteOptions,\n type UndecodedParams,\n handlerSuccess,\n} from './types.js'\n\nexport type ParamsVerifierInternal<P extends Params = Params> = (\n req: IncomingMessage | ExpressRequest,\n) => P\n\nexport type AuthVerifierInternal<C, A extends Auth = Auth> = (\n ctx: C,\n) => Promise<Exclude<A, ErrorResult>>\n\nexport type InputVerifierInternal<I extends Input = Input> = (\n req: ExpressRequest,\n res: ExpressResponse,\n) => Promise<I>\n\nexport type OutputVerifierInternal<O extends Output = Output> = (\n handleOutput: O,\n) => void\n\nexport const asArray = <T>(arr: T | T[]): T[] =>\n Array.isArray(arr) ? arr : [arr]\n\nexport function setHeaders(\n res: OutgoingMessage,\n headers?: Record<string, string | number>,\n) {\n if (headers) {\n for (const [name, val] of Object.entries(headers)) {\n if (val != null) res.setHeader(name, val)\n }\n }\n}\n\nfunction decodeQueryParams(\n def: LexXrpcProcedure | LexXrpcQuery | LexXrpcSubscription,\n params: UndecodedParams,\n): Params {\n const decoded: Params = {}\n for (const k in params) {\n const val = params[k]\n const property = def.parameters?.properties?.[k]\n if (property) {\n if (property.type === 'array') {\n const vals: (typeof val)[] = []\n decoded[k] = val\n ? vals\n .concat(val) // Cast to array\n .flatMap((v) => decodeQueryParam(property.items.type, v) ?? [])\n : undefined\n } else {\n decoded[k] = decodeQueryParam(property.type, val)\n }\n }\n }\n return decoded\n}\n\nexport function decodeQueryParam(\n type: string,\n value: unknown,\n): string | number | boolean | undefined {\n if (!value) {\n return undefined\n }\n if (type === 'string' || type === 'datetime') {\n return String(value)\n }\n if (type === 'float') {\n return Number(String(value))\n } else if (type === 'integer') {\n return parseInt(String(value), 10) || 0\n } else if (type === 'boolean') {\n return value === 'true'\n }\n}\n\nfunction getSearchParams(\n url?: string,\n opts?: { parseLoose?: boolean },\n): URLSearchParams | undefined {\n if (!url) return undefined\n\n const queryStringIdx = url.indexOf('?')\n if (queryStringIdx === -1) return undefined\n\n const queryString = url.slice(queryStringIdx + 1)\n if (queryString.length === 0) return undefined\n\n const urlSearchParams = new URLSearchParams(queryString)\n\n if (opts?.parseLoose) {\n // @NOTE this is non-standard and should only be used for limited backwards-compatibility purposes.\n // Converts \"foo[]=bar&foo[0]=baz\" syntax into \"foo=bar&foo=baz\"\n\n // We cannot \"delete()\" while iterating. SO we'll first collect all keys\n // that need to be changed, then apply the changes after\n const toAppend = new URLSearchParams()\n const toDelete = new Set<string>()\n\n for (const [key, value] of urlSearchParams) {\n const match = key.endsWith(']') ? key.match(/^([^[]*)\\[\\d*\\]$/) : null\n if (match) {\n toAppend.append(match[1], value)\n toDelete.add(key)\n }\n }\n\n for (const key of toDelete) {\n urlSearchParams.delete(key)\n }\n\n for (const [key, value] of toAppend) {\n urlSearchParams.append(key, value)\n }\n }\n\n return urlSearchParams\n}\n\nexport function getQueryParams(\n req: IncomingMessage | ExpressRequest,\n opts?: { parseLoose?: boolean },\n): UndecodedParams {\n const result: UndecodedParams = Object.create(null)\n const expressQuery = 'query' in req ? req.query : undefined\n\n const searchParams = getSearchParams(req.url, opts)\n if (!searchParams) {\n return expressQuery ?? result\n }\n\n if (searchParams.has('__proto__')) {\n // Prevent prototype pollution\n throw new InvalidRequestError(\n `Invalid query parameter: __proto__`,\n 'InvalidQueryParameter',\n )\n }\n\n for (const key of searchParams.keys()) {\n const values = searchParams.getAll(key)\n result[key] = values.length === 1 ? values[0] : values\n }\n\n // Preserve Express's support for bracket-style query parameters in the\n // legacy Lexicons path, but let repeated standard params from the URL win so\n // Express/qs array limits cannot collapse them into numeric-keyed objects.\n if (expressQuery) {\n for (const [key, value] of Object.entries(expressQuery)) {\n if (!(key in result)) {\n result[key] = value\n }\n }\n }\n\n return result\n}\n\nexport function createLexiconParamsVerifier<P extends Params = Params>(\n nsid: string,\n def: LexXrpcQuery | LexXrpcProcedure | LexXrpcSubscription,\n lexicons: Lexicons,\n): ParamsVerifierInternal<P> {\n return (req) => {\n const queryParams = getQueryParams(req)\n const params = decodeQueryParams(def, queryParams)\n try {\n return lexicons.assertValidXrpcParams(nsid, params) as P\n } catch (cause) {\n // @NOTE WE historically did not check for specific error types here,\n throw new InvalidRequestError(String(cause), undefined, { cause })\n }\n }\n}\n\nexport function createSchemaParamsVerifier<\n M extends l.Procedure | l.Query | l.Subscription,\n>(\n ns: l.Main<M>,\n options?: RouteOptions,\n): ParamsVerifierInternal<LexMethodParams<M>> {\n const schema = l.getMain(ns)\n const queryOpts = { parseLoose: options?.paramsParseLoose }\n return (req) => {\n const urlSearchParams =\n getSearchParams(req.url, queryOpts) ?? new URLSearchParams()\n try {\n const params = schema.parameters.fromURLSearchParams(urlSearchParams)\n return params as LexMethodParams<M>\n } catch (cause) {\n if (cause instanceof l.LexValidationError) {\n const message = `Invalid ${schema.nsid} params: ${cause.issues\n .map((issue) => issue.message)\n .join(', ')}`\n throw new InvalidRequestError(message, undefined, { cause })\n }\n throw cause\n }\n }\n}\n\nexport function createLexiconInputVerifier<I extends Input = Input>(\n nsid: string,\n def: LexXrpcProcedure | LexXrpcQuery,\n options: RouteOptions,\n lexicons: Lexicons,\n): InputVerifierInternal<I> {\n if (def.type === 'query' || !def.input) {\n return async (req) => {\n // @NOTE We allow (and ignore) \"empty\" bodies\n if (getBodyPresence(req) === 'present') {\n throw new InvalidRequestError(\n `A request body was provided when none was expected`,\n )\n }\n\n return undefined as I\n }\n }\n\n // Lexicon definition expects a request body\n\n const { input } = def\n const { blobLimit } = options\n\n const allowedEncodings = parseDefEncoding(input)\n const checkEncoding = allowedEncodings.includes(ENCODING_ANY)\n ? undefined // No need to check\n : (encoding: string) => allowedEncodings.includes(encoding)\n\n const bodyParser = createBodyParser(input.encoding, options)\n\n return async (req, res) => {\n if (getBodyPresence(req) === 'missing') {\n throw new InvalidRequestError(\n `A request body is expected but none was provided`,\n )\n }\n\n const reqEncoding = parseReqEncoding(req)\n if (checkEncoding && !checkEncoding(reqEncoding)) {\n throw new InvalidRequestError(\n `Wrong request encoding (Content-Type): ${reqEncoding}`,\n )\n }\n\n if (bodyParser) {\n await bodyParser(req, res)\n }\n\n if (input.schema) {\n try {\n const lexBody = req.body ? jsonToLexWithBlobRef(req.body) : req.body\n req.body = lexicons.assertValidXrpcInput(nsid, lexBody)\n } catch (cause) {\n throw new InvalidRequestError(\n cause instanceof Error ? cause.message : String(cause),\n undefined,\n { cause },\n )\n }\n }\n\n // if middleware already got the body, we pass that along as input\n // otherwise, we pass along a decoded readable stream\n const body = req.readableEnded ? req.body : decodeBodyStream(req, blobLimit)\n\n return { encoding: reqEncoding, body } as I\n }\n}\n\nexport function createSchemaInputVerifier<M extends l.Procedure | l.Query>(\n ns: l.Main<M>,\n options: RouteOptions,\n): InputVerifierInternal<LexMethodInput<M>> {\n const schema = l.getMain(ns)\n const { blobLimit } = options\n\n const input: l.Payload | undefined =\n 'input' in schema ? schema.input : undefined\n\n if (!input?.encoding) {\n //\n return async (req) => {\n if (getBodyPresence(req) === 'present') {\n // @NOTE we *could* also discard the body here instead of throwing an error\n throw new InvalidRequestError(\n `A request body was provided when none was expected`,\n )\n }\n\n return undefined as LexMethodInput<M>\n }\n }\n\n const bodyParser = createBodyParser(input.encoding, options)\n\n return async (req, res) => {\n if (getBodyPresence(req) === 'missing') {\n throw new InvalidRequestError(\n `A request body is expected but none was provided`,\n )\n }\n\n const reqEncoding = parseReqEncoding(req)\n if (!input.matchesEncoding(reqEncoding)) {\n throw new InvalidRequestError(\n `Wrong request encoding (Content-Type): ${reqEncoding}`,\n )\n }\n\n if (bodyParser) {\n await bodyParser(req, res)\n }\n\n if (input.schema) {\n try {\n const lexBody = req.body ? jsonToLex(req.body) : req.body\n req.body = input.schema.parse(lexBody)\n } catch (cause) {\n throw new InvalidRequestError(\n cause instanceof Error ? cause.message : String(cause),\n undefined,\n { cause },\n )\n }\n }\n\n // if middleware already got the body, we pass that along as input\n // otherwise, we pass along a decoded readable stream\n const body = req.readableEnded ? req.body : decodeBodyStream(req, blobLimit)\n\n return { encoding: reqEncoding, body } as LexMethodInput<M>\n }\n}\n\nexport function createLexiconOutputVerifier<O extends Output = Output>(\n nsid: string,\n def: LexXrpcProcedure | LexXrpcQuery,\n lexicons: Lexicons,\n): OutputVerifierInternal<O> {\n const outputDef = def.output\n\n // Expects no output\n if (!outputDef) {\n return (handlerOutput) => {\n if (handlerOutput !== undefined) {\n throw new InternalServerError(\n `A response body was provided when none was expected`,\n )\n }\n }\n }\n\n // An output is expected\n return (handlerOutput) => {\n if (handlerOutput === undefined) {\n throw new InternalServerError(\n `A response body is expected but none was provided`,\n )\n }\n\n if (!('encoding' in handlerOutput)) {\n // Ensure handlerOutput is valid ErrorResult\n if ('status' in handlerOutput && handlerOutput.status >= 400) {\n return\n }\n\n throw new InternalServerError(`Invalid handler output: missing encoding`)\n }\n\n if (!('body' in handlerOutput)) {\n // Ensure handlerOutput is valid HandlerPipeThrough\n if ('stream' in handlerOutput || 'buffer' in handlerOutput) {\n return // Validation is ignored for pipe-through outputs\n }\n\n throw new InternalServerError(`Invalid handler output: missing body`)\n }\n\n // Fool-proofing (should not be necessary due to type system)\n const result = handlerSuccess.safeParse(handlerOutput)\n if (!result.success) {\n throw new InternalServerError(`Invalid handler output`, undefined, {\n cause: result.reason,\n })\n }\n\n // output mime\n const { encoding } = handlerOutput\n if (!isValidEncoding(outputDef, encoding)) {\n throw new InternalServerError(`Invalid response encoding: ${encoding}`)\n }\n\n // output schema\n try {\n lexicons.assertValidXrpcOutput(nsid, handlerOutput.body)\n // @TODO Since the output verifier is typically enabled in dev/tests and\n // disabled in production, we don't want to assign the (altered) output\n // back to the handlerOutput object, as this would cause different\n // behaviors between environments. Instead, we should compare the value\n // returned by assertValidXrpcOutput with the original output and throw if\n // they differ (indicating that the output was mutated during validation,\n // e.g. due to default values being applied).\n } catch (cause) {\n const message =\n cause instanceof Error ? cause.message : 'Output body validation failed'\n throw new InternalServerError(message, undefined, { cause })\n }\n }\n}\n\nexport function createSchemaOutputVerifier<M extends l.Procedure | l.Query>(\n ns: l.Main<M>,\n): OutputVerifierInternal<LexMethodOutput<M>> {\n const outputSchema = l.getMain(ns).output\n return (handlerOutput) => {\n // @NOTE If the user of the lib wants to return an output that doesn't\n // conform to the schema, they can use HandlerPipeThrough return types\n if (!outputSchema.matchesEncoding(handlerOutput?.encoding)) {\n throw new InternalServerError('Output encoding mismatch')\n }\n if (outputSchema.schema) {\n const result = outputSchema.schema.safeValidate(handlerOutput?.body)\n if (!result.success) {\n throw new InternalServerError(result.reason.message, undefined, {\n cause: result.reason,\n })\n }\n } else if (!outputSchema.encoding && handlerOutput?.body !== undefined) {\n throw new InternalServerError('Output body not expected')\n }\n }\n}\n\nexport function parseReqEncoding(req: IncomingMessage): string {\n const encoding = normalizeMime(req.headers['content-type'])\n if (encoding) return encoding\n throw new InvalidRequestError(\n `Request encoding (Content-Type) required but not provided`,\n )\n}\n\nfunction normalizeMime(v?: string): string | null {\n if (!v) return null\n const fullType = contentType(v)\n if (!fullType) return null\n const shortType = fullType.split(';')[0]\n if (!shortType) return null\n return shortType\n}\n\nconst ENCODING_ANY = '*/*'\n\nfunction parseDefEncoding({ encoding }: LexXrpcBody) {\n return encoding.split(',').map(trimString)\n}\n\nfunction trimString(str: string): string {\n return str.trim()\n}\n\nfunction isValidEncoding(output: LexXrpcBody, encoding?: string) {\n if (!encoding) return false\n\n const normalized = normalizeMime(encoding)\n if (!normalized) return false\n\n const allowed = parseDefEncoding(output)\n if (!allowed.length) return false\n\n if (allowed.includes(ENCODING_ANY)) return true\n if (allowed.includes(normalized)) return true\n\n // Check for wildcard matches (e.g. normalized=application/json, allowed=application/*)\n for (const allowedEnc of allowed) {\n if (\n allowedEnc.endsWith('/*') &&\n normalized.startsWith(allowedEnc.slice(0, -1))\n ) {\n return true\n }\n }\n\n return false\n}\n\ntype BodyPresence = 'missing' | 'empty' | 'present'\n\nfunction getBodyPresence(req: IncomingMessage): BodyPresence {\n if (req.headers['transfer-encoding'] != null) return 'present'\n if (req.headers['content-length'] === '0') return 'empty'\n if (req.headers['content-length'] != null) return 'present'\n return 'missing'\n}\n\nfunction createBodyParser(inputEncoding: string, options: RouteOptions) {\n if (inputEncoding === ENCODING_ANY) {\n // When the lexicon's input encoding is */*, the handler will determine how to process it\n return\n }\n const { jsonLimit, textLimit } = options\n const jsonParser = json({ limit: jsonLimit })\n const textParser = text({ limit: textLimit })\n // Transform json and text parser middlewares into a single function\n return (req: ExpressRequest, res: ExpressResponse) => {\n return new Promise<void>((resolve, reject) => {\n jsonParser(req, res, (err) => {\n if (err) return reject(XRPCError.fromError(err))\n textParser(req, res, (err) => {\n if (err) return reject(XRPCError.fromError(err))\n resolve()\n })\n })\n })\n }\n}\n\nfunction decodeBodyStream(\n req: IncomingMessage,\n maxSize: number | undefined,\n): Readable {\n const contentEncoding = req.headers['content-encoding']\n const contentLength = req.headers['content-length']\n\n const contentLengthParsed = contentLength\n ? parseInt(contentLength, 10)\n : undefined\n\n if (Number.isNaN(contentLengthParsed)) {\n throw new XRPCError(ResponseType.InvalidRequest, 'invalid content-length')\n }\n\n if (\n maxSize !== undefined &&\n contentLengthParsed !== undefined &&\n contentLengthParsed > maxSize\n ) {\n throw new XRPCError(\n ResponseType.PayloadTooLarge,\n 'request entity too large',\n )\n }\n\n let transforms: Duplex[]\n try {\n transforms = createDecoders(contentEncoding)\n } catch (cause) {\n throw new XRPCError(\n ResponseType.UnsupportedMediaType,\n 'unsupported content-encoding',\n undefined,\n { cause },\n )\n }\n\n if (maxSize !== undefined) {\n const maxSizeChecker = new MaxSizeChecker(\n maxSize,\n () =>\n new XRPCError(ResponseType.PayloadTooLarge, 'request entity too large'),\n )\n transforms.push(maxSizeChecker)\n }\n\n return transforms.length > 0\n ? (pipeline([req, ...transforms], () => {}) as Duplex)\n : req\n}\n\nexport function serverTimingHeader(timings: ServerTiming[]) {\n return timings\n .map((timing) => {\n let header = timing.name\n if (timing.duration) header += `;dur=${timing.duration}`\n if (timing.description) header += `;desc=\"${timing.description}\"`\n return header\n })\n .join(', ')\n}\n\nexport class ServerTimer implements ServerTiming {\n public duration?: number\n private startMs?: number\n constructor(\n public name: string,\n public description?: string,\n ) {}\n start() {\n this.startMs = Date.now()\n return this\n }\n stop() {\n assert(this.startMs, \"timer hasn't been started\")\n this.duration = Date.now() - this.startMs\n return this\n }\n}\n\nexport interface ServerTiming {\n name: string\n duration?: number\n description?: string\n}\n\nexport const parseReqNsid = (req: ExpressRequest | IncomingMessage) =>\n parseUrlNsid('originalUrl' in req ? req.originalUrl : req.url || '/')\n\n/**\n * Validates and extracts the nsid from an xrpc path\n */\nexport const parseUrlNsid = (url: string): string => {\n const nsid = extractUrlNsid(url)\n if (nsid) return nsid\n throw new InvalidRequestError('invalid xrpc path')\n}\n\nexport const extractUrlNsid = (url: string): string | undefined => {\n // /!\\ Hot path\n\n if (\n // Ordered by likelihood of failure\n url.length <= 6 ||\n url[5] !== '/' ||\n url[4] !== 'c' ||\n url[3] !== 'p' ||\n url[2] !== 'r' ||\n url[1] !== 'x' ||\n url[0] !== '/'\n ) {\n return undefined\n }\n\n const startOfNsid = 6\n\n let curr = startOfNsid\n let char: number\n let alphaNumRequired = true\n for (; curr < url.length; curr++) {\n char = url.charCodeAt(curr)\n if (\n (char >= 48 && char <= 57) || // 0-9\n (char >= 65 && char <= 90) || // A-Z\n (char >= 97 && char <= 122) // a-z\n ) {\n alphaNumRequired = false\n } else if (char === 45 /* \"-\" */ || char === 46 /* \".\" */) {\n if (alphaNumRequired) {\n return undefined\n }\n alphaNumRequired = true\n } else if (char === 47 /* \"/\" */) {\n // Allow trailing slash (next char is either EOS or \"?\")\n if (curr === url.length - 1 || url.charCodeAt(curr + 1) === 63) {\n break\n }\n return undefined\n } else if (char === 63 /* \"?\"\" */) {\n break\n } else {\n return undefined\n }\n }\n\n // last char was one of: '-', '.', '/'\n if (alphaNumRequired) {\n return undefined\n }\n\n // A domain name consists of minimum two characters\n if (curr - startOfNsid < 2) {\n return undefined\n }\n\n // @TODO check max length of nsid\n\n return url.slice(startOfNsid, curr)\n}\n"]}
package/package.json ADDED
@@ -0,0 +1,68 @@
1
+ {
2
+ "name": "@atproto/xrpc-server",
3
+ "version": "0.0.0-spaces-alpha-20260818163953",
4
+ "license": "MIT",
5
+ "description": "atproto HTTP API (XRPC) server library",
6
+ "keywords": [
7
+ "atproto",
8
+ "xrpc"
9
+ ],
10
+ "homepage": "https://atproto.com",
11
+ "repository": {
12
+ "type": "git",
13
+ "url": "https://github.com/bluesky-social/atproto",
14
+ "directory": "packages/xrpc-server"
15
+ },
16
+ "files": [
17
+ "./dist",
18
+ "./README.md",
19
+ "./CHANGELOG.md"
20
+ ],
21
+ "type": "module",
22
+ "exports": {
23
+ ".": {
24
+ "types": "./dist/index.d.ts",
25
+ "default": "./dist/index.js"
26
+ }
27
+ },
28
+ "engines": {
29
+ "node": ">=22"
30
+ },
31
+ "dependencies": {
32
+ "express": "^4.17.2",
33
+ "http-errors": "^2.0.0",
34
+ "mime-types": "^3.0.2",
35
+ "rate-limiter-flexible": "^2.4.1",
36
+ "ws": "^8.12.0",
37
+ "@atproto/common": "^0.0.0-spaces-alpha-20260818163953",
38
+ "@atproto/lex-cbor": "^0.1.6",
39
+ "@atproto/lex-data": "^0.1.7",
40
+ "@atproto/lex-json": "^0.1.6",
41
+ "@atproto/lex-schema": "^0.0.0-spaces-alpha-20260818163953",
42
+ "@atproto/ws-client": "^0.2.0",
43
+ "@atproto/lexicon": "^0.0.0-spaces-alpha-20260818163953",
44
+ "@atproto/xrpc": "^0.0.0-spaces-alpha-20260818163953",
45
+ "@atproto/crypto": "^0.0.0-spaces-alpha-20260818163953",
46
+ "@atproto/lex-client": "^0.0.0-spaces-alpha-20260818163953"
47
+ },
48
+ "devDependencies": {
49
+ "@jest/globals": "^30.0.0",
50
+ "@types/express": "^4.17.13",
51
+ "@types/express-serve-static-core": "^4.17.36",
52
+ "@types/http-errors": "^2.0.4",
53
+ "@types/mime-types": "^3.0.1",
54
+ "@types/ws": "^8.5.4",
55
+ "get-port": "^6.1.2",
56
+ "jest": "^30.0.0",
57
+ "jose": "^5.0.1",
58
+ "key-encoder": "^2.0.3",
59
+ "multiformats": "^13.0.0",
60
+ "@atproto/crypto": "^0.0.0-spaces-alpha-20260818163953",
61
+ "@atproto/lex": "^0.0.0-spaces-alpha-20260818163953",
62
+ "@atproto/lex-document": "^0.0.0-spaces-alpha-20260818163953"
63
+ },
64
+ "scripts": {
65
+ "test": "NODE_OPTIONS=--experimental-vm-modules jest",
66
+ "build": "tsc --build tsconfig.build.json"
67
+ }
68
+ }