@seamless-auth/express 0.0.2-beta.6 → 0.0.2-beta.7

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.
Files changed (2) hide show
  1. package/dist/index.d.ts +213 -0
  2. package/package.json +2 -2
@@ -0,0 +1,213 @@
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
+ * cookieDomain: "mycompany.com",
41
+ * accesscookieName: "sa_access",
42
+ * registrationCookieName: "sa_registration",
43
+ * refreshCookieName: "sa_refresh",
44
+ * }));
45
+ * ```
46
+ *
47
+ * @param opts - Configuration options for the Seamless Auth proxy:
48
+ * - `authServerUrl` — Base URL of your Seamless Auth instance (required)
49
+ * - `cookieDomain` — Domain attribute applied to all auth cookies
50
+ * - `accesscookieName` — Name of the session access cookie
51
+ * - `registrationCookieName` — Name of the ephemeral registration cookie
52
+ * - `refreshCookieName` — Name of the refresh token cookie
53
+ * - `preAuthCookieName` — Name of the cookie used during login initiation
54
+ *
55
+ * @returns An Express `Router` preconfigured with all Seamless Auth routes.
56
+ */
57
+ declare function createSeamlessAuthServer(opts: SeamlessAuthServerOptions): Router;
58
+
59
+ /**
60
+ * Express middleware that enforces authentication using Seamless Auth cookies.
61
+ *
62
+ * This guard verifies the signed access cookie generated by the Seamless Auth
63
+ * server. If the access cookie is valid and unexpired, the decoded session
64
+ * payload is attached to `req.user` and the request proceeds.
65
+ *
66
+ * If the access cookie is expired or missing *but* a valid refresh cookie is
67
+ * present, the middleware automatically attempts a silent token refresh using
68
+ * the Seamless Auth server. When successful, new session cookies are issued and
69
+ * the request continues with an updated `req.user`.
70
+ *
71
+ * If neither the access token nor refresh token can validate the session,
72
+ * the middleware returns a 401 Unauthorized error and prevents further
73
+ * route execution.
74
+ *
75
+ * ### Responsibilities
76
+ * - Validates the Seamless Auth session access cookie
77
+ * - Attempts refresh-token–based session renewal when necessary
78
+ * - Populates `req.user` with the verified session payload
79
+ * - Handles all cookie rewriting during refresh flows
80
+ * - Acts as a request-level authentication guard for API routes
81
+ *
82
+ * ### Cookie Parameters
83
+ * - **cookieName** — Name of the access cookie that holds the signed session JWT
84
+ * - **refreshCookieName** — Name of the refresh cookie used for silent token refresh
85
+ * - **cookieDomain** — Domain or path value applied to issued cookies
86
+ *
87
+ * ### Example
88
+ * ```ts
89
+ * // Protect a route
90
+ * app.get("/api/me", requireAuth(), (req, res) => {
91
+ * res.json({ user: req.user });
92
+ * });
93
+ *
94
+ * // Custom cookie names (if your Seamless Auth server uses overrides)
95
+ * app.use(
96
+ * "/internal",
97
+ * requireAuth("sa_access", "sa_refresh", "mycompany.com"),
98
+ * internalRouter
99
+ * );
100
+ * ```
101
+ *
102
+ * @param cookieName - The access cookie name. Defaults to `"seamless-access"`.
103
+ * @param refreshCookieName - The refresh cookie name used for session rotation. Defaults to `"seamless-refresh"`.
104
+ * @param cookieDomain - Domain or path used when rewriting cookies. Defaults to `"/"`.
105
+ *
106
+ * @returns An Express middleware function that enforces Seamless Auth
107
+ * authentication on incoming requests.
108
+ */
109
+ declare function requireAuth(cookieName?: string, refreshCookieName?: string, cookieDomain?: string): (req: Request, res: Response, next: NextFunction) => Promise<void>;
110
+
111
+ /**
112
+ * Express middleware that enforces role-based authorization for Seamless Auth sessions.
113
+ *
114
+ * This guard assumes that `requireAuth()` has already validated the request
115
+ * and populated `req.user` with the decoded Seamless Auth session payload.
116
+ * It then checks whether the user’s roles include the required role (or any
117
+ * of several, when an array is provided).
118
+ *
119
+ * If the user possesses the required authorization, the request proceeds.
120
+ * Otherwise, the middleware responds with a 403 Forbidden error.
121
+ *
122
+ * ### Responsibilities
123
+ * - Validates that `req.user` is present (enforced upstream by `requireAuth`)
124
+ * - Ensures the authenticated user includes the specified role(s)
125
+ * - Blocks unauthorized access with a standardized JSON 403 response
126
+ *
127
+ * ### Parameters
128
+ * - **requiredRole** — A role (string) or list of roles the user must have.
129
+ * If an array is provided, *any* matching role grants access.
130
+ * - **cookieName** — Optional name of the access cookie to inspect.
131
+ * Defaults to `"seamless-access"`, but typically not needed because
132
+ * `requireAuth` is expected to run first.
133
+ *
134
+ * ### Example
135
+ * ```ts
136
+ * // Require a single role
137
+ * app.get("/admin/users",
138
+ * requireAuth(),
139
+ * requireRole("admin"),
140
+ * (req, res) => {
141
+ * res.send("Welcome admin!");
142
+ * }
143
+ * );
144
+ *
145
+ * // Allow any of multiple roles
146
+ * app.post("/settings",
147
+ * requireAuth(),
148
+ * requireRole(["admin", "supervisor"]),
149
+ * updateSettingsHandler
150
+ * );
151
+ * ```
152
+ *
153
+ * @param requiredRole - A role or list of roles required to access the route.
154
+ * @param cookieName - Optional access cookie name (defaults to `seamless-access`).
155
+ * @returns An Express middleware function enforcing role-based access control.
156
+ */
157
+ declare function requireRole(role: string, cookieName?: string): RequestHandler;
158
+
159
+ interface CookieRequest extends Request {
160
+ cookiePayload?: JwtPayload;
161
+ }
162
+
163
+ /**
164
+ * Retrieves the authenticated Seamless Auth user for a request by calling
165
+ * the upstream Seamless Auth Server’s introspection endpoint.
166
+ *
167
+ * This helper is used when server-side code needs the fully hydrated
168
+ * Seamless Auth user object (including roles, metadata, and profile fields),
169
+ * not just the JWT payload extracted from cookies.
170
+ *
171
+ * Unlike `requireAuth`, this helper does **not** enforce authentication.
172
+ * It simply returns:
173
+ * - The resolved user object (if the session is valid)
174
+ * - `null` if the session is invalid, expired, or missing
175
+ *
176
+ * ### Responsibilities
177
+ * - Extracts the access cookie (or refresh cookie when needed)
178
+ * - Calls the Seamless Auth Server’s `/internal/session/introspect` endpoint
179
+ * - Validates whether the session is active
180
+ * - Returns the user object or `null` without throwing
181
+ *
182
+ * ### Use Cases
183
+ * - Fetching the current user in internal APIs
184
+ * - Enriching backend requests with server-authoritative user information
185
+ * - Logging, analytics, auditing
186
+ * - Optional-auth routes that behave differently for signed-in users
187
+ *
188
+ * ### Example
189
+ * ```ts
190
+ * app.get("/portal/me", async (req, res) => {
191
+ * const user = await getSeamlessUser(req, process.env.SA_AUTH_SERVER_URL);
192
+ *
193
+ * if (!user) {
194
+ * return res.json({ user: null });
195
+ * }
196
+ *
197
+ * return res.json({ user });
198
+ * });
199
+ * ```
200
+ *
201
+ * ### Returns
202
+ * - A full Seamless Auth user object (if active)
203
+ * - `null` if not authenticated or session expired
204
+ *
205
+ * @param req - The Express request object containing auth cookies.
206
+ * @param authServerUrl - Base URL of the Seamless Auth instance to introspect against.
207
+ * @param cookieName - Name of the access cookie storing the session JWT (`"seamless-access"` by default).
208
+ *
209
+ * @returns The authenticated user object, or `null` if the session is inactive.
210
+ */
211
+ declare function getSeamlessUser<T = any>(req: CookieRequest, authServerUrl: string, cookieName?: string): Promise<T | null>;
212
+
213
+ export { type SeamlessAuthServerOptions, createSeamlessAuthServer as default, getSeamlessUser, requireAuth, requireRole };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@seamless-auth/express",
3
- "version": "0.0.2-beta.6",
3
+ "version": "0.0.2-beta.7",
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": {