@55387.ai/uniauth-server 1.0.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,260 @@
1
+ /**
2
+ * UniAuth Server SDK
3
+ * 统一认证后端 SDK
4
+ *
5
+ * Usage:
6
+ * ```typescript
7
+ * import { UniAuthServer } from '@uniauth/server-sdk';
8
+ *
9
+ * const auth = new UniAuthServer({
10
+ * baseUrl: 'https://auth.example.com',
11
+ * clientId: 'your-client-id',
12
+ * clientSecret: 'your-client-secret',
13
+ * });
14
+ *
15
+ * // Verify token
16
+ * const payload = await auth.verifyToken(accessToken);
17
+ *
18
+ * // Introspect token (RFC 7662)
19
+ * const introspectResult = await auth.introspectToken(accessToken);
20
+ *
21
+ * // Express middleware
22
+ * app.use('/api/*', auth.middleware());
23
+ *
24
+ * // Hono middleware
25
+ * app.use('/api/*', auth.honoMiddleware());
26
+ * ```
27
+ */
28
+ interface UniAuthServerConfig {
29
+ /** API base URL */
30
+ baseUrl: string;
31
+ /** OAuth2 Client ID (also used as appKey) */
32
+ clientId: string;
33
+ /** OAuth2 Client Secret (also used as appSecret) */
34
+ clientSecret: string;
35
+ /** JWT public key (optional, for local verification) */
36
+ jwtPublicKey?: string;
37
+ /** @deprecated Use clientId instead */
38
+ appKey?: string;
39
+ /** @deprecated Use clientSecret instead */
40
+ appSecret?: string;
41
+ }
42
+ interface TokenPayload {
43
+ /** User ID or Client ID (for M2M) */
44
+ sub: string;
45
+ /** Issuer */
46
+ iss?: string;
47
+ /** Audience */
48
+ aud?: string | string[];
49
+ /** Issued at timestamp */
50
+ iat: number;
51
+ /** Expiration timestamp */
52
+ exp: number;
53
+ /** Scopes */
54
+ scope?: string;
55
+ /** Authorized party (client_id that requested this token) */
56
+ azp?: string;
57
+ /** Phone number (optional) */
58
+ phone?: string;
59
+ /** Email address (optional) */
60
+ email?: string;
61
+ }
62
+ interface UserInfo {
63
+ id: string;
64
+ phone?: string | null;
65
+ email?: string | null;
66
+ nickname?: string | null;
67
+ avatar_url?: string | null;
68
+ phone_verified?: boolean;
69
+ email_verified?: boolean;
70
+ created_at?: string;
71
+ updated_at?: string;
72
+ }
73
+ interface VerifyResult {
74
+ valid: boolean;
75
+ payload?: TokenPayload;
76
+ error?: string;
77
+ }
78
+ /**
79
+ * RFC 7662 Token Introspection Response
80
+ * 令牌内省响应
81
+ */
82
+ interface IntrospectionResult {
83
+ /** Whether the token is active */
84
+ active: boolean;
85
+ /** Scopes associated with this token */
86
+ scope?: string;
87
+ /** Client ID that requested the token */
88
+ client_id?: string;
89
+ /** Username or user identifier */
90
+ username?: string;
91
+ /** Token type (usually "Bearer") */
92
+ token_type?: string;
93
+ /** Expiration timestamp */
94
+ exp?: number;
95
+ /** Issued at timestamp */
96
+ iat?: number;
97
+ /** Not before timestamp */
98
+ nbf?: number;
99
+ /** Subject (user ID or client ID) */
100
+ sub?: string;
101
+ /** Audience */
102
+ aud?: string | string[];
103
+ /** Issuer */
104
+ iss?: string;
105
+ /** JWT ID */
106
+ jti?: string;
107
+ }
108
+ /**
109
+ * Error codes for UniAuth Server SDK
110
+ * UniAuth 服务端 SDK 错误码
111
+ */
112
+ declare const ServerErrorCode: {
113
+ readonly INVALID_TOKEN: "INVALID_TOKEN";
114
+ readonly TOKEN_EXPIRED: "TOKEN_EXPIRED";
115
+ readonly VERIFICATION_FAILED: "VERIFICATION_FAILED";
116
+ readonly USER_NOT_FOUND: "USER_NOT_FOUND";
117
+ readonly UNAUTHORIZED: "UNAUTHORIZED";
118
+ readonly NO_PUBLIC_KEY: "NO_PUBLIC_KEY";
119
+ readonly NETWORK_ERROR: "NETWORK_ERROR";
120
+ readonly INTERNAL_ERROR: "INTERNAL_ERROR";
121
+ };
122
+ type ServerErrorCodeType = typeof ServerErrorCode[keyof typeof ServerErrorCode];
123
+ /**
124
+ * Custom error class for server SDK
125
+ * 服务端 SDK 自定义错误类
126
+ */
127
+ declare class ServerAuthError extends Error {
128
+ code: ServerErrorCodeType | string;
129
+ statusCode: number;
130
+ constructor(code: ServerErrorCodeType | string, message: string, statusCode?: number);
131
+ }
132
+ interface ExpressRequest {
133
+ headers: Record<string, string | string[] | undefined>;
134
+ user?: UserInfo;
135
+ authPayload?: TokenPayload;
136
+ }
137
+ interface ExpressResponse {
138
+ status(code: number): ExpressResponse;
139
+ json(data: unknown): void;
140
+ }
141
+ type NextFunction = (error?: Error) => void;
142
+ interface HonoContext {
143
+ req: {
144
+ header(name: string): string | undefined;
145
+ };
146
+ set(key: string, value: unknown): void;
147
+ get(key: string): unknown;
148
+ json(data: unknown, status?: number): Response;
149
+ }
150
+ type HonoMiddlewareHandler = (c: HonoContext, next: () => Promise<void>) => Promise<Response | void>;
151
+ /**
152
+ * UniAuth Server SDK
153
+ * 统一认证后端 SDK
154
+ */
155
+ declare class UniAuthServer {
156
+ private config;
157
+ private tokenCache;
158
+ constructor(config: UniAuthServerConfig);
159
+ /**
160
+ * Verify access token
161
+ * 验证访问令牌
162
+ *
163
+ * @param token - JWT access token
164
+ * @returns Token payload if valid
165
+ * @throws ServerAuthError if token is invalid
166
+ */
167
+ verifyToken(token: string): Promise<TokenPayload>;
168
+ /**
169
+ * Verify token locally using JWT public key
170
+ * 使用 JWT 公钥本地验证令牌
171
+ */
172
+ private verifyTokenLocally;
173
+ /**
174
+ * Introspect a token (RFC 7662)
175
+ * 内省令牌(RFC 7662 标准)
176
+ *
177
+ * This is the standard way for resource servers to validate tokens.
178
+ *
179
+ * @param token - The token to introspect
180
+ * @param tokenTypeHint - Optional hint about the token type ('access_token' or 'refresh_token')
181
+ * @returns Introspection result
182
+ *
183
+ * @example
184
+ * ```typescript
185
+ * const result = await auth.introspectToken(accessToken);
186
+ * if (result.active) {
187
+ * console.log('Token is valid, user:', result.sub);
188
+ * }
189
+ * ```
190
+ */
191
+ introspectToken(token: string, tokenTypeHint?: 'access_token' | 'refresh_token'): Promise<IntrospectionResult>;
192
+ /**
193
+ * Check if a token is active
194
+ * 检查令牌是否有效
195
+ *
196
+ * @param token - The token to check
197
+ * @returns true if token is active
198
+ */
199
+ isTokenActive(token: string): Promise<boolean>;
200
+ /**
201
+ * Get user info by ID
202
+ * 根据 ID 获取用户信息
203
+ */
204
+ getUser(userId: string): Promise<UserInfo>;
205
+ /**
206
+ * Express/Connect middleware for authentication
207
+ * Express/Connect 认证中间件
208
+ *
209
+ * @example
210
+ * ```typescript
211
+ * import express from 'express';
212
+ *
213
+ * const app = express();
214
+ * app.use('/api/*', auth.middleware());
215
+ *
216
+ * app.get('/api/profile', (req, res) => {
217
+ * res.json({ user: req.user });
218
+ * });
219
+ * ```
220
+ */
221
+ middleware(): (req: ExpressRequest, res: ExpressResponse, next: NextFunction) => Promise<void>;
222
+ /**
223
+ * Hono middleware for authentication
224
+ * Hono 认证中间件
225
+ *
226
+ * @example
227
+ * ```typescript
228
+ * import { Hono } from 'hono';
229
+ *
230
+ * const app = new Hono();
231
+ * app.use('/api/*', auth.honoMiddleware());
232
+ *
233
+ * app.get('/api/profile', (c) => {
234
+ * const user = c.get('user');
235
+ * return c.json({ user });
236
+ * });
237
+ * ```
238
+ */
239
+ honoMiddleware(): HonoMiddlewareHandler;
240
+ /**
241
+ * Clear token cache
242
+ * 清除令牌缓存
243
+ */
244
+ clearCache(): void;
245
+ /**
246
+ * Get cache statistics
247
+ * 获取缓存统计
248
+ */
249
+ getCacheStats(): {
250
+ size: number;
251
+ entries: number;
252
+ };
253
+ }
254
+ /** @deprecated Use ServerAuthError instead */
255
+ interface AuthError extends Error {
256
+ code: string;
257
+ statusCode: number;
258
+ }
259
+
260
+ export { type AuthError, type IntrospectionResult, ServerAuthError, ServerErrorCode, type ServerErrorCodeType, type TokenPayload, UniAuthServer, type UniAuthServerConfig, type UserInfo, type VerifyResult, UniAuthServer as default };
@@ -0,0 +1,260 @@
1
+ /**
2
+ * UniAuth Server SDK
3
+ * 统一认证后端 SDK
4
+ *
5
+ * Usage:
6
+ * ```typescript
7
+ * import { UniAuthServer } from '@uniauth/server-sdk';
8
+ *
9
+ * const auth = new UniAuthServer({
10
+ * baseUrl: 'https://auth.example.com',
11
+ * clientId: 'your-client-id',
12
+ * clientSecret: 'your-client-secret',
13
+ * });
14
+ *
15
+ * // Verify token
16
+ * const payload = await auth.verifyToken(accessToken);
17
+ *
18
+ * // Introspect token (RFC 7662)
19
+ * const introspectResult = await auth.introspectToken(accessToken);
20
+ *
21
+ * // Express middleware
22
+ * app.use('/api/*', auth.middleware());
23
+ *
24
+ * // Hono middleware
25
+ * app.use('/api/*', auth.honoMiddleware());
26
+ * ```
27
+ */
28
+ interface UniAuthServerConfig {
29
+ /** API base URL */
30
+ baseUrl: string;
31
+ /** OAuth2 Client ID (also used as appKey) */
32
+ clientId: string;
33
+ /** OAuth2 Client Secret (also used as appSecret) */
34
+ clientSecret: string;
35
+ /** JWT public key (optional, for local verification) */
36
+ jwtPublicKey?: string;
37
+ /** @deprecated Use clientId instead */
38
+ appKey?: string;
39
+ /** @deprecated Use clientSecret instead */
40
+ appSecret?: string;
41
+ }
42
+ interface TokenPayload {
43
+ /** User ID or Client ID (for M2M) */
44
+ sub: string;
45
+ /** Issuer */
46
+ iss?: string;
47
+ /** Audience */
48
+ aud?: string | string[];
49
+ /** Issued at timestamp */
50
+ iat: number;
51
+ /** Expiration timestamp */
52
+ exp: number;
53
+ /** Scopes */
54
+ scope?: string;
55
+ /** Authorized party (client_id that requested this token) */
56
+ azp?: string;
57
+ /** Phone number (optional) */
58
+ phone?: string;
59
+ /** Email address (optional) */
60
+ email?: string;
61
+ }
62
+ interface UserInfo {
63
+ id: string;
64
+ phone?: string | null;
65
+ email?: string | null;
66
+ nickname?: string | null;
67
+ avatar_url?: string | null;
68
+ phone_verified?: boolean;
69
+ email_verified?: boolean;
70
+ created_at?: string;
71
+ updated_at?: string;
72
+ }
73
+ interface VerifyResult {
74
+ valid: boolean;
75
+ payload?: TokenPayload;
76
+ error?: string;
77
+ }
78
+ /**
79
+ * RFC 7662 Token Introspection Response
80
+ * 令牌内省响应
81
+ */
82
+ interface IntrospectionResult {
83
+ /** Whether the token is active */
84
+ active: boolean;
85
+ /** Scopes associated with this token */
86
+ scope?: string;
87
+ /** Client ID that requested the token */
88
+ client_id?: string;
89
+ /** Username or user identifier */
90
+ username?: string;
91
+ /** Token type (usually "Bearer") */
92
+ token_type?: string;
93
+ /** Expiration timestamp */
94
+ exp?: number;
95
+ /** Issued at timestamp */
96
+ iat?: number;
97
+ /** Not before timestamp */
98
+ nbf?: number;
99
+ /** Subject (user ID or client ID) */
100
+ sub?: string;
101
+ /** Audience */
102
+ aud?: string | string[];
103
+ /** Issuer */
104
+ iss?: string;
105
+ /** JWT ID */
106
+ jti?: string;
107
+ }
108
+ /**
109
+ * Error codes for UniAuth Server SDK
110
+ * UniAuth 服务端 SDK 错误码
111
+ */
112
+ declare const ServerErrorCode: {
113
+ readonly INVALID_TOKEN: "INVALID_TOKEN";
114
+ readonly TOKEN_EXPIRED: "TOKEN_EXPIRED";
115
+ readonly VERIFICATION_FAILED: "VERIFICATION_FAILED";
116
+ readonly USER_NOT_FOUND: "USER_NOT_FOUND";
117
+ readonly UNAUTHORIZED: "UNAUTHORIZED";
118
+ readonly NO_PUBLIC_KEY: "NO_PUBLIC_KEY";
119
+ readonly NETWORK_ERROR: "NETWORK_ERROR";
120
+ readonly INTERNAL_ERROR: "INTERNAL_ERROR";
121
+ };
122
+ type ServerErrorCodeType = typeof ServerErrorCode[keyof typeof ServerErrorCode];
123
+ /**
124
+ * Custom error class for server SDK
125
+ * 服务端 SDK 自定义错误类
126
+ */
127
+ declare class ServerAuthError extends Error {
128
+ code: ServerErrorCodeType | string;
129
+ statusCode: number;
130
+ constructor(code: ServerErrorCodeType | string, message: string, statusCode?: number);
131
+ }
132
+ interface ExpressRequest {
133
+ headers: Record<string, string | string[] | undefined>;
134
+ user?: UserInfo;
135
+ authPayload?: TokenPayload;
136
+ }
137
+ interface ExpressResponse {
138
+ status(code: number): ExpressResponse;
139
+ json(data: unknown): void;
140
+ }
141
+ type NextFunction = (error?: Error) => void;
142
+ interface HonoContext {
143
+ req: {
144
+ header(name: string): string | undefined;
145
+ };
146
+ set(key: string, value: unknown): void;
147
+ get(key: string): unknown;
148
+ json(data: unknown, status?: number): Response;
149
+ }
150
+ type HonoMiddlewareHandler = (c: HonoContext, next: () => Promise<void>) => Promise<Response | void>;
151
+ /**
152
+ * UniAuth Server SDK
153
+ * 统一认证后端 SDK
154
+ */
155
+ declare class UniAuthServer {
156
+ private config;
157
+ private tokenCache;
158
+ constructor(config: UniAuthServerConfig);
159
+ /**
160
+ * Verify access token
161
+ * 验证访问令牌
162
+ *
163
+ * @param token - JWT access token
164
+ * @returns Token payload if valid
165
+ * @throws ServerAuthError if token is invalid
166
+ */
167
+ verifyToken(token: string): Promise<TokenPayload>;
168
+ /**
169
+ * Verify token locally using JWT public key
170
+ * 使用 JWT 公钥本地验证令牌
171
+ */
172
+ private verifyTokenLocally;
173
+ /**
174
+ * Introspect a token (RFC 7662)
175
+ * 内省令牌(RFC 7662 标准)
176
+ *
177
+ * This is the standard way for resource servers to validate tokens.
178
+ *
179
+ * @param token - The token to introspect
180
+ * @param tokenTypeHint - Optional hint about the token type ('access_token' or 'refresh_token')
181
+ * @returns Introspection result
182
+ *
183
+ * @example
184
+ * ```typescript
185
+ * const result = await auth.introspectToken(accessToken);
186
+ * if (result.active) {
187
+ * console.log('Token is valid, user:', result.sub);
188
+ * }
189
+ * ```
190
+ */
191
+ introspectToken(token: string, tokenTypeHint?: 'access_token' | 'refresh_token'): Promise<IntrospectionResult>;
192
+ /**
193
+ * Check if a token is active
194
+ * 检查令牌是否有效
195
+ *
196
+ * @param token - The token to check
197
+ * @returns true if token is active
198
+ */
199
+ isTokenActive(token: string): Promise<boolean>;
200
+ /**
201
+ * Get user info by ID
202
+ * 根据 ID 获取用户信息
203
+ */
204
+ getUser(userId: string): Promise<UserInfo>;
205
+ /**
206
+ * Express/Connect middleware for authentication
207
+ * Express/Connect 认证中间件
208
+ *
209
+ * @example
210
+ * ```typescript
211
+ * import express from 'express';
212
+ *
213
+ * const app = express();
214
+ * app.use('/api/*', auth.middleware());
215
+ *
216
+ * app.get('/api/profile', (req, res) => {
217
+ * res.json({ user: req.user });
218
+ * });
219
+ * ```
220
+ */
221
+ middleware(): (req: ExpressRequest, res: ExpressResponse, next: NextFunction) => Promise<void>;
222
+ /**
223
+ * Hono middleware for authentication
224
+ * Hono 认证中间件
225
+ *
226
+ * @example
227
+ * ```typescript
228
+ * import { Hono } from 'hono';
229
+ *
230
+ * const app = new Hono();
231
+ * app.use('/api/*', auth.honoMiddleware());
232
+ *
233
+ * app.get('/api/profile', (c) => {
234
+ * const user = c.get('user');
235
+ * return c.json({ user });
236
+ * });
237
+ * ```
238
+ */
239
+ honoMiddleware(): HonoMiddlewareHandler;
240
+ /**
241
+ * Clear token cache
242
+ * 清除令牌缓存
243
+ */
244
+ clearCache(): void;
245
+ /**
246
+ * Get cache statistics
247
+ * 获取缓存统计
248
+ */
249
+ getCacheStats(): {
250
+ size: number;
251
+ entries: number;
252
+ };
253
+ }
254
+ /** @deprecated Use ServerAuthError instead */
255
+ interface AuthError extends Error {
256
+ code: string;
257
+ statusCode: number;
258
+ }
259
+
260
+ export { type AuthError, type IntrospectionResult, ServerAuthError, ServerErrorCode, type ServerErrorCodeType, type TokenPayload, UniAuthServer, type UniAuthServerConfig, type UserInfo, type VerifyResult, UniAuthServer as default };