@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.
- package/CHANGELOG.md +921 -0
- package/LICENSE.txt +7 -0
- package/README.md +62 -0
- package/dist/auth.d.ts +30 -0
- package/dist/auth.d.ts.map +1 -0
- package/dist/auth.js +147 -0
- package/dist/auth.js.map +1 -0
- package/dist/errors.d.ts +60 -0
- package/dist/errors.d.ts.map +1 -0
- package/dist/errors.js +187 -0
- package/dist/errors.js.map +1 -0
- package/dist/index.d.ts +9 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +8 -0
- package/dist/index.js.map +1 -0
- package/dist/logger.d.ts +5 -0
- package/dist/logger.d.ts.map +1 -0
- package/dist/logger.js +5 -0
- package/dist/logger.js.map +1 -0
- package/dist/rate-limiter-http.d.ts +24 -0
- package/dist/rate-limiter-http.d.ts.map +1 -0
- package/dist/rate-limiter-http.js +53 -0
- package/dist/rate-limiter-http.js.map +1 -0
- package/dist/rate-limiter.d.ts +95 -0
- package/dist/rate-limiter.d.ts.map +1 -0
- package/dist/rate-limiter.js +168 -0
- package/dist/rate-limiter.js.map +1 -0
- package/dist/server.d.ts +52 -0
- package/dist/server.d.ts.map +1 -0
- package/dist/server.js +487 -0
- package/dist/server.js.map +1 -0
- package/dist/stream/frames.d.ts +31 -0
- package/dist/stream/frames.d.ts.map +1 -0
- package/dist/stream/frames.js +100 -0
- package/dist/stream/frames.js.map +1 -0
- package/dist/stream/index.d.ts +6 -0
- package/dist/stream/index.d.ts.map +1 -0
- package/dist/stream/index.js +6 -0
- package/dist/stream/index.js.map +1 -0
- package/dist/stream/logger.d.ts +4 -0
- package/dist/stream/logger.d.ts.map +1 -0
- package/dist/stream/logger.js +4 -0
- package/dist/stream/logger.js.map +1 -0
- package/dist/stream/server.d.ts +23 -0
- package/dist/stream/server.d.ts.map +1 -0
- package/dist/stream/server.js +70 -0
- package/dist/stream/server.js.map +1 -0
- package/dist/stream/stream.d.ts +8 -0
- package/dist/stream/stream.d.ts.map +1 -0
- package/dist/stream/stream.js +37 -0
- package/dist/stream/stream.js.map +1 -0
- package/dist/stream/subscription.d.ts +31 -0
- package/dist/stream/subscription.d.ts.map +1 -0
- package/dist/stream/subscription.js +92 -0
- package/dist/stream/subscription.js.map +1 -0
- package/dist/stream/types.d.ts +29 -0
- package/dist/stream/types.d.ts.map +1 -0
- package/dist/stream/types.js +19 -0
- package/dist/stream/types.js.map +1 -0
- package/dist/types.d.ts +166 -0
- package/dist/types.d.ts.map +1 -0
- package/dist/types.js +46 -0
- package/dist/types.js.map +1 -0
- package/dist/util.d.ts +45 -0
- package/dist/util.d.ts.map +1 -0
- package/dist/util.js +516 -0
- package/dist/util.js.map +1 -0
- package/package.json +68 -0
package/LICENSE.txt
ADDED
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
Dual MIT/Apache-2.0 License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2022-2026 Bluesky Social PBC, and Contributors
|
|
4
|
+
|
|
5
|
+
Except as otherwise noted in individual files, this software is licensed under the MIT license (<http://opensource.org/licenses/MIT>), or the Apache License, Version 2.0 (<http://www.apache.org/licenses/LICENSE-2.0>).
|
|
6
|
+
|
|
7
|
+
Downstream projects and end users may chose either license individually, or both together, at their discretion. The motivation for this dual-licensing is the additional software patent assurance provided by Apache 2.0.
|
package/README.md
ADDED
|
@@ -0,0 +1,62 @@
|
|
|
1
|
+
# @atproto/xrpc-server: atproto HTTP API server library
|
|
2
|
+
|
|
3
|
+
TypeScript library for implementing [atproto](https://atproto.com) HTTP API services, with Lexicon schema validation.
|
|
4
|
+
|
|
5
|
+
[](https://www.npmjs.com/package/@atproto/xrpc-server)
|
|
6
|
+
[](https://github.com/bluesky-social/atproto/actions/workflows/repo.yaml)
|
|
7
|
+
|
|
8
|
+
## Usage
|
|
9
|
+
|
|
10
|
+
```typescript
|
|
11
|
+
import { LexiconDoc } from '@atproto/lexicon'
|
|
12
|
+
import * as xrpc from '@atproto/xrpc-server'
|
|
13
|
+
import express from 'express'
|
|
14
|
+
|
|
15
|
+
const lexicons: LexiconDoc[] = [
|
|
16
|
+
{
|
|
17
|
+
lexicon: 1,
|
|
18
|
+
id: 'io.example.ping',
|
|
19
|
+
defs: {
|
|
20
|
+
main: {
|
|
21
|
+
type: 'query',
|
|
22
|
+
parameters: {
|
|
23
|
+
type: 'params',
|
|
24
|
+
properties: { message: { type: 'string' } },
|
|
25
|
+
},
|
|
26
|
+
output: {
|
|
27
|
+
encoding: 'application/json',
|
|
28
|
+
},
|
|
29
|
+
},
|
|
30
|
+
},
|
|
31
|
+
},
|
|
32
|
+
]
|
|
33
|
+
|
|
34
|
+
// create xrpc server
|
|
35
|
+
const server = xrpc.createServer(lexicons)
|
|
36
|
+
|
|
37
|
+
function ping(ctx: {
|
|
38
|
+
auth: xrpc.HandlerAuth | undefined
|
|
39
|
+
params: xrpc.Params
|
|
40
|
+
input: xrpc.HandlerInput | undefined
|
|
41
|
+
req: express.Request
|
|
42
|
+
res: express.Response
|
|
43
|
+
}) {
|
|
44
|
+
return { encoding: 'application/json', body: { message: ctx.params.message } }
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
server.method('io.example.ping', ping)
|
|
48
|
+
|
|
49
|
+
// mount in express
|
|
50
|
+
const app = express()
|
|
51
|
+
app.use(server.router)
|
|
52
|
+
app.listen(8080)
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## License
|
|
56
|
+
|
|
57
|
+
This project is dual-licensed under MIT and Apache 2.0 terms:
|
|
58
|
+
|
|
59
|
+
- MIT license ([LICENSE-MIT.txt](https://github.com/bluesky-social/atproto/blob/main/LICENSE-MIT.txt) or http://opensource.org/licenses/MIT)
|
|
60
|
+
- Apache License, Version 2.0, ([LICENSE-APACHE.txt](https://github.com/bluesky-social/atproto/blob/main/LICENSE-APACHE.txt) or http://www.apache.org/licenses/LICENSE-2.0)
|
|
61
|
+
|
|
62
|
+
Downstream projects and end users may chose either license individually, or both together, at their discretion. The motivation for this dual-licensing is the additional software patent assurance provided by Apache 2.0.
|
package/dist/auth.d.ts
ADDED
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import * as crypto from '@atproto/crypto';
|
|
2
|
+
import { type DidString } from '@atproto/lex-schema';
|
|
3
|
+
type ServiceJwtParams = {
|
|
4
|
+
iss: string;
|
|
5
|
+
aud: string;
|
|
6
|
+
iat?: number;
|
|
7
|
+
exp?: number;
|
|
8
|
+
lxm: string | null;
|
|
9
|
+
keypair: crypto.Keypair;
|
|
10
|
+
};
|
|
11
|
+
type ServiceJwtPayload = {
|
|
12
|
+
iss: DidString | `${DidString}#${string}`;
|
|
13
|
+
aud: string;
|
|
14
|
+
exp: number;
|
|
15
|
+
lxm?: string;
|
|
16
|
+
jti?: string;
|
|
17
|
+
};
|
|
18
|
+
export declare const createServiceJwt: (params: ServiceJwtParams) => Promise<string>;
|
|
19
|
+
export declare const createServiceAuthHeaders: (params: ServiceJwtParams) => Promise<{
|
|
20
|
+
headers: {
|
|
21
|
+
authorization: string;
|
|
22
|
+
};
|
|
23
|
+
}>;
|
|
24
|
+
export type VerifySignatureWithKeyFn = (key: string, msgBytes: Uint8Array, sigBytes: Uint8Array, alg: string) => Promise<boolean>;
|
|
25
|
+
export declare const verifyJwt: (jwtStr: string, ownDid: string | null, // null indicates to skip the audience check
|
|
26
|
+
lxm: string | null, // null indicates to skip the lxm check
|
|
27
|
+
getSigningKey: (iss: DidString | `${DidString}#${string}`, forceRefresh: boolean) => Promise<string>, verifySignatureWithKey?: VerifySignatureWithKeyFn) => Promise<ServiceJwtPayload>;
|
|
28
|
+
export declare const cryptoVerifySignatureWithKey: VerifySignatureWithKeyFn;
|
|
29
|
+
export {};
|
|
30
|
+
//# sourceMappingURL=auth.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"auth.d.ts","sourceRoot":"","sources":["../src/auth.ts"],"names":[],"mappings":"AAEA,OA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
package/dist/auth.js
ADDED
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
import * as common from '@atproto/common';
|
|
2
|
+
import { MINUTE } from '@atproto/common';
|
|
3
|
+
import * as crypto from '@atproto/crypto';
|
|
4
|
+
import { isDidString } from '@atproto/lex-schema';
|
|
5
|
+
import { AuthRequiredError } from './errors.js';
|
|
6
|
+
export const createServiceJwt = async (params) => {
|
|
7
|
+
const { iss, aud, keypair } = params;
|
|
8
|
+
const iat = params.iat ?? Math.floor(Date.now() / 1e3);
|
|
9
|
+
const exp = params.exp ?? iat + MINUTE / 1e3;
|
|
10
|
+
const lxm = params.lxm ?? undefined;
|
|
11
|
+
const jti = await crypto.randomStr(16, 'hex');
|
|
12
|
+
const header = {
|
|
13
|
+
typ: 'JWT',
|
|
14
|
+
alg: keypair.jwtAlg,
|
|
15
|
+
};
|
|
16
|
+
const payload = common.noUndefinedVals({
|
|
17
|
+
iat,
|
|
18
|
+
iss,
|
|
19
|
+
aud,
|
|
20
|
+
exp,
|
|
21
|
+
lxm,
|
|
22
|
+
jti,
|
|
23
|
+
});
|
|
24
|
+
const toSignStr = `${jsonToB64Url(header)}.${jsonToB64Url(payload)}`;
|
|
25
|
+
const toSign = Buffer.from(toSignStr, 'utf8');
|
|
26
|
+
const sig = Buffer.from(await keypair.sign(toSign));
|
|
27
|
+
return `${toSignStr}.${sig.toString('base64url')}`;
|
|
28
|
+
};
|
|
29
|
+
export const createServiceAuthHeaders = async (params) => {
|
|
30
|
+
const jwt = await createServiceJwt(params);
|
|
31
|
+
return {
|
|
32
|
+
headers: { authorization: `Bearer ${jwt}` },
|
|
33
|
+
};
|
|
34
|
+
};
|
|
35
|
+
const jsonToB64Url = (json) => {
|
|
36
|
+
return Buffer.from(JSON.stringify(json)).toString('base64url');
|
|
37
|
+
};
|
|
38
|
+
export const verifyJwt = async (jwtStr, ownDid, // null indicates to skip the audience check
|
|
39
|
+
lxm, // null indicates to skip the lxm check
|
|
40
|
+
getSigningKey, verifySignatureWithKey = cryptoVerifySignatureWithKey) => {
|
|
41
|
+
const parts = jwtStr.split('.');
|
|
42
|
+
if (parts.length !== 3) {
|
|
43
|
+
throw new AuthRequiredError('poorly formatted jwt', 'BadJwt');
|
|
44
|
+
}
|
|
45
|
+
const header = parseHeader(parts[0]);
|
|
46
|
+
// The spec does not describe what to do with the "typ" claim. We can,
|
|
47
|
+
// however, forbid some values that are not compatible with our use case.
|
|
48
|
+
if (
|
|
49
|
+
// service tokens are not OAuth 2.0 access tokens
|
|
50
|
+
// https://datatracker.ietf.org/doc/html/rfc9068
|
|
51
|
+
header['typ'] === 'at+jwt' ||
|
|
52
|
+
// "refresh+jwt" is a non-standard type used by the @atproto packages
|
|
53
|
+
header['typ'] === 'refresh+jwt' ||
|
|
54
|
+
// "DPoP" proofs are not meant to be used as service tokens
|
|
55
|
+
// https://datatracker.ietf.org/doc/html/rfc9449
|
|
56
|
+
header['typ'] === 'dpop+jwt') {
|
|
57
|
+
throw new AuthRequiredError(`Invalid jwt type "${header['typ']}"`, 'BadJwtType');
|
|
58
|
+
}
|
|
59
|
+
const payload = parsePayload(parts[1]);
|
|
60
|
+
const sig = parts[2];
|
|
61
|
+
if (Date.now() / 1000 > payload.exp) {
|
|
62
|
+
throw new AuthRequiredError('jwt expired', 'JwtExpired');
|
|
63
|
+
}
|
|
64
|
+
if (ownDid !== null && payload.aud !== ownDid) {
|
|
65
|
+
throw new AuthRequiredError('jwt audience does not match service did', 'BadJwtAudience');
|
|
66
|
+
}
|
|
67
|
+
if (lxm !== null && payload.lxm !== lxm) {
|
|
68
|
+
throw new AuthRequiredError(payload.lxm !== undefined
|
|
69
|
+
? `bad jwt lexicon method ("lxm"). must match: ${lxm}`
|
|
70
|
+
: `missing jwt lexicon method ("lxm"). must match: ${lxm}`, 'BadJwtLexiconMethod');
|
|
71
|
+
}
|
|
72
|
+
if (!payload.iss || !isDidStringOrService(payload.iss)) {
|
|
73
|
+
throw new AuthRequiredError('jwt iss is not a valid did', 'BadJwtIss');
|
|
74
|
+
}
|
|
75
|
+
const msgBytes = Buffer.from(parts.slice(0, 2).join('.'), 'utf8');
|
|
76
|
+
const sigBytes = Buffer.from(sig, 'base64url');
|
|
77
|
+
const signingKey = await getSigningKey(payload.iss, false);
|
|
78
|
+
const { alg } = header;
|
|
79
|
+
let validSig;
|
|
80
|
+
try {
|
|
81
|
+
validSig = await verifySignatureWithKey(signingKey, msgBytes, sigBytes, alg);
|
|
82
|
+
}
|
|
83
|
+
catch (err) {
|
|
84
|
+
throw new AuthRequiredError('could not verify jwt signature', 'BadJwtSignature');
|
|
85
|
+
}
|
|
86
|
+
if (!validSig) {
|
|
87
|
+
// get fresh signing key in case it failed due to a recent rotation
|
|
88
|
+
const freshSigningKey = await getSigningKey(payload.iss, true);
|
|
89
|
+
try {
|
|
90
|
+
validSig =
|
|
91
|
+
freshSigningKey !== signingKey
|
|
92
|
+
? await verifySignatureWithKey(freshSigningKey, msgBytes, sigBytes, alg)
|
|
93
|
+
: false;
|
|
94
|
+
}
|
|
95
|
+
catch (err) {
|
|
96
|
+
throw new AuthRequiredError('could not verify jwt signature', 'BadJwtSignature');
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
if (!validSig) {
|
|
100
|
+
throw new AuthRequiredError('jwt signature does not match jwt issuer', 'BadJwtSignature');
|
|
101
|
+
}
|
|
102
|
+
return payload;
|
|
103
|
+
};
|
|
104
|
+
export const cryptoVerifySignatureWithKey = async (key, msgBytes, sigBytes, alg) => {
|
|
105
|
+
return crypto.verifySignature(key, msgBytes, sigBytes, {
|
|
106
|
+
jwtAlg: alg,
|
|
107
|
+
allowMalleableSig: true,
|
|
108
|
+
});
|
|
109
|
+
};
|
|
110
|
+
const parseB64UrlToJson = (b64) => {
|
|
111
|
+
return JSON.parse(Buffer.from(b64, 'base64url').toString('utf8'));
|
|
112
|
+
};
|
|
113
|
+
const parseHeader = (b64) => {
|
|
114
|
+
const header = parseB64UrlToJson(b64);
|
|
115
|
+
if (!header || typeof header !== 'object' || typeof header.alg !== 'string') {
|
|
116
|
+
throw new AuthRequiredError('poorly formatted jwt', 'BadJwt');
|
|
117
|
+
}
|
|
118
|
+
return header;
|
|
119
|
+
};
|
|
120
|
+
const parsePayload = (b64) => {
|
|
121
|
+
const payload = parseB64UrlToJson(b64);
|
|
122
|
+
if (!payload ||
|
|
123
|
+
typeof payload !== 'object' ||
|
|
124
|
+
typeof payload.iss !== 'string' ||
|
|
125
|
+
typeof payload.aud !== 'string' ||
|
|
126
|
+
typeof payload.exp !== 'number' ||
|
|
127
|
+
(payload.lxm && typeof payload.lxm !== 'string') ||
|
|
128
|
+
(payload.nonce && typeof payload.nonce !== 'string')) {
|
|
129
|
+
throw new AuthRequiredError('poorly formatted jwt', 'BadJwt');
|
|
130
|
+
}
|
|
131
|
+
return payload;
|
|
132
|
+
};
|
|
133
|
+
function isDidStringOrService(value) {
|
|
134
|
+
const hashIdx = value.indexOf('#');
|
|
135
|
+
if (hashIdx === -1) {
|
|
136
|
+
return isDidString(value);
|
|
137
|
+
}
|
|
138
|
+
// basic validation of the fragment part
|
|
139
|
+
const fragmentLen = value.length - hashIdx - 1;
|
|
140
|
+
if (fragmentLen < 1 || value.includes('#', hashIdx + 1)) {
|
|
141
|
+
return false;
|
|
142
|
+
}
|
|
143
|
+
// Validate the did part
|
|
144
|
+
const didPart = value.slice(0, hashIdx);
|
|
145
|
+
return isDidString(didPart);
|
|
146
|
+
}
|
|
147
|
+
//# sourceMappingURL=auth.js.map
|
package/dist/auth.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"auth.js","sourceRoot":"","sources":["../src/auth.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,MAAM,iBAAiB,CAAA;AACzC,OAAO,EAAE,MAAM,EAAE,MAAM,iBAAiB,CAAA;AACxC,OAAO,KAAK,MAAM,MAAM,iBAAiB,CAAA;AACzC,OAAO,EAAkB,WAAW,EAAE,MAAM,qBAAqB,CAAA;AACjE,OAAO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G,EAAE,OAAO,GAAG,CAAC,CAAC,EAAE,CAAC;QACxD,OAAO,KAAK,CAAA;IACd,CAAC;IAED,wBAAwB;IACxB,MAAM,OAAO,GAAG,KAAK,CAAC,KAAK,CAAC,CAAC,EAAE,OAAO,CAAC,CAAA;IACvC,OAAO,WAAW,CAAC,OAAO,CAAC,CAAA;AAC7B,CAAC","sourcesContent":["import * as common from '@atproto/common'\nimport { MINUTE } from '@atproto/common'\nimport * as crypto from '@atproto/crypto'\nimport { type DidString, isDidString } from '@atproto/lex-schema'\nimport { AuthRequiredError } from './errors.js'\n\ntype ServiceJwtParams = {\n iss: string\n aud: string\n iat?: number\n exp?: number\n lxm: string | null\n keypair: crypto.Keypair\n}\n\ntype ServiceJwtHeaders = {\n alg: string\n} & Record<string, unknown>\n\ntype ServiceJwtPayload = {\n iss: DidString | `${DidString}#${string}`\n aud: string\n exp: number\n lxm?: string\n jti?: string\n}\n\nexport const createServiceJwt = async (\n params: ServiceJwtParams,\n): Promise<string> => {\n const { iss, aud, keypair } = params\n const iat = params.iat ?? Math.floor(Date.now() / 1e3)\n const exp = params.exp ?? iat + MINUTE / 1e3\n const lxm = params.lxm ?? undefined\n const jti = await crypto.randomStr(16, 'hex')\n const header = {\n typ: 'JWT',\n alg: keypair.jwtAlg,\n }\n const payload = common.noUndefinedVals({\n iat,\n iss,\n aud,\n exp,\n lxm,\n jti,\n })\n const toSignStr = `${jsonToB64Url(header)}.${jsonToB64Url(payload)}`\n const toSign = Buffer.from(toSignStr, 'utf8')\n const sig = Buffer.from(await keypair.sign(toSign))\n return `${toSignStr}.${sig.toString('base64url')}`\n}\n\nexport const createServiceAuthHeaders = async (params: ServiceJwtParams) => {\n const jwt = await createServiceJwt(params)\n return {\n headers: { authorization: `Bearer ${jwt}` },\n }\n}\n\nconst jsonToB64Url = (json: Record<string, unknown>): string => {\n return Buffer.from(JSON.stringify(json)).toString('base64url')\n}\n\nexport type VerifySignatureWithKeyFn = (\n key: string,\n msgBytes: Uint8Array,\n sigBytes: Uint8Array,\n alg: string,\n) => Promise<boolean>\n\nexport const verifyJwt = async (\n jwtStr: string,\n ownDid: string | null, // null indicates to skip the audience check\n lxm: string | null, // null indicates to skip the lxm check\n getSigningKey: (\n iss: DidString | `${DidString}#${string}`,\n forceRefresh: boolean,\n ) => Promise<string>,\n verifySignatureWithKey: VerifySignatureWithKeyFn = cryptoVerifySignatureWithKey,\n): Promise<ServiceJwtPayload> => {\n const parts = jwtStr.split('.')\n if (parts.length !== 3) {\n throw new AuthRequiredError('poorly formatted jwt', 'BadJwt')\n }\n\n const header = parseHeader(parts[0])\n\n // The spec does not describe what to do with the \"typ\" claim. We can,\n // however, forbid some values that are not compatible with our use case.\n if (\n // service tokens are not OAuth 2.0 access tokens\n // https://datatracker.ietf.org/doc/html/rfc9068\n header['typ'] === 'at+jwt' ||\n // \"refresh+jwt\" is a non-standard type used by the @atproto packages\n header['typ'] === 'refresh+jwt' ||\n // \"DPoP\" proofs are not meant to be used as service tokens\n // https://datatracker.ietf.org/doc/html/rfc9449\n header['typ'] === 'dpop+jwt'\n ) {\n throw new AuthRequiredError(\n `Invalid jwt type \"${header['typ']}\"`,\n 'BadJwtType',\n )\n }\n\n const payload = parsePayload(parts[1])\n const sig = parts[2]\n\n if (Date.now() / 1000 > payload.exp) {\n throw new AuthRequiredError('jwt expired', 'JwtExpired')\n }\n if (ownDid !== null && payload.aud !== ownDid) {\n throw new AuthRequiredError(\n 'jwt audience does not match service did',\n 'BadJwtAudience',\n )\n }\n if (lxm !== null && payload.lxm !== lxm) {\n throw new AuthRequiredError(\n payload.lxm !== undefined\n ? `bad jwt lexicon method (\"lxm\"). must match: ${lxm}`\n : `missing jwt lexicon method (\"lxm\"). must match: ${lxm}`,\n 'BadJwtLexiconMethod',\n )\n }\n if (!payload.iss || !isDidStringOrService(payload.iss)) {\n throw new AuthRequiredError('jwt iss is not a valid did', 'BadJwtIss')\n }\n\n const msgBytes = Buffer.from(parts.slice(0, 2).join('.'), 'utf8')\n const sigBytes = Buffer.from(sig, 'base64url')\n\n const signingKey = await getSigningKey(payload.iss, false)\n const { alg } = header\n\n let validSig: boolean\n try {\n validSig = await verifySignatureWithKey(signingKey, msgBytes, sigBytes, alg)\n } catch (err) {\n throw new AuthRequiredError(\n 'could not verify jwt signature',\n 'BadJwtSignature',\n )\n }\n\n if (!validSig) {\n // get fresh signing key in case it failed due to a recent rotation\n const freshSigningKey = await getSigningKey(payload.iss, true)\n try {\n validSig =\n freshSigningKey !== signingKey\n ? await verifySignatureWithKey(\n freshSigningKey,\n msgBytes,\n sigBytes,\n alg,\n )\n : false\n } catch (err) {\n throw new AuthRequiredError(\n 'could not verify jwt signature',\n 'BadJwtSignature',\n )\n }\n }\n\n if (!validSig) {\n throw new AuthRequiredError(\n 'jwt signature does not match jwt issuer',\n 'BadJwtSignature',\n )\n }\n\n return payload\n}\n\nexport const cryptoVerifySignatureWithKey: VerifySignatureWithKeyFn = async (\n key: string,\n msgBytes: Uint8Array,\n sigBytes: Uint8Array,\n alg: string,\n) => {\n return crypto.verifySignature(key, msgBytes, sigBytes, {\n jwtAlg: alg,\n allowMalleableSig: true,\n })\n}\n\nconst parseB64UrlToJson = (b64: string) => {\n return JSON.parse(Buffer.from(b64, 'base64url').toString('utf8'))\n}\n\nconst parseHeader = (b64: string): ServiceJwtHeaders => {\n const header = parseB64UrlToJson(b64)\n if (!header || typeof header !== 'object' || typeof header.alg !== 'string') {\n throw new AuthRequiredError('poorly formatted jwt', 'BadJwt')\n }\n return header\n}\n\nconst parsePayload = (b64: string): ServiceJwtPayload => {\n const payload = parseB64UrlToJson(b64)\n if (\n !payload ||\n typeof payload !== 'object' ||\n typeof payload.iss !== 'string' ||\n typeof payload.aud !== 'string' ||\n typeof payload.exp !== 'number' ||\n (payload.lxm && typeof payload.lxm !== 'string') ||\n (payload.nonce && typeof payload.nonce !== 'string')\n ) {\n throw new AuthRequiredError('poorly formatted jwt', 'BadJwt')\n }\n return payload\n}\n\nfunction isDidStringOrService(\n value: string,\n): value is DidString | `${DidString}#${string}` {\n const hashIdx = value.indexOf('#')\n if (hashIdx === -1) {\n return isDidString(value)\n }\n\n // basic validation of the fragment part\n const fragmentLen = value.length - hashIdx - 1\n if (fragmentLen < 1 || value.includes('#', hashIdx + 1)) {\n return false\n }\n\n // Validate the did part\n const didPart = value.slice(0, hashIdx)\n return isDidString(didPart)\n}\n"]}
|
package/dist/errors.d.ts
ADDED
|
@@ -0,0 +1,60 @@
|
|
|
1
|
+
import { l } from '@atproto/lex-schema';
|
|
2
|
+
import { ResponseType } from '@atproto/xrpc';
|
|
3
|
+
export declare const errorResult: l.ObjectSchema<{
|
|
4
|
+
readonly status: l.IntegerSchema;
|
|
5
|
+
readonly error: l.OptionalSchema<l.StringSchema<{}>>;
|
|
6
|
+
readonly message: l.OptionalSchema<l.StringSchema<{}>>;
|
|
7
|
+
}>;
|
|
8
|
+
export type ErrorResult = l.Infer<typeof errorResult>;
|
|
9
|
+
export declare function isErrorResult(v: unknown): v is ErrorResult;
|
|
10
|
+
export declare function excludeErrorResult<V>(v: V): Exclude<V, ErrorResult>;
|
|
11
|
+
export { ResponseType };
|
|
12
|
+
export declare class XRPCError extends Error {
|
|
13
|
+
type: ResponseType;
|
|
14
|
+
errorMessage?: string | undefined;
|
|
15
|
+
customErrorName?: string | undefined;
|
|
16
|
+
constructor(type: ResponseType, errorMessage?: string | undefined, customErrorName?: string | undefined, options?: ErrorOptions);
|
|
17
|
+
get statusCode(): number;
|
|
18
|
+
get error(): string | undefined;
|
|
19
|
+
get payload(): {
|
|
20
|
+
error: string | undefined;
|
|
21
|
+
message: string | undefined;
|
|
22
|
+
};
|
|
23
|
+
get typeName(): string | undefined;
|
|
24
|
+
get typeStr(): string | undefined;
|
|
25
|
+
static fromError(cause: unknown): XRPCError;
|
|
26
|
+
static fromErrorResult(err: ErrorResult): XRPCError;
|
|
27
|
+
}
|
|
28
|
+
export declare class InvalidRequestError extends XRPCError {
|
|
29
|
+
constructor(errorMessage?: string, customErrorName?: string, options?: ErrorOptions);
|
|
30
|
+
[Symbol.hasInstance](instance: unknown): boolean;
|
|
31
|
+
}
|
|
32
|
+
export declare class AuthRequiredError extends XRPCError {
|
|
33
|
+
constructor(errorMessage?: string, customErrorName?: string, options?: ErrorOptions);
|
|
34
|
+
[Symbol.hasInstance](instance: unknown): boolean;
|
|
35
|
+
}
|
|
36
|
+
export declare class ForbiddenError extends XRPCError {
|
|
37
|
+
constructor(errorMessage?: string, customErrorName?: string, options?: ErrorOptions);
|
|
38
|
+
[Symbol.hasInstance](instance: unknown): boolean;
|
|
39
|
+
}
|
|
40
|
+
export declare class InternalServerError extends XRPCError {
|
|
41
|
+
constructor(errorMessage?: string, customErrorName?: string, options?: ErrorOptions);
|
|
42
|
+
[Symbol.hasInstance](instance: unknown): boolean;
|
|
43
|
+
}
|
|
44
|
+
export declare class UpstreamFailureError extends XRPCError {
|
|
45
|
+
constructor(errorMessage?: string, customErrorName?: string, options?: ErrorOptions);
|
|
46
|
+
[Symbol.hasInstance](instance: unknown): boolean;
|
|
47
|
+
}
|
|
48
|
+
export declare class NotEnoughResourcesError extends XRPCError {
|
|
49
|
+
constructor(errorMessage?: string, customErrorName?: string, options?: ErrorOptions);
|
|
50
|
+
[Symbol.hasInstance](instance: unknown): boolean;
|
|
51
|
+
}
|
|
52
|
+
export declare class UpstreamTimeoutError extends XRPCError {
|
|
53
|
+
constructor(errorMessage?: string, customErrorName?: string, options?: ErrorOptions);
|
|
54
|
+
[Symbol.hasInstance](instance: unknown): boolean;
|
|
55
|
+
}
|
|
56
|
+
export declare class MethodNotImplementedError extends XRPCError {
|
|
57
|
+
constructor(errorMessage?: string, customErrorName?: string, options?: ErrorOptions);
|
|
58
|
+
[Symbol.hasInstance](instance: unknown): boolean;
|
|
59
|
+
}
|
|
60
|
+
//# sourceMappingURL=errors.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors.d.ts","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"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,CAAC,EAAE,MAAM,EACxB,OAAO,CAAC,EAAE,YAAY,EAGvB;IAED,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC,QAAQ,EAAE,OAAO,GAAG,OAAO,CAK/C;CACF;AAED,qBAAa,yBAA0B,SAAQ,SAAS;IACtD,YACE,YAAY,CAAC,EAAE,MAAM,EACrB,eAAe,CAAC,EAAE,MAAM,EACxB,OAAO,CAAC,EAAE,YAAY,EAQvB;IAED,CAAC,MAAM,CAAC,WAAW,CAAC,CAAC,QAAQ,EAAE,OAAO,GAAG,OAAO,CAK/C;CACF"}
|
package/dist/errors.js
ADDED
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
import httpErrors from 'http-errors';
|
|
2
|
+
const { isHttpError } = httpErrors;
|
|
3
|
+
import { LexError, XrpcError } from '@atproto/lex-client';
|
|
4
|
+
import { l } from '@atproto/lex-schema';
|
|
5
|
+
import { ResponseType, ResponseTypeStrings, XRPCError as XRPCClientError, httpResponseCodeToName, httpResponseCodeToString, } from '@atproto/xrpc';
|
|
6
|
+
// @NOTE Do not depend (directly or indirectly) on "./types" here, as it would
|
|
7
|
+
// create a circular dependency.
|
|
8
|
+
export const errorResult = l.object({
|
|
9
|
+
status: l.integer({ minimum: 400 }),
|
|
10
|
+
error: l.optional(l.string()),
|
|
11
|
+
message: l.optional(l.string()),
|
|
12
|
+
});
|
|
13
|
+
export function isErrorResult(v) {
|
|
14
|
+
return errorResult.safeParse(v).success;
|
|
15
|
+
}
|
|
16
|
+
export function excludeErrorResult(v) {
|
|
17
|
+
if (isErrorResult(v))
|
|
18
|
+
throw XRPCError.fromErrorResult(v);
|
|
19
|
+
return v;
|
|
20
|
+
}
|
|
21
|
+
export { ResponseType };
|
|
22
|
+
export class XRPCError extends Error {
|
|
23
|
+
constructor(type, errorMessage, customErrorName, options) {
|
|
24
|
+
super(errorMessage, options);
|
|
25
|
+
this.type = type;
|
|
26
|
+
this.errorMessage = errorMessage;
|
|
27
|
+
this.customErrorName = customErrorName;
|
|
28
|
+
}
|
|
29
|
+
get statusCode() {
|
|
30
|
+
const { type } = this;
|
|
31
|
+
// Fool-proofing. `new XRPCError(123.5 as number, '')` does not generate a TypeScript error.
|
|
32
|
+
// Because of this, we can end-up with any numeric value instead of an actual `ResponseType`.
|
|
33
|
+
// For legacy reasons, the `type` argument is not checked in the constructor, so we check it here.
|
|
34
|
+
if (type < 400 || type >= 600 || !Number.isFinite(type)) {
|
|
35
|
+
return 500;
|
|
36
|
+
}
|
|
37
|
+
return type;
|
|
38
|
+
}
|
|
39
|
+
get error() {
|
|
40
|
+
return this.customErrorName ?? this.typeName;
|
|
41
|
+
}
|
|
42
|
+
get payload() {
|
|
43
|
+
return {
|
|
44
|
+
error: this.error,
|
|
45
|
+
message: this.type === ResponseType.InternalServerError
|
|
46
|
+
? this.typeStr // Do not respond with error details for 500s
|
|
47
|
+
: this.errorMessage || this.typeStr,
|
|
48
|
+
};
|
|
49
|
+
}
|
|
50
|
+
get typeName() {
|
|
51
|
+
return ResponseType[this.type];
|
|
52
|
+
}
|
|
53
|
+
get typeStr() {
|
|
54
|
+
return ResponseTypeStrings[this.type];
|
|
55
|
+
}
|
|
56
|
+
static fromError(cause) {
|
|
57
|
+
if (cause instanceof XRPCError) {
|
|
58
|
+
return cause;
|
|
59
|
+
}
|
|
60
|
+
if (cause instanceof XRPCClientError) {
|
|
61
|
+
const { error, message, type } = mapFromClientError(cause);
|
|
62
|
+
return new XRPCError(type, message, error, { cause });
|
|
63
|
+
}
|
|
64
|
+
if (cause instanceof XrpcError) {
|
|
65
|
+
const { status, body } = cause.toDownstreamError();
|
|
66
|
+
return new XRPCError(status, body.message, body.error, { cause });
|
|
67
|
+
}
|
|
68
|
+
if (cause instanceof LexError) {
|
|
69
|
+
const data = cause.toJSON();
|
|
70
|
+
const type = ResponseType.InternalServerError;
|
|
71
|
+
return new XRPCError(type, data.message, data.error, { cause });
|
|
72
|
+
}
|
|
73
|
+
if (isHttpError(cause)) {
|
|
74
|
+
return new XRPCError(cause.status, cause.message, cause.name, { cause });
|
|
75
|
+
}
|
|
76
|
+
if (isErrorResult(cause)) {
|
|
77
|
+
return this.fromErrorResult(cause);
|
|
78
|
+
}
|
|
79
|
+
if (cause instanceof Error) {
|
|
80
|
+
return new InternalServerError(cause.message, undefined, { cause });
|
|
81
|
+
}
|
|
82
|
+
return new InternalServerError('Unexpected internal server error', undefined, { cause });
|
|
83
|
+
}
|
|
84
|
+
static fromErrorResult(err) {
|
|
85
|
+
return new XRPCError(err.status, err.message, err.error, { cause: err });
|
|
86
|
+
}
|
|
87
|
+
}
|
|
88
|
+
export class InvalidRequestError extends XRPCError {
|
|
89
|
+
constructor(errorMessage, customErrorName, options) {
|
|
90
|
+
super(ResponseType.InvalidRequest, errorMessage, customErrorName, options);
|
|
91
|
+
}
|
|
92
|
+
[Symbol.hasInstance](instance) {
|
|
93
|
+
return (instance instanceof XRPCError &&
|
|
94
|
+
instance.type === ResponseType.InvalidRequest);
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
export class AuthRequiredError extends XRPCError {
|
|
98
|
+
constructor(errorMessage, customErrorName, options) {
|
|
99
|
+
super(ResponseType.AuthenticationRequired, errorMessage, customErrorName, options);
|
|
100
|
+
}
|
|
101
|
+
[Symbol.hasInstance](instance) {
|
|
102
|
+
return (instance instanceof XRPCError &&
|
|
103
|
+
instance.type === ResponseType.AuthenticationRequired);
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
export class ForbiddenError extends XRPCError {
|
|
107
|
+
constructor(errorMessage, customErrorName, options) {
|
|
108
|
+
super(ResponseType.Forbidden, errorMessage, customErrorName, options);
|
|
109
|
+
}
|
|
110
|
+
[Symbol.hasInstance](instance) {
|
|
111
|
+
return (instance instanceof XRPCError && instance.type === ResponseType.Forbidden);
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
export class InternalServerError extends XRPCError {
|
|
115
|
+
constructor(errorMessage, customErrorName, options) {
|
|
116
|
+
super(ResponseType.InternalServerError, errorMessage, customErrorName, options);
|
|
117
|
+
}
|
|
118
|
+
[Symbol.hasInstance](instance) {
|
|
119
|
+
return (instance instanceof XRPCError &&
|
|
120
|
+
instance.type === ResponseType.InternalServerError);
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
export class UpstreamFailureError extends XRPCError {
|
|
124
|
+
constructor(errorMessage, customErrorName, options) {
|
|
125
|
+
super(ResponseType.UpstreamFailure, errorMessage, customErrorName, options);
|
|
126
|
+
}
|
|
127
|
+
[Symbol.hasInstance](instance) {
|
|
128
|
+
return (instance instanceof XRPCError &&
|
|
129
|
+
instance.type === ResponseType.UpstreamFailure);
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
export class NotEnoughResourcesError extends XRPCError {
|
|
133
|
+
constructor(errorMessage, customErrorName, options) {
|
|
134
|
+
super(ResponseType.NotEnoughResources, errorMessage, customErrorName, options);
|
|
135
|
+
}
|
|
136
|
+
[Symbol.hasInstance](instance) {
|
|
137
|
+
return (instance instanceof XRPCError &&
|
|
138
|
+
instance.type === ResponseType.NotEnoughResources);
|
|
139
|
+
}
|
|
140
|
+
}
|
|
141
|
+
export class UpstreamTimeoutError extends XRPCError {
|
|
142
|
+
constructor(errorMessage, customErrorName, options) {
|
|
143
|
+
super(ResponseType.UpstreamTimeout, errorMessage, customErrorName, options);
|
|
144
|
+
}
|
|
145
|
+
[Symbol.hasInstance](instance) {
|
|
146
|
+
return (instance instanceof XRPCError &&
|
|
147
|
+
instance.type === ResponseType.UpstreamTimeout);
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
export class MethodNotImplementedError extends XRPCError {
|
|
151
|
+
constructor(errorMessage, customErrorName, options) {
|
|
152
|
+
super(ResponseType.MethodNotImplemented, errorMessage, customErrorName, options);
|
|
153
|
+
}
|
|
154
|
+
[Symbol.hasInstance](instance) {
|
|
155
|
+
return (instance instanceof XRPCError &&
|
|
156
|
+
instance.type === ResponseType.MethodNotImplemented);
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
/**
|
|
160
|
+
* Converts an upstream XRPC {@link ResponseType} into a downstream {@link ResponseType}.
|
|
161
|
+
*/
|
|
162
|
+
function mapFromClientError(error) {
|
|
163
|
+
switch (error.status) {
|
|
164
|
+
case ResponseType.InvalidResponse:
|
|
165
|
+
// Upstream server returned an XRPC response that is not compatible with our internal lexicon definitions for that XRPC method.
|
|
166
|
+
// @NOTE This could be reflected as both a 500 ("we" are at fault) and 502 ("they" are at fault). Let's be gents about it.
|
|
167
|
+
return {
|
|
168
|
+
error: httpResponseCodeToName(ResponseType.InternalServerError),
|
|
169
|
+
message: httpResponseCodeToString(ResponseType.InternalServerError),
|
|
170
|
+
type: ResponseType.InternalServerError,
|
|
171
|
+
};
|
|
172
|
+
case ResponseType.Unknown:
|
|
173
|
+
// Typically a network error / unknown host
|
|
174
|
+
return {
|
|
175
|
+
error: httpResponseCodeToName(ResponseType.InternalServerError),
|
|
176
|
+
message: httpResponseCodeToString(ResponseType.InternalServerError),
|
|
177
|
+
type: ResponseType.InternalServerError,
|
|
178
|
+
};
|
|
179
|
+
default:
|
|
180
|
+
return {
|
|
181
|
+
error: error.error,
|
|
182
|
+
message: error.message,
|
|
183
|
+
type: error.status,
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
}
|
|
187
|
+
//# sourceMappingURL=errors.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"errors.js","sourceRoot":"","sources":["../src/errors.ts"],"names":[],"mappings":"AAAA,OAAO,UAAU,MAAM,aAAa,CAAA;AACpC,MAAM,EAAE,WAAW,EAAE,GAAG,UAAU,CAAA;AAClC,OAAO,EAAE,QAAQ,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAA;AACzD,OAAO,EAAE,CAAC,EAAE,MAAM,qBAAqB,CAAA;AACvC,OAAO,EACL,YAAY,EACZ,mBAAmB,EACnB,SAAS,IAAI,eAAe,EAC5B,sBAAsB,EACtB,wBAAwB,GACzB,MA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EAAE,CAAC;QACrB,KAAK,YAAY,CAAC,eAAe;YAC/B,+HAA+H;YAC/H,0HAA0H;YAC1H,OAAO;gBACL,KAAK,EAAE,sBAAsB,CAAC,YAAY,CAAC,mBAAmB,CAAC;gBAC/D,OAAO,EAAE,wBAAwB,CAAC,YAAY,CAAC,mBAAmB,CAAC;gBACnE,IAAI,EAAE,YAAY,CAAC,mBAAmB;aACvC,CAAA;QACH,KAAK,YAAY,CAAC,OAAO;YACvB,2CAA2C;YAC3C,OAAO;gBACL,KAAK,EAAE,sBAAsB,CAAC,YAAY,CAAC,mBAAmB,CAAC;gBAC/D,OAAO,EAAE,wBAAwB,CAAC,YAAY,CAAC,mBAAmB,CAAC;gBACnE,IAAI,EAAE,YAAY,CAAC,mBAAmB;aACvC,CAAA;QACH;YACE,OAAO;gBACL,KAAK,EAAE,KAAK,CAAC,KAAK;gBAClB,OAAO,EAAE,KAAK,CAAC,OAAO;gBACtB,IAAI,EAAE,KAAK,CAAC,MAAM;aACnB,CAAA;IACL,CAAC;AACH,CAAC","sourcesContent":["import httpErrors from 'http-errors'\nconst { isHttpError } = httpErrors\nimport { LexError, XrpcError } from '@atproto/lex-client'\nimport { l } from '@atproto/lex-schema'\nimport {\n ResponseType,\n ResponseTypeStrings,\n XRPCError as XRPCClientError,\n httpResponseCodeToName,\n httpResponseCodeToString,\n} from '@atproto/xrpc'\n\n// @NOTE Do not depend (directly or indirectly) on \"./types\" here, as it would\n// create a circular dependency.\n\nexport const errorResult = l.object({\n status: l.integer({ minimum: 400 }),\n error: l.optional(l.string()),\n message: l.optional(l.string()),\n})\nexport type ErrorResult = l.Infer<typeof errorResult>\n\nexport function isErrorResult(v: unknown): v is ErrorResult {\n return errorResult.safeParse(v).success\n}\n\nexport function excludeErrorResult<V>(v: V) {\n if (isErrorResult(v)) throw XRPCError.fromErrorResult(v)\n return v as Exclude<V, ErrorResult>\n}\n\nexport { ResponseType }\n\nexport class XRPCError extends Error {\n constructor(\n public type: ResponseType,\n public errorMessage?: string,\n public customErrorName?: string,\n options?: ErrorOptions,\n ) {\n super(errorMessage, options)\n }\n\n get statusCode(): number {\n const { type } = this\n\n // Fool-proofing. `new XRPCError(123.5 as number, '')` does not generate a TypeScript error.\n // Because of this, we can end-up with any numeric value instead of an actual `ResponseType`.\n // For legacy reasons, the `type` argument is not checked in the constructor, so we check it here.\n if (type < 400 || type >= 600 || !Number.isFinite(type)) {\n return 500\n }\n\n return type\n }\n\n get error(): string | undefined {\n return this.customErrorName ?? this.typeName\n }\n\n get payload() {\n return {\n error: this.error,\n message:\n this.type === ResponseType.InternalServerError\n ? this.typeStr // Do not respond with error details for 500s\n : this.errorMessage || this.typeStr,\n }\n }\n\n get typeName(): string | undefined {\n return ResponseType[this.type]\n }\n\n get typeStr(): string | undefined {\n return ResponseTypeStrings[this.type]\n }\n\n static fromError(cause: unknown): XRPCError {\n if (cause instanceof XRPCError) {\n return cause\n }\n\n if (cause instanceof XRPCClientError) {\n const { error, message, type } = mapFromClientError(cause)\n return new XRPCError(type, message, error, { cause })\n }\n\n if (cause instanceof XrpcError) {\n const { status, body } = cause.toDownstreamError()\n return new XRPCError(status, body.message, body.error, { cause })\n }\n\n if (cause instanceof LexError) {\n const data = cause.toJSON()\n const type = ResponseType.InternalServerError\n return new XRPCError(type, data.message, data.error, { cause })\n }\n\n if (isHttpError(cause)) {\n return new XRPCError(cause.status, cause.message, cause.name, { cause })\n }\n\n if (isErrorResult(cause)) {\n return this.fromErrorResult(cause)\n }\n\n if (cause instanceof Error) {\n return new InternalServerError(cause.message, undefined, { cause })\n }\n\n return new InternalServerError(\n 'Unexpected internal server error',\n undefined,\n { cause },\n )\n }\n\n static fromErrorResult(err: ErrorResult): XRPCError {\n return new XRPCError(err.status, err.message, err.error, { cause: err })\n }\n}\n\nexport class InvalidRequestError extends XRPCError {\n constructor(\n errorMessage?: string,\n customErrorName?: string,\n options?: ErrorOptions,\n ) {\n super(ResponseType.InvalidRequest, errorMessage, customErrorName, options)\n }\n\n [Symbol.hasInstance](instance: unknown): boolean {\n return (\n instance instanceof XRPCError &&\n instance.type === ResponseType.InvalidRequest\n )\n }\n}\n\nexport class AuthRequiredError extends XRPCError {\n constructor(\n errorMessage?: string,\n customErrorName?: string,\n options?: ErrorOptions,\n ) {\n super(\n ResponseType.AuthenticationRequired,\n errorMessage,\n customErrorName,\n options,\n )\n }\n\n [Symbol.hasInstance](instance: unknown): boolean {\n return (\n instance instanceof XRPCError &&\n instance.type === ResponseType.AuthenticationRequired\n )\n }\n}\n\nexport class ForbiddenError extends XRPCError {\n constructor(\n errorMessage?: string,\n customErrorName?: string,\n options?: ErrorOptions,\n ) {\n super(ResponseType.Forbidden, errorMessage, customErrorName, options)\n }\n\n [Symbol.hasInstance](instance: unknown): boolean {\n return (\n instance instanceof XRPCError && instance.type === ResponseType.Forbidden\n )\n }\n}\n\nexport class InternalServerError extends XRPCError {\n constructor(\n errorMessage?: string,\n customErrorName?: string,\n options?: ErrorOptions,\n ) {\n super(\n ResponseType.InternalServerError,\n errorMessage,\n customErrorName,\n options,\n )\n }\n\n [Symbol.hasInstance](instance: unknown): boolean {\n return (\n instance instanceof XRPCError &&\n instance.type === ResponseType.InternalServerError\n )\n }\n}\n\nexport class UpstreamFailureError extends XRPCError {\n constructor(\n errorMessage?: string,\n customErrorName?: string,\n options?: ErrorOptions,\n ) {\n super(ResponseType.UpstreamFailure, errorMessage, customErrorName, options)\n }\n\n [Symbol.hasInstance](instance: unknown): boolean {\n return (\n instance instanceof XRPCError &&\n instance.type === ResponseType.UpstreamFailure\n )\n }\n}\n\nexport class NotEnoughResourcesError extends XRPCError {\n constructor(\n errorMessage?: string,\n customErrorName?: string,\n options?: ErrorOptions,\n ) {\n super(\n ResponseType.NotEnoughResources,\n errorMessage,\n customErrorName,\n options,\n )\n }\n\n [Symbol.hasInstance](instance: unknown): boolean {\n return (\n instance instanceof XRPCError &&\n instance.type === ResponseType.NotEnoughResources\n )\n }\n}\n\nexport class UpstreamTimeoutError extends XRPCError {\n constructor(\n errorMessage?: string,\n customErrorName?: string,\n options?: ErrorOptions,\n ) {\n super(ResponseType.UpstreamTimeout, errorMessage, customErrorName, options)\n }\n\n [Symbol.hasInstance](instance: unknown): boolean {\n return (\n instance instanceof XRPCError &&\n instance.type === ResponseType.UpstreamTimeout\n )\n }\n}\n\nexport class MethodNotImplementedError extends XRPCError {\n constructor(\n errorMessage?: string,\n customErrorName?: string,\n options?: ErrorOptions,\n ) {\n super(\n ResponseType.MethodNotImplemented,\n errorMessage,\n customErrorName,\n options,\n )\n }\n\n [Symbol.hasInstance](instance: unknown): boolean {\n return (\n instance instanceof XRPCError &&\n instance.type === ResponseType.MethodNotImplemented\n )\n }\n}\n\n/**\n * Converts an upstream XRPC {@link ResponseType} into a downstream {@link ResponseType}.\n */\nfunction mapFromClientError(error: XRPCClientError): {\n error: string\n message: string\n type: ResponseType\n} {\n switch (error.status) {\n case ResponseType.InvalidResponse:\n // Upstream server returned an XRPC response that is not compatible with our internal lexicon definitions for that XRPC method.\n // @NOTE This could be reflected as both a 500 (\"we\" are at fault) and 502 (\"they\" are at fault). Let's be gents about it.\n return {\n error: httpResponseCodeToName(ResponseType.InternalServerError),\n message: httpResponseCodeToString(ResponseType.InternalServerError),\n type: ResponseType.InternalServerError,\n }\n case ResponseType.Unknown:\n // Typically a network error / unknown host\n return {\n error: httpResponseCodeToName(ResponseType.InternalServerError),\n message: httpResponseCodeToString(ResponseType.InternalServerError),\n type: ResponseType.InternalServerError,\n }\n default:\n return {\n error: error.error,\n message: error.message,\n type: error.status,\n }\n }\n}\n"]}
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,9 @@
|
|
|
1
|
+
export * from './auth.js';
|
|
2
|
+
export * from './errors.js';
|
|
3
|
+
export * from './rate-limiter.js';
|
|
4
|
+
export * from './server.js';
|
|
5
|
+
export * from './stream/index.js';
|
|
6
|
+
export * from './types.js';
|
|
7
|
+
export { ServerTimer, parseReqEncoding, parseReqNsid, serverTimingHeader, } from './util.js';
|
|
8
|
+
export type { ServerTiming } from './util.js';
|
|
9
|
+
//# sourceMappingURL=index.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,WAAW,CAAA;AACzB,cAAc,aAAa,CAAA;AAC3B,cAAc,mBAAmB,CAAA;AACjC,cAAc,aAAa,CAAA;AAC3B,cAAc,mBAAmB,CAAA;AACjC,cAAc,YAAY,CAAA;AAE1B,OAAO,EACL,WAAW,EACX,gBAAgB,EAChB,YAAY,EACZ,kBAAkB,GACnB,MAAM,WAAW,CAAA;AAClB,YAAY,EAAE,YAAY,EAAE,MAAM,WAAW,CAAA"}
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export * from './auth.js';
|
|
2
|
+
export * from './errors.js';
|
|
3
|
+
export * from './rate-limiter.js';
|
|
4
|
+
export * from './server.js';
|
|
5
|
+
export * from './stream/index.js';
|
|
6
|
+
export * from './types.js';
|
|
7
|
+
export { ServerTimer, parseReqEncoding, parseReqNsid, serverTimingHeader, } from './util.js';
|
|
8
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,cAAc,WAAW,CAAA;AACzB,cAAc,aAAa,CAAA;AAC3B,cAAc,mBAAmB,CAAA;AACjC,cAAc,aAAa,CAAA;AAC3B,cAAc,mBAAmB,CAAA;AACjC,cAAc,YAAY,CAAA;AAE1B,OAAO,EACL,WAAW,EACX,gBAAgB,EAChB,YAAY,EACZ,kBAAkB,GACnB,MAAM,WAAW,CAAA","sourcesContent":["export * from './auth.js'\nexport * from './errors.js'\nexport * from './rate-limiter.js'\nexport * from './server.js'\nexport * from './stream/index.js'\nexport * from './types.js'\n\nexport {\n ServerTimer,\n parseReqEncoding,\n parseReqNsid,\n serverTimingHeader,\n} from './util.js'\nexport type { ServerTiming } from './util.js'\n"]}
|
package/dist/logger.d.ts
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"logger.d.ts","sourceRoot":"","sources":["../src/logger.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAA;AAEjD,eAAO,MAAM,WAAW,gBAAgB,CAAA;AAExC,eAAO,MAAM,MAAM,EAAE,UAAU,CAAC,OAAO,eAAe,CACxB,CAAA;eAEf,MAAM"}
|
package/dist/logger.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"logger.js","sourceRoot":"","sources":["../src/logger.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,eAAe,EAAE,MAAM,iBAAiB,CAAA;AAEjD,MAAM,CAAC,MAAM,WAAW,GAAG,aAAa,CAAA;AAExC,MAAM,CAAC,MAAM,MAAM,GACjB,eAAe,CAAC,WAAW,CAAC,CAAA;AAE9B,eAAe,MAAM,CAAA","sourcesContent":["import { subsystemLogger } from '@atproto/common'\n\nexport const LOGGER_NAME = 'xrpc-server'\n\nexport const logger: ReturnType<typeof subsystemLogger> =\n subsystemLogger(LOGGER_NAME)\n\nexport default logger\n"]}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
2
|
+
import { type RateLimiterConsume, type RateLimiterI, type RateLimiterReset, type RateLimiterStatus } from './rate-limiter.js';
|
|
3
|
+
export interface HttpRateLimiterContext {
|
|
4
|
+
req: IncomingMessage;
|
|
5
|
+
res?: ServerResponse;
|
|
6
|
+
}
|
|
7
|
+
export type HttpRateLimiterOptions<C extends HttpRateLimiterContext = HttpRateLimiterContext> = {
|
|
8
|
+
bypass?: (ctx: C) => boolean;
|
|
9
|
+
};
|
|
10
|
+
/**
|
|
11
|
+
* Wraps a {@link RateLimiterI} class with an {@link RateLimiterI}
|
|
12
|
+
* implementation that will apply the appropriate headers to the response if a
|
|
13
|
+
* limit is exceeded.
|
|
14
|
+
*/
|
|
15
|
+
export declare class HttpRateLimiter<C extends HttpRateLimiterContext = HttpRateLimiterContext> implements RateLimiterI<C> {
|
|
16
|
+
private readonly rateLimiter;
|
|
17
|
+
private readonly options;
|
|
18
|
+
constructor(rateLimiter: RateLimiterI<C>, options?: Readonly<HttpRateLimiterOptions<C>>);
|
|
19
|
+
handle(ctx: C): Promise<void>;
|
|
20
|
+
consume(...args: Parameters<RateLimiterConsume<C>>): Promise<RateLimiterStatus | null>;
|
|
21
|
+
reset(...args: Parameters<RateLimiterReset<C>>): Promise<void>;
|
|
22
|
+
static from<C extends HttpRateLimiterContext = HttpRateLimiterContext>(rateLimiters: readonly RateLimiterI<C>[], { bypass }?: HttpRateLimiterOptions<C>): HttpRateLimiter<C> | undefined;
|
|
23
|
+
}
|
|
24
|
+
//# sourceMappingURL=rate-limiter-http.d.ts.map
|