@seamless-auth/express 0.0.2-beta.2 → 0.0.2-beta.5
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/dist/index.d.ts +211 -0
- package/dist/index.js +5 -2
- package/package.json +1 -1
package/dist/index.d.ts
ADDED
|
@@ -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
|
@@ -10,6 +10,7 @@ function setSessionCookie(res, payload, domain, ttlSeconds = 300, name = "sa_ses
|
|
|
10
10
|
console.warn("[SeamlessAuth] Missing SEAMLESS_COOKIE_SIGNING_KEY env var!");
|
|
11
11
|
throw new Error("Missing required env SEAMLESS_COOKIE_SIGNING_KEY");
|
|
12
12
|
}
|
|
13
|
+
console.debug("[SeamlessAuth] Domain check... ", domain);
|
|
13
14
|
const token = jwt.sign(payload, COOKIE_SECRET2, {
|
|
14
15
|
algorithm: "HS256",
|
|
15
16
|
expiresIn: `${ttlSeconds}s`
|
|
@@ -27,6 +28,7 @@ function clearSessionCookie(res, domain, name = "sa_session") {
|
|
|
27
28
|
res.clearCookie(name, { domain, path: "/" });
|
|
28
29
|
}
|
|
29
30
|
function clearAllCookies(res, domain, accesscookieName, registrationCookieName, refreshCookieName) {
|
|
31
|
+
console.debug("[SeamlessAuth] clearing cookies");
|
|
30
32
|
res.clearCookie(accesscookieName, { domain, path: "/" });
|
|
31
33
|
res.clearCookie(registrationCookieName, { domain, path: "/" });
|
|
32
34
|
res.clearCookie(refreshCookieName, { domain, path: "/" });
|
|
@@ -172,7 +174,8 @@ function createEnsureCookiesMiddleware(opts) {
|
|
|
172
174
|
"/logout": { name: opts.accesscookieName, required: true },
|
|
173
175
|
"/users/me": { name: opts.accesscookieName, required: true }
|
|
174
176
|
};
|
|
175
|
-
return async function ensureCookies(req, res, next, cookieDomain = "") {
|
|
177
|
+
return async function ensureCookies(req, res, next, cookieDomain = opts.cookieDomain || "") {
|
|
178
|
+
console.debug("[SeamlessAuth] Ensuring cookies domain...", cookieDomain);
|
|
176
179
|
const match = Object.entries(COOKIE_REQUIREMENTS).find(
|
|
177
180
|
([path]) => req.path.startsWith(path)
|
|
178
181
|
);
|
|
@@ -369,7 +372,7 @@ function createSeamlessAuthServer(opts) {
|
|
|
369
372
|
setSessionCookie(
|
|
370
373
|
res,
|
|
371
374
|
{ sub: data.sub, refreshToken: data.refreshToken },
|
|
372
|
-
|
|
375
|
+
cookieDomain,
|
|
373
376
|
data.refreshTtl,
|
|
374
377
|
refreshCookieName
|
|
375
378
|
);
|