@seamless-auth/express 0.0.2-beta.2 → 0.0.2-beta.4

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,211 @@
1
+ import { Router, Request, Response, NextFunction, RequestHandler } from 'express';
2
+ import { JwtPayload } from 'jsonwebtoken';
3
+
4
+ interface SeamlessAuthServerOptions {
5
+ authServerUrl: string;
6
+ cookieDomain?: string;
7
+ accesscookieName?: string;
8
+ registrationCookieName?: string;
9
+ refreshCookieName?: string;
10
+ preAuthCookieName?: string;
11
+ }
12
+
13
+ /**
14
+ * Creates an Express Router that proxies all authentication traffic to a Seamless Auth server.
15
+ *
16
+ * This helper wires your API backend to a Seamless Auth instance running in
17
+ * "server mode." It automatically forwards login, registration, WebAuthn,
18
+ * logout, token refresh, and session validation routes to the auth server
19
+ * and handles all cookie management required for a seamless login flow.
20
+ *
21
+ * ### Responsibilities
22
+ * - Proxies all `/auth/*` routes to the upstream Seamless Auth server
23
+ * - Manages `access`, `registration`, `pre-auth`, and `refresh` cookies
24
+ * - Normalizes cookie settings for cross-domain or same-domain deployments
25
+ * - Ensures authentication routes behave consistently across environments
26
+ * - Provides shared middleware for auth flows
27
+ *
28
+ * ### Cookie Types
29
+ * - **accessCookie** – long-lived session cookie for authenticated API requests
30
+ * - **registrationCookie** – ephemeral cookie used during registration and OTP/WebAuthn flows
31
+ * - **preAuthCookie** – short-lived cookie used during login initiation
32
+ * - **refreshCookie** – opaque refresh token cookie used to rotate session tokens
33
+ *
34
+ * All cookie names and their domains may be customized via the `opts` parameter.
35
+ *
36
+ * ### Example
37
+ * ```ts
38
+ * app.use("/auth", createSeamlessAuthServer({
39
+ * authServerUrl: "https://identifier.seamlessauth.com",
40
+ * accesscookieName: "sa_access",
41
+ * registrationCookieName: "sa_registration",
42
+ * refreshCookieName: "sa_refresh",
43
+ * }));
44
+ * ```
45
+ *
46
+ * @param opts - Configuration options for the Seamless Auth proxy:
47
+ * - `authServerUrl` — Base URL of your Seamless Auth instance (required)
48
+ * - `accesscookieName` — Name of the session access cookie
49
+ * - `registrationCookieName` — Name of the ephemeral registration cookie
50
+ * - `refreshCookieName` — Name of the refresh token cookie
51
+ * - `preAuthCookieName` — Name of the cookie used during login initiation
52
+ *
53
+ * @returns An Express `Router` preconfigured with all Seamless Auth routes.
54
+ */
55
+ declare function createSeamlessAuthServer(opts: SeamlessAuthServerOptions): Router;
56
+
57
+ /**
58
+ * Express middleware that enforces authentication using Seamless Auth cookies.
59
+ *
60
+ * This guard verifies the signed access cookie generated by the Seamless Auth
61
+ * server. If the access cookie is valid and unexpired, the decoded session
62
+ * payload is attached to `req.user` and the request proceeds.
63
+ *
64
+ * If the access cookie is expired or missing *but* a valid refresh cookie is
65
+ * present, the middleware automatically attempts a silent token refresh using
66
+ * the Seamless Auth server. When successful, new session cookies are issued and
67
+ * the request continues with an updated `req.user`.
68
+ *
69
+ * If neither the access token nor refresh token can validate the session,
70
+ * the middleware returns a 401 Unauthorized error and prevents further
71
+ * route execution.
72
+ *
73
+ * ### Responsibilities
74
+ * - Validates the Seamless Auth session access cookie
75
+ * - Attempts refresh-token–based session renewal when necessary
76
+ * - Populates `req.user` with the verified session payload
77
+ * - Handles all cookie rewriting during refresh flows
78
+ * - Acts as a request-level authentication guard for API routes
79
+ *
80
+ * ### Cookie Parameters
81
+ * - **cookieName** — Name of the access cookie that holds the signed session JWT
82
+ * - **refreshCookieName** — Name of the refresh cookie used for silent token refresh
83
+ * - **cookieDomain** — Domain or path value applied to issued cookies
84
+ *
85
+ * ### Example
86
+ * ```ts
87
+ * // Protect a route
88
+ * app.get("/api/me", requireAuth(), (req, res) => {
89
+ * res.json({ user: req.user });
90
+ * });
91
+ *
92
+ * // Custom cookie names (if your Seamless Auth server uses overrides)
93
+ * app.use(
94
+ * "/internal",
95
+ * requireAuth("sa_access", "sa_refresh", "mycompany.com"),
96
+ * internalRouter
97
+ * );
98
+ * ```
99
+ *
100
+ * @param cookieName - The access cookie name. Defaults to `"seamless-access"`.
101
+ * @param refreshCookieName - The refresh cookie name used for session rotation. Defaults to `"seamless-refresh"`.
102
+ * @param cookieDomain - Domain or path used when rewriting cookies. Defaults to `"/"`.
103
+ *
104
+ * @returns An Express middleware function that enforces Seamless Auth
105
+ * authentication on incoming requests.
106
+ */
107
+ declare function requireAuth(cookieName?: string, refreshCookieName?: string, cookieDomain?: string): (req: Request, res: Response, next: NextFunction) => Promise<void>;
108
+
109
+ /**
110
+ * Express middleware that enforces role-based authorization for Seamless Auth sessions.
111
+ *
112
+ * This guard assumes that `requireAuth()` has already validated the request
113
+ * and populated `req.user` with the decoded Seamless Auth session payload.
114
+ * It then checks whether the user’s roles include the required role (or any
115
+ * of several, when an array is provided).
116
+ *
117
+ * If the user possesses the required authorization, the request proceeds.
118
+ * Otherwise, the middleware responds with a 403 Forbidden error.
119
+ *
120
+ * ### Responsibilities
121
+ * - Validates that `req.user` is present (enforced upstream by `requireAuth`)
122
+ * - Ensures the authenticated user includes the specified role(s)
123
+ * - Blocks unauthorized access with a standardized JSON 403 response
124
+ *
125
+ * ### Parameters
126
+ * - **requiredRole** — A role (string) or list of roles the user must have.
127
+ * If an array is provided, *any* matching role grants access.
128
+ * - **cookieName** — Optional name of the access cookie to inspect.
129
+ * Defaults to `"seamless-access"`, but typically not needed because
130
+ * `requireAuth` is expected to run first.
131
+ *
132
+ * ### Example
133
+ * ```ts
134
+ * // Require a single role
135
+ * app.get("/admin/users",
136
+ * requireAuth(),
137
+ * requireRole("admin"),
138
+ * (req, res) => {
139
+ * res.send("Welcome admin!");
140
+ * }
141
+ * );
142
+ *
143
+ * // Allow any of multiple roles
144
+ * app.post("/settings",
145
+ * requireAuth(),
146
+ * requireRole(["admin", "supervisor"]),
147
+ * updateSettingsHandler
148
+ * );
149
+ * ```
150
+ *
151
+ * @param requiredRole - A role or list of roles required to access the route.
152
+ * @param cookieName - Optional access cookie name (defaults to `seamless-access`).
153
+ * @returns An Express middleware function enforcing role-based access control.
154
+ */
155
+ declare function requireRole(role: string, cookieName?: string): RequestHandler;
156
+
157
+ interface CookieRequest extends Request {
158
+ cookiePayload?: JwtPayload;
159
+ }
160
+
161
+ /**
162
+ * Retrieves the authenticated Seamless Auth user for a request by calling
163
+ * the upstream Seamless Auth Server’s introspection endpoint.
164
+ *
165
+ * This helper is used when server-side code needs the fully hydrated
166
+ * Seamless Auth user object (including roles, metadata, and profile fields),
167
+ * not just the JWT payload extracted from cookies.
168
+ *
169
+ * Unlike `requireAuth`, this helper does **not** enforce authentication.
170
+ * It simply returns:
171
+ * - The resolved user object (if the session is valid)
172
+ * - `null` if the session is invalid, expired, or missing
173
+ *
174
+ * ### Responsibilities
175
+ * - Extracts the access cookie (or refresh cookie when needed)
176
+ * - Calls the Seamless Auth Server’s `/internal/session/introspect` endpoint
177
+ * - Validates whether the session is active
178
+ * - Returns the user object or `null` without throwing
179
+ *
180
+ * ### Use Cases
181
+ * - Fetching the current user in internal APIs
182
+ * - Enriching backend requests with server-authoritative user information
183
+ * - Logging, analytics, auditing
184
+ * - Optional-auth routes that behave differently for signed-in users
185
+ *
186
+ * ### Example
187
+ * ```ts
188
+ * app.get("/portal/me", async (req, res) => {
189
+ * const user = await getSeamlessUser(req, process.env.SA_AUTH_SERVER_URL);
190
+ *
191
+ * if (!user) {
192
+ * return res.json({ user: null });
193
+ * }
194
+ *
195
+ * return res.json({ user });
196
+ * });
197
+ * ```
198
+ *
199
+ * ### Returns
200
+ * - A full Seamless Auth user object (if active)
201
+ * - `null` if not authenticated or session expired
202
+ *
203
+ * @param req - The Express request object containing auth cookies.
204
+ * @param authServerUrl - Base URL of the Seamless Auth instance to introspect against.
205
+ * @param cookieName - Name of the access cookie storing the session JWT (`"seamless-access"` by default).
206
+ *
207
+ * @returns The authenticated user object, or `null` if the session is inactive.
208
+ */
209
+ declare function getSeamlessUser<T = any>(req: CookieRequest, authServerUrl: string, cookieName?: string): Promise<T | null>;
210
+
211
+ export { type SeamlessAuthServerOptions, createSeamlessAuthServer as default, getSeamlessUser, requireAuth, requireRole };
package/dist/index.js CHANGED
@@ -4,7 +4,7 @@ import cookieParser from "cookie-parser";
4
4
 
5
5
  // src/internal/cookie.ts
6
6
  import jwt from "jsonwebtoken";
7
- function setSessionCookie(res, payload, domain, ttlSeconds = 300, name = "sa_session") {
7
+ function setSessionCookie(res, payload, ttlSeconds = 300, name = "sa_session") {
8
8
  const COOKIE_SECRET2 = process.env.SEAMLESS_COOKIE_SIGNING_KEY;
9
9
  if (!COOKIE_SECRET2) {
10
10
  console.warn("[SeamlessAuth] Missing SEAMLESS_COOKIE_SIGNING_KEY env var!");
@@ -19,17 +19,16 @@ function setSessionCookie(res, payload, domain, ttlSeconds = 300, name = "sa_ses
19
19
  secure: process.env.NODE_ENV === "production",
20
20
  sameSite: process.env.NODE_ENV === "production" ? "none" : "lax",
21
21
  path: "/",
22
- domain,
23
22
  maxAge: ttlSeconds * 1e3
24
23
  });
25
24
  }
26
25
  function clearSessionCookie(res, domain, name = "sa_session") {
27
26
  res.clearCookie(name, { domain, path: "/" });
28
27
  }
29
- function clearAllCookies(res, domain, accesscookieName, registrationCookieName, refreshCookieName) {
30
- res.clearCookie(accesscookieName, { domain, path: "/" });
31
- res.clearCookie(registrationCookieName, { domain, path: "/" });
32
- res.clearCookie(refreshCookieName, { domain, path: "/" });
28
+ function clearAllCookies(res, accesscookieName, registrationCookieName, refreshCookieName) {
29
+ res.clearCookie(accesscookieName, { path: "/" });
30
+ res.clearCookie(registrationCookieName, { path: "/" });
31
+ res.clearCookie(refreshCookieName, { path: "/" });
33
32
  }
34
33
 
35
34
  // src/internal/authFetch.ts
@@ -192,7 +191,6 @@ function createEnsureCookiesMiddleware(opts) {
192
191
  if (!refreshed?.token) {
193
192
  clearAllCookies(
194
193
  res,
195
- cookieDomain,
196
194
  name,
197
195
  opts.registrationCookieName,
198
196
  opts.refreshCookieName
@@ -207,14 +205,12 @@ function createEnsureCookiesMiddleware(opts) {
207
205
  token: refreshed.token,
208
206
  roles: refreshed.roles
209
207
  },
210
- cookieDomain,
211
208
  refreshed.ttl,
212
209
  name
213
210
  );
214
211
  setSessionCookie(
215
212
  res,
216
213
  { sub: refreshed.sub, refreshToken: refreshed.refreshToken },
217
- cookieDomain,
218
214
  refreshed.refreshTtl,
219
215
  opts.refreshCookieName
220
216
  );
@@ -264,7 +260,6 @@ function createSeamlessAuthServer(opts) {
264
260
  r.use(cookieParser());
265
261
  const {
266
262
  authServerUrl,
267
- cookieDomain = "",
268
263
  accesscookieName = "seamless-access",
269
264
  registrationCookieName = "seamless-ephemeral",
270
265
  refreshCookieName = "seamless-refresh",
@@ -284,7 +279,6 @@ function createSeamlessAuthServer(opts) {
284
279
  r.use(
285
280
  createEnsureCookiesMiddleware({
286
281
  authServerUrl,
287
- cookieDomain,
288
282
  accesscookieName,
289
283
  registrationCookieName,
290
284
  refreshCookieName,
@@ -317,13 +311,7 @@ function createSeamlessAuthServer(opts) {
317
311
  if (verified.sub !== data.sub) {
318
312
  throw new Error("Signature mismatch with data payload");
319
313
  }
320
- setSessionCookie(
321
- res,
322
- { sub: data.sub },
323
- cookieDomain,
324
- data.ttl,
325
- preAuthCookieName
326
- );
314
+ setSessionCookie(res, { sub: data.sub }, data.ttl, preAuthCookieName);
327
315
  res.status(204).end();
328
316
  }
329
317
  async function register(req, res) {
@@ -333,13 +321,7 @@ function createSeamlessAuthServer(opts) {
333
321
  });
334
322
  const data = await up.json();
335
323
  if (!up.ok) return res.status(up.status).json(data);
336
- setSessionCookie(
337
- res,
338
- { sub: data.sub },
339
- cookieDomain,
340
- data.ttl,
341
- registrationCookieName
342
- );
324
+ setSessionCookie(res, { sub: data.sub }, data.ttl, registrationCookieName);
343
325
  res.status(200).json(data).end();
344
326
  }
345
327
  async function finishLogin(req, res) {
@@ -362,14 +344,12 @@ function createSeamlessAuthServer(opts) {
362
344
  setSessionCookie(
363
345
  res,
364
346
  { sub: data.sub, roles: data.roles },
365
- cookieDomain,
366
347
  data.ttl,
367
348
  accesscookieName
368
349
  );
369
350
  setSessionCookie(
370
351
  res,
371
352
  { sub: data.sub, refreshToken: data.refreshToken },
372
- req.hostname,
373
353
  data.refreshTtl,
374
354
  refreshCookieName
375
355
  );
@@ -389,7 +369,6 @@ function createSeamlessAuthServer(opts) {
389
369
  setSessionCookie(
390
370
  res,
391
371
  { sub: data.sub, roles: data.roles },
392
- cookieDomain,
393
372
  data.ttl,
394
373
  accesscookieName
395
374
  );
@@ -401,7 +380,6 @@ function createSeamlessAuthServer(opts) {
401
380
  });
402
381
  clearAllCookies(
403
382
  res,
404
- cookieDomain,
405
383
  accesscookieName,
406
384
  registrationCookieName,
407
385
  refreshCookieName
@@ -413,7 +391,7 @@ function createSeamlessAuthServer(opts) {
413
391
  method: "GET"
414
392
  });
415
393
  const data = await up.json();
416
- clearSessionCookie(res, cookieDomain, preAuthCookieName);
394
+ clearSessionCookie(res, preAuthCookieName);
417
395
  if (!data.user) return res.status(401).json({ error: "unauthenticated" });
418
396
  res.json({ user: data.user });
419
397
  }
@@ -474,14 +452,12 @@ function requireAuth(cookieName = "seamless-access", refreshCookieName = "seamle
474
452
  token: refreshed.token,
475
453
  roles: refreshed.roles
476
454
  },
477
- cookieDomain,
478
455
  refreshed.ttl,
479
456
  cookieName
480
457
  );
481
458
  setSessionCookie(
482
459
  res,
483
460
  { sub: refreshed.sub, refreshToken: refreshed.refreshToken },
484
- req.hostname,
485
461
  refreshed.refreshTtl,
486
462
  refreshCookieName
487
463
  );
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@seamless-auth/express",
3
- "version": "0.0.2-beta.2",
3
+ "version": "0.0.2-beta.4",
4
4
  "description": "Express adapter for Seamless Auth passwordless authentication",
5
5
  "license": "MIT",
6
6
  "type": "module",
@@ -8,7 +8,7 @@
8
8
  "types": "./dist/index.d.ts",
9
9
  "author": "Fells Code LLC",
10
10
  "scripts": {
11
- "build": "tsup src/index.ts --format esm --out-dir dist --splitting",
11
+ "build": "tsup src/index.ts --format esm --out-dir dist --dts --splitting",
12
12
  "dev": "tsc --watch"
13
13
  },
14
14
  "repository": {