@atproto/xrpc-server 0.3.3 → 0.4.1

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/dist/server.d.ts CHANGED
@@ -1,8 +1,8 @@
1
1
  import express, { NextFunction, RequestHandler } from 'express';
2
- import { Lexicons, LexXrpcProcedure, LexXrpcQuery, LexXrpcSubscription } from '@atproto/lexicon';
2
+ import { LexiconDoc, Lexicons, LexXrpcProcedure, LexXrpcQuery, LexXrpcSubscription } from '@atproto/lexicon';
3
3
  import { XrpcStreamServer } from './stream';
4
4
  import { XRPCHandler, XRPCHandlerConfig, Options, XRPCStreamHandlerConfig, XRPCStreamHandler, RateLimiterI, RateLimiterConsume } from './types';
5
- export declare function createServer(lexicons?: unknown[], options?: Options): Server;
5
+ export declare function createServer(lexicons?: LexiconDoc[], options?: Options): Server;
6
6
  export declare class Server {
7
7
  router: import("express-serve-static-core").Express;
8
8
  routes: import("express-serve-static-core").Router;
@@ -13,13 +13,13 @@ export declare class Server {
13
13
  globalRateLimiters: RateLimiterI[];
14
14
  sharedRateLimiters: Record<string, RateLimiterI>;
15
15
  routeRateLimiterFns: Record<string, RateLimiterConsume[]>;
16
- constructor(lexicons?: unknown[], opts?: Options);
16
+ constructor(lexicons?: LexiconDoc[], opts?: Options);
17
17
  method(nsid: string, configOrFn: XRPCHandlerConfig | XRPCHandler): void;
18
18
  addMethod(nsid: string, configOrFn: XRPCHandlerConfig | XRPCHandler): void;
19
19
  streamMethod(nsid: string, configOrFn: XRPCStreamHandlerConfig | XRPCStreamHandler): void;
20
20
  addStreamMethod(nsid: string, configOrFn: XRPCStreamHandlerConfig | XRPCStreamHandler): void;
21
- addLexicon(doc: unknown): void;
22
- addLexicons(docs: unknown[]): void;
21
+ addLexicon(doc: LexiconDoc): void;
22
+ addLexicons(docs: LexiconDoc[]): void;
23
23
  protected addRoute(nsid: string, def: LexXrpcQuery | LexXrpcProcedure, config: XRPCHandlerConfig): Promise<void>;
24
24
  catchall(req: express.Request, _res: express.Response, next: NextFunction): Promise<void>;
25
25
  createHandler(nsid: string, def: LexXrpcQuery | LexXrpcProcedure, handler: XRPCHandler): RequestHandler;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@atproto/xrpc-server",
3
- "version": "0.3.3",
3
+ "version": "0.4.1",
4
4
  "license": "MIT",
5
5
  "description": "atproto HTTP API (XRPC) server library",
6
6
  "keywords": [
@@ -23,9 +23,9 @@
23
23
  "uint8arrays": "3.0.0",
24
24
  "ws": "^8.12.0",
25
25
  "zod": "^3.21.4",
26
- "@atproto/common": "^0.3.2",
27
- "@atproto/crypto": "^0.2.2",
28
- "@atproto/lexicon": "^0.2.3"
26
+ "@atproto/common": "^0.3.3",
27
+ "@atproto/crypto": "^0.3.0",
28
+ "@atproto/lexicon": "^0.3.0"
29
29
  },
30
30
  "devDependencies": {
31
31
  "@types/express": "^4.17.13",
@@ -33,9 +33,11 @@
33
33
  "@types/http-errors": "^2.0.1",
34
34
  "@types/ws": "^8.5.4",
35
35
  "get-port": "^6.1.2",
36
+ "jose": "^4.15.4",
37
+ "key-encoder": "^2.0.3",
36
38
  "multiformats": "^9.9.0",
37
- "@atproto/crypto": "^0.2.2",
38
- "@atproto/xrpc": "^0.3.3"
39
+ "@atproto/crypto": "^0.3.0",
40
+ "@atproto/xrpc": "^0.4.0"
39
41
  },
40
42
  "scripts": {
41
43
  "test": "jest",
package/src/auth.ts CHANGED
@@ -4,10 +4,13 @@ import * as crypto from '@atproto/crypto'
4
4
  import * as ui8 from 'uint8arrays'
5
5
  import { AuthRequiredError } from './types'
6
6
 
7
- type ServiceJwtParams = {
7
+ type ServiceJwtPayload = {
8
8
  iss: string
9
9
  aud: string
10
10
  exp?: number
11
+ }
12
+
13
+ type ServiceJwtParams = ServiceJwtPayload & {
11
14
  keypair: crypto.Keypair
12
15
  }
13
16
 
@@ -45,8 +48,8 @@ const jsonToB64Url = (json: Record<string, unknown>): string => {
45
48
  export const verifyJwt = async (
46
49
  jwtStr: string,
47
50
  ownDid: string | null, // null indicates to skip the audience check
48
- getSigningKey: (did: string) => Promise<string>,
49
- ): Promise<string> => {
51
+ getSigningKey: (did: string, forceRefresh: boolean) => Promise<string>,
52
+ ): Promise<ServiceJwtPayload> => {
50
53
  const parts = jwtStr.split('.')
51
54
  if (parts.length !== 3) {
52
55
  throw new AuthRequiredError('poorly formatted jwt', 'BadJwt')
@@ -66,18 +69,40 @@ export const verifyJwt = async (
66
69
 
67
70
  const msgBytes = ui8.fromString(parts.slice(0, 2).join('.'), 'utf8')
68
71
  const sigBytes = ui8.fromString(sig, 'base64url')
72
+ const verifySignatureWithKey = (key: string) => {
73
+ return crypto.verifySignature(key, msgBytes, sigBytes, {
74
+ allowMalleableSig: true,
75
+ })
76
+ }
69
77
 
70
- const signingKey = await getSigningKey(payload.iss)
78
+ const signingKey = await getSigningKey(payload.iss, false)
71
79
 
72
80
  let validSig: boolean
73
81
  try {
74
- validSig = await crypto.verifySignature(signingKey, msgBytes, sigBytes)
82
+ validSig = await verifySignatureWithKey(signingKey)
75
83
  } catch (err) {
76
84
  throw new AuthRequiredError(
77
85
  'could not verify jwt signature',
78
86
  'BadJwtSignature',
79
87
  )
80
88
  }
89
+
90
+ if (!validSig) {
91
+ // get fresh signing key in case it failed due to a recent rotation
92
+ const freshSigningKey = await getSigningKey(payload.iss, true)
93
+ try {
94
+ validSig =
95
+ freshSigningKey !== signingKey
96
+ ? await verifySignatureWithKey(freshSigningKey)
97
+ : false
98
+ } catch (err) {
99
+ throw new AuthRequiredError(
100
+ 'could not verify jwt signature',
101
+ 'BadJwtSignature',
102
+ )
103
+ }
104
+ }
105
+
81
106
  if (!validSig) {
82
107
  throw new AuthRequiredError(
83
108
  'jwt signature does not match jwt issuer',
@@ -85,7 +110,7 @@ export const verifyJwt = async (
85
110
  )
86
111
  }
87
112
 
88
- return payload.iss
113
+ return payload
89
114
  }
90
115
 
91
116
  const parseB64UrlToJson = (b64: string) => {
package/src/server.ts CHANGED
@@ -5,6 +5,7 @@ import express, {
5
5
  RequestHandler,
6
6
  } from 'express'
7
7
  import {
8
+ LexiconDoc,
8
9
  Lexicons,
9
10
  lexToJson,
10
11
  LexXrpcProcedure,
@@ -45,7 +46,7 @@ import {
45
46
  import log from './logger'
46
47
  import { consumeMany } from './rate-limiter'
47
48
 
48
- export function createServer(lexicons?: unknown[], options?: Options) {
49
+ export function createServer(lexicons?: LexiconDoc[], options?: Options) {
49
50
  return new Server(lexicons, options)
50
51
  }
51
52
 
@@ -60,7 +61,7 @@ export class Server {
60
61
  sharedRateLimiters: Record<string, RateLimiterI>
61
62
  routeRateLimiterFns: Record<string, RateLimiterConsume[]>
62
63
 
63
- constructor(lexicons?: unknown[], opts?: Options) {
64
+ constructor(lexicons?: LexiconDoc[], opts?: Options) {
64
65
  if (lexicons) {
65
66
  this.addLexicons(lexicons)
66
67
  }
@@ -140,11 +141,11 @@ export class Server {
140
141
  // schemas
141
142
  // =
142
143
 
143
- addLexicon(doc: unknown) {
144
+ addLexicon(doc: LexiconDoc) {
144
145
  this.lex.add(doc)
145
146
  }
146
147
 
147
- addLexicons(docs: unknown[]) {
148
+ addLexicons(docs: LexiconDoc[]) {
148
149
  for (const doc of docs) {
149
150
  this.addLexicon(doc)
150
151
  }
package/src/util.ts CHANGED
@@ -60,7 +60,7 @@ export function decodeQueryParam(
60
60
  if (type === 'float') {
61
61
  return Number(String(value))
62
62
  } else if (type === 'integer') {
63
- return Number(String(value)) | 0
63
+ return parseInt(String(value), 10) || 0
64
64
  } else if (type === 'boolean') {
65
65
  return value === 'true'
66
66
  }
@@ -1,5 +1,12 @@
1
- import * as http from 'http'
1
+ import * as http from 'node:http'
2
+ import { KeyObject, createPrivateKey } from 'node:crypto'
2
3
  import getPort from 'get-port'
4
+ import * as jose from 'jose'
5
+ import KeyEncoder from 'key-encoder'
6
+ import * as ui8 from 'uint8arrays'
7
+ import { MINUTE } from '@atproto/common'
8
+ import { Secp256k1Keypair } from '@atproto/crypto'
9
+ import { LexiconDoc } from '@atproto/lexicon'
3
10
  import xrpc, { ServiceClient, XRPCError } from '@atproto/xrpc'
4
11
  import * as xrpcServer from '../src'
5
12
  import {
@@ -9,7 +16,7 @@ import {
9
16
  basicAuthHeaders,
10
17
  } from './_util'
11
18
 
12
- const LEXICONS = [
19
+ const LEXICONS: LexiconDoc[] = [
13
20
  {
14
21
  lexicon: 1,
15
22
  id: 'io.example.authTest',
@@ -131,4 +138,104 @@ describe('Auth', () => {
131
138
  original: 'YWRtaW46cGFzc3dvcmQ=',
132
139
  })
133
140
  })
141
+
142
+ describe('verifyJwt()', () => {
143
+ it('fails on expired jwt.', async () => {
144
+ const keypair = await Secp256k1Keypair.create()
145
+ const jwt = await xrpcServer.createServiceJwt({
146
+ aud: 'did:example:aud',
147
+ iss: 'did:example:iss',
148
+ keypair,
149
+ exp: Math.floor((Date.now() - MINUTE) / 1000),
150
+ })
151
+ const tryVerify = xrpcServer.verifyJwt(
152
+ jwt,
153
+ 'did:example:aud',
154
+ async () => {
155
+ return keypair.did()
156
+ },
157
+ )
158
+ await expect(tryVerify).rejects.toThrow('jwt expired')
159
+ })
160
+
161
+ it('fails on bad audience.', async () => {
162
+ const keypair = await Secp256k1Keypair.create()
163
+ const jwt = await xrpcServer.createServiceJwt({
164
+ aud: 'did:example:aud1',
165
+ iss: 'did:example:iss',
166
+ keypair,
167
+ })
168
+ const tryVerify = xrpcServer.verifyJwt(
169
+ jwt,
170
+ 'did:example:aud2',
171
+ async () => {
172
+ return keypair.did()
173
+ },
174
+ )
175
+ await expect(tryVerify).rejects.toThrow(
176
+ 'jwt audience does not match service did',
177
+ )
178
+ })
179
+
180
+ it('refreshes key on verification failure.', async () => {
181
+ const keypair1 = await Secp256k1Keypair.create()
182
+ const keypair2 = await Secp256k1Keypair.create()
183
+ const jwt = await xrpcServer.createServiceJwt({
184
+ aud: 'did:example:aud',
185
+ iss: 'did:example:iss',
186
+ keypair: keypair2,
187
+ })
188
+ let usedKeypair1 = false
189
+ let usedKeypair2 = false
190
+ const tryVerify = xrpcServer.verifyJwt(
191
+ jwt,
192
+ 'did:example:aud',
193
+ async (_did, forceRefresh) => {
194
+ if (forceRefresh) {
195
+ usedKeypair2 = true
196
+ return keypair2.did()
197
+ } else {
198
+ usedKeypair1 = true
199
+ return keypair1.did()
200
+ }
201
+ },
202
+ )
203
+ await expect(tryVerify).resolves.toMatchObject({
204
+ aud: 'did:example:aud',
205
+ iss: 'did:example:iss',
206
+ })
207
+ expect(usedKeypair1).toBe(true)
208
+ expect(usedKeypair2).toBe(true)
209
+ })
210
+
211
+ it('interoperates with jwts signed by other libraries.', async () => {
212
+ const keypair = await Secp256k1Keypair.create({ exportable: true })
213
+ const signingKey = await createPrivateKeyObject(keypair)
214
+ const payload = {
215
+ aud: 'did:example:aud',
216
+ iss: 'did:example:iss',
217
+ exp: Math.floor((Date.now() + MINUTE) / 1000),
218
+ }
219
+ const jwt = await new jose.SignJWT(payload)
220
+ .setProtectedHeader({ typ: 'JWT', alg: keypair.jwtAlg })
221
+ .sign(signingKey)
222
+ const tryVerify = xrpcServer.verifyJwt(
223
+ jwt,
224
+ 'did:example:aud',
225
+ async () => {
226
+ return keypair.did()
227
+ },
228
+ )
229
+ await expect(tryVerify).resolves.toEqual(payload)
230
+ })
231
+ })
134
232
  })
233
+
234
+ const createPrivateKeyObject = async (
235
+ privateKey: Secp256k1Keypair,
236
+ ): Promise<KeyObject> => {
237
+ const raw = await privateKey.export()
238
+ const encoder = new KeyEncoder('secp256k1')
239
+ const key = encoder.encodePrivate(ui8.toString(raw, 'hex'), 'raw', 'pem')
240
+ return createPrivateKey({ format: 'pem', key })
241
+ }
@@ -2,6 +2,7 @@ import * as http from 'http'
2
2
  import { Readable } from 'stream'
3
3
  import { gzipSync } from 'zlib'
4
4
  import getPort from 'get-port'
5
+ import { LexiconDoc } from '@atproto/lexicon'
5
6
  import xrpc, { ServiceClient } from '@atproto/xrpc'
6
7
  import { bytesToStream, cidForCbor } from '@atproto/common'
7
8
  import { randomBytes } from '@atproto/crypto'
@@ -9,7 +10,7 @@ import { createServer, closeServer } from './_util'
9
10
  import * as xrpcServer from '../src'
10
11
  import logger from '../src/logger'
11
12
 
12
- const LEXICONS = [
13
+ const LEXICONS: LexiconDoc[] = [
13
14
  {
14
15
  lexicon: 1,
15
16
  id: 'io.example.validationTest',
@@ -1,5 +1,6 @@
1
1
  import * as http from 'http'
2
2
  import getPort from 'get-port'
3
+ import { LexiconDoc } from '@atproto/lexicon'
3
4
  import { createServer, closeServer } from './_util'
4
5
  import * as xrpcServer from '../src'
5
6
  import xrpc, {
@@ -9,7 +10,7 @@ import xrpc, {
9
10
  XRPCInvalidResponseError,
10
11
  } from '@atproto/xrpc'
11
12
 
12
- const LEXICONS = [
13
+ const LEXICONS: LexiconDoc[] = [
13
14
  {
14
15
  lexicon: 1,
15
16
  id: 'io.example.error',
@@ -1,11 +1,12 @@
1
1
  import * as http from 'http'
2
+ import { LexiconDoc } from '@atproto/lexicon'
2
3
  import xrpc, { ServiceClient } from '@atproto/xrpc'
3
4
  import { CID } from 'multiformats/cid'
4
5
  import getPort from 'get-port'
5
6
  import { createServer, closeServer } from './_util'
6
7
  import * as xrpcServer from '../src'
7
8
 
8
- const LEXICONS = [
9
+ const LEXICONS: LexiconDoc[] = [
9
10
  {
10
11
  lexicon: 1,
11
12
  id: 'io.example.ipld',
@@ -1,10 +1,11 @@
1
1
  import * as http from 'http'
2
2
  import getPort from 'get-port'
3
+ import { LexiconDoc } from '@atproto/lexicon'
3
4
  import xrpc, { ServiceClient } from '@atproto/xrpc'
4
5
  import { createServer, closeServer } from './_util'
5
6
  import * as xrpcServer from '../src'
6
7
 
7
- const LEXICONS = [
8
+ const LEXICONS: LexiconDoc[] = [
8
9
  {
9
10
  lexicon: 1,
10
11
  id: 'io.example.paramTest',
@@ -1,11 +1,12 @@
1
1
  import * as http from 'http'
2
2
  import { Readable } from 'stream'
3
+ import { LexiconDoc } from '@atproto/lexicon'
3
4
  import xrpc, { ServiceClient } from '@atproto/xrpc'
4
5
  import getPort from 'get-port'
5
6
  import { createServer, closeServer } from './_util'
6
7
  import * as xrpcServer from '../src'
7
8
 
8
- const LEXICONS = [
9
+ const LEXICONS: LexiconDoc[] = [
9
10
  {
10
11
  lexicon: 1,
11
12
  id: 'io.example.pingOne',
@@ -1,10 +1,11 @@
1
1
  import * as http from 'http'
2
2
  import getPort from 'get-port'
3
+ import { LexiconDoc } from '@atproto/lexicon'
3
4
  import xrpc, { ServiceClient } from '@atproto/xrpc'
4
5
  import { createServer, closeServer } from './_util'
5
6
  import * as xrpcServer from '../src'
6
7
 
7
- const LEXICONS = [
8
+ const LEXICONS: LexiconDoc[] = [
8
9
  {
9
10
  lexicon: 1,
10
11
  id: 'io.example.pingOne',
@@ -1,12 +1,13 @@
1
1
  import * as http from 'http'
2
2
  import getPort from 'get-port'
3
+ import { LexiconDoc } from '@atproto/lexicon'
3
4
  import xrpc, { ServiceClient } from '@atproto/xrpc'
4
5
  import { createServer, closeServer } from './_util'
5
6
  import * as xrpcServer from '../src'
6
7
  import { RateLimiter } from '../src'
7
8
  import { MINUTE } from '@atproto/common'
8
9
 
9
- const LEXICONS = [
10
+ const LEXICONS: LexiconDoc[] = [
10
11
  {
11
12
  lexicon: 1,
12
13
  id: 'io.example.routeLimit',
@@ -1,11 +1,12 @@
1
1
  import * as http from 'http'
2
2
  import getPort from 'get-port'
3
+ import { LexiconDoc } from '@atproto/lexicon'
3
4
  import xrpc, { ServiceClient } from '@atproto/xrpc'
4
5
  import { byteIterableToStream } from '@atproto/common'
5
6
  import { createServer, closeServer } from './_util'
6
7
  import * as xrpcServer from '../src'
7
8
 
8
- const LEXICONS = [
9
+ const LEXICONS: LexiconDoc[] = [
9
10
  {
10
11
  lexicon: 1,
11
12
  id: 'io.example.readableStream',
@@ -2,6 +2,7 @@ import * as http from 'http'
2
2
  import { WebSocket, WebSocketServer, createWebSocketStream } from 'ws'
3
3
  import getPort from 'get-port'
4
4
  import { wait } from '@atproto/common'
5
+ import { LexiconDoc } from '@atproto/lexicon'
5
6
  import { byFrame, MessageFrame, ErrorFrame, Frame, Subscription } from '../src'
6
7
  import {
7
8
  createServer,
@@ -11,7 +12,7 @@ import {
11
12
  } from './_util'
12
13
  import * as xrpcServer from '../src'
13
14
 
14
- const LEXICONS = [
15
+ const LEXICONS: LexiconDoc[] = [
15
16
  {
16
17
  lexicon: 1,
17
18
  id: 'io.example.streamOne',
package/LICENSE DELETED
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2022-2023 Bluesky PBC
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.