@nya-account/node-sdk 2.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,307 @@
1
+ import { AccessTokenPayload, IdTokenPayload, getAuth$1 as getAuth } from "./express-yO7hxKKd.js";
2
+ import { NextFunction, Request, Response } from "express";
3
+
4
+ //#region src/core/types.d.ts
5
+ interface NyaAccountConfig {
6
+ /** SSO service URL (Issuer URL), can be the service or daemon address */
7
+ issuer: string;
8
+ /** OAuth client ID */
9
+ clientId: string;
10
+ /** OAuth client secret */
11
+ clientSecret: string;
12
+ /** HTTP request timeout in milliseconds (default: 10000) */
13
+ timeout?: number;
14
+ /** Discovery document cache TTL in milliseconds (default: 3600000 = 1 hour) */
15
+ discoveryCacheTtl?: number;
16
+ /** Explicitly specify endpoint URLs (optional, auto-discovered via OIDC Discovery if omitted) */
17
+ endpoints?: EndpointConfig;
18
+ }
19
+ interface EndpointConfig {
20
+ authorization?: string;
21
+ token?: string;
22
+ userinfo?: string;
23
+ revocation?: string;
24
+ introspection?: string;
25
+ jwks?: string;
26
+ endSession?: string;
27
+ }
28
+ interface TokenResponse {
29
+ accessToken: string;
30
+ tokenType: string;
31
+ expiresIn: number;
32
+ refreshToken: string;
33
+ scope: string;
34
+ idToken?: string;
35
+ }
36
+ interface UserInfo {
37
+ sub: string;
38
+ name?: string;
39
+ preferredUsername?: string;
40
+ email?: string;
41
+ emailVerified?: boolean;
42
+ updatedAt?: number;
43
+ }
44
+ interface IntrospectionResponse {
45
+ active: boolean;
46
+ scope?: string;
47
+ clientId?: string;
48
+ username?: string;
49
+ tokenType?: string;
50
+ exp?: number;
51
+ iat?: number;
52
+ sub?: string;
53
+ aud?: string;
54
+ iss?: string;
55
+ jti?: string;
56
+ }
57
+ interface DiscoveryDocument {
58
+ issuer: string;
59
+ authorizationEndpoint: string;
60
+ tokenEndpoint: string;
61
+ userinfoEndpoint?: string;
62
+ jwksUri: string;
63
+ revocationEndpoint?: string;
64
+ introspectionEndpoint?: string;
65
+ pushedAuthorizationRequestEndpoint?: string;
66
+ endSessionEndpoint?: string;
67
+ responseTypesSupported: string[];
68
+ grantTypesSupported: string[];
69
+ idTokenSigningAlgValuesSupported: string[];
70
+ scopesSupported: string[];
71
+ subjectTypesSupported: string[];
72
+ tokenEndpointAuthMethodsSupported: string[];
73
+ codeChallengeMethodsSupported?: string[];
74
+ claimsSupported?: string[];
75
+ }
76
+ interface CreateAuthorizationUrlOptions {
77
+ /** Redirect URI, must match the one registered with the OAuth client */
78
+ redirectUri: string;
79
+ /** Requested scopes, space-separated (default: 'openid') */
80
+ scope?: string;
81
+ /** CSRF protection parameter, auto-generated if not provided */
82
+ state?: string;
83
+ /** ID Token replay protection parameter */
84
+ nonce?: string;
85
+ }
86
+ interface AuthorizationUrlResult {
87
+ /** Full authorization URL to redirect the user to */
88
+ url: string;
89
+ /** PKCE code_verifier, must be stored in session for later token exchange */
90
+ codeVerifier: string;
91
+ /** State parameter, must be stored in session for CSRF validation */
92
+ state: string;
93
+ }
94
+ interface ExchangeCodeOptions {
95
+ /** Authorization code received in the callback */
96
+ code: string;
97
+ /** Redirect URI (must match the one used during authorization) */
98
+ redirectUri: string;
99
+ /** PKCE code_verifier saved during the authorization step */
100
+ codeVerifier: string;
101
+ }
102
+ interface AuthenticateOptions {
103
+ /** Token verification strategy: 'local' for JWT local verification (default), 'introspection' for remote introspection */
104
+ strategy?: 'local' | 'introspection';
105
+ }
106
+ interface PkcePair {
107
+ codeVerifier: string;
108
+ codeChallenge: string;
109
+ } //#endregion
110
+ //#region src/client.d.ts
111
+
112
+ /**
113
+ * Nya Account Node.js SDK client.
114
+ *
115
+ * Provides full OAuth 2.1 / OIDC flow support:
116
+ * - Authorization Code + PKCE
117
+ * - Token exchange / refresh / revocation / introspection
118
+ * - Local JWT verification (via JWKS)
119
+ * - OIDC UserInfo
120
+ * - OIDC Discovery auto-discovery
121
+ * - Express middleware (Bearer Token auth + scope validation)
122
+ *
123
+ * @example
124
+ * ```typescript
125
+ * const client = new NyaAccountClient({
126
+ * issuer: 'https://account.example.com',
127
+ * clientId: 'my-app',
128
+ * clientSecret: 'my-secret',
129
+ * })
130
+ *
131
+ * // Create authorization URL (with PKCE)
132
+ * const { url, codeVerifier, state } = await client.createAuthorizationUrl({
133
+ * redirectUri: 'https://myapp.com/callback',
134
+ * scope: 'openid profile email',
135
+ * })
136
+ *
137
+ * // Exchange code for tokens
138
+ * const tokens = await client.exchangeCode({
139
+ * code: callbackCode,
140
+ * redirectUri: 'https://myapp.com/callback',
141
+ * codeVerifier,
142
+ * })
143
+ *
144
+ * // Get user info
145
+ * const userInfo = await client.getUserInfo(tokens.accessToken)
146
+ * ```
147
+ */
148
+ declare class NyaAccountClient {
149
+ private httpClient;
150
+ private config;
151
+ private discoveryCache;
152
+ private discoveryCacheTimestamp;
153
+ private readonly discoveryCacheTtl;
154
+ private jwtVerifier;
155
+ constructor(config: NyaAccountConfig);
156
+ /**
157
+ * Fetch the OIDC Discovery document. Results are cached with a configurable TTL.
158
+ */
159
+ discover(): Promise<DiscoveryDocument>;
160
+ /**
161
+ * Clear the cached Discovery document and JWT verifier, forcing a re-fetch on next use.
162
+ */
163
+ clearCache(): void;
164
+ /**
165
+ * Create an OAuth authorization URL (automatically includes PKCE).
166
+ *
167
+ * The returned `codeVerifier` and `state` must be saved to the session
168
+ * for later use in token exchange and CSRF validation.
169
+ */
170
+ createAuthorizationUrl(options: CreateAuthorizationUrlOptions): Promise<AuthorizationUrlResult>;
171
+ /**
172
+ * Exchange an authorization code for tokens (Authorization Code Grant).
173
+ */
174
+ exchangeCode(options: ExchangeCodeOptions): Promise<TokenResponse>;
175
+ /**
176
+ * Refresh an Access Token using a Refresh Token.
177
+ */
178
+ refreshToken(refreshToken: string): Promise<TokenResponse>;
179
+ /**
180
+ * Revoke a token (RFC 7009).
181
+ *
182
+ * Supports revoking Access Tokens or Refresh Tokens.
183
+ * Revoking a Refresh Token also revokes its entire token family.
184
+ */
185
+ revokeToken(token: string): Promise<void>;
186
+ /**
187
+ * Token introspection (RFC 7662).
188
+ *
189
+ * Query the server for the current state of a token (active status, associated user info, etc.).
190
+ */
191
+ introspectToken(token: string): Promise<IntrospectionResponse>;
192
+ /**
193
+ * Get user info using an Access Token (OIDC UserInfo Endpoint).
194
+ *
195
+ * The returned fields depend on the scopes included in the token:
196
+ * - `profile`: name, preferredUsername, updatedAt
197
+ * - `email`: email, emailVerified
198
+ */
199
+ getUserInfo(accessToken: string): Promise<UserInfo>;
200
+ /**
201
+ * Locally verify a JWT Access Token (RFC 9068).
202
+ *
203
+ * Uses remote JWKS for signature verification, and validates issuer, audience, expiry, etc.
204
+ *
205
+ * @param token JWT Access Token string
206
+ * @param options.audience Custom audience validation value (defaults to clientId)
207
+ */
208
+ verifyAccessToken(token: string, options?: {
209
+ audience?: string;
210
+ }): Promise<AccessTokenPayload>;
211
+ /**
212
+ * Locally verify an OIDC ID Token.
213
+ *
214
+ * @param token JWT ID Token string
215
+ * @param options.audience Custom audience validation value (defaults to clientId)
216
+ * @param options.nonce Validate the nonce claim (required if nonce was sent during authorization)
217
+ */
218
+ verifyIdToken(token: string, options?: {
219
+ audience?: string;
220
+ nonce?: string;
221
+ }): Promise<IdTokenPayload>;
222
+ /**
223
+ * Express middleware: verify the Bearer Token in the request.
224
+ *
225
+ * After successful verification, use `getAuth(req)` to retrieve the token payload.
226
+ *
227
+ * @param options.strategy Verification strategy: 'local' (default, JWT local verification) or 'introspection' (remote introspection)
228
+ *
229
+ * @example
230
+ * ```typescript
231
+ * import { getAuth } from '@nya-account/node-sdk/express'
232
+ *
233
+ * app.use('/api', client.authenticate())
234
+ *
235
+ * app.get('/api/me', (req, res) => {
236
+ * const auth = getAuth(req)
237
+ * res.json({ userId: auth?.sub })
238
+ * })
239
+ * ```
240
+ */
241
+ authenticate(options?: AuthenticateOptions): (req: Request, res: Response, next: NextFunction) => void;
242
+ /**
243
+ * Express middleware: validate that the token in the request contains the specified scopes.
244
+ *
245
+ * Must be used after the `authenticate()` middleware.
246
+ *
247
+ * @example
248
+ * ```typescript
249
+ * app.get('/api/profile',
250
+ * client.authenticate(),
251
+ * client.requireScopes('profile'),
252
+ * (req, res) => { ... }
253
+ * )
254
+ * ```
255
+ */
256
+ requireScopes(...scopes: string[]): (req: Request, res: Response, next: NextFunction) => void;
257
+ private resolveEndpoint;
258
+ private getJwtVerifier;
259
+ private mapTokenResponse;
260
+ private handleTokenError;
261
+ } //#endregion
262
+ //#region src/core/errors.d.ts
263
+ /**
264
+ * Base error class for the SDK.
265
+ */
266
+ declare class NyaAccountError extends Error {
267
+ readonly code: string;
268
+ readonly description: string;
269
+ constructor(code: string, description: string);
270
+ }
271
+ /**
272
+ * OAuth protocol error (from server error / error_description response).
273
+ */
274
+ declare class OAuthError extends NyaAccountError {
275
+ constructor(error: string, errorDescription: string);
276
+ }
277
+ /**
278
+ * JWT verification error.
279
+ */
280
+ declare class TokenVerificationError extends NyaAccountError {
281
+ constructor(description: string);
282
+ }
283
+ /**
284
+ * OIDC Discovery error.
285
+ */
286
+ declare class DiscoveryError extends NyaAccountError {
287
+ constructor(description: string);
288
+ }
289
+
290
+ //#endregion
291
+ //#region src/utils/pkce.d.ts
292
+ /**
293
+ * Generate a PKCE code_verifier (43-128 character random string).
294
+ */
295
+ declare function generateCodeVerifier(): string;
296
+ /**
297
+ * Generate an S256 code_challenge from a code_verifier.
298
+ */
299
+ declare function generateCodeChallenge(codeVerifier: string): string;
300
+ /**
301
+ * Generate a PKCE code_verifier and code_challenge pair.
302
+ */
303
+ declare function generatePkce(): PkcePair;
304
+
305
+ //#endregion
306
+ export { AccessTokenPayload, AuthenticateOptions, AuthorizationUrlResult, CreateAuthorizationUrlOptions, DiscoveryDocument, DiscoveryError, EndpointConfig, ExchangeCodeOptions, IdTokenPayload, IntrospectionResponse, NyaAccountClient, NyaAccountConfig, NyaAccountError, OAuthError, PkcePair, TokenResponse, TokenVerificationError, UserInfo, generateCodeChallenge, generateCodeVerifier, generatePkce, getAuth };
307
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"index.d.ts","names":[],"sources":["../src/core/types.d.ts","../src/client.d.ts","../src/core/errors.d.ts","../src/utils/pkce.d.ts"],"sourcesContent":null,"mappings":";;;;AAEA,IAAW,mBAAmB,CAAC,IAAG,MAAA,cAAA;AAClC,IAAW,iBAAiB,CAAC,EAAG;AAChC,IAAW,gBAAO,CAAA,EAAA;AAClB,IAAW,WAAW,CAAC,EAAE;AACzB,IAAW,wBAAS,CAAA,EAAA;AACpB,IAAW,oBAAkB,CAAA,EAAA;AAC7B,IAAW,gCAAa,CAAA,EAAA;AACxB,IAAW,yBAAyB,CAAC,EAAG;AACxC,IAAW,sBAAS,CAAA,EAAA;AACpB,IAAW,sBAAsB,CAAC,EAAG;AACrC,IAAW,WAAW,CAAC,EAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AC2B1B,IAAW,mBAAmB;CAAC;CAAG,MAAI;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;CAAA,MAAA;AAAA;;;;;;;ACpCtC,IAAW,kBAAkB,CAAC,IAAI,MAAM,KAAM;;;;AAI9C,IAAA,aAAA,CAAA,IAAA,MAAA,eAAA;;;;AAIA,IAAW,yBAAyB,CAAC,IAAI,MAAM,eAAS;;;;AAIxD,IAAW,iBAAc,CAAA,IAAA,MAAA,eAAA;;;;;;;ACXzB,IAAW,uBAAuB,CAAC,EAAG;;;;AAItC,IAAW,wBAAwB,CAAC,EAAG;;;;AAIvC,IAAW,eAAe,CAAC,IAAI,MAAM,QAAS"}