@atproto/lex-server 0.0.0-spaces-alpha-20260818163953

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,209 @@
1
+ import type { AtprotoDid, AtprotoDidDocument } from '@atproto/did';
2
+ import type { DidString } from '@atproto/lex-schema';
3
+ import type { CreateDidResolverOptions } from '@atproto-labs/did-resolver';
4
+ import type { LexRouterAuth } from './lex-router.js';
5
+ /**
6
+ * Callback function to check and record nonce uniqueness.
7
+ *
8
+ * Used to prevent replay attacks by ensuring each nonce is only used once.
9
+ * The implementation must track nonces for at least the `maxAge` duration
10
+ * (default 5 minutes before and after the current time).
11
+ *
12
+ * @param nonce - The nonce string from the JWT token
13
+ * @returns Promise resolving to `true` if the nonce is unique (first time seen),
14
+ * `false` if it has been seen before
15
+ *
16
+ * @example
17
+ * ```typescript
18
+ * // Using Redis for nonce tracking
19
+ * const checkNonce: UniqueNonceChecker = async (nonce) => {
20
+ * const key = `nonce:${nonce}`
21
+ * const result = await redis.setnx(key, '1')
22
+ * if (result === 1) {
23
+ * await redis.expire(key, 600) // 10 minutes TTL
24
+ * return true
25
+ * }
26
+ * return false
27
+ * }
28
+ * ```
29
+ */
30
+ export type UniqueNonceChecker = (nonce: string) => Promise<boolean>;
31
+ /**
32
+ * Configuration options for AT Protocol service authentication.
33
+ *
34
+ * Service auth is used for server-to-server communication in the AT Protocol,
35
+ * where one service authenticates to another using signed JWT tokens tied to
36
+ * the caller's DID.
37
+ *
38
+ * @example
39
+ * ```typescript
40
+ * const options: ServiceAuthOptions = {
41
+ * audience: 'did:web:api.example.com',
42
+ * unique: async (nonce) => nonceStore.checkAndAdd(nonce),
43
+ * maxAge: 300, // 5 minutes
44
+ * // Optional DID resolver options
45
+ * plcDirectoryUrl: 'https://plc.directory'
46
+ * }
47
+ * ```
48
+ */
49
+ export type ServiceAuthOptions = CreateDidResolverOptions & {
50
+ /**
51
+ * Expected audience ("aud") claim in the JWT token.
52
+ *
53
+ * This should be the DID of your service. The token must include this
54
+ * value in its `aud` claim to be accepted. Set to `null` to skip
55
+ * audience verification (not recommended for production).
56
+ */
57
+ audience: null | DidString;
58
+ /**
59
+ * Function to check and record nonce uniqueness.
60
+ *
61
+ * This is critical for preventing replay attacks. The value checked here
62
+ * must be unique within `maxAge` seconds before and after the current time.
63
+ *
64
+ * @param nonce - The nonce to check
65
+ * @returns Promise resolving to `true` if unique, `false` if seen before
66
+ */
67
+ unique: UniqueNonceChecker;
68
+ /**
69
+ * Maximum age of the JWT token in seconds.
70
+ *
71
+ * Tokens with `iat` (issued at) or `exp` (expiry) timestamps outside
72
+ * this window from the current time will be rejected.
73
+ *
74
+ * @default 300 (5 minutes)
75
+ */
76
+ maxAge?: number;
77
+ };
78
+ /**
79
+ * Credentials returned after successful service authentication.
80
+ *
81
+ * Contains the verified DID, resolved DID document, and parsed JWT token.
82
+ * These are available in handler context as `ctx.credentials`.
83
+ *
84
+ * @example
85
+ * ```typescript
86
+ * router.add(protectedMethod, {
87
+ * handler: async (ctx) => {
88
+ * const { did, didDocument, jwt } = ctx.credentials
89
+ * console.log('Request from:', did)
90
+ * console.log('Token expires:', new Date(jwt.payload.exp * 1000))
91
+ * return { body: { callerDid: did } }
92
+ * },
93
+ * auth: serviceAuth({ audience: myDid, unique: checkNonce })
94
+ * })
95
+ * ```
96
+ */
97
+ export type ServiceAuthCredentials = {
98
+ /** The verified AT Protocol DID of the caller. */
99
+ did: AtprotoDid;
100
+ /** The resolved DID document of the caller. */
101
+ didDocument: AtprotoDidDocument;
102
+ /** The parsed and validated JWT token. */
103
+ jwt: ParsedJwt;
104
+ };
105
+ /**
106
+ * Creates an authentication handler for verifying AT Protocol service auth JWTs.
107
+ *
108
+ * Service auth is the standard authentication mechanism for server-to-server
109
+ * communication in the AT Protocol. It uses JWT bearer tokens signed by the
110
+ * caller's DID signing key, with the signature verified against the public
111
+ * key in the caller's DID document.
112
+ *
113
+ * The handler performs the following validations:
114
+ * - Extracts and parses the Bearer token from the Authorization header
115
+ * - Validates JWT structure and claims (aud, exp, iat, lxm, nonce)
116
+ * - Resolves the issuer's DID document
117
+ * - Verifies the JWT signature against the `#atproto` verification method
118
+ * - Checks nonce uniqueness to prevent replay attacks
119
+ *
120
+ * @param options - Configuration options for service auth
121
+ * @returns An auth handler function for use with {@link LexRouter.add}
122
+ *
123
+ * @example Basic usage
124
+ * ```typescript
125
+ * import { LexRouter, serviceAuth } from '@atproto/lex-server'
126
+ *
127
+ * const router = new LexRouter()
128
+ *
129
+ * const auth = serviceAuth({
130
+ * audience: 'did:web:api.example.com',
131
+ * unique: async (nonce) => {
132
+ * // Check if nonce has been seen, return true if unique
133
+ * const isNew = await redis.setnx(`nonce:${nonce}`, '1')
134
+ * if (isNew) await redis.expire(`nonce:${nonce}`, 600)
135
+ * return isNew
136
+ * }
137
+ * })
138
+ *
139
+ * router.add(myMethod, {
140
+ * handler: async (ctx) => {
141
+ * console.log('Authenticated as:', ctx.credentials.did)
142
+ * return { body: { success: true } }
143
+ * },
144
+ * auth
145
+ * })
146
+ * ```
147
+ */
148
+ export declare function serviceAuth({ audience, maxAge, unique, ...options }: ServiceAuthOptions): LexRouterAuth<ServiceAuthCredentials>;
149
+ /**
150
+ * Options for parsing and validating a JWT token.
151
+ */
152
+ export type ParseJwtOptions = {
153
+ /** Maximum age in seconds for token validity window. */
154
+ maxAge: number;
155
+ /** Expected audience claim, or null to skip audience verification. */
156
+ audience: null | DidString;
157
+ /** Function to check nonce uniqueness. */
158
+ unique: UniqueNonceChecker;
159
+ /** Expected lexicon method NSID for the `lxm` claim. */
160
+ lxm: string;
161
+ };
162
+ /**
163
+ * A parsed and partially validated JWT token.
164
+ *
165
+ * Contains the decoded header and payload, along with the raw bytes
166
+ * needed for signature verification.
167
+ *
168
+ * @example
169
+ * ```typescript
170
+ * const jwt: ParsedJwt = {
171
+ * header: { alg: 'ES256K', typ: 'JWT' },
172
+ * payload: {
173
+ * iss: 'did:plc:abc123',
174
+ * aud: 'did:web:api.example.com',
175
+ * exp: 1704067200,
176
+ * iat: 1704066900,
177
+ * lxm: 'com.atproto.sync.getBlob'
178
+ * },
179
+ * message: new Uint8Array([...]),
180
+ * signature: new Uint8Array([...])
181
+ * }
182
+ * ```
183
+ */
184
+ export type ParsedJwt = {
185
+ /** The decoded JWT header containing algorithm and type. */
186
+ header: HeaderObject;
187
+ /** The decoded JWT payload containing claims. */
188
+ payload: PayloadObject;
189
+ /** The raw header.payload bytes for signature verification. */
190
+ message: Uint8Array;
191
+ /** The decoded signature bytes. */
192
+ signature: Uint8Array;
193
+ };
194
+ type HeaderObject = {
195
+ alg: string;
196
+ typ?: string;
197
+ };
198
+ type PayloadObject = {
199
+ iss: DidString;
200
+ aud: DidString;
201
+ exp: number;
202
+ iat?: number;
203
+ nbf?: number;
204
+ lxm?: string;
205
+ nonce?: string;
206
+ };
207
+ export declare function isPayloadObject(obj: unknown): obj is PayloadObject;
208
+ export {};
209
+ //# sourceMappingURL=service-auth.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"service-auth.d.ts","sourceRoot":"","sources":["../src/service-auth.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,UAAU,EAAE,kBAAkB,EAAO,MAAM,cAAc,CAAA;AAGvE,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,qBAAqB,CAAA;AAEpD,OAAO,KAAK,EAAE,wBAAwB,EAAE,MAAM,4BAA4B,CAAA;AAG1E,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,iBAAiB,CAAA;AAIpD;;;;;;;;;;;;;;;;;;;;;;;;GAwBG;AACH,MAAM,MAAM,kBAAkB,GAAG,CAAC,KAAK,EAAE,MAAM,KAAK,OAAO,CAAC,OAAO,CAAC,CAAA;AAEpE;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAM,MAAM,kBAAkB,GAAG,wBAAwB,GAAG;IAC1D;;;;;;OAMG;IACH,QAAQ,EAAE,IAAI,GAAG,SAAS,CAAA;IAC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AAG,EAAE,MAAM,CAAA;IACX,GAAG,CAAC,EAAE,MAAM,CAAA;IACZ,GAAG,CAAC,EAAE,MAAM,CAAA;IACZ,GAAG,CAAC,EAAE,MAAM,CAAA;IACZ,KAAK,CAAC,EAAE,MAAM,CAAA;CACf,CAAA;AACD,wBAAgB,eAAe,CAAC,GAAG,EAAE,OAAO,GAAG,GAAG,IAAI,aAAa,CAalE"}
@@ -0,0 +1,225 @@
1
+ import * as crypto from '@atproto/crypto';
2
+ import { matchesIdentifier } from '@atproto/did';
3
+ import { fromBase64, isPlainObject, utf8FromBase64 } from '@atproto/lex-data';
4
+ import { isDidString } from '@atproto/lex-schema';
5
+ import { createDidResolver } from '@atproto-labs/did-resolver';
6
+ import { LexServerAuthError } from './errors.js';
7
+ const BEARER_PREFIX = 'Bearer ';
8
+ /**
9
+ * Creates an authentication handler for verifying AT Protocol service auth JWTs.
10
+ *
11
+ * Service auth is the standard authentication mechanism for server-to-server
12
+ * communication in the AT Protocol. It uses JWT bearer tokens signed by the
13
+ * caller's DID signing key, with the signature verified against the public
14
+ * key in the caller's DID document.
15
+ *
16
+ * The handler performs the following validations:
17
+ * - Extracts and parses the Bearer token from the Authorization header
18
+ * - Validates JWT structure and claims (aud, exp, iat, lxm, nonce)
19
+ * - Resolves the issuer's DID document
20
+ * - Verifies the JWT signature against the `#atproto` verification method
21
+ * - Checks nonce uniqueness to prevent replay attacks
22
+ *
23
+ * @param options - Configuration options for service auth
24
+ * @returns An auth handler function for use with {@link LexRouter.add}
25
+ *
26
+ * @example Basic usage
27
+ * ```typescript
28
+ * import { LexRouter, serviceAuth } from '@atproto/lex-server'
29
+ *
30
+ * const router = new LexRouter()
31
+ *
32
+ * const auth = serviceAuth({
33
+ * audience: 'did:web:api.example.com',
34
+ * unique: async (nonce) => {
35
+ * // Check if nonce has been seen, return true if unique
36
+ * const isNew = await redis.setnx(`nonce:${nonce}`, '1')
37
+ * if (isNew) await redis.expire(`nonce:${nonce}`, 600)
38
+ * return isNew
39
+ * }
40
+ * })
41
+ *
42
+ * router.add(myMethod, {
43
+ * handler: async (ctx) => {
44
+ * console.log('Authenticated as:', ctx.credentials.did)
45
+ * return { body: { success: true } }
46
+ * },
47
+ * auth
48
+ * })
49
+ * ```
50
+ */
51
+ export function serviceAuth({ audience, maxAge = 5 * 60, unique, ...options }) {
52
+ const didResolver = createDidResolver(options);
53
+ return async ({ request, method }) => {
54
+ const { signal } = request;
55
+ const jwt = await parseJwtBearer(request, {
56
+ lxm: method.nsid,
57
+ maxAge,
58
+ audience,
59
+ unique,
60
+ });
61
+ let didDocument = await didResolver
62
+ .resolve(jwt.payload.iss, { signal })
63
+ .catch((cause) => {
64
+ throw new LexServerAuthError('AuthenticationRequired', 'Could not resolve DID document', { Bearer: { error: 'DidResolutionFailed' } }, { cause });
65
+ });
66
+ const key = getAtprotoSigningKey(didDocument);
67
+ if (!key || !(await verifyJwt(jwt, key))) {
68
+ signal.throwIfAborted();
69
+ // Try refreshing the DID document in case it was updated
70
+ didDocument = await didResolver
71
+ .resolve(jwt.payload.iss, { signal, noCache: true })
72
+ .catch((cause) => {
73
+ throw new LexServerAuthError('AuthenticationRequired', 'Could not resolve DID document', { Bearer: { error: 'DidResolutionFailed' } }, { cause });
74
+ });
75
+ // Verify again with the fresh key (if it changed)
76
+ const keyFresh = getAtprotoSigningKey(didDocument);
77
+ if (!keyFresh || key === keyFresh || !(await verifyJwt(jwt, keyFresh))) {
78
+ throw new LexServerAuthError('AuthenticationRequired', 'Invalid JWT signature', { Bearer: { error: 'BadJwtSignature' } });
79
+ }
80
+ }
81
+ return {
82
+ did: didDocument.id,
83
+ didDocument,
84
+ jwt,
85
+ };
86
+ };
87
+ }
88
+ async function verifyJwt(jwt, key) {
89
+ try {
90
+ return await crypto.verifySignature(key, jwt.message, jwt.signature, {
91
+ jwtAlg: jwt.header.alg,
92
+ allowMalleableSig: true,
93
+ });
94
+ }
95
+ catch (cause) {
96
+ throw new LexServerAuthError('AuthenticationRequired', 'Could not verify JWT signature', { Bearer: { error: 'BadJwtSignature' } }, { cause });
97
+ }
98
+ }
99
+ function getAtprotoSigningKey(didDocument) {
100
+ try {
101
+ const key = didDocument.verificationMethod?.find(isAtprotoVerificationMethod, didDocument);
102
+ if (key?.publicKeyMultibase) {
103
+ if (key.type === 'EcdsaSecp256r1VerificationKey2019') {
104
+ const keyBytes = crypto.multibaseToBytes(key.publicKeyMultibase);
105
+ return crypto.formatDidKey(crypto.P256_JWT_ALG, keyBytes);
106
+ }
107
+ else if (key.type === 'EcdsaSecp256k1VerificationKey2019') {
108
+ const keyBytes = crypto.multibaseToBytes(key.publicKeyMultibase);
109
+ return crypto.formatDidKey(crypto.SECP256K1_JWT_ALG, keyBytes);
110
+ }
111
+ else if (key.type === 'Multikey') {
112
+ const parsed = crypto.parseMultikey(key.publicKeyMultibase);
113
+ return crypto.formatDidKey(parsed.jwtAlg, parsed.keyBytes);
114
+ }
115
+ }
116
+ }
117
+ catch {
118
+ // Invalid key, ignore
119
+ }
120
+ return null;
121
+ }
122
+ function isAtprotoVerificationMethod(vm) {
123
+ return typeof vm === 'object' && matchesIdentifier(this.id, 'atproto', vm.id);
124
+ }
125
+ async function parseJwtBearer(request, options) {
126
+ const authorization = request.headers.get('authorization');
127
+ if (!authorization?.startsWith(BEARER_PREFIX)) {
128
+ throw new LexServerAuthError('AuthenticationRequired', 'Bearer token required', { Bearer: { error: 'MissingBearer' } });
129
+ }
130
+ const token = authorization.slice(BEARER_PREFIX.length).trim();
131
+ return parseJwt(token, options);
132
+ }
133
+ async function parseJwt(token, options) {
134
+ const { length, 0: headerB64, 1: payloadB64, 2: signatureB64, } = token.split('.');
135
+ if (length !== 3) {
136
+ throw new LexServerAuthError('AuthenticationRequired', 'Invalid JWT token', { Bearer: { error: 'BadJwt' } });
137
+ }
138
+ let header;
139
+ try {
140
+ header = jsonFromBase64(headerB64, isHeaderObject);
141
+ }
142
+ catch (cause) {
143
+ throw new LexServerAuthError('AuthenticationRequired', 'Invalid JWT token', { Bearer: { error: 'BadJwt' } }, { cause });
144
+ }
145
+ if (header.alg === 'none' ||
146
+ // service tokens are not OAuth 2.0 access tokens
147
+ // https://datatracker.ietf.org/doc/html/rfc9068
148
+ header.typ === 'at+jwt' ||
149
+ // "refresh+jwt" is a non-standard type used by the @atproto packages
150
+ header.typ === 'refresh+jwt' ||
151
+ // "DPoP" proofs are not meant to be used as service tokens
152
+ // https://datatracker.ietf.org/doc/html/rfc9449
153
+ header.typ === 'dpop+jwt') {
154
+ throw new LexServerAuthError('AuthenticationRequired', 'Invalid JWT token', { Bearer: { error: 'BadJwt' } });
155
+ }
156
+ let payload;
157
+ try {
158
+ payload = jsonFromBase64(payloadB64, isPayloadObject);
159
+ }
160
+ catch (cause) {
161
+ throw new LexServerAuthError('AuthenticationRequired', 'Invalid JWT token', { Bearer: { error: 'BadJwt' } }, { cause });
162
+ }
163
+ if (options.audience !== null && options.audience !== payload.aud) {
164
+ throw new LexServerAuthError('AuthenticationRequired', 'Invalid audience', {
165
+ Bearer: { error: 'InvalidAudience' },
166
+ });
167
+ }
168
+ const now = Math.floor(Date.now() / 1000);
169
+ if (payload.nbf != null && now < payload.nbf) {
170
+ throw new LexServerAuthError('AuthenticationRequired', 'JWT token not yet valid', { Bearer: { error: 'JwtNotYetValid' } });
171
+ }
172
+ if (now > payload.exp) {
173
+ throw new LexServerAuthError('AuthenticationRequired', 'JWT token expired', { Bearer: { error: 'JwtExpired' } });
174
+ }
175
+ // Prevent issuer from generating very long-lived tokens
176
+ if (timeDiff(now, payload.exp) > options.maxAge ||
177
+ timeDiff(now, payload.iat) > options.maxAge) {
178
+ throw new LexServerAuthError('AuthenticationRequired', 'JWT token too old', { Bearer: { error: 'JwtTooOld' } });
179
+ }
180
+ if (payload.lxm != null && payload.lxm !== options.lxm) {
181
+ throw new LexServerAuthError('AuthenticationRequired', 'Invalid JWT lexicon method ("lxm")', { Bearer: { error: 'BadJwtLexiconMethod' } });
182
+ }
183
+ if (payload.nonce != null && !(await (0, options.unique)(payload.nonce))) {
184
+ throw new LexServerAuthError('AuthenticationRequired', 'Replay attack detected: nonce is not unique', { Bearer: { error: 'NonceNotUnique' } });
185
+ }
186
+ return {
187
+ header,
188
+ payload,
189
+ message: textEncoder.encode(`${headerB64}.${payloadB64}`),
190
+ signature: fromBase64(signatureB64, 'base64url'),
191
+ };
192
+ }
193
+ const textEncoder = /*#__PURE__*/ new TextEncoder();
194
+ function isHeaderObject(obj) {
195
+ return (isPlainObject(obj) &&
196
+ typeof obj.alg === 'string' &&
197
+ (obj.typ === undefined || typeof obj.typ === 'string'));
198
+ }
199
+ export function isPayloadObject(obj) {
200
+ return (isPlainObject(obj) &&
201
+ typeof obj.iss === 'string' &&
202
+ typeof obj.aud === 'string' &&
203
+ (obj.lxm === undefined || typeof obj.lxm === 'string') &&
204
+ (obj.nonce === undefined || typeof obj.nonce === 'string') &&
205
+ (obj.iat === undefined || isPositiveInt(obj.iat)) &&
206
+ (obj.nbf === undefined || isPositiveInt(obj.nbf)) &&
207
+ isPositiveInt(obj.exp) &&
208
+ isDidString(obj.iss) &&
209
+ isDidString(obj.aud));
210
+ }
211
+ function timeDiff(t1, t2) {
212
+ if (t2 === undefined)
213
+ return 0;
214
+ return Math.abs(t1 - t2);
215
+ }
216
+ function isPositiveInt(value) {
217
+ return typeof value === 'number' && Number.isInteger(value) && value > 0;
218
+ }
219
+ function jsonFromBase64(b64, isType) {
220
+ const obj = JSON.parse(utf8FromBase64(b64, 'base64url'));
221
+ if (isType(obj))
222
+ return obj;
223
+ throw new Error('Invalid type');
224
+ }
225
+ //# sourceMappingURL=service-auth.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"service-auth.js","sourceRoot":"","sources":["../src/service-auth.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,MAAM,MAAM,iBAAiB,CAAA;AAEzC,OAAO,EAAE,iBAAiB,EAAE,MAAM,cAAc,CAAA;AAChD,OAAO,EAAE,UAAU,EAAE,aAAa,EAAE,cAAc,EAAE,MA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AAK,KAAK,QAAQ,IAAI,MAAM,CAAC,SAAS,CAAC,KAAK,CAAC,IAAI,KAAK,GAAG,CAAC,CAAA;AAC1E,CAAC;AAED,SAAS,cAAc,CAAI,GAAW,EAAE,MAAkC;IACxE,MAAM,GAAG,GAAG,IAAI,CAAC,KAAK,CAAC,cAAc,CAAC,GAAG,EAAE,WAAW,CAAC,CAAC,CAAA;IACxD,IAAI,MAAM,CAAC,GAAG,CAAC;QAAE,OAAO,GAAG,CAAA;IAC3B,MAAM,IAAI,KAAK,CAAC,cAAc,CAAC,CAAA;AACjC,CAAC","sourcesContent":["import * as crypto from '@atproto/crypto'\nimport type { AtprotoDid, AtprotoDidDocument, Did } from '@atproto/did'\nimport { matchesIdentifier } from '@atproto/did'\nimport { fromBase64, isPlainObject, utf8FromBase64 } from '@atproto/lex-data'\nimport type { DidString } from '@atproto/lex-schema'\nimport { isDidString } from '@atproto/lex-schema'\nimport type { CreateDidResolverOptions } from '@atproto-labs/did-resolver'\nimport { createDidResolver } from '@atproto-labs/did-resolver'\nimport { LexServerAuthError } from './errors.js'\nimport type { LexRouterAuth } from './lex-router.js'\n\nconst BEARER_PREFIX = 'Bearer '\n\n/**\n * Callback function to check and record nonce uniqueness.\n *\n * Used to prevent replay attacks by ensuring each nonce is only used once.\n * The implementation must track nonces for at least the `maxAge` duration\n * (default 5 minutes before and after the current time).\n *\n * @param nonce - The nonce string from the JWT token\n * @returns Promise resolving to `true` if the nonce is unique (first time seen),\n * `false` if it has been seen before\n *\n * @example\n * ```typescript\n * // Using Redis for nonce tracking\n * const checkNonce: UniqueNonceChecker = async (nonce) => {\n * const key = `nonce:${nonce}`\n * const result = await redis.setnx(key, '1')\n * if (result === 1) {\n * await redis.expire(key, 600) // 10 minutes TTL\n * return true\n * }\n * return false\n * }\n * ```\n */\nexport type UniqueNonceChecker = (nonce: string) => Promise<boolean>\n\n/**\n * Configuration options for AT Protocol service authentication.\n *\n * Service auth is used for server-to-server communication in the AT Protocol,\n * where one service authenticates to another using signed JWT tokens tied to\n * the caller's DID.\n *\n * @example\n * ```typescript\n * const options: ServiceAuthOptions = {\n * audience: 'did:web:api.example.com',\n * unique: async (nonce) => nonceStore.checkAndAdd(nonce),\n * maxAge: 300, // 5 minutes\n * // Optional DID resolver options\n * plcDirectoryUrl: 'https://plc.directory'\n * }\n * ```\n */\nexport type ServiceAuthOptions = CreateDidResolverOptions & {\n /**\n * Expected audience (\"aud\") claim in the JWT token.\n *\n * This should be the DID of your service. The token must include this\n * value in its `aud` claim to be accepted. Set to `null` to skip\n * audience verification (not recommended for production).\n */\n audience: null | DidString\n /**\n * Function to check and record nonce uniqueness.\n *\n * This is critical for preventing replay attacks. The value checked here\n * must be unique within `maxAge` seconds before and after the current time.\n *\n * @param nonce - The nonce to check\n * @returns Promise resolving to `true` if unique, `false` if seen before\n */\n unique: UniqueNonceChecker\n /**\n * Maximum age of the JWT token in seconds.\n *\n * Tokens with `iat` (issued at) or `exp` (expiry) timestamps outside\n * this window from the current time will be rejected.\n *\n * @default 300 (5 minutes)\n */\n maxAge?: number\n}\n\n/**\n * Credentials returned after successful service authentication.\n *\n * Contains the verified DID, resolved DID document, and parsed JWT token.\n * These are available in handler context as `ctx.credentials`.\n *\n * @example\n * ```typescript\n * router.add(protectedMethod, {\n * handler: async (ctx) => {\n * const { did, didDocument, jwt } = ctx.credentials\n * console.log('Request from:', did)\n * console.log('Token expires:', new Date(jwt.payload.exp * 1000))\n * return { body: { callerDid: did } }\n * },\n * auth: serviceAuth({ audience: myDid, unique: checkNonce })\n * })\n * ```\n */\nexport type ServiceAuthCredentials = {\n /** The verified AT Protocol DID of the caller. */\n did: AtprotoDid\n /** The resolved DID document of the caller. */\n didDocument: AtprotoDidDocument\n /** The parsed and validated JWT token. */\n jwt: ParsedJwt\n}\n\n/**\n * Creates an authentication handler for verifying AT Protocol service auth JWTs.\n *\n * Service auth is the standard authentication mechanism for server-to-server\n * communication in the AT Protocol. It uses JWT bearer tokens signed by the\n * caller's DID signing key, with the signature verified against the public\n * key in the caller's DID document.\n *\n * The handler performs the following validations:\n * - Extracts and parses the Bearer token from the Authorization header\n * - Validates JWT structure and claims (aud, exp, iat, lxm, nonce)\n * - Resolves the issuer's DID document\n * - Verifies the JWT signature against the `#atproto` verification method\n * - Checks nonce uniqueness to prevent replay attacks\n *\n * @param options - Configuration options for service auth\n * @returns An auth handler function for use with {@link LexRouter.add}\n *\n * @example Basic usage\n * ```typescript\n * import { LexRouter, serviceAuth } from '@atproto/lex-server'\n *\n * const router = new LexRouter()\n *\n * const auth = serviceAuth({\n * audience: 'did:web:api.example.com',\n * unique: async (nonce) => {\n * // Check if nonce has been seen, return true if unique\n * const isNew = await redis.setnx(`nonce:${nonce}`, '1')\n * if (isNew) await redis.expire(`nonce:${nonce}`, 600)\n * return isNew\n * }\n * })\n *\n * router.add(myMethod, {\n * handler: async (ctx) => {\n * console.log('Authenticated as:', ctx.credentials.did)\n * return { body: { success: true } }\n * },\n * auth\n * })\n * ```\n */\nexport function serviceAuth({\n audience,\n maxAge = 5 * 60,\n unique,\n ...options\n}: ServiceAuthOptions): LexRouterAuth<ServiceAuthCredentials> {\n const didResolver = createDidResolver(options)\n\n return async ({ request, method }) => {\n const { signal } = request\n const jwt = await parseJwtBearer(request, {\n lxm: method.nsid,\n maxAge,\n audience,\n unique,\n })\n\n let didDocument: AtprotoDidDocument = await didResolver\n .resolve(jwt.payload.iss, { signal })\n .catch((cause) => {\n throw new LexServerAuthError(\n 'AuthenticationRequired',\n 'Could not resolve DID document',\n { Bearer: { error: 'DidResolutionFailed' } },\n { cause },\n )\n })\n\n const key = getAtprotoSigningKey(didDocument)\n\n if (!key || !(await verifyJwt(jwt, key))) {\n signal.throwIfAborted()\n\n // Try refreshing the DID document in case it was updated\n didDocument = await didResolver\n .resolve(jwt.payload.iss, { signal, noCache: true })\n .catch((cause) => {\n throw new LexServerAuthError(\n 'AuthenticationRequired',\n 'Could not resolve DID document',\n { Bearer: { error: 'DidResolutionFailed' } },\n { cause },\n )\n })\n\n // Verify again with the fresh key (if it changed)\n const keyFresh = getAtprotoSigningKey(didDocument)\n if (!keyFresh || key === keyFresh || !(await verifyJwt(jwt, keyFresh))) {\n throw new LexServerAuthError(\n 'AuthenticationRequired',\n 'Invalid JWT signature',\n { Bearer: { error: 'BadJwtSignature' } },\n )\n }\n }\n\n return {\n did: didDocument.id,\n didDocument,\n jwt,\n }\n }\n}\n\nasync function verifyJwt(jwt: ParsedJwt, key: Did<'key'>) {\n try {\n return await crypto.verifySignature(key, jwt.message, jwt.signature, {\n jwtAlg: jwt.header.alg,\n allowMalleableSig: true,\n })\n } catch (cause) {\n throw new LexServerAuthError(\n 'AuthenticationRequired',\n 'Could not verify JWT signature',\n { Bearer: { error: 'BadJwtSignature' } },\n { cause },\n )\n }\n}\n\nfunction getAtprotoSigningKey(\n didDocument: AtprotoDidDocument,\n): null | Did<'key'> {\n try {\n const key = didDocument.verificationMethod?.find(\n isAtprotoVerificationMethod,\n didDocument,\n )\n\n if (key?.publicKeyMultibase) {\n if (key.type === 'EcdsaSecp256r1VerificationKey2019') {\n const keyBytes = crypto.multibaseToBytes(key.publicKeyMultibase)\n return crypto.formatDidKey(crypto.P256_JWT_ALG, keyBytes)\n } else if (key.type === 'EcdsaSecp256k1VerificationKey2019') {\n const keyBytes = crypto.multibaseToBytes(key.publicKeyMultibase)\n return crypto.formatDidKey(crypto.SECP256K1_JWT_ALG, keyBytes)\n } else if (key.type === 'Multikey') {\n const parsed = crypto.parseMultikey(key.publicKeyMultibase)\n return crypto.formatDidKey(parsed.jwtAlg, parsed.keyBytes)\n }\n }\n } catch {\n // Invalid key, ignore\n }\n\n return null\n}\n\nfunction isAtprotoVerificationMethod<\n V extends string | { id: string; type: string; publicKeyMultibase?: string },\n>(\n this: AtprotoDidDocument,\n vm: V,\n): vm is Exclude<V, string> & {\n id: `${string}#atproto`\n} {\n return typeof vm === 'object' && matchesIdentifier(this.id, 'atproto', vm.id)\n}\n\nasync function parseJwtBearer(\n request: Request,\n options: ParseJwtOptions,\n): Promise<ParsedJwt> {\n const authorization = request.headers.get('authorization')\n if (!authorization?.startsWith(BEARER_PREFIX)) {\n throw new LexServerAuthError(\n 'AuthenticationRequired',\n 'Bearer token required',\n { Bearer: { error: 'MissingBearer' } },\n )\n }\n\n const token = authorization.slice(BEARER_PREFIX.length).trim()\n\n return parseJwt(token, options)\n}\n\n/**\n * Options for parsing and validating a JWT token.\n */\nexport type ParseJwtOptions = {\n /** Maximum age in seconds for token validity window. */\n maxAge: number\n /** Expected audience claim, or null to skip audience verification. */\n audience: null | DidString\n /** Function to check nonce uniqueness. */\n unique: UniqueNonceChecker\n /** Expected lexicon method NSID for the `lxm` claim. */\n lxm: string\n}\n\n/**\n * A parsed and partially validated JWT token.\n *\n * Contains the decoded header and payload, along with the raw bytes\n * needed for signature verification.\n *\n * @example\n * ```typescript\n * const jwt: ParsedJwt = {\n * header: { alg: 'ES256K', typ: 'JWT' },\n * payload: {\n * iss: 'did:plc:abc123',\n * aud: 'did:web:api.example.com',\n * exp: 1704067200,\n * iat: 1704066900,\n * lxm: 'com.atproto.sync.getBlob'\n * },\n * message: new Uint8Array([...]),\n * signature: new Uint8Array([...])\n * }\n * ```\n */\nexport type ParsedJwt = {\n /** The decoded JWT header containing algorithm and type. */\n header: HeaderObject\n /** The decoded JWT payload containing claims. */\n payload: PayloadObject\n /** The raw header.payload bytes for signature verification. */\n message: Uint8Array\n /** The decoded signature bytes. */\n signature: Uint8Array\n}\n\nasync function parseJwt(\n token: string,\n options: ParseJwtOptions,\n): Promise<ParsedJwt> {\n const {\n length,\n 0: headerB64,\n 1: payloadB64,\n 2: signatureB64,\n } = token.split('.')\n if (length !== 3) {\n throw new LexServerAuthError(\n 'AuthenticationRequired',\n 'Invalid JWT token',\n { Bearer: { error: 'BadJwt' } },\n )\n }\n\n let header: HeaderObject\n try {\n header = jsonFromBase64(headerB64, isHeaderObject)\n } catch (cause) {\n throw new LexServerAuthError(\n 'AuthenticationRequired',\n 'Invalid JWT token',\n { Bearer: { error: 'BadJwt' } },\n { cause },\n )\n }\n\n if (\n header.alg === 'none' ||\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 LexServerAuthError(\n 'AuthenticationRequired',\n 'Invalid JWT token',\n { Bearer: { error: 'BadJwt' } },\n )\n }\n\n let payload: PayloadObject\n try {\n payload = jsonFromBase64(payloadB64, isPayloadObject)\n } catch (cause) {\n throw new LexServerAuthError(\n 'AuthenticationRequired',\n 'Invalid JWT token',\n { Bearer: { error: 'BadJwt' } },\n { cause },\n )\n }\n\n if (options.audience !== null && options.audience !== payload.aud) {\n throw new LexServerAuthError('AuthenticationRequired', 'Invalid audience', {\n Bearer: { error: 'InvalidAudience' },\n })\n }\n\n const now = Math.floor(Date.now() / 1000)\n\n if (payload.nbf != null && now < payload.nbf) {\n throw new LexServerAuthError(\n 'AuthenticationRequired',\n 'JWT token not yet valid',\n { Bearer: { error: 'JwtNotYetValid' } },\n )\n }\n\n if (now > payload.exp) {\n throw new LexServerAuthError(\n 'AuthenticationRequired',\n 'JWT token expired',\n { Bearer: { error: 'JwtExpired' } },\n )\n }\n\n // Prevent issuer from generating very long-lived tokens\n if (\n timeDiff(now, payload.exp) > options.maxAge ||\n timeDiff(now, payload.iat) > options.maxAge\n ) {\n throw new LexServerAuthError(\n 'AuthenticationRequired',\n 'JWT token too old',\n { Bearer: { error: 'JwtTooOld' } },\n )\n }\n\n if (payload.lxm != null && payload.lxm !== options.lxm) {\n throw new LexServerAuthError(\n 'AuthenticationRequired',\n 'Invalid JWT lexicon method (\"lxm\")',\n { Bearer: { error: 'BadJwtLexiconMethod' } },\n )\n }\n\n if (payload.nonce != null && !(await (0, options.unique)(payload.nonce))) {\n throw new LexServerAuthError(\n 'AuthenticationRequired',\n 'Replay attack detected: nonce is not unique',\n { Bearer: { error: 'NonceNotUnique' } },\n )\n }\n\n return {\n header,\n payload,\n message: textEncoder.encode(`${headerB64}.${payloadB64}`),\n signature: fromBase64(signatureB64, 'base64url'),\n }\n}\n\nconst textEncoder = /*#__PURE__*/ new TextEncoder()\n\ntype HeaderObject = { alg: string; typ?: string }\nfunction isHeaderObject(obj: unknown): obj is HeaderObject {\n return (\n isPlainObject(obj) &&\n typeof obj.alg === 'string' &&\n (obj.typ === undefined || typeof obj.typ === 'string')\n )\n}\n\ntype PayloadObject = {\n iss: DidString\n aud: DidString\n exp: number\n iat?: number\n nbf?: number\n lxm?: string\n nonce?: string\n}\nexport function isPayloadObject(obj: unknown): obj is PayloadObject {\n return (\n isPlainObject(obj) &&\n typeof obj.iss === 'string' &&\n typeof obj.aud === 'string' &&\n (obj.lxm === undefined || typeof obj.lxm === 'string') &&\n (obj.nonce === undefined || typeof obj.nonce === 'string') &&\n (obj.iat === undefined || isPositiveInt(obj.iat)) &&\n (obj.nbf === undefined || isPositiveInt(obj.nbf)) &&\n isPositiveInt(obj.exp) &&\n isDidString(obj.iss) &&\n isDidString(obj.aud)\n )\n}\n\nfunction timeDiff(t1: number, t2?: number): number {\n if (t2 === undefined) return 0\n return Math.abs(t1 - t2)\n}\n\nfunction isPositiveInt(value: unknown): value is number {\n return typeof value === 'number' && Number.isInteger(value) && value > 0\n}\n\nfunction jsonFromBase64<T>(b64: string, isType: (obj: unknown) => obj is T): T {\n const obj = JSON.parse(utf8FromBase64(b64, 'base64url'))\n if (isType(obj)) return obj\n throw new Error('Invalid type')\n}\n"]}
package/package.json ADDED
@@ -0,0 +1,61 @@
1
+ {
2
+ "name": "@atproto/lex-server",
3
+ "version": "0.0.0-spaces-alpha-20260818163953",
4
+ "license": "MIT",
5
+ "description": "Request router for Atproto Lexicon protocols and schemas",
6
+ "keywords": [
7
+ "atproto",
8
+ "lexicon",
9
+ "router",
10
+ "typescript"
11
+ ],
12
+ "homepage": "https://atproto.com",
13
+ "repository": {
14
+ "type": "git",
15
+ "url": "https://github.com/bluesky-social/atproto",
16
+ "directory": "packages/lex/lex-server"
17
+ },
18
+ "files": [
19
+ "./dist",
20
+ "./README.md",
21
+ "./CHANGELOG.md"
22
+ ],
23
+ "sideEffects": false,
24
+ "type": "module",
25
+ "exports": {
26
+ ".": {
27
+ "types": "./dist/index.d.ts",
28
+ "default": "./dist/index.js"
29
+ },
30
+ "./nodejs": {
31
+ "types": "./dist/nodejs.d.ts",
32
+ "default": "./dist/nodejs.js"
33
+ }
34
+ },
35
+ "engines": {
36
+ "node": ">=22"
37
+ },
38
+ "dependencies": {
39
+ "http-terminator": "^3.2.0",
40
+ "tslib": "^2.8.1",
41
+ "ws": "^8.18.3",
42
+ "@atproto-labs/did-resolver": "^0.3.7",
43
+ "@atproto/crypto": "^0.0.0-spaces-alpha-20260818163953",
44
+ "@atproto/lex-cbor": "^0.1.6",
45
+ "@atproto/lex-client": "^0.0.0-spaces-alpha-20260818163953",
46
+ "@atproto/lex-data": "^0.1.7",
47
+ "@atproto/lex-json": "^0.1.6",
48
+ "@atproto/did": "^0.5.4",
49
+ "@atproto/lex-schema": "^0.0.0-spaces-alpha-20260818163953"
50
+ },
51
+ "devDependencies": {
52
+ "@types/ws": "^8.18.1",
53
+ "vitest": "^4.1.10",
54
+ "@atproto/lex": "^0.0.0-spaces-alpha-20260818163953",
55
+ "@atproto/lex-client": "^0.0.0-spaces-alpha-20260818163953"
56
+ },
57
+ "scripts": {
58
+ "build": "tsc --build tsconfig.build.json",
59
+ "test": "vitest run"
60
+ }
61
+ }