@npmatomicauthy/node 0.0.0-stage → 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.
package/README.md CHANGED
@@ -1,3 +1,254 @@
1
- # Temporary Holding Version
1
+ # Authly Node.js SDK
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ The official Authly SDK for Node.js server applications. It provides OAuth 2.0 / OpenID Connect login helpers, PKCE generation, RS256 JWT verification using Authly JWKS, user management API access, and webhook signature verification. It has no runtime dependencies and uses Node.js built-in APIs.
4
+
5
+ > **License notice:** This package is marked `UNLICENSED`. No open-source license is granted. Use and redistribution require authorization from the package owner.
6
+
7
+ ## Requirements
8
+
9
+ - Node.js 22 or newer.
10
+ - An Authly issuer URL and a registered OAuth client for login and token verification.
11
+ - A server-side confidential client secret only when the OAuth client is registered as confidential.
12
+
13
+ ## Install
14
+
15
+ ```sh
16
+ npm install @authly/node
17
+ ```
18
+
19
+ ## Configure the OAuth client
20
+
21
+ Keep OAuth client secrets, session secrets, management API keys, and tokens on the server. For example, load these values from a secrets manager or a server-only `.env` file:
22
+
23
+ ```dotenv
24
+ AUTHLY_ISSUER=https://auth.example.com
25
+ AUTHLY_CLIENT_ID=your-client-id
26
+ AUTHLY_CLIENT_SECRET=your-confidential-client-secret
27
+ AUTHLY_CALLBACK_URL=https://app.example.com/auth/callback
28
+ AUTHLY_LOGOUT_REDIRECT_URL=https://app.example.com/
29
+ AUTHLY_AUDIENCE=https://api.example.com
30
+ AUTHLY_SCOPES=openid profile email offline_access
31
+ SESSION_SECRET=use-a-long-random-secret
32
+ ```
33
+
34
+ Initialize the OAuth client in server-only code:
35
+
36
+ ```js
37
+ import { AuthlyOAuthClient, AuthlyTokenVerifier } from '@authly/node';
38
+
39
+ const issuer = process.env.AUTHLY_ISSUER;
40
+ const clientId = process.env.AUTHLY_CLIENT_ID;
41
+ const callbackUrl = process.env.AUTHLY_CALLBACK_URL;
42
+
43
+ if (!issuer || !clientId || !callbackUrl) {
44
+ throw new Error('AUTHLY_ISSUER, AUTHLY_CLIENT_ID, and AUTHLY_CALLBACK_URL are required');
45
+ }
46
+
47
+ export const authlyOAuth = new AuthlyOAuthClient({
48
+ issuer,
49
+ clientId,
50
+ clientSecret: process.env.AUTHLY_CLIENT_SECRET,
51
+ redirectUri: callbackUrl,
52
+ postLogoutRedirectUri: process.env.AUTHLY_LOGOUT_REDIRECT_URL,
53
+ scopes: (process.env.AUTHLY_SCOPES ?? 'openid profile email offline_access').split(/\s+/),
54
+ audience: process.env.AUTHLY_AUDIENCE,
55
+ });
56
+
57
+ export const authlyTokenVerifier = new AuthlyTokenVerifier({
58
+ issuer,
59
+ audience: process.env.AUTHLY_AUDIENCE || clientId,
60
+ });
61
+ ```
62
+
63
+ For a public client, omit `clientSecret`. Never put a confidential client secret or a management API key in browser code or a `NEXT_PUBLIC_*` variable.
64
+
65
+ ## OAuth 2.0 / OpenID Connect login
66
+
67
+ The SDK provides the protocol operations; your application must maintain an authenticated server-side session. The following Express example uses `express-session` to keep the PKCE verifier, state, and nonce server-side. Configure a production-grade session store (the default in-memory store is not suitable for production).
68
+
69
+ Install `express` and `express-session` separately if you use this example; they are application dependencies, not SDK dependencies.
70
+
71
+ ```js
72
+ import express from 'express';
73
+ import session from 'express-session';
74
+ import { AuthlyOAuthClient } from '@authly/node';
75
+ import { authlyOAuth, authlyTokenVerifier } from './authly.js';
76
+
77
+ const app = express();
78
+
79
+ app.use(session({
80
+ secret: process.env.SESSION_SECRET,
81
+ resave: false,
82
+ saveUninitialized: false,
83
+ cookie: {
84
+ httpOnly: true,
85
+ sameSite: 'lax',
86
+ secure: process.env.NODE_ENV === 'production',
87
+ },
88
+ }));
89
+
90
+ app.get('/auth/login', (req, res) => {
91
+ const pkce = AuthlyOAuthClient.generatePkce();
92
+ req.session.authlyTransaction = {
93
+ verifier: pkce.verifier,
94
+ state: pkce.state,
95
+ nonce: pkce.nonce,
96
+ };
97
+ res.redirect(authlyOAuth.buildAuthorizeUrl({
98
+ codeChallenge: pkce.challenge,
99
+ state: pkce.state,
100
+ nonce: pkce.nonce,
101
+ }));
102
+ });
103
+
104
+ app.get('/auth/callback', async (req, res, next) => {
105
+ const code = typeof req.query.code === 'string' ? req.query.code : '';
106
+ const state = typeof req.query.state === 'string' ? req.query.state : '';
107
+ const transaction = req.session.authlyTransaction;
108
+
109
+ if (!code || !transaction || state !== transaction.state) {
110
+ return res.status(400).send('Invalid OAuth state or callback');
111
+ }
112
+ delete req.session.authlyTransaction;
113
+
114
+ try {
115
+ const tokens = await authlyOAuth.exchangeCode({
116
+ code,
117
+ codeVerifier: transaction.verifier,
118
+ });
119
+
120
+ if (!tokens.id_token) {
121
+ return res.status(400).send('Authly did not return an ID token');
122
+ }
123
+
124
+ const claims = await authlyTokenVerifier.verifyToken(tokens.id_token, {
125
+ audience: process.env.AUTHLY_CLIENT_ID,
126
+ });
127
+ if (claims.nonce !== transaction.nonce) {
128
+ return res.status(400).send('Invalid ID token nonce');
129
+ }
130
+
131
+ const user = await authlyOAuth.getUserInfo(tokens.access_token);
132
+ req.session.authlyUser = { sub: user.sub, email: user.email };
133
+ req.session.authlyTokens = {
134
+ accessToken: tokens.access_token,
135
+ refreshToken: tokens.refresh_token,
136
+ idToken: tokens.id_token,
137
+ };
138
+ res.redirect('/account');
139
+ } catch (error) {
140
+ next(error);
141
+ }
142
+ });
143
+ ```
144
+
145
+ The callback must compare the returned `state`, use the same PKCE verifier generated before redirecting, verify the ID token and its nonce, and create your application's own session. The session property declarations above are application-specific; add matching `express-session` TypeScript declaration merging if using TypeScript.
146
+
147
+ ## Protecting API routes
148
+
149
+ `AuthlyTokenVerifier` retrieves and caches JWKS from `<issuer>/oauth/jwks` by default, pins verification to RS256, and validates the signature, issuer, audience, expiry, and not-before time. You can override the JWKS endpoint with `jwksUri`, or supply `staticJwks` for offline use.
150
+
151
+ ```js
152
+ app.get('/api/profile', authlyTokenVerifier.middleware(), (req, res) => {
153
+ res.json({ sub: req.authlyUser.sub, email: req.authlyUser.email });
154
+ });
155
+ ```
156
+
157
+ The middleware returns a 401 JSON response for missing or invalid bearer tokens. For direct verification outside Express/Connect middleware:
158
+
159
+ ```js
160
+ const claims = await authlyTokenVerifier.verifyToken(accessToken);
161
+ ```
162
+
163
+ Only use claims after successful verification. Never trust a user ID supplied by the request body or an unverified token.
164
+
165
+ ## User information, refresh, revocation, and logout
166
+
167
+ ```js
168
+ const user = await authlyOAuth.getUserInfo(accessToken);
169
+
170
+ if (refreshToken) {
171
+ const refreshed = await authlyOAuth.refreshToken(refreshToken);
172
+ // Persist the replacement tokens securely; refresh tokens may rotate.
173
+ }
174
+
175
+ await authlyOAuth.revokeToken(accessToken);
176
+ const logoutUrl = authlyOAuth.buildLogoutUrl({ idTokenHint });
177
+ ```
178
+
179
+ Redirect the browser to the returned logout URL to end the Authly session. Clear your application's session as part of logout. The OAuth client also accepts a `postLogoutRedirectUri` at initialization or as an option to `buildLogoutUrl`.
180
+
181
+ ## Management API
182
+
183
+ `AuthlyManagementClient` uses a project-scoped `authly_sk_...` key and must only be instantiated on a trusted server:
184
+
185
+ ```js
186
+ import { AuthlyManagementClient } from '@authly/node';
187
+
188
+ const management = new AuthlyManagementClient({
189
+ baseUrl: process.env.AUTHLY_ISSUER,
190
+ managementApiKey: process.env.AUTHLY_MANAGEMENT_API_KEY,
191
+ });
192
+
193
+ const users = await management.listUsers({ limit: 25, page: 1 });
194
+ ```
195
+
196
+ Available operations include listing, retrieving, updating, suspending, reactivating, and deleting users, revoking user sessions, resending verification, and triggering password resets.
197
+
198
+ ## Webhook signatures
199
+
200
+ Verify the raw request payload with its Authly timestamp and signature headers before processing a webhook:
201
+
202
+ ```js
203
+ import { verifyAuthlyWebhookSignature } from '@authly/node';
204
+
205
+ const timestamp = request.headers['x-authly-timestamp'];
206
+ const signature = request.headers['x-authly-signature'];
207
+ if (typeof timestamp !== 'string' || typeof signature !== 'string') {
208
+ throw new Error('Missing Authly webhook signature headers');
209
+ }
210
+
211
+ const valid = verifyAuthlyWebhookSignature({
212
+ payload: rawRequestBody,
213
+ timestamp,
214
+ signature,
215
+ secret: process.env.AUTHLY_WEBHOOK_SECRET,
216
+ });
217
+
218
+ if (!valid) {
219
+ throw new Error('Invalid or expired Authly webhook signature');
220
+ }
221
+ ```
222
+
223
+ Pass the exact payload bytes/string used to calculate the signature. The verifier rejects timestamps outside its default five-minute tolerance; set `toleranceSeconds` only when your delivery requirements justify it.
224
+
225
+ ## Errors
226
+
227
+ OAuth HTTP failures from `exchangeCode`, `refreshToken`, `getUserInfo`, and `revokeToken` throw `AuthlyManagementError`, which includes `status` and `code`. Token parsing, signature, issuer, audience, and JWKS failures throw `AuthlyTokenError`, which includes a typed `code`. Catch these errors at your application boundary, log safe diagnostic details, and never log secrets or tokens.
228
+
229
+ ```js
230
+ import { AuthlyManagementError, AuthlyTokenError } from '@authly/node';
231
+
232
+ try {
233
+ const claims = await authlyTokenVerifier.verifyToken(token);
234
+ } catch (error) {
235
+ if (error instanceof AuthlyTokenError) {
236
+ // Reject the request; use error.code for safe diagnostics.
237
+ } else if (error instanceof AuthlyManagementError) {
238
+ // Handle an Authly HTTP error using status and code.
239
+ } else {
240
+ throw error;
241
+ }
242
+ }
243
+ ```
244
+
245
+ ## Security recommendations
246
+
247
+ - Keep client secrets, management keys, webhook secrets, session secrets, and tokens in server-side secret storage.
248
+ - Use HTTPS for the issuer and application in production.
249
+ - Use secure, HttpOnly, SameSite cookies and a production session store; rotate/regenerate the app session after login.
250
+ - Bind each login transaction to its own session state, PKCE verifier, and nonce; enforce single use and short lifetimes.
251
+ - Validate the audience appropriate to the token you verify. Do not treat an ID token as an API access token.
252
+ - Do not log, expose, or persist bearer/refresh tokens in browser-accessible storage.
253
+
254
+ Authly's SDK source and integration guidance are maintained in the Authly monorepo under `packages/node-sdk` and `docs/INTEGRATION_GUIDE.md`.
@@ -0,0 +1,223 @@
1
+ import { type JsonWebKey } from 'node:crypto';
2
+ export interface AuthlyNodeConfig {
3
+ /** Authly server base URL (e.g. https://auth.example.com) */
4
+ baseUrl: string;
5
+ /** Project-scoped Management API key (authly_sk_...). Server-side ONLY. */
6
+ managementApiKey: string;
7
+ /** Optional request timeout in ms (default 10000) */
8
+ timeoutMs?: number;
9
+ }
10
+ export interface ManagedUser {
11
+ id: string;
12
+ projectId: string;
13
+ email: string;
14
+ username: string | null;
15
+ displayName: string;
16
+ phone: string | null;
17
+ status: string;
18
+ emailVerified: boolean;
19
+ lastLoginAt: string | null;
20
+ createdAt: string;
21
+ }
22
+ export interface PaginatedUsers {
23
+ items: ManagedUser[];
24
+ total: number;
25
+ limit: number;
26
+ page: number;
27
+ hasMore: boolean;
28
+ nextCursor: string | null;
29
+ }
30
+ export interface VerifiedAuthlyClaims {
31
+ sub: string;
32
+ iss: string;
33
+ aud: string | string[];
34
+ exp: number;
35
+ iat: number;
36
+ nbf?: number;
37
+ email?: string;
38
+ email_verified?: boolean;
39
+ name?: string;
40
+ roles?: string[];
41
+ scope?: string;
42
+ client_id?: string;
43
+ project_id?: string;
44
+ [key: string]: unknown;
45
+ }
46
+ export interface AuthlyUserIdentity {
47
+ sub: string;
48
+ email?: string;
49
+ email_verified?: boolean;
50
+ name?: string;
51
+ roles?: string[];
52
+ project_id?: string;
53
+ }
54
+ export interface AuthlyOAuthTokenResponse {
55
+ access_token: string;
56
+ token_type: string;
57
+ expires_in: number;
58
+ id_token?: string;
59
+ refresh_token?: string;
60
+ scope?: string;
61
+ }
62
+ export declare class AuthlyManagementError extends Error {
63
+ readonly status: number;
64
+ readonly code: string;
65
+ constructor(status: number, code: string, message: string);
66
+ }
67
+ export declare class AuthlyTokenError extends Error {
68
+ readonly code: 'missing_token' | 'malformed_token' | 'unsupported_alg' | 'unknown_kid' | 'invalid_signature' | 'token_expired' | 'token_not_active' | 'invalid_issuer' | 'invalid_audience' | 'jwks_fetch_failed';
69
+ constructor(code: 'missing_token' | 'malformed_token' | 'unsupported_alg' | 'unknown_kid' | 'invalid_signature' | 'token_expired' | 'token_not_active' | 'invalid_issuer' | 'invalid_audience' | 'jwks_fetch_failed', message: string);
70
+ }
71
+ export interface AuthlyTokenVerifierConfig {
72
+ /** Expected OIDC issuer (e.g. https://auth.example.com) */
73
+ issuer: string;
74
+ /** Expected audience (API resource identifier or client_id for ID tokens) */
75
+ audience: string;
76
+ /** Optional explicit JWKS URL (defaults to <issuer>/oauth/jwks) */
77
+ jwksUri?: string;
78
+ /** Optional static JWKS for tests or offline verification */
79
+ staticJwks?: {
80
+ keys: Array<JsonWebKey & {
81
+ kid?: string;
82
+ alg?: string;
83
+ use?: string;
84
+ }>;
85
+ };
86
+ /** Clock skew tolerance in seconds (default 30) */
87
+ clockToleranceSeconds?: number;
88
+ /** JWKS cache TTL in ms (default 300000 = 5 minutes) */
89
+ jwksCacheTtlMs?: number;
90
+ }
91
+ /**
92
+ * Zero-dependency RS256 JWKS JWT verifier for Node.js resource servers and backends.
93
+ * Verifies cryptographic signature, issuer, audience, expiration, and not-before claims.
94
+ * Never trusts an unverified user ID from request bodies or headers.
95
+ */
96
+ export declare class AuthlyTokenVerifier {
97
+ private readonly config;
98
+ private readonly issuer;
99
+ private readonly audience;
100
+ private readonly jwksUri;
101
+ private readonly clockTolerance;
102
+ private readonly cacheTtlMs;
103
+ private keyCache;
104
+ private allKeys;
105
+ private cacheExpiresAt;
106
+ constructor(config: AuthlyTokenVerifierConfig);
107
+ private loadKeys;
108
+ private ensureKeys;
109
+ verifyToken(token: string, opts?: {
110
+ nowSeconds?: number;
111
+ audience?: string;
112
+ }): Promise<VerifiedAuthlyClaims>;
113
+ /**
114
+ * Express / Connect middleware that verifies `Authorization: Bearer <token>` against Authly JWKS
115
+ * and attaches verified claims to `req.authlyUser` (never trusting client-submitted user IDs).
116
+ */
117
+ middleware(): (req: {
118
+ headers?: Record<string, string | string[] | undefined>;
119
+ authlyUser?: VerifiedAuthlyClaims;
120
+ }, res: {
121
+ status: (code: number) => {
122
+ json: (body: unknown) => void;
123
+ };
124
+ }, next: (err?: unknown) => void) => Promise<void>;
125
+ }
126
+ export interface AuthlyOAuthClientConfig {
127
+ issuer: string;
128
+ clientId: string;
129
+ /** Server-side confidential secret (never expose to browsers or mobile apps). */
130
+ clientSecret?: string;
131
+ redirectUri: string;
132
+ postLogoutRedirectUri?: string;
133
+ scopes?: string[];
134
+ audience?: string;
135
+ }
136
+ /**
137
+ * Server-side OAuth 2.0 / OIDC client for confidential Node.js and Next.js applications.
138
+ * Supports Authorization Code + PKCE S256, token exchange, refresh rotation, UserInfo, revocation, and logout.
139
+ */
140
+ export declare class AuthlyOAuthClient {
141
+ private readonly config;
142
+ private readonly issuer;
143
+ constructor(config: AuthlyOAuthClientConfig);
144
+ static generatePkce(): {
145
+ verifier: string;
146
+ challenge: string;
147
+ state: string;
148
+ nonce: string;
149
+ };
150
+ buildAuthorizeUrl(params: {
151
+ codeChallenge: string;
152
+ state: string;
153
+ nonce?: string;
154
+ extra?: Record<string, string>;
155
+ }): string;
156
+ private authHeaders;
157
+ exchangeCode(input: {
158
+ code: string;
159
+ codeVerifier: string;
160
+ }): Promise<AuthlyOAuthTokenResponse>;
161
+ refreshToken(refreshToken: string): Promise<AuthlyOAuthTokenResponse>;
162
+ getUserInfo(accessToken: string): Promise<AuthlyUserIdentity>;
163
+ revokeToken(token: string): Promise<void>;
164
+ buildLogoutUrl(opts?: {
165
+ idTokenHint?: string;
166
+ postLogoutRedirectUri?: string;
167
+ }): string;
168
+ }
169
+ export declare class AuthlyManagementClient {
170
+ private readonly baseUrl;
171
+ private readonly apiKey;
172
+ private readonly timeoutMs;
173
+ constructor(config: AuthlyNodeConfig);
174
+ private req;
175
+ listUsers(params?: {
176
+ search?: string;
177
+ status?: string;
178
+ verified?: 'true' | 'false';
179
+ limit?: number;
180
+ page?: number;
181
+ cursor?: string;
182
+ }): Promise<PaginatedUsers>;
183
+ getUser(id: string): Promise<{
184
+ user: ManagedUser;
185
+ sessions: unknown[];
186
+ authEvents: unknown[];
187
+ adminHistory: unknown[];
188
+ }>;
189
+ updateUser(id: string, patch: {
190
+ displayName?: string;
191
+ phone?: string | null;
192
+ profileData?: Record<string, unknown>;
193
+ }): Promise<{
194
+ user: ManagedUser;
195
+ }>;
196
+ suspendUser(id: string): Promise<{
197
+ user: ManagedUser;
198
+ }>;
199
+ reactivateUser(id: string): Promise<{
200
+ user: ManagedUser;
201
+ }>;
202
+ revokeUserSessions(id: string): Promise<{
203
+ ok: true;
204
+ revokedCount: number;
205
+ }>;
206
+ resendVerification(id: string): Promise<{
207
+ ok: true;
208
+ }>;
209
+ triggerPasswordReset(id: string): Promise<{
210
+ ok: true;
211
+ }>;
212
+ deleteUser(id: string, hard?: boolean): Promise<{
213
+ ok: true;
214
+ }>;
215
+ }
216
+ /** Verifies an Authly HMAC-SHA256 webhook signature (`X-Authly-Signature` + `X-Authly-Timestamp`). */
217
+ export declare function verifyAuthlyWebhookSignature(opts: {
218
+ payload: string | Buffer;
219
+ timestamp: string;
220
+ signature: string;
221
+ secret: string;
222
+ toleranceSeconds?: number;
223
+ }): boolean;
package/dist/index.js ADDED
@@ -0,0 +1,343 @@
1
+ import { createHash, createHmac, createPublicKey, randomBytes, timingSafeEqual, verify as cryptoVerify } from 'node:crypto';
2
+ export class AuthlyManagementError extends Error {
3
+ status;
4
+ code;
5
+ constructor(status, code, message) {
6
+ super(message);
7
+ this.status = status;
8
+ this.code = code;
9
+ this.name = 'AuthlyManagementError';
10
+ }
11
+ }
12
+ export class AuthlyTokenError extends Error {
13
+ code;
14
+ constructor(code, message) {
15
+ super(message);
16
+ this.code = code;
17
+ this.name = 'AuthlyTokenError';
18
+ }
19
+ }
20
+ function decodeBase64UrlJson(segment) {
21
+ const json = Buffer.from(segment, 'base64url').toString('utf8');
22
+ return JSON.parse(json);
23
+ }
24
+ /**
25
+ * Zero-dependency RS256 JWKS JWT verifier for Node.js resource servers and backends.
26
+ * Verifies cryptographic signature, issuer, audience, expiration, and not-before claims.
27
+ * Never trusts an unverified user ID from request bodies or headers.
28
+ */
29
+ export class AuthlyTokenVerifier {
30
+ config;
31
+ issuer;
32
+ audience;
33
+ jwksUri;
34
+ clockTolerance;
35
+ cacheTtlMs;
36
+ keyCache = new Map();
37
+ allKeys = [];
38
+ cacheExpiresAt = 0;
39
+ constructor(config) {
40
+ this.config = config;
41
+ this.issuer = config.issuer.replace(/\/+$/, '');
42
+ this.audience = config.audience;
43
+ this.jwksUri = config.jwksUri ?? `${this.issuer}/oauth/jwks`;
44
+ this.clockTolerance = config.clockToleranceSeconds ?? 30;
45
+ this.cacheTtlMs = config.jwksCacheTtlMs ?? 300_000;
46
+ if (config.staticJwks) {
47
+ this.loadKeys(config.staticJwks.keys);
48
+ this.cacheExpiresAt = Number.POSITIVE_INFINITY;
49
+ }
50
+ }
51
+ loadKeys(keys) {
52
+ const map = new Map();
53
+ const list = [];
54
+ for (const jwk of keys) {
55
+ const keyObj = createPublicKey({ key: jwk, format: 'jwk' });
56
+ list.push(keyObj);
57
+ if (jwk.kid)
58
+ map.set(jwk.kid, keyObj);
59
+ }
60
+ this.keyCache = map;
61
+ this.allKeys = list;
62
+ }
63
+ async ensureKeys(kid, forceRefresh = false) {
64
+ if (!this.config.staticJwks && (forceRefresh || Date.now() >= this.cacheExpiresAt || (kid && !this.keyCache.has(kid)))) {
65
+ const res = await fetch(this.jwksUri, { headers: { Accept: 'application/json' } }).catch(() => null);
66
+ if (!res || !res.ok)
67
+ throw new AuthlyTokenError('jwks_fetch_failed', 'Failed to fetch JWKS from Authly.');
68
+ const body = (await res.json());
69
+ if (!Array.isArray(body.keys) || body.keys.length === 0) {
70
+ throw new AuthlyTokenError('jwks_fetch_failed', 'JWKS response contained no keys.');
71
+ }
72
+ this.loadKeys(body.keys);
73
+ this.cacheExpiresAt = Date.now() + this.cacheTtlMs;
74
+ }
75
+ if (kid) {
76
+ const exact = this.keyCache.get(kid);
77
+ if (!exact)
78
+ throw new AuthlyTokenError('unknown_kid', 'Signing key ID not found in JWKS.');
79
+ return [exact];
80
+ }
81
+ return this.allKeys;
82
+ }
83
+ async verifyToken(token, opts = {}) {
84
+ const parts = token.trim().split('.');
85
+ if (parts.length !== 3 || !parts[0] || !parts[1] || !parts[2]) {
86
+ throw new AuthlyTokenError('malformed_token', 'Token is not a valid compact JWT.');
87
+ }
88
+ let header;
89
+ let payload;
90
+ try {
91
+ header = decodeBase64UrlJson(parts[0]);
92
+ payload = decodeBase64UrlJson(parts[1]);
93
+ }
94
+ catch {
95
+ throw new AuthlyTokenError('malformed_token', 'Token header or payload is not valid JSON.');
96
+ }
97
+ // Pin RS256 to prevent algorithm-confusion attacks (alg=none or HS256).
98
+ if (header.alg !== 'RS256') {
99
+ throw new AuthlyTokenError('unsupported_alg', `Unsupported JWT algorithm: ${String(header.alg)}`);
100
+ }
101
+ const keys = await this.ensureKeys(header.kid);
102
+ const signingInput = Buffer.from(`${parts[0]}.${parts[1]}`, 'utf8');
103
+ const signature = Buffer.from(parts[2], 'base64url');
104
+ const validSig = keys.some((key) => cryptoVerify('RSA-SHA256', signingInput, key, signature));
105
+ if (!validSig) {
106
+ throw new AuthlyTokenError('invalid_signature', 'JWT signature verification failed.');
107
+ }
108
+ const now = opts.nowSeconds ?? Math.floor(Date.now() / 1000);
109
+ if (typeof payload.exp !== 'number' || now >= payload.exp + this.clockTolerance) {
110
+ throw new AuthlyTokenError('token_expired', 'JWT has expired.');
111
+ }
112
+ if (typeof payload.nbf === 'number' && now + this.clockTolerance < payload.nbf) {
113
+ throw new AuthlyTokenError('token_not_active', 'JWT is not yet valid.');
114
+ }
115
+ const tokenIssuer = typeof payload.iss === 'string' ? payload.iss.replace(/\/+$/, '') : '';
116
+ if (tokenIssuer !== this.issuer) {
117
+ throw new AuthlyTokenError('invalid_issuer', 'JWT issuer does not match expected Authly issuer.');
118
+ }
119
+ const expectedAud = opts.audience ?? this.audience;
120
+ const audList = Array.isArray(payload.aud) ? payload.aud : typeof payload.aud === 'string' ? [payload.aud] : [];
121
+ if (!audList.includes(expectedAud)) {
122
+ throw new AuthlyTokenError('invalid_audience', 'JWT audience does not match this application.');
123
+ }
124
+ if (typeof payload.sub !== 'string' || !payload.sub) {
125
+ throw new AuthlyTokenError('malformed_token', 'JWT subject claim (sub) is missing.');
126
+ }
127
+ return payload;
128
+ }
129
+ /**
130
+ * Express / Connect middleware that verifies `Authorization: Bearer <token>` against Authly JWKS
131
+ * and attaches verified claims to `req.authlyUser` (never trusting client-submitted user IDs).
132
+ */
133
+ middleware() {
134
+ return async (req, res, next) => {
135
+ const authHeader = req.headers?.authorization;
136
+ const raw = typeof authHeader === 'string' ? authHeader : '';
137
+ if (!raw.startsWith('Bearer ')) {
138
+ return res.status(401).json({ error: { code: 'missing_token', message: 'Authorization Bearer token is required.' } });
139
+ }
140
+ try {
141
+ req.authlyUser = await this.verifyToken(raw.slice(7).trim());
142
+ next();
143
+ }
144
+ catch (err) {
145
+ const te = err instanceof AuthlyTokenError ? err : new AuthlyTokenError('invalid_signature', 'Invalid access token.');
146
+ res.status(401).json({ error: { code: te.code, message: te.message } });
147
+ }
148
+ };
149
+ }
150
+ }
151
+ /**
152
+ * Server-side OAuth 2.0 / OIDC client for confidential Node.js and Next.js applications.
153
+ * Supports Authorization Code + PKCE S256, token exchange, refresh rotation, UserInfo, revocation, and logout.
154
+ */
155
+ export class AuthlyOAuthClient {
156
+ config;
157
+ issuer;
158
+ constructor(config) {
159
+ this.config = config;
160
+ this.issuer = config.issuer.replace(/\/+$/, '');
161
+ }
162
+ static generatePkce() {
163
+ const verifier = randomBytes(32).toString('base64url');
164
+ const challenge = createHash('sha256').update(verifier).digest('base64url');
165
+ const state = randomBytes(16).toString('base64url');
166
+ const nonce = randomBytes(16).toString('base64url');
167
+ return { verifier, challenge, state, nonce };
168
+ }
169
+ buildAuthorizeUrl(params) {
170
+ const url = new URL(`${this.issuer}/oauth/authorize`);
171
+ url.searchParams.set('client_id', this.config.clientId);
172
+ url.searchParams.set('redirect_uri', this.config.redirectUri);
173
+ url.searchParams.set('response_type', 'code');
174
+ url.searchParams.set('scope', (this.config.scopes ?? ['openid', 'profile', 'email', 'offline_access']).join(' '));
175
+ url.searchParams.set('code_challenge', params.codeChallenge);
176
+ url.searchParams.set('code_challenge_method', 'S256');
177
+ url.searchParams.set('state', params.state);
178
+ if (params.nonce)
179
+ url.searchParams.set('nonce', params.nonce);
180
+ if (this.config.audience)
181
+ url.searchParams.set('resource', this.config.audience);
182
+ for (const [k, v] of Object.entries(params.extra ?? {}))
183
+ url.searchParams.set(k, v);
184
+ return url.toString();
185
+ }
186
+ authHeaders(body) {
187
+ const headers = { 'Content-Type': 'application/x-www-form-urlencoded' };
188
+ if (this.config.clientSecret) {
189
+ headers.Authorization = `Basic ${Buffer.from(`${encodeURIComponent(this.config.clientId)}:${encodeURIComponent(this.config.clientSecret)}`).toString('base64')}`;
190
+ }
191
+ else {
192
+ body.set('client_id', this.config.clientId);
193
+ }
194
+ return headers;
195
+ }
196
+ async exchangeCode(input) {
197
+ const body = new URLSearchParams({
198
+ grant_type: 'authorization_code',
199
+ code: input.code,
200
+ redirect_uri: this.config.redirectUri,
201
+ code_verifier: input.codeVerifier,
202
+ });
203
+ const res = await fetch(`${this.issuer}/oauth/token`, {
204
+ method: 'POST',
205
+ headers: this.authHeaders(body),
206
+ body: body.toString(),
207
+ });
208
+ const json = (await res.json().catch(() => ({})));
209
+ if (!res.ok) {
210
+ throw new AuthlyManagementError(res.status, String(json.error ?? 'token_error'), String(json.error_description ?? 'Authorization code exchange failed.'));
211
+ }
212
+ return json;
213
+ }
214
+ async refreshToken(refreshToken) {
215
+ const body = new URLSearchParams({
216
+ grant_type: 'refresh_token',
217
+ refresh_token: refreshToken,
218
+ });
219
+ const res = await fetch(`${this.issuer}/oauth/token`, {
220
+ method: 'POST',
221
+ headers: this.authHeaders(body),
222
+ body: body.toString(),
223
+ });
224
+ const json = (await res.json().catch(() => ({})));
225
+ if (!res.ok) {
226
+ throw new AuthlyManagementError(res.status, String(json.error ?? 'refresh_error'), String(json.error_description ?? 'Token refresh failed.'));
227
+ }
228
+ return json;
229
+ }
230
+ async getUserInfo(accessToken) {
231
+ const res = await fetch(`${this.issuer}/oauth/userinfo`, {
232
+ headers: { Authorization: `Bearer ${accessToken}`, Accept: 'application/json' },
233
+ });
234
+ const json = (await res.json().catch(() => ({})));
235
+ if (!res.ok) {
236
+ throw new AuthlyManagementError(res.status, String(json.error ?? 'userinfo_error'), String(json.error_description ?? 'Failed to fetch user info.'));
237
+ }
238
+ return json;
239
+ }
240
+ async revokeToken(token) {
241
+ const body = new URLSearchParams({ token });
242
+ const res = await fetch(`${this.issuer}/oauth/revoke`, {
243
+ method: 'POST',
244
+ headers: this.authHeaders(body),
245
+ body: body.toString(),
246
+ });
247
+ if (!res.ok) {
248
+ throw new AuthlyManagementError(res.status, 'revocation_failed', 'Token revocation failed.');
249
+ }
250
+ }
251
+ buildLogoutUrl(opts = {}) {
252
+ const url = new URL(`${this.issuer}/oauth/logout`);
253
+ if (opts.idTokenHint)
254
+ url.searchParams.set('id_token_hint', opts.idTokenHint);
255
+ const redirect = opts.postLogoutRedirectUri ?? this.config.postLogoutRedirectUri;
256
+ if (redirect)
257
+ url.searchParams.set('post_logout_redirect_uri', redirect);
258
+ return url.toString();
259
+ }
260
+ }
261
+ export class AuthlyManagementClient {
262
+ baseUrl;
263
+ apiKey;
264
+ timeoutMs;
265
+ constructor(config) {
266
+ if (!config.managementApiKey.startsWith('authly_sk_')) {
267
+ throw new Error('Invalid Authly Management API key format.');
268
+ }
269
+ this.baseUrl = config.baseUrl.replace(/\/+$/, '');
270
+ this.apiKey = config.managementApiKey;
271
+ this.timeoutMs = config.timeoutMs ?? 10_000;
272
+ }
273
+ async req(path, init = {}) {
274
+ const controller = new AbortController();
275
+ const timer = setTimeout(() => controller.abort(), this.timeoutMs);
276
+ try {
277
+ const res = await fetch(`${this.baseUrl}/v1/management${path}`, {
278
+ ...init,
279
+ signal: controller.signal,
280
+ headers: {
281
+ 'Content-Type': 'application/json',
282
+ Authorization: `Bearer ${this.apiKey}`,
283
+ ...(init.headers ?? {}),
284
+ },
285
+ });
286
+ const json = await res.json().catch(() => ({}));
287
+ if (!res.ok) {
288
+ const err = json.error;
289
+ throw new AuthlyManagementError(res.status, err?.code ?? 'management_error', err?.message ?? 'Management API error');
290
+ }
291
+ return json;
292
+ }
293
+ finally {
294
+ clearTimeout(timer);
295
+ }
296
+ }
297
+ listUsers(params = {}) {
298
+ const q = new URLSearchParams();
299
+ for (const [k, v] of Object.entries(params)) {
300
+ if (v !== undefined)
301
+ q.set(k, String(v));
302
+ }
303
+ const qs = q.toString();
304
+ return this.req(`/users${qs ? `?${qs}` : ''}`);
305
+ }
306
+ getUser(id) {
307
+ return this.req(`/users/${encodeURIComponent(id)}`);
308
+ }
309
+ updateUser(id, patch) {
310
+ return this.req(`/users/${encodeURIComponent(id)}`, { method: 'PATCH', body: JSON.stringify(patch) });
311
+ }
312
+ suspendUser(id) {
313
+ return this.req(`/users/${encodeURIComponent(id)}/suspend`, { method: 'POST', body: '{}' });
314
+ }
315
+ reactivateUser(id) {
316
+ return this.req(`/users/${encodeURIComponent(id)}/reactivate`, { method: 'POST', body: '{}' });
317
+ }
318
+ revokeUserSessions(id) {
319
+ return this.req(`/users/${encodeURIComponent(id)}/revoke-sessions`, { method: 'POST', body: '{}' });
320
+ }
321
+ resendVerification(id) {
322
+ return this.req(`/users/${encodeURIComponent(id)}/resend-verification`, { method: 'POST', body: '{}' });
323
+ }
324
+ triggerPasswordReset(id) {
325
+ return this.req(`/users/${encodeURIComponent(id)}/password-reset`, { method: 'POST', body: '{}' });
326
+ }
327
+ deleteUser(id, hard = false) {
328
+ return this.req(`/users/${encodeURIComponent(id)}${hard ? '?hard=true' : ''}`, { method: 'DELETE' });
329
+ }
330
+ }
331
+ /** Verifies an Authly HMAC-SHA256 webhook signature (`X-Authly-Signature` + `X-Authly-Timestamp`). */
332
+ export function verifyAuthlyWebhookSignature(opts) {
333
+ const tolerance = opts.toleranceSeconds ?? 300;
334
+ const tsNum = Number(opts.timestamp);
335
+ if (!Number.isFinite(tsNum) || Math.abs(Math.floor(Date.now() / 1000) - tsNum) > tolerance) {
336
+ return false;
337
+ }
338
+ const signedContent = `${opts.timestamp}.${typeof opts.payload === 'string' ? opts.payload : opts.payload.toString('utf8')}`;
339
+ const expected = `v1=${createHmac('sha256', opts.secret).update(signedContent).digest('hex')}`;
340
+ const a = Buffer.from(expected);
341
+ const b = Buffer.from(opts.signature);
342
+ return a.length === b.length && timingSafeEqual(a, b);
343
+ }
package/package.json CHANGED
@@ -1,6 +1,35 @@
1
1
  {
2
2
  "name": "@npmatomicauthy/node",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "1.0.0",
4
+ "description": "Official Authly authentication SDK for Node.js",
5
+ "license": "UNLICENSED",
6
+ "type": "module",
7
+ "main": "./dist/index.js",
8
+ "types": "./dist/index.d.ts",
9
+ "exports": {
10
+ ".": {
11
+ "types": "./dist/index.d.ts",
12
+ "import": "./dist/index.js"
13
+ }
14
+ },
15
+ "files": [
16
+ "dist",
17
+ "README.md"
18
+ ],
19
+ "publishConfig": {
20
+ "access": "public"
21
+ },
22
+ "engines": {
23
+ "node": ">=22"
24
+ },
25
+ "scripts": {
26
+ "clean": "node -e \"require('node:fs').rmSync('dist', { recursive: true, force: true })\"",
27
+ "build": "tsc -p tsconfig.build.json",
28
+ "typecheck": "tsc --noEmit",
29
+ "prepublishOnly": "npm run clean && npm run build && npm run typecheck"
30
+ },
31
+ "devDependencies": {
32
+ "@types/node": "^22.20.5",
33
+ "typescript": "^5.9.3"
34
+ }
35
+ }