@silkweave/auth 1.3.0

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,18 @@
1
+
2
+ 
3
+ > @silkweave/auth@1.3.0 build /Users/atomic/projects/ai/silkweave/packages/auth
4
+ > tsup
5
+
6
+ CLI Building entry: src/index.ts
7
+ CLI Using tsconfig: tsconfig.json
8
+ CLI tsup v8.5.1
9
+ CLI Using tsup config: /Users/atomic/projects/ai/silkweave/packages/auth/tsup.config.ts
10
+ CLI Target: node18
11
+ CLI Cleaning output folder
12
+ ESM Build start
13
+ ESM build/index.js 25.84 KB
14
+ ESM build/index.js.map 46.97 KB
15
+ ESM ⚡️ Build success in 9ms
16
+ DTS Build start
17
+ DTS ⚡️ Build success in 447ms
18
+ DTS build/index.d.ts 5.81 KB
@@ -0,0 +1,13 @@
1
+
2
+ 
3
+ > @silkweave/auth@1.3.0 check /Users/atomic/projects/ai/silkweave/packages/auth
4
+ > pnpm lint && pnpm typecheck
5
+
6
+
7
+ > @silkweave/auth@1.3.0 lint /Users/atomic/projects/ai/silkweave/packages/auth
8
+ > eslint
9
+
10
+
11
+ > @silkweave/auth@1.3.0 typecheck /Users/atomic/projects/ai/silkweave/packages/auth
12
+ > tsc --noEmit
13
+
@@ -0,0 +1,5 @@
1
+
2
+ 
3
+ > @silkweave/auth@1.3.0 lint /Users/atomic/projects/ai/silkweave/packages/auth
4
+ > eslint
5
+
@@ -0,0 +1,26 @@
1
+
2
+ 
3
+ > @silkweave/auth@1.3.0 prepack /Users/atomic/projects/ai/mcphero/packages/auth
4
+ > pnpm clean && pnpm build
5
+
6
+
7
+ > @silkweave/auth@1.3.0 clean /Users/atomic/projects/ai/mcphero/packages/auth
8
+ > rimraf build
9
+
10
+
11
+ > @silkweave/auth@1.3.0 build /Users/atomic/projects/ai/mcphero/packages/auth
12
+ > tsup
13
+
14
+ CLI Building entry: src/index.ts
15
+ CLI Using tsconfig: tsconfig.json
16
+ CLI tsup v8.5.1
17
+ CLI Using tsup config: /Users/atomic/projects/ai/mcphero/packages/auth/tsup.config.ts
18
+ CLI Target: node18
19
+ CLI Cleaning output folder
20
+ ESM Build start
21
+ ESM build/index.js 25.84 KB
22
+ ESM build/index.js.map 46.97 KB
23
+ ESM ⚡️ Build success in 10ms
24
+ DTS Build start
25
+ DTS ⚡️ Build success in 434ms
26
+ DTS build/index.d.ts 5.81 KB
package/README.md ADDED
@@ -0,0 +1,245 @@
1
+ # @silkweave/auth
2
+
3
+ OAuth 2.1 authentication for [Silkweave](https://github.com/atomicbi/silkweave) MCP servers. Acts as an OAuth proxy between MCP clients and upstream identity providers (Google, etc.), handling PKCE, refresh tokens, dynamic client registration (CIMD), and protected resource metadata (RFC 9728).
4
+
5
+ Standalone package -- only depends on `jose` for JWT signing/verification.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ pnpm add @silkweave/auth
11
+ ```
12
+
13
+ ## Quick Start with Google OAuth
14
+
15
+ The `google()` helper returns a complete `AuthConfig` ready to pass to the `http()` adapter:
16
+
17
+ ```typescript
18
+ import { google, createJsonStore } from '@silkweave/auth'
19
+ import { silkweave } from '@silkweave/core'
20
+ import { http } from '@silkweave/mcp'
21
+
22
+ const auth = google({
23
+ clientId: process.env.GOOGLE_CLIENT_ID!,
24
+ clientSecret: process.env.GOOGLE_CLIENT_SECRET!,
25
+ resourceUrl: 'http://localhost:8080',
26
+ redirectUris: ['http://localhost:*', 'https://claude.ai/*'],
27
+ requiredScopes: ['openid', 'https://www.googleapis.com/auth/userinfo.email'],
28
+ signingKey: 'your-signing-secret',
29
+ store: createJsonStore('oauth-store.json')
30
+ })
31
+
32
+ await silkweave({ name: 'my-server', description: 'My MCP Server', version: '1.0.0' })
33
+ .adapter(http({ host: 'localhost', port: 8080, auth }))
34
+ .action(MyAction)
35
+ .start()
36
+ ```
37
+
38
+ ### `GoogleOAuthOptions`
39
+
40
+ | Option | Type | Default | Description |
41
+ |--------|------|---------|-------------|
42
+ | `clientId` | `string` | -- | Google OAuth client ID |
43
+ | `clientSecret` | `string` | -- | Google OAuth client secret |
44
+ | `resourceUrl` | `string` | -- | Public URL of your MCP server |
45
+ | `redirectUris` | `string[]` | -- | Allowed redirect URI patterns (supports `*` wildcards) |
46
+ | `requiredScopes` | `string[]` | `['openid', 'email']` | Scopes to request from Google |
47
+ | `callbackPath` | `string` | `'/auth/callback'` | Path for the OAuth callback endpoint |
48
+ | `signingKey` | `string` | random | Secret for signing JWTs (random per-process if omitted) |
49
+ | `tokenTtl` | `number` | `3600` | Access token lifetime in seconds |
50
+ | `store` | `OAuthStore` | memory | Store adapter for OAuth state |
51
+
52
+ ## Custom Providers with `createOAuthProxy()`
53
+
54
+ For providers other than Google, use `createOAuthProxy()` directly. It returns an `OAuthProvider` that implements the full OAuth 2.1 proxy flow:
55
+
56
+ ```typescript
57
+ import { createOAuthProxy } from '@silkweave/auth'
58
+
59
+ const provider = createOAuthProxy({
60
+ authorizeUrl: 'https://provider.example.com/authorize',
61
+ tokenUrl: 'https://provider.example.com/token',
62
+ userinfoUrl: 'https://provider.example.com/userinfo',
63
+ clientId: process.env.OAUTH_CLIENT_ID!,
64
+ clientSecret: process.env.OAUTH_CLIENT_SECRET!,
65
+ resourceUrl: 'https://my-server.example.com',
66
+ redirectUris: ['https://claude.ai/*'],
67
+ requiredScopes: ['openid', 'email']
68
+ })
69
+ ```
70
+
71
+ ### `OAuthProxyConfig`
72
+
73
+ | Option | Type | Default | Description |
74
+ |--------|------|---------|-------------|
75
+ | `authorizeUrl` | `string` | -- | Upstream authorization endpoint |
76
+ | `tokenUrl` | `string` | -- | Upstream token endpoint |
77
+ | `userinfoUrl` | `string` | -- | Upstream userinfo endpoint (optional, best-effort) |
78
+ | `clientId` | `string` | -- | Your client ID with the upstream provider |
79
+ | `clientSecret` | `string` | -- | Your client secret with the upstream provider |
80
+ | `resourceUrl` | `string` | -- | Public URL of your MCP server |
81
+ | `redirectUris` | `string[]` | -- | Allowed redirect URI patterns |
82
+ | `requiredScopes` | `string[]` | `[]` | Scopes to request upstream |
83
+ | `callbackPath` | `string` | `'/auth/callback'` | Path for the OAuth callback endpoint |
84
+ | `signingKey` | `string` | random | Secret for signing JWTs |
85
+ | `tokenTtl` | `number` | `3600` | Access token lifetime in seconds |
86
+ | `store` | `OAuthStore` | memory | Store adapter for OAuth state |
87
+
88
+ ### `OAuthProvider` interface
89
+
90
+ The provider returned by `createOAuthProxy()` exposes:
91
+
92
+ ```typescript
93
+ interface OAuthProvider {
94
+ metadata(): OAuthResponse
95
+ register(req: OAuthRequest): Promise<OAuthResponse>
96
+ authorize(req: OAuthRequest): Promise<OAuthResponse>
97
+ callback(req: OAuthRequest): Promise<OAuthResponse>
98
+ token(req: OAuthRequest): Promise<OAuthResponse>
99
+ verifyToken(token: string): Promise<AuthInfo | undefined>
100
+ }
101
+ ```
102
+
103
+ To build a full `AuthConfig` from a custom provider:
104
+
105
+ ```typescript
106
+ const auth: AuthConfig = {
107
+ verifyToken: (token) => provider.verifyToken(token),
108
+ required: true,
109
+ resourceUrl: 'https://my-server.example.com',
110
+ authorizationServers: ['https://my-server.example.com'],
111
+ provider
112
+ }
113
+ ```
114
+
115
+ ## Token Validation
116
+
117
+ Use `validateToken()` to verify bearer tokens in your own middleware or custom adapters:
118
+
119
+ ```typescript
120
+ import { validateToken } from '@silkweave/auth'
121
+
122
+ const result = await validateToken(request.headers.authorization, {
123
+ verifyToken: async (token) => {
124
+ // Your verification logic -- return AuthInfo or undefined
125
+ return { token, clientId: 'user-123', scopes: ['read'] }
126
+ },
127
+ required: true,
128
+ resourceUrl: 'https://my-server.example.com',
129
+ requiredScopes: ['read']
130
+ })
131
+
132
+ if (result.error) {
133
+ // result.error.statusCode, result.error.headers, result.error.body
134
+ return new Response(JSON.stringify(result.error.body), {
135
+ status: result.error.statusCode,
136
+ headers: result.error.headers
137
+ })
138
+ }
139
+
140
+ // result.auth contains the verified AuthInfo
141
+ console.log(result.auth?.clientId)
142
+ ```
143
+
144
+ ## Protected Resource Metadata (RFC 9728)
145
+
146
+ Generate the `/.well-known/oauth-protected-resource` document for your server:
147
+
148
+ ```typescript
149
+ import { generateProtectedResourceMetadata } from '@silkweave/auth'
150
+
151
+ const metadata = generateProtectedResourceMetadata(
152
+ 'https://my-server.example.com',
153
+ ['https://my-server.example.com']
154
+ )
155
+ // {
156
+ // resource: 'https://my-server.example.com',
157
+ // authorization_servers: ['https://my-server.example.com'],
158
+ // bearer_methods_supported: ['header']
159
+ // }
160
+ ```
161
+
162
+ ## Store Adapters
163
+
164
+ The OAuth proxy needs persistent storage for auth codes, client registrations, PKCE verifiers, and refresh tokens. Three built-in adapters are available:
165
+
166
+ ### Memory (default)
167
+
168
+ In-memory storage -- data is lost on restart. Good for development:
169
+
170
+ ```typescript
171
+ import { createMemoryStore } from '@silkweave/auth'
172
+
173
+ const store = createMemoryStore()
174
+ ```
175
+
176
+ ### JSON File
177
+
178
+ Persists to a JSON file on disk. Suitable for single-process deployments:
179
+
180
+ ```typescript
181
+ import { createJsonStore } from '@silkweave/auth'
182
+
183
+ const store = createJsonStore('oauth-store.json')
184
+ ```
185
+
186
+ ### Redis
187
+
188
+ For production multi-process deployments. Accepts any Redis client with `get`/`set`/`del` methods (compatible with `ioredis` and `redis`):
189
+
190
+ ```typescript
191
+ import { createRedisStore } from '@silkweave/auth'
192
+ import Redis from 'ioredis'
193
+
194
+ const store = createRedisStore({
195
+ client: new Redis(),
196
+ prefix: 'silkweave:oauth:' // default prefix
197
+ })
198
+ ```
199
+
200
+ ### Custom Store
201
+
202
+ Implement the `OAuthStore` interface for your own backend:
203
+
204
+ ```typescript
205
+ import type { OAuthStore } from '@silkweave/auth'
206
+
207
+ const store: OAuthStore = {
208
+ saveAuthCode(code, data) { /* ... */ },
209
+ getAuthCode(code) { /* ... */ },
210
+ deleteAuthCode(code) { /* ... */ },
211
+ savePendingAuth(state, data) { /* ... */ },
212
+ getPendingAuth(state) { /* ... */ },
213
+ deletePendingAuth(state) { /* ... */ },
214
+ savePkceVerifier(state, verifier) { /* ... */ },
215
+ getPkceVerifier(state) { /* ... */ },
216
+ deletePkceVerifier(state) { /* ... */ },
217
+ saveClient(clientId, data) { /* ... */ },
218
+ getClient(clientId) { /* ... */ },
219
+ saveRefreshToken(token, data) { /* ... */ },
220
+ getRefreshToken(token) { /* ... */ },
221
+ deleteRefreshToken(token) { /* ... */ }
222
+ }
223
+ ```
224
+
225
+ ## How It Works
226
+
227
+ The OAuth proxy sits between MCP clients and the upstream identity provider:
228
+
229
+ 1. MCP client calls `/authorize` -- the proxy generates its own PKCE pair and redirects to the upstream provider
230
+ 2. User authenticates with the upstream provider (e.g., Google)
231
+ 3. Upstream redirects back to the proxy's callback path with an authorization code
232
+ 4. Proxy exchanges the upstream code for tokens, then issues its own authorization code to the MCP client
233
+ 5. MCP client exchanges that code at `/token` (with PKCE verification) and receives a signed JWT access token + refresh token
234
+ 6. Subsequent requests include the JWT as a Bearer token, verified locally via `jose`
235
+
236
+ The proxy also supports:
237
+ - **Dynamic client registration** at `/register` (RFC 7591)
238
+ - **Client Information Metadata Documents (CIMD)** -- clients with HTTPS URLs as `client_id` are auto-registered by fetching their metadata document
239
+ - **Refresh tokens** with 30-day expiry for long-lived sessions
240
+
241
+ ## See Also
242
+
243
+ - [Silkweave README](https://github.com/atomicbi/silkweave) -- Full documentation
244
+ - [`@silkweave/core`](https://www.npmjs.com/package/@silkweave/core) -- Core library
245
+ - [`@silkweave/mcp`](https://www.npmjs.com/package/@silkweave/mcp) -- MCP stdio and HTTP adapters
@@ -0,0 +1,173 @@
1
+ declare class AuthError extends Error {
2
+ readonly code: string;
3
+ readonly statusCode: number;
4
+ constructor(message: string, code: string, statusCode?: number);
5
+ }
6
+ declare function invalidToken(message?: string): AuthError;
7
+ declare function insufficientScope(message?: string): AuthError;
8
+ declare function missingToken(message?: string): AuthError;
9
+
10
+ declare function extractBearerToken(header: string | null | undefined): string | null;
11
+ declare function buildWWWAuthenticate(error?: string, description?: string, resourceMetadataUrl?: string): string;
12
+
13
+ interface ProtectedResourceMetadata {
14
+ resource: string;
15
+ authorization_servers: string[];
16
+ scopes_supported?: string[];
17
+ bearer_methods_supported?: string[];
18
+ }
19
+ declare function generateProtectedResourceMetadata(resourceUrl: string, authorizationServers: string[]): ProtectedResourceMetadata;
20
+
21
+ interface AuthCodeData {
22
+ clientId: string;
23
+ redirectUri: string;
24
+ codeChallenge: string;
25
+ codeChallengeMethod: string;
26
+ scopes: string[];
27
+ upstreamAccessToken: string;
28
+ upstreamIdToken?: string;
29
+ email?: string;
30
+ sub?: string;
31
+ expiresAt: number;
32
+ }
33
+ interface PendingAuthData {
34
+ clientId: string;
35
+ redirectUri: string;
36
+ codeChallenge: string;
37
+ codeChallengeMethod: string;
38
+ scope: string;
39
+ clientState: string;
40
+ resource?: string;
41
+ expiresAt: number;
42
+ }
43
+ interface ClientRegistration {
44
+ clientId: string;
45
+ clientSecret: string;
46
+ redirectUris: string[];
47
+ clientName?: string;
48
+ createdAt: number;
49
+ }
50
+ interface RefreshTokenData {
51
+ clientId: string;
52
+ scopes: string[];
53
+ email?: string;
54
+ sub?: string;
55
+ expiresAt: number;
56
+ }
57
+ interface OAuthStore {
58
+ saveAuthCode(code: string, data: AuthCodeData): Promise<void>;
59
+ getAuthCode(code: string): Promise<AuthCodeData | undefined>;
60
+ deleteAuthCode(code: string): Promise<void>;
61
+ savePendingAuth(state: string, data: PendingAuthData): Promise<void>;
62
+ getPendingAuth(state: string): Promise<PendingAuthData | undefined>;
63
+ deletePendingAuth(state: string): Promise<void>;
64
+ savePkceVerifier(state: string, verifier: string): Promise<void>;
65
+ getPkceVerifier(state: string): Promise<string | undefined>;
66
+ deletePkceVerifier(state: string): Promise<void>;
67
+ saveClient(clientId: string, data: ClientRegistration): Promise<void>;
68
+ getClient(clientId: string): Promise<ClientRegistration | undefined>;
69
+ saveRefreshToken(token: string, data: RefreshTokenData): Promise<void>;
70
+ getRefreshToken(token: string): Promise<RefreshTokenData | undefined>;
71
+ deleteRefreshToken(token: string): Promise<void>;
72
+ }
73
+
74
+ declare function createMemoryStore(): OAuthStore;
75
+
76
+ interface OAuthRequest {
77
+ method: string;
78
+ url: URL;
79
+ headers: Record<string, string | undefined>;
80
+ body?: Record<string, string>;
81
+ }
82
+ interface OAuthResponse {
83
+ status: number;
84
+ headers: Record<string, string>;
85
+ body?: string | Record<string, unknown>;
86
+ }
87
+ interface OAuthProvider {
88
+ authorize(req: OAuthRequest): Promise<OAuthResponse>;
89
+ callback(req: OAuthRequest): Promise<OAuthResponse>;
90
+ token(req: OAuthRequest): Promise<OAuthResponse>;
91
+ register(req: OAuthRequest): Promise<OAuthResponse>;
92
+ metadata(): OAuthResponse;
93
+ verifyToken(token: string): Promise<AuthInfo | undefined>;
94
+ }
95
+
96
+ interface AuthInfo {
97
+ token: string;
98
+ clientId?: string;
99
+ scopes?: string[];
100
+ expiresAt?: number;
101
+ [key: string]: unknown;
102
+ }
103
+ type VerifyToken = (token: string) => Promise<AuthInfo | undefined>;
104
+ interface AuthConfig {
105
+ verifyToken: VerifyToken;
106
+ required?: boolean;
107
+ resourceUrl?: string;
108
+ authorizationServers?: string[];
109
+ requiredScopes?: string[];
110
+ provider?: OAuthProvider;
111
+ callbackPath?: string;
112
+ }
113
+
114
+ interface GoogleOAuthOptions {
115
+ clientId: string;
116
+ clientSecret: string;
117
+ resourceUrl: string;
118
+ redirectUris: string[];
119
+ requiredScopes?: string[];
120
+ callbackPath?: string;
121
+ signingKey?: string;
122
+ tokenTtl?: number;
123
+ store?: OAuthStore;
124
+ }
125
+ declare function google(options: GoogleOAuthOptions): AuthConfig;
126
+
127
+ interface OAuthProxyConfig {
128
+ authorizeUrl: string;
129
+ tokenUrl: string;
130
+ userinfoUrl?: string;
131
+ clientId: string;
132
+ clientSecret: string;
133
+ resourceUrl: string;
134
+ redirectUris: string[];
135
+ requiredScopes?: string[];
136
+ callbackPath?: string;
137
+ signingKey?: string;
138
+ tokenTtl?: number;
139
+ store?: OAuthStore;
140
+ }
141
+ declare function createOAuthProxy(config: OAuthProxyConfig): OAuthProvider;
142
+
143
+ declare function matchRedirectUri(uri: string, patterns: string[]): boolean;
144
+
145
+ declare function createJsonStore(path: string): OAuthStore;
146
+
147
+ interface RedisClient {
148
+ get(key: string): Promise<unknown>;
149
+ set(key: string, value: string, options?: {
150
+ ex?: number;
151
+ }): Promise<unknown>;
152
+ del(key: string): Promise<unknown>;
153
+ }
154
+ interface RedisStoreOptions {
155
+ client: RedisClient;
156
+ prefix?: string;
157
+ }
158
+ declare function createRedisStore(options: RedisStoreOptions): OAuthStore;
159
+
160
+ interface ValidateResult {
161
+ auth?: AuthInfo;
162
+ error?: {
163
+ statusCode: number;
164
+ headers: Record<string, string>;
165
+ body: {
166
+ error: string;
167
+ error_description: string;
168
+ };
169
+ };
170
+ }
171
+ declare function validateToken(authorizationHeader: string | null | undefined, config: AuthConfig): Promise<ValidateResult>;
172
+
173
+ export { type AuthCodeData, type AuthConfig, AuthError, type AuthInfo, type ClientRegistration, type GoogleOAuthOptions, type OAuthProvider, type OAuthProxyConfig, type OAuthRequest, type OAuthResponse, type OAuthStore, type PendingAuthData, type ProtectedResourceMetadata, type RedisClient, type RedisStoreOptions, type RefreshTokenData, type ValidateResult, type VerifyToken, buildWWWAuthenticate, createJsonStore, createMemoryStore, createOAuthProxy, createRedisStore, extractBearerToken, generateProtectedResourceMetadata, google, insufficientScope, invalidToken, matchRedirectUri, missingToken, validateToken };